Does NEAR need both Serialize and BorshSerialize?
Asked Answered
P

2

6

Writing NEAR smart contracts in Rust, my compiler seems to require objects sent through the API to have the Serialize trait, and objects stored in the blockchain to have BorshSerialize and BorshDeserialize. Is that really the case, or am I doing something wrong? I would have thought that BorshSerialize would provide Serialize, and that you could use one library for both purposes.

Pee answered 18/12, 2020 at 18:45 Comment(0)
H
4

I would have thought that BorshSerialize would provide Serialize

That is not the case. BorshSerialize is specific to Borsh whereas Serialize comes from serde and neither implies the other. The reason why return type requires Serialize is because we want it to be serialized as json so that it is easy to handle on the frontend.

Hoye answered 18/12, 2020 at 19:5 Comment(1)
To clarify, the reason why Borsh does not implement serde Serialize, is because that would impede its performance and significantly increase the code size, which affects the size of the compiled contract.Fowkes
S
4

Your observation is correct. Serialize is serde::Serialize, with serde_json gives you serde Serialize. BorshSerailize is serialize with borsh, commonly used serialization format implemented by NEAR to store data on chain. Depending on your use case you might want to use them both or separately. Separately: you create "model" that store on chain that has only BorshSerialize, create "view" that returns by API that has only Serialize.

Salim answered 18/12, 2020 at 19:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.