Skip to content

Commit 4072136

Browse files
authored
Eth <> Wei + ERC20 Formatting functions for Utils.cs (#10)
1 parent d1c7291 commit 4072136

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Assets/Thirdweb/Scripts/Utils.cs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System;
22
using System.Collections.Generic;
33
using System.Text;
4+
using System.Numerics;
45
using Newtonsoft.Json;
56

67
namespace 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

Comments
 (0)