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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1,11 +1,12 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('bignumber.js')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'react', 'bignumber.js'], factory) :
4
- (global = global || self, factory(global.uiKit = {}, global.react, global.bignumber_js));
5
- })(this, (function (exports, React, bignumber_js) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('bignumber.js'), require('axios')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'react', 'bignumber.js', 'axios'], factory) :
4
+ (global = global || self, factory(global.uiKit = {}, global.react, global.bignumber_js, global.axios));
5
+ })(this, (function (exports, React, bignumber_js, axios) {
6
6
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
7
7
 
8
8
  var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
9
+ var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
9
10
 
10
11
  function createCommonjsModule(fn) {
11
12
  var module = { exports: {} };
@@ -1574,6 +1575,18 @@
1574
1575
  };
1575
1576
  return _extends.apply(this, arguments);
1576
1577
  }
1578
+ function _inheritsLoose(subClass, superClass) {
1579
+ subClass.prototype = Object.create(superClass.prototype);
1580
+ subClass.prototype.constructor = subClass;
1581
+ _setPrototypeOf(subClass, superClass);
1582
+ }
1583
+ function _setPrototypeOf(o, p) {
1584
+ _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
1585
+ o.__proto__ = p;
1586
+ return o;
1587
+ };
1588
+ return _setPrototypeOf(o, p);
1589
+ }
1577
1590
  function _unsupportedIterableToArray(o, minLen) {
1578
1591
  if (!o) return;
1579
1592
  if (typeof o === "string") return _arrayLikeToArray(o, minLen);
@@ -2737,6 +2750,615 @@
2737
2750
  FAILED: "failed" // public +
2738
2751
  };
2739
2752
 
2753
+ function _catch(body, recover) {
2754
+ try {
2755
+ var result = body();
2756
+ } catch (e) {
2757
+ return recover(e);
2758
+ }
2759
+ if (result && result.then) {
2760
+ return result.then(void 0, recover);
2761
+ }
2762
+ return result;
2763
+ }
2764
+ var BANNED_PARTNERS = ["stealthex", "changee", "coincraddle"];
2765
+ var FALLBACK_ICON_URL = "https://rabbit.io/asset-icons/fallback.svg";
2766
+ var SwapspaceSwapProvider = /*#__PURE__*/function (_SwapProvider) {
2767
+ _inheritsLoose(SwapspaceSwapProvider, _SwapProvider);
2768
+ function SwapspaceSwapProvider(apiKeysProxyUrl, cache, customCoinBuilder, useRestrictedCoinsSet) {
2769
+ var _this;
2770
+ if (customCoinBuilder === void 0) {
2771
+ customCoinBuilder = function customCoinBuilder(coin, network) {
2772
+ return null;
2773
+ };
2774
+ }
2775
+ if (useRestrictedCoinsSet === void 0) {
2776
+ useRestrictedCoinsSet = true;
2777
+ }
2778
+ _this = _SwapProvider.call(this) || this;
2779
+ _this._supportedCoins = [];
2780
+ _this._URL = apiKeysProxyUrl + "/swapspace";
2781
+ _this._maxRateDigits = 20;
2782
+ _this.useRestrictedCoinsSet = useRestrictedCoinsSet;
2783
+ _this._customCoinBuilder = customCoinBuilder;
2784
+ _this._cache = cache;
2785
+ return _this;
2786
+ }
2787
+ var _proto = SwapspaceSwapProvider.prototype;
2788
+ _proto.getSwapCreationInfoTtlMs = function getSwapCreationInfoTtlMs() {
2789
+ /* Actually 2 minutes and only relevant for some partners, but we use it
2790
+ * (and even a bit smaller value) for better consistency */
2791
+ return 110000;
2792
+ };
2793
+ _proto.getDepositCurrencies = function getDepositCurrencies() {
2794
+ try {
2795
+ var _this2 = this;
2796
+ var loggerSource = "getDepositCurrencies";
2797
+ return Promise.resolve(_catch(function () {
2798
+ return Promise.resolve(_this2._fetchSupportedCurrenciesIfNeeded()).then(function () {
2799
+ var _this2$_supportedCoin;
2800
+ Logger.log("We have " + ((_this2$_supportedCoin = _this2._supportedCoins) == null ? void 0 : _this2$_supportedCoin.length) + " supported coins, getting depositable", loggerSource);
2801
+ return {
2802
+ result: true,
2803
+ coins: _this2._supportedCoins.filter(function (item) {
2804
+ return item.deposit;
2805
+ }).map(function (item) {
2806
+ return item.coin;
2807
+ })
2808
+ };
2809
+ });
2810
+ }, function (e) {
2811
+ var _e$response;
2812
+ if ((e == null || (_e$response = e.response) == null ? void 0 : _e$response.status) === 429) {
2813
+ return {
2814
+ result: false,
2815
+ reason: SwapProvider.COMMON_ERRORS.REQUESTS_LIMIT_EXCEEDED
2816
+ };
2817
+ }
2818
+ improveAndRethrow(e, loggerSource);
2819
+ }));
2820
+ } catch (e) {
2821
+ return Promise.reject(e);
2822
+ }
2823
+ };
2824
+ _proto.getWithdrawalCurrencies = function getWithdrawalCurrencies(exceptCurrency) {
2825
+ if (exceptCurrency === void 0) {
2826
+ exceptCurrency = null;
2827
+ }
2828
+ try {
2829
+ var _this3 = this;
2830
+ var loggerSource = "getWithdrawalCurrencies";
2831
+ return Promise.resolve(_catch(function () {
2832
+ return Promise.resolve(_this3._fetchSupportedCurrenciesIfNeeded()).then(function () {
2833
+ var _this3$_supportedCoin;
2834
+ Logger.log("We have " + ((_this3$_supportedCoin = _this3._supportedCoins) == null ? void 0 : _this3$_supportedCoin.length) + " supported coins, getting withdrawable", loggerSource);
2835
+ return {
2836
+ result: true,
2837
+ coins: _this3._supportedCoins.filter(function (item) {
2838
+ return item.withdrawal && (!exceptCurrency || item.coin !== exceptCurrency);
2839
+ }).map(function (item) {
2840
+ return item.coin;
2841
+ })
2842
+ };
2843
+ });
2844
+ }, function (e) {
2845
+ var _e$response2;
2846
+ if ((e == null || (_e$response2 = e.response) == null ? void 0 : _e$response2.status) === 429) {
2847
+ return {
2848
+ result: false,
2849
+ reason: SwapProvider.COMMON_ERRORS.REQUESTS_LIMIT_EXCEEDED
2850
+ };
2851
+ }
2852
+ improveAndRethrow(e, loggerSource);
2853
+ }));
2854
+ } catch (e) {
2855
+ return Promise.reject(e);
2856
+ }
2857
+ };
2858
+ _proto.initialize = function initialize() {
2859
+ try {
2860
+ var _this4 = this;
2861
+ return Promise.resolve(_this4._fetchSupportedCurrenciesIfNeeded()).then(function () {});
2862
+ } catch (e) {
2863
+ return Promise.reject(e);
2864
+ }
2865
+ };
2866
+ _proto.getIconUrl = function getIconUrl(coinOrTicker) {
2867
+ var loggerSource = "getIconUrl";
2868
+ try {
2869
+ var _this$_supportedCoins2, _this$_supportedCoins3;
2870
+ var coin = coinOrTicker;
2871
+ if (!(coinOrTicker instanceof Coin)) {
2872
+ var _this$_supportedCoins;
2873
+ coin = (_this$_supportedCoins = this._supportedCoins.find(function (i) {
2874
+ return i.coin.ticker === coinOrTicker;
2875
+ })) == null ? void 0 : _this$_supportedCoins.coin;
2876
+ }
2877
+ return (_this$_supportedCoins2 = (_this$_supportedCoins3 = this._supportedCoins.find(function (item) {
2878
+ return item.coin === coin;
2879
+ })) == null ? void 0 : _this$_supportedCoins3.iconURL) != null ? _this$_supportedCoins2 : FALLBACK_ICON_URL;
2880
+ } catch (e) {
2881
+ improveAndRethrow(e, loggerSource);
2882
+ }
2883
+ };
2884
+ _proto._fetchSupportedCurrenciesIfNeeded = function _fetchSupportedCurrenciesIfNeeded() {
2885
+ try {
2886
+ var _this5 = this;
2887
+ var loggerSource = "_fetchSupportedCurrenciesIfNeeded";
2888
+ return Promise.resolve(_catch(function () {
2889
+ var _temp = function (_this5$_supportedCoin) {
2890
+ if (!((_this5$_supportedCoin = _this5._supportedCoins) != null && _this5$_supportedCoin.length)) {
2891
+ return Promise.resolve(axios__default["default"].get(_this5._URL + "/api/v2/currencies")).then(function (rawResponse) {
2892
+ var _rawResponse$data, _rawResponse$data2;
2893
+ Logger.log("Retrieved " + (rawResponse == null || (_rawResponse$data = rawResponse.data) == null ? void 0 : _rawResponse$data.length) + " currencies", loggerSource);
2894
+ _this5._supportedCoins = ((_rawResponse$data2 = rawResponse == null ? void 0 : rawResponse.data) != null ? _rawResponse$data2 : []).map(function (item) {
2895
+ var coin = _this5._customCoinBuilder(item.code, item.network);
2896
+ if (!coin && !_this5.useRestrictedCoinsSet) {
2897
+ /** Building coin object for coin that isn't supported OOB in Rabbit.
2898
+ * We are doing this way to be able to use extended coins set for swaps.
2899
+ * These temporary built coins are only for in-swap use, and we omit some usual
2900
+ * coin details here.
2901
+ * Ideally we should add some new abstractions e.g. BaseCoin:
2902
+ * Coin will extend BaseCoin, SwapCoin will extend BaseCoin etc.
2903
+ * But for now it is reasonable to use this simpler approach.
2904
+ */
2905
+ var code = item.code.toUpperCase();
2906
+ var network = item.network.toUpperCase();
2907
+ var ticker = "" + code + (code === network ? "" : network);
2908
+ var defaultDecimalPlacesForCoinNotSupportedOOB = 8;
2909
+ var defaultMinConfirmationsForCoinNotSupportedOOB = 1;
2910
+ coin = new Coin(item.name, ticker, code, defaultDecimalPlacesForCoinNotSupportedOOB, null, "", null, null, defaultMinConfirmationsForCoinNotSupportedOOB, null, [], 60000, null,
2911
+ // We cannot recognize blockchain from swapspace data
2912
+ new Protocol(network),
2913
+ // TODO: [dev] maybe we should recognize standard protocols?
2914
+ item.contractAddress || null, false);
2915
+ }
2916
+ if (coin) {
2917
+ var _item$deposit, _item$withdrawal, _item$validationRegex;
2918
+ return {
2919
+ coin: coin,
2920
+ code: item.code,
2921
+ network: item.network,
2922
+ extraId: item.extraIdName,
2923
+ isPopular: !!(item != null && item.popular),
2924
+ iconURL: item.icon ? "https://storage.swapspace.co" + item.icon : FALLBACK_ICON_URL,
2925
+ deposit: (_item$deposit = item.deposit) != null ? _item$deposit : false,
2926
+ withdrawal: (_item$withdrawal = item.withdrawal) != null ? _item$withdrawal : false,
2927
+ validationRegexp: (_item$validationRegex = item.validationRegexp) != null ? _item$validationRegex : null
2928
+ };
2929
+ }
2930
+ return [];
2931
+ }).flat();
2932
+ _this5._putPopularCoinsFirst();
2933
+ });
2934
+ }
2935
+ }();
2936
+ if (_temp && _temp.then) return _temp.then(function () {});
2937
+ }, function (e) {
2938
+ improveAndRethrow(e, loggerSource);
2939
+ }));
2940
+ } catch (e) {
2941
+ return Promise.reject(e);
2942
+ }
2943
+ }
2944
+ /**
2945
+ * This method sort internal list putting popular (as swapspace thinks) coins to the top.
2946
+ * This is just for users of this API if they don't care about the sorting - we just improve a list a bit this way.
2947
+ * @private
2948
+ */
2949
+ ;
2950
+ _proto._putPopularCoinsFirst = function _putPopularCoinsFirst() {
2951
+ this._supportedCoins.sort(function (i1, i2) {
2952
+ if (i1.isPopular && !i2.isPopular) return -1;
2953
+ if (i2.isPopular && !i1.isPopular) return 1;
2954
+ return i1.coin.ticker > i2.coin.ticker ? 1 : i1.coin.ticker < i2.coin.ticker ? -1 : 0;
2955
+ });
2956
+ };
2957
+ _proto.getCoinToUSDTRate = function getCoinToUSDTRate(coin) {
2958
+ try {
2959
+ var _this6 = this;
2960
+ var loggerSource = "getCoinToUSDTRate";
2961
+ return Promise.resolve(_catch(function () {
2962
+ return Promise.resolve(_this6._fetchSupportedCurrenciesIfNeeded()).then(function () {
2963
+ var _this6$_supportedCoin;
2964
+ // Using USDT TRC20 as usually fee in this network is smaller than ERC20 and this network is widely used for USDT
2965
+ var usdtTrc20 = (_this6$_supportedCoin = _this6._supportedCoins.find(function (i) {
2966
+ return i.code === "usdt" && i.network === "trc20";
2967
+ })) == null ? void 0 : _this6$_supportedCoin.coin;
2968
+ if (!usdtTrc20) {
2969
+ return {
2970
+ result: false
2971
+ };
2972
+ }
2973
+ var cached = _this6._cache.get("swapspace_usdt_rate_" + coin.ticker);
2974
+ if (cached != null) {
2975
+ return {
2976
+ result: true,
2977
+ rate: cached
2978
+ };
2979
+ }
2980
+ Logger.log("Loading USDT -> coin rate as not found in cache:", coin == null ? void 0 : coin.ticker);
2981
+ return Promise.resolve(_this6.getSwapInfo(usdtTrc20, coin, "5000")).then(function (result) {
2982
+ if (!result.result) {
2983
+ return {
2984
+ result: false
2985
+ };
2986
+ }
2987
+
2988
+ // This calculation is not precise as we cannot recognize the actual fee and network fee. Just approximate.
2989
+ var standardSwapspaceFeeMultiplier = 1.002; // usually 0.2%
2990
+ var rate = bignumber_js.BigNumber(1).div(bignumber_js.BigNumber(result.rate).times(standardSwapspaceFeeMultiplier)).toString();
2991
+ _this6._cache.put("swapspace_usdt_rate_" + coin.ticker, rate, 15 * 60000);
2992
+ return {
2993
+ result: true,
2994
+ rate: rate
2995
+ };
2996
+ });
2997
+ });
2998
+ }, function (e) {
2999
+ improveAndRethrow(e, loggerSource);
3000
+ }));
3001
+ } catch (e) {
3002
+ return Promise.reject(e);
3003
+ }
3004
+ };
3005
+ _proto.getCoinByTickerIfPresent = function getCoinByTickerIfPresent(ticker) {
3006
+ try {
3007
+ var _item$coin;
3008
+ var item = this._supportedCoins.find(function (i) {
3009
+ return i.coin.ticker === ticker;
3010
+ });
3011
+ return (_item$coin = item == null ? void 0 : item.coin) != null ? _item$coin : null;
3012
+ } catch (e) {
3013
+ improveAndRethrow(e, "getCoinByTickerIfPresent");
3014
+ }
3015
+ };
3016
+ _proto.getSwapInfo = function getSwapInfo(fromCoin, toCoin, amountCoins, fromCoinToUsdRate) {
3017
+ if (fromCoinToUsdRate === void 0) {
3018
+ fromCoinToUsdRate = null;
3019
+ }
3020
+ try {
3021
+ var _this7 = this;
3022
+ var loggerSource = "getSwapInfo";
3023
+ return Promise.resolve(_catch(function () {
3024
+ if (!(fromCoin instanceof Coin) || !(toCoin instanceof Coin) || typeof amountCoins !== "string" || bignumber_js.BigNumber(amountCoins).lt("0")) {
3025
+ throw new Error("Wrong input params: " + amountCoins + " " + fromCoin.ticker + " -> " + toCoin.ticker + (fromCoin instanceof Coin) + (toCoin instanceof Coin));
3026
+ }
3027
+ var fromCoinSwapspaceDetails = _this7._supportedCoins.find(function (i) {
3028
+ return i.coin === fromCoin;
3029
+ });
3030
+ var toCoinSwapspaceDetails = _this7._supportedCoins.find(function (i) {
3031
+ return i.coin === toCoin;
3032
+ });
3033
+ if (!fromCoinSwapspaceDetails || !toCoinSwapspaceDetails) {
3034
+ throw new Error("Failed to find swapspace coin details for: " + fromCoin.ticker + " -> " + toCoin.ticker);
3035
+ }
3036
+ /* Here we use not documented parameter 'estimated=false'. This parameter controls whether we want to use
3037
+ * cached rate values stored in swapspace cache. Their support says they store at most for 30 sec.
3038
+ * But we are better off using the most actual rates.
3039
+ */
3040
+ return Promise.resolve(axios__default["default"].get(_this7._URL + "/api/v2/amounts?fromCurrency=" + fromCoinSwapspaceDetails.code + "&fromNetwork=" + fromCoinSwapspaceDetails.network + "&toNetwork=" + toCoinSwapspaceDetails.network + "&toCurrency=" + toCoinSwapspaceDetails.code + "&amount=" + amountCoins + "&float=true&estimated=false")).then(function (response) {
3041
+ var _response$data;
3042
+ Logger.log("Retrieved " + (response == null || (_response$data = response.data) == null ? void 0 : _response$data.length) + " options", loggerSource);
3043
+ var options = Array.isArray(response.data) ? response.data : [];
3044
+ var exchangesSupportingThePair = options.filter(function (exchange) {
3045
+ return (exchange == null ? void 0 : exchange.exists) && !BANNED_PARTNERS.find(function (bannedPartner) {
3046
+ return bannedPartner === (exchange == null ? void 0 : exchange.partner);
3047
+ }) && (exchange == null ? void 0 : exchange.fixed) === false && (exchange.min === 0 || exchange.max === 0 || exchange.max > exchange.min || (typeof exchange.min !== "number" || typeof exchange.max !== "number") && exchange.toAmount > 0);
3048
+ });
3049
+ Logger.log((exchangesSupportingThePair == null ? void 0 : exchangesSupportingThePair.length) + " of them have exist=true", loggerSource);
3050
+ if (!exchangesSupportingThePair.length) {
3051
+ return {
3052
+ result: false,
3053
+ reason: SwapProvider.NO_SWAPS_REASONS.NOT_SUPPORTED
3054
+ };
3055
+ }
3056
+ var availableExchanges = exchangesSupportingThePair.filter(function (exchange) {
3057
+ return typeof (exchange == null ? void 0 : exchange.toAmount) === "number" && exchange.toAmount > 0;
3058
+ });
3059
+ Logger.log("Available (having amountTo): " + safeStringify(availableExchanges), loggerSource);
3060
+ // min=0 or max=0 means there is no limit for the partner
3061
+ var smallestMin = null;
3062
+ if (exchangesSupportingThePair.find(function (ex) {
3063
+ return bignumber_js.BigNumber(ex.min).isZero();
3064
+ }) == null) {
3065
+ smallestMin = exchangesSupportingThePair.reduce(function (prev, cur) {
3066
+ if (typeof cur.min === "number" && (prev === null || bignumber_js.BigNumber(cur.min).lt(prev))) return bignumber_js.BigNumber(cur.min);
3067
+ return prev;
3068
+ }, null);
3069
+ }
3070
+ var greatestMax = null;
3071
+ if (exchangesSupportingThePair.find(function (ex) {
3072
+ return bignumber_js.BigNumber(ex.max).isZero();
3073
+ }) == null) {
3074
+ greatestMax = exchangesSupportingThePair.reduce(function (prev, cur) {
3075
+ if (typeof cur.max === "number" && (prev === null || bignumber_js.BigNumber(cur.max).gt(prev))) return bignumber_js.BigNumber(cur.max);
3076
+ return prev;
3077
+ }, null);
3078
+ }
3079
+ var extraCoinsToFitMinMax = "0";
3080
+ if (typeof fromCoinToUsdRate === "string" && bignumber_js.BigNumber(fromCoinToUsdRate).gt("0")) {
3081
+ var extraUsdToFitMinMax = bignumber_js.BigNumber("1"); // We correct the limits as the exact limit can fluctuate and cause failed swap creation
3082
+ extraCoinsToFitMinMax = AmountUtils.trim(extraUsdToFitMinMax.div(fromCoinToUsdRate), fromCoin.digits);
3083
+ }
3084
+ if (smallestMin instanceof bignumber_js.BigNumber) {
3085
+ smallestMin = AmountUtils.trim(smallestMin.plus(extraCoinsToFitMinMax), fromCoin.digits);
3086
+ }
3087
+ if (greatestMax instanceof bignumber_js.BigNumber) {
3088
+ if (greatestMax > extraCoinsToFitMinMax) {
3089
+ greatestMax = AmountUtils.trim(greatestMax.minus(extraCoinsToFitMinMax), fromCoin.digits);
3090
+ } else {
3091
+ greatestMax = "0";
3092
+ }
3093
+ }
3094
+ if (availableExchanges.length) {
3095
+ var _bestOpt$duration;
3096
+ var sorted = availableExchanges.sort(function (op1, op2) {
3097
+ return op2.toAmount - op1.toAmount;
3098
+ });
3099
+ var bestOpt = sorted[0];
3100
+ Logger.log("Returning first option after sorting: " + safeStringify(bestOpt), loggerSource);
3101
+ var max = null;
3102
+ var min = null;
3103
+ if (extraCoinsToFitMinMax != null) {
3104
+ if (typeof bestOpt.max === "number" && bestOpt.max !== 0) {
3105
+ max = bignumber_js.BigNumber(bestOpt.max).minus(extraCoinsToFitMinMax);
3106
+ max = AmountUtils.trim(max.lt(0) ? "0" : max, fromCoin.digits);
3107
+ }
3108
+ if (typeof bestOpt.min === "number" && bestOpt.min !== 0) {
3109
+ min = AmountUtils.trim(bignumber_js.BigNumber(bestOpt.min).plus(extraCoinsToFitMinMax), fromCoin.digits);
3110
+ }
3111
+ }
3112
+ var rate = bestOpt.toAmount && bestOpt.fromAmount ? bignumber_js.BigNumber(bestOpt.toAmount).div(bestOpt.fromAmount) : null;
3113
+ return {
3114
+ result: true,
3115
+ min: min,
3116
+ max: max,
3117
+ smallestMin: smallestMin,
3118
+ greatestMax: greatestMax,
3119
+ rate: rate != null ? AmountUtils.trim(rate, _this7._maxRateDigits) : null,
3120
+ durationMinutesRange: (_bestOpt$duration = bestOpt.duration) != null ? _bestOpt$duration : null,
3121
+ rawSwapData: bestOpt
3122
+ };
3123
+ }
3124
+ var result = {
3125
+ result: false,
3126
+ reason: smallestMin && bignumber_js.BigNumber(amountCoins).lt(smallestMin) ? SwapProvider.NO_SWAPS_REASONS.TOO_LOW : greatestMax && bignumber_js.BigNumber(amountCoins).gt(greatestMax) ? SwapProvider.NO_SWAPS_REASONS.TOO_HIGH : SwapProvider.NO_SWAPS_REASONS.NOT_SUPPORTED,
3127
+ smallestMin: smallestMin,
3128
+ greatestMax: greatestMax
3129
+ };
3130
+ Logger.log("Returning result " + safeStringify(result), loggerSource);
3131
+ return result;
3132
+ });
3133
+ }, function (e) {
3134
+ var _e$response3;
3135
+ if ((e == null || (_e$response3 = e.response) == null ? void 0 : _e$response3.status) === 429) {
3136
+ return {
3137
+ result: false,
3138
+ reason: SwapProvider.COMMON_ERRORS.REQUESTS_LIMIT_EXCEEDED
3139
+ };
3140
+ }
3141
+ Logger.log("Internal swapspace/rabbit error when getting swap options " + safeStringify(e), loggerSource);
3142
+ improveAndRethrow(e, loggerSource);
3143
+ }));
3144
+ } catch (e) {
3145
+ return Promise.reject(e);
3146
+ }
3147
+ };
3148
+ _proto.createSwap = function createSwap(fromCoin, toCoin, amount, toAddress, refundAddress, rawSwapData, clientIpAddress) {
3149
+ try {
3150
+ var _this8 = this;
3151
+ var loggerSource = "createSwap";
3152
+ var partner = rawSwapData == null ? void 0 : rawSwapData.partner;
3153
+ return Promise.resolve(_catch(function () {
3154
+ if (!(fromCoin instanceof Coin) || !(toCoin instanceof Coin) || typeof amount !== "string" || typeof toAddress !== "string" || typeof refundAddress !== "string") {
3155
+ throw new Error("Invalid input: " + fromCoin + " " + toCoin + " " + amount + " " + toAddress + " " + refundAddress);
3156
+ }
3157
+ if (typeof partner !== "string" || typeof (rawSwapData == null ? void 0 : rawSwapData.fromCurrency) !== "string" || typeof (rawSwapData == null ? void 0 : rawSwapData.fromNetwork) !== "string" || typeof (rawSwapData == null ? void 0 : rawSwapData.toCurrency) !== "string" || typeof (rawSwapData == null ? void 0 : rawSwapData.toNetwork) !== "string" || typeof (rawSwapData == null ? void 0 : rawSwapData.id) !== "string" // can be just empty
3158
+ ) {
3159
+ throw new Error("Invalid raw swap data: " + safeStringify(rawSwapData));
3160
+ }
3161
+ return Promise.resolve(_this8._fetchSupportedCurrenciesIfNeeded()).then(function () {
3162
+ var _this8$_supportedCoin, _this8$_supportedCoin2;
3163
+ var toCurrencyExtraId = (_this8$_supportedCoin = (_this8$_supportedCoin2 = _this8._supportedCoins.find(function (item) {
3164
+ return item.coin === toCoin;
3165
+ })) == null ? void 0 : _this8$_supportedCoin2.extraId) != null ? _this8$_supportedCoin : "";
3166
+ var requestData = {
3167
+ partner: partner,
3168
+ fromCurrency: rawSwapData == null ? void 0 : rawSwapData.fromCurrency,
3169
+ fromNetwork: rawSwapData == null ? void 0 : rawSwapData.fromNetwork,
3170
+ toCurrency: rawSwapData == null ? void 0 : rawSwapData.toCurrency,
3171
+ toNetwork: rawSwapData == null ? void 0 : rawSwapData.toNetwork,
3172
+ address: toAddress,
3173
+ amount: amount,
3174
+ fixed: false,
3175
+ extraId: toCurrencyExtraId != null ? toCurrencyExtraId : "",
3176
+ rateId: rawSwapData == null ? void 0 : rawSwapData.id,
3177
+ userIp: clientIpAddress,
3178
+ refund: refundAddress
3179
+ };
3180
+ Logger.log("Sending create request: " + safeStringify(requestData), loggerSource);
3181
+ return Promise.resolve(axios__default["default"].post(_this8._URL + "/api/v2/exchange", requestData)).then(function (response) {
3182
+ var result = response.data;
3183
+ Logger.log("Creation result " + safeStringify(result), loggerSource);
3184
+ if (result != null && result.id) {
3185
+ var _result$from, _result$from2, _result$to, _result$to2, _result$from4, _result$from5, _result$to4, _result$to5;
3186
+ if (typeof (result == null || (_result$from = result.from) == null ? void 0 : _result$from.amount) !== "number" || typeof (result == null || (_result$from2 = result.from) == null ? void 0 : _result$from2.address) !== "string" || typeof (result == null || (_result$to = result.to) == null ? void 0 : _result$to.amount) !== "number" || typeof (result == null || (_result$to2 = result.to) == null ? void 0 : _result$to2.address) !== "string") throw new Error("Wrong swap creation result " + result);
3187
+ /* We use the returned rate preferably but if the retrieved
3188
+ * rate 0/null/undefined we calculate it manually */
3189
+ var rate = result.rate;
3190
+ if (typeof rate !== "number" || bignumber_js.BigNumber(rate).isZero()) {
3191
+ var _result$to3, _result$from3;
3192
+ rate = bignumber_js.BigNumber(result == null || (_result$to3 = result.to) == null ? void 0 : _result$to3.amount).div(result == null || (_result$from3 = result.from) == null ? void 0 : _result$from3.amount);
3193
+ } else {
3194
+ rate = bignumber_js.BigNumber(rate);
3195
+ }
3196
+ return {
3197
+ result: true,
3198
+ swapId: result == null ? void 0 : result.id,
3199
+ fromCoin: fromCoin,
3200
+ fromAmount: AmountUtils.trim(result == null || (_result$from4 = result.from) == null ? void 0 : _result$from4.amount, fromCoin.digits),
3201
+ fromAddress: result == null || (_result$from5 = result.from) == null ? void 0 : _result$from5.address,
3202
+ toCoin: toCoin,
3203
+ toAmount: AmountUtils.trim(result == null || (_result$to4 = result.to) == null ? void 0 : _result$to4.amount, toCoin.digits),
3204
+ toAddress: result == null || (_result$to5 = result.to) == null ? void 0 : _result$to5.address,
3205
+ rate: AmountUtils.trim(rate, _this8._maxRateDigits)
3206
+ };
3207
+ }
3208
+ var errorMessage = "Swap creation succeeded but the response is wrong: " + safeStringify(response);
3209
+ Logger.log(errorMessage, loggerSource);
3210
+ throw new Error(errorMessage);
3211
+ });
3212
+ });
3213
+ }, function (e) {
3214
+ var _e$response4, _e$response5;
3215
+ Logger.log("Failed to create swap. Error is: " + safeStringify(e), loggerSource);
3216
+ var composeFailResult = function composeFailResult(reason) {
3217
+ return {
3218
+ result: false,
3219
+ reason: reason,
3220
+ partner: partner
3221
+ };
3222
+ };
3223
+ var status = e == null || (_e$response4 = e.response) == null ? void 0 : _e$response4.status;
3224
+ var data = e == null || (_e$response5 = e.response) == null ? void 0 : _e$response5.data;
3225
+ if (status === 429) {
3226
+ Logger.log("Returning fail - RPS limit exceeded " + data, loggerSource);
3227
+ return composeFailResult(SwapProvider.COMMON_ERRORS.REQUESTS_LIMIT_EXCEEDED);
3228
+ }
3229
+ var texts422 = ["Pair cannot be processed by", "Currency not found", "Amount maximum is", "Amount minimum is"];
3230
+ var text403 = "IP address is forbidden";
3231
+ if (typeof data === "string" && (status === 403 && data.includes(text403) || status === 422 && texts422.find(function (text) {
3232
+ return data.includes(text);
3233
+ }))) {
3234
+ Logger.log("Returning retriable fail: " + status + " - " + data + ", " + partner, loggerSource);
3235
+ return composeFailResult(SwapProvider.CREATION_FAIL_REASONS.RETRIABLE_FAIL);
3236
+ }
3237
+ Logger.log("Internal swapspace/rabbit error for " + partner + ": " + safeStringify(e), loggerSource);
3238
+ improveAndRethrow(e, loggerSource);
3239
+ }));
3240
+ } catch (e) {
3241
+ return Promise.reject(e);
3242
+ }
3243
+ };
3244
+ _proto._mapSwapspaceStatusToRabbitStatus = function _mapSwapspaceStatusToRabbitStatus(status) {
3245
+ switch (status) {
3246
+ case "waiting":
3247
+ return SwapProvider.SWAP_STATUSES.WAITING_FOR_PAYMENT;
3248
+ case "confirming":
3249
+ return SwapProvider.SWAP_STATUSES.CONFIRMING;
3250
+ case "exchanging":
3251
+ return SwapProvider.SWAP_STATUSES.EXCHANGING;
3252
+ case "sending":
3253
+ return SwapProvider.SWAP_STATUSES.PAYMENT_RECEIVED;
3254
+ case "finished":
3255
+ return SwapProvider.SWAP_STATUSES.COMPLETED;
3256
+ case "verifying":
3257
+ return SwapProvider.SWAP_STATUSES.EXCHANGING;
3258
+ case "refunded":
3259
+ return SwapProvider.SWAP_STATUSES.REFUNDED;
3260
+ case "expired":
3261
+ return SwapProvider.SWAP_STATUSES.EXPIRED;
3262
+ case "failed":
3263
+ return SwapProvider.SWAP_STATUSES.FAILED;
3264
+ default:
3265
+ throw new Error("Unknown swapspace status: " + status);
3266
+ }
3267
+ };
3268
+ _proto.getExistingSwapsDetailsAndStatus = function getExistingSwapsDetailsAndStatus(swapIds) {
3269
+ try {
3270
+ var _this9 = this;
3271
+ var loggerSource = "getExistingSwapsDetailsAndStatus";
3272
+ return Promise.resolve(_catch(function () {
3273
+ if (swapIds.find(function (id) {
3274
+ return typeof id !== "string";
3275
+ })) {
3276
+ throw new Error("Swap id is not string: " + safeStringify(swapIds));
3277
+ }
3278
+ var getNotFailingOn404 = function getNotFailingOn404(swapId) {
3279
+ try {
3280
+ return Promise.resolve(_catch(function () {
3281
+ return Promise.resolve(axios__default["default"].get(_this9._URL + "/api/v2/exchange/" + swapId));
3282
+ }, function (error) {
3283
+ var _error$response;
3284
+ if ((error == null || (_error$response = error.response) == null ? void 0 : _error$response.status) === 404) return [];
3285
+ throw error;
3286
+ }));
3287
+ } catch (e) {
3288
+ return Promise.reject(e);
3289
+ }
3290
+ };
3291
+ return Promise.resolve(Promise.all(swapIds.map(function (swapId) {
3292
+ return getNotFailingOn404(swapId);
3293
+ }))).then(function (responses) {
3294
+ var wo404 = responses.flat();
3295
+ var swaps = wo404.map(function (r) {
3296
+ return r.data;
3297
+ }).map(function (swap, index) {
3298
+ var _this9$_supportedCoin, _this9$_supportedCoin2;
3299
+ var fromCoin = (_this9$_supportedCoin = _this9._supportedCoins.find(function (i) {
3300
+ return i.code === swap.from.code && i.network === swap.from.network;
3301
+ })) == null ? void 0 : _this9$_supportedCoin.coin;
3302
+ var toCoin = (_this9$_supportedCoin2 = _this9._supportedCoins.find(function (i) {
3303
+ return i.code === swap.to.code && i.network === swap.to.network;
3304
+ })) == null ? void 0 : _this9$_supportedCoin2.coin;
3305
+ if (!fromCoin || !toCoin) {
3306
+ return []; // We skip swaps with not supported coins for now
3307
+ }
3308
+ var status = _this9._mapSwapspaceStatusToRabbitStatus(swap.status);
3309
+ var toDigits = status === SwapProvider.SWAP_STATUSES.REFUNDED ? fromCoin.digits : toCoin.digits;
3310
+ var addressToSendCoinsToSwapspace = swap.from.address;
3311
+ var toUtcTimestamp = function toUtcTimestamp(timeStr) {
3312
+ return Date.parse(timeStr.match(/.+[Zz]$/) ? timeStr : timeStr + "Z");
3313
+ };
3314
+ return new ExistingSwap(swapIds[index], status, toUtcTimestamp(swap.timestamps.createdAt), toUtcTimestamp(swap.timestamps.expiresAt), swap.confirmations, AmountUtils.trim(swap.rate, _this9._maxRateDigits), swap.refundAddress, addressToSendCoinsToSwapspace, fromCoin, AmountUtils.trim(swap.from.amount, fromCoin.digits), swap.from.transactionHash, swap.blockExplorerTransactionUrl.from, toCoin, AmountUtils.trim(swap.to.amount, toDigits), swap.to.transactionHash, swap.blockExplorerTransactionUrl.to, swap.to.address, swap.partner);
3315
+ }).flat();
3316
+ Logger.log("Swap details result " + safeStringify(swaps), loggerSource);
3317
+ return {
3318
+ result: true,
3319
+ swaps: swaps
3320
+ };
3321
+ });
3322
+ }, function (e) {
3323
+ var _e$response6, _e$response7;
3324
+ Logger.log("Failed to get swap details. Error is: " + safeStringify(e), loggerSource);
3325
+ var composeFailResult = function composeFailResult(reason) {
3326
+ return {
3327
+ result: false,
3328
+ reason: reason
3329
+ };
3330
+ };
3331
+ var status = e == null || (_e$response6 = e.response) == null ? void 0 : _e$response6.status;
3332
+ var data = e == null || (_e$response7 = e.response) == null ? void 0 : _e$response7.data;
3333
+ if (status === 429) {
3334
+ Logger.log("Returning fail - RPS limit exceeded " + data, loggerSource);
3335
+ return composeFailResult(SwapProvider.COMMON_ERRORS.REQUESTS_LIMIT_EXCEEDED);
3336
+ }
3337
+ improveAndRethrow(e, loggerSource);
3338
+ }));
3339
+ } catch (e) {
3340
+ return Promise.reject(e);
3341
+ }
3342
+ };
3343
+ _proto.isAddressValidForAsset = function isAddressValidForAsset(asset, address) {
3344
+ try {
3345
+ var assetData = this._supportedCoins.find(function (i) {
3346
+ return i.coin === asset;
3347
+ });
3348
+ if (assetData) {
3349
+ var corrected = assetData.validationRegexp.trim();
3350
+ corrected = corrected[0] === "/" ? corrected.slice(1) : corrected;
3351
+ corrected = corrected[corrected.length - 1] === "/" ? corrected.slice(0, corrected.length - 1) : corrected;
3352
+ return address.match(corrected) != null;
3353
+ }
3354
+ } catch (e) {
3355
+ Logger.logError(e, "isAddressValidForAsset");
3356
+ }
3357
+ return false;
3358
+ };
3359
+ return SwapspaceSwapProvider;
3360
+ }(SwapProvider);
3361
+
2740
3362
  exports.AmountUtils = AmountUtils;
2741
3363
  exports.AssetIcon = AssetIcon;
2742
3364
  exports.Blockchain = Blockchain;
@@ -2751,6 +3373,7 @@
2751
3373
  exports.Protocol = Protocol;
2752
3374
  exports.SupportChat = SupportChat;
2753
3375
  exports.SwapProvider = SwapProvider;
3376
+ exports.SwapspaceSwapProvider = SwapspaceSwapProvider;
2754
3377
  exports.improveAndRethrow = improveAndRethrow;
2755
3378
  exports.safeStringify = safeStringify;
2756
3379