【问题标题】:String attribute set in init method always returns empty stringinit 方法中设置的字符串属性总是返回空字符串
【发布时间】:2020-02-27 18:56:00
【问题描述】:

我有以下带有 impl 的结构:

#[near_bindgen]
#[derive(Default, Serialize, Deserialize, BorshDeserialize, BorshSerialize, Debug)]
pub struct MyStruct {
    owner: String
}

#[near_bindgen(init => new)]
impl MyStruct {
    fn new() -> Self {
        Self {
             owner: "bob".to_string()
        }
    }

    fn get_owner(&self) -> String {
         return self.owner;
    }
}

然后我使用near deploy my_contract --masterAccount myAccount部署合约

如果我使用近壳调用 get_owner:near call my_contract get_owner --accountId=myAccount 它总是返回 "" 而不是预期的 "bob"

似乎新方法可能不会在部署时被调用。

【问题讨论】:

    标签: nearprotocol


    【解决方案1】:

    当您需要对合约的初始化进行参数化时,通常会使用初始化函数。如果没有参数,那么只需实现Default trait:

    impl Default for MyStruct {
      fn default() -> Self {
        Self {
          owner: "bob".to_string()
        }
    }}
    

    【讨论】:

      【解决方案2】:

      初始化程序不会在部署时自动调用。 deploy 只是部署代码而不调用合约上的任何东西。我们可能应该向 shell 添加一个新方法,即deploy_and_call。但现在只需手动拨打new

      我们不自动初始化的原因是initializer 可能需要额外的参数。您可以将所有者传递给 new 方法。这是一个如何使用带有自定义参数的初始化程序以及如何确保在没有初始化的情况下不能调用合约的示例:

      #[near_bindgen]
      #[derive(BorshDeserialize, BorshSerialize)]
      pub struct FunToken {
          /// AccountID -> Account details.
          pub accounts: Map<AccountId, Account>,
      
          /// Total supply of the all token.
          pub total_supply: Balance,
      }
      
      impl Default for FunToken {
          fn default() -> Self {
              env::panic(b"Not initialized");
              unreachable!();
          }
      }
      
      #[near_bindgen(init => new)]
      impl FunToken {
          pub fn new(owner_id: AccountId, total_supply: Balance) -> Self {
              let mut ft = Self { accounts: Map::new(b"a".to_vec()), total_supply };
              let mut account = ft.get_account(&owner_id);
              account.balance = total_supply;
              ft.accounts.insert(&owner_id, &account);
              ft
          }
      }
      

      从这里:https://github.com/nearprotocol/near-bindgen/blob/master/examples/fun-token/src/lib.rs#L52-L77

      基本上它在默认调用期间会发生恐慌,因此无法调用未初始化的合约。

      【讨论】:

        猜你喜欢
        • 2020-10-28
        • 2016-12-16
        • 2019-07-25
        • 1970-01-01
        • 2013-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多