简体   繁体   中英

Solana CPI (runtime) invoke fails when creating a new account by system_instruction::create_account (on-chain program with anchor framework)

I am trying to create a simple program that lets users mint SPL tokens. This program is bootstrapped by Anchor. Unfortunately, It failed on very first step creating a PDA account by CPI. Please see the detailed info below:

----Processors------

I tried to simplify the on-chain program's processor to create a simple PDA account using Solana system program. The processor has only one CPI.

----Instructions-----

I also tried to simplify the instruction by only inputting 4 accounts(See the screenshot or my code attached herewith): In typescript test code, it is also pretty simple. I just derive a PDA and then pass this PDA and the rest 3 accounts into the instruction. (two constraints 1. Assign a signer 2. Set mut for PDA account)

-----Error-----

But I still get the error

Transaction simulation failed: Error processing Instruction 0: An account required by the instruction is missing 
    Program 6KA5onmgQN7gsBZ5whPCTVL4EQcRob6vw7TYYNvik8xb invoke [1]
    Program log: Instruction: Mintnft
    Program log: First line in MintNFT processor
    Instruction references an unknown account 11111111111111111111111111111111
    Program 6KA5onmgQN7gsBZ5whPCTVL4EQcRob6vw7TYYNvik8xb consumed 15319 of 200000 compute units
    Program 6KA5onmgQN7gsBZ5whPCTVL4EQcRob6vw7TYYNvik8xb failed: An account required by the instruction is missing
    1) is minted


  2 passing (2s)
  1 failing

  1) anchor_programs
       is minted:
     Error: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: An account required by the instruction is missing
      at Connection.sendEncodedTransaction (node_modules/@solana/web3.js/src/connection.ts:3961:13)
      at processTicksAndRejections (internal/process/task_queues.js:97:5)
      at Connection.sendRawTransaction (node_modules/@solana/web3.js/src/connection.ts:3918:20)
      at sendAndConfirmRawTransaction (node_modules/@solana/web3.js/src/util/send-and-confirm-raw-transaction.ts:27:21)
      at Provider.send (node_modules/@project-serum/anchor/src/provider.ts:118:18)
      at Object.rpc [as mintnft] (node_modules/@project-serum/anchor/src/program/namespace/rpc.ts:25:23)

It seems that I did not pass the correct accounts into the invoke body, but I have spent like a whole day checking but still not sure if there are any other missing accounts ( or AccountInfo). It will be super appreciated if anyone can give me a hint. You can see the summary of my code attached in a screenshot format.

.src/lib.rs

use anchor_lang::prelude::*;
use anchor_spl::token::Mint;
use solana_program::program::invoke;
use solana_program::system_instruction;


declare_id!("ArT6Hwus2hMwmNeNeJ2zGcQnvZsbrhz8vTbBdq35AdgG");

#[program]
pub mod anchor_programs {
    use super::*;
    pub fn initialize(ctx: Context<Initialize>, price: u64) -> ProgramResult {
        ctx.accounts.nft_creator.price = price;
        ctx.accounts.nft_creator.collection = vec![];
        
        Ok(())
    }    
    pub fn mintnft(ctx: Context<MintNFT>) -> ProgramResult {
        msg!("First line in MintNFT processor");
        let (mint_pda, _bump) = Pubkey::find_program_address(           // Calc PDA address from passed in nft_creater_program_id
            &[b"nft_creator"], 
            &ctx.accounts.nft_creater_program.key()
        );
        if mint_pda != ctx.accounts.mint_pda_acc.key()  {                         // Confirm if passed in PDA address is the same
            return Err(ProgramError::Custom(123))
        }
        let create_acc_ix = system_instruction::create_account(        // Try create account using system_instruction
            &ctx.accounts.minter.key(),
            &ctx.accounts.mint_pda_acc.key(),
            ctx.accounts.rent.minimum_balance(Mint::LEN),
            Mint::LEN as u64,
            &spl_token::ID,
        );
        invoke(&create_acc_ix, &[                          // Use invoke to call cross program invocation
            ctx.accounts.minter.clone(),
            ctx.accounts.mint_pda_acc.clone(),
        ])?;        
        Ok(())
    }
    
}
#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(init, payer=initializer, space=500)] 
    pub nft_creator: Account<'info, NftCreator>,
    #[account(mut, signer)]
    pub initializer: AccountInfo<'info>,
    pub system_program: AccountInfo<'info>,
    pub rent: Sysvar<'info, Rent>
}
#[derive(Accounts)]
pub struct MintNFT<'info> {
    #[account(mut, signer)]
    pub minter: AccountInfo<'info>,
    pub nft_creater_program: AccountInfo<'info>,
    #[account(mut)]
    pub mint_pda_acc: AccountInfo<'info>,
    pub rent: Sysvar<'info, Rent>
}
#[account]
pub struct NftCreator {
    collection: Vec<Pubkey>,
    price: u64
}



./tests/anchor_programs.ts

...

  it('is minted', async () => {
    let [mint_pda, _bump] = await anchor.web3.PublicKey.findProgramAddress(               // Use findProgram Address to generate PDA
        [Buffer.from(anchor.utils.bytes.utf8.encode("nft_creator"))],
        program.programId
    )


    const tx = await program.rpc.mintnft({                                                // Call program mintnft instruction
        accounts: {                                                                       /**@ACCOUNTS */
            // tokenProgram: TOKEN_PROGRAM_ID,
            minter: initializerMainAccount.publicKey,                                       // 1. minter as the initializer
            // nftCreater: nftCreatorAcc.publicKey,
            nftCreaterProgram: program.programId,                                           // 2. this program id
            mintPdaAcc: mint_pda,                                                           // 3. The mint_pda just generated
            // mintPdaAcc: mint_pda.publicKey,
            rent: anchor.web3.SYSVAR_RENT_PUBKEY,                                           // 4. sysVar 
        },
        signers: [initializerMainAccount]
    });
    console.log("Your transaction signature", tx);    
  });
});

Or refer to the full anchor project code in the github repo

I realized the issue:

  1. I did not pass the system_program into instruction.
pub system_program: Program<'info, System>
  1. Need to use invoke_signed to also let pda to sign
invoke_signed(                                                            
            &create_acc_ix,                                             
            &[                          
                self.minter.clone(),
                self.mint_pda_acc.clone(),
            ],
            &[&[ &mint_seed.as_ref(), &[*bump_seed] ]]
        )?;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM