@rabbitio/ui-kit 1.0.0-beta.10 → 1.0.0-beta.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1,11 +1,12 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('bignumber.js')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'react', 'bignumber.js'], factory) :
4
- (global = global || self, factory(global.uiKit = {}, global.react, global.bignumber_js));
5
- })(this, (function (exports, React, bignumber_js) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('bignumber.js'), require('axios')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'react', 'bignumber.js', 'axios'], factory) :
4
+ (global = global || self, factory(global.uiKit = {}, global.react, global.bignumber_js, global.axios));
5
+ })(this, (function (exports, React, bignumber_js, axios) {
6
6
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
7
7
 
8
8
  var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
9
+ var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
9
10
 
10
11
  function createCommonjsModule(fn) {
11
12
  var module = { exports: {} };
@@ -1443,8 +1444,8 @@
1443
1444
 
1444
1445
  var AssetIcon = function AssetIcon(_ref) {
1445
1446
  var assetIconSrc = _ref.assetIconSrc,
1446
- _ref$assetIconProtoco = _ref.assetIconProtocolScr,
1447
- assetIconProtocolScr = _ref$assetIconProtoco === void 0 ? null : _ref$assetIconProtoco,
1447
+ _ref$assetIconProtoco = _ref.assetIconProtocolSrc,
1448
+ assetIconProtocolSrc = _ref$assetIconProtoco === void 0 ? null : _ref$assetIconProtoco,
1448
1449
  _ref$fallbackSrc = _ref.fallbackSrc,
1449
1450
  fallbackSrc = _ref$fallbackSrc === void 0 ? null : _ref$fallbackSrc,
1450
1451
  _ref$small = _ref.small,
@@ -1460,8 +1461,8 @@
1460
1461
  className: s["asset-icon-primary"] + (small ? " " + s["small"] : ""),
1461
1462
  alt: " ",
1462
1463
  onError: handleFailedLoad
1463
- }), assetIconProtocolScr ? /*#__PURE__*/React__default["default"].createElement("img", {
1464
- src: assetIconProtocolScr,
1464
+ }), assetIconProtocolSrc ? /*#__PURE__*/React__default["default"].createElement("img", {
1465
+ src: assetIconProtocolSrc,
1465
1466
  className: s["asset-icon-secondary"] + (small ? " " + s["small"] : ""),
1466
1467
  alt: " ",
1467
1468
  onError: handleFailedLoad
@@ -1469,12 +1470,12 @@
1469
1470
  };
1470
1471
  AssetIcon.propTypes = {
1471
1472
  assetIconSrc: PropTypes.string.isRequired,
1472
- assetIconProtocolScr: PropTypes.string,
1473
+ assetIconProtocolSrc: PropTypes.string,
1473
1474
  fallbackSrc: PropTypes.string,
1474
1475
  small: PropTypes.bool
1475
1476
  };
1476
1477
  AssetIcon.defaultProps = {
1477
- assetIconProtocolScr: null,
1478
+ assetIconProtocolSrc: null,
1478
1479
  fallbackSrc: null,
1479
1480
  small: false
1480
1481
  };
@@ -1574,6 +1575,49 @@
1574
1575
  };
1575
1576
  return _extends.apply(this, arguments);
1576
1577
  }
1578
+ function _inheritsLoose(subClass, superClass) {
1579
+ subClass.prototype = Object.create(superClass.prototype);
1580
+ subClass.prototype.constructor = subClass;
1581
+ _setPrototypeOf(subClass, superClass);
1582
+ }
1583
+ function _setPrototypeOf(o, p) {
1584
+ _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
1585
+ o.__proto__ = p;
1586
+ return o;
1587
+ };
1588
+ return _setPrototypeOf(o, p);
1589
+ }
1590
+ function _unsupportedIterableToArray(o, minLen) {
1591
+ if (!o) return;
1592
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
1593
+ var n = Object.prototype.toString.call(o).slice(8, -1);
1594
+ if (n === "Object" && o.constructor) n = o.constructor.name;
1595
+ if (n === "Map" || n === "Set") return Array.from(o);
1596
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
1597
+ }
1598
+ function _arrayLikeToArray(arr, len) {
1599
+ if (len == null || len > arr.length) len = arr.length;
1600
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
1601
+ return arr2;
1602
+ }
1603
+ function _createForOfIteratorHelperLoose(o, allowArrayLike) {
1604
+ var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
1605
+ if (it) return (it = it.call(o)).next.bind(it);
1606
+ if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
1607
+ if (it) o = it;
1608
+ var i = 0;
1609
+ return function () {
1610
+ if (i >= o.length) return {
1611
+ done: true
1612
+ };
1613
+ return {
1614
+ done: false,
1615
+ value: o[i++]
1616
+ };
1617
+ };
1618
+ }
1619
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1620
+ }
1577
1621
 
1578
1622
  // TODO: [dev] return addCommasToAmountString internal method to encapsulate commas adding
1579
1623
 
@@ -1893,13 +1937,1445 @@
1893
1937
  periods: true // Whether we add periods ("..") as suffix for trimmed numbers
1894
1938
  };
1895
1939
 
1940
+ var Blockchain =
1941
+ /**
1942
+ * @param name {string} latin printable name of blockchain
1943
+ * @param supportedProtocols {Protocol[]}
1944
+ */
1945
+ function Blockchain(name, supportedProtocols) {
1946
+ if (supportedProtocols === void 0) {
1947
+ supportedProtocols = [];
1948
+ }
1949
+ this.name = name;
1950
+ this.supportedProtocols = supportedProtocols;
1951
+ };
1952
+
1953
+ var Protocol = function Protocol(protocolName) {
1954
+ this.protocol = protocolName;
1955
+ };
1956
+
1957
+ /**
1958
+ * The model for cryptocurrency coins.
1959
+ *
1960
+ * WARNING: this class should not be instantiated directly. Use only predefined singleton Coin (or descendants) instances.
1961
+ */
1962
+ var Coin = /*#__PURE__*/function () {
1963
+ /**
1964
+ * Creates new coin
1965
+ *
1966
+ * @param latinName {string} the coin name in latin symbols like "Bitcoin"
1967
+ * @param ticker {string} the coin symbol/ticker/code like 'BTC'. Always upper case. A unique coin identifier
1968
+ * @param tickerPrintable {string} ticker but in printable format. Useful for tokens based on external blockchains
1969
+ * like ERC20 or TRC20. It is not friendly to display USDTERC20 or BUSDTRC20 - more neat options are just
1970
+ * USDT and BUSD. Note that you should always care about user's understanding of what coin he/she is working
1971
+ * with as printable ticker for USDTERC20 and USDTTRC20 are the same.
1972
+ * @param digitsCountAfterComma {number} count of digits after the comma. E.g. 8 for bitcoin
1973
+ * @param maxValue {number|null} max possible value for cryptocurrency. Null means that the currency has no max possible value
1974
+ * @param atomName {string} name of the coin's atomic value. Like 'satoshi' for bitcoin
1975
+ * @param mainnet {Network} main network for this coin
1976
+ * @param testnet {Network} test network for this coin
1977
+ * @param minConfirmations {number} min confirmations count to treat the coin's transaction confirmed
1978
+ * @param payableEntityStringForFeeRate {string|null} the payable fee entity like byte for bitcoin or gas for ether if present
1979
+ * @param feeOptionsTimeStringsSortedDesc {string[]} array of 4 strings for fee options when sending coins. Should be sorted from the highest time to the smallest
1980
+ * @param feeRatesExpirationTimeMs {number} number of milliseconds to treat the fee rates as expired
1981
+ * @param blockchain {Blockchain} blockchain object
1982
+ * @param [protocol] {Protocol|null} token/coin protocol if relevant
1983
+ * @param [tokenAddress] {string|null} address of contract of this token (if the coin is token)
1984
+ * @param [doesUseLowerCaseAddresses] {boolean} flag to clarify whether we can use lower case addresses to ensure more robust comparisons
1985
+ * @param [doesUseOutputs=false] {boolean} true if this coin uses inputs/outputs concept and false if it uses just balances
1986
+ */
1987
+ function Coin(latinName, ticker, tickerPrintable, digitsCountAfterComma, maxValue, atomName, mainnet, testnet, minConfirmations, payableEntityStringForFeeRate, feeOptionsTimeStringsSortedDesc, feeRatesExpirationTimeMs, blockchain, protocol, tokenAddress, doesUseLowerCaseAddresses, doesUseOutputs) {
1988
+ if (protocol === void 0) {
1989
+ protocol = null;
1990
+ }
1991
+ if (tokenAddress === void 0) {
1992
+ tokenAddress = null;
1993
+ }
1994
+ if (doesUseLowerCaseAddresses === void 0) {
1995
+ doesUseLowerCaseAddresses = true;
1996
+ }
1997
+ if (doesUseOutputs === void 0) {
1998
+ doesUseOutputs = false;
1999
+ }
2000
+ this.latinName = latinName;
2001
+ this.ticker = ticker;
2002
+ this.tickerPrintable = tickerPrintable;
2003
+ this.digits = digitsCountAfterComma;
2004
+ this.maxValue = maxValue;
2005
+ this.atomName = atomName;
2006
+ this.mainnet = mainnet;
2007
+ this.testnet = testnet;
2008
+ this.minConfirmations = minConfirmations;
2009
+ this.payableEntityStringForFeeRate = payableEntityStringForFeeRate;
2010
+ this.feeOptionsTimeStringsSortedDesc = feeOptionsTimeStringsSortedDesc;
2011
+ this.feeRatesExpirationTimeMs = feeRatesExpirationTimeMs;
2012
+ this.protocol = protocol;
2013
+ this.blockchain = blockchain;
2014
+ // TODO: [bug, critical] use testnet property for testnet contract address as it blocks the app work in testnets
2015
+ this.tokenAddress = tokenAddress;
2016
+ this.feeCoin = this;
2017
+ this._significantDigits = 8;
2018
+ this.doesUseLowerCaseAddresses = doesUseLowerCaseAddresses;
2019
+ this.doesUseOutputs = doesUseOutputs;
2020
+ }
2021
+
2022
+ /**
2023
+ * Sets fee coin
2024
+ *
2025
+ * @param feeCoin {Coin} some tokens use another coin to charge transaction fee as they work on top of some external
2026
+ * blockchain. So pass here the coin the token uses for fee charging. Like for ERC20 token the fee coin is ETH.
2027
+ * By default, the creating coin will be set as a value for this field.
2028
+ */
2029
+ var _proto = Coin.prototype;
2030
+ _proto.setFeeCoin = function setFeeCoin(feeCoin) {
2031
+ this.feeCoin = feeCoin;
2032
+ }
2033
+
2034
+ /**
2035
+ * Checks whether this coin uses another coin (blockchain) to charge fee for transactions (means works on base of
2036
+ * some external blockchain).
2037
+ *
2038
+ * @return {boolean} true if this coin uses external blockchain to perform transactions and charge fee
2039
+ */;
2040
+ _proto.doesUseDifferentCoinFee = function doesUseDifferentCoinFee() {
2041
+ return this.feeCoin !== this;
2042
+ }
2043
+
2044
+ /**
2045
+ * Converts the given atoms string/number to string representing the same amount in coin itself - floating point number
2046
+ *
2047
+ * @param atoms {string} atoms positive integer amount
2048
+ * @return {string} coin amount floating point number as a string
2049
+ */;
2050
+ _proto.atomsToCoinAmount = function atomsToCoinAmount(atoms) {
2051
+ throw new Error("Not implemented in base Coin");
2052
+ }
2053
+
2054
+ /**
2055
+ * Converts the given coins amount string/number to string representing the same amount in coin atoms - integer number
2056
+ *
2057
+ * @param coinsAmount {string} coins positive floating point amount
2058
+ * @return {string} coin atoms amount integer number as a string
2059
+ */;
2060
+ _proto.coinAmountToAtoms = function coinAmountToAtoms(coinsAmount) {
2061
+ throw new Error("Not implemented in base Coin");
2062
+ }
2063
+
2064
+ /**
2065
+ * Composes URL to view the tx with given id in the external blockchain explorer
2066
+ *
2067
+ * @param txId {string} id of transaction
2068
+ * @return {string} URL string
2069
+ */;
2070
+ _proto.composeUrlToTransactionExplorer = function composeUrlToTransactionExplorer(txId) {
2071
+ throw new Error("Not implemented in base Coin");
2072
+ }
2073
+
2074
+ /**
2075
+ * Most of the cryptocurrencies has specific fee rate or fee price metric. This value usually has specific measure
2076
+ * like satoshi/byte or gWei/gas. This function adds the described denomination string to the given amount
2077
+ * as a suffix and returns the result string ready to be show to a user.
2078
+ *
2079
+ * @param coinAtomsString {string} coin atoms positive integer amount
2080
+ * @return {string} string of coin amount and fee rate units
2081
+ */;
2082
+ _proto.coinAtomsFeeRateToCommonlyUsedAmountFormatWithDenominationString = function coinAtomsFeeRateToCommonlyUsedAmountFormatWithDenominationString(coinAtomsString) {
2083
+ throw new Error("Not implemented in base Coin");
2084
+ }
2085
+
2086
+ /**
2087
+ * Check whether this coin support transaction prioritisation during the sending process.
2088
+ *
2089
+ * @return {boolean} true if support transaction prioritisation and false otherwise
2090
+ */;
2091
+ _proto.doesSupportTransactionPrioritisation = function doesSupportTransactionPrioritisation() {
2092
+ return Array.isArray(this.feeOptionsTimeStringsSortedDesc);
2093
+ };
2094
+ _proto.tickerAndProtocol = function tickerAndProtocol() {
2095
+ try {
2096
+ var _ref;
2097
+ return "" + this.tickerPrintable + (this.protocol ? (_ref = " " + this.protocol.protocol) != null ? _ref : "" : "");
2098
+ } catch (e) {
2099
+ improveAndRethrow(e, "tickerAndProtocol");
2100
+ }
2101
+ };
2102
+ return Coin;
2103
+ }();
2104
+
2105
+ var LogsStorage = /*#__PURE__*/function () {
2106
+ function LogsStorage() {}
2107
+ LogsStorage.saveLog = function saveLog(log) {
2108
+ this._inMemoryStorage.push(log);
2109
+ };
2110
+ LogsStorage.getInMemoryLogs = function getInMemoryLogs() {
2111
+ return this._inMemoryStorage;
2112
+ };
2113
+ LogsStorage.getAllLogs = function getAllLogs() {
2114
+ var storedLogs = "";
2115
+ if (typeof window !== "undefined") {
2116
+ storedLogs = localStorage.getItem(this._logsStorageId);
2117
+ }
2118
+ return storedLogs + "\n" + this._inMemoryStorage.join("\n");
2119
+ }
2120
+
2121
+ /**
2122
+ * @param logger {Logger}
2123
+ */;
2124
+ LogsStorage.saveToTheDisk = function saveToTheDisk(logger) {
2125
+ try {
2126
+ var MAX_LOCAL_STORAGE_VOLUME_BYTES = 5 * 1024 * 1024;
2127
+ var MAX_LOGS_STORAGE_BYTES = MAX_LOCAL_STORAGE_VOLUME_BYTES * 0.65;
2128
+ if (typeof window !== "undefined") {
2129
+ var existingLogs = localStorage.getItem(this._logsStorageId);
2130
+ var logsString = existingLogs + "\n" + this._inMemoryStorage.join("\n");
2131
+ var lettersCountToRemove = logsString.length - Math.round(MAX_LOGS_STORAGE_BYTES / 2);
2132
+ if (lettersCountToRemove > 0) {
2133
+ localStorage.setItem(this._logsStorageId, logsString.slice(lettersCountToRemove, logsString.length));
2134
+ } else {
2135
+ localStorage.setItem(this._logsStorageId, logsString);
2136
+ }
2137
+ this._inMemoryStorage = [];
2138
+ }
2139
+ } catch (e) {
2140
+ logger == null || logger.logError(e, "saveToTheDisk", "Failed to save logs to disk");
2141
+ }
2142
+ };
2143
+ LogsStorage.removeAllClientLogs = function removeAllClientLogs() {
2144
+ if (typeof window !== "undefined") {
2145
+ if (localStorage.getItem("doNotRemoveClientLogsWhenSignedOut") !== "true") {
2146
+ localStorage.removeItem(this._logsStorageId);
2147
+ }
2148
+ }
2149
+ this._inMemoryStorage = [];
2150
+ };
2151
+ LogsStorage.setDoNotRemoveClientLogsWhenSignedOut = function setDoNotRemoveClientLogsWhenSignedOut(value) {
2152
+ if (typeof window !== "undefined") {
2153
+ localStorage.setItem("doNotRemoveClientLogsWhenSignedOut", value);
2154
+ }
2155
+ };
2156
+ return LogsStorage;
2157
+ }();
2158
+ LogsStorage._inMemoryStorage = [];
2159
+ LogsStorage._logsStorageId = "clietnLogs_j203fj2D0n-d1";
2160
+
2161
+ /**
2162
+ * Stringify given object by use of JSON.stringify but handles circular structures and "response", "request" properties
2163
+ * to avoid stringing redundant data when printing errors containing request/response objects.
2164
+ *
2165
+ * @param object - object to be stringed
2166
+ * @param indent - custom indentation
2167
+ * @return {string} - stringed object
2168
+ */
2169
+ function safeStringify(object, indent) {
2170
+ if (indent === void 0) {
2171
+ indent = 2;
2172
+ }
2173
+ var cache = [];
2174
+ if (typeof object === "string" || typeof object === "function" || typeof object === "number" || typeof object === "undefined" || typeof object === "boolean") {
2175
+ return String(object);
2176
+ }
2177
+ var retVal = JSON.stringify(object, function (key, value) {
2178
+ if (key.toLowerCase().includes("request")) {
2179
+ return JSON.stringify({
2180
+ body: value == null ? void 0 : value.body,
2181
+ query: value == null ? void 0 : value.query,
2182
+ headers: value == null ? void 0 : value.headers
2183
+ });
2184
+ }
2185
+ if (key.toLowerCase().includes("response")) {
2186
+ return JSON.stringify({
2187
+ statusText: value == null ? void 0 : value.statusText,
2188
+ status: value == null ? void 0 : value.status,
2189
+ data: value == null ? void 0 : value.data,
2190
+ headers: value == null ? void 0 : value.headers
2191
+ });
2192
+ }
2193
+ return typeof value === "object" && value !== null ? cache.includes(value) ? "duplicated reference" // Duplicated references were found, discarding this key
2194
+ : cache.push(value) && value // Store value in our collection
2195
+ : value;
2196
+ }, indent);
2197
+ cache = null;
2198
+ return retVal;
2199
+ }
2200
+
2201
+ var Logger = /*#__PURE__*/function () {
2202
+ function Logger() {}
2203
+ /**
2204
+ * Logs to client logs storage.
2205
+ *
2206
+ * WARNING! this method should ce used carefully for critical logging as we have the restriction for storing logs
2207
+ * on client side as we store them inside the local storage. Please see details inside storage.js
2208
+ * @param logString {string} log string
2209
+ * @param source {string} source of the log entry
2210
+ */
2211
+ Logger.log = function log(logString, source) {
2212
+ var timestamp = new Date().toISOString();
2213
+ LogsStorage.saveLog(timestamp + "|" + source + ":" + logString);
2214
+ };
2215
+ Logger.logError = function logError(e, settingFunction, additionalMessage, onlyToConsole) {
2216
+ var _e$errorDescription, _e$howToFix;
2217
+ if (additionalMessage === void 0) {
2218
+ additionalMessage = "";
2219
+ }
2220
+ if (onlyToConsole === void 0) {
2221
+ onlyToConsole = false;
2222
+ }
2223
+ var message = "\nFunction call " + (settingFunction != null ? settingFunction : "") + " failed. Error message: " + (e == null ? void 0 : e.message) + ". " + additionalMessage + " ";
2224
+ message += "" + ((_e$errorDescription = e == null ? void 0 : e.errorDescription) != null ? _e$errorDescription : "") + ((_e$howToFix = e == null ? void 0 : e.howToFix) != null ? _e$howToFix : "") + ((e == null ? void 0 : e.httpStatus) === 403 ? "Authentication has expired or was lost. " : "");
2225
+ if (e != null && e.response) {
2226
+ try {
2227
+ var responseData = safeStringify({
2228
+ response: e.response
2229
+ });
2230
+ responseData && (message += "\n" + responseData + ". ");
2231
+ } catch (e) {}
2232
+ }
2233
+ var finalErrorText = message + ". " + safeStringify(e);
2234
+ // eslint-disable-next-line no-console
2235
+ console.error(finalErrorText);
2236
+ if (!onlyToConsole) {
2237
+ this.log(finalErrorText, "logError");
2238
+ }
2239
+ };
2240
+ return Logger;
2241
+ }();
2242
+
2243
+ /**
2244
+ * TODO: [tests, critical] Ued by payments logic
2245
+ *
2246
+ * Simple cache based on Map.
2247
+ * Provides ability to store event-dependent data.
2248
+ */
2249
+ var Cache = /*#__PURE__*/function () {
2250
+ /**
2251
+ * @param eventBus {EventBus} EventBus.js lib instance
2252
+ * @param [noSessionEvents=[]] {string[]} array of events that will be treated as "no session"
2253
+ */
2254
+ function Cache(eventBus, noSessionEvents) {
2255
+ if (noSessionEvents === void 0) {
2256
+ noSessionEvents = [];
2257
+ }
2258
+ this._cache = new Map();
2259
+ this._eventDependentDataKeys = [];
2260
+ this._noSessionEvents = noSessionEvents;
2261
+ this._eventBus = eventBus;
2262
+ }
2263
+ var _proto = Cache.prototype;
2264
+ _proto._setupIntervalClearingExpired = function _setupIntervalClearingExpired() {
2265
+ var cleaner = function cleaner() {
2266
+ try {
2267
+ for (var _iterator = _createForOfIteratorHelperLoose(this._cache.keys()), _step; !(_step = _iterator()).done;) {
2268
+ var key = _step.value;
2269
+ var item = this._cache.get(key);
2270
+ if (item && item.ttlMs && item.addedMsTimestamp + item.ttlMs < Date.now()) {
2271
+ this._cache["delete"](key);
2272
+ }
2273
+ }
2274
+ } catch (e) {
2275
+ improveAndRethrow(e, "_intervalClearingExpiredCache");
2276
+ }
2277
+ };
2278
+ cleaner = cleaner.bind(this);
2279
+ setInterval(cleaner, 1000);
2280
+ }
2281
+
2282
+ /**
2283
+ * Puts data to cache
2284
+ *
2285
+ * @param key {string} string key for this data
2286
+ * @param data {any} any data
2287
+ * @param ttlMs {number|null} optional milliseconds number for cache lifetime
2288
+ * @throws {Error} when the data is null/undefined because these values for data are reserved for internal logic
2289
+ */;
2290
+ _proto.put = function put(key, data, ttlMs) {
2291
+ if (ttlMs === void 0) {
2292
+ ttlMs = null;
2293
+ }
2294
+ try {
2295
+ if (typeof key !== "string" || data == null) {
2296
+ throw new Error("Trying to cache corrupted data: " + key + ", " + data);
2297
+ }
2298
+ this._cache.set(key, {
2299
+ data: data,
2300
+ addedMsTimestamp: Date.now(),
2301
+ ttlMs: ttlMs
2302
+ });
2303
+ } catch (e) {
2304
+ improveAndRethrow(e, "cache.put");
2305
+ }
2306
+ };
2307
+ _proto.putSessionDependentData = function putSessionDependentData(key, data, ttlMs) {
2308
+ if (ttlMs === void 0) {
2309
+ ttlMs = null;
2310
+ }
2311
+ this._putEventDependentData(key, data, this._noSessionEvents, ttlMs);
2312
+ }
2313
+
2314
+ /**
2315
+ * Puts data to cache and adds its key to list of keys that should be related by each of given events.
2316
+ *
2317
+ * @param key {string} key for cache
2318
+ * @param data {any} any caching data
2319
+ * @param events {string[]} list of events forcing putting data to be removed when triggered
2320
+ * @param ttlMs {|null} optional time to live for this cache item
2321
+ * @throws {Error} when the data is null/undefined because these values for data are reserved for internal logic
2322
+ */;
2323
+ _proto.putEventDependentData = function putEventDependentData(key, data, events, ttlMs) {
2324
+ if (ttlMs === void 0) {
2325
+ ttlMs = null;
2326
+ }
2327
+ this._putEventDependentData(key, data, events, ttlMs);
2328
+ };
2329
+ _proto._putEventDependentData = function _putEventDependentData(key, data, events, ttlMs) {
2330
+ var _this = this;
2331
+ if (ttlMs === void 0) {
2332
+ ttlMs = null;
2333
+ }
2334
+ try {
2335
+ if (typeof key !== "string" || data == null) {
2336
+ throw new Error("Trying to cache corrupted data: " + key + ", " + data);
2337
+ }
2338
+ this._cache.set(key, {
2339
+ data: data,
2340
+ addedMsTimestamp: Date.now(),
2341
+ ttlMs: ttlMs
2342
+ });
2343
+ var _loop = function _loop() {
2344
+ var event = _step2.value;
2345
+ var eventAndKeys = _this._eventDependentDataKeys.find(function (item) {
2346
+ return item[0] === event;
2347
+ });
2348
+ if (eventAndKeys) {
2349
+ eventAndKeys.push(key);
2350
+ } else {
2351
+ _this._eventDependentDataKeys.push([event, key]);
2352
+ _this._eventBus.addEventListener(event, function () {
2353
+ try {
2354
+ var keys = _this._eventDependentDataKeys.find(function (item) {
2355
+ return item[0] === event;
2356
+ });
2357
+ (keys != null ? keys : [event]).slice(1).forEach(function (key) {
2358
+ return _this._cache["delete"](key);
2359
+ });
2360
+ } catch (e) {
2361
+ Logger.logError(e, "cache.removing-for-event", "Event: " + event);
2362
+ }
2363
+ });
2364
+ }
2365
+ };
2366
+ for (var _iterator2 = _createForOfIteratorHelperLoose(events), _step2; !(_step2 = _iterator2()).done;) {
2367
+ _loop();
2368
+ }
2369
+ } catch (e) {
2370
+ improveAndRethrow(e, "cache.putEventDependentData");
2371
+ }
2372
+ }
2373
+
2374
+ // TODO: [feature, low] add clearing of expired data by schedule
2375
+ ;
2376
+ _proto.get = function get(key) {
2377
+ try {
2378
+ var item = this._cache.get(key);
2379
+ if (item) {
2380
+ if (item.addedMsTimestamp && item.ttlMs !== null && item.addedMsTimestamp + item.ttlMs < Date.now()) {
2381
+ this._cache["delete"](key);
2382
+ return null;
2383
+ } else {
2384
+ return item.data;
2385
+ }
2386
+ }
2387
+ return null;
2388
+ } catch (e) {
2389
+ improveAndRethrow(e, "cache.get");
2390
+ }
2391
+ };
2392
+ _proto.getLastUpdateTimestamp = function getLastUpdateTimestamp(key) {
2393
+ var _this$_cache$get$adde, _this$_cache$get;
2394
+ return (_this$_cache$get$adde = (_this$_cache$get = this._cache.get(key)) == null ? void 0 : _this$_cache$get.addedMsTimestamp) != null ? _this$_cache$get$adde : null;
2395
+ }
2396
+
2397
+ /**
2398
+ * Updates the timestamp of the last update for specified key to the provided value.
2399
+ * Can be useful when TTL is controlled outside this class.
2400
+ *
2401
+ * @param key {string}
2402
+ * @param timestamp {number}
2403
+ * @return {boolean}
2404
+ */;
2405
+ _proto.setLastUpdateTimestamp = function setLastUpdateTimestamp(key, timestamp) {
2406
+ try {
2407
+ var item = this._cache.get(key);
2408
+ if (item != null && typeof timestamp === "number") {
2409
+ this._cache.set(key, _extends({}, item, {
2410
+ addedTimestampMs: timestamp
2411
+ }));
2412
+ return true;
2413
+ }
2414
+ return false;
2415
+ } catch (e) {
2416
+ improveAndRethrow("cache.setLastUpdateTimestamp");
2417
+ }
2418
+ };
2419
+ _proto.invalidate = function invalidate(key) {
2420
+ try {
2421
+ this._cache["delete"](key);
2422
+ } catch (e) {
2423
+ improveAndRethrow(e, "cache.invalidate");
2424
+ }
2425
+ };
2426
+ _proto.invalidateContaining = function invalidateContaining(keyPart) {
2427
+ if (typeof keyPart !== "string" || keyPart === "") {
2428
+ throw new Error("Trying to invalidate containing wrong key or empty key: " + keyPart);
2429
+ }
2430
+ try {
2431
+ var matchedKeys = Array.from(this._cache.keys()).filter(function (key) {
2432
+ return typeof key === "string" && new RegExp(keyPart).test(key);
2433
+ });
2434
+ for (var i = 0; i < matchedKeys.length; ++i) {
2435
+ this._cache["delete"](matchedKeys[i]);
2436
+ }
2437
+ } catch (e) {
2438
+ improveAndRethrow(e, "invalidateContaining");
2439
+ }
2440
+ };
2441
+ _proto.clear = function clear() {
2442
+ this._cache.clear();
2443
+ this._sessionDependentDataKeys = [];
2444
+ }
2445
+
2446
+ /**
2447
+ * Saves given data string to persistent cache.
2448
+ * NOTE: we have no TTL here, implement if needed.
2449
+ *
2450
+ * WARNING: use only when really needed and don't store big data as we use localStorage
2451
+ * under the hood and its capacity is restricted.
2452
+ *
2453
+ * @param uniqueKey {string} the key should be unique
2454
+ * @param data {string} only string data allowed
2455
+ */;
2456
+ _proto.putClientPersistentData = function putClientPersistentData(uniqueKey, data) {
2457
+ try {
2458
+ if (typeof window !== "undefined") {
2459
+ localStorage.setItem(uniqueKey, data);
2460
+ }
2461
+ } catch (e) {
2462
+ improveAndRethrow(e, "cache.putClientPersistentData");
2463
+ }
2464
+ }
2465
+
2466
+ /**
2467
+ * @param uniqueKey {string}
2468
+ * @return {string|null}
2469
+ */;
2470
+ _proto.getClientPersistentData = function getClientPersistentData(uniqueKey) {
2471
+ try {
2472
+ if (typeof window !== "undefined") {
2473
+ return localStorage.getItem(uniqueKey);
2474
+ }
2475
+ return null;
2476
+ } catch (e) {
2477
+ improveAndRethrow(e, "cache.getClientPersistentData");
2478
+ }
2479
+ }
2480
+
2481
+ /**
2482
+ * Only makes effect if the TTL is not null.
2483
+ *
2484
+ * @param key {string}
2485
+ * @param ttlMs {number|null}
2486
+ */;
2487
+ _proto.markCacheItemAsExpiredButDontRemove = function markCacheItemAsExpiredButDontRemove(key, ttlMs) {
2488
+ if (ttlMs === void 0) {
2489
+ ttlMs = null;
2490
+ }
2491
+ try {
2492
+ var _ttlMs;
2493
+ var item = this._cache.get(key);
2494
+ var ttlFinalMs = (_ttlMs = ttlMs) != null ? _ttlMs : item == null ? void 0 : item.ttlMs;
2495
+ if (item != null && ttlFinalMs) {
2496
+ this._cache.set(key, {
2497
+ data: item.data,
2498
+ addedMsTimestamp: Date.now() - ttlFinalMs - 1,
2499
+ ttlMs: ttlFinalMs
2500
+ });
2501
+ }
2502
+ } catch (e) {
2503
+ improveAndRethrow(e, "cache.markCacheItemAsExpiredButDontRemove");
2504
+ }
2505
+ };
2506
+ return Cache;
2507
+ }();
2508
+
2509
+ var ExistingSwap =
2510
+ /**
2511
+ * @param swapId {string}
2512
+ * @param status {SwapProvider.SWAP_STATUSES}
2513
+ * @param createdAt {number}
2514
+ * @param expiresAt {number}
2515
+ * @param confirmations {number}
2516
+ * @param rate {string}
2517
+ * @param refundAddress {string}
2518
+ * @param fromCoin {Coin}
2519
+ * @param fromAmount {string}
2520
+ * @param fromTransactionId {string}
2521
+ * @param toCoin {Coin}
2522
+ * @param toAmount {string}
2523
+ * @param toTransactionId {string|null}
2524
+ * @param toAddress {string}
2525
+ * @param partner {string}
2526
+ */
2527
+ function ExistingSwap(swapId, status, createdAt, expiresAt, confirmations, rate, refundAddress, payToAddress, fromCoin, fromAmount, fromTransactionId, fromTransactionLink, toCoin, toAmount, toTransactionId, toTransactionLink, toAddress,
2528
+ // TODO: [refactoring, moderate] toAddress is not quite clear. How about recipientAddress? task_id=0815a111c99543b78d374217eadbde4f
2529
+ partner) {
2530
+ this.swapId = swapId;
2531
+ this.status = status;
2532
+ this.createdAt = createdAt;
2533
+ this.expiresAt = expiresAt;
2534
+ this.confirmations = confirmations;
2535
+ this.rate = rate;
2536
+ this.refundAddress = refundAddress;
2537
+ this.payToAddress = payToAddress;
2538
+ this.fromCoin = fromCoin;
2539
+ this.fromTransactionId = fromTransactionId;
2540
+ this.fromAmount = fromAmount;
2541
+ this.fromTransactionLink = fromTransactionLink;
2542
+ this.toCoin = toCoin;
2543
+ this.toTransactionId = toTransactionId;
2544
+ this.toTransactionLink = toTransactionLink;
2545
+ this.toAmount = toAmount;
2546
+ this.toAddress = toAddress;
2547
+ this.partner = partner;
2548
+ };
2549
+
2550
+ var SwapProvider = /*#__PURE__*/function () {
2551
+ function SwapProvider() {}
2552
+ var _proto = SwapProvider.prototype;
2553
+ /**
2554
+ * @return {Promise<void>}
2555
+ */
2556
+ _proto.initialize = function initialize() {
2557
+ try {
2558
+ throw new Error("Not implemented in base");
2559
+ } catch (e) {
2560
+ return Promise.reject(e);
2561
+ }
2562
+ }
2563
+ /**
2564
+ * @return {number} milliseconds TTL
2565
+ */
2566
+ ;
2567
+ _proto.getSwapCreationInfoTtlMs = function getSwapCreationInfoTtlMs() {
2568
+ throw new Error("Not implemented in base");
2569
+ }
2570
+
2571
+ /**
2572
+ * Retrieves all deposit currencies supported by this swap provider.
2573
+ * Returns one of SwapProvider.COMMON_ERRORS in case of processable fail.
2574
+ *
2575
+ * @return {Promise<({ result: true, coins: Coin[] }|{ result: false, reason: string })>}
2576
+ */;
2577
+ _proto.getDepositCurrencies = function getDepositCurrencies() {
2578
+ try {
2579
+ throw new Error("Not implemented in base");
2580
+ } catch (e) {
2581
+ return Promise.reject(e);
2582
+ }
2583
+ }
2584
+ /**
2585
+ * Retrieves all withdrawable currencies supported by this swap provider.
2586
+ * Returns one of SwapProvider.COMMON_ERRORS in case of processable fail.
2587
+ *
2588
+ * @param [exceptCurrency=null] {Coin|null}
2589
+ * @return {Promise<({ result: true, coins: Coin[] }|{ result: false, reason: string })>}
2590
+ */
2591
+ ;
2592
+ _proto.getWithdrawalCurrencies = function getWithdrawalCurrencies(exceptCurrency) {
2593
+ try {
2594
+ throw new Error("Not implemented in base");
2595
+ } catch (e) {
2596
+ return Promise.reject(e);
2597
+ }
2598
+ }
2599
+ /**
2600
+ * Retrieves URL for coin icon or fallback if not found.
2601
+ *
2602
+ * @param coin {Coin|string} coin or rabbit-format of coin ticker
2603
+ * @return {string}
2604
+ */
2605
+ ;
2606
+ _proto.getIconUrl = function getIconUrl(coin) {
2607
+ throw new Error("Not implemented in base");
2608
+ }
2609
+
2610
+ /**
2611
+ * Retrieves coin to USDT rate.
2612
+ *
2613
+ * @param coin {Coin}
2614
+ * @return {{result: true, rate: string}|{result: false}}
2615
+ */;
2616
+ _proto.getCoinToUSDTRate = function getCoinToUSDTRate(coin) {
2617
+ try {
2618
+ throw new Error("Not implemented in base");
2619
+ } catch (e) {
2620
+ return Promise.reject(e);
2621
+ }
2622
+ }
2623
+ /**
2624
+ * Retrieves estimation for swapping giving coins amount.
2625
+ * null min or max signals there is no corresponding limitation. undefined means that the limits were not retrieved.
2626
+ * For fail result on of SwapProvider.NO_SWAPS_REASONS or SwapProvider.COMMON_ERRORS reasons will be returned.
2627
+ *
2628
+ * @param fromCoin {Coin}
2629
+ * @param toCoin {Coin}
2630
+ * @param amountCoins {string}
2631
+ * @param [fromCoinToUsdRate=null] pass if you want to increase the min amount returned
2632
+ * by provider with some fixed "insurance" amount to cover min amount fluctuations.
2633
+ * @return {Promise<({
2634
+ * result: false,
2635
+ * reason: string,
2636
+ * smallestMin: (string|null|undefined),
2637
+ * greatestMax: (string|null|undefined),
2638
+ * }|{
2639
+ * result: true,
2640
+ * min: (string|null),
2641
+ * max: (string|null),
2642
+ * smallestMin: (string|null),
2643
+ * greatestMax: (string|null),
2644
+ * rate: (string|null),
2645
+ * durationMinutesRange: string,
2646
+ * [rawSwapData]: Object
2647
+ * })>}
2648
+ */
2649
+ ;
2650
+ _proto.getSwapInfo = function getSwapInfo(fromCoin, toCoin, amountCoins, fromCoinToUsdRate) {
2651
+ try {
2652
+ throw new Error("Not implemented in base");
2653
+ } catch (e) {
2654
+ return Promise.reject(e);
2655
+ }
2656
+ }
2657
+ /**
2658
+ * For fail result we return one of SwapProvider.CREATION_FAIL_REASONS or SwapProvider.COMMON_ERRORS.
2659
+ *
2660
+ * @param fromCoin {Coin}
2661
+ * @param toCoin {Coin}
2662
+ * @param amount {string}
2663
+ * @param toAddress {string}
2664
+ * @param refundAddress {string}
2665
+ * @param rawSwapData {Object|null}
2666
+ * @param clientIpAddress {string}
2667
+ * @return {Promise<({
2668
+ * result: true,
2669
+ * swapId: string,
2670
+ * fromCoin: Coin,
2671
+ * fromAmount: string,
2672
+ * fromAddress: string,
2673
+ * toCoin: Coin,
2674
+ * toAmount: string,
2675
+ * toAddress: string,
2676
+ * rate: string
2677
+ * }|{
2678
+ * result: false,
2679
+ * reason: string,
2680
+ * partner: string
2681
+ * })>}
2682
+ */
2683
+ ;
2684
+ _proto.createSwap = function createSwap(fromCoin, toCoin, amount, toAddress, refundAddress, rawSwapData, clientIpAddress) {
2685
+ try {
2686
+ throw new Error("Not implemented in base");
2687
+ } catch (e) {
2688
+ return Promise.reject(e);
2689
+ }
2690
+ }
2691
+ /**
2692
+ * Retrieves details and status for swaps by given ids.
2693
+ * If some swap is not found by id then there is no item in return list.
2694
+ *
2695
+ * @param swapIds {string[]}
2696
+ * @return {Promise<{result: false, reason: string}|{result:true, swaps: ExistingSwap[]}>}
2697
+ */
2698
+ ;
2699
+ _proto.getExistingSwapsDetailsAndStatus = function getExistingSwapsDetailsAndStatus(swapIds) {
2700
+ try {
2701
+ throw new Error("Not implemented in base");
2702
+ } catch (e) {
2703
+ return Promise.reject(e);
2704
+ }
2705
+ }
2706
+ /**
2707
+ * @param ticker {string}
2708
+ * @return {Coin|null}
2709
+ */
2710
+ ;
2711
+ _proto.getCoinByTickerIfPresent = function getCoinByTickerIfPresent(ticker) {
2712
+ throw new Error("Not implemented in base");
2713
+ }
2714
+
2715
+ /**
2716
+ * @param asset {Coin}
2717
+ * @param address {string}
2718
+ * @return {boolean}
2719
+ */;
2720
+ _proto.isAddressValidForAsset = function isAddressValidForAsset(asset, address) {
2721
+ throw new Error("Not implemented in base");
2722
+ };
2723
+ return SwapProvider;
2724
+ }();
2725
+ SwapProvider.COMMON_ERRORS = {
2726
+ REQUESTS_LIMIT_EXCEEDED: "requestsLimitExceeded"
2727
+ };
2728
+ SwapProvider.NO_SWAPS_REASONS = {
2729
+ TOO_LOW: "tooLow",
2730
+ TOO_HIGH: "tooHigh",
2731
+ NOT_SUPPORTED: "notSupported"
2732
+ };
2733
+ SwapProvider.CREATION_FAIL_REASONS = {
2734
+ RETRIABLE_FAIL: "retriableFail"
2735
+ };
2736
+ SwapProvider.SWAP_STATUSES = {
2737
+ WAITING_FOR_PAYMENT: "waiting_for_payment",
2738
+ // public +
2739
+ CONFIRMING: "confirming",
2740
+ PAYMENT_RECEIVED: "payment_received",
2741
+ // public +
2742
+ EXCHANGING: "exchanging",
2743
+ // session full // public +
2744
+ COMPLETED: "completed",
2745
+ // session full // public +
2746
+ REFUNDED: "refunded",
2747
+ // session full // public +
2748
+ EXPIRED: "expired",
2749
+ // public +
2750
+ FAILED: "failed" // public +
2751
+ };
2752
+
2753
+ function _catch(body, recover) {
2754
+ try {
2755
+ var result = body();
2756
+ } catch (e) {
2757
+ return recover(e);
2758
+ }
2759
+ if (result && result.then) {
2760
+ return result.then(void 0, recover);
2761
+ }
2762
+ return result;
2763
+ }
2764
+ var BANNED_PARTNERS = ["stealthex", "changee", "coincraddle"];
2765
+ var FALLBACK_ICON_URL = "https://rabbit.io/asset-icons/fallback.svg";
2766
+ var SwapspaceSwapProvider = /*#__PURE__*/function (_SwapProvider) {
2767
+ _inheritsLoose(SwapspaceSwapProvider, _SwapProvider);
2768
+ function SwapspaceSwapProvider(apiKeysProxyUrl, cache, customCoinBuilder, useRestrictedCoinsSet) {
2769
+ var _this;
2770
+ if (customCoinBuilder === void 0) {
2771
+ customCoinBuilder = function customCoinBuilder(coin, network) {
2772
+ return null;
2773
+ };
2774
+ }
2775
+ if (useRestrictedCoinsSet === void 0) {
2776
+ useRestrictedCoinsSet = true;
2777
+ }
2778
+ _this = _SwapProvider.call(this) || this;
2779
+ _this._supportedCoins = [];
2780
+ _this._URL = apiKeysProxyUrl + "/swapspace";
2781
+ _this._maxRateDigits = 20;
2782
+ _this.useRestrictedCoinsSet = useRestrictedCoinsSet;
2783
+ _this._customCoinBuilder = customCoinBuilder;
2784
+ _this._cache = cache;
2785
+ return _this;
2786
+ }
2787
+ var _proto = SwapspaceSwapProvider.prototype;
2788
+ _proto.getSwapCreationInfoTtlMs = function getSwapCreationInfoTtlMs() {
2789
+ /* Actually 2 minutes and only relevant for some partners, but we use it
2790
+ * (and even a bit smaller value) for better consistency */
2791
+ return 110000;
2792
+ };
2793
+ _proto.getDepositCurrencies = function getDepositCurrencies() {
2794
+ try {
2795
+ var _this2 = this;
2796
+ var loggerSource = "getDepositCurrencies";
2797
+ return Promise.resolve(_catch(function () {
2798
+ return Promise.resolve(_this2._fetchSupportedCurrenciesIfNeeded()).then(function () {
2799
+ var _this2$_supportedCoin;
2800
+ Logger.log("We have " + ((_this2$_supportedCoin = _this2._supportedCoins) == null ? void 0 : _this2$_supportedCoin.length) + " supported coins, getting depositable", loggerSource);
2801
+ return {
2802
+ result: true,
2803
+ coins: _this2._supportedCoins.filter(function (item) {
2804
+ return item.deposit;
2805
+ }).map(function (item) {
2806
+ return item.coin;
2807
+ })
2808
+ };
2809
+ });
2810
+ }, function (e) {
2811
+ var _e$response;
2812
+ if ((e == null || (_e$response = e.response) == null ? void 0 : _e$response.status) === 429) {
2813
+ return {
2814
+ result: false,
2815
+ reason: SwapProvider.COMMON_ERRORS.REQUESTS_LIMIT_EXCEEDED
2816
+ };
2817
+ }
2818
+ improveAndRethrow(e, loggerSource);
2819
+ }));
2820
+ } catch (e) {
2821
+ return Promise.reject(e);
2822
+ }
2823
+ };
2824
+ _proto.getWithdrawalCurrencies = function getWithdrawalCurrencies(exceptCurrency) {
2825
+ if (exceptCurrency === void 0) {
2826
+ exceptCurrency = null;
2827
+ }
2828
+ try {
2829
+ var _this3 = this;
2830
+ var loggerSource = "getWithdrawalCurrencies";
2831
+ return Promise.resolve(_catch(function () {
2832
+ return Promise.resolve(_this3._fetchSupportedCurrenciesIfNeeded()).then(function () {
2833
+ var _this3$_supportedCoin;
2834
+ Logger.log("We have " + ((_this3$_supportedCoin = _this3._supportedCoins) == null ? void 0 : _this3$_supportedCoin.length) + " supported coins, getting withdrawable", loggerSource);
2835
+ return {
2836
+ result: true,
2837
+ coins: _this3._supportedCoins.filter(function (item) {
2838
+ return item.withdrawal && (!exceptCurrency || item.coin !== exceptCurrency);
2839
+ }).map(function (item) {
2840
+ return item.coin;
2841
+ })
2842
+ };
2843
+ });
2844
+ }, function (e) {
2845
+ var _e$response2;
2846
+ if ((e == null || (_e$response2 = e.response) == null ? void 0 : _e$response2.status) === 429) {
2847
+ return {
2848
+ result: false,
2849
+ reason: SwapProvider.COMMON_ERRORS.REQUESTS_LIMIT_EXCEEDED
2850
+ };
2851
+ }
2852
+ improveAndRethrow(e, loggerSource);
2853
+ }));
2854
+ } catch (e) {
2855
+ return Promise.reject(e);
2856
+ }
2857
+ };
2858
+ _proto.initialize = function initialize() {
2859
+ try {
2860
+ var _this4 = this;
2861
+ return Promise.resolve(_this4._fetchSupportedCurrenciesIfNeeded()).then(function () {});
2862
+ } catch (e) {
2863
+ return Promise.reject(e);
2864
+ }
2865
+ };
2866
+ _proto.getIconUrl = function getIconUrl(coinOrTicker) {
2867
+ var loggerSource = "getIconUrl";
2868
+ try {
2869
+ var _this$_supportedCoins2, _this$_supportedCoins3;
2870
+ var coin = coinOrTicker;
2871
+ if (!(coinOrTicker instanceof Coin)) {
2872
+ var _this$_supportedCoins;
2873
+ coin = (_this$_supportedCoins = this._supportedCoins.find(function (i) {
2874
+ return i.coin.ticker === coinOrTicker;
2875
+ })) == null ? void 0 : _this$_supportedCoins.coin;
2876
+ }
2877
+ return (_this$_supportedCoins2 = (_this$_supportedCoins3 = this._supportedCoins.find(function (item) {
2878
+ return item.coin === coin;
2879
+ })) == null ? void 0 : _this$_supportedCoins3.iconURL) != null ? _this$_supportedCoins2 : FALLBACK_ICON_URL;
2880
+ } catch (e) {
2881
+ improveAndRethrow(e, loggerSource);
2882
+ }
2883
+ };
2884
+ _proto._fetchSupportedCurrenciesIfNeeded = function _fetchSupportedCurrenciesIfNeeded() {
2885
+ try {
2886
+ var _this5 = this;
2887
+ var loggerSource = "_fetchSupportedCurrenciesIfNeeded";
2888
+ return Promise.resolve(_catch(function () {
2889
+ var _temp = function (_this5$_supportedCoin) {
2890
+ if (!((_this5$_supportedCoin = _this5._supportedCoins) != null && _this5$_supportedCoin.length)) {
2891
+ return Promise.resolve(axios__default["default"].get(_this5._URL + "/api/v2/currencies")).then(function (rawResponse) {
2892
+ var _rawResponse$data, _rawResponse$data2;
2893
+ Logger.log("Retrieved " + (rawResponse == null || (_rawResponse$data = rawResponse.data) == null ? void 0 : _rawResponse$data.length) + " currencies", loggerSource);
2894
+ _this5._supportedCoins = ((_rawResponse$data2 = rawResponse == null ? void 0 : rawResponse.data) != null ? _rawResponse$data2 : []).map(function (item) {
2895
+ var coin = _this5._customCoinBuilder(item.code, item.network);
2896
+ if (!coin && !_this5.useRestrictedCoinsSet) {
2897
+ /** Building coin object for coin that isn't supported OOB in Rabbit.
2898
+ * We are doing this way to be able to use extended coins set for swaps.
2899
+ * These temporary built coins are only for in-swap use, and we omit some usual
2900
+ * coin details here.
2901
+ * Ideally we should add some new abstractions e.g. BaseCoin:
2902
+ * Coin will extend BaseCoin, SwapCoin will extend BaseCoin etc.
2903
+ * But for now it is reasonable to use this simpler approach.
2904
+ */
2905
+ var code = item.code.toUpperCase();
2906
+ var network = item.network.toUpperCase();
2907
+ var ticker = "" + code + (code === network ? "" : network);
2908
+ var defaultDecimalPlacesForCoinNotSupportedOOB = 8;
2909
+ var defaultMinConfirmationsForCoinNotSupportedOOB = 1;
2910
+ coin = new Coin(item.name, ticker, code, defaultDecimalPlacesForCoinNotSupportedOOB, null, "", null, null, defaultMinConfirmationsForCoinNotSupportedOOB, null, [], 60000, null,
2911
+ // We cannot recognize blockchain from swapspace data
2912
+ new Protocol(network),
2913
+ // TODO: [dev] maybe we should recognize standard protocols?
2914
+ item.contractAddress || null, false);
2915
+ }
2916
+ if (coin) {
2917
+ var _item$deposit, _item$withdrawal, _item$validationRegex;
2918
+ return {
2919
+ coin: coin,
2920
+ code: item.code,
2921
+ network: item.network,
2922
+ extraId: item.extraIdName,
2923
+ isPopular: !!(item != null && item.popular),
2924
+ iconURL: item.icon ? "https://storage.swapspace.co" + item.icon : FALLBACK_ICON_URL,
2925
+ deposit: (_item$deposit = item.deposit) != null ? _item$deposit : false,
2926
+ withdrawal: (_item$withdrawal = item.withdrawal) != null ? _item$withdrawal : false,
2927
+ validationRegexp: (_item$validationRegex = item.validationRegexp) != null ? _item$validationRegex : null
2928
+ };
2929
+ }
2930
+ return [];
2931
+ }).flat();
2932
+ _this5._putPopularCoinsFirst();
2933
+ });
2934
+ }
2935
+ }();
2936
+ if (_temp && _temp.then) return _temp.then(function () {});
2937
+ }, function (e) {
2938
+ improveAndRethrow(e, loggerSource);
2939
+ }));
2940
+ } catch (e) {
2941
+ return Promise.reject(e);
2942
+ }
2943
+ }
2944
+ /**
2945
+ * This method sort internal list putting popular (as swapspace thinks) coins to the top.
2946
+ * This is just for users of this API if they don't care about the sorting - we just improve a list a bit this way.
2947
+ * @private
2948
+ */
2949
+ ;
2950
+ _proto._putPopularCoinsFirst = function _putPopularCoinsFirst() {
2951
+ this._supportedCoins.sort(function (i1, i2) {
2952
+ if (i1.isPopular && !i2.isPopular) return -1;
2953
+ if (i2.isPopular && !i1.isPopular) return 1;
2954
+ return i1.coin.ticker > i2.coin.ticker ? 1 : i1.coin.ticker < i2.coin.ticker ? -1 : 0;
2955
+ });
2956
+ };
2957
+ _proto.getCoinToUSDTRate = function getCoinToUSDTRate(coin) {
2958
+ try {
2959
+ var _this6 = this;
2960
+ var loggerSource = "getCoinToUSDTRate";
2961
+ return Promise.resolve(_catch(function () {
2962
+ return Promise.resolve(_this6._fetchSupportedCurrenciesIfNeeded()).then(function () {
2963
+ var _this6$_supportedCoin;
2964
+ // Using USDT TRC20 as usually fee in this network is smaller than ERC20 and this network is widely used for USDT
2965
+ var usdtTrc20 = (_this6$_supportedCoin = _this6._supportedCoins.find(function (i) {
2966
+ return i.code === "usdt" && i.network === "trc20";
2967
+ })) == null ? void 0 : _this6$_supportedCoin.coin;
2968
+ if (!usdtTrc20) {
2969
+ return {
2970
+ result: false
2971
+ };
2972
+ }
2973
+ var cached = _this6._cache.get("swapspace_usdt_rate_" + coin.ticker);
2974
+ if (cached != null) {
2975
+ return {
2976
+ result: true,
2977
+ rate: cached
2978
+ };
2979
+ }
2980
+ Logger.log("Loading USDT -> coin rate as not found in cache:", coin == null ? void 0 : coin.ticker);
2981
+ return Promise.resolve(_this6.getSwapInfo(usdtTrc20, coin, "5000")).then(function (result) {
2982
+ if (!result.result) {
2983
+ return {
2984
+ result: false
2985
+ };
2986
+ }
2987
+
2988
+ // This calculation is not precise as we cannot recognize the actual fee and network fee. Just approximate.
2989
+ var standardSwapspaceFeeMultiplier = 1.002; // usually 0.2%
2990
+ var rate = bignumber_js.BigNumber(1).div(bignumber_js.BigNumber(result.rate).times(standardSwapspaceFeeMultiplier)).toString();
2991
+ _this6._cache.put("swapspace_usdt_rate_" + coin.ticker, rate, 15 * 60000);
2992
+ return {
2993
+ result: true,
2994
+ rate: rate
2995
+ };
2996
+ });
2997
+ });
2998
+ }, function (e) {
2999
+ improveAndRethrow(e, loggerSource);
3000
+ }));
3001
+ } catch (e) {
3002
+ return Promise.reject(e);
3003
+ }
3004
+ };
3005
+ _proto.getCoinByTickerIfPresent = function getCoinByTickerIfPresent(ticker) {
3006
+ try {
3007
+ var _item$coin;
3008
+ var item = this._supportedCoins.find(function (i) {
3009
+ return i.coin.ticker === ticker;
3010
+ });
3011
+ return (_item$coin = item == null ? void 0 : item.coin) != null ? _item$coin : null;
3012
+ } catch (e) {
3013
+ improveAndRethrow(e, "getCoinByTickerIfPresent");
3014
+ }
3015
+ };
3016
+ _proto.getSwapInfo = function getSwapInfo(fromCoin, toCoin, amountCoins, fromCoinToUsdRate) {
3017
+ if (fromCoinToUsdRate === void 0) {
3018
+ fromCoinToUsdRate = null;
3019
+ }
3020
+ try {
3021
+ var _this7 = this;
3022
+ var loggerSource = "getSwapInfo";
3023
+ return Promise.resolve(_catch(function () {
3024
+ if (!(fromCoin instanceof Coin) || !(toCoin instanceof Coin) || typeof amountCoins !== "string" || bignumber_js.BigNumber(amountCoins).lt("0")) {
3025
+ throw new Error("Wrong input params: " + amountCoins + " " + fromCoin.ticker + " -> " + toCoin.ticker + (fromCoin instanceof Coin) + (toCoin instanceof Coin));
3026
+ }
3027
+ var fromCoinSwapspaceDetails = _this7._supportedCoins.find(function (i) {
3028
+ return i.coin === fromCoin;
3029
+ });
3030
+ var toCoinSwapspaceDetails = _this7._supportedCoins.find(function (i) {
3031
+ return i.coin === toCoin;
3032
+ });
3033
+ if (!fromCoinSwapspaceDetails || !toCoinSwapspaceDetails) {
3034
+ throw new Error("Failed to find swapspace coin details for: " + fromCoin.ticker + " -> " + toCoin.ticker);
3035
+ }
3036
+ /* Here we use not documented parameter 'estimated=false'. This parameter controls whether we want to use
3037
+ * cached rate values stored in swapspace cache. Their support says they store at most for 30 sec.
3038
+ * But we are better off using the most actual rates.
3039
+ */
3040
+ return Promise.resolve(axios__default["default"].get(_this7._URL + "/api/v2/amounts?fromCurrency=" + fromCoinSwapspaceDetails.code + "&fromNetwork=" + fromCoinSwapspaceDetails.network + "&toNetwork=" + toCoinSwapspaceDetails.network + "&toCurrency=" + toCoinSwapspaceDetails.code + "&amount=" + amountCoins + "&float=true&estimated=false")).then(function (response) {
3041
+ var _response$data;
3042
+ Logger.log("Retrieved " + (response == null || (_response$data = response.data) == null ? void 0 : _response$data.length) + " options", loggerSource);
3043
+ var options = Array.isArray(response.data) ? response.data : [];
3044
+ var exchangesSupportingThePair = options.filter(function (exchange) {
3045
+ return (exchange == null ? void 0 : exchange.exists) && !BANNED_PARTNERS.find(function (bannedPartner) {
3046
+ return bannedPartner === (exchange == null ? void 0 : exchange.partner);
3047
+ }) && (exchange == null ? void 0 : exchange.fixed) === false && (exchange.min === 0 || exchange.max === 0 || exchange.max > exchange.min || (typeof exchange.min !== "number" || typeof exchange.max !== "number") && exchange.toAmount > 0);
3048
+ });
3049
+ Logger.log((exchangesSupportingThePair == null ? void 0 : exchangesSupportingThePair.length) + " of them have exist=true", loggerSource);
3050
+ if (!exchangesSupportingThePair.length) {
3051
+ return {
3052
+ result: false,
3053
+ reason: SwapProvider.NO_SWAPS_REASONS.NOT_SUPPORTED
3054
+ };
3055
+ }
3056
+ var availableExchanges = exchangesSupportingThePair.filter(function (exchange) {
3057
+ return typeof (exchange == null ? void 0 : exchange.toAmount) === "number" && exchange.toAmount > 0;
3058
+ });
3059
+ Logger.log("Available (having amountTo): " + safeStringify(availableExchanges), loggerSource);
3060
+ // min=0 or max=0 means there is no limit for the partner
3061
+ var smallestMin = null;
3062
+ if (exchangesSupportingThePair.find(function (ex) {
3063
+ return bignumber_js.BigNumber(ex.min).isZero();
3064
+ }) == null) {
3065
+ smallestMin = exchangesSupportingThePair.reduce(function (prev, cur) {
3066
+ if (typeof cur.min === "number" && (prev === null || bignumber_js.BigNumber(cur.min).lt(prev))) return bignumber_js.BigNumber(cur.min);
3067
+ return prev;
3068
+ }, null);
3069
+ }
3070
+ var greatestMax = null;
3071
+ if (exchangesSupportingThePair.find(function (ex) {
3072
+ return bignumber_js.BigNumber(ex.max).isZero();
3073
+ }) == null) {
3074
+ greatestMax = exchangesSupportingThePair.reduce(function (prev, cur) {
3075
+ if (typeof cur.max === "number" && (prev === null || bignumber_js.BigNumber(cur.max).gt(prev))) return bignumber_js.BigNumber(cur.max);
3076
+ return prev;
3077
+ }, null);
3078
+ }
3079
+ var extraCoinsToFitMinMax = "0";
3080
+ if (typeof fromCoinToUsdRate === "string" && bignumber_js.BigNumber(fromCoinToUsdRate).gt("0")) {
3081
+ var extraUsdToFitMinMax = bignumber_js.BigNumber("1"); // We correct the limits as the exact limit can fluctuate and cause failed swap creation
3082
+ extraCoinsToFitMinMax = AmountUtils.trim(extraUsdToFitMinMax.div(fromCoinToUsdRate), fromCoin.digits);
3083
+ }
3084
+ if (smallestMin instanceof bignumber_js.BigNumber) {
3085
+ smallestMin = AmountUtils.trim(smallestMin.plus(extraCoinsToFitMinMax), fromCoin.digits);
3086
+ }
3087
+ if (greatestMax instanceof bignumber_js.BigNumber) {
3088
+ if (greatestMax > extraCoinsToFitMinMax) {
3089
+ greatestMax = AmountUtils.trim(greatestMax.minus(extraCoinsToFitMinMax), fromCoin.digits);
3090
+ } else {
3091
+ greatestMax = "0";
3092
+ }
3093
+ }
3094
+ if (availableExchanges.length) {
3095
+ var _bestOpt$duration;
3096
+ var sorted = availableExchanges.sort(function (op1, op2) {
3097
+ return op2.toAmount - op1.toAmount;
3098
+ });
3099
+ var bestOpt = sorted[0];
3100
+ Logger.log("Returning first option after sorting: " + safeStringify(bestOpt), loggerSource);
3101
+ var max = null;
3102
+ var min = null;
3103
+ if (extraCoinsToFitMinMax != null) {
3104
+ if (typeof bestOpt.max === "number" && bestOpt.max !== 0) {
3105
+ max = bignumber_js.BigNumber(bestOpt.max).minus(extraCoinsToFitMinMax);
3106
+ max = AmountUtils.trim(max.lt(0) ? "0" : max, fromCoin.digits);
3107
+ }
3108
+ if (typeof bestOpt.min === "number" && bestOpt.min !== 0) {
3109
+ min = AmountUtils.trim(bignumber_js.BigNumber(bestOpt.min).plus(extraCoinsToFitMinMax), fromCoin.digits);
3110
+ }
3111
+ }
3112
+ var rate = bestOpt.toAmount && bestOpt.fromAmount ? bignumber_js.BigNumber(bestOpt.toAmount).div(bestOpt.fromAmount) : null;
3113
+ return {
3114
+ result: true,
3115
+ min: min,
3116
+ max: max,
3117
+ smallestMin: smallestMin,
3118
+ greatestMax: greatestMax,
3119
+ rate: rate != null ? AmountUtils.trim(rate, _this7._maxRateDigits) : null,
3120
+ durationMinutesRange: (_bestOpt$duration = bestOpt.duration) != null ? _bestOpt$duration : null,
3121
+ rawSwapData: bestOpt
3122
+ };
3123
+ }
3124
+ var result = {
3125
+ result: false,
3126
+ reason: smallestMin && bignumber_js.BigNumber(amountCoins).lt(smallestMin) ? SwapProvider.NO_SWAPS_REASONS.TOO_LOW : greatestMax && bignumber_js.BigNumber(amountCoins).gt(greatestMax) ? SwapProvider.NO_SWAPS_REASONS.TOO_HIGH : SwapProvider.NO_SWAPS_REASONS.NOT_SUPPORTED,
3127
+ smallestMin: smallestMin,
3128
+ greatestMax: greatestMax
3129
+ };
3130
+ Logger.log("Returning result " + safeStringify(result), loggerSource);
3131
+ return result;
3132
+ });
3133
+ }, function (e) {
3134
+ var _e$response3;
3135
+ if ((e == null || (_e$response3 = e.response) == null ? void 0 : _e$response3.status) === 429) {
3136
+ return {
3137
+ result: false,
3138
+ reason: SwapProvider.COMMON_ERRORS.REQUESTS_LIMIT_EXCEEDED
3139
+ };
3140
+ }
3141
+ Logger.log("Internal swapspace/rabbit error when getting swap options " + safeStringify(e), loggerSource);
3142
+ improveAndRethrow(e, loggerSource);
3143
+ }));
3144
+ } catch (e) {
3145
+ return Promise.reject(e);
3146
+ }
3147
+ };
3148
+ _proto.createSwap = function createSwap(fromCoin, toCoin, amount, toAddress, refundAddress, rawSwapData, clientIpAddress) {
3149
+ try {
3150
+ var _this8 = this;
3151
+ var loggerSource = "createSwap";
3152
+ var partner = rawSwapData == null ? void 0 : rawSwapData.partner;
3153
+ return Promise.resolve(_catch(function () {
3154
+ if (!(fromCoin instanceof Coin) || !(toCoin instanceof Coin) || typeof amount !== "string" || typeof toAddress !== "string" || typeof refundAddress !== "string") {
3155
+ throw new Error("Invalid input: " + fromCoin + " " + toCoin + " " + amount + " " + toAddress + " " + refundAddress);
3156
+ }
3157
+ if (typeof partner !== "string" || typeof (rawSwapData == null ? void 0 : rawSwapData.fromCurrency) !== "string" || typeof (rawSwapData == null ? void 0 : rawSwapData.fromNetwork) !== "string" || typeof (rawSwapData == null ? void 0 : rawSwapData.toCurrency) !== "string" || typeof (rawSwapData == null ? void 0 : rawSwapData.toNetwork) !== "string" || typeof (rawSwapData == null ? void 0 : rawSwapData.id) !== "string" // can be just empty
3158
+ ) {
3159
+ throw new Error("Invalid raw swap data: " + safeStringify(rawSwapData));
3160
+ }
3161
+ return Promise.resolve(_this8._fetchSupportedCurrenciesIfNeeded()).then(function () {
3162
+ var _this8$_supportedCoin, _this8$_supportedCoin2;
3163
+ var toCurrencyExtraId = (_this8$_supportedCoin = (_this8$_supportedCoin2 = _this8._supportedCoins.find(function (item) {
3164
+ return item.coin === toCoin;
3165
+ })) == null ? void 0 : _this8$_supportedCoin2.extraId) != null ? _this8$_supportedCoin : "";
3166
+ var requestData = {
3167
+ partner: partner,
3168
+ fromCurrency: rawSwapData == null ? void 0 : rawSwapData.fromCurrency,
3169
+ fromNetwork: rawSwapData == null ? void 0 : rawSwapData.fromNetwork,
3170
+ toCurrency: rawSwapData == null ? void 0 : rawSwapData.toCurrency,
3171
+ toNetwork: rawSwapData == null ? void 0 : rawSwapData.toNetwork,
3172
+ address: toAddress,
3173
+ amount: amount,
3174
+ fixed: false,
3175
+ extraId: toCurrencyExtraId != null ? toCurrencyExtraId : "",
3176
+ rateId: rawSwapData == null ? void 0 : rawSwapData.id,
3177
+ userIp: clientIpAddress,
3178
+ refund: refundAddress
3179
+ };
3180
+ Logger.log("Sending create request: " + safeStringify(requestData), loggerSource);
3181
+ return Promise.resolve(axios__default["default"].post(_this8._URL + "/api/v2/exchange", requestData)).then(function (response) {
3182
+ var result = response.data;
3183
+ Logger.log("Creation result " + safeStringify(result), loggerSource);
3184
+ if (result != null && result.id) {
3185
+ var _result$from, _result$from2, _result$to, _result$to2, _result$from4, _result$from5, _result$to4, _result$to5;
3186
+ if (typeof (result == null || (_result$from = result.from) == null ? void 0 : _result$from.amount) !== "number" || typeof (result == null || (_result$from2 = result.from) == null ? void 0 : _result$from2.address) !== "string" || typeof (result == null || (_result$to = result.to) == null ? void 0 : _result$to.amount) !== "number" || typeof (result == null || (_result$to2 = result.to) == null ? void 0 : _result$to2.address) !== "string") throw new Error("Wrong swap creation result " + result);
3187
+ /* We use the returned rate preferably but if the retrieved
3188
+ * rate 0/null/undefined we calculate it manually */
3189
+ var rate = result.rate;
3190
+ if (typeof rate !== "number" || bignumber_js.BigNumber(rate).isZero()) {
3191
+ var _result$to3, _result$from3;
3192
+ rate = bignumber_js.BigNumber(result == null || (_result$to3 = result.to) == null ? void 0 : _result$to3.amount).div(result == null || (_result$from3 = result.from) == null ? void 0 : _result$from3.amount);
3193
+ } else {
3194
+ rate = bignumber_js.BigNumber(rate);
3195
+ }
3196
+ return {
3197
+ result: true,
3198
+ swapId: result == null ? void 0 : result.id,
3199
+ fromCoin: fromCoin,
3200
+ fromAmount: AmountUtils.trim(result == null || (_result$from4 = result.from) == null ? void 0 : _result$from4.amount, fromCoin.digits),
3201
+ fromAddress: result == null || (_result$from5 = result.from) == null ? void 0 : _result$from5.address,
3202
+ toCoin: toCoin,
3203
+ toAmount: AmountUtils.trim(result == null || (_result$to4 = result.to) == null ? void 0 : _result$to4.amount, toCoin.digits),
3204
+ toAddress: result == null || (_result$to5 = result.to) == null ? void 0 : _result$to5.address,
3205
+ rate: AmountUtils.trim(rate, _this8._maxRateDigits)
3206
+ };
3207
+ }
3208
+ var errorMessage = "Swap creation succeeded but the response is wrong: " + safeStringify(response);
3209
+ Logger.log(errorMessage, loggerSource);
3210
+ throw new Error(errorMessage);
3211
+ });
3212
+ });
3213
+ }, function (e) {
3214
+ var _e$response4, _e$response5;
3215
+ Logger.log("Failed to create swap. Error is: " + safeStringify(e), loggerSource);
3216
+ var composeFailResult = function composeFailResult(reason) {
3217
+ return {
3218
+ result: false,
3219
+ reason: reason,
3220
+ partner: partner
3221
+ };
3222
+ };
3223
+ var status = e == null || (_e$response4 = e.response) == null ? void 0 : _e$response4.status;
3224
+ var data = e == null || (_e$response5 = e.response) == null ? void 0 : _e$response5.data;
3225
+ if (status === 429) {
3226
+ Logger.log("Returning fail - RPS limit exceeded " + data, loggerSource);
3227
+ return composeFailResult(SwapProvider.COMMON_ERRORS.REQUESTS_LIMIT_EXCEEDED);
3228
+ }
3229
+ var texts422 = ["Pair cannot be processed by", "Currency not found", "Amount maximum is", "Amount minimum is"];
3230
+ var text403 = "IP address is forbidden";
3231
+ if (typeof data === "string" && (status === 403 && data.includes(text403) || status === 422 && texts422.find(function (text) {
3232
+ return data.includes(text);
3233
+ }))) {
3234
+ Logger.log("Returning retriable fail: " + status + " - " + data + ", " + partner, loggerSource);
3235
+ return composeFailResult(SwapProvider.CREATION_FAIL_REASONS.RETRIABLE_FAIL);
3236
+ }
3237
+ Logger.log("Internal swapspace/rabbit error for " + partner + ": " + safeStringify(e), loggerSource);
3238
+ improveAndRethrow(e, loggerSource);
3239
+ }));
3240
+ } catch (e) {
3241
+ return Promise.reject(e);
3242
+ }
3243
+ };
3244
+ _proto._mapSwapspaceStatusToRabbitStatus = function _mapSwapspaceStatusToRabbitStatus(status) {
3245
+ switch (status) {
3246
+ case "waiting":
3247
+ return SwapProvider.SWAP_STATUSES.WAITING_FOR_PAYMENT;
3248
+ case "confirming":
3249
+ return SwapProvider.SWAP_STATUSES.CONFIRMING;
3250
+ case "exchanging":
3251
+ return SwapProvider.SWAP_STATUSES.EXCHANGING;
3252
+ case "sending":
3253
+ return SwapProvider.SWAP_STATUSES.PAYMENT_RECEIVED;
3254
+ case "finished":
3255
+ return SwapProvider.SWAP_STATUSES.COMPLETED;
3256
+ case "verifying":
3257
+ return SwapProvider.SWAP_STATUSES.EXCHANGING;
3258
+ case "refunded":
3259
+ return SwapProvider.SWAP_STATUSES.REFUNDED;
3260
+ case "expired":
3261
+ return SwapProvider.SWAP_STATUSES.EXPIRED;
3262
+ case "failed":
3263
+ return SwapProvider.SWAP_STATUSES.FAILED;
3264
+ default:
3265
+ throw new Error("Unknown swapspace status: " + status);
3266
+ }
3267
+ };
3268
+ _proto.getExistingSwapsDetailsAndStatus = function getExistingSwapsDetailsAndStatus(swapIds) {
3269
+ try {
3270
+ var _this9 = this;
3271
+ var loggerSource = "getExistingSwapsDetailsAndStatus";
3272
+ return Promise.resolve(_catch(function () {
3273
+ if (swapIds.find(function (id) {
3274
+ return typeof id !== "string";
3275
+ })) {
3276
+ throw new Error("Swap id is not string: " + safeStringify(swapIds));
3277
+ }
3278
+ var getNotFailingOn404 = function getNotFailingOn404(swapId) {
3279
+ try {
3280
+ return Promise.resolve(_catch(function () {
3281
+ return Promise.resolve(axios__default["default"].get(_this9._URL + "/api/v2/exchange/" + swapId));
3282
+ }, function (error) {
3283
+ var _error$response;
3284
+ if ((error == null || (_error$response = error.response) == null ? void 0 : _error$response.status) === 404) return [];
3285
+ throw error;
3286
+ }));
3287
+ } catch (e) {
3288
+ return Promise.reject(e);
3289
+ }
3290
+ };
3291
+ return Promise.resolve(Promise.all(swapIds.map(function (swapId) {
3292
+ return getNotFailingOn404(swapId);
3293
+ }))).then(function (responses) {
3294
+ var wo404 = responses.flat();
3295
+ var swaps = wo404.map(function (r) {
3296
+ return r.data;
3297
+ }).map(function (swap, index) {
3298
+ var _this9$_supportedCoin, _this9$_supportedCoin2;
3299
+ var fromCoin = (_this9$_supportedCoin = _this9._supportedCoins.find(function (i) {
3300
+ return i.code === swap.from.code && i.network === swap.from.network;
3301
+ })) == null ? void 0 : _this9$_supportedCoin.coin;
3302
+ var toCoin = (_this9$_supportedCoin2 = _this9._supportedCoins.find(function (i) {
3303
+ return i.code === swap.to.code && i.network === swap.to.network;
3304
+ })) == null ? void 0 : _this9$_supportedCoin2.coin;
3305
+ if (!fromCoin || !toCoin) {
3306
+ return []; // We skip swaps with not supported coins for now
3307
+ }
3308
+ var status = _this9._mapSwapspaceStatusToRabbitStatus(swap.status);
3309
+ var toDigits = status === SwapProvider.SWAP_STATUSES.REFUNDED ? fromCoin.digits : toCoin.digits;
3310
+ var addressToSendCoinsToSwapspace = swap.from.address;
3311
+ var toUtcTimestamp = function toUtcTimestamp(timeStr) {
3312
+ return Date.parse(timeStr.match(/.+[Zz]$/) ? timeStr : timeStr + "Z");
3313
+ };
3314
+ return new ExistingSwap(swapIds[index], status, toUtcTimestamp(swap.timestamps.createdAt), toUtcTimestamp(swap.timestamps.expiresAt), swap.confirmations, AmountUtils.trim(swap.rate, _this9._maxRateDigits), swap.refundAddress, addressToSendCoinsToSwapspace, fromCoin, AmountUtils.trim(swap.from.amount, fromCoin.digits), swap.from.transactionHash, swap.blockExplorerTransactionUrl.from, toCoin, AmountUtils.trim(swap.to.amount, toDigits), swap.to.transactionHash, swap.blockExplorerTransactionUrl.to, swap.to.address, swap.partner);
3315
+ }).flat();
3316
+ Logger.log("Swap details result " + safeStringify(swaps), loggerSource);
3317
+ return {
3318
+ result: true,
3319
+ swaps: swaps
3320
+ };
3321
+ });
3322
+ }, function (e) {
3323
+ var _e$response6, _e$response7;
3324
+ Logger.log("Failed to get swap details. Error is: " + safeStringify(e), loggerSource);
3325
+ var composeFailResult = function composeFailResult(reason) {
3326
+ return {
3327
+ result: false,
3328
+ reason: reason
3329
+ };
3330
+ };
3331
+ var status = e == null || (_e$response6 = e.response) == null ? void 0 : _e$response6.status;
3332
+ var data = e == null || (_e$response7 = e.response) == null ? void 0 : _e$response7.data;
3333
+ if (status === 429) {
3334
+ Logger.log("Returning fail - RPS limit exceeded " + data, loggerSource);
3335
+ return composeFailResult(SwapProvider.COMMON_ERRORS.REQUESTS_LIMIT_EXCEEDED);
3336
+ }
3337
+ improveAndRethrow(e, loggerSource);
3338
+ }));
3339
+ } catch (e) {
3340
+ return Promise.reject(e);
3341
+ }
3342
+ };
3343
+ _proto.isAddressValidForAsset = function isAddressValidForAsset(asset, address) {
3344
+ try {
3345
+ var assetData = this._supportedCoins.find(function (i) {
3346
+ return i.coin === asset;
3347
+ });
3348
+ if (assetData) {
3349
+ var corrected = assetData.validationRegexp.trim();
3350
+ corrected = corrected[0] === "/" ? corrected.slice(1) : corrected;
3351
+ corrected = corrected[corrected.length - 1] === "/" ? corrected.slice(0, corrected.length - 1) : corrected;
3352
+ return address.match(corrected) != null;
3353
+ }
3354
+ } catch (e) {
3355
+ Logger.logError(e, "isAddressValidForAsset");
3356
+ }
3357
+ return false;
3358
+ };
3359
+ return SwapspaceSwapProvider;
3360
+ }(SwapProvider);
3361
+
1896
3362
  exports.AmountUtils = AmountUtils;
1897
3363
  exports.AssetIcon = AssetIcon;
3364
+ exports.Blockchain = Blockchain;
1898
3365
  exports.Button = Button;
3366
+ exports.Cache = Cache;
3367
+ exports.Coin = Coin;
3368
+ exports.ExistingSwap = ExistingSwap;
1899
3369
  exports.FiatCurrenciesService = FiatCurrenciesService;
1900
3370
  exports.LoadingDots = LoadingDots;
3371
+ exports.Logger = Logger;
3372
+ exports.LogsStorage = LogsStorage;
3373
+ exports.Protocol = Protocol;
1901
3374
  exports.SupportChat = SupportChat;
3375
+ exports.SwapProvider = SwapProvider;
3376
+ exports.SwapspaceSwapProvider = SwapspaceSwapProvider;
1902
3377
  exports.improveAndRethrow = improveAndRethrow;
3378
+ exports.safeStringify = safeStringify;
1903
3379
 
1904
3380
  }));
1905
3381
  //# sourceMappingURL=index.umd.js.map