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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  import React, { useState, useRef, useEffect } from 'react';
2
2
  import { BigNumber } from 'bignumber.js';
3
+ import axios from 'axios';
3
4
 
4
5
  function createCommonjsModule(fn) {
5
6
  var module = { exports: {} };
@@ -1568,6 +1569,18 @@ function _extends() {
1568
1569
  };
1569
1570
  return _extends.apply(this, arguments);
1570
1571
  }
1572
+ function _inheritsLoose(subClass, superClass) {
1573
+ subClass.prototype = Object.create(superClass.prototype);
1574
+ subClass.prototype.constructor = subClass;
1575
+ _setPrototypeOf(subClass, superClass);
1576
+ }
1577
+ function _setPrototypeOf(o, p) {
1578
+ _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
1579
+ o.__proto__ = p;
1580
+ return o;
1581
+ };
1582
+ return _setPrototypeOf(o, p);
1583
+ }
1571
1584
  function _unsupportedIterableToArray(o, minLen) {
1572
1585
  if (!o) return;
1573
1586
  if (typeof o === "string") return _arrayLikeToArray(o, minLen);
@@ -2487,6 +2500,40 @@ var Cache = /*#__PURE__*/function () {
2487
2500
  return Cache;
2488
2501
  }();
2489
2502
 
2503
+ function _catch$1(body, recover) {
2504
+ try {
2505
+ var result = body();
2506
+ } catch (e) {
2507
+ return recover(e);
2508
+ }
2509
+ if (result && result.then) {
2510
+ return result.then(void 0, recover);
2511
+ }
2512
+ return result;
2513
+ }
2514
+ var EmailsApi = /*#__PURE__*/function () {
2515
+ function EmailsApi() {}
2516
+ EmailsApi.sendEmail = function sendEmail(subject, body) {
2517
+ try {
2518
+ var _this = this;
2519
+ var _temp = _catch$1(function () {
2520
+ var url = window.location.protocol + "//" + window.location.host + "/api/v1/" + _this.serverEndpointEntity;
2521
+ return Promise.resolve(axios.post(url, {
2522
+ subject: subject,
2523
+ body: body
2524
+ })).then(function () {});
2525
+ }, function (e) {
2526
+ improveAndRethrow(e, "sendEmail", subject + body);
2527
+ });
2528
+ return Promise.resolve(_temp && _temp.then ? _temp.then(function () {}) : void 0);
2529
+ } catch (e) {
2530
+ return Promise.reject(e);
2531
+ }
2532
+ };
2533
+ return EmailsApi;
2534
+ }();
2535
+ EmailsApi.serverEndpointEntity = "emails";
2536
+
2490
2537
  var ExistingSwap =
2491
2538
  /**
2492
2539
  * @param swapId {string}
@@ -2528,6 +2575,81 @@ partner) {
2528
2575
  this.partner = partner;
2529
2576
  };
2530
2577
 
2578
+ var ExistingSwapWithFiatData = /*#__PURE__*/function (_ExistingSwap) {
2579
+ _inheritsLoose(ExistingSwapWithFiatData, _ExistingSwap);
2580
+ /**
2581
+ * @param swapId {string}
2582
+ * @param status {SwapProvider.SWAP_STATUSES}
2583
+ * @param createdAt {number}
2584
+ * @param expiresAt {number}
2585
+ * @param confirmations {number}
2586
+ * @param rate {string}
2587
+ * @param refundAddress {string}
2588
+ * @param fromCoin {Coin}
2589
+ * @param fromAmount {string}
2590
+ * @param fromTransactionId {string}
2591
+ * @param toCoin {Coin}
2592
+ * @param toAmount {string}
2593
+ * @param toTransactionId {string|null}
2594
+ * @param toAddress {string}
2595
+ * @param partner {string}
2596
+ * @param fromAmountFiat {number}
2597
+ * @param toAmountFiat {number}
2598
+ * @param fiatCurrencyCode {string}
2599
+ * @param fiatCurrencyDecimals {number}
2600
+ */
2601
+ function ExistingSwapWithFiatData(swapId, status, createdAt, expiresAt, confirmations, rate, refundAddress, payToAddress, fromCoin, fromAmount, fromTransactionId, fromTransactionLink, toCoin, toAmount, toTransactionId, toTransactionLink, toAddress, partner, fromAmountFiat, toAmountFiat, fiatCurrencyCode, fiatCurrencyDecimals) {
2602
+ var _this;
2603
+ _this = _ExistingSwap.call(this, swapId, status, createdAt, expiresAt, confirmations, rate, refundAddress, payToAddress, fromCoin, fromAmount, fromTransactionId, fromTransactionLink, toCoin, toAmount, toTransactionId, toTransactionLink, toAddress, partner) || this;
2604
+ _this.fromAmountFiat = fromAmountFiat;
2605
+ _this.toAmountFiat = toAmountFiat;
2606
+ _this.fiatCurrencyCode = fiatCurrencyCode;
2607
+ _this.fiatCurrencyDecimals = fiatCurrencyDecimals;
2608
+ return _this;
2609
+ }
2610
+
2611
+ /**
2612
+ * @param existingSwap {ExistingSwap}
2613
+ * @param fromAmountFiat {number}
2614
+ * @param toAmountFiat {number}
2615
+ * @param fiatCurrencyCode {string}
2616
+ * @param fiatCurrencyDecimals {number}
2617
+ * @return {ExistingSwapWithFiatData}
2618
+ */
2619
+ ExistingSwapWithFiatData.fromExistingSwap = function fromExistingSwap(existingSwap, fromAmountFiat, toAmountFiat, fiatCurrencyCode, fiatCurrencyDecimals) {
2620
+ return new ExistingSwapWithFiatData(existingSwap.swapId, existingSwap.status, existingSwap.createdAt, existingSwap.expiresAt, existingSwap.confirmations, existingSwap.rate, existingSwap.refundAddress, existingSwap.payToAddress, existingSwap.fromCoin, existingSwap.fromAmount, existingSwap.fromTransactionId, existingSwap.fromTransactionLink, existingSwap.toCoin, existingSwap.toAmount, existingSwap.toTransactionId, existingSwap.toTransactionLink, existingSwap.toAddress, existingSwap.partner, fromAmountFiat, toAmountFiat, fiatCurrencyCode, fiatCurrencyDecimals);
2621
+ };
2622
+ return ExistingSwapWithFiatData;
2623
+ }(ExistingSwap);
2624
+
2625
+ var PublicSwapCreationInfo =
2626
+ /**
2627
+ * @param fromCoin {Coin}
2628
+ * @param toCoin {Coin}
2629
+ * @param fromAmountCoins {string}
2630
+ * @param toAmountCoins {string}
2631
+ * @param rate {string}
2632
+ * @param rawSwapData {Object}
2633
+ * @param min {string}
2634
+ * @param fiatMin {number}
2635
+ * @param max {string}
2636
+ * @param fiatMax {number}
2637
+ * @param durationMinutesRange {string}
2638
+ */
2639
+ function PublicSwapCreationInfo(fromCoin, toCoin, fromAmountCoins, toAmountCoins, rate, rawSwapData, min, fiatMin, max, fiatMax, durationMinutesRange) {
2640
+ this.fromCoin = fromCoin;
2641
+ this.toCoin = toCoin;
2642
+ this.fromAmountCoins = fromAmountCoins;
2643
+ this.toAmountCoins = toAmountCoins;
2644
+ this.rate = rate;
2645
+ this.rawSwapData = rawSwapData;
2646
+ this.min = min;
2647
+ this.fiatMin = fiatMin;
2648
+ this.max = max;
2649
+ this.fiatMax = fiatMax;
2650
+ this.durationMinutesRange = durationMinutesRange;
2651
+ };
2652
+
2531
2653
  var SwapProvider = /*#__PURE__*/function () {
2532
2654
  function SwapProvider() {}
2533
2655
  var _proto = SwapProvider.prototype;
@@ -2731,5 +2853,614 @@ SwapProvider.SWAP_STATUSES = {
2731
2853
  FAILED: "failed" // public +
2732
2854
  };
2733
2855
 
2734
- export { AmountUtils, AssetIcon, Blockchain, Button, Cache, Coin, ExistingSwap, FiatCurrenciesService, LoadingDots, Logger, LogsStorage, Protocol, SupportChat, SwapProvider, improveAndRethrow, safeStringify };
2856
+ function _catch(body, recover) {
2857
+ try {
2858
+ var result = body();
2859
+ } catch (e) {
2860
+ return recover(e);
2861
+ }
2862
+ if (result && result.then) {
2863
+ return result.then(void 0, recover);
2864
+ }
2865
+ return result;
2866
+ }
2867
+ var BANNED_PARTNERS = ["stealthex", "changee", "coincraddle"];
2868
+ var FALLBACK_ICON_URL = "https://rabbit.io/asset-icons/fallback.svg";
2869
+ var SwapspaceSwapProvider = /*#__PURE__*/function (_SwapProvider) {
2870
+ _inheritsLoose(SwapspaceSwapProvider, _SwapProvider);
2871
+ function SwapspaceSwapProvider(apiKeysProxyUrl, cache, customCoinBuilder, useRestrictedCoinsSet) {
2872
+ var _this;
2873
+ if (customCoinBuilder === void 0) {
2874
+ customCoinBuilder = function customCoinBuilder(coin, network) {
2875
+ return null;
2876
+ };
2877
+ }
2878
+ if (useRestrictedCoinsSet === void 0) {
2879
+ useRestrictedCoinsSet = true;
2880
+ }
2881
+ _this = _SwapProvider.call(this) || this;
2882
+ _this._supportedCoins = [];
2883
+ _this._URL = apiKeysProxyUrl + "/swapspace";
2884
+ _this._maxRateDigits = 20;
2885
+ _this.useRestrictedCoinsSet = useRestrictedCoinsSet;
2886
+ _this._customCoinBuilder = customCoinBuilder;
2887
+ _this._cache = cache;
2888
+ return _this;
2889
+ }
2890
+ var _proto = SwapspaceSwapProvider.prototype;
2891
+ _proto.getSwapCreationInfoTtlMs = function getSwapCreationInfoTtlMs() {
2892
+ /* Actually 2 minutes and only relevant for some partners, but we use it
2893
+ * (and even a bit smaller value) for better consistency */
2894
+ return 110000;
2895
+ };
2896
+ _proto.getDepositCurrencies = function getDepositCurrencies() {
2897
+ try {
2898
+ var _this2 = this;
2899
+ var loggerSource = "getDepositCurrencies";
2900
+ return Promise.resolve(_catch(function () {
2901
+ return Promise.resolve(_this2._fetchSupportedCurrenciesIfNeeded()).then(function () {
2902
+ var _this2$_supportedCoin;
2903
+ Logger.log("We have " + ((_this2$_supportedCoin = _this2._supportedCoins) == null ? void 0 : _this2$_supportedCoin.length) + " supported coins, getting depositable", loggerSource);
2904
+ return {
2905
+ result: true,
2906
+ coins: _this2._supportedCoins.filter(function (item) {
2907
+ return item.deposit;
2908
+ }).map(function (item) {
2909
+ return item.coin;
2910
+ })
2911
+ };
2912
+ });
2913
+ }, function (e) {
2914
+ var _e$response;
2915
+ if ((e == null || (_e$response = e.response) == null ? void 0 : _e$response.status) === 429) {
2916
+ return {
2917
+ result: false,
2918
+ reason: SwapProvider.COMMON_ERRORS.REQUESTS_LIMIT_EXCEEDED
2919
+ };
2920
+ }
2921
+ improveAndRethrow(e, loggerSource);
2922
+ }));
2923
+ } catch (e) {
2924
+ return Promise.reject(e);
2925
+ }
2926
+ };
2927
+ _proto.getWithdrawalCurrencies = function getWithdrawalCurrencies(exceptCurrency) {
2928
+ if (exceptCurrency === void 0) {
2929
+ exceptCurrency = null;
2930
+ }
2931
+ try {
2932
+ var _this3 = this;
2933
+ var loggerSource = "getWithdrawalCurrencies";
2934
+ return Promise.resolve(_catch(function () {
2935
+ return Promise.resolve(_this3._fetchSupportedCurrenciesIfNeeded()).then(function () {
2936
+ var _this3$_supportedCoin;
2937
+ Logger.log("We have " + ((_this3$_supportedCoin = _this3._supportedCoins) == null ? void 0 : _this3$_supportedCoin.length) + " supported coins, getting withdrawable", loggerSource);
2938
+ return {
2939
+ result: true,
2940
+ coins: _this3._supportedCoins.filter(function (item) {
2941
+ return item.withdrawal && (!exceptCurrency || item.coin !== exceptCurrency);
2942
+ }).map(function (item) {
2943
+ return item.coin;
2944
+ })
2945
+ };
2946
+ });
2947
+ }, function (e) {
2948
+ var _e$response2;
2949
+ if ((e == null || (_e$response2 = e.response) == null ? void 0 : _e$response2.status) === 429) {
2950
+ return {
2951
+ result: false,
2952
+ reason: SwapProvider.COMMON_ERRORS.REQUESTS_LIMIT_EXCEEDED
2953
+ };
2954
+ }
2955
+ improveAndRethrow(e, loggerSource);
2956
+ }));
2957
+ } catch (e) {
2958
+ return Promise.reject(e);
2959
+ }
2960
+ };
2961
+ _proto.initialize = function initialize() {
2962
+ try {
2963
+ var _this4 = this;
2964
+ return Promise.resolve(_this4._fetchSupportedCurrenciesIfNeeded()).then(function () {});
2965
+ } catch (e) {
2966
+ return Promise.reject(e);
2967
+ }
2968
+ };
2969
+ _proto.getIconUrl = function getIconUrl(coinOrTicker) {
2970
+ var loggerSource = "getIconUrl";
2971
+ try {
2972
+ var _this$_supportedCoins2, _this$_supportedCoins3;
2973
+ var coin = coinOrTicker;
2974
+ if (!(coinOrTicker instanceof Coin)) {
2975
+ var _this$_supportedCoins;
2976
+ coin = (_this$_supportedCoins = this._supportedCoins.find(function (i) {
2977
+ return i.coin.ticker === coinOrTicker;
2978
+ })) == null ? void 0 : _this$_supportedCoins.coin;
2979
+ }
2980
+ return (_this$_supportedCoins2 = (_this$_supportedCoins3 = this._supportedCoins.find(function (item) {
2981
+ return item.coin === coin;
2982
+ })) == null ? void 0 : _this$_supportedCoins3.iconURL) != null ? _this$_supportedCoins2 : FALLBACK_ICON_URL;
2983
+ } catch (e) {
2984
+ improveAndRethrow(e, loggerSource);
2985
+ }
2986
+ };
2987
+ _proto._fetchSupportedCurrenciesIfNeeded = function _fetchSupportedCurrenciesIfNeeded() {
2988
+ try {
2989
+ var _this5 = this;
2990
+ var loggerSource = "_fetchSupportedCurrenciesIfNeeded";
2991
+ return Promise.resolve(_catch(function () {
2992
+ var _temp = function (_this5$_supportedCoin) {
2993
+ if (!((_this5$_supportedCoin = _this5._supportedCoins) != null && _this5$_supportedCoin.length)) {
2994
+ return Promise.resolve(axios.get(_this5._URL + "/api/v2/currencies")).then(function (rawResponse) {
2995
+ var _rawResponse$data, _rawResponse$data2;
2996
+ Logger.log("Retrieved " + (rawResponse == null || (_rawResponse$data = rawResponse.data) == null ? void 0 : _rawResponse$data.length) + " currencies", loggerSource);
2997
+ _this5._supportedCoins = ((_rawResponse$data2 = rawResponse == null ? void 0 : rawResponse.data) != null ? _rawResponse$data2 : []).map(function (item) {
2998
+ var coin = _this5._customCoinBuilder(item.code, item.network);
2999
+ if (!coin && !_this5.useRestrictedCoinsSet) {
3000
+ /** Building coin object for coin that isn't supported OOB in Rabbit.
3001
+ * We are doing this way to be able to use extended coins set for swaps.
3002
+ * These temporary built coins are only for in-swap use, and we omit some usual
3003
+ * coin details here.
3004
+ * Ideally we should add some new abstractions e.g. BaseCoin:
3005
+ * Coin will extend BaseCoin, SwapCoin will extend BaseCoin etc.
3006
+ * But for now it is reasonable to use this simpler approach.
3007
+ */
3008
+ var code = item.code.toUpperCase();
3009
+ var network = item.network.toUpperCase();
3010
+ var ticker = "" + code + (code === network ? "" : network);
3011
+ var defaultDecimalPlacesForCoinNotSupportedOOB = 8;
3012
+ var defaultMinConfirmationsForCoinNotSupportedOOB = 1;
3013
+ coin = new Coin(item.name, ticker, code, defaultDecimalPlacesForCoinNotSupportedOOB, null, "", null, null, defaultMinConfirmationsForCoinNotSupportedOOB, null, [], 60000, null,
3014
+ // We cannot recognize blockchain from swapspace data
3015
+ new Protocol(network),
3016
+ // TODO: [dev] maybe we should recognize standard protocols?
3017
+ item.contractAddress || null, false);
3018
+ }
3019
+ if (coin) {
3020
+ var _item$deposit, _item$withdrawal, _item$validationRegex;
3021
+ return {
3022
+ coin: coin,
3023
+ code: item.code,
3024
+ network: item.network,
3025
+ extraId: item.extraIdName,
3026
+ isPopular: !!(item != null && item.popular),
3027
+ iconURL: item.icon ? "https://storage.swapspace.co" + item.icon : FALLBACK_ICON_URL,
3028
+ deposit: (_item$deposit = item.deposit) != null ? _item$deposit : false,
3029
+ withdrawal: (_item$withdrawal = item.withdrawal) != null ? _item$withdrawal : false,
3030
+ validationRegexp: (_item$validationRegex = item.validationRegexp) != null ? _item$validationRegex : null
3031
+ };
3032
+ }
3033
+ return [];
3034
+ }).flat();
3035
+ _this5._putPopularCoinsFirst();
3036
+ });
3037
+ }
3038
+ }();
3039
+ if (_temp && _temp.then) return _temp.then(function () {});
3040
+ }, function (e) {
3041
+ improveAndRethrow(e, loggerSource);
3042
+ }));
3043
+ } catch (e) {
3044
+ return Promise.reject(e);
3045
+ }
3046
+ }
3047
+ /**
3048
+ * This method sort internal list putting popular (as swapspace thinks) coins to the top.
3049
+ * 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.
3050
+ * @private
3051
+ */
3052
+ ;
3053
+ _proto._putPopularCoinsFirst = function _putPopularCoinsFirst() {
3054
+ this._supportedCoins.sort(function (i1, i2) {
3055
+ if (i1.isPopular && !i2.isPopular) return -1;
3056
+ if (i2.isPopular && !i1.isPopular) return 1;
3057
+ return i1.coin.ticker > i2.coin.ticker ? 1 : i1.coin.ticker < i2.coin.ticker ? -1 : 0;
3058
+ });
3059
+ };
3060
+ _proto.getCoinToUSDTRate = function getCoinToUSDTRate(coin) {
3061
+ try {
3062
+ var _this6 = this;
3063
+ var loggerSource = "getCoinToUSDTRate";
3064
+ return Promise.resolve(_catch(function () {
3065
+ return Promise.resolve(_this6._fetchSupportedCurrenciesIfNeeded()).then(function () {
3066
+ var _this6$_supportedCoin;
3067
+ // Using USDT TRC20 as usually fee in this network is smaller than ERC20 and this network is widely used for USDT
3068
+ var usdtTrc20 = (_this6$_supportedCoin = _this6._supportedCoins.find(function (i) {
3069
+ return i.code === "usdt" && i.network === "trc20";
3070
+ })) == null ? void 0 : _this6$_supportedCoin.coin;
3071
+ if (!usdtTrc20) {
3072
+ return {
3073
+ result: false
3074
+ };
3075
+ }
3076
+ var cached = _this6._cache.get("swapspace_usdt_rate_" + coin.ticker);
3077
+ if (cached != null) {
3078
+ return {
3079
+ result: true,
3080
+ rate: cached
3081
+ };
3082
+ }
3083
+ Logger.log("Loading USDT -> coin rate as not found in cache:", coin == null ? void 0 : coin.ticker);
3084
+ return Promise.resolve(_this6.getSwapInfo(usdtTrc20, coin, "5000")).then(function (result) {
3085
+ if (!result.result) {
3086
+ return {
3087
+ result: false
3088
+ };
3089
+ }
3090
+
3091
+ // This calculation is not precise as we cannot recognize the actual fee and network fee. Just approximate.
3092
+ var standardSwapspaceFeeMultiplier = 1.002; // usually 0.2%
3093
+ var rate = BigNumber(1).div(BigNumber(result.rate).times(standardSwapspaceFeeMultiplier)).toString();
3094
+ _this6._cache.put("swapspace_usdt_rate_" + coin.ticker, rate, 15 * 60000);
3095
+ return {
3096
+ result: true,
3097
+ rate: rate
3098
+ };
3099
+ });
3100
+ });
3101
+ }, function (e) {
3102
+ improveAndRethrow(e, loggerSource);
3103
+ }));
3104
+ } catch (e) {
3105
+ return Promise.reject(e);
3106
+ }
3107
+ };
3108
+ _proto.getCoinByTickerIfPresent = function getCoinByTickerIfPresent(ticker) {
3109
+ try {
3110
+ var _item$coin;
3111
+ var item = this._supportedCoins.find(function (i) {
3112
+ return i.coin.ticker === ticker;
3113
+ });
3114
+ return (_item$coin = item == null ? void 0 : item.coin) != null ? _item$coin : null;
3115
+ } catch (e) {
3116
+ improveAndRethrow(e, "getCoinByTickerIfPresent");
3117
+ }
3118
+ };
3119
+ _proto.getSwapInfo = function getSwapInfo(fromCoin, toCoin, amountCoins, fromCoinToUsdRate) {
3120
+ if (fromCoinToUsdRate === void 0) {
3121
+ fromCoinToUsdRate = null;
3122
+ }
3123
+ try {
3124
+ var _this7 = this;
3125
+ var loggerSource = "getSwapInfo";
3126
+ return Promise.resolve(_catch(function () {
3127
+ if (!(fromCoin instanceof Coin) || !(toCoin instanceof Coin) || typeof amountCoins !== "string" || BigNumber(amountCoins).lt("0")) {
3128
+ throw new Error("Wrong input params: " + amountCoins + " " + fromCoin.ticker + " -> " + toCoin.ticker + (fromCoin instanceof Coin) + (toCoin instanceof Coin));
3129
+ }
3130
+ var fromCoinSwapspaceDetails = _this7._supportedCoins.find(function (i) {
3131
+ return i.coin === fromCoin;
3132
+ });
3133
+ var toCoinSwapspaceDetails = _this7._supportedCoins.find(function (i) {
3134
+ return i.coin === toCoin;
3135
+ });
3136
+ if (!fromCoinSwapspaceDetails || !toCoinSwapspaceDetails) {
3137
+ throw new Error("Failed to find swapspace coin details for: " + fromCoin.ticker + " -> " + toCoin.ticker);
3138
+ }
3139
+ /* Here we use not documented parameter 'estimated=false'. This parameter controls whether we want to use
3140
+ * cached rate values stored in swapspace cache. Their support says they store at most for 30 sec.
3141
+ * But we are better off using the most actual rates.
3142
+ */
3143
+ return Promise.resolve(axios.get(_this7._URL + "/api/v2/amounts?fromCurrency=" + fromCoinSwapspaceDetails.code + "&fromNetwork=" + fromCoinSwapspaceDetails.network + "&toNetwork=" + toCoinSwapspaceDetails.network + "&toCurrency=" + toCoinSwapspaceDetails.code + "&amount=" + amountCoins + "&float=true&estimated=false")).then(function (response) {
3144
+ var _response$data;
3145
+ Logger.log("Retrieved " + (response == null || (_response$data = response.data) == null ? void 0 : _response$data.length) + " options", loggerSource);
3146
+ var options = Array.isArray(response.data) ? response.data : [];
3147
+ var exchangesSupportingThePair = options.filter(function (exchange) {
3148
+ return (exchange == null ? void 0 : exchange.exists) && !BANNED_PARTNERS.find(function (bannedPartner) {
3149
+ return bannedPartner === (exchange == null ? void 0 : exchange.partner);
3150
+ }) && (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);
3151
+ });
3152
+ Logger.log((exchangesSupportingThePair == null ? void 0 : exchangesSupportingThePair.length) + " of them have exist=true", loggerSource);
3153
+ if (!exchangesSupportingThePair.length) {
3154
+ return {
3155
+ result: false,
3156
+ reason: SwapProvider.NO_SWAPS_REASONS.NOT_SUPPORTED
3157
+ };
3158
+ }
3159
+ var availableExchanges = exchangesSupportingThePair.filter(function (exchange) {
3160
+ return typeof (exchange == null ? void 0 : exchange.toAmount) === "number" && exchange.toAmount > 0;
3161
+ });
3162
+ Logger.log("Available (having amountTo): " + safeStringify(availableExchanges), loggerSource);
3163
+ // min=0 or max=0 means there is no limit for the partner
3164
+ var smallestMin = null;
3165
+ if (exchangesSupportingThePair.find(function (ex) {
3166
+ return BigNumber(ex.min).isZero();
3167
+ }) == null) {
3168
+ smallestMin = exchangesSupportingThePair.reduce(function (prev, cur) {
3169
+ if (typeof cur.min === "number" && (prev === null || BigNumber(cur.min).lt(prev))) return BigNumber(cur.min);
3170
+ return prev;
3171
+ }, null);
3172
+ }
3173
+ var greatestMax = null;
3174
+ if (exchangesSupportingThePair.find(function (ex) {
3175
+ return BigNumber(ex.max).isZero();
3176
+ }) == null) {
3177
+ greatestMax = exchangesSupportingThePair.reduce(function (prev, cur) {
3178
+ if (typeof cur.max === "number" && (prev === null || BigNumber(cur.max).gt(prev))) return BigNumber(cur.max);
3179
+ return prev;
3180
+ }, null);
3181
+ }
3182
+ var extraCoinsToFitMinMax = "0";
3183
+ if (typeof fromCoinToUsdRate === "string" && BigNumber(fromCoinToUsdRate).gt("0")) {
3184
+ var extraUsdToFitMinMax = BigNumber("1"); // We correct the limits as the exact limit can fluctuate and cause failed swap creation
3185
+ extraCoinsToFitMinMax = AmountUtils.trim(extraUsdToFitMinMax.div(fromCoinToUsdRate), fromCoin.digits);
3186
+ }
3187
+ if (smallestMin instanceof BigNumber) {
3188
+ smallestMin = AmountUtils.trim(smallestMin.plus(extraCoinsToFitMinMax), fromCoin.digits);
3189
+ }
3190
+ if (greatestMax instanceof BigNumber) {
3191
+ if (greatestMax > extraCoinsToFitMinMax) {
3192
+ greatestMax = AmountUtils.trim(greatestMax.minus(extraCoinsToFitMinMax), fromCoin.digits);
3193
+ } else {
3194
+ greatestMax = "0";
3195
+ }
3196
+ }
3197
+ if (availableExchanges.length) {
3198
+ var _bestOpt$duration;
3199
+ var sorted = availableExchanges.sort(function (op1, op2) {
3200
+ return op2.toAmount - op1.toAmount;
3201
+ });
3202
+ var bestOpt = sorted[0];
3203
+ Logger.log("Returning first option after sorting: " + safeStringify(bestOpt), loggerSource);
3204
+ var max = null;
3205
+ var min = null;
3206
+ if (extraCoinsToFitMinMax != null) {
3207
+ if (typeof bestOpt.max === "number" && bestOpt.max !== 0) {
3208
+ max = BigNumber(bestOpt.max).minus(extraCoinsToFitMinMax);
3209
+ max = AmountUtils.trim(max.lt(0) ? "0" : max, fromCoin.digits);
3210
+ }
3211
+ if (typeof bestOpt.min === "number" && bestOpt.min !== 0) {
3212
+ min = AmountUtils.trim(BigNumber(bestOpt.min).plus(extraCoinsToFitMinMax), fromCoin.digits);
3213
+ }
3214
+ }
3215
+ var rate = bestOpt.toAmount && bestOpt.fromAmount ? BigNumber(bestOpt.toAmount).div(bestOpt.fromAmount) : null;
3216
+ return {
3217
+ result: true,
3218
+ min: min,
3219
+ max: max,
3220
+ smallestMin: smallestMin,
3221
+ greatestMax: greatestMax,
3222
+ rate: rate != null ? AmountUtils.trim(rate, _this7._maxRateDigits) : null,
3223
+ durationMinutesRange: (_bestOpt$duration = bestOpt.duration) != null ? _bestOpt$duration : null,
3224
+ rawSwapData: bestOpt
3225
+ };
3226
+ }
3227
+ var result = {
3228
+ result: false,
3229
+ reason: smallestMin && BigNumber(amountCoins).lt(smallestMin) ? SwapProvider.NO_SWAPS_REASONS.TOO_LOW : greatestMax && BigNumber(amountCoins).gt(greatestMax) ? SwapProvider.NO_SWAPS_REASONS.TOO_HIGH : SwapProvider.NO_SWAPS_REASONS.NOT_SUPPORTED,
3230
+ smallestMin: smallestMin,
3231
+ greatestMax: greatestMax
3232
+ };
3233
+ Logger.log("Returning result " + safeStringify(result), loggerSource);
3234
+ return result;
3235
+ });
3236
+ }, function (e) {
3237
+ var _e$response3;
3238
+ if ((e == null || (_e$response3 = e.response) == null ? void 0 : _e$response3.status) === 429) {
3239
+ return {
3240
+ result: false,
3241
+ reason: SwapProvider.COMMON_ERRORS.REQUESTS_LIMIT_EXCEEDED
3242
+ };
3243
+ }
3244
+ Logger.log("Internal swapspace/rabbit error when getting swap options " + safeStringify(e), loggerSource);
3245
+ improveAndRethrow(e, loggerSource);
3246
+ }));
3247
+ } catch (e) {
3248
+ return Promise.reject(e);
3249
+ }
3250
+ };
3251
+ _proto.createSwap = function createSwap(fromCoin, toCoin, amount, toAddress, refundAddress, rawSwapData, clientIpAddress) {
3252
+ try {
3253
+ var _this8 = this;
3254
+ var loggerSource = "createSwap";
3255
+ var partner = rawSwapData == null ? void 0 : rawSwapData.partner;
3256
+ return Promise.resolve(_catch(function () {
3257
+ if (!(fromCoin instanceof Coin) || !(toCoin instanceof Coin) || typeof amount !== "string" || typeof toAddress !== "string" || typeof refundAddress !== "string") {
3258
+ throw new Error("Invalid input: " + fromCoin + " " + toCoin + " " + amount + " " + toAddress + " " + refundAddress);
3259
+ }
3260
+ 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
3261
+ ) {
3262
+ throw new Error("Invalid raw swap data: " + safeStringify(rawSwapData));
3263
+ }
3264
+ return Promise.resolve(_this8._fetchSupportedCurrenciesIfNeeded()).then(function () {
3265
+ var _this8$_supportedCoin, _this8$_supportedCoin2;
3266
+ var toCurrencyExtraId = (_this8$_supportedCoin = (_this8$_supportedCoin2 = _this8._supportedCoins.find(function (item) {
3267
+ return item.coin === toCoin;
3268
+ })) == null ? void 0 : _this8$_supportedCoin2.extraId) != null ? _this8$_supportedCoin : "";
3269
+ var requestData = {
3270
+ partner: partner,
3271
+ fromCurrency: rawSwapData == null ? void 0 : rawSwapData.fromCurrency,
3272
+ fromNetwork: rawSwapData == null ? void 0 : rawSwapData.fromNetwork,
3273
+ toCurrency: rawSwapData == null ? void 0 : rawSwapData.toCurrency,
3274
+ toNetwork: rawSwapData == null ? void 0 : rawSwapData.toNetwork,
3275
+ address: toAddress,
3276
+ amount: amount,
3277
+ fixed: false,
3278
+ extraId: toCurrencyExtraId != null ? toCurrencyExtraId : "",
3279
+ rateId: rawSwapData == null ? void 0 : rawSwapData.id,
3280
+ userIp: clientIpAddress,
3281
+ refund: refundAddress
3282
+ };
3283
+ Logger.log("Sending create request: " + safeStringify(requestData), loggerSource);
3284
+ return Promise.resolve(axios.post(_this8._URL + "/api/v2/exchange", requestData)).then(function (response) {
3285
+ var result = response.data;
3286
+ Logger.log("Creation result " + safeStringify(result), loggerSource);
3287
+ if (result != null && result.id) {
3288
+ var _result$from, _result$from2, _result$to, _result$to2, _result$from4, _result$from5, _result$to4, _result$to5;
3289
+ 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);
3290
+ /* We use the returned rate preferably but if the retrieved
3291
+ * rate 0/null/undefined we calculate it manually */
3292
+ var rate = result.rate;
3293
+ if (typeof rate !== "number" || BigNumber(rate).isZero()) {
3294
+ var _result$to3, _result$from3;
3295
+ rate = BigNumber(result == null || (_result$to3 = result.to) == null ? void 0 : _result$to3.amount).div(result == null || (_result$from3 = result.from) == null ? void 0 : _result$from3.amount);
3296
+ } else {
3297
+ rate = BigNumber(rate);
3298
+ }
3299
+ return {
3300
+ result: true,
3301
+ swapId: result == null ? void 0 : result.id,
3302
+ fromCoin: fromCoin,
3303
+ fromAmount: AmountUtils.trim(result == null || (_result$from4 = result.from) == null ? void 0 : _result$from4.amount, fromCoin.digits),
3304
+ fromAddress: result == null || (_result$from5 = result.from) == null ? void 0 : _result$from5.address,
3305
+ toCoin: toCoin,
3306
+ toAmount: AmountUtils.trim(result == null || (_result$to4 = result.to) == null ? void 0 : _result$to4.amount, toCoin.digits),
3307
+ toAddress: result == null || (_result$to5 = result.to) == null ? void 0 : _result$to5.address,
3308
+ rate: AmountUtils.trim(rate, _this8._maxRateDigits)
3309
+ };
3310
+ }
3311
+ var errorMessage = "Swap creation succeeded but the response is wrong: " + safeStringify(response);
3312
+ Logger.log(errorMessage, loggerSource);
3313
+ throw new Error(errorMessage);
3314
+ });
3315
+ });
3316
+ }, function (e) {
3317
+ var _e$response4, _e$response5;
3318
+ Logger.log("Failed to create swap. Error is: " + safeStringify(e), loggerSource);
3319
+ var composeFailResult = function composeFailResult(reason) {
3320
+ return {
3321
+ result: false,
3322
+ reason: reason,
3323
+ partner: partner
3324
+ };
3325
+ };
3326
+ var status = e == null || (_e$response4 = e.response) == null ? void 0 : _e$response4.status;
3327
+ var data = e == null || (_e$response5 = e.response) == null ? void 0 : _e$response5.data;
3328
+ if (status === 429) {
3329
+ Logger.log("Returning fail - RPS limit exceeded " + data, loggerSource);
3330
+ return composeFailResult(SwapProvider.COMMON_ERRORS.REQUESTS_LIMIT_EXCEEDED);
3331
+ }
3332
+ var texts422 = ["Pair cannot be processed by", "Currency not found", "Amount maximum is", "Amount minimum is"];
3333
+ var text403 = "IP address is forbidden";
3334
+ if (typeof data === "string" && (status === 403 && data.includes(text403) || status === 422 && texts422.find(function (text) {
3335
+ return data.includes(text);
3336
+ }))) {
3337
+ Logger.log("Returning retriable fail: " + status + " - " + data + ", " + partner, loggerSource);
3338
+ return composeFailResult(SwapProvider.CREATION_FAIL_REASONS.RETRIABLE_FAIL);
3339
+ }
3340
+ Logger.log("Internal swapspace/rabbit error for " + partner + ": " + safeStringify(e), loggerSource);
3341
+ improveAndRethrow(e, loggerSource);
3342
+ }));
3343
+ } catch (e) {
3344
+ return Promise.reject(e);
3345
+ }
3346
+ };
3347
+ _proto._mapSwapspaceStatusToRabbitStatus = function _mapSwapspaceStatusToRabbitStatus(status) {
3348
+ switch (status) {
3349
+ case "waiting":
3350
+ return SwapProvider.SWAP_STATUSES.WAITING_FOR_PAYMENT;
3351
+ case "confirming":
3352
+ return SwapProvider.SWAP_STATUSES.CONFIRMING;
3353
+ case "exchanging":
3354
+ return SwapProvider.SWAP_STATUSES.EXCHANGING;
3355
+ case "sending":
3356
+ return SwapProvider.SWAP_STATUSES.PAYMENT_RECEIVED;
3357
+ case "finished":
3358
+ return SwapProvider.SWAP_STATUSES.COMPLETED;
3359
+ case "verifying":
3360
+ return SwapProvider.SWAP_STATUSES.EXCHANGING;
3361
+ case "refunded":
3362
+ return SwapProvider.SWAP_STATUSES.REFUNDED;
3363
+ case "expired":
3364
+ return SwapProvider.SWAP_STATUSES.EXPIRED;
3365
+ case "failed":
3366
+ return SwapProvider.SWAP_STATUSES.FAILED;
3367
+ default:
3368
+ throw new Error("Unknown swapspace status: " + status);
3369
+ }
3370
+ };
3371
+ _proto.getExistingSwapsDetailsAndStatus = function getExistingSwapsDetailsAndStatus(swapIds) {
3372
+ try {
3373
+ var _this9 = this;
3374
+ var loggerSource = "getExistingSwapsDetailsAndStatus";
3375
+ return Promise.resolve(_catch(function () {
3376
+ if (swapIds.find(function (id) {
3377
+ return typeof id !== "string";
3378
+ })) {
3379
+ throw new Error("Swap id is not string: " + safeStringify(swapIds));
3380
+ }
3381
+ var getNotFailingOn404 = function getNotFailingOn404(swapId) {
3382
+ try {
3383
+ return Promise.resolve(_catch(function () {
3384
+ return Promise.resolve(axios.get(_this9._URL + "/api/v2/exchange/" + swapId));
3385
+ }, function (error) {
3386
+ var _error$response;
3387
+ if ((error == null || (_error$response = error.response) == null ? void 0 : _error$response.status) === 404) return [];
3388
+ throw error;
3389
+ }));
3390
+ } catch (e) {
3391
+ return Promise.reject(e);
3392
+ }
3393
+ };
3394
+ return Promise.resolve(Promise.all(swapIds.map(function (swapId) {
3395
+ return getNotFailingOn404(swapId);
3396
+ }))).then(function (responses) {
3397
+ var wo404 = responses.flat();
3398
+ var swaps = wo404.map(function (r) {
3399
+ return r.data;
3400
+ }).map(function (swap, index) {
3401
+ var _this9$_supportedCoin, _this9$_supportedCoin2;
3402
+ var fromCoin = (_this9$_supportedCoin = _this9._supportedCoins.find(function (i) {
3403
+ return i.code === swap.from.code && i.network === swap.from.network;
3404
+ })) == null ? void 0 : _this9$_supportedCoin.coin;
3405
+ var toCoin = (_this9$_supportedCoin2 = _this9._supportedCoins.find(function (i) {
3406
+ return i.code === swap.to.code && i.network === swap.to.network;
3407
+ })) == null ? void 0 : _this9$_supportedCoin2.coin;
3408
+ if (!fromCoin || !toCoin) {
3409
+ return []; // We skip swaps with not supported coins for now
3410
+ }
3411
+ var status = _this9._mapSwapspaceStatusToRabbitStatus(swap.status);
3412
+ var toDigits = status === SwapProvider.SWAP_STATUSES.REFUNDED ? fromCoin.digits : toCoin.digits;
3413
+ var addressToSendCoinsToSwapspace = swap.from.address;
3414
+ var toUtcTimestamp = function toUtcTimestamp(timeStr) {
3415
+ return Date.parse(timeStr.match(/.+[Zz]$/) ? timeStr : timeStr + "Z");
3416
+ };
3417
+ 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);
3418
+ }).flat();
3419
+ Logger.log("Swap details result " + safeStringify(swaps), loggerSource);
3420
+ return {
3421
+ result: true,
3422
+ swaps: swaps
3423
+ };
3424
+ });
3425
+ }, function (e) {
3426
+ var _e$response6, _e$response7;
3427
+ Logger.log("Failed to get swap details. Error is: " + safeStringify(e), loggerSource);
3428
+ var composeFailResult = function composeFailResult(reason) {
3429
+ return {
3430
+ result: false,
3431
+ reason: reason
3432
+ };
3433
+ };
3434
+ var status = e == null || (_e$response6 = e.response) == null ? void 0 : _e$response6.status;
3435
+ var data = e == null || (_e$response7 = e.response) == null ? void 0 : _e$response7.data;
3436
+ if (status === 429) {
3437
+ Logger.log("Returning fail - RPS limit exceeded " + data, loggerSource);
3438
+ return composeFailResult(SwapProvider.COMMON_ERRORS.REQUESTS_LIMIT_EXCEEDED);
3439
+ }
3440
+ improveAndRethrow(e, loggerSource);
3441
+ }));
3442
+ } catch (e) {
3443
+ return Promise.reject(e);
3444
+ }
3445
+ };
3446
+ _proto.isAddressValidForAsset = function isAddressValidForAsset(asset, address) {
3447
+ try {
3448
+ var assetData = this._supportedCoins.find(function (i) {
3449
+ return i.coin === asset;
3450
+ });
3451
+ if (assetData) {
3452
+ var corrected = assetData.validationRegexp.trim();
3453
+ corrected = corrected[0] === "/" ? corrected.slice(1) : corrected;
3454
+ corrected = corrected[corrected.length - 1] === "/" ? corrected.slice(0, corrected.length - 1) : corrected;
3455
+ return address.match(corrected) != null;
3456
+ }
3457
+ } catch (e) {
3458
+ Logger.logError(e, "isAddressValidForAsset");
3459
+ }
3460
+ return false;
3461
+ };
3462
+ return SwapspaceSwapProvider;
3463
+ }(SwapProvider);
3464
+
3465
+ export { AmountUtils, AssetIcon, Blockchain, Button, Cache, Coin, EmailsApi, ExistingSwap, ExistingSwapWithFiatData, FiatCurrenciesService, LoadingDots, Logger, LogsStorage, Protocol, PublicSwapCreationInfo, SupportChat, SwapProvider, SwapspaceSwapProvider, improveAndRethrow, safeStringify };
2735
3466
  //# sourceMappingURL=index.module.js.map