Skip to content

Eth <> Wei + ERC20 Formatting functions for Utils.cs #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Nov 29, 2022
Merged
30 changes: 30 additions & 0 deletions Assets/Thirdweb/Scripts/Utils.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Numerics;
using Newtonsoft.Json;

namespace Thirdweb
Expand All @@ -10,6 +11,7 @@ public class Utils

public const string AddressZero = "0x0000000000000000000000000000000000000000";
public const string NativeTokenAddress = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
public const double DECIMALS_18 = 1000000000000000000;

public static string[] ToJsonStringArray(params object[] args)
{
Expand Down Expand Up @@ -53,5 +55,33 @@ public static long UnixTimeNowMs()
var timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
return (long)timeSpan.TotalMilliseconds;
}

public static string ToWei(this string eth)
{
double ethDouble = 0;
if (!double.TryParse(eth, out ethDouble))
throw new ArgumentException("Invalid eth value.");
BigInteger wei = (BigInteger)(ethDouble * DECIMALS_18);
return wei.ToString();
}

public static string ToEth(this string wei, int decimalsToDisplay = 4)
{
return FormatERC20(wei, decimalsToDisplay);
}

public static string FormatERC20(this string wei, int decimalsToDisplay = 4, int decimals = 18)
{
BigInteger weiBigInt = 0;
if (!BigInteger.TryParse(wei, out weiBigInt))
throw new ArgumentException("Invalid wei value.");
double eth = (double)weiBigInt / Math.Pow(10.0, decimals);
string format = "#,0";
if (decimalsToDisplay > 0)
format += ".";
for (int i = 0; i < decimalsToDisplay; i++)
format += "#";
return eth.ToString(format);
}
}
}