Skip to content

Instantly share code, notes, and snippets.

@satellitex
Created June 12, 2019 08:40
Show Gist options
  • Save satellitex/6641dd968426ee03f41b1edc5d046f2d to your computer and use it in GitHub Desktop.
Save satellitex/6641dd968426ee03f41b1edc5d046f2d to your computer and use it in GitHub Desktop.
use metadata::{RuntimeMetadata, RuntimeMetadataV4, RuntimeMetadataPrefixed};
use parity_codec::Decode;
use serde_json::json;
use sr_primitives::OpaqueMetadata;
use ws::{connect, CloseCode};
use jsonrpc_core_client::transports::parse_response;
use jsonrpc_core::Value;
use url::form_urlencoded::Target;
fn main() {
// Connect to the url and call the closure
if let Err(error) = connect("ws://127.0.0.1:9944", |out| {
let req = json!({
"method": "chain_getBlockHash",
"params": [],
"jsonrpc": "2.0",
"id": "1",
})
.to_string();
// Queue a message to be sent when the WebSocket is open
if out.send(req.clone()).is_err() {
println!("Websocket couldn't queue an initial message.")
} else {
println!("Client sent message {}. ", req)
}
// The handler needs to take ownership of out, so we use move
move |msg: ws::Message| {
// Handle messages received on this connection
println!("Client got message '{}'. ", msg);
println!("Client got message '{}'. ", msg.is_binary());
out.close(CloseCode::Normal)
}
}) {
// Inform the user of failure
println!("Failed to create WebSocket due to: {:?}", error);
}
if let Err(error) = connect("ws://127.0.0.1:9944", |out| {
let req = json!({
"method": "state_getMetadata",
"params": ["0x4c61f1b0a5f0311a42fa08c0edf229e94fe2cc210d1ab2a0460209c39d96e241"],
"jsonrpc": "2.0",
"id": "2",
})
.to_string();
// Queue a message to be sent when the WebSocket is open
if out.send(req.clone()).is_err() {
println!("Websocket couldn't queue an initial message.")
} else {
println!("Client sent message {}. ", req)
}
move |msg: ws::Message| {
// Handle messages received on this connection
println!("Client got message '{}'. ", msg);
let mut res = parse_response(&msg.as_text().expect("as_text"));
if let Value::String(s) = res.as_mut().expect("ok parse response")[0].1.as_mut().expect("no error") {
let binary = hex::decode(s.split_off(2)).expect("ok");
let metadata = RuntimeMetadataPrefixed::decode(&mut &binary[..]).expect("unk3");
println!("Get Vec<u8>: {:?}.", metadata);
// let meta_p = RuntimeMetadataPrefixed::decode(&mut &(*metadata)[..]).expect("unk4");
// println!("Get JSON: {:?}.", meta_p);
}
// Close the connection
out.close(CloseCode::Normal)
}
}) {
// Inform the user of failure
println!("Failed to create WebSocket due to: {:?}", error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment