createAssociatedTokenAccount method

Future<ProgramAccount> createAssociatedTokenAccount({
  1. Ed25519HDPublicKey? owner,
  2. required Ed25519HDPublicKey mint,
  3. required Wallet funder,
  4. SignatureCallback? onSigned,
  5. Commitment commitment = Commitment.finalized,
})

Create the account associated to the SPL token mint for this wallet.

If you want to use another wallet as a funder use the funder parameter.

Also adds the token to the wallet object.

For commitment parameter description see this document Commitment.processed is not supported as commitment.

Implementation

Future<ProgramAccount> createAssociatedTokenAccount({
  Ed25519HDPublicKey? owner,
  required Ed25519HDPublicKey mint,
  required Wallet funder,
  SignatureCallback? onSigned,
  Commitment commitment = Commitment.finalized,
}) async {
  final effectiveOwner = owner ?? funder.publicKey;

  final derivedAddress = await findAssociatedTokenAddress(
    owner: effectiveOwner,
    mint: mint,
  );
  final instruction = AssociatedTokenAccountInstruction.createAccount(
    mint: mint,
    address: derivedAddress,
    owner: effectiveOwner,
    funder: funder.publicKey,
  );

  await sendAndConfirmTransaction(
    message: Message.only(instruction),
    signers: [funder],
    onSigned: onSigned ?? ignoreOnSigned,
    commitment: commitment,
  );

  // TODO(IA): populate rentEpoch correctly
  return ProgramAccount(
    pubkey: derivedAddress.toBase58(),
    account: Account(
      owner: effectiveOwner.toBase58(),
      lamports: 0,
      executable: false,
      rentEpoch: BigInt.zero,
      data: null,
    ),
  );
}