forked from btcpayserver/btcpayserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CurrencyPair.cs
99 lines (90 loc) · 3.17 KB
/
CurrencyPair.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using BTCPayServer.Services.Rates;
namespace BTCPayServer.Rating
{
public class CurrencyPair
{
public CurrencyPair(string left, string right)
{
ArgumentNullException.ThrowIfNull(right);
ArgumentNullException.ThrowIfNull(left);
Right = right.ToUpperInvariant();
Left = left.ToUpperInvariant();
}
public string Left { get; private set; }
public string Right { get; private set; }
public static CurrencyPair Parse(string str)
{
if (!TryParse(str, out var result))
throw new FormatException("Invalid currency pair");
return result;
}
public static bool TryParse(string str, out CurrencyPair value)
{
ArgumentNullException.ThrowIfNull(str);
value = null;
str = str.Trim();
if (str.Length > 12)
return false;
var splitted = str.Split(new[] { '_', '-' }, StringSplitOptions.RemoveEmptyEntries);
if (splitted.Length == 2)
{
value = new CurrencyPair(splitted[0], splitted[1]);
return true;
}
else if (splitted.Length == 1)
{
var currencyPair = splitted[0];
if (currencyPair.Length < 6 || currencyPair.Length > 10)
return false;
if (currencyPair.Length == 6)
{
value = new CurrencyPair(currencyPair.Substring(0, 3), currencyPair.Substring(3, 3));
return true;
}
for (int i = 3; i < 5; i++)
{
var potentialCryptoName = currencyPair.Substring(0, i);
var currency = CurrencyNameTable.Instance.GetCurrencyData(potentialCryptoName, false);
if (currency != null)
{
value = new CurrencyPair(currency.Code, currencyPair.Substring(i));
return true;
}
}
}
return false;
}
public override bool Equals(object obj)
{
CurrencyPair item = obj as CurrencyPair;
if (item == null)
return false;
return ToString().Equals(item.ToString(), StringComparison.OrdinalIgnoreCase);
}
public static bool operator ==(CurrencyPair a, CurrencyPair b)
{
if (System.Object.ReferenceEquals(a, b))
return true;
if (((object)a == null) || ((object)b == null))
return false;
return a.ToString() == b.ToString();
}
public static bool operator !=(CurrencyPair a, CurrencyPair b)
{
return !(a == b);
}
public override int GetHashCode()
{
return ToString().GetHashCode(StringComparison.OrdinalIgnoreCase);
}
public override string ToString()
{
return $"{Left}_{Right}";
}
public CurrencyPair Inverse()
{
return new CurrencyPair(Right, Left);
}
}
}