Skip to content

Commit

Permalink
Extract serde part of xpallet-support into xp-rpc (paritytech#325)
Browse files Browse the repository at this point in the history
Signed-off-by: koushiro <koushiro.cqx@gmail.com>
  • Loading branch information
koushiro authored Nov 4, 2020
1 parent 5566a13 commit e8db23f
Show file tree
Hide file tree
Showing 28 changed files with 192 additions and 226 deletions.
18 changes: 8 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 2 additions & 5 deletions primitives/genesis-builder/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,13 @@ serde = { version = "1.0", features = ["derive"], optional = true }

# ChainX primitives
chainx-primitives = { path = "../../primitives", default-features = false }

# ChainX pallets
xpallet-support = { path = "../../xpallets/support", default-features = false }
xp-rpc = { path = "../../primitives/rpc", optional = true }

[features]
default = ["std"]
std = [
"serde",
# ChainX primitives
"chainx-primitives/std",
# ChainX pallets
"xpallet-support/std",
"xp-rpc",
]
10 changes: 5 additions & 5 deletions primitives/genesis-builder/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,19 @@ mod genesis_params {
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct ValidatorInfo<AccountId, Balance> {
pub who: AccountId,
#[serde(with = "xpallet_support::serde_text")]
#[serde(with = "xp_rpc::serde_text")]
pub referral_id: Vec<u8>,
pub self_bonded: Balance,
pub total_nomination: Balance,
#[serde(with = "xpallet_support::serde_num_str")]
#[serde(with = "xp_rpc::serde_num_str")]
pub total_weight: u128,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Nomination<AccountId, Balance> {
pub nominee: AccountId,
pub nomination: Balance,
#[serde(with = "xpallet_support::serde_num_str")]
#[serde(with = "xp_rpc::serde_num_str")]
pub weight: u128,
}

Expand All @@ -73,14 +73,14 @@ mod genesis_params {
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct XBtcInfo {
pub balance: Balance,
#[serde(with = "xpallet_support::serde_num_str")]
#[serde(with = "xp_rpc::serde_num_str")]
pub weight: u128,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct XBtcMiner<AccountId> {
pub who: AccountId,
#[serde(with = "xpallet_support::serde_num_str")]
#[serde(with = "xp_rpc::serde_num_str")]
pub weight: u128,
}

Expand Down
5 changes: 5 additions & 0 deletions primitives/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,9 @@ authors = ["The ChainX Authors"]
edition = "2018"

[dependencies]
hex = "0.4"
jsonrpc-core = "15.0.0"
serde = { version = "1.0", features = ["derive"] }

[dev-dependencies]
serde_json = "1.0"
151 changes: 150 additions & 1 deletion primitives/rpc/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
// Copyright 2019-2020 ChainX Project Authors. Licensed under GPL-3.0.

use std::fmt::Debug;
use std::{
fmt::{Debug, Display},
result::Result as StdResult,
str::FromStr,
};

pub use jsonrpc_core::{Error, ErrorCode, Result};
use serde::{de, ser, Deserialize, Serialize};

/// The call to runtime failed.
pub const RUNTIME_ERROR: i64 = 1;
Expand Down Expand Up @@ -60,3 +65,147 @@ pub fn hex_decode_error_into_rpc_err(err: impl Debug) -> Error {
data: Some(format!("{:?}", err).into()),
}
}

/// Balance type when interacting with RPC.
pub type RpcBalance<Balance> = RpcU128<Balance>;

/// Price type of order when interacting with RPC.
pub type RpcPrice<Price> = RpcU128<Price>;

/// Weight type of mining when interacting with RPC.
pub type RpcMiningWeight<Weight> = RpcU128<Weight>;

/// Weight type of staking when interacting with RPC.
pub type RpcVoteWeight<Weight> = RpcU128<Weight>;

/// A helper struct for handling u128 serialization/deserialization of RPC.
/// See https://github.com/polkadot-js/api/issues/2464 for details (shit!).
#[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)]
pub struct RpcU128<T: Display + FromStr>(#[serde(with = "self::serde_num_str")] T);

impl<T: Display + FromStr> From<T> for RpcU128<T> {
fn from(value: T) -> Self {
RpcU128(value)
}
}

/// Number string serialization/deserialization
pub mod serde_num_str {
use super::*;

/// A serializer that encodes the number as a string
pub fn serialize<S, T>(value: &T, serializer: S) -> StdResult<S::Ok, S::Error>
where
S: ser::Serializer,
T: Display,
{
serializer.serialize_str(&value.to_string())
}

/// A deserializer that decodes a string to the number.
pub fn deserialize<'de, D, T>(deserializer: D) -> StdResult<T, D::Error>
where
D: de::Deserializer<'de>,
T: FromStr,
{
let data = String::deserialize(deserializer)?;
data.parse::<T>()
.map_err(|_| de::Error::custom("Parse from string failed"))
}
}

/// Hex serialization/deserialization
pub mod serde_hex {
use super::*;

/// A serializer that encodes the bytes as a hex-string
pub fn serialize<T, S>(value: &T, serializer: S) -> StdResult<S::Ok, S::Error>
where
S: ser::Serializer,
T: AsRef<[u8]>,
{
serializer.serialize_str(&format!("0x{}", hex::encode(value)))
}

/// A deserializer that decodes the hex-string to bytes (Vec<u8>)
pub fn deserialize<'de, D>(deserializer: D) -> StdResult<Vec<u8>, D::Error>
where
D: de::Deserializer<'de>,
{
let data = String::deserialize(deserializer)?;
let data = if data.starts_with("0x") {
&data[2..]
} else {
&data[..]
};
let hex = hex::decode(data).map_err(de::Error::custom)?;
Ok(hex)
}
}

/// Text serialization/deserialization
pub mod serde_text {
use super::*;

/// A serializer that encodes the bytes as a string
pub fn serialize<T, S>(value: &T, serializer: S) -> StdResult<S::Ok, S::Error>
where
S: ser::Serializer,
T: AsRef<[u8]>,
{
let output = String::from_utf8_lossy(value.as_ref());
serializer.serialize_str(&output)
}

/// A deserializer that decodes the string to the bytes (Vec<u8>)
pub fn deserialize<'de, D>(deserializer: D) -> StdResult<Vec<u8>, D::Error>
where
D: de::Deserializer<'de>,
{
let data = String::deserialize(deserializer)?;
Ok(data.into_bytes())
}
}

#[cfg(test)]
mod tests {
use serde::{Deserialize, Serialize};

#[test]
fn test_serde_num_str_attr() {
use super::RpcU128;

let test = RpcU128(u128::max_value());
let ser = serde_json::to_string(&test).unwrap();
assert_eq!(ser, "\"340282366920938463463374607431768211455\"");
let de = serde_json::from_str::<RpcU128<u128>>(&ser).unwrap();
assert_eq!(de, test);
}

#[test]
fn test_serde_hex_attr() {
#[derive(PartialEq, Debug, Serialize, Deserialize)]
struct HexTest(#[serde(with = "super::serde_hex")] Vec<u8>);

let test = HexTest(b"0123456789".to_vec());
let ser = serde_json::to_string(&test).unwrap();
assert_eq!(ser, "\"0x30313233343536373839\"");
let de = serde_json::from_str::<HexTest>(&ser).unwrap();
assert_eq!(de, test);
// without 0x
let de = serde_json::from_str::<HexTest>("\"30313233343536373839\"").unwrap();
assert_eq!(de, test);
}

#[test]
fn test_serde_text_attr() {
#[derive(PartialEq, Debug, Serialize, Deserialize)]
struct TextTest(#[serde(with = "super::serde_text")] Vec<u8>);

let test = TextTest(b"0123456789".to_vec());
let ser = serde_json::to_string(&test).unwrap();
assert_eq!(ser, "\"0123456789\"");
let de = serde_json::from_str::<TextTest>(&ser).unwrap();
assert_eq!(de, test);
}
}
2 changes: 2 additions & 0 deletions xpallets/assets-registrar/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ chainx-primitives = { path = "../../primitives", default-features = false }
xp-assets-registrar = { path = "../../primitives/assets-registrar", default-features = false }
xp-logging = { path = "../../primitives/logging", default-features = false }
xp-protocol = { path = "../../primitives/protocol", default-features = false }
xp-rpc = { path = "../../primitives/rpc", optional = true }
xp-runtime = { path = "../../primitives/runtime", default-features = false }

# ChainX pallets
Expand All @@ -48,6 +49,7 @@ std = [
"xp-assets-registrar/std",
"xp-logging/std",
"xp-protocol/std",
"xp-rpc",
"xp-runtime/std",
# ChainX pallets
"xpallet-support/std",
Expand Down
6 changes: 3 additions & 3 deletions xpallets/assets-registrar/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,13 @@ impl Default for Chain {
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
pub struct AssetInfo {
#[cfg_attr(feature = "std", serde(with = "xpallet_support::serde_text"))]
#[cfg_attr(feature = "std", serde(with = "xp_rpc::serde_text"))]
token: Token,
#[cfg_attr(feature = "std", serde(with = "xpallet_support::serde_text"))]
#[cfg_attr(feature = "std", serde(with = "xp_rpc::serde_text"))]
token_name: Token,
chain: Chain,
decimals: Decimals,
#[cfg_attr(feature = "std", serde(with = "xpallet_support::serde_text"))]
#[cfg_attr(feature = "std", serde(with = "xp_rpc::serde_text"))]
desc: Desc,
}

Expand Down
3 changes: 0 additions & 3 deletions xpallets/assets/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,5 @@ sp-runtime = "2.0.0"
# ChainX primitives
xp-rpc = { path = "../../../primitives/rpc" }

# ChainX pallets
xpallet-support = { path = "../../support" }

# ChainX pallets api
xpallet-assets-rpc-runtime-api = { path = "./runtime-api" }
4 changes: 1 addition & 3 deletions xpallets/assets/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@ use sp_runtime::{
traits::{Block as BlockT, Zero},
};

use xp_rpc::{runtime_error_into_rpc_err, Result};

use xpallet_support::RpcBalance;
use xp_rpc::{runtime_error_into_rpc_err, Result, RpcBalance};

use xpallet_assets_rpc_runtime_api::{
AssetId, AssetType, TotalAssetInfo, XAssetsApi as XAssetsRuntimeApi,
Expand Down
3 changes: 0 additions & 3 deletions xpallets/dex/spot/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,5 @@ sp-runtime = "2.0.0"
# ChainX primitives
xp-rpc = { path = "../../../../primitives/rpc" }

# ChainX pallets
xpallet-support = { path = "../../../support" }

# ChainX pallets api
xpallet-dex-spot-rpc-runtime-api = { path = "./runtime-api" }
Loading

0 comments on commit e8db23f

Please sign in to comment.