golem_base_sdk/
utils.rs

1use alloy::primitives::U256;
2use bigdecimal::{BigDecimal, ToPrimitive};
3use std::str::FromStr;
4
5/// Converts an ETH amount to wei as a `U256`.
6/// Accepts a `BigDecimal` ETH value and returns the equivalent amount in wei as a `U256`.
7/// This is useful for preparing values for smart contract calls or transactions.
8/// Returns an error if the value is too large to fit in a `u128`.
9pub fn eth_to_wei(eth: BigDecimal) -> anyhow::Result<U256> {
10    let wei = (eth * BigDecimal::from(1_000_000_000_000_000_000u128))
11        .to_u128()
12        .ok_or_else(|| anyhow::anyhow!("Value too large"))?;
13    Ok(U256::from(wei))
14}
15
16/// Converts a wei amount (`U256`) to ETH as a `BigDecimal`.
17/// Useful for displaying human-readable ETH values from raw wei amounts, such as for UI or logs.
18/// Panics if the `U256` value cannot be parsed as a string (should not happen for valid values).
19pub fn wei_to_eth(wei: U256) -> BigDecimal {
20    BigDecimal::from_str(&wei.to_string()).unwrap()
21        / BigDecimal::from(1_000_000_000_000_000_000u128)
22}