0

I want to write a method which takes a String and converts it to an AccountId, like this:

pub fn send(
    &mut self,
    address: String
) -> Result<()> {
    // Some type conversion `address` to `account`
    self.env().transfer(account, value)
}

There's no type conversion from String to AccountId as part of the traits implemented on AccountId. How can I do this conversion?

1
  • your question is not clear, what exactly are you trying to do? Sep 5, 2022 at 4:41

2 Answers 2

3

I agree with Adam, you should prefer to take an AccountId directly instead of a String.

That said, if you do want to do this here is an option:

#[ink(message)]
pub fn convert(&mut self, s: ink::prelude::string::String) -> AccountId {
    let bytes = s.as_bytes();
    let account = AccountId::try_from(bytes).expect("You should handle this properly.");
    account
}
1

I assume the question is: "How to parse AccountId from String in an ink contract method?"

First, I would reconsider if this is actually needed. Why not make the method parameter to be of type AccountId?

In a contract code one is not limited to methods from the AccountId trait, but can use other methods implemented by the concrete type being used in the environment. The AccountId type is configurable, so one could provide a type with appropriate method for parsing strings. E.g. sp_runtime::AccountId32 has a FromStr implementation.

1
  • 2
    Unfortunately FromStr is std only. Given ink contracts are written in no_std environment, we should use an external crate like hex to parse the string to &[u8], and then convert it to AccountId32 by TryInto.
    – h4x3rotab
    Sep 8, 2022 at 4:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.