11using System ;
22using System . Collections . Generic ;
33using System . Text ;
4+ using System . Numerics ;
45using Newtonsoft . Json ;
56
67namespace Thirdweb
@@ -10,6 +11,7 @@ public class Utils
1011
1112 public const string AddressZero = "0x0000000000000000000000000000000000000000" ;
1213 public const string NativeTokenAddress = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" ;
14+ public const double DECIMALS_18 = 1000000000000000000 ;
1315
1416 public static string [ ] ToJsonStringArray ( params object [ ] args )
1517 {
@@ -53,5 +55,33 @@ public static long UnixTimeNowMs()
5355 var timeSpan = ( DateTime . UtcNow - new DateTime ( 1970 , 1 , 1 , 0 , 0 , 0 ) ) ;
5456 return ( long ) timeSpan . TotalMilliseconds ;
5557 }
58+
59+ public static string ToWei ( this string eth )
60+ {
61+ double ethDouble = 0 ;
62+ if ( ! double . TryParse ( eth , out ethDouble ) )
63+ throw new ArgumentException ( "Invalid eth value." ) ;
64+ BigInteger wei = ( BigInteger ) ( ethDouble * DECIMALS_18 ) ;
65+ return wei . ToString ( ) ;
66+ }
67+
68+ public static string ToEth ( this string wei , int decimalsToDisplay = 4 )
69+ {
70+ return FormatERC20 ( wei , decimalsToDisplay ) ;
71+ }
72+
73+ public static string FormatERC20 ( this string wei , int decimalsToDisplay = 4 , int decimals = 18 )
74+ {
75+ BigInteger weiBigInt = 0 ;
76+ if ( ! BigInteger . TryParse ( wei , out weiBigInt ) )
77+ throw new ArgumentException ( "Invalid wei value." ) ;
78+ double eth = ( double ) weiBigInt / Math . Pow ( 10.0 , decimals ) ;
79+ string format = "#,0" ;
80+ if ( decimalsToDisplay > 0 )
81+ format += "." ;
82+ for ( int i = 0 ; i < decimalsToDisplay ; i ++ )
83+ format += "#" ;
84+ return eth . ToString ( format ) ;
85+ }
5686 }
5787}
0 commit comments