1

I want to get the same Borsh Serialize result in both JS and rust for same data structure.

First , I run a demo test, but the result break my hope.

My rust program snippet:

#[derive(BorshDeserialize, BorshSerialize, Debug)]
pub struct PackTestOne {
    pub amount: u64,
    pub token_id: u32,
    pub recipient: Pubkey,
}

pub fn ser_der_test(ctx: Context<SerDerTest>, , token_id: u32, amount: u64, token_account:  Pubkey) -> Result<()> {
    let v1 = PackTestOne {
        amount: amount,
        token_id: token_id,
        recipient:token_account
    }; 
    let r1: Vec<u8> = v1.try_to_vec().unwrap(); 
    msg!("ser_der_test() r1: {:?}", r1); 
    Ok(())
}

my JS code:

// use  https://github.com/nameskyteam/borsher
import { BorshSchema, borshSerialize, borshDeserialize, Unit } from 'borsher';
   // other import ...

let tokenId = 100;
let token_account = new PublicKey( "Erg72DCzBE5X6qWDwLdzJ5owju8gKemL2JgYxEg8kHKs");
let amount = new anchor.BN(0.0123 * LAMPORTS_PER_SOL);

let DataSchema = BorshSchema.Struct({
    amount: BorshSchema.u64,
    tokenId: BorshSchema.u32,
    recipient: BorshSchema.Vec(BorshSchema.u8),
  });

type Data = {
    amount: number;
    tokenId: number;
    recipient: Uint8Array,
  };

const message : Data = {
    amount : amount.toNumber(),
    tokenId: tokenId,
    recipient: token_account.toBytes()
}  

buffer = borshSerialize(DataSchema, message);
console.log("message borshSerialize: ", buffer)

Then , using same data input, compare both result:

JS result:

 <Buffer e0 ae bb 00 00 00 00 00 64 00 00 00 20 00 00 00 cd e1 9a c0 c6 d7 b4 31 81 41 7b e8 1b 0a 7b ba 76 1c e1 1c ba a2 2f d4 45 08 dd 50 d2 a7 65 ce>

Rust result:

> Program logged: "ser_der_test() r1: [224, 174, 187, 0, 0, 0, 0, 0, 100, 0, 0, 0, 205, 225, 154, 192, 198, 215, 180, 49, 129, 65, 123, 232, 27, 10, 123, 186, 118, 28, 225, 28, 186, 162, 47, 212, 69, 8, 221, 80, 210, 167, 101, 206]"

obviously, in JS result , there is '20 00 00 00' fraction that rust result do not have. This '20 00 00 00' is the recipient bytes length. This is not my expectation.

How to get the same borsh Serialize of a struct in JS as the one in Rust program ?

1 Answer 1

1

I found the mistake I have made. SHOULD use BorshSchema.Array(BorshSchema.u8, 32), for PubKey type data 'recipient', not BorshSchema.Vec(BorshSchema.u8)

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.