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

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.
@@ -1437,8 +1437,8 @@ var s = {"container":"_DYS-g","m-0":"_85R9d","p-0":"_wi0-U","m-1":"_YoewO","p-1"
1437
1437
 
1438
1438
  var AssetIcon = function AssetIcon(_ref) {
1439
1439
  var assetIconSrc = _ref.assetIconSrc,
1440
- _ref$assetIconProtoco = _ref.assetIconProtocolScr,
1441
- assetIconProtocolScr = _ref$assetIconProtoco === void 0 ? null : _ref$assetIconProtoco,
1440
+ _ref$assetIconProtoco = _ref.assetIconProtocolSrc,
1441
+ assetIconProtocolSrc = _ref$assetIconProtoco === void 0 ? null : _ref$assetIconProtoco,
1442
1442
  _ref$fallbackSrc = _ref.fallbackSrc,
1443
1443
  fallbackSrc = _ref$fallbackSrc === void 0 ? null : _ref$fallbackSrc,
1444
1444
  _ref$small = _ref.small,
@@ -1454,8 +1454,8 @@ var AssetIcon = function AssetIcon(_ref) {
1454
1454
  className: s["asset-icon-primary"] + (small ? " " + s["small"] : ""),
1455
1455
  alt: " ",
1456
1456
  onError: handleFailedLoad
1457
- }), assetIconProtocolScr ? /*#__PURE__*/React.createElement("img", {
1458
- src: assetIconProtocolScr,
1457
+ }), assetIconProtocolSrc ? /*#__PURE__*/React.createElement("img", {
1458
+ src: assetIconProtocolSrc,
1459
1459
  className: s["asset-icon-secondary"] + (small ? " " + s["small"] : ""),
1460
1460
  alt: " ",
1461
1461
  onError: handleFailedLoad
@@ -1463,12 +1463,12 @@ var AssetIcon = function AssetIcon(_ref) {
1463
1463
  };
1464
1464
  AssetIcon.propTypes = {
1465
1465
  assetIconSrc: PropTypes.string.isRequired,
1466
- assetIconProtocolScr: PropTypes.string,
1466
+ assetIconProtocolSrc: PropTypes.string,
1467
1467
  fallbackSrc: PropTypes.string,
1468
1468
  small: PropTypes.bool
1469
1469
  };
1470
1470
  AssetIcon.defaultProps = {
1471
- assetIconProtocolScr: null,
1471
+ assetIconProtocolSrc: null,
1472
1472
  fallbackSrc: null,
1473
1473
  small: false
1474
1474
  };
@@ -1568,6 +1568,37 @@ function _extends() {
1568
1568
  };
1569
1569
  return _extends.apply(this, arguments);
1570
1570
  }
1571
+ function _unsupportedIterableToArray(o, minLen) {
1572
+ if (!o) return;
1573
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
1574
+ var n = Object.prototype.toString.call(o).slice(8, -1);
1575
+ if (n === "Object" && o.constructor) n = o.constructor.name;
1576
+ if (n === "Map" || n === "Set") return Array.from(o);
1577
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
1578
+ }
1579
+ function _arrayLikeToArray(arr, len) {
1580
+ if (len == null || len > arr.length) len = arr.length;
1581
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
1582
+ return arr2;
1583
+ }
1584
+ function _createForOfIteratorHelperLoose(o, allowArrayLike) {
1585
+ var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
1586
+ if (it) return (it = it.call(o)).next.bind(it);
1587
+ if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
1588
+ if (it) o = it;
1589
+ var i = 0;
1590
+ return function () {
1591
+ if (i >= o.length) return {
1592
+ done: true
1593
+ };
1594
+ return {
1595
+ done: false,
1596
+ value: o[i++]
1597
+ };
1598
+ };
1599
+ }
1600
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1601
+ }
1571
1602
 
1572
1603
  // TODO: [dev] return addCommasToAmountString internal method to encapsulate commas adding
1573
1604
 
@@ -1887,5 +1918,818 @@ AmountUtils.defaultCryptoParams = {
1887
1918
  periods: true // Whether we add periods ("..") as suffix for trimmed numbers
1888
1919
  };
1889
1920
 
1890
- export { AmountUtils, AssetIcon, Button, FiatCurrenciesService, LoadingDots, SupportChat, improveAndRethrow };
1921
+ var Blockchain =
1922
+ /**
1923
+ * @param name {string} latin printable name of blockchain
1924
+ * @param supportedProtocols {Protocol[]}
1925
+ */
1926
+ function Blockchain(name, supportedProtocols) {
1927
+ if (supportedProtocols === void 0) {
1928
+ supportedProtocols = [];
1929
+ }
1930
+ this.name = name;
1931
+ this.supportedProtocols = supportedProtocols;
1932
+ };
1933
+
1934
+ var Protocol = function Protocol(protocolName) {
1935
+ this.protocol = protocolName;
1936
+ };
1937
+
1938
+ /**
1939
+ * The model for cryptocurrency coins.
1940
+ *
1941
+ * WARNING: this class should not be instantiated directly. Use only predefined singleton Coin (or descendants) instances.
1942
+ */
1943
+ var Coin = /*#__PURE__*/function () {
1944
+ /**
1945
+ * Creates new coin
1946
+ *
1947
+ * @param latinName {string} the coin name in latin symbols like "Bitcoin"
1948
+ * @param ticker {string} the coin symbol/ticker/code like 'BTC'. Always upper case. A unique coin identifier
1949
+ * @param tickerPrintable {string} ticker but in printable format. Useful for tokens based on external blockchains
1950
+ * like ERC20 or TRC20. It is not friendly to display USDTERC20 or BUSDTRC20 - more neat options are just
1951
+ * USDT and BUSD. Note that you should always care about user's understanding of what coin he/she is working
1952
+ * with as printable ticker for USDTERC20 and USDTTRC20 are the same.
1953
+ * @param digitsCountAfterComma {number} count of digits after the comma. E.g. 8 for bitcoin
1954
+ * @param maxValue {number|null} max possible value for cryptocurrency. Null means that the currency has no max possible value
1955
+ * @param atomName {string} name of the coin's atomic value. Like 'satoshi' for bitcoin
1956
+ * @param mainnet {Network} main network for this coin
1957
+ * @param testnet {Network} test network for this coin
1958
+ * @param minConfirmations {number} min confirmations count to treat the coin's transaction confirmed
1959
+ * @param payableEntityStringForFeeRate {string|null} the payable fee entity like byte for bitcoin or gas for ether if present
1960
+ * @param feeOptionsTimeStringsSortedDesc {string[]} array of 4 strings for fee options when sending coins. Should be sorted from the highest time to the smallest
1961
+ * @param feeRatesExpirationTimeMs {number} number of milliseconds to treat the fee rates as expired
1962
+ * @param blockchain {Blockchain} blockchain object
1963
+ * @param [protocol] {Protocol|null} token/coin protocol if relevant
1964
+ * @param [tokenAddress] {string|null} address of contract of this token (if the coin is token)
1965
+ * @param [doesUseLowerCaseAddresses] {boolean} flag to clarify whether we can use lower case addresses to ensure more robust comparisons
1966
+ * @param [doesUseOutputs=false] {boolean} true if this coin uses inputs/outputs concept and false if it uses just balances
1967
+ */
1968
+ function Coin(latinName, ticker, tickerPrintable, digitsCountAfterComma, maxValue, atomName, mainnet, testnet, minConfirmations, payableEntityStringForFeeRate, feeOptionsTimeStringsSortedDesc, feeRatesExpirationTimeMs, blockchain, protocol, tokenAddress, doesUseLowerCaseAddresses, doesUseOutputs) {
1969
+ if (protocol === void 0) {
1970
+ protocol = null;
1971
+ }
1972
+ if (tokenAddress === void 0) {
1973
+ tokenAddress = null;
1974
+ }
1975
+ if (doesUseLowerCaseAddresses === void 0) {
1976
+ doesUseLowerCaseAddresses = true;
1977
+ }
1978
+ if (doesUseOutputs === void 0) {
1979
+ doesUseOutputs = false;
1980
+ }
1981
+ this.latinName = latinName;
1982
+ this.ticker = ticker;
1983
+ this.tickerPrintable = tickerPrintable;
1984
+ this.digits = digitsCountAfterComma;
1985
+ this.maxValue = maxValue;
1986
+ this.atomName = atomName;
1987
+ this.mainnet = mainnet;
1988
+ this.testnet = testnet;
1989
+ this.minConfirmations = minConfirmations;
1990
+ this.payableEntityStringForFeeRate = payableEntityStringForFeeRate;
1991
+ this.feeOptionsTimeStringsSortedDesc = feeOptionsTimeStringsSortedDesc;
1992
+ this.feeRatesExpirationTimeMs = feeRatesExpirationTimeMs;
1993
+ this.protocol = protocol;
1994
+ this.blockchain = blockchain;
1995
+ // TODO: [bug, critical] use testnet property for testnet contract address as it blocks the app work in testnets
1996
+ this.tokenAddress = tokenAddress;
1997
+ this.feeCoin = this;
1998
+ this._significantDigits = 8;
1999
+ this.doesUseLowerCaseAddresses = doesUseLowerCaseAddresses;
2000
+ this.doesUseOutputs = doesUseOutputs;
2001
+ }
2002
+
2003
+ /**
2004
+ * Sets fee coin
2005
+ *
2006
+ * @param feeCoin {Coin} some tokens use another coin to charge transaction fee as they work on top of some external
2007
+ * blockchain. So pass here the coin the token uses for fee charging. Like for ERC20 token the fee coin is ETH.
2008
+ * By default, the creating coin will be set as a value for this field.
2009
+ */
2010
+ var _proto = Coin.prototype;
2011
+ _proto.setFeeCoin = function setFeeCoin(feeCoin) {
2012
+ this.feeCoin = feeCoin;
2013
+ }
2014
+
2015
+ /**
2016
+ * Checks whether this coin uses another coin (blockchain) to charge fee for transactions (means works on base of
2017
+ * some external blockchain).
2018
+ *
2019
+ * @return {boolean} true if this coin uses external blockchain to perform transactions and charge fee
2020
+ */;
2021
+ _proto.doesUseDifferentCoinFee = function doesUseDifferentCoinFee() {
2022
+ return this.feeCoin !== this;
2023
+ }
2024
+
2025
+ /**
2026
+ * Converts the given atoms string/number to string representing the same amount in coin itself - floating point number
2027
+ *
2028
+ * @param atoms {string} atoms positive integer amount
2029
+ * @return {string} coin amount floating point number as a string
2030
+ */;
2031
+ _proto.atomsToCoinAmount = function atomsToCoinAmount(atoms) {
2032
+ throw new Error("Not implemented in base Coin");
2033
+ }
2034
+
2035
+ /**
2036
+ * Converts the given coins amount string/number to string representing the same amount in coin atoms - integer number
2037
+ *
2038
+ * @param coinsAmount {string} coins positive floating point amount
2039
+ * @return {string} coin atoms amount integer number as a string
2040
+ */;
2041
+ _proto.coinAmountToAtoms = function coinAmountToAtoms(coinsAmount) {
2042
+ throw new Error("Not implemented in base Coin");
2043
+ }
2044
+
2045
+ /**
2046
+ * Composes URL to view the tx with given id in the external blockchain explorer
2047
+ *
2048
+ * @param txId {string} id of transaction
2049
+ * @return {string} URL string
2050
+ */;
2051
+ _proto.composeUrlToTransactionExplorer = function composeUrlToTransactionExplorer(txId) {
2052
+ throw new Error("Not implemented in base Coin");
2053
+ }
2054
+
2055
+ /**
2056
+ * Most of the cryptocurrencies has specific fee rate or fee price metric. This value usually has specific measure
2057
+ * like satoshi/byte or gWei/gas. This function adds the described denomination string to the given amount
2058
+ * as a suffix and returns the result string ready to be show to a user.
2059
+ *
2060
+ * @param coinAtomsString {string} coin atoms positive integer amount
2061
+ * @return {string} string of coin amount and fee rate units
2062
+ */;
2063
+ _proto.coinAtomsFeeRateToCommonlyUsedAmountFormatWithDenominationString = function coinAtomsFeeRateToCommonlyUsedAmountFormatWithDenominationString(coinAtomsString) {
2064
+ throw new Error("Not implemented in base Coin");
2065
+ }
2066
+
2067
+ /**
2068
+ * Check whether this coin support transaction prioritisation during the sending process.
2069
+ *
2070
+ * @return {boolean} true if support transaction prioritisation and false otherwise
2071
+ */;
2072
+ _proto.doesSupportTransactionPrioritisation = function doesSupportTransactionPrioritisation() {
2073
+ return Array.isArray(this.feeOptionsTimeStringsSortedDesc);
2074
+ };
2075
+ _proto.tickerAndProtocol = function tickerAndProtocol() {
2076
+ try {
2077
+ var _ref;
2078
+ return "" + this.tickerPrintable + (this.protocol ? (_ref = " " + this.protocol.protocol) != null ? _ref : "" : "");
2079
+ } catch (e) {
2080
+ improveAndRethrow(e, "tickerAndProtocol");
2081
+ }
2082
+ };
2083
+ return Coin;
2084
+ }();
2085
+
2086
+ var LogsStorage = /*#__PURE__*/function () {
2087
+ function LogsStorage() {}
2088
+ LogsStorage.saveLog = function saveLog(log) {
2089
+ this._inMemoryStorage.push(log);
2090
+ };
2091
+ LogsStorage.getInMemoryLogs = function getInMemoryLogs() {
2092
+ return this._inMemoryStorage;
2093
+ };
2094
+ LogsStorage.getAllLogs = function getAllLogs() {
2095
+ var storedLogs = "";
2096
+ if (typeof window !== "undefined") {
2097
+ storedLogs = localStorage.getItem(this._logsStorageId);
2098
+ }
2099
+ return storedLogs + "\n" + this._inMemoryStorage.join("\n");
2100
+ }
2101
+
2102
+ /**
2103
+ * @param logger {Logger}
2104
+ */;
2105
+ LogsStorage.saveToTheDisk = function saveToTheDisk(logger) {
2106
+ try {
2107
+ var MAX_LOCAL_STORAGE_VOLUME_BYTES = 5 * 1024 * 1024;
2108
+ var MAX_LOGS_STORAGE_BYTES = MAX_LOCAL_STORAGE_VOLUME_BYTES * 0.65;
2109
+ if (typeof window !== "undefined") {
2110
+ var existingLogs = localStorage.getItem(this._logsStorageId);
2111
+ var logsString = existingLogs + "\n" + this._inMemoryStorage.join("\n");
2112
+ var lettersCountToRemove = logsString.length - Math.round(MAX_LOGS_STORAGE_BYTES / 2);
2113
+ if (lettersCountToRemove > 0) {
2114
+ localStorage.setItem(this._logsStorageId, logsString.slice(lettersCountToRemove, logsString.length));
2115
+ } else {
2116
+ localStorage.setItem(this._logsStorageId, logsString);
2117
+ }
2118
+ this._inMemoryStorage = [];
2119
+ }
2120
+ } catch (e) {
2121
+ logger == null || logger.logError(e, "saveToTheDisk", "Failed to save logs to disk");
2122
+ }
2123
+ };
2124
+ LogsStorage.removeAllClientLogs = function removeAllClientLogs() {
2125
+ if (typeof window !== "undefined") {
2126
+ if (localStorage.getItem("doNotRemoveClientLogsWhenSignedOut") !== "true") {
2127
+ localStorage.removeItem(this._logsStorageId);
2128
+ }
2129
+ }
2130
+ this._inMemoryStorage = [];
2131
+ };
2132
+ LogsStorage.setDoNotRemoveClientLogsWhenSignedOut = function setDoNotRemoveClientLogsWhenSignedOut(value) {
2133
+ if (typeof window !== "undefined") {
2134
+ localStorage.setItem("doNotRemoveClientLogsWhenSignedOut", value);
2135
+ }
2136
+ };
2137
+ return LogsStorage;
2138
+ }();
2139
+ LogsStorage._inMemoryStorage = [];
2140
+ LogsStorage._logsStorageId = "clietnLogs_j203fj2D0n-d1";
2141
+
2142
+ /**
2143
+ * Stringify given object by use of JSON.stringify but handles circular structures and "response", "request" properties
2144
+ * to avoid stringing redundant data when printing errors containing request/response objects.
2145
+ *
2146
+ * @param object - object to be stringed
2147
+ * @param indent - custom indentation
2148
+ * @return {string} - stringed object
2149
+ */
2150
+ function safeStringify(object, indent) {
2151
+ if (indent === void 0) {
2152
+ indent = 2;
2153
+ }
2154
+ var cache = [];
2155
+ if (typeof object === "string" || typeof object === "function" || typeof object === "number" || typeof object === "undefined" || typeof object === "boolean") {
2156
+ return String(object);
2157
+ }
2158
+ var retVal = JSON.stringify(object, function (key, value) {
2159
+ if (key.toLowerCase().includes("request")) {
2160
+ return JSON.stringify({
2161
+ body: value == null ? void 0 : value.body,
2162
+ query: value == null ? void 0 : value.query,
2163
+ headers: value == null ? void 0 : value.headers
2164
+ });
2165
+ }
2166
+ if (key.toLowerCase().includes("response")) {
2167
+ return JSON.stringify({
2168
+ statusText: value == null ? void 0 : value.statusText,
2169
+ status: value == null ? void 0 : value.status,
2170
+ data: value == null ? void 0 : value.data,
2171
+ headers: value == null ? void 0 : value.headers
2172
+ });
2173
+ }
2174
+ return typeof value === "object" && value !== null ? cache.includes(value) ? "duplicated reference" // Duplicated references were found, discarding this key
2175
+ : cache.push(value) && value // Store value in our collection
2176
+ : value;
2177
+ }, indent);
2178
+ cache = null;
2179
+ return retVal;
2180
+ }
2181
+
2182
+ var Logger = /*#__PURE__*/function () {
2183
+ function Logger() {}
2184
+ /**
2185
+ * Logs to client logs storage.
2186
+ *
2187
+ * WARNING! this method should ce used carefully for critical logging as we have the restriction for storing logs
2188
+ * on client side as we store them inside the local storage. Please see details inside storage.js
2189
+ * @param logString {string} log string
2190
+ * @param source {string} source of the log entry
2191
+ */
2192
+ Logger.log = function log(logString, source) {
2193
+ var timestamp = new Date().toISOString();
2194
+ LogsStorage.saveLog(timestamp + "|" + source + ":" + logString);
2195
+ };
2196
+ Logger.logError = function logError(e, settingFunction, additionalMessage, onlyToConsole) {
2197
+ var _e$errorDescription, _e$howToFix;
2198
+ if (additionalMessage === void 0) {
2199
+ additionalMessage = "";
2200
+ }
2201
+ if (onlyToConsole === void 0) {
2202
+ onlyToConsole = false;
2203
+ }
2204
+ var message = "\nFunction call " + (settingFunction != null ? settingFunction : "") + " failed. Error message: " + (e == null ? void 0 : e.message) + ". " + additionalMessage + " ";
2205
+ 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. " : "");
2206
+ if (e != null && e.response) {
2207
+ try {
2208
+ var responseData = safeStringify({
2209
+ response: e.response
2210
+ });
2211
+ responseData && (message += "\n" + responseData + ". ");
2212
+ } catch (e) {}
2213
+ }
2214
+ var finalErrorText = message + ". " + safeStringify(e);
2215
+ // eslint-disable-next-line no-console
2216
+ console.error(finalErrorText);
2217
+ if (!onlyToConsole) {
2218
+ this.log(finalErrorText, "logError");
2219
+ }
2220
+ };
2221
+ return Logger;
2222
+ }();
2223
+
2224
+ /**
2225
+ * TODO: [tests, critical] Ued by payments logic
2226
+ *
2227
+ * Simple cache based on Map.
2228
+ * Provides ability to store event-dependent data.
2229
+ */
2230
+ var Cache = /*#__PURE__*/function () {
2231
+ /**
2232
+ * @param eventBus {EventBus} EventBus.js lib instance
2233
+ * @param [noSessionEvents=[]] {string[]} array of events that will be treated as "no session"
2234
+ */
2235
+ function Cache(eventBus, noSessionEvents) {
2236
+ if (noSessionEvents === void 0) {
2237
+ noSessionEvents = [];
2238
+ }
2239
+ this._cache = new Map();
2240
+ this._eventDependentDataKeys = [];
2241
+ this._noSessionEvents = noSessionEvents;
2242
+ this._eventBus = eventBus;
2243
+ }
2244
+ var _proto = Cache.prototype;
2245
+ _proto._setupIntervalClearingExpired = function _setupIntervalClearingExpired() {
2246
+ var cleaner = function cleaner() {
2247
+ try {
2248
+ for (var _iterator = _createForOfIteratorHelperLoose(this._cache.keys()), _step; !(_step = _iterator()).done;) {
2249
+ var key = _step.value;
2250
+ var item = this._cache.get(key);
2251
+ if (item && item.ttlMs && item.addedMsTimestamp + item.ttlMs < Date.now()) {
2252
+ this._cache["delete"](key);
2253
+ }
2254
+ }
2255
+ } catch (e) {
2256
+ improveAndRethrow(e, "_intervalClearingExpiredCache");
2257
+ }
2258
+ };
2259
+ cleaner = cleaner.bind(this);
2260
+ setInterval(cleaner, 1000);
2261
+ }
2262
+
2263
+ /**
2264
+ * Puts data to cache
2265
+ *
2266
+ * @param key {string} string key for this data
2267
+ * @param data {any} any data
2268
+ * @param ttlMs {number|null} optional milliseconds number for cache lifetime
2269
+ * @throws {Error} when the data is null/undefined because these values for data are reserved for internal logic
2270
+ */;
2271
+ _proto.put = function put(key, data, ttlMs) {
2272
+ if (ttlMs === void 0) {
2273
+ ttlMs = null;
2274
+ }
2275
+ try {
2276
+ if (typeof key !== "string" || data == null) {
2277
+ throw new Error("Trying to cache corrupted data: " + key + ", " + data);
2278
+ }
2279
+ this._cache.set(key, {
2280
+ data: data,
2281
+ addedMsTimestamp: Date.now(),
2282
+ ttlMs: ttlMs
2283
+ });
2284
+ } catch (e) {
2285
+ improveAndRethrow(e, "cache.put");
2286
+ }
2287
+ };
2288
+ _proto.putSessionDependentData = function putSessionDependentData(key, data, ttlMs) {
2289
+ if (ttlMs === void 0) {
2290
+ ttlMs = null;
2291
+ }
2292
+ this._putEventDependentData(key, data, this._noSessionEvents, ttlMs);
2293
+ }
2294
+
2295
+ /**
2296
+ * Puts data to cache and adds its key to list of keys that should be related by each of given events.
2297
+ *
2298
+ * @param key {string} key for cache
2299
+ * @param data {any} any caching data
2300
+ * @param events {string[]} list of events forcing putting data to be removed when triggered
2301
+ * @param ttlMs {|null} optional time to live for this cache item
2302
+ * @throws {Error} when the data is null/undefined because these values for data are reserved for internal logic
2303
+ */;
2304
+ _proto.putEventDependentData = function putEventDependentData(key, data, events, ttlMs) {
2305
+ if (ttlMs === void 0) {
2306
+ ttlMs = null;
2307
+ }
2308
+ this._putEventDependentData(key, data, events, ttlMs);
2309
+ };
2310
+ _proto._putEventDependentData = function _putEventDependentData(key, data, events, ttlMs) {
2311
+ var _this = this;
2312
+ if (ttlMs === void 0) {
2313
+ ttlMs = null;
2314
+ }
2315
+ try {
2316
+ if (typeof key !== "string" || data == null) {
2317
+ throw new Error("Trying to cache corrupted data: " + key + ", " + data);
2318
+ }
2319
+ this._cache.set(key, {
2320
+ data: data,
2321
+ addedMsTimestamp: Date.now(),
2322
+ ttlMs: ttlMs
2323
+ });
2324
+ var _loop = function _loop() {
2325
+ var event = _step2.value;
2326
+ var eventAndKeys = _this._eventDependentDataKeys.find(function (item) {
2327
+ return item[0] === event;
2328
+ });
2329
+ if (eventAndKeys) {
2330
+ eventAndKeys.push(key);
2331
+ } else {
2332
+ _this._eventDependentDataKeys.push([event, key]);
2333
+ _this._eventBus.addEventListener(event, function () {
2334
+ try {
2335
+ var keys = _this._eventDependentDataKeys.find(function (item) {
2336
+ return item[0] === event;
2337
+ });
2338
+ (keys != null ? keys : [event]).slice(1).forEach(function (key) {
2339
+ return _this._cache["delete"](key);
2340
+ });
2341
+ } catch (e) {
2342
+ Logger.logError(e, "cache.removing-for-event", "Event: " + event);
2343
+ }
2344
+ });
2345
+ }
2346
+ };
2347
+ for (var _iterator2 = _createForOfIteratorHelperLoose(events), _step2; !(_step2 = _iterator2()).done;) {
2348
+ _loop();
2349
+ }
2350
+ } catch (e) {
2351
+ improveAndRethrow(e, "cache.putEventDependentData");
2352
+ }
2353
+ }
2354
+
2355
+ // TODO: [feature, low] add clearing of expired data by schedule
2356
+ ;
2357
+ _proto.get = function get(key) {
2358
+ try {
2359
+ var item = this._cache.get(key);
2360
+ if (item) {
2361
+ if (item.addedMsTimestamp && item.ttlMs !== null && item.addedMsTimestamp + item.ttlMs < Date.now()) {
2362
+ this._cache["delete"](key);
2363
+ return null;
2364
+ } else {
2365
+ return item.data;
2366
+ }
2367
+ }
2368
+ return null;
2369
+ } catch (e) {
2370
+ improveAndRethrow(e, "cache.get");
2371
+ }
2372
+ };
2373
+ _proto.getLastUpdateTimestamp = function getLastUpdateTimestamp(key) {
2374
+ var _this$_cache$get$adde, _this$_cache$get;
2375
+ 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;
2376
+ }
2377
+
2378
+ /**
2379
+ * Updates the timestamp of the last update for specified key to the provided value.
2380
+ * Can be useful when TTL is controlled outside this class.
2381
+ *
2382
+ * @param key {string}
2383
+ * @param timestamp {number}
2384
+ * @return {boolean}
2385
+ */;
2386
+ _proto.setLastUpdateTimestamp = function setLastUpdateTimestamp(key, timestamp) {
2387
+ try {
2388
+ var item = this._cache.get(key);
2389
+ if (item != null && typeof timestamp === "number") {
2390
+ this._cache.set(key, _extends({}, item, {
2391
+ addedTimestampMs: timestamp
2392
+ }));
2393
+ return true;
2394
+ }
2395
+ return false;
2396
+ } catch (e) {
2397
+ improveAndRethrow("cache.setLastUpdateTimestamp");
2398
+ }
2399
+ };
2400
+ _proto.invalidate = function invalidate(key) {
2401
+ try {
2402
+ this._cache["delete"](key);
2403
+ } catch (e) {
2404
+ improveAndRethrow(e, "cache.invalidate");
2405
+ }
2406
+ };
2407
+ _proto.invalidateContaining = function invalidateContaining(keyPart) {
2408
+ if (typeof keyPart !== "string" || keyPart === "") {
2409
+ throw new Error("Trying to invalidate containing wrong key or empty key: " + keyPart);
2410
+ }
2411
+ try {
2412
+ var matchedKeys = Array.from(this._cache.keys()).filter(function (key) {
2413
+ return typeof key === "string" && new RegExp(keyPart).test(key);
2414
+ });
2415
+ for (var i = 0; i < matchedKeys.length; ++i) {
2416
+ this._cache["delete"](matchedKeys[i]);
2417
+ }
2418
+ } catch (e) {
2419
+ improveAndRethrow(e, "invalidateContaining");
2420
+ }
2421
+ };
2422
+ _proto.clear = function clear() {
2423
+ this._cache.clear();
2424
+ this._sessionDependentDataKeys = [];
2425
+ }
2426
+
2427
+ /**
2428
+ * Saves given data string to persistent cache.
2429
+ * NOTE: we have no TTL here, implement if needed.
2430
+ *
2431
+ * WARNING: use only when really needed and don't store big data as we use localStorage
2432
+ * under the hood and its capacity is restricted.
2433
+ *
2434
+ * @param uniqueKey {string} the key should be unique
2435
+ * @param data {string} only string data allowed
2436
+ */;
2437
+ _proto.putClientPersistentData = function putClientPersistentData(uniqueKey, data) {
2438
+ try {
2439
+ if (typeof window !== "undefined") {
2440
+ localStorage.setItem(uniqueKey, data);
2441
+ }
2442
+ } catch (e) {
2443
+ improveAndRethrow(e, "cache.putClientPersistentData");
2444
+ }
2445
+ }
2446
+
2447
+ /**
2448
+ * @param uniqueKey {string}
2449
+ * @return {string|null}
2450
+ */;
2451
+ _proto.getClientPersistentData = function getClientPersistentData(uniqueKey) {
2452
+ try {
2453
+ if (typeof window !== "undefined") {
2454
+ return localStorage.getItem(uniqueKey);
2455
+ }
2456
+ return null;
2457
+ } catch (e) {
2458
+ improveAndRethrow(e, "cache.getClientPersistentData");
2459
+ }
2460
+ }
2461
+
2462
+ /**
2463
+ * Only makes effect if the TTL is not null.
2464
+ *
2465
+ * @param key {string}
2466
+ * @param ttlMs {number|null}
2467
+ */;
2468
+ _proto.markCacheItemAsExpiredButDontRemove = function markCacheItemAsExpiredButDontRemove(key, ttlMs) {
2469
+ if (ttlMs === void 0) {
2470
+ ttlMs = null;
2471
+ }
2472
+ try {
2473
+ var _ttlMs;
2474
+ var item = this._cache.get(key);
2475
+ var ttlFinalMs = (_ttlMs = ttlMs) != null ? _ttlMs : item == null ? void 0 : item.ttlMs;
2476
+ if (item != null && ttlFinalMs) {
2477
+ this._cache.set(key, {
2478
+ data: item.data,
2479
+ addedMsTimestamp: Date.now() - ttlFinalMs - 1,
2480
+ ttlMs: ttlFinalMs
2481
+ });
2482
+ }
2483
+ } catch (e) {
2484
+ improveAndRethrow(e, "cache.markCacheItemAsExpiredButDontRemove");
2485
+ }
2486
+ };
2487
+ return Cache;
2488
+ }();
2489
+
2490
+ var ExistingSwap =
2491
+ /**
2492
+ * @param swapId {string}
2493
+ * @param status {SwapProvider.SWAP_STATUSES}
2494
+ * @param createdAt {number}
2495
+ * @param expiresAt {number}
2496
+ * @param confirmations {number}
2497
+ * @param rate {string}
2498
+ * @param refundAddress {string}
2499
+ * @param fromCoin {Coin}
2500
+ * @param fromAmount {string}
2501
+ * @param fromTransactionId {string}
2502
+ * @param toCoin {Coin}
2503
+ * @param toAmount {string}
2504
+ * @param toTransactionId {string|null}
2505
+ * @param toAddress {string}
2506
+ * @param partner {string}
2507
+ */
2508
+ function ExistingSwap(swapId, status, createdAt, expiresAt, confirmations, rate, refundAddress, payToAddress, fromCoin, fromAmount, fromTransactionId, fromTransactionLink, toCoin, toAmount, toTransactionId, toTransactionLink, toAddress,
2509
+ // TODO: [refactoring, moderate] toAddress is not quite clear. How about recipientAddress? task_id=0815a111c99543b78d374217eadbde4f
2510
+ partner) {
2511
+ this.swapId = swapId;
2512
+ this.status = status;
2513
+ this.createdAt = createdAt;
2514
+ this.expiresAt = expiresAt;
2515
+ this.confirmations = confirmations;
2516
+ this.rate = rate;
2517
+ this.refundAddress = refundAddress;
2518
+ this.payToAddress = payToAddress;
2519
+ this.fromCoin = fromCoin;
2520
+ this.fromTransactionId = fromTransactionId;
2521
+ this.fromAmount = fromAmount;
2522
+ this.fromTransactionLink = fromTransactionLink;
2523
+ this.toCoin = toCoin;
2524
+ this.toTransactionId = toTransactionId;
2525
+ this.toTransactionLink = toTransactionLink;
2526
+ this.toAmount = toAmount;
2527
+ this.toAddress = toAddress;
2528
+ this.partner = partner;
2529
+ };
2530
+
2531
+ var SwapProvider = /*#__PURE__*/function () {
2532
+ function SwapProvider() {}
2533
+ var _proto = SwapProvider.prototype;
2534
+ /**
2535
+ * @return {Promise<void>}
2536
+ */
2537
+ _proto.initialize = function initialize() {
2538
+ try {
2539
+ throw new Error("Not implemented in base");
2540
+ } catch (e) {
2541
+ return Promise.reject(e);
2542
+ }
2543
+ }
2544
+ /**
2545
+ * @return {number} milliseconds TTL
2546
+ */
2547
+ ;
2548
+ _proto.getSwapCreationInfoTtlMs = function getSwapCreationInfoTtlMs() {
2549
+ throw new Error("Not implemented in base");
2550
+ }
2551
+
2552
+ /**
2553
+ * Retrieves all deposit currencies supported by this swap provider.
2554
+ * Returns one of SwapProvider.COMMON_ERRORS in case of processable fail.
2555
+ *
2556
+ * @return {Promise<({ result: true, coins: Coin[] }|{ result: false, reason: string })>}
2557
+ */;
2558
+ _proto.getDepositCurrencies = function getDepositCurrencies() {
2559
+ try {
2560
+ throw new Error("Not implemented in base");
2561
+ } catch (e) {
2562
+ return Promise.reject(e);
2563
+ }
2564
+ }
2565
+ /**
2566
+ * Retrieves all withdrawable currencies supported by this swap provider.
2567
+ * Returns one of SwapProvider.COMMON_ERRORS in case of processable fail.
2568
+ *
2569
+ * @param [exceptCurrency=null] {Coin|null}
2570
+ * @return {Promise<({ result: true, coins: Coin[] }|{ result: false, reason: string })>}
2571
+ */
2572
+ ;
2573
+ _proto.getWithdrawalCurrencies = function getWithdrawalCurrencies(exceptCurrency) {
2574
+ try {
2575
+ throw new Error("Not implemented in base");
2576
+ } catch (e) {
2577
+ return Promise.reject(e);
2578
+ }
2579
+ }
2580
+ /**
2581
+ * Retrieves URL for coin icon or fallback if not found.
2582
+ *
2583
+ * @param coin {Coin|string} coin or rabbit-format of coin ticker
2584
+ * @return {string}
2585
+ */
2586
+ ;
2587
+ _proto.getIconUrl = function getIconUrl(coin) {
2588
+ throw new Error("Not implemented in base");
2589
+ }
2590
+
2591
+ /**
2592
+ * Retrieves coin to USDT rate.
2593
+ *
2594
+ * @param coin {Coin}
2595
+ * @return {{result: true, rate: string}|{result: false}}
2596
+ */;
2597
+ _proto.getCoinToUSDTRate = function getCoinToUSDTRate(coin) {
2598
+ try {
2599
+ throw new Error("Not implemented in base");
2600
+ } catch (e) {
2601
+ return Promise.reject(e);
2602
+ }
2603
+ }
2604
+ /**
2605
+ * Retrieves estimation for swapping giving coins amount.
2606
+ * null min or max signals there is no corresponding limitation. undefined means that the limits were not retrieved.
2607
+ * For fail result on of SwapProvider.NO_SWAPS_REASONS or SwapProvider.COMMON_ERRORS reasons will be returned.
2608
+ *
2609
+ * @param fromCoin {Coin}
2610
+ * @param toCoin {Coin}
2611
+ * @param amountCoins {string}
2612
+ * @param [fromCoinToUsdRate=null] pass if you want to increase the min amount returned
2613
+ * by provider with some fixed "insurance" amount to cover min amount fluctuations.
2614
+ * @return {Promise<({
2615
+ * result: false,
2616
+ * reason: string,
2617
+ * smallestMin: (string|null|undefined),
2618
+ * greatestMax: (string|null|undefined),
2619
+ * }|{
2620
+ * result: true,
2621
+ * min: (string|null),
2622
+ * max: (string|null),
2623
+ * smallestMin: (string|null),
2624
+ * greatestMax: (string|null),
2625
+ * rate: (string|null),
2626
+ * durationMinutesRange: string,
2627
+ * [rawSwapData]: Object
2628
+ * })>}
2629
+ */
2630
+ ;
2631
+ _proto.getSwapInfo = function getSwapInfo(fromCoin, toCoin, amountCoins, fromCoinToUsdRate) {
2632
+ try {
2633
+ throw new Error("Not implemented in base");
2634
+ } catch (e) {
2635
+ return Promise.reject(e);
2636
+ }
2637
+ }
2638
+ /**
2639
+ * For fail result we return one of SwapProvider.CREATION_FAIL_REASONS or SwapProvider.COMMON_ERRORS.
2640
+ *
2641
+ * @param fromCoin {Coin}
2642
+ * @param toCoin {Coin}
2643
+ * @param amount {string}
2644
+ * @param toAddress {string}
2645
+ * @param refundAddress {string}
2646
+ * @param rawSwapData {Object|null}
2647
+ * @param clientIpAddress {string}
2648
+ * @return {Promise<({
2649
+ * result: true,
2650
+ * swapId: string,
2651
+ * fromCoin: Coin,
2652
+ * fromAmount: string,
2653
+ * fromAddress: string,
2654
+ * toCoin: Coin,
2655
+ * toAmount: string,
2656
+ * toAddress: string,
2657
+ * rate: string
2658
+ * }|{
2659
+ * result: false,
2660
+ * reason: string,
2661
+ * partner: string
2662
+ * })>}
2663
+ */
2664
+ ;
2665
+ _proto.createSwap = function createSwap(fromCoin, toCoin, amount, toAddress, refundAddress, rawSwapData, clientIpAddress) {
2666
+ try {
2667
+ throw new Error("Not implemented in base");
2668
+ } catch (e) {
2669
+ return Promise.reject(e);
2670
+ }
2671
+ }
2672
+ /**
2673
+ * Retrieves details and status for swaps by given ids.
2674
+ * If some swap is not found by id then there is no item in return list.
2675
+ *
2676
+ * @param swapIds {string[]}
2677
+ * @return {Promise<{result: false, reason: string}|{result:true, swaps: ExistingSwap[]}>}
2678
+ */
2679
+ ;
2680
+ _proto.getExistingSwapsDetailsAndStatus = function getExistingSwapsDetailsAndStatus(swapIds) {
2681
+ try {
2682
+ throw new Error("Not implemented in base");
2683
+ } catch (e) {
2684
+ return Promise.reject(e);
2685
+ }
2686
+ }
2687
+ /**
2688
+ * @param ticker {string}
2689
+ * @return {Coin|null}
2690
+ */
2691
+ ;
2692
+ _proto.getCoinByTickerIfPresent = function getCoinByTickerIfPresent(ticker) {
2693
+ throw new Error("Not implemented in base");
2694
+ }
2695
+
2696
+ /**
2697
+ * @param asset {Coin}
2698
+ * @param address {string}
2699
+ * @return {boolean}
2700
+ */;
2701
+ _proto.isAddressValidForAsset = function isAddressValidForAsset(asset, address) {
2702
+ throw new Error("Not implemented in base");
2703
+ };
2704
+ return SwapProvider;
2705
+ }();
2706
+ SwapProvider.COMMON_ERRORS = {
2707
+ REQUESTS_LIMIT_EXCEEDED: "requestsLimitExceeded"
2708
+ };
2709
+ SwapProvider.NO_SWAPS_REASONS = {
2710
+ TOO_LOW: "tooLow",
2711
+ TOO_HIGH: "tooHigh",
2712
+ NOT_SUPPORTED: "notSupported"
2713
+ };
2714
+ SwapProvider.CREATION_FAIL_REASONS = {
2715
+ RETRIABLE_FAIL: "retriableFail"
2716
+ };
2717
+ SwapProvider.SWAP_STATUSES = {
2718
+ WAITING_FOR_PAYMENT: "waiting_for_payment",
2719
+ // public +
2720
+ CONFIRMING: "confirming",
2721
+ PAYMENT_RECEIVED: "payment_received",
2722
+ // public +
2723
+ EXCHANGING: "exchanging",
2724
+ // session full // public +
2725
+ COMPLETED: "completed",
2726
+ // session full // public +
2727
+ REFUNDED: "refunded",
2728
+ // session full // public +
2729
+ EXPIRED: "expired",
2730
+ // public +
2731
+ FAILED: "failed" // public +
2732
+ };
2733
+
2734
+ export { AmountUtils, AssetIcon, Blockchain, Button, Cache, Coin, ExistingSwap, FiatCurrenciesService, LoadingDots, Logger, LogsStorage, Protocol, SupportChat, SwapProvider, improveAndRethrow, safeStringify };
1891
2735
  //# sourceMappingURL=index.module.js.map