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