kabu_evm_utils/
nweth.rs

1use alloy::primitives::{Address, U256};
2use kabu_defi_address_book::TokenAddressEth;
3use std::ops::{Add, Mul};
4
5pub struct NWETH {}
6
7impl NWETH {
8    const NWETH_EXP_U128: u128 = 10u128.pow(18);
9
10    const NWETH_EXP: f64 = 10u64.pow(18) as f64;
11    const GWEI_EXP_U128: u128 = 10u128.pow(9);
12    const GWEI_EXP: f64 = 10u64.pow(9) as f64;
13    const WEI_EXP_U128: u128 = 10u128.pow(18);
14    const WEI_EXP: f64 = 10u64.pow(18) as f64;
15
16    pub const ADDRESS: Address = TokenAddressEth::WETH;
17    pub const NATIVE_ADDRESS: Address = Address::ZERO;
18
19    #[inline]
20    pub fn to_float(value: U256) -> f64 {
21        let divider = U256::from(Self::NWETH_EXP);
22
23        let ret = value.div_rem(divider);
24
25        let div = u64::try_from(ret.0);
26        let rem = u64::try_from(ret.1);
27
28        if div.is_err() || rem.is_err() {
29            0f64
30        } else {
31            div.unwrap_or_default() as f64 + ((rem.unwrap_or_default() as f64) / Self::NWETH_EXP)
32        }
33    }
34
35    #[inline]
36    pub fn to_float_gwei(value: u128) -> f64 {
37        let div = value / Self::GWEI_EXP_U128;
38        let rem = value % Self::GWEI_EXP_U128;
39
40        div as f64 + ((rem as f64) / Self::GWEI_EXP)
41    }
42
43    #[inline]
44    pub fn to_float_wei(value: u128) -> f64 {
45        let div = value / Self::WEI_EXP_U128;
46        let rem = value % Self::WEI_EXP_U128;
47
48        div as f64 + ((rem as f64) / Self::WEI_EXP)
49    }
50
51    #[inline]
52    pub fn from_float(value: f64) -> U256 {
53        let multiplier = U256::from(value as i64);
54        let modulus = U256::from(((value - value.round()) * 10_i64.pow(18) as f64) as u64);
55        multiplier.mul(U256::from(10).pow(U256::from(18))).add(modulus)
56    }
57
58    #[inline]
59    pub fn get_exp() -> U256 {
60        U256::from(Self::NWETH_EXP_U128)
61    }
62
63    #[inline]
64    pub fn address() -> Address {
65        Self::ADDRESS
66    }
67}