【问题标题】:How can I upgrade the contract in future?以后如何升级合约?
【发布时间】:2021-09-12 07:28:04
【问题描述】:

合约函数是可升级的,但不是状态,例如

#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)]
pub struct Contract {
   owner_id: AccountId
}

如果我想添加另一个字段,比如saving_id,它会报错

#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)]
pub struct Contract {
   owner_id: AccountId,
   saving_id: AccountId
}

如何编写可升级的合约?

【问题讨论】:

  • 如果你提供它给你的错误将会很有用

标签: nearprotocol


【解决方案1】:

您应该编写一个类似于 init 函数的迁移函数,但不是从头开始创建状态,而是首先您可以访问旧状态,执行迁移并转储新状态。

要从 rust 合约执行此操作,您需要使用 #[init(ignore_state)] 注释迁移函数(在 3.0.1 的 near-sdk-rs 中可用)。这将在不检查合约是否首先初始化的情况下执行该函数。

完整示例取自near-sdk-rs

#[near_bindgen]
impl Contract {
    #[init(ignore_state)]
    pub fn migrate_state(new_data: String) -> Self {
        // Deserialize the state using the old contract structure.
        let old_contract: OldContract = env::state_read().expect("Old state doesn't exist");
        // Verify that the migration can only be done by the owner.
        // This is not necessary, if the upgrade is done internally.
        assert_eq!(
            &env::predecessor_account_id(),
            &old_contract.owner_id,
            "Can only be called by the owner"
        );

        // Create the new contract using the data from the old contract.
        Self { owner_id: old_contract.owner_id, data: old_contract.data, new_data }
    }
}

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 2021-06-14
      • 2022-07-19
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 2023-03-23
      相关资源
      最近更新 更多