2

Please help to fix that error.

Error:
    'Program 6j89j9GECjYQCqu67ayNZKnyzLMGPhGF7yXrFohoWxjG invoke [1]',
    'Program log: process_instruction: 6j89j9GECjYQCqu67ayNZKnyzLMGPhGF7yXrFohoWxjG: 8 accounts, data=[0, 4, 0, 0, 0, 97, 97, 97, 97, 5, 11, 0, 0, 0, 100, 101, 115, 99, 114, 105, 112, 116, 105, 111, 110]',
    'Program log: Adding movie review...',
    'Program log: Title: aaaa',
    'Program log: Rating: 5',
    'Program log: Description: description',
    'Program 11111111111111111111111111111111 invoke [2]',
    'Program 11111111111111111111111111111111 success',
    'Program log: PDA created: 2jhYmq462wq7nqBTdJN1ydGyJYTo2N8CFSkVxaajXURy',
    'Program log: unpacking state account',
    'Program log: borrowed account data',
    'Program log: checking if movie account is already initialized',
    'Program log: serializing account',
    'Program log: state account serialized',
    'Program log: create comment counter',
    'Program 11111111111111111111111111111111 invoke [2]',
    'Program 11111111111111111111111111111111 success',
    'Program log: comment counter created',
    'Program log: checking if counter account is already initialized',
    'Program log: comment count: 0',
    'Program log: deriving mint authority',
    'Program log: Minting 10 tokens to User associated token account',
    'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [2]',
    'Program log: Instruction: MintTo',
    'Program log: Error: InvalidAccountData',
    'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 1261 of 139034 compute units',
    'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA failed: invalid account data for instruction',
    'Program 6j89j9GECjYQCqu67ayNZKnyzLMGPhGF7yXrFohoWxjG consumed 62227 of 200000 compute units',
    'Program 6j89j9GECjYQCqu67ayNZKnyzLMGPhGF7yXrFohoWxjG failed: invalid account data for instruction'
  ]
My client code:
async function main() {
  
  console.log("Launching client...");

  /*
  Connect to Solana DEV net
  */
  let connection = new Connection('http://127.0.0.1:8899', 'confirmed');

  /*
  Get our program's public key
  */
  const secretKeyString = await fs.readFile(PROGRAM_KEYPAIR_PATH, {encoding: 'utf8'});
  const secretKey = Uint8Array.from(JSON.parse(secretKeyString));
  const programKeypair = Keypair.fromSecretKey(secretKey);
  let programId: PublicKey = programKeypair.publicKey;

  const transaction = new web3.Transaction()


  /*
  Generate an account (keypair) to transact with our program
  */
  const triggerKeypair = Keypair.generate();
  const airdropRequest = await connection.requestAirdrop(
    triggerKeypair.publicKey,
    20000000000,
  );
  await connection.confirmTransaction(airdropRequest);
  console.log('--LAMPORTS_PER_SOL ', LAMPORTS_PER_SOL);

  const movie = new Movie("aaaa", 5, "description", triggerKeypair.publicKey)
  const buffer = movie.serialize(0)

  const [pda] = await PublicKey.findProgramAddress(
    [triggerKeypair.publicKey.toBuffer(), Buffer.from(movie.title)], // new TextEncoder().encode(movie.title)],
    programId
)

const [pdaCounter] = await PublicKey.findProgramAddress(
    [pda.toBuffer(), Buffer.from("comment")], // new TextEncoder().encode(movie.title)],
    programId
)
const [tokenMint] = await PublicKey.findProgramAddress(
  [Buffer.from("token_mint")],
  programId
)

const [mintAuth] = await PublicKey.findProgramAddress(
  [Buffer.from("token_auth")],
  programId
)

const userAta = await getAssociatedTokenAddress(tokenMint, triggerKeypair.publicKey)
const ataAccount = await connection.getAccountInfo(userAta)

if (!ataAccount) {
  const ataInstruction = createAssociatedTokenAccountInstruction(
      triggerKeypair.publicKey,
      userAta,
      triggerKeypair.publicKey,
      tokenMint
  )
  //await connection.confirmTransaction(ataInstruction);
  transaction.add(ataInstruction)
}


  /*
  Conduct a transaction with our program
  */
  console.log('--Pinging Program ', programId.toBase58());
  const instruction = new TransactionInstruction({
    keys: [
      {
          pubkey: triggerKeypair.publicKey,
          isSigner: true,
          isWritable: false,
      },
      {
          pubkey: pda,
          isSigner: false,
          isWritable: true,
      },
      {
          pubkey: pdaCounter,
          isSigner: false,
          isWritable: true,
      },
      {
        pubkey: tokenMint,
        isSigner: false,
        isWritable: true,
    },
    {
        pubkey: mintAuth,
        isSigner: false,
        isWritable: false,
    },
    {
        pubkey: userAta,
        isSigner: false,
        isWritable: true,
    },
      {
          pubkey: SystemProgram.programId,
          isSigner: false,
          isWritable: false,
      },
      {
        pubkey: TOKEN_PROGRAM_ID,
        isSigner: false,
        isWritable: false,
    },
    ],
    programId,
    data: buffer,
  });
  await sendAndConfirmTransaction(
    connection,
    new Transaction().add(instruction),
    [triggerKeypair],
  );
}


main().then(
  () => process.exit(),
  err => {
    console.error(err);
    process.exit(-1);
  },
);
pub fn add_comment(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    comment: String,
) -> ProgramResult {
    msg!("Adding Comment...");
    msg!("Comment: {}", comment);

    let account_info_iter = &mut accounts.iter();

    let commenter = next_account_info(account_info_iter)?;
    let pda_review = next_account_info(account_info_iter)?;
    let pda_counter = next_account_info(account_info_iter)?;
    let pda_comment = next_account_info(account_info_iter)?;
    let token_mint = next_account_info(account_info_iter)?;
    let mint_auth = next_account_info(account_info_iter)?;
    let user_ata = next_account_info(account_info_iter)?;
    let system_program = next_account_info(account_info_iter)?;
    let token_program = next_account_info(account_info_iter)?;

    let mut counter_data =
        my_try_from_slice_unchecked::<MovieCommentCounter>(&pda_counter.data.borrow()).unwrap();

    let account_len = MovieComment::get_account_size(comment.clone());

    let rent = Rent::get()?;
    let rent_lamports = rent.minimum_balance(account_len);

    let (pda, bump_seed) = Pubkey::find_program_address(
        &[
            pda_review.key.as_ref(),
            counter_data.counter.to_be_bytes().as_ref(),
        ],
        program_id,
    );
    if pda != *pda_comment.key {
        msg!("Invalid seeds for PDA");
        return Err(ReviewError::InvalidPDA.into());
    }

    invoke_signed(
        &system_instruction::create_account(
            commenter.key,
            pda_comment.key,
            rent_lamports,
            account_len.try_into().unwrap(),
            program_id,
        ),
        &[
            commenter.clone(),
            pda_comment.clone(),
            system_program.clone(),
        ],
        &[&[
            pda_review.key.as_ref(),
            counter_data.counter.to_be_bytes().as_ref(),
            &[bump_seed],
        ]],
    )?;

    msg!("Created Comment Account");

    let mut comment_data =
        my_try_from_slice_unchecked::<MovieComment>(&pda_comment.data.borrow()).unwrap();

    msg!("checking if comment account is already initialized");
    if comment_data.is_initialized() {
        msg!("Account already initialized");
        return Err(ProgramError::AccountAlreadyInitialized);
    }

    comment_data.discriminator = MovieComment::DISCRIMINATOR.to_string();
    comment_data.review = *pda_review.key;
    comment_data.commenter = *commenter.key;
    comment_data.comment = comment;
    comment_data.is_initialized = true;
    comment_data.serialize(&mut &mut pda_comment.data.borrow_mut()[..])?;

    msg!("Comment Count: {}", counter_data.counter);
    counter_data.counter += 1;
    counter_data.serialize(&mut &mut pda_counter.data.borrow_mut()[..])?;

    // mint tokens here
    msg!("deriving mint authority");
    let (mint_pda, _mint_bump) = Pubkey::find_program_address(&[b"token_mint"], program_id);
    let (mint_auth_pda, mint_auth_bump) =
        Pubkey::find_program_address(&[b"token_auth"], program_id);

    if *token_mint.key != mint_pda {
        msg!("Incorrect token mint");
        return Err(ReviewError::IncorrectAccountError.into());
    }

    if *mint_auth.key != mint_auth_pda {
        msg!("Mint passed in and mint derived do not match");
        return Err(ReviewError::InvalidPDA.into());
    }

    if *user_ata.key != get_associated_token_address(commenter.key, token_mint.key) {
        msg!("Incorrect token mint");
        return Err(ReviewError::IncorrectAccountError.into());
    }

    if *token_program.key != TOKEN_PROGRAM_ID {
        msg!("Incorrect token program");
        return Err(ReviewError::IncorrectAccountError.into());
    }

    msg!("Minting 5 tokens to User associated token account");
    invoke_signed(
        // instruction
        &spl_token::instruction::mint_to(
            token_program.key,
            token_mint.key,
            user_ata.key,
            mint_auth.key,
            &[],
            5 * LAMPORTS_PER_SOL,
        )?,
        // account_infos
        &[token_mint.clone(), user_ata.clone(), mint_auth.clone()],
        // seeds
        &[&[b"token_auth", &[mint_auth_bump]]],
    )?;

    Ok(())
}
1
  • I failed at step: <br/> msg!("Minting 5 tokens to User associated token account"); invoke_signed( // instruction &spl_token::instruction::mint_to( token_program.key, token_mint.key, user_ata.key, mint_auth.key, &[], 5 * LAMPORTS_PER_SOL, )?, // account_infos &[token_mint.clone(), user_ata.clone(), mint_auth.clone()], // seeds &[&[b"token_auth", &[mint_auth_bump]]], )?; Commented Jun 8 at 0:41

1 Answer 1

1

It looks like you've commented out the line which confirms the transaction to create the ATA, which means that the chain hasn't confirmed that your ATA is created. When you try to mint to it, it will fail. Try uncommenting this line:

  //await connection.confirmTransaction(ataInstruction);

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.