Skip to content

Commit

Permalink
feat: replace NumberOrHex (#4163)
Browse files Browse the repository at this point in the history
Co-authored-by: Daniel <daniel@chainflip.io>
  • Loading branch information
acdibble and dandanlen authored Oct 26, 2023
1 parent ed0baff commit fb3dfb9
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 23 deletions.
2 changes: 1 addition & 1 deletion api/bin/chainflip-broker-api/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use cf_utilities::{
rpc::NumberOrHex,
task_scope::{task_scope, Scope},
AnyhowRpcError,
};
Expand All @@ -12,7 +13,6 @@ use clap::Parser;
use futures::FutureExt;
use jsonrpsee::{core::async_trait, proc_macros::rpc, server::ServerBuilder};
use serde::{Deserialize, Serialize};
use sp_rpc::number::NumberOrHex;
use std::path::PathBuf;
use tracing::log;

Expand Down
4 changes: 2 additions & 2 deletions api/bin/chainflip-lp-api/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use cf_utilities::{
rpc::NumberOrHex,
task_scope::{task_scope, Scope},
try_parse_number_or_hex, AnyhowRpcError,
};
Expand All @@ -17,18 +18,17 @@ use futures::FutureExt;
use jsonrpsee::{core::async_trait, proc_macros::rpc, server::ServerBuilder};
use pallet_cf_pools::{IncreaseOrDecrease, OrderId, RangeOrderSize};
use rpc_types::{OpenSwapChannels, OrderIdJson, RangeOrderSizeJson};
use sp_rpc::number::NumberOrHex;
use std::{collections::BTreeMap, ops::Range, path::PathBuf};
use tracing::log;

/// Contains RPC interface types that differ from internal types.
pub mod rpc_types {
use super::*;
use anyhow::anyhow;
use cf_utilities::rpc::NumberOrHex;
use chainflip_api::queries::SwapChannelInfo;
use pallet_cf_pools::AssetsMap;
use serde::{Deserialize, Serialize};
use sp_rpc::number::NumberOrHex;

#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct OrderIdJson(NumberOrHex);
Expand Down
17 changes: 10 additions & 7 deletions state-chain/custom-rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -730,13 +730,16 @@ where
self.unwrap_or_best(at),
from,
to,
amount.try_into().and_then(|amount| {
if amount == 0 {
Err(anyhow::anyhow!("Swap input amount cannot be zero."))
} else {
Ok(amount)
}
})?,
amount
.try_into()
.and_then(|amount| {
if amount == 0 {
Err("Swap input amount cannot be zero.")
} else {
Ok(amount)
}
})
.map_err(|str| anyhow::anyhow!(str))?,
)
.map_err(to_rpc_error)
.and_then(|r| {
Expand Down
4 changes: 2 additions & 2 deletions utilities/src/with_std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use futures::{stream, Stream};
use jsonrpsee::types::{error::CALL_EXECUTION_FAILED_CODE, ErrorObjectOwned};
#[doc(hidden)]
pub use lazy_format::lazy_format as internal_lazy_format;
use sp_rpc::number::NumberOrHex;
use rpc::NumberOrHex;

pub mod future_map;
pub mod loop_select;
Expand Down Expand Up @@ -54,7 +54,7 @@ pub fn clean_hex_address<A: TryFrom<Vec<u8>>>(address_str: &str) -> Result<A, an

pub fn try_parse_number_or_hex(amount: NumberOrHex) -> anyhow::Result<u128> {
u128::try_from(amount).map_err(|_| {
anyhow!("Error parsing amount. Please use a valid number or hex string as input.")
anyhow!("Error parsing amount to u128. Please use a valid number or hex string as input.")
})
}

Expand Down
41 changes: 31 additions & 10 deletions utilities/src/with_std/rpc.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use anyhow::anyhow;
use serde::{Deserialize, Serialize};
use sp_core::U256;

#[derive(Debug, PartialEq, Eq, Deserialize)]
#[derive(Debug, PartialEq, Eq, Deserialize, Copy, Clone)]
#[serde(untagged)]
pub enum NumberOrHex {
Number(u64),
Expand Down Expand Up @@ -51,15 +50,24 @@ macro_rules! impl_safe_hex {

impl_safe_hex!(u128, U256);

impl TryInto<u128> for NumberOrHex {
type Error = anyhow::Error;
impl TryFrom<NumberOrHex> for u128 {
type Error = &'static str;

fn try_into(self) -> Result<u128, Self::Error> {
match self {
Self::Number(n) => Ok(n.into()),
Self::Hex(n) => n.try_into().map_err(|_| {
anyhow!("Error parsing amount. Please use a valid number or hex string as input.")
}),
fn try_from(value: NumberOrHex) -> Result<Self, Self::Error> {
match value {
NumberOrHex::Number(n) => Ok(n.into()),
NumberOrHex::Hex(n) => u128::try_from(n),
}
}
}

impl TryFrom<NumberOrHex> for u64 {
type Error = &'static str;

fn try_from(value: NumberOrHex) -> Result<Self, Self::Error> {
match value {
NumberOrHex::Number(n) => Ok(n),
NumberOrHex::Hex(n) => u64::try_from(n),
}
}
}
Expand Down Expand Up @@ -88,4 +96,17 @@ mod test {
assert_deser(r#"0"#, NumberOrHex::Number(0));
assert_deser(r#"1000000000000"#, NumberOrHex::Number(1000000000000));
}

#[test]
fn test_conversions() {
assert_eq!(u128::try_from(NumberOrHex::Hex(u128::MAX.into())).unwrap(), u128::MAX);
assert!(u128::try_from(NumberOrHex::Hex(U256::MAX / 2)).is_err());

assert_eq!(u64::try_from(NumberOrHex::Hex(u64::MAX.into())).unwrap(), u64::MAX);
assert_eq!(u64::try_from(NumberOrHex::Number(u64::MAX)).unwrap(), u64::MAX);
assert!(u64::try_from(NumberOrHex::Hex((u128::MAX / 2).into())).is_err());

assert_eq!(u128::try_from(NumberOrHex::Number(0)).unwrap(), 0);
assert_eq!(u128::try_from(NumberOrHex::Hex(U256::zero())).unwrap(), 0);
}
}
2 changes: 1 addition & 1 deletion utilities/src/with_std/serde_helpers/number_or_hex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
//! bar: u128,
//! }
/// ```
use crate::rpc::NumberOrHex;
use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
use sp_rpc::number::NumberOrHex;

pub fn serialize<S, T>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down

0 comments on commit fb3dfb9

Please sign in to comment.