1

In my account struct:

#[derive(Accounts)]
pub struct WithdrawToken<'info> {
  #[account(mut, token::mint = mint, token::authority = signer, 
     token::token_program = token_program)]
  pub to_ata: InterfaceAccount<'info, TokenAccount>,
  pub signer: Signer<'info>,
  pub token_program: Interface<'info, TokenInterface>,
}

How can I validate the token_program via #[account(constraint = settings.token_program == token_program)]?

Do I need to validate token_program against attacks?

From Anchor library, token_program can be either TOKEN_PROGRAM_ID, or TOKEN_2022_PROGRAM_ID public key. but attackers may try to use a fake token_program...

How can I save token_program into my Settings account?

#[account]
#[derive(InitSpace)]
pub struct Settings {
  pub token_program: Interface<'_, TokenInterface>,
}

the above gives me error: the trait bound anchor_lang::prelude::Interface<'_, TokenInterface>: anchor_lang::Space is not satisfied

2 Answers 2

3

By defining Interface<'info, TokenInterface>, your program will automatically check that the provided token program is either SPL Token or SPL Token 2022: https://github.com/coral-xyz/anchor/blob/a0ddeb375e5835c0db00313d3eced21512de8f5d/spl/src/token_interface.rs#L14

If you still want to save the token program somewhere though, you'll just want to store a Pubkey in your account struct:

#[account]
#[derive(InitSpace)]
pub struct Settings {
  pub token_program: Pubkey,
}
2
  • then use constraint = settings.token_program == token_program ?
    – Russo
    Commented Sep 10 at 20:45
  • That's right, you'll need to specify it by hand somewhere
    – Jon C
    Commented Sep 11 at 10:10
1

if your token_program can be 2 different programs, i'mnot sure you can check it with constaints. But you can check it the function :

if ctx.accounts.token_program.to_account_info().key().to_string() != "Token..." && ctx.accounts.token_program.to_account_info().key().to_string() != "..." {
    return err!(ErrorCode::PublicKeyMismatch);
}
1
  • Effe2, could you clarify why "Token..." and "..." ?
    – Russo
    Commented Sep 6 at 8:40

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.