2

I am trying to invoke an instruction and since it is not a cross-program, how can I achieve that without using CPI?

Think like that, I have some instructions on my program asset_create, asset_delete and asset_split. Each instruction has its own responsibility, that is they have different structs. However, in some case, I want to invoke asset_create instruction into my asset_split one.

impl <'info> AssetSplit<'info>{
  pub fn process(&mut self) -> Result<()> {
 // some logic related to the split

 // after split, I want to trigger `asset_create`
 asset_create()
  }
}

1 Answer 1

1

You could just extract the logic into a new function and call that function from both of your instruction handlers.

Here you can see an example:

https://github.com/solana-developers/solana-game-examples/blob/main/seven-seas/program/programs/seven-seas/src/instructions/move_player.rs

pub fn move_player_v2(ctx: Context<MovePlayer>, direction: u8) -> Result<()> {
    let game = &mut ctx.accounts.game_data_account.load_mut()?;

    match game.move_in_direction(
        direction,
        ctx.accounts.player.to_account_info(),
        ctx.accounts.chest_vault.to_account_info(),
        ctx.accounts.vault_token_account.to_account_info(),
        ctx.accounts.player_token_account.to_account_info(),
        ctx.accounts.token_account_owner_pda.to_account_info(),
        ctx.accounts.token_program.to_account_info(),
        ctx.bumps["token_account_owner_pda"],
        &mut ctx.accounts.game_actions,
    ) {
        Ok(_val) => {}
        Err(err) => {
            panic!("Error: {}", err);
        }
    }
    game.print().unwrap();
    Ok(())
}

The move_in_direction function can be called from different instructions. Just one thing you need to make sure is that you have all the needed accounts in both cases.

2
  • But in your case, move_in_direction is not an instruction, it is a method inside your state account. Let's think like that, you want to use pause_thread instruction within your move_player ix. Would you do a CPI for that? Commented Nov 14 at 8:20
  • 1
    No you would extract pause thread into its own function and call it from both instructions
    – Jonas H.
    Commented Nov 14 at 9:23

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.