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