Skip to content
Snippets Groups Projects
Unverified Commit b5fc649d authored by Kian Paimani's avatar Kian Paimani
Browse files

Add FromStr for AccountId32

parent b9d96fab
Branches 547
No related merge requests found
...@@ -647,6 +647,28 @@ impl<'de> serde::Deserialize<'de> for AccountId32 { ...@@ -647,6 +647,28 @@ impl<'de> serde::Deserialize<'de> for AccountId32 {
} }
} }
#[cfg(feature = "std")]
impl sp_std::str::FromStr for AccountId32 {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if &s[..2] == "0x" && s.len() == 66 {
// try and parse 0x hex string
let mut bytes = [0u8; 32];
hex::decode_to_slice(&s[2..], &mut bytes).map_err(|_| "invalid hex address.")?;
Ok(bytes.into())
} else if s.len() == 64 {
// or string without 0x
let mut bytes = [0u8; 32];
hex::decode_to_slice(s, &mut bytes).map_err(|_| "invalid hex address.")?;
Ok(bytes.into())
} else {
// or ss58
Self::from_ss58check(s).map_err(|_| "invalid ss58 address.")
}
}
}
#[cfg(feature = "std")] #[cfg(feature = "std")]
pub use self::dummy::*; pub use self::dummy::*;
...@@ -1159,4 +1181,25 @@ mod tests { ...@@ -1159,4 +1181,25 @@ mod tests {
Ok(TestPair::Standard{phrase: "hello world".to_owned(), password: Some("password".to_owned()), path: vec![DeriveJunction::soft(1), DeriveJunction::hard("DOT")]}) Ok(TestPair::Standard{phrase: "hello world".to_owned(), password: Some("password".to_owned()), path: vec![DeriveJunction::soft(1), DeriveJunction::hard("DOT")]})
); );
} }
#[test]
fn accountid_32_from_str_works() {
use std::str::FromStr;
assert!(AccountId32::from_str("5G9VdMwXvzza9pS8qE8ZHJk3CheHW9uucBn9ngW4C1gmmzpv").is_ok());
assert!(AccountId32::from_str("5c55177d67b064bb5d189a3e1ddad9bc6646e02e64d6e308f5acbb1533ac430d").is_ok());
assert!(AccountId32::from_str("0x5c55177d67b064bb5d189a3e1ddad9bc6646e02e64d6e308f5acbb1533ac430d").is_ok());
assert_eq!(
AccountId32::from_str("99G9VdMwXvzza9pS8qE8ZHJk3CheHW9uucBn9ngW4C1gmmzpv").unwrap_err(),
"invalid ss58 address.",
);
assert_eq!(
AccountId32::from_str("gc55177d67b064bb5d189a3e1ddad9bc6646e02e64d6e308f5acbb1533ac430d").unwrap_err(),
"invalid hex address.",
);
assert_eq!(
AccountId32::from_str("0xgc55177d67b064bb5d189a3e1ddad9bc6646e02e64d6e308f5acbb1533ac430d").unwrap_err(),
"invalid hex address.",
);
}
} }
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment