2

I defined UserAction enum in the Solana program.

#[derive(AnchorDeserialize)]
#[derive(AnchorSerialize)]
pub enum UserAction {
    VIEW,
    LIKE,
    SHARE,
    COMMENT,
    DOWNLOAD,
}

Using this in an entry point.

    pub fn my_fun(ctx: Context<DoPost>, action: UserAction) -> ProgramResult {
        // Do something
        Ok(())
    }

How can I pass enum using @solana/web3.js?

Xueming
  • 168
  • 1
  • 1
  • 11

1 Answers1

0

As you've noticed, there's no native way to do this in JS, so you'll have to do the encoding by hand, first a byte to define the instruction type, then all the other bytes to define the instruction data.

Here's a simple example to call VIEW, assuming that it also takes a u64:

import * as BufferLayout from '@solana/buffer-layout';
const instructionLayout = BufferLayout.struct([
  BufferLayout.u8('instruction'),
  BufferLayout.ns64('number'),
]);
const data = Buffer.alloc(instructionLayout.span);
instructionLayout.encode({instruction: 0, number: 42}, data);
const instruction = TransactionInstruction({
      keys: [
        {pubkey: myPubkey, isSigner: false, isWritable: true},
// .. add all your account keys here
      ],
      programId: myProgramId,
      data,
    });

For a more complete example, check out how createAccount is defined for the system program in web3.js: https://github.com/solana-labs/solana/blob/f0a235d16fd21da11176c21297176234121a3d8c/web3.js/src/system-program.ts#L655

Jon C
  • 7,019
  • 10
  • 17