getOrCreateAssociatedTokenAccount method
Future<Ed25519HDPublicKey>
getOrCreateAssociatedTokenAccount(
- Ed25519HDKeyPair ownerKeys,
- Ed25519HDPublicKey senderPubKey,
- Ed25519HDPublicKey accountPubKey,
- SolanaClient solanaClient,
Get or create associated token account
Functionality
Fetches or creates an associated token account for a given mint and owner.
Params
Ed25519HDKeyPair
ownerKeys - The keypair of the account that will own the newly created token account.
Ed25519HDPublicKey
senderPubKey - The public key of the token for which an account will be created.
Ed25519HDPublicKey
accountPubKey - The public key of the account that will own the newly created token account.
SolanaClient
solanaClient - RPC Client
Ed25519HDPublicKey
- The public key of the associated token account
Return
Ed25519HDPublicKey
as new associated account public address
Implementation
Future<solana.Ed25519HDPublicKey> getOrCreateAssociatedTokenAccount(
solana.Ed25519HDKeyPair ownerKeys,
solana.Ed25519HDPublicKey senderPubKey,
solana.Ed25519HDPublicKey accountPubKey,
solana.SolanaClient solanaClient) async {
final solana.Ed25519HDPublicKey mintPubKey =
solana.Ed25519HDPublicKey.fromBase58(Constants.MINT_TOKEN);
final response = await solanaClient.rpcClient.getTokenAccountsByOwner(
accountPubKey.toBase58(),
TokenAccountsFilter.byMint(mintPubKey.toBase58()),
);
if (response.value.isNotEmpty) {
final String associatedAccountAddress = response.value[0].pubkey;
return solana.Ed25519HDPublicKey.fromBase58(associatedAccountAddress);
}
final TransactionInstruction instruction =
await createAssociatedTokenAccountInstruction(
/// [Sender] is the fee payer
senderPubKey,
accountPubKey,
mintPubKey,
);
await solanaClient.rpcClient.signAndSendTransaction(
solana.Message.only(
encoder.Instruction(
accounts: instruction.keys,
data: encoder.ByteArray(instruction.data),
programId: instruction.programId,
),
),
[ownerKeys],
);
final solana.Ed25519HDPublicKey newAssociatedAccountAddress =
await findAssociatedTokenAddress(
accountPubKey,
mintPubKey,
);
return newAssociatedAccountAddress;
}