1

I am trying to pass parameters of types: float, int, bool, pubkey to Solana anchor program instructions from web3js library

#[account]
pub struct Parent {
    pub field1: String,
    pub field2: u8,
    pub field3: f64,
    pub field4: Pubkey,
}

I am using the following approach to serialize a string parameter

// serializing a string parameter
const data = 'sample data';

const string_u8vec = new TextEncoder().encode(data)
const string_u8vec_length = Buffer.from(new Uint8Array(new BN(string_u8vec.length).toArray("le", 4)));

const instructionBuffer = Buffer.concat([
   ixBuffer,            // namespace+method_name
   string_u8vec_length, // the length of the string
   string_u8vec         // the string itself
])

What is the correct way to serialize all other data types mentioned above? And is there a common method to serialize all data types or we should handle each differently?

Please help. Thanks

1 Answer 1

1

Each data type is serialized differently into the buffer, but they're all possible.

  • For u8, you can do instructionBuffer.writeUInt8(value), be sure to allocate 1 byte for it.
  • For f64, you can do instructionBuffer.writeDoubleLE(value), be sure to allocate 8 bytes for it.
  • For pubkey, you can do Buffer.concat([instructionBuffer, pubkey.toBuffer()]).

Most of this was taken from the Buffer documentation at https://nodejs.org/api/buffer.html

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.