Search code examples
rustnearprotocol

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


I want to know the function caller's ID and check his balance. Issue is that env::signer_account_id() returns data of type AccountId/String while function ft_balance_of() needs an input of type ValidAccountId. ft_balance_of() is an NEP-141 fungible token function.

let current_user = env::signer_account_id();

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

Error message in VS Code

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

Solution

  • ValidAccountId is a wrapper around a AccountId, which validates the string to ensure that it is a valid format. This is usually done when deserializing the JSON sent when calling the contract method. However, here you have to be explicit:

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

    See test here: https://github.com/near/near-sdk-rs/blob/1951284503168c4e842e957e172c3b12c3c46240/near-sdk/src/json_types/account.rs#L90