1#![allow(clippy::result_large_err)]
19
20use std::{fmt::Debug, str::FromStr, time::Duration};
21
22use common::shared_parameters::SharedParams;
23use parity_scale_codec::DecodeAll;
24use sc_executor::{sp_wasm_interface::HostFunctions, WasmExecutor};
25use sp_core::{
26 offchain::{
27 testing::{TestOffchainExt, TestTransactionPoolExt},
28 OffchainDbExt, OffchainWorkerExt, TransactionPoolExt,
29 },
30 traits::ReadRuntimeVersionExt,
31};
32use sp_externalities::Extensions;
33use sp_keystore::{testing::MemoryKeystore, KeystoreExt};
34use sp_runtime::traits::Block as BlockT;
35use sp_weights::Weight;
36
37pub mod commands;
38pub mod common;
39
40pub(crate) const LOG_TARGET: &str = "try-runtime::cli";
41
42pub(crate) fn hash_of<Block: BlockT>(hash_str: &str) -> sc_cli::Result<Block::Hash>
44where
45 <Block::Hash as FromStr>::Err: Debug,
46{
47 hash_str
48 .parse::<<Block as BlockT>::Hash>()
49 .map_err(|e| format!("Could not parse block hash: {:?}", e).into())
50}
51
52pub struct RefTimeInfo {
53 pub used: Duration,
54 pub max: Duration,
55}
56
57impl TryFrom<Vec<u8>> for RefTimeInfo {
58 type Error = String;
59
60 fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
62 let (weight_used, weight_max) = <(Weight, Weight)>::decode_all(&mut &*value)
63 .map_err(|e| format!("failed to decode weight: {:?}", e))?;
64
65 Ok(RefTimeInfo {
66 used: Duration::from_nanos(weight_used.ref_time() / 1000),
68 max: Duration::from_nanos(weight_max.ref_time() / 1000),
69 })
70 }
71}
72
73pub(crate) fn full_extensions<H: HostFunctions>(wasm_executor: WasmExecutor<H>) -> Extensions {
75 let mut extensions = Extensions::default();
76 let (offchain, _offchain_state) = TestOffchainExt::new();
77 let (pool, _pool_state) = TestTransactionPoolExt::new();
78 let keystore = MemoryKeystore::new();
79 extensions.register(OffchainDbExt::new(offchain.clone()));
80 extensions.register(OffchainWorkerExt::new(offchain));
81 extensions.register(KeystoreExt::new(keystore));
82 extensions.register(TransactionPoolExt::new(pool));
83 extensions.register(ReadRuntimeVersionExt::new(wasm_executor));
84
85 extensions
86}
87
88pub(crate) fn rpc_err_handler(error: impl Debug) -> &'static str {
89 log::error!(target: LOG_TARGET, "rpc error: {:?}", error);
90 "rpc error."
91}