[英]How to add new properties to a NEAR Rust smart contract that already has state?
I have a Rust smart contract deployed to NEAR protocol, and now I want to update it and add properties for persistence.我有一个部署到 NEAR 协议的 Rust 智能合约,现在我想更新它并添加持久性属性。 But the contract does already have state, and if calling the new version I get the error
Cannot deserialize the contract state
.但是合同确实已经有 state,如果调用新版本,我会收到错误
Cannot deserialize the contract state
。
Here's the updated state struct ( where I want to add another HashMap ):这是更新的 state 结构(我想在其中添加另一个 HashMap ):
#[near_bindgen]
#[derive(Default, BorshDeserialize, BorshSerialize)]
pub struct RepositoryPermission {
permission: HashMap<String, HashMap<String, Permission>>,
invitations: HashMap<InvitationId, Invitation>, // I want to add this HashMap
}
What is the best way to add new properties for persisting?添加新属性以进行持久化的最佳方法是什么?
Instead of adding the property to the original and already persisted struct, you can create a new struct您可以创建一个新结构,而不是将属性添加到原始且已持久化的结构
const INVITATIONS_KEY: &[u8] = b"INVITATIONS";
#[derive(Default, BorshDeserialize, BorshSerialize)]
pub struct Invitations {
invitations: HashMap<InvitationId, Invitation>
}
and create (private) methods in the contract for deserialize / serialize this in the contract:并在合约中创建(私有)方法以在合约中反序列化/序列化它:
fn load_invitations(&self) -> Invitations {
return env::storage_read(INVITATIONS_KEY)
.map(|data| Invitations::try_from_slice(&data).expect("Cannot deserialize the invitations."))
.unwrap_or_default();
}
fn save_invitations(&self, invitations: Invitations) {
env::storage_write(INVITATIONS_KEY, &invitations.try_to_vec().expect("Cannot serialize invitations."));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.