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 {
13 fn from_str(s: &str) -> Result<H256, String>;
24}
25
26impl H256Ext for H256 {
27 fn from_str(s: &str) -> Result<H256, String> {
28 let mut s = s;
29 if s.starts_with("0x") {
30 s = &s[2..];
31 }
32
33 if s.len() != 64 {
34 let msg = std::format!(
35 "Failed to convert string to H256. Expected 64 bytes got {}. Input string: {}",
36 s.len(),
37 s
38 );
39 return Err(msg);
40 }
41
42 let block_hash = const_hex::decode(s).map_err(|e| e.to_string())?;
43 let block_hash = TryInto::<[u8; 32]>::try_into(block_hash);
44 match block_hash {
45 Ok(v) => Ok(H256(v)),
46 Err(e) => {
47 let msg = std::format!("Failed to covert decoded string to H256. Input {:?}", e);
48 Err(msg)
49 },
50 }
51 }
52}
53
54pub trait AccountIdExt {
56 fn from_str(value: &str) -> Result<AccountId, String>;
67
68 fn from_slice(value: &[u8]) -> Result<AccountId, String>;
79
80 fn default() -> AccountId;
85}
86
87impl AccountIdExt for AccountId {
88 fn from_str(value: &str) -> Result<AccountId, String> {
89 account_id_from_str(value)
90 }
91
92 fn from_slice(value: &[u8]) -> Result<AccountId, String> {
93 account_id_from_slice(value)
94 }
95
96 fn default() -> AccountId {
97 AccountId32([0u8; 32])
98 }
99}
100
101pub trait SecretUriExt {
103 fn from_str(value: &str) -> Result<SecretUri, UserError>;
114}
115
116impl SecretUriExt for SecretUri {
117 fn from_str(value: &str) -> Result<SecretUri, UserError> {
118 value.parse().map_err(|e| UserError::Other(std::format!("{:?}", e)))
119 }
120}
121
122pub trait KeypairExt {
124 fn from_str(value: &str) -> Result<Keypair, UserError>;
135
136 fn account_id(&self) -> AccountId;
141}
142
143impl KeypairExt for Keypair {
144 fn from_str(value: &str) -> Result<Keypair, UserError> {
145 let secret_uri = SecretUri::from_str(value).map_err(|e| UserError::Other(e.to_string()))?;
146 let keypair = Keypair::from_uri(&secret_uri).map_err(|e| UserError::Other(e.to_string()))?;
147 Ok(keypair)
148 }
149
150 fn account_id(&self) -> AccountId {
151 self.public_key().to_account_id()
152 }
153}