Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/broker rpc #4

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
810 changes: 676 additions & 134 deletions Cargo.lock

Large diffs are not rendered by default.

19 changes: 16 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,21 @@ members = [
]

[dependencies]
async-trait = "0.1.68"
hex = { version = "0.4.3", default-features = false, features = ["alloc"] }
log = { version = "0.4.17", optional = true }
metadata = { version = "15.0.0", default-features = false, package = "frame-metadata", features = ["v14"] }
dashmap = "5.4.0"
tokio = { version = "1.16", features = ["full"] }
tokio-stream = { version = "0.1", features = ["sync"] }
frame-metadata = { version = "15.0.0", default-features = false, package = "frame-metadata", features = ["v14"] }
primitive-types = { version = "0.11.1", optional = true, features = ["codec"] }
serde = { version = "1.0.136", optional = true, features = ["derive"] }
serde_json = { version = "1.0.79", optional = true }
thiserror = { version = "1.0.30", optional = true }
ws = { version = "0.9.2", optional = true, features = ["ssl"] }
tokio-tungstenite = { version = "0.18.0", features = ["native-tls"] }
tungstenite = "0.18.0"
futures-util = "0.3"
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ['derive'] }

# Substrate dependencies
Expand All @@ -36,13 +43,19 @@ support = { version = "4.0.0-dev", default-features = false, git = "https://gith
sp-std = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.30" }
# need to add this for the app_crypto macro
sp-application-crypto = { version = "6.0.0", default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.30", features = ["full_crypto"] }
jsonrpsee = {version = "0.15.1", features = [ "macros", "ws-client", "client-ws-transport" ] }
jsonrpsee = {version = "0.16.2", features = [ "full" ] }

# local deps
ac-compose-macros = { path = "compose-macros", default-features = false }
ac-node-api = { path = "node-api", optional = true }
ac-primitives = { path = "primitives", default-features = false }

# broker
rust_decimal = { version = "1.22" }
x25519-dalek = "1.1.1"
rand = "0.8.5"
rand_core = "0.5"

[dev-dependencies]
env_logger = "0.9.0"
node-template-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.30" }
Expand All @@ -57,7 +70,7 @@ std = [
"sp-application-crypto/std",
"sp-core/std",
"codec/std",
"metadata/std",
"frame-metadata/std",
"sp-version",
"balances",
"system",
Expand Down
34 changes: 34 additions & 0 deletions examples/trader.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// #![feature(result_option_inspect)]
// use rust_decimal::Decimal;
use sp_keyring::AccountKeyring;
// use std::str::FromStr;
use substrate_api_client::{net::TungsteniteClient, Api};

// pub fn main() {
// let client = WsRpcClient::new("ws://127.0.0.1:9944");
// let mut api = Api::<sp_core::sr25519::Pair, WsRpcClient>::new(client).unwrap();
// api = api.set_signer(AccountKeyring::Bob.pair());
// let trader = Trader::new(api, AccountKeyring::Alice.to_account_id()).unwrap();
// println!("{:?}", trader.query_orders(0, 1));
// println!("{:?}", trader.query_account());
// trader.ask(
// 0,
// 1,
// Decimal::from_str("1").unwrap(),
// Decimal::from_str("9").unwrap(),
// );
// trader.cancel(0, 1, 2);
// }
#[tokio::main]
pub async fn main() {
env_logger::init();
let client = TungsteniteClient::new(
"wss://gateway.mainnet.octopus.network/fusotao/0efwa9v0crdx4dg3uj8jdmc5y7dj4ir2",
);
let api = Api::<sp_core::sr25519::Pair, TungsteniteClient>::new(
client,
Some(AccountKeyring::Bob.pair()),
)
.await
.unwrap();
}
169 changes: 156 additions & 13 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,166 @@
limitations under the License.

*/
#![cfg_attr(not(feature = "std"), no_std)]
#![feature(result_flattening)]
#![feature(result_option_inspect)]
#![feature(assert_matches)]
pub mod net;
pub mod rpc;
//pub mod trade;

#[cfg(feature = "std")]
pub mod std;
pub use ac_compose_macros::*;
pub use ac_node_api as runtime_types;
pub use ac_primitives as primitives;
pub use net::JsonRpcClient;
pub use rpc::Api;

pub mod utils;
pub trait FromHexString {
fn from_hex(hex: String) -> Result<Self, hex::FromHexError>
where
Self: Sized;
}

#[cfg(feature = "std")]
pub use crate::std::*;
impl FromHexString for Vec<u8> {
fn from_hex(hex: String) -> Result<Self, hex::FromHexError> {
let hexstr = hex
.trim_matches('\"')
.to_string()
.trim_start_matches("0x")
.to_string();
hex::decode(&hexstr)
}
}

pub use ac_primitives::{
AccountData, AccountDataGen, AccountInfo, AccountInfoGen, Balance, BlockNumber, GenericAddress,
GenericExtra, Hash, Index, Moment, RefCount, UncheckedExtrinsicV4,
};
impl FromHexString for primitives::Hash {
fn from_hex(hex: String) -> Result<Self, hex::FromHexError> {
let vec = Vec::from_hex(hex)?;
match vec.len() {
32 => Ok(primitives::Hash::from_slice(&vec)),
_ => Err(hex::FromHexError::InvalidStringLength),
}
}
}

#[cfg(feature = "std")]
pub use ac_compose_macros::compose_extrinsic;
pub trait DecodeHexString {
fn decode_hex(hex: String) -> Result<Self, hex::FromHexError>
where
Self: Sized;
}

pub use ac_compose_macros::{compose_call, compose_extrinsic_offline};
// TODO
impl<T: codec::Decode> DecodeHexString for T {
fn decode_hex(hex: String) -> Result<Self, hex::FromHexError>
where
Self: Sized,
{
let raw = Vec::from_hex(hex)?;
T::decode(&mut &raw[..]).map_err(|_| hex::FromHexError::InvalidStringLength)
}
}

pub trait ToHexString {
fn to_hex(&self) -> String;
}

impl<T: codec::Encode> ToHexString for T {
fn to_hex(&self) -> String
where
Self: codec::Encode,
{
format!("0x{}", hex::encode(self.encode()))
}
}

#[macro_export]
macro_rules! rpc {
($pallet: ident, $method: ident, [$($args: expr),*]) => {
{
serde_json::json!({
"jsonrpc": "2.0",
"method": format!("{}_{}", stringify!($pallet), stringify!($method)),
"params": [$($args),*],
})
}
};
($method: ident, [$($args: expr),*]) => {
{
serde_json::json!({
"jsonrpc": "2.0",
"method": stringify!(method),
"params": [$($args),*],
})
}
};
}

#[macro_export]
macro_rules! storage {
(value => $pallet: ident, $storage: ident, $block: expr) => {
{
let mut key = twox_128(stringify!($pallet).as_bytes()).to_vec();
key.extend(&twox_128(stringify!($storage).as_bytes()));
let key = format!("0x{}", hex::encode(key));
serde_json::json!({
"jsonrpc": "2.0",
"method": "state_getStorage",
"params": [key, $block],
})
}
};
(map => $pallet: ident, $storage: ident, $metadata: expr, $key: expr, $block: expr) => {
{
let mut prefix = twox_128(stringify!($pallet).as_bytes()).to_vec();
prefix.extend(&twox_128(stringify!($storage).as_bytes()));
let key = $metadata.pallet(stringify!($pallet))
.expect("pallet not exists")
.storage(stringify!($storage))
.expect("storage not exists")
.hasher()
.encode(&mut key);
prefix.extend(&key);
let key = format!("0x{}", hex::encode(key));
serde_json::json!({
"jsonrpc": "2.0",
"method": "state_getStorage",
"params": [key, $block],
})
}
};
}

#[cfg(test)]
mod tests {
// Note this useful idiom: importing names from outer (for mod tests) scope.
use super::*;

#[test]
fn test_hextstr_to_vec() {
assert_eq!(Vec::from_hex("0x01020a".to_string()), Ok(vec!(1, 2, 10)));
assert_eq!(
Vec::from_hex("null".to_string()),
Err(hex::FromHexError::InvalidHexCharacter { c: 'n', index: 0 })
);
assert_eq!(
Vec::from_hex("0x0q".to_string()),
Err(hex::FromHexError::InvalidHexCharacter { c: 'q', index: 1 })
);
}

#[test]
fn test_hextstr_to_hash() {
assert_eq!(
primitives::Hash::from_hex(
"0x0000000000000000000000000000000000000000000000000000000000000000".to_string()
),
Ok(primitives::Hash::from([0u8; 32]))
);
assert_eq!(
primitives::Hash::from_hex("0x010000000000000000".to_string()),
Err(hex::FromHexError::InvalidStringLength)
);
assert_eq!(
primitives::Hash::from_hex("0x0q".to_string()),
Err(hex::FromHexError::InvalidHexCharacter { c: 'q', index: 1 })
);
}
}
31 changes: 31 additions & 0 deletions src/net/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
pub mod tungstenite_client;

use crate::{
primitives::Hash,
rpc::{ApiResult, XtStatus},
};
pub use tungstenite_client::TungsteniteClient;

// TODO deprecated
pub trait RpcClient {
/// Sends a RPC request that returns a String
fn get_request(&self, jsonreq: serde_json::Value) -> ApiResult<String>;

/// Send a RPC request that returns a BlakeTwo_256 hash
fn send_extrinsic(&self, xthex_prefixed: String, exit_on: XtStatus) -> ApiResult<Option<Hash>>;
}

#[async_trait::async_trait]
pub trait JsonRpcClient {
async fn request(&self, req: serde_json::Value) -> ApiResult<Vec<u8>>;
}

#[derive(Debug, thiserror::Error)]
pub enum RpcClientError {
#[error("Serde json error: {0}")]
Serde(#[from] serde_json::error::Error),
#[error("Extrinsic Error: {0}")]
Extrinsic(String),
#[error("mpsc send Error: {0}")]
Send(#[from] std::sync::mpsc::SendError<String>),
}
Loading