In order to send nft to my contract then it can transfer to other accounts, I create an associated account from programId and transfer to that ata. Then how can I transfer NFT from my contract to other accounts?
let tokenAccountOfProgram = await createAssociatedTokenAccount(
provider.connection,
owner,
minter,
program.programId
)
await program.methods
.createMarketItem(...)
.accounts({
// systemProgram: SystemProgram.programId,
stateAccount: state_pda.publicKey,
to: tokenAccountOfProgram,
tokenProgram: TOKEN_PROGRAM_ID,
user: owner,
from: tokenAccount,
authProgram: program.programId
}).signers([owner]).rpc();
This is the code for transfering and its context:
let transfer_instruction = Transfer {
from: ctx.accounts.from.to_account_info(),
to: ctx.accounts.to.to_account_info(),
authority: ctx.accounts.user.to_account_info(),
};
let cpi_program = ctx.accounts.token_program.to_account_info();
let cpi_ctx = CpiContext::new(cpi_program, transfer_instruction);
anchor_spl::token::transfer(cpi_ctx, 1)?;
#[derive(Accounts)]
pub struct CreateMarketItem<'info> {
#[account(mut)]
pub user: Signer<'info>, // seller
#[account(mut)]
pub state_account: Account<'info, State>,
/// CHECK:
#[account(mut)]
pub to: AccountInfo<'info>,
/// CHECK:
#[account(mut)]
pub from: AccountInfo<'info>,
pub token_program: Program<'info, Token>,
/// CHECK:
#[account(mut)]
pub auth_program: AccountInfo<'info>,
}
And this is the code I use for transferring back:
pub fn transfer_back(
ctx: Context<CreateMarketItem>,
) -> Result<()> {
let transfer_instruction = Transfer {
from: ctx.accounts.to.to_account_info(),
to: ctx.accounts.from.to_account_info(),
authority: ctx.accounts.auth_program.to_account_info(),
};
let cpi_program = ctx.accounts.token_program.to_account_info();
let cpi_ctx = CpiContext::new(cpi_program, transfer_instruction);
anchor_spl::token::transfer(cpi_ctx, 1)?;
Ok(())
}
// code on client
await program.methods
.transferBack()
.accounts({
// systemProgram: SystemProgram.programId,
stateAccount: state_pda.publicKey,
to: tokenAccountOfProgram,
tokenProgram: TOKEN_PROGRAM_ID,
user: owner,
from: tokenAccount,
authProgram: program.programId
}).signers([owner]).rpc();
It return "Error: AnchorError caused by account: auth_program. Error Code: ConstraintMut. Error Number: 2000. Error Message: A mut constraint was violated.". How can I fix this?