fix creating associated token account
OmarHatem committed
Dec 31, 2024 at 07:33 UTC
c880dbd83c54cd1e338ecec4c3caebe183915fd7
2 files changed
+41
-9
cw_solana/lib/solana_client.dart
+41
-8
@@ -481,6 +481,9 @@ class SolanaWalletClient {
481
final destinationOwner = Ed25519HDPublicKey.fromBase58(destinationAddress);
482
final mint = Ed25519HDPublicKey.fromBase58(tokenMint);
483
484
+ // Input by the user
485
+ final amount = (inputAmount * math.pow(10, tokenDecimals)).toInt();
486
+
487
ProgramAccount? associatedRecipientAccount;
488
ProgramAccount? associatedSenderAccount;
489
@@ -503,18 +506,46 @@ class SolanaWalletClient {
506
}
507
508
try {
506
- associatedRecipientAccount ??= await _client!.createAssociatedTokenAccount(
507
- mint: mint,
508
- owner: destinationOwner,
509
- funder: ownerKeypair,
510
- );
509
+ if (associatedRecipientAccount == null) {
510
+ final derivedAddress = await findAssociatedTokenAddress(
511
+ owner: destinationOwner,
512
+ mint: mint,
513
+ );
514
+
515
+ final instruction = AssociatedTokenAccountInstruction.createAccount(
516
+ mint: mint,
517
+ address: derivedAddress,
518
+ owner: ownerKeypair.publicKey,
519
+ funder: ownerKeypair.publicKey,
520
+ );
521
+
522
+ final _signedTx = await _signTransactionInternal(
523
+ message: Message.only(instruction),
524
+ signers: [ownerKeypair],
525
+ commitment: commitment,
526
+ latestBlockhash: await _getLatestBlockhash(commitment),
527
+ );
528
+
529
+ await sendTransaction(
530
+ signedTransaction: _signedTx,
531
+ commitment: commitment,
532
+ );
533
+
534
+ associatedRecipientAccount = ProgramAccount(
535
+ pubkey: derivedAddress.toBase58(),
536
+ account: Account(
537
+ owner: destinationOwner.toBase58(),
538
+ lamports: 0,
539
+ executable: false,
540
+ rentEpoch: BigInt.zero,
541
+ data: null,
542
+ ),
543
+ );
544
+ }
545
} catch (e) {
546
throw SolanaCreateAssociatedTokenAccountException(e.toString());
547
}
548
515
- // Input by the user
516
- final amount = (inputAmount * math.pow(10, tokenDecimals)).toInt();
517
-
549
final instruction = TokenInstruction.transfer(
550
source: Ed25519HDPublicKey.fromBase58(associatedSenderAccount.pubkey),
551
destination: Ed25519HDPublicKey.fromBase58(associatedRecipientAccount.pubkey),
@@ -587,6 +618,8 @@ class SolanaWalletClient {
618
signedTransaction.encode(),
619
preflightCommitment: commitment,
620
);
621
+ print("#########");
622
+ print(signature);
623
624
_client!.waitForSignatureStatus(signature, status: commitment);
625
cw_solana/lib/solana_wallet.dart
-1
@@ -33,7 +33,6 @@ import 'package:shared_preferences/shared_preferences.dart';
33
import 'package:solana/base58.dart';
34
import 'package:solana/metaplex.dart' as metaplex;
35
import 'package:solana/solana.dart';
36
-import 'package:solana/src/crypto/ed25519_hd_keypair.dart';
36
37
part 'solana_wallet.g.dart';
38