avail_rust_client/
extensions.rs1use crate::{
2 UserError,
3 subxt_signer::{SecretUri, sr25519::Keypair},
4};
5use avail_rust_core::{
6 AccountId, H256,
7 ext::subxt_core::utils::AccountId32,
8 utils::{account_id_from_slice, account_id_from_str},
9};
10
11pub trait H256Ext {
12 fn from_str(s: &str) -> Result<H256, String>;
13}
14
15impl H256Ext for H256 {
16 fn from_str(s: &str) -> Result<H256, String> {
17 let mut s = s;
18 if s.starts_with("0x") {
19 s = &s[2..];
20 }
21
22 if s.len() != 64 {
23 let msg = std::format!(
24 "Failed to convert string to H256. Expected 64 bytes got {}. Input string: {}",
25 s.len(),
26 s
27 );
28 return Err(msg);
29 }
30
31 let block_hash = const_hex::decode(s).map_err(|e| e.to_string())?;
32 let block_hash = TryInto::<[u8; 32]>::try_into(block_hash);
33 match block_hash {
34 Ok(v) => Ok(H256(v)),
35 Err(e) => {
36 let msg = std::format!("Failed to covert decoded string to H256. Input {:?}", e);
37 Err(msg)
38 },
39 }
40 }
41}
42
43pub trait AccountIdExt {
44 fn from_str(value: &str) -> Result<AccountId, String>;
45 fn from_slice(value: &[u8]) -> Result<AccountId, String>;
46 fn default() -> AccountId;
47}
48
49impl AccountIdExt for AccountId {
50 fn from_str(value: &str) -> Result<AccountId, String> {
51 account_id_from_str(value)
52 }
53
54 fn from_slice(value: &[u8]) -> Result<AccountId, String> {
55 account_id_from_slice(value)
56 }
57
58 fn default() -> AccountId {
59 AccountId32([0u8; 32])
60 }
61}
62
63pub trait SecretUriExt {
64 fn from_str(value: &str) -> Result<SecretUri, UserError>;
65}
66
67impl SecretUriExt for SecretUri {
68 fn from_str(value: &str) -> Result<SecretUri, UserError> {
69 value.parse().map_err(|e| UserError::Other(std::format!("{:?}", e)))
70 }
71}
72
73pub trait KeypairExt {
74 fn from_str(value: &str) -> Result<Keypair, UserError>;
75 fn account_id(&self) -> AccountId;
76}
77
78impl KeypairExt for Keypair {
79 fn from_str(value: &str) -> Result<Keypair, UserError> {
80 let secret_uri = SecretUri::from_str(value).map_err(|e| UserError::Other(e.to_string()))?;
81 let keypair = Keypair::from_uri(&secret_uri).map_err(|e| UserError::Other(e.to_string()))?;
82 Ok(keypair)
83 }
84
85 fn account_id(&self) -> AccountId {
86 self.public_key().to_account_id()
87 }
88}