0

I have a Solidity function:

    function add(uint256 a, uint256 b) public pure returns (uint256) {
        uint256 result = a + b;
        return result;
    }

That I've migrated over to Solana using solang. I want to call the add() function in a NodeJS script. It seems I need to serialize the call using the borsh serializer package.

The problem I have is that I can't figure out how to create the required schema for this Solana transaction instruction object:

   const num1 = 10;
   const num2 = 20;
   const transcationInstruction = {
      add: {
        num1,
        num2,
      },
    }

For what it's worth, I am trying to follow this example from from the GitHub page. But, I can't quite grasp how to serialize a nested JSON object.

The end goal is I want to define a transaction instruction like so:

  const instruction = new TransactionInstruction({
    keys: [
      { pubkey: payerKeypair.publicKey, isSigner: true },
      { pubkey: programAccountId, isSigner: false },
    ],
    programId: programAccountId,
    data: encodedInstruction,
  });

WHERE

encodedInstruction is the borsh serialized transaction instruction for the add(num1, num2) function in the Solana smart contract.

Thus, I reach out for help. Thanks in advance for any assistance.

I owe you one.

1 Answer 1

0

Typically an instruction is serialized as an enum, ie:

const schema = { enum: [{ struct: { add: { struct: { num1: 'u64', num2: 'u64' } }}}] };

Which you can serialize by running:

const encoded = borsh.serialize(schema, {add: { num1: 10, num2: 20 } });

This is according to the examples in the README. In your program you should double-check that the bytes are correct.

1
  • Thank you @Jon C! Will try your suggestion today!
    – reselbob
    Commented Dec 12, 2023 at 21:03

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.