Skip to content

Commit

Permalink
refactor: Add more detailed logging information and fix logging forma…
Browse files Browse the repository at this point in the history
…t inconsistency
  • Loading branch information
S0c5 committed May 1, 2024
1 parent dbe6c7c commit 667a5b1
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 25 deletions.
2 changes: 1 addition & 1 deletion sube/examples/send_tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let public_hex = public.as_ref();
println!("hex: {}", hex::encode(public_hex));

let response = sube!("wss://kreivo.io/balances/transfer_keep_alive" => {
let response = sube!("ws://127.0.0.1:8000/balances/transfer_keep_alive" => {
signer: async |message: &[u8]| Ok(wallet.sign(message).await.expect("hello").as_bytes()) ,
sender: public.as_ref(),
body: json!({
Expand Down
3 changes: 2 additions & 1 deletion sube/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ impl Backend {
impl Rpc for Backend {
/// HTTP based JSONRpc request expecting an hex encoded result
async fn rpc(&self, method: &str, params: &[&str]) -> RpcResult {
log::info!("RPC `{}` to {}", method, &self.0);
log::info!("RPC `{}`({:?}) to {}", method, params, &self.0);

let req = surf::post(&self.0).content_type("application/json").body(
to_string(&rpc::Request {
id: 1.into(),
Expand Down
67 changes: 49 additions & 18 deletions sube/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,15 +163,15 @@ async fn query<'m>(chain: &impl Backend, meta: &'m Metadata, path: &str) -> Resu
}

if let Ok(key_res) = StorageKey::new(pallet, &item_or_call, &keys) {
log::info!("key_res {:?}", &key_res);
let res = chain.query_storage(&key_res).await?;
Ok(Response::Value(Value::new(res, key_res.ty, &meta.types)))
} else {
log::info!("hello here the chain is not available {:?}", &keys);
Err(Error::ChainUnavailable)
}
}



#[derive(Deserialize, Debug)]
pub struct AccountInfo {
nonce: u64,
Expand All @@ -189,7 +189,6 @@ pub struct Data {
flags: u128,
}


async fn submit<'m, V>(
chain: impl Backend,
meta: &'m Metadata,
Expand All @@ -209,7 +208,7 @@ where
.ok_or_else(|| Error::PalletNotFound(pallet))?;

let reg = &meta.types;

let ty = pallet.calls().expect("pallet does not have calls").ty.id;

let mut encoded_call = vec![pallet.index];
Expand Down Expand Up @@ -240,12 +239,12 @@ where
)
.await?;


match response {
Response::Value(value) => {
match response {
Response::Value(value) => {
log::info!("{:?}", serde_json::to_string(&value));
let str = serde_json::to_string(&value).expect("wrong account info");
let value: AccountInfo = serde_json::from_str(&str).expect("it must serialize");
let value: AccountInfo =
serde_json::from_str(&str).expect("it must serialize");
// let account_info: AccountInfo = serde_json::).unwrap();
log::info!("{}", &value.nonce);
Ok(value.nonce)
Expand All @@ -263,28 +262,37 @@ where

log::info!("tip_hex: {}", hex::encode(Compact(tip.clone()).encode()));

let extra_params_hex =
hex::encode([Compact(era).encode(), Compact(nonce).encode(), Compact(tip).encode(), vec![0x00u8]].concat());
let extra_params_hex = hex::encode(
[
Compact(era).encode(),
Compact(nonce).encode(),
Compact(tip).encode(),
vec![0x00u8],
]
.concat(),
);

log::info!("extra_params_hex: {}", extra_params_hex);
let extensions = ();


// vec![0x00u8] sign extensions
// TODO: implement signed extensions
// TODO: implement signed extensions
// meta.extrinsic.signed_extensions.iter().for_each(|ext| {
// log::info!("signed extension: {:?}", ext);
// let type_resolved = meta.types.resolve(ext.ty.id);
// log::info!("type_resolved: {:?}", type_resolved);
// log::info!("========================");
// });

[
vec![era], Compact(nonce).encode(), Compact(tip).encode(), vec![0x00u8]
].concat()
vec![era],
Compact(nonce).encode(),
Compact(tip).encode(),
vec![0x00u8],
]
.concat()
};


log::info!("Hex {:?}", hex::encode(&extra_params));

let additional_params = {
Expand Down Expand Up @@ -324,11 +332,24 @@ where
"System_Version.transaction_version is not a number".into(),
))? as u32;

let genesis_info = chain.block_info(Some(0u32)).await?;
log::info!("genesis_info {:?}", &genesis_info.number);
let genesis_block: Vec<u8> = chain.block_info(Some(0u32)).await?.into();

log::info!("spec {:?}", &spec_version);
log::info!("transaction_version {:?}", &transaction_version);
log::info!("genesis_block {:?}", &genesis_block);
log::info!("genesis_block {:?}", hex::encode(&genesis_block));
log::info!("genesis_block_hash {:?}", hex::encode(&genesis_info.hash));

// let response = query(&chain, meta, "system/BlockHash/0").await?;
// TODO: check why this params were not converted to 0x
// match response {
// Response::Value(value) => {
// let str = serde_json::to_string(&value).expect("helo");
// log::info!("storage blockhash {:?}", str);
// }
// _ => return Err(Error::BadInput),
// };

[
spec_version.to_le_bytes().to_vec(),
Expand Down Expand Up @@ -537,16 +558,26 @@ pub struct StorageKey {

impl StorageKey {
pub fn new<T: AsRef<str>>(meta: &PalletMeta, item: &str, map_keys: &[T]) -> Result<Self> {
log::info!("item {:?}", item);

let entry = meta
.storage()
.map(|s| s.entries().find(|e| e.name() == item))
.map(|s| s.entries().find(|e| {
log::info!("e.name {:?}", e.name());
e.name() == item
}))
.flatten()
.ok_or(Error::StorageKeyNotFound)?;

log::info!("entry {:?}", &entry);
log::info!("meta.name {:?}", &meta.name());

let key = entry
.key(meta.name(), map_keys)
.ok_or(Error::StorageKeyNotFound)?;

log::info!("key {:?}", key);

Ok(StorageKey {
key,
ty: entry.ty_id(),
Expand Down
16 changes: 13 additions & 3 deletions sube/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,18 @@ pub trait Rpc: Backend + Send + Sync {
async fn rpc(&self, method: &str, params: &[&str]) -> RpcResult;

fn convert_params(params: &[&str]) -> Vec<Box<RawValue>> {

let params_debug = params
.iter()
.map(|p| format!("{}", p))
.map(RawValue::from_string)
.map(Result::unwrap)
.collect::<Vec<_>>();

log::info!("rpc_debug {:?}", &params_debug);
params
.iter()
.map(|p| format!("\"{}\"", p))
.map(|p| format!("{}", p))
.map(RawValue::from_string)
.map(Result::unwrap)
.collect::<Vec<_>>()
Expand All @@ -30,7 +39,7 @@ impl<R: Rpc> Backend for R {
async fn query_storage(&self, key: &StorageKey) -> crate::Result<Vec<u8>> {
let key = key.to_string();
log::debug!("StorageKey encoded: {}", key);
self.rpc("state_getStorage", &[&key]).await.map_err(|e| {
self.rpc("state_getStorage", &[&format!("\"{}\"", &key)]).await.map_err(|e| {
log::debug!("RPC failure: {}", e);
// NOTE it could fail for more reasons
crate::Error::StorageKeyNotFound
Expand All @@ -45,7 +54,7 @@ impl<R: Rpc> Backend for R {
log::debug!("Extrinsic: {}", extrinsic);

let res = self
.rpc("author_submitExtrinsic", &[&extrinsic])
.rpc("author_submitExtrinsic", &[&format!("\"{}\"", &extrinsic)])
.await
.map_err(|e| crate::Error::Node(e.to_string()))?;
log::debug!("Extrinsic {:x?}", res);
Expand Down Expand Up @@ -75,6 +84,7 @@ impl<R: Rpc> Backend for R {

let block_hash = if let Some(block_number) = at {
let block_number = block_number.to_string();

block_info(self, &[&block_number]).await?
} else {
block_info(self, &[]).await?
Expand Down
4 changes: 2 additions & 2 deletions sube/src/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ unsafe impl Sync for Backend {}
impl Rpc for Backend {
async fn rpc(&self, method: &str, params: &[&str]) -> RpcResult {
let id = self.next_id().await;
info!("RPC `{}` (ID={})", method, id);
info!("RPC `{}`({:?}) (ID={})", method, params, id);

// Store a sender that will notify our receiver when a matching message arrives
let (sender, recv) = oneshot::channel::<rpc::Response>();
Expand All @@ -68,7 +68,7 @@ impl Rpc for Backend {
})
.expect("Request is serializable");

log::debug!("RPC Request {} ...", &msg[..50]);
log::debug!("RPC Request {} ...", &msg);

self.tx
.lock()
Expand Down

0 comments on commit 667a5b1

Please sign in to comment.