1

I'm using get_associated_token_address to get a token account but how to find out if it is valid or not? Any help please?

let payer_associated_token_account = get_associated_token_address(
    payer_account.unwrap().key,
    token_mint.unwrap().key
);

// how to get the data of above ATA?

1 Answer 1

3

In order to access the data of an account, it has to be expected as an account input to the instruction and provided as AccountInfo.

Once you have the token account info, it can be deserialized into its appropriate data structure with:

let mut data: &[u8] = &info.try_borrow_data()?;
let acc = TokenAccount::try_deserialize(&mut data)?;

If you are using anchor, this can all be done for you if you include the account in the instruction's account context struct:

#[derive(Accounts)]
pub struct MyInstruction<'info> {
    // ...
    pub token_acc: Account<'info, TokenAccount>,
    // ...
}

then accessing the token account data within the instruction simply becomes:

let amount = ctx.accounts.token_acc.amount;

(or whatever data you need to access)

5
  • Is it not possible to get the token account data if I don't pass the token account to instructions? What I want to do is, within the onchain program, I want to do get_or_create_associated_token_account. Or at least get the data from within the program, want to be able to only pass the token owner, token mint and token receiver wallet to the on-chain program and then token account creation will happen within the on-chain program. Is that not possible? Commented Mar 12, 2023 at 12:42
  • no. this is a runtime limitation of solana where instructions are only provided with the data of accounts that are given as inputs. its helps make on chain contracts deterministic and efficient.
    – m_callens
    Commented Mar 13, 2023 at 0:20
  • Gotcha. Thank you! Commented Mar 13, 2023 at 7:13
  • One more question @m_callens, how can I access the data of ATA within on-chain program after I passed it to program? Commented Mar 13, 2023 at 9:57
  • an associated token account is just a token account. you can use the same code above.
    – m_callens
    Commented Mar 13, 2023 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.