2

An example is a thousand word. Is something like this possible:

#[program]
pub mod cross_chain_swap {
    use super::*;

    pub fn my_fn(Either<Context<Instruction1>, Context<Instruction2>>) -> Result<()> {...}

Basically, I'm implementing kind of a "swap" program. I have to deal with either native SOL or arbitrary ERC20 tokens. So, I have two instruction:

#[derive(Accounts)]
pub struct Native<'info> {
    #[account(mut)]
    pub program_token_account: SystemAccount<'info>,
    #[account(mut)]
    pub user_token_account: SystemAccount<'info>,
}

#[derive(Accounts)]
pub struct Erc20<'info> {
    pub user: SystemAccount<'info>,
    pub token_mint: Account<'info, Mint>,
    #[account(
        mut,
        associated_token::mint = token_mint,
        associated_token::authority = user
    )]
    pub signer_token_account: Account<'info, TokenAccount>,

    #[account(
        mut,
        associated_token::mint = token_mint,
        associated_token::authority = my_program_account,
    )]
    pub program_token_account: Box<Account<'info, TokenAccount>>,

}

Both these instructions essentially does the same thing, but it mean that I need two different functions for the same behavior. I would like to have a function that can either take the "Native" Instruction, or the "Erc20" one

1 Answer 1

4

No, it is not possible to use Either (at least not out of the box).

First, the Either type is a third-party library (https://github.com/rayon-rs/either) and any such thing would need to be specifically integrated into libraries (SDK or Anchor or ...). Somebody would need to provide such integration. There is nothing like what I can say.

Second, and more important, the Solana runtime requires you to provide all the accounts that will be used in the contract. Potentially you could pass into the contract code a list of AccountInfo (UncheckedAccounts) and then manually do all the deserialization in the contract code.

From the code, you use Anchor. The Anchor framework is not designed for such "dynamic" functionality.

I believe it's much better to have two separate instructions and manage the business logic on decisions which one is called at the client. Even, when you code one on-chain logic that is capable of deciding what token is used there will be needed still the same off-chain client logic to provide particular accounts that will be processed on-chain.

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.