Near协议合约中如何将'AccountId'转换为'ValidAccountId'?

How to convert 'AccountId' into 'ValidAccountId' in Near protocol contracts?

我想知道函数调用者的 ID 并查看他的余额。问题是 env::signer_account_id() returns 类型 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 Code 中的错误消息

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

ValidAccountIdAccountId 的包装器,它验证字符串以确保它是有效格式。这通常在反序列化调用合约方法时发送的 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

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

您也可以使用 TryFrom 特性,如果它更容易的话。

我刚刚为该类型添加了一个 PR in to implement the FromStr 特征,这样您就不需要导入任何特征,而只需调用 .parse()。不过,在它被拉入和释放之前,这将不可用。