btcpayserver/BTCPayServer/Extensions/MoneyExtensions.cs
Andrew Camilleri 67da6ee379
Decimal precision and filter valid transaction (#1538)
The liquid transactions list was showing all transactions to the wallet, even when it had nothing to do with the specific crypto code (e.g sending LBTC txs in USDT, LCAD in USDT, etc). This PR fixes that.

It also uses the previously introduced checkout decimal precision fix to the Wallets screen, specifically the balance amount on wallet llist and balance change on transaction list.
2020-05-04 01:04:34 +09:00

63 lines
2.3 KiB
C#

using System;
using System.Globalization;
using System.Linq;
using NBitcoin;
using NBXplorer;
namespace BTCPayServer
{
public static class MoneyExtensions
{
public static decimal GetValue(this IMoney m, BTCPayNetwork network = null)
{
switch (m)
{
case Money money:
return money.ToDecimal(MoneyUnit.BTC);
case MoneyBag mb:
return mb.Select(money => money.GetValue(network)).Sum();
case AssetMoney assetMoney:
if (network is ElementsBTCPayNetwork elementsBTCPayNetwork)
{
return elementsBTCPayNetwork.AssetId == assetMoney.AssetId
? Convert(assetMoney.Quantity, elementsBTCPayNetwork.Divisibility)
: 0;
}
throw new NotSupportedException("IMoney type not supported");
default:
throw new NotSupportedException("IMoney type not supported");
}
}
public static decimal Convert(long sats, int divisibility = 8)
{
var amt = sats.ToString(CultureInfo.InvariantCulture).PadLeft(divisibility, '0');
amt = amt.Length == divisibility ? $"0.{amt}" : amt.Insert(amt.Length - divisibility, ".");
return decimal.Parse(amt, CultureInfo.InvariantCulture);
}
public static string ShowMoney(this IMoney money, BTCPayNetwork network)
{
return money.GetValue(network).ShowMoney(network.Divisibility);
}
public static string ShowMoney(this Money money, int? divisibility)
{
return !divisibility.HasValue
? money.ToString()
: money.ToDecimal(MoneyUnit.BTC).ShowMoney(divisibility.Value);
}
public static string ShowMoney(this decimal d, int divisibility)
{
return d.ToString(GetDecimalFormat(divisibility), CultureInfo.InvariantCulture);
}
private static string GetDecimalFormat(int divisibility)
{
var res = $"0{(divisibility > 0 ? "." : string.Empty)}";
return res.PadRight(divisibility + res.Length, '0');
}
}
}