use crate::{Api, config::GearConfig, gear::DispatchError, result::Result};
use parity_scale_codec::Encode;
use sp_core::hashing;
use subxt::{
Metadata, OnlineClient,
error::{DispatchError as SubxtDispatchError, Error},
storage::{Address, Storage},
utils::H256,
};
impl Api {
pub fn decode_error(&self, dispatch_error: DispatchError) -> Error {
match SubxtDispatchError::decode_from(dispatch_error.encode(), self.metadata()) {
Ok(err) => err.into(),
Err(err) => err,
}
}
pub async fn storage_at(
&self,
block_hash: Option<H256>,
) -> Result<Storage<GearConfig, OnlineClient<GearConfig>>> {
let client = self.storage();
let storage = if let Some(h) = block_hash {
client.at(h)
} else {
client.at_latest().await?
};
Ok(storage)
}
}
pub(crate) fn write_storage_address_root_bytes(addr: &impl Address, out: &mut Vec<u8>) {
out.extend(hashing::twox_128(addr.pallet_name().as_bytes()));
out.extend(hashing::twox_128(addr.entry_name().as_bytes()));
}
pub(crate) fn storage_address_bytes(
addr: &impl Address,
metadata: &Metadata,
) -> Result<Vec<u8>, Box<Error>> {
let mut bytes = Vec::new();
write_storage_address_root_bytes(addr, &mut bytes);
addr.append_entry_bytes(metadata, &mut bytes)
.map_err(|e| Box::new(e.into()))?;
Ok(bytes)
}