【问题标题】:How to convert 'AccountId' into 'ValidAccountId' in Near protocol contracts?如何在 Near 协议合约中将“AccountId”转换为“ValidAccountId”?
【发布时间】:2021-07-23 17:04:27
【问题描述】:

我想知道函数调用者的 ID 并检查他的余额。问题是env::signer_account_id() 返回AccountId/String 类型的数据,而函数ft_balance_of() 需要ValidAccountId 类型的输入。 ft_balance_of() 是 NEP-141 fungible token function。

let current_user = env::signer_account_id();

let balance = self.ft_balance_of(current_user); // error

VS 代码中的错误消息

mismatched types
expected struct `near_sdk::json_types::ValidAccountId`, found struct `std::string::String`

【问题讨论】:

    标签: rust nearprotocol


    【解决方案1】:

    我无法评论 @sirwillem 的答案,但需要注意的一点是,您需要导入 std::convert::TryInto 特征才能使用该方法。

    你也可以使用TryFrom trait,如果它更容易的话。

    我刚刚添加了一个PR 来实现该类型的FromStr 特征,这样您就不需要导入任何特征而只需调用.parse()。不过,在它被拉入并发布之前,它是不可用的。

    【讨论】:

      【解决方案2】:

      ValidAccountId 是AccountId 的包装器,它验证字符串以确保它是有效格式。这通常在反序列化调用合约方法时发送的 JSON 时完成。但是,在这里你必须明确:

      // use try_into because it could fail to validate.
      let balance = self.ft_balance_of(current_user.try_into().unwrap());
      
      

      在这里查看测试: https://github.com/near/near-sdk-rs/blob/1951284503168c4e842e957e172c3b12c3c46240/near-sdk/src/json_types/account.rs#L90

      【讨论】:

        猜你喜欢
        • 2022-06-22
        • 2021-01-14
        • 2021-01-19
        • 2020-07-19
        • 2021-08-18
        • 2020-09-27
        • 1970-01-01
        • 2021-01-12
        • 2018-05-27
        相关资源
        最近更新 更多