5

I'm trying to write a program that mint token to an address being passed as an argument, my code looks like this

 pub fn mint_tok(ctx:Context<Donate>,amount_token:u64,address:pubkey) -> Result<()> {
let cpi_ctx = CpiContext::new(
            self.token_program.to_account_info(),
             MintTo {  
                    mint:ctx.accounts.chrt_mint.to_account_info(),
                    to:address.to_account_info,
                    authority: self.chrt_mint_authority.to_account_info(),
                }
        );
 
}

but I got an error that says I can't use pubkey with the to_account_info() method, Any help about how I can pass the token account address as an argument will be appreciated

2 Answers 2

8

You cannot pass the public key of an account you intend to modify as an argument in solana. Instead you need to include the public key as one of the accounts in the account context. This will make sure the solana runtime gives you access to the account data. To ensure the user has passed a token account you can add the following to your account context.

use anchor_spl::token::TokenAccount;
...
#[derive(Accounts)]
pub struct Donate<'info> {
  ...
  pub address: Account<'info, TokenAccount>,
  ...
}

There are additional token account specific constraints you can place on top of the address token account to ensure it has the right mint or account owner but that is beyond the scope of this question. https://docs.rs/anchor-lang/latest/anchor_lang/derive.Accounts.html#spl-constraints

2

On Solana, you need to provide all the accounts you'll use on the code in the instruction definition, that's why you can't transform a Pubkey to a AccountInfo. So you would need to send the to address on the Donate struct, just like you send the other accounts. It would end up something like this:

pub fn mint_tok(ctx:Context<Donate>, amount_token:u64) -> Result<()> {
  let cpi_ctx = CpiContext::new(
    self.token_program.to_account_info(),
    MintTo {  
      mint: ctx.accounts.chrt_mint.to_account_info(),
      to: ctx.accounts.address.to_account_info(),
      authority: self.chrt_mint_authority.to_account_info(),
    }
  );
}

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.