anondevpepe
anondevpepe

Reputation: 317

I notice when I try and use Borsh to serialize/deserialize I'll get errors

I notice when I try and use Borsh to serialize/deserialize I'll get errors when the data sizes don't match. For example, if I have an array in the account data and then I go and try and add another element. If I don't already have a placeholder data item in there with dummy values in the fields the serialization attempt will fail. Am I doing something wrong or is this just the way that it is and I just have to accept that?

Upvotes: 5

Views: 3231

Answers (1)

Chase Barker
Chase Barker

Reputation: 1015

If you are passing in the &[u8] of data to try_from_slice but the overall account data size is greater than your data you will get that borsh error as it defaults to checking the deserialized length with the overall slice length (or something like that):

  • Capture the actual size of the data you are storing by taking the .len() of the try_to_vec() output and write that in the account data block and then store your data. When you deserialize, use the stored len and use that to create a slice of that size from the account data to pass to try_from_slice. You can see an example (using a BTreeMap instead of your array but you get the idea) here https://github.com/hashblock/solana-cli-program-template/blob/main/program/src/account_state.rs at L66 (serialize) and L85 (deserialize).

Upvotes: 7

Related Questions