Skip to content

Commit

Permalink
deserialize eth
Browse files Browse the repository at this point in the history
  • Loading branch information
ltitanb committed Nov 19, 2024
1 parent 5c9a122 commit 288e41c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
1 change: 1 addition & 0 deletions config.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ timeout_register_validator_ms = 3000
# OPTIONAL, DEFAULT: false
skip_sigverify = false
# Minimum bid in ETH that will be accepted from `get_header`
# Can be specified as a float or a string for extra precision (e.g. "0.01")
# OPTIONAL, DEFAULT: 0.0
min_bid_eth = 0.0
# List of URLs of relay monitors to send registrations to
Expand Down
31 changes: 22 additions & 9 deletions crates/common/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,7 @@ pub fn utcnow_ns() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos() as u64
}

// Formatting
const WEI_PER_ETH: u64 = 1_000_000_000_000_000_000;
pub fn wei_to_eth(wei: &U256) -> f64 {
wei.to_string().parse::<f64>().unwrap_or_default() / WEI_PER_ETH as f64
}
pub fn eth_to_wei(eth: f64) -> U256 {
U256::from((eth * WEI_PER_ETH as f64).floor())
}
Expand Down Expand Up @@ -96,25 +92,42 @@ pub mod as_str {
}

pub mod as_eth_str {
use alloy::primitives::U256;
use alloy::primitives::{
utils::{format_ether, parse_ether},
U256,
};
use serde::Deserialize;

use super::{eth_to_wei, wei_to_eth};
use super::eth_to_wei;

pub fn serialize<S>(data: &U256, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let s = wei_to_eth(data).to_string();
let s = format_ether(*data);
serializer.serialize_str(&s)
}

pub fn deserialize<'de, D>(deserializer: D) -> Result<U256, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = f64::deserialize(deserializer)?;
Ok(eth_to_wei(s))
#[derive(Deserialize)]
#[serde(untagged)]
enum StringOrF64 {
Str(String),
F64(f64),
}

let value = StringOrF64::deserialize(deserializer)?;
let wei = match value {
StringOrF64::Str(s) => {
parse_ether(&s).map_err(|_| serde::de::Error::custom("invalid eth amount"))?
}
StringOrF64::F64(f) => eth_to_wei(f),
};

Ok(wei)
}
}

Expand Down

0 comments on commit 288e41c

Please sign in to comment.