Skip to content

Commit 918653d

Browse files
committed
Fallback to double to avoid overflow
1 parent 456732f commit 918653d

File tree

1 file changed

+30
-9
lines changed

1 file changed

+30
-9
lines changed

Assets/Thirdweb/Core/Scripts/Utils.cs

+30-9
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ public static class Utils
2323
{
2424
public const string AddressZero = "0x0000000000000000000000000000000000000000";
2525
public const string NativeTokenAddress = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
26-
public const decimal DECIMALS_18 = 1000000000000000000;
26+
public const decimal DECIMALS_18 = 1_000_000_000_000_000_000M;
2727

2828
public static string[] ToJsonStringArray(params object[] args)
2929
{
@@ -93,10 +93,22 @@ public static long UnixTimeNowMs()
9393

9494
public static string ToWei(this string eth)
9595
{
96-
if (!decimal.TryParse(eth, NumberStyles.Number, CultureInfo.InvariantCulture, out decimal ethDecimal))
97-
throw new ArgumentException("Invalid eth value.");
98-
BigInteger wei = (BigInteger)(ethDecimal * DECIMALS_18);
99-
return wei.ToString();
96+
try
97+
{
98+
if (!decimal.TryParse(eth, NumberStyles.Number, CultureInfo.InvariantCulture, out decimal ethDecimal))
99+
throw new ArgumentException("Invalid eth value.");
100+
101+
BigInteger wei = (BigInteger)(ethDecimal * DECIMALS_18);
102+
return wei.ToString();
103+
}
104+
catch (OverflowException)
105+
{
106+
if (!double.TryParse(eth, NumberStyles.Number, CultureInfo.InvariantCulture, out double ethDouble))
107+
throw new ArgumentException("Invalid eth value.");
108+
109+
BigInteger wei = (BigInteger)(ethDouble * (double)DECIMALS_18);
110+
return wei.ToString();
111+
}
100112
}
101113

102114
public static string ToEth(this string wei, int decimalsToDisplay = 4, bool addCommas = true)
@@ -109,15 +121,24 @@ public static string FormatERC20(this string wei, int decimalsToDisplay = 4, int
109121
if (!BigInteger.TryParse(wei, out BigInteger weiBigInt))
110122
throw new ArgumentException("Invalid wei value.");
111123

112-
decimal eth = (decimal)weiBigInt / (decimal)Math.Pow(10, decimals);
113124
string format = addCommas ? "#,0" : "#0";
114125

115126
if (decimalsToDisplay > 0)
127+
{
116128
format += ".";
117-
for (int i = 0; i < decimalsToDisplay; i++)
118-
format += "#";
129+
format += new string('#', decimalsToDisplay);
130+
}
119131

120-
return eth.ToString(format);
132+
try
133+
{
134+
decimal eth = (decimal)weiBigInt / (decimal)BigInteger.Pow(10, decimals);
135+
return eth.ToString(format, CultureInfo.InvariantCulture);
136+
}
137+
catch (OverflowException)
138+
{
139+
double eth = (double)weiBigInt / Math.Pow(10, decimals);
140+
return eth.ToString(format, CultureInfo.InvariantCulture);
141+
}
121142
}
122143

123144
public static BigInteger AdjustDecimals(this BigInteger value, int fromDecimals, int toDecimals)

0 commit comments

Comments
 (0)