1
1
using System ;
2
2
using System . Collections . Generic ;
3
3
using System . Text ;
4
+ using System . Numerics ;
4
5
using Newtonsoft . Json ;
5
6
6
7
namespace Thirdweb
@@ -10,6 +11,7 @@ public class Utils
10
11
11
12
public const string AddressZero = "0x0000000000000000000000000000000000000000" ;
12
13
public const string NativeTokenAddress = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" ;
14
+ public const double DECIMALS_18 = 1000000000000000000 ;
13
15
14
16
public static string [ ] ToJsonStringArray ( params object [ ] args )
15
17
{
@@ -53,5 +55,33 @@ public static long UnixTimeNowMs()
53
55
var timeSpan = ( DateTime . UtcNow - new DateTime ( 1970 , 1 , 1 , 0 , 0 , 0 ) ) ;
54
56
return ( long ) timeSpan . TotalMilliseconds ;
55
57
}
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
+ }
56
86
}
57
87
}
0 commit comments