Skip to content
Merged
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
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
pub 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