ethereum_mysql/utils.rs
1//! Utilities for parsing and formatting SqlU256 with decimals (e.g. for ERC20/ETH amounts).
2
3use crate::SqlU256;
4use alloy::primitives::{
5 utils::{format_units, parse_units, UnitsError},
6 U256,
7};
8
9/// Parses a decimal string (e.g. "1.23") into a SqlU256, given the number of decimals.
10///
11/// # Examples
12/// ```
13/// use ethereum_mysql::utils::{parse_suint, format_suint};
14/// let v = parse_suint("1.23", 6).unwrap();
15/// assert_eq!(format_suint(v, 6).unwrap(), "1.230000");
16/// ```
17pub fn parse_suint(s: &str, decimals: u8) -> Result<SqlU256, UnitsError> {
18 parse_units(s, decimals).map(|v| {
19 let value: U256 = v.into();
20 SqlU256::from(value)
21 })
22}
23
24/// Formats a SqlU256 as a decimal string with the given number of decimals.
25///
26/// # Examples
27/// ```
28/// use ethereum_mysql::utils::{parse_suint, format_suint};
29/// let v = parse_suint("1.23", 6).unwrap();
30/// assert_eq!(format_suint(v, 6).unwrap(), "1.230000");
31/// ```
32pub fn format_suint(value: SqlU256, decimals: u8) -> Result<String, UnitsError> {
33 format_units(value.into_inner(), decimals)
34}
35
36/// Parses a decimal string as Ether (18 decimals).
37pub fn parse_sether(s: &str) -> Result<SqlU256, UnitsError> {
38 parse_suint(s, 18)
39}
40
41/// Formats a SqlU256 as Ether (18 decimals).
42pub fn format_sether(value: SqlU256) -> Result<String, UnitsError> {
43 format_suint(value, 18)
44}