Associated Token Account (ATA)

Associated Token Account Program defines the convention and provides the mechanism for mapping the user’s wallet address to the associated token accounts they hold.

For example, for a wallet to hold some random SPL token, an associated token account needs to be initialized. That account will be holding the tokens, while the wallet will be the one owning that token account.

Take a look at what SolanaService.transfer_spl_to_address does under the hood:

func transfer_spl_to_address(token_address:String,receiver:String,amount:float) -> String:
	var instructions:Array[Instruction]
	
	var sender_account:Pubkey = wallet.get_pubkey()
	var receiver_account:Pubkey = Pubkey.new_from_string(receiver) 
	var token_mint:Pubkey = Pubkey.new_from_string(token_address) 
	var token_program_id:Pubkey = Pubkey.new_from_string("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL")
	
	var sender_ata:Pubkey = get_associated_token_account(sender_account.get_value(),token_address)
	
	#check if an ATA for this token exists in wallet. if not, add initalize as instruction
	var receiver_ata:Pubkey = get_associated_token_account(receiver_account.get_value(),token_address)
	if receiver_ata == null:
		receiver_ata = Pubkey.new_associated_token_address(receiver_account,token_mint)
		var init_ata_ix:Instruction = AssociatedTokenAccountProgram.create_associated_token_account(
			sender_account,
			receiver_account,
			token_mint,
			token_program_id
			)
		instructions.append(init_ata_ix)
		
	#get the decimals of the token to multiply by the amount provided
	var token_decimals = get_token_decimals(token_address)
	var transfer_ix:Instruction = TokenProgram.transfer_checked(sender_ata,token_mint,receiver_ata,sender_account,amount,token_decimals)
	instructions.append(transfer_ix)
	
	var tx_id:String = await transaction_processor.sign_transaction(sender_keypair,instructions)
	return tx_id

To summarize the code, this script first checks if there is an ATA for this token already created in receiver's wallet. If yes, then it is the account to send the tokens to. If not, then an additioanl instruction is added to the transaction, which initializes the associated token account and only then it receives the tokens.

For more information about ATAs, check here

Last updated