3

I'm trying to migrate from Ethereum to Solana, I'm stuck on a simple piece of code. The add liquidity method is supposed to mint fungible tokens, but I get an error "Error: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: An account required by the instruction is missing". What am I doing wrong?

#[derive(Accounts)]
pub struct AddLiquidity<'info> {
    #[account(mut)]
    pub signer: Signer<'info>,
    #[account(
        init_if_needed,
        payer = signer,
        associated_token::mint = mint_to,
        associated_token::authority = signer
    )]
    pub mint_to: Account<'info, TokenAccount>,
    #[account(mut)]
    pub lsx_mint: Account<'info, Mint>,

    pub token_program: Program<'info, Token>,
    pub associated_token_program: Program<'info, AssociatedToken>,  
    pub system_program: Program<'info, System>
}

impl<'info> AddLiquidity<'info> {
    pub fn process(&mut self, amount: u64) -> Result<()> {
        msg!("Started!");
        let cpi_accounts = MintTo {
            mint: self.lsx_mint.to_account_info(),
            to: self.mint_to.to_account_info(),
            authority: self.lsx_mint.to_account_info(),
        };
        let cpi_program = self.token_program.to_account_info();
        let cpi_ctx = CpiContext::new(cpi_program, cpi_accounts);

        mint_to(cpi_ctx, amount)?;

        Ok(())
    }
}
import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { Application } from "../target/types/application";
import { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_PROGRAM_ID, getAccount, getAssociatedTokenAddressSync, getOrCreateAssociatedTokenAccount } from "@solana/spl-token";

async function airdropSol (wallet: anchor.web3.Keypair) {
  const signature = await anchor.getProvider().connection.requestAirdrop(wallet.publicKey, 1e12);
  const { blockhash, lastValidBlockHeight } = await anchor.getProvider().connection.getLatestBlockhash();
  await anchor.getProvider().connection.confirmTransaction({
    blockhash,
    lastValidBlockHeight,
    signature
    },'finalized'
  );
  const balance = await anchor.getProvider().connection.getBalance(wallet.publicKey);
  console.log("balance: ", balance);
}

describe("tests", () => {
  // Configure the client to use the local cluster.
  anchor.setProvider(anchor.AnchorProvider.env());

  const program = anchor.workspace.Application as Program<Application>;
  const wallet = anchor.web3.Keypair.generate();
  
  const [lsxMintPDA] = anchor.web3.PublicKey.findProgramAddressSync(
    [Buffer.from("lsx")],
    program.programId
  );

  const [statePDA] = anchor.web3.PublicKey.findProgramAddressSync(
    [Buffer.from("state")],
    program.programId
  );

  before(async () => {
    await airdropSol(wallet);
  })

  it("Add liquidity", async () => {
    let tx = await program.methods.initialize({}).accounts({
      state: statePDA,
      admin: wallet.publicKey,
      lsxMint: lsxMintPDA,
      tokenProgram: TOKEN_PROGRAM_ID,
      rent: anchor.web3.SYSVAR_RENT_PUBKEY 
    }).signers([wallet]).rpc();

    console.log("Transaction signature", tx);
    const latestBlockHash = await anchor.getProvider().connection.getLatestBlockhash();

    await anchor.getProvider().connection.confirmTransaction({
      blockhash: latestBlockHash.blockhash,
      lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
      signature: tx,
    });

    const liquidityProviderATA = getAssociatedTokenAddressSync(
      lsxMintPDA,
      wallet.publicKey
    );

    console.log("liquidityProviderATA ", liquidityProviderATA);

    tx = await program.methods.addLiquidity(new anchor.BN(10e9)).accounts({
      signer: wallet.publicKey,
      mintTo: liquidityProviderATA,
      lsxMint: lsxMintPDA,
      tokenProgram: TOKEN_PROGRAM_ID,
      associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
      systemProgram: anchor.web3.SystemProgram.programId,
    }).signers([wallet]).rpc();

    console.log("tx:", tx);

    let balance = await anchor.getProvider().connection.getTokenAccountBalance(liquidityProviderATA);
    console.log("Balance after: ", balance.value);
  });
});
2
  • Did you create the lsx_mint mint account in the initialize instruction?
    – john
    Commented Dec 24, 2023 at 5:32
  • Yep, I did it before
    – Nutinaguti
    Commented Dec 24, 2023 at 8:19

2 Answers 2

3

I realized that I was creating object CpiContext through CpiContext::new, the mistake was that a signature is required to perform the mint function, so it would be more correct to do this:

let cpi_ctx = CpiContext::new_with_signer(
            self.token_program.to_account_info(),
            MintTo {
                mint: self.lsx_mint.to_account_info(),
                to: self.mint_to.to_account_info(),
                authority: self.lsx_mint.to_account_info(),
            },
            signer
        );
1

It's probably because you aren't passing the Anchor context into the process function. You are passing the accounts in the script, but you aren't telling the process function what accounts to expect via Anchor.

It would probably run if you stripped out the impl block, or at least you would be on to the next error.

    pub fn process(ctx: Context<AddLiquidity>, amount: u64) -> Result<()> {
        msg!("Started!");
        let cpi_accounts = MintTo {
            mint: ctx.lsx_mint.to_account_info(), 
            to: ctx.mint_to.to_account_info(),
            authority: ctx.lsx_mint.to_account_info(),
        };
        let cpi_program = ctx.token_program.to_account_info();
        let cpi_ctx = CpiContext::new(cpi_program, cpi_accounts);

        mint_to(cpi_ctx, amount)?;

        Ok(())
    }

Or something thereabouts.. In any case my guess would be because you aren't passing the context into the function in a way that satisfies it.

5
  • Thanks for an answer, but i have "initialize" function that looks like "add_liquidity" and it works fine
    – Nutinaguti
    Commented Dec 24, 2023 at 8:13
  • So nowhere in your initialize function has a Context<> passed into it? Impl aside..? Commented Dec 24, 2023 at 12:32
  • Yes, in my case it works, btw i found my fault
    – Nutinaguti
    Commented Dec 24, 2023 at 14:10
  • What was it? …. Commented Dec 24, 2023 at 14:47
  • what is the fault ???
    – blackhorse
    Commented Jan 12 at 18:25

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.