Skip to content

Commit 49effd5

Browse files
authored
CBST-13: deserialize wei (#174)
1 parent 901cd5e commit 49effd5

File tree

2 files changed

+23
-9
lines changed

2 files changed

+23
-9
lines changed

config.example.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ timeout_register_validator_ms = 3000
3737
# OPTIONAL, DEFAULT: false
3838
skip_sigverify = false
3939
# Minimum bid in ETH that will be accepted from `get_header`
40+
# Can be specified as a float or a string for extra precision (e.g. "0.01")
4041
# OPTIONAL, DEFAULT: 0.0
4142
min_bid_eth = 0.0
4243
# List of URLs of relay monitors to send registrations to

crates/common/src/utils.rs

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,7 @@ pub fn utcnow_ns() -> u64 {
4949
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos() as u64
5050
}
5151

52-
// Formatting
5352
pub const WEI_PER_ETH: u64 = 1_000_000_000_000_000_000;
54-
pub fn wei_to_eth(wei: &U256) -> f64 {
55-
wei.to_string().parse::<f64>().unwrap_or_default() / WEI_PER_ETH as f64
56-
}
5753
pub fn eth_to_wei(eth: f64) -> U256 {
5854
U256::from((eth * WEI_PER_ETH as f64).floor())
5955
}
@@ -96,25 +92,42 @@ pub mod as_str {
9692
}
9793

9894
pub mod as_eth_str {
99-
use alloy::primitives::U256;
95+
use alloy::primitives::{
96+
utils::{format_ether, parse_ether},
97+
U256,
98+
};
10099
use serde::Deserialize;
101100

102-
use super::{eth_to_wei, wei_to_eth};
101+
use super::eth_to_wei;
103102

104103
pub fn serialize<S>(data: &U256, serializer: S) -> Result<S::Ok, S::Error>
105104
where
106105
S: serde::Serializer,
107106
{
108-
let s = wei_to_eth(data).to_string();
107+
let s = format_ether(*data);
109108
serializer.serialize_str(&s)
110109
}
111110

112111
pub fn deserialize<'de, D>(deserializer: D) -> Result<U256, D::Error>
113112
where
114113
D: serde::Deserializer<'de>,
115114
{
116-
let s = f64::deserialize(deserializer)?;
117-
Ok(eth_to_wei(s))
115+
#[derive(Deserialize)]
116+
#[serde(untagged)]
117+
enum StringOrF64 {
118+
Str(String),
119+
F64(f64),
120+
}
121+
122+
let value = StringOrF64::deserialize(deserializer)?;
123+
let wei = match value {
124+
StringOrF64::Str(s) => {
125+
parse_ether(&s).map_err(|_| serde::de::Error::custom("invalid eth amount"))?
126+
}
127+
StringOrF64::F64(f) => eth_to_wei(f),
128+
};
129+
130+
Ok(wei)
118131
}
119132
}
120133

0 commit comments

Comments
 (0)