@curvefi/api 1.25.2 → 2.2.0

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.
Files changed (219) hide show
  1. package/README.md +797 -590
  2. package/docs/v1/README.md +916 -0
  3. package/lib/boosting.d.ts +12 -12
  4. package/lib/boosting.js +23 -23
  5. package/lib/constants/abis/{json/2pool → 2pool}/swap.json +0 -0
  6. package/lib/constants/abis/{json/3pool → 3pool}/swap.json +0 -0
  7. package/lib/constants/abis/{json/4pool → 4pool}/swap.json +0 -0
  8. package/lib/constants/abis/{json/ERC20.json → ERC20.json} +0 -0
  9. package/lib/constants/abis/{json/aave → aave}/rewards.json +0 -0
  10. package/lib/constants/abis/{json/aave → aave}/swap.json +0 -0
  11. package/lib/constants/abis/{json/address_provider.json → address_provider.json} +0 -0
  12. package/lib/constants/abis/{json/ankreth → ankreth}/sCurveRewards.json +0 -0
  13. package/lib/constants/abis/{json/ankreth → ankreth}/swap.json +0 -0
  14. package/lib/constants/abis/{json/atricrypto3 → atricrypto3}/swap.json +0 -0
  15. package/lib/constants/abis/{json/atricrypto3 → atricrypto3}/zap.json +0 -0
  16. package/lib/constants/abis/{json/bbtc → bbtc}/deposit.json +0 -0
  17. package/lib/constants/abis/{json/bbtc → bbtc}/swap.json +0 -0
  18. package/lib/constants/abis/{json/busd → busd}/deposit.json +0 -0
  19. package/lib/constants/abis/{json/busd → busd}/swap.json +0 -0
  20. package/lib/constants/abis/{json/cERC20.json → cERC20.json} +0 -0
  21. package/lib/constants/abis/{json/compound → compound}/deposit.json +0 -0
  22. package/lib/constants/abis/{json/compound → compound}/swap.json +0 -0
  23. package/lib/constants/abis/{json/crveth → crveth}/swap.json +0 -0
  24. package/lib/constants/abis/{json/deposit_and_stake.json → deposit_and_stake.json} +0 -0
  25. package/lib/constants/abis/{json/dusd → dusd}/deposit.json +0 -0
  26. package/lib/constants/abis/{json/dusd → dusd}/sCurveRewards.json +0 -0
  27. package/lib/constants/abis/{json/dusd → dusd}/swap.json +0 -0
  28. package/lib/constants/abis/{json/eurs → eurs}/sCurveRewards.json +0 -0
  29. package/lib/constants/abis/{json/eurs → eurs}/swap.json +0 -0
  30. package/lib/constants/abis/{json/eursusd → eursusd}/swap.json +0 -0
  31. package/lib/constants/abis/{json/eurt → eurt}/swap.json +0 -0
  32. package/lib/constants/abis/{json/eurtusd → eurtusd}/deposit.json +0 -0
  33. package/lib/constants/abis/{json/eurtusd → eurtusd}/swap.json +0 -0
  34. package/lib/constants/abis/{json/factory-crypto → factory-crypto}/factory-crypto-pool-2.json +0 -0
  35. package/lib/constants/abis/{json/factory-crypto.json → factory-crypto.json} +0 -0
  36. package/lib/constants/abis/{json/factory-v2 → factory-v2}/DepositZapMetaBtcPolygon.json +0 -0
  37. package/lib/constants/abis/{json/factory-v2 → factory-v2}/DepositZapMetaUsdPolygon.json +0 -0
  38. package/lib/constants/abis/{json/factory-v2 → factory-v2}/MetaBTC.json +0 -0
  39. package/lib/constants/abis/{json/factory-v2 → factory-v2}/MetaBTCBalances.json +0 -0
  40. package/lib/constants/abis/{json/factory-v2 → factory-v2}/MetaBTCBalancesRen.json +0 -0
  41. package/lib/constants/abis/{json/factory-v2 → factory-v2}/MetaBTCRen.json +0 -0
  42. package/lib/constants/abis/{json/factory-v2 → factory-v2}/MetaUSD.json +0 -0
  43. package/lib/constants/abis/{json/factory-v2 → factory-v2}/MetaUSDBalances.json +0 -0
  44. package/lib/constants/abis/{json/factory-v2 → factory-v2}/Plain2Balances.json +0 -0
  45. package/lib/constants/abis/{json/factory-v2 → factory-v2}/Plain2Basic.json +0 -0
  46. package/lib/constants/abis/{json/factory-v2 → factory-v2}/Plain2ETH.json +0 -0
  47. package/lib/constants/abis/{json/factory-v2 → factory-v2}/Plain2Optimized.json +0 -0
  48. package/lib/constants/abis/{json/factory-v2 → factory-v2}/Plain3Balances.json +0 -0
  49. package/lib/constants/abis/{json/factory-v2 → factory-v2}/Plain3Basic.json +0 -0
  50. package/lib/constants/abis/{json/factory-v2 → factory-v2}/Plain3ETH.json +0 -0
  51. package/lib/constants/abis/{json/factory-v2 → factory-v2}/Plain3Optimized.json +0 -0
  52. package/lib/constants/abis/{json/factory-v2 → factory-v2}/Plain4Balances.json +0 -0
  53. package/lib/constants/abis/{json/factory-v2 → factory-v2}/Plain4Basic.json +0 -0
  54. package/lib/constants/abis/{json/factory-v2 → factory-v2}/Plain4ETH.json +0 -0
  55. package/lib/constants/abis/{json/factory-v2 → factory-v2}/Plain4Optimized.json +0 -0
  56. package/lib/constants/abis/{json/factory.json → factory.json} +0 -0
  57. package/lib/constants/abis/{json/factoryPools → factoryPools}/deposit.json +0 -0
  58. package/lib/constants/abis/{json/factoryPools → factoryPools}/rewards.json +0 -0
  59. package/lib/constants/abis/{json/factoryPools → factoryPools}/swap.json +0 -0
  60. package/lib/constants/abis/{json/gauge.json → gauge.json} +0 -0
  61. package/lib/constants/abis/{json/gauge_factory.json → gauge_factory.json} +0 -0
  62. package/lib/constants/abis/{json/gauge_rewards_only.json → gauge_rewards_only.json} +0 -0
  63. package/lib/constants/abis/{json/gauge_synthetix.json → gauge_synthetix.json} +0 -0
  64. package/lib/constants/abis/{json/gauge_v2.json → gauge_v2.json} +0 -0
  65. package/lib/constants/abis/{json/gauge_v3.json → gauge_v3.json} +0 -0
  66. package/lib/constants/abis/{json/gauge_v4.json → gauge_v4.json} +0 -0
  67. package/lib/constants/abis/{json/gauge_v5.json → gauge_v5.json} +0 -0
  68. package/lib/constants/abis/{json/gaugecontroller.json → gaugecontroller.json} +0 -0
  69. package/lib/constants/abis/{json/gusd → gusd}/deposit.json +0 -0
  70. package/lib/constants/abis/{json/gusd → gusd}/swap.json +0 -0
  71. package/lib/constants/abis/{json/hbtc → hbtc}/swap.json +0 -0
  72. package/lib/constants/abis/{json/husd → husd}/deposit.json +0 -0
  73. package/lib/constants/abis/{json/husd → husd}/swap.json +0 -0
  74. package/lib/constants/abis/{json/ib → ib}/swap.json +0 -0
  75. package/lib/constants/abis/{json/iearn → iearn}/deposit.json +0 -0
  76. package/lib/constants/abis/{json/iearn → iearn}/sCurveRewards.json +0 -0
  77. package/lib/constants/abis/{json/iearn → iearn}/swap.json +0 -0
  78. package/lib/constants/abis/{json/link → link}/swap.json +0 -0
  79. package/lib/constants/abis/{json/minter.json → minter.json} +0 -0
  80. package/lib/constants/abis/{json/musd → musd}/deposit.json +0 -0
  81. package/lib/constants/abis/{json/musd → musd}/sCurveRewards.json +0 -0
  82. package/lib/constants/abis/{json/musd → musd}/swap.json +0 -0
  83. package/lib/constants/abis/{json/obtc → obtc}/deposit.json +0 -0
  84. package/lib/constants/abis/{json/obtc → obtc}/sCurveRewards.json +0 -0
  85. package/lib/constants/abis/{json/obtc → obtc}/swap.json +0 -0
  86. package/lib/constants/abis/{json/paave → paave}/rewards.json +0 -0
  87. package/lib/constants/abis/{json/pax → pax}/deposit.json +0 -0
  88. package/lib/constants/abis/{json/pax → pax}/swap.json +0 -0
  89. package/lib/constants/abis/{json/pbtc → pbtc}/deposit.json +0 -0
  90. package/lib/constants/abis/{json/pbtc → pbtc}/sCurveRewards.json +0 -0
  91. package/lib/constants/abis/{json/pbtc → pbtc}/swap.json +0 -0
  92. package/lib/constants/abis/{json/rai → rai}/deposit.json +0 -0
  93. package/lib/constants/abis/{json/rai → rai}/swap.json +0 -0
  94. package/lib/constants/abis/{json/registry_exchange.json → registry_exchange.json} +0 -0
  95. package/lib/constants/abis/{json/ren → ren}/swap.json +0 -0
  96. package/lib/constants/abis/{json/ren-polygon → ren-polygon}/swap.json +0 -0
  97. package/lib/constants/abis/{json/reth → reth}/swap.json +0 -0
  98. package/lib/constants/abis/{json/router.json → router.json} +0 -0
  99. package/lib/constants/abis/{json/rsv → rsv}/deposit.json +0 -0
  100. package/lib/constants/abis/{json/rsv → rsv}/sCurveRewards.json +0 -0
  101. package/lib/constants/abis/{json/rsv → rsv}/swap.json +0 -0
  102. package/lib/constants/abis/{json/saave → saave}/swap.json +0 -0
  103. package/lib/constants/abis/{json/sbtc → sbtc}/sCurveRewards.json +0 -0
  104. package/lib/constants/abis/{json/sbtc → sbtc}/swap.json +0 -0
  105. package/lib/constants/abis/{json/seth → seth}/swap.json +0 -0
  106. package/lib/constants/abis/{json/steth → steth}/sCurveRewards.json +0 -0
  107. package/lib/constants/abis/{json/steth → steth}/swap.json +0 -0
  108. package/lib/constants/abis/{json/streamer.json → streamer.json} +0 -0
  109. package/lib/constants/abis/{json/susdv2 → susdv2}/deposit.json +0 -0
  110. package/lib/constants/abis/{json/susdv2 → susdv2}/sCurveRewards.json +0 -0
  111. package/lib/constants/abis/{json/susdv2 → susdv2}/swap.json +0 -0
  112. package/lib/constants/abis/{json/tbtc → tbtc}/deposit.json +0 -0
  113. package/lib/constants/abis/{json/tbtc → tbtc}/sCurveRewards.json +0 -0
  114. package/lib/constants/abis/{json/tbtc → tbtc}/swap.json +0 -0
  115. package/lib/constants/abis/{json/tricrypto2 → tricrypto2}/deposit.json +0 -0
  116. package/lib/constants/abis/{json/tricrypto2 → tricrypto2}/swap.json +0 -0
  117. package/lib/constants/abis/{json/usdk → usdk}/deposit.json +0 -0
  118. package/lib/constants/abis/{json/usdk → usdk}/swap.json +0 -0
  119. package/lib/constants/abis/{json/usdn → usdn}/deposit.json +0 -0
  120. package/lib/constants/abis/{json/usdn → usdn}/swap.json +0 -0
  121. package/lib/constants/abis/{json/usdp → usdp}/deposit.json +0 -0
  122. package/lib/constants/abis/{json/usdp → usdp}/swap.json +0 -0
  123. package/lib/constants/abis/{json/usdt → usdt}/deposit.json +0 -0
  124. package/lib/constants/abis/{json/usdt → usdt}/swap.json +0 -0
  125. package/lib/constants/abis/{json/ust → ust}/deposit.json +0 -0
  126. package/lib/constants/abis/{json/ust → ust}/swap.json +0 -0
  127. package/lib/constants/abis/{json/votingescrow.json → votingescrow.json} +0 -0
  128. package/lib/constants/abis/{json/yERC20.json → yERC20.json} +0 -0
  129. package/lib/constants/aliases.d.ts +3 -24
  130. package/lib/constants/aliases.js +18 -5
  131. package/lib/constants/coins/avalanche.d.ts +7 -0
  132. package/lib/constants/coins/avalanche.js +32 -0
  133. package/lib/constants/{coins-ethereum.d.ts → coins/ethereum.d.ts} +0 -9
  134. package/lib/constants/{coins-ethereum.js → coins/ethereum.js} +12 -23
  135. package/lib/constants/{coins-polygon.d.ts → coins/polygon.d.ts} +0 -12
  136. package/lib/constants/{coins-polygon.js → coins/polygon.js} +8 -20
  137. package/lib/constants/pools/avalanche.d.ts +4 -0
  138. package/lib/constants/pools/avalanche.js +113 -0
  139. package/lib/constants/pools/ethereum.d.ts +2 -0
  140. package/lib/constants/{abis/abis-ethereum.js → pools/ethereum.js} +517 -1012
  141. package/lib/constants/pools/index.d.ts +4 -0
  142. package/lib/constants/pools/index.js +9 -0
  143. package/lib/constants/pools/polygon.d.ts +4 -0
  144. package/lib/constants/{abis/abis-polygon.js → pools/polygon.js} +52 -80
  145. package/lib/constants/utils.d.ts +5 -0
  146. package/lib/constants/utils.js +69 -0
  147. package/lib/curve.d.ts +13 -31
  148. package/lib/curve.js +204 -232
  149. package/lib/external-api.d.ts +4 -3
  150. package/lib/external-api.js +18 -1
  151. package/lib/factory/common.d.ts +2 -0
  152. package/lib/factory/common.js +45 -0
  153. package/lib/factory/constants.d.ts +16 -16
  154. package/lib/factory/constants.js +79 -77
  155. package/lib/factory/factory-api.d.ts +2 -2
  156. package/lib/factory/factory-api.js +51 -85
  157. package/lib/factory/factory-crypto.d.ts +2 -2
  158. package/lib/factory/factory-crypto.js +30 -35
  159. package/lib/factory/factory.d.ts +2 -2
  160. package/lib/factory/factory.js +60 -205
  161. package/lib/index.d.ts +37 -53
  162. package/lib/index.js +28 -35
  163. package/lib/interfaces.d.ts +51 -83
  164. package/lib/pools/PoolTemplate.d.ts +212 -0
  165. package/lib/pools/PoolTemplate.js +2371 -0
  166. package/lib/pools/index.d.ts +3 -0
  167. package/lib/pools/index.js +7 -0
  168. package/lib/pools/mixins/common.d.ts +3 -0
  169. package/lib/pools/mixins/common.js +77 -0
  170. package/lib/pools/mixins/depositBalancedAmountsMixins.d.ts +5 -0
  171. package/lib/pools/mixins/depositBalancedAmountsMixins.js +145 -0
  172. package/lib/pools/mixins/depositBonusMixins.d.ts +5 -0
  173. package/lib/pools/mixins/depositBonusMixins.js +164 -0
  174. package/lib/pools/mixins/depositMixins.d.ts +5 -0
  175. package/lib/pools/mixins/depositMixins.js +373 -0
  176. package/lib/pools/mixins/depositWrappedMixins.d.ts +3 -0
  177. package/lib/pools/mixins/depositWrappedMixins.js +243 -0
  178. package/lib/pools/mixins/poolBalancesMixin.d.ts +4 -0
  179. package/lib/pools/mixins/poolBalancesMixin.js +129 -0
  180. package/lib/pools/mixins/swapMixins.d.ts +4 -0
  181. package/lib/pools/mixins/swapMixins.js +313 -0
  182. package/lib/pools/mixins/swapWrappedMixins.d.ts +4 -0
  183. package/lib/pools/mixins/swapWrappedMixins.js +297 -0
  184. package/lib/pools/mixins/withdrawExpectedMixins.d.ts +6 -0
  185. package/lib/pools/mixins/withdrawExpectedMixins.js +164 -0
  186. package/lib/pools/mixins/withdrawImbalanceMixins.d.ts +5 -0
  187. package/lib/pools/mixins/withdrawImbalanceMixins.js +348 -0
  188. package/lib/pools/mixins/withdrawImbalanceWrappedMixins.d.ts +3 -0
  189. package/lib/pools/mixins/withdrawImbalanceWrappedMixins.js +207 -0
  190. package/lib/pools/mixins/withdrawMixins.d.ts +5 -0
  191. package/lib/pools/mixins/withdrawMixins.js +347 -0
  192. package/lib/pools/mixins/withdrawOneCoinExpectedMixins.d.ts +5 -0
  193. package/lib/pools/mixins/withdrawOneCoinExpectedMixins.js +104 -0
  194. package/lib/pools/mixins/withdrawOneCoinMixins.d.ts +5 -0
  195. package/lib/pools/mixins/withdrawOneCoinMixins.js +347 -0
  196. package/lib/pools/mixins/withdrawOneCoinWrappedExpectedMixins.d.ts +3 -0
  197. package/lib/pools/mixins/withdrawOneCoinWrappedExpectedMixins.js +72 -0
  198. package/lib/pools/mixins/withdrawOneCoinWrappedMixins.d.ts +3 -0
  199. package/lib/pools/mixins/withdrawOneCoinWrappedMixins.js +205 -0
  200. package/lib/pools/mixins/withdrawWrappedMixins.d.ts +3 -0
  201. package/lib/pools/mixins/withdrawWrappedMixins.js +206 -0
  202. package/lib/pools/poolConstructor.d.ts +2 -0
  203. package/lib/pools/poolConstructor.js +228 -0
  204. package/lib/pools/utils.d.ts +4 -0
  205. package/lib/pools/utils.js +85 -0
  206. package/lib/router.d.ts +13 -0
  207. package/lib/router.js +651 -0
  208. package/lib/utils.d.ts +12 -16
  209. package/lib/utils.js +59 -138
  210. package/package.json +1 -1
  211. package/lib/constants/abis/abis-ethereum.d.ts +0 -4
  212. package/lib/constants/abis/abis-polygon.d.ts +0 -4
  213. package/lib/constants/abis/json/aRewards.json +0 -1
  214. package/lib/constants/abis/json/compound/migration.json +0 -57
  215. package/lib/constants/abis/json/compound/oldSwap.json +0 -688
  216. package/lib/constants/abis/json/ren/adapter.json +0 -1
  217. package/lib/constants/abis/json/sbtc/adapter.json +0 -1
  218. package/lib/pools.d.ts +0 -267
  219. package/lib/pools.js +0 -4752
package/lib/router.js ADDED
@@ -0,0 +1,651 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (_) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
50
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
51
+ if (ar || !(i in from)) {
52
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
53
+ ar[i] = from[i];
54
+ }
55
+ }
56
+ return to.concat(ar || Array.prototype.slice.call(from));
57
+ };
58
+ var __importDefault = (this && this.__importDefault) || function (mod) {
59
+ return (mod && mod.__esModule) ? mod : { "default": mod };
60
+ };
61
+ Object.defineProperty(exports, "__esModule", { value: true });
62
+ exports.swap = exports.swapEstimateGas = exports.swapApprove = exports.swapApproveEstimateGas = exports.swapIsApproved = exports.swapPriceImpact = exports.swapExpected = exports.getBestRouteAndOutput = exports._findAllRoutes = void 0;
63
+ var axios_1 = __importDefault(require("axios"));
64
+ var memoizee_1 = __importDefault(require("memoizee"));
65
+ var bignumber_js_1 = __importDefault(require("bignumber.js"));
66
+ var ethers_1 = require("ethers");
67
+ var curve_1 = require("./curve");
68
+ var utils_1 = require("./utils");
69
+ var pools_1 = require("./pools");
70
+ // TODO make working or remove
71
+ var IMBALANCED_POOLS = [];
72
+ // Inspired by Dijkstra's algorithm
73
+ var _findAllRoutes = function (inputCoinAddress, outputCoinAddress) { return __awaiter(void 0, void 0, void 0, function () {
74
+ var ALL_POOLS, basePoolsSet, _i, ALL_POOLS_1, pool, basePoolIds, markedCoins, curCoins, nextCoins, routes, step, _a, curCoins_1, inCoin, _b, ALL_POOLS_2, _c, poolId, poolData, wrapped_coin_addresses, underlying_coin_addresses, meta_coin_addresses, token_address, is_lending, inCoinIndexes, j, swapType, _d, _e, inCoinRoute, swapType, _f, _h, inCoinRoute, j, tvl, _j, swapType, _k, _l, inCoinRoute, poolAddress, j, tvl, _m, swapType, _o, _p, inCoinRoute, j, tvl, _q, swapType, _r, _s, inCoinRoute, tvl, _t, swapType, _u, _v, inCoinRoute;
75
+ var _w;
76
+ var _x, _y, _z, _0, _1, _2, _3, _4;
77
+ return __generator(this, function (_5) {
78
+ switch (_5.label) {
79
+ case 0:
80
+ inputCoinAddress = inputCoinAddress.toLowerCase();
81
+ outputCoinAddress = outputCoinAddress.toLowerCase();
82
+ ALL_POOLS = Object.entries(__assign(__assign(__assign({}, curve_1.curve.constants.POOLS_DATA), curve_1.curve.constants.FACTORY_POOLS_DATA), curve_1.curve.constants.CRYPTO_FACTORY_POOLS_DATA));
83
+ basePoolsSet = new Set();
84
+ for (_i = 0, ALL_POOLS_1 = ALL_POOLS; _i < ALL_POOLS_1.length; _i++) {
85
+ pool = ALL_POOLS_1[_i];
86
+ if (pool[1].base_pool)
87
+ basePoolsSet.add(pool[1].base_pool);
88
+ }
89
+ basePoolIds = Array.from(basePoolsSet);
90
+ markedCoins = [];
91
+ curCoins = [inputCoinAddress];
92
+ nextCoins = new Set();
93
+ routes = (_w = {},
94
+ _w[inputCoinAddress] = [[]],
95
+ _w);
96
+ step = 0;
97
+ _5.label = 1;
98
+ case 1:
99
+ if (!(step < 4)) return [3 /*break*/, 21];
100
+ _a = 0, curCoins_1 = curCoins;
101
+ _5.label = 2;
102
+ case 2:
103
+ if (!(_a < curCoins_1.length)) return [3 /*break*/, 19];
104
+ inCoin = curCoins_1[_a];
105
+ _b = 0, ALL_POOLS_2 = ALL_POOLS;
106
+ _5.label = 3;
107
+ case 3:
108
+ if (!(_b < ALL_POOLS_2.length)) return [3 /*break*/, 18];
109
+ _c = ALL_POOLS_2[_b], poolId = _c[0], poolData = _c[1];
110
+ wrapped_coin_addresses = poolData.wrapped_coin_addresses.map(function (a) { return a.toLowerCase(); });
111
+ underlying_coin_addresses = poolData.underlying_coin_addresses.map(function (a) { return a.toLowerCase(); });
112
+ meta_coin_addresses = poolData.is_meta ?
113
+ curve_1.curve.constants.POOLS_DATA[poolData.base_pool].underlying_coin_addresses.map(function (a) { return a.toLowerCase(); }) : [];
114
+ token_address = poolData.token_address.toLowerCase();
115
+ is_lending = (_x = poolData.is_lending) !== null && _x !== void 0 ? _x : false;
116
+ inCoinIndexes = {
117
+ wrapped_coin: wrapped_coin_addresses.indexOf(inCoin),
118
+ underlying_coin: underlying_coin_addresses.indexOf(inCoin),
119
+ meta_coin: meta_coin_addresses ? meta_coin_addresses.indexOf(inCoin) : -1,
120
+ };
121
+ // Find all LP -> underlying coin "swaps" (actually remove_liquidity_one_coin)
122
+ if (basePoolIds.includes(poolId) && inCoin === token_address) {
123
+ for (j = 0; j < underlying_coin_addresses.length; j++) {
124
+ // If this coin already marked or will be marked on the current step, no need to consider it on the next step
125
+ if (markedCoins.includes(underlying_coin_addresses[j]) || curCoins.includes(underlying_coin_addresses[j]))
126
+ continue;
127
+ // Looking for outputCoinAddress only on the final step
128
+ if (step === 3 && underlying_coin_addresses[j] !== outputCoinAddress)
129
+ continue;
130
+ swapType = poolId === 'aave' ? 10 : 9;
131
+ for (_d = 0, _e = routes[inCoin]; _d < _e.length; _d++) {
132
+ inCoinRoute = _e[_d];
133
+ routes[underlying_coin_addresses[j]] = ((_y = routes[underlying_coin_addresses[j]]) !== null && _y !== void 0 ? _y : []).concat([__spreadArray(__spreadArray([], inCoinRoute, true), [
134
+ {
135
+ poolId: poolId,
136
+ poolAddress: poolData.swap_address,
137
+ outputCoinAddress: underlying_coin_addresses[j],
138
+ i: 0,
139
+ j: j,
140
+ swapType: swapType,
141
+ swapAddress: ethers_1.ethers.constants.AddressZero,
142
+ },
143
+ ], false)]);
144
+ }
145
+ nextCoins.add(underlying_coin_addresses[j]);
146
+ }
147
+ }
148
+ // Find all underlying coin -> LP "swaps" (actually add_liquidity)
149
+ if (basePoolIds.includes(poolId) && underlying_coin_addresses.includes(inCoin)) {
150
+ // If this coin already marked or will be marked on the current step, no need to consider it on the next step
151
+ if (markedCoins.includes(token_address) || curCoins.includes(token_address))
152
+ return [3 /*break*/, 17];
153
+ // Looking for outputCoinAddress only on the final step
154
+ if (step === 3 && token_address !== outputCoinAddress)
155
+ return [3 /*break*/, 17];
156
+ swapType = is_lending ? 8 : underlying_coin_addresses.length === 2 ? 6 : 7;
157
+ for (_f = 0, _h = routes[inCoin]; _f < _h.length; _f++) {
158
+ inCoinRoute = _h[_f];
159
+ routes[token_address] = ((_z = routes[token_address]) !== null && _z !== void 0 ? _z : []).concat([__spreadArray(__spreadArray([], inCoinRoute, true), [
160
+ {
161
+ poolId: poolId,
162
+ poolAddress: poolData.swap_address,
163
+ outputCoinAddress: token_address,
164
+ i: underlying_coin_addresses.indexOf(inCoin),
165
+ j: 0,
166
+ swapType: swapType,
167
+ swapAddress: ethers_1.ethers.constants.AddressZero,
168
+ },
169
+ ], false)]);
170
+ }
171
+ nextCoins.add(token_address);
172
+ }
173
+ // No input coin in this pool --> skip
174
+ if (inCoinIndexes.wrapped_coin === -1 && inCoinIndexes.underlying_coin === -1 && inCoinIndexes.meta_coin === -1)
175
+ return [3 /*break*/, 17];
176
+ if (!(inCoinIndexes.wrapped_coin >= 0 && !poolData.is_fake)) return [3 /*break*/, 7];
177
+ j = 0;
178
+ _5.label = 4;
179
+ case 4:
180
+ if (!(j < wrapped_coin_addresses.length)) return [3 /*break*/, 7];
181
+ // If this coin already marked or will be marked on the current step, no need to consider it on the next step
182
+ if (markedCoins.includes(wrapped_coin_addresses[j]) || curCoins.includes(wrapped_coin_addresses[j]))
183
+ return [3 /*break*/, 6];
184
+ // Looking for outputCoinAddress only on the final step
185
+ if (step === 3 && wrapped_coin_addresses[j] !== outputCoinAddress)
186
+ return [3 /*break*/, 6];
187
+ _j = Number;
188
+ return [4 /*yield*/, ((0, pools_1.getPool)(poolId)).stats.totalLiquidity()];
189
+ case 5:
190
+ tvl = _j.apply(void 0, [_5.sent()]);
191
+ if (tvl === 0)
192
+ return [3 /*break*/, 6];
193
+ // Skip imbalanced pools
194
+ if (IMBALANCED_POOLS.includes(poolId))
195
+ return [3 /*break*/, 6];
196
+ swapType = poolData.is_crypto ? 3 : 1;
197
+ for (_k = 0, _l = routes[inCoin]; _k < _l.length; _k++) {
198
+ inCoinRoute = _l[_k];
199
+ routes[wrapped_coin_addresses[j]] = ((_0 = routes[wrapped_coin_addresses[j]]) !== null && _0 !== void 0 ? _0 : []).concat([__spreadArray(__spreadArray([], inCoinRoute, true), [
200
+ {
201
+ poolId: poolId,
202
+ poolAddress: poolData.swap_address,
203
+ outputCoinAddress: wrapped_coin_addresses[j],
204
+ i: inCoinIndexes.wrapped_coin,
205
+ j: j,
206
+ swapType: swapType,
207
+ swapAddress: ethers_1.ethers.constants.AddressZero,
208
+ },
209
+ ], false)]);
210
+ }
211
+ nextCoins.add(wrapped_coin_addresses[j]);
212
+ _5.label = 6;
213
+ case 6:
214
+ j++;
215
+ return [3 /*break*/, 4];
216
+ case 7:
217
+ poolAddress = (poolData.is_crypto && poolData.is_meta) || ([137, 43114].includes(curve_1.curve.chainId) && poolData.is_factory) ?
218
+ poolData.deposit_address : poolData.swap_address;
219
+ if (!(wrapped_coin_addresses.join("|") !== underlying_coin_addresses.join("|") && inCoinIndexes.underlying_coin >= 0)) return [3 /*break*/, 11];
220
+ j = 0;
221
+ _5.label = 8;
222
+ case 8:
223
+ if (!(j < underlying_coin_addresses.length)) return [3 /*break*/, 11];
224
+ if (poolData.is_fake && inCoinIndexes.meta_coin >= 0 && meta_coin_addresses.includes(underlying_coin_addresses[j]))
225
+ return [3 /*break*/, 10];
226
+ // If this coin already marked or will be marked on the current step, no need to consider it on the next step
227
+ if (markedCoins.includes(underlying_coin_addresses[j]) || curCoins.includes(underlying_coin_addresses[j]))
228
+ return [3 /*break*/, 10];
229
+ // Looking for outputCoinAddress only on the final step
230
+ if (step === 3 && underlying_coin_addresses[j] !== outputCoinAddress)
231
+ return [3 /*break*/, 10];
232
+ _m = Number;
233
+ return [4 /*yield*/, ((0, pools_1.getPool)(poolId)).stats.totalLiquidity()];
234
+ case 9:
235
+ tvl = _m.apply(void 0, [_5.sent()]);
236
+ if (tvl === 0)
237
+ return [3 /*break*/, 10];
238
+ // Skip imbalanced pools
239
+ if (IMBALANCED_POOLS.includes(poolId))
240
+ return [3 /*break*/, 10];
241
+ swapType = poolData.is_crypto && (poolData.is_fake || poolData.is_meta) ? 4 : poolData.is_crypto ? 3 : 2;
242
+ for (_o = 0, _p = routes[inCoin]; _o < _p.length; _o++) {
243
+ inCoinRoute = _p[_o];
244
+ routes[underlying_coin_addresses[j]] = ((_1 = routes[underlying_coin_addresses[j]]) !== null && _1 !== void 0 ? _1 : []).concat([__spreadArray(__spreadArray([], inCoinRoute, true), [
245
+ {
246
+ poolId: poolId,
247
+ poolAddress: poolAddress,
248
+ outputCoinAddress: underlying_coin_addresses[j],
249
+ i: inCoinIndexes.underlying_coin,
250
+ j: j,
251
+ swapType: swapType,
252
+ swapAddress: ethers_1.ethers.constants.AddressZero,
253
+ },
254
+ ], false)]);
255
+ }
256
+ nextCoins.add(underlying_coin_addresses[j]);
257
+ _5.label = 10;
258
+ case 10:
259
+ j++;
260
+ return [3 /*break*/, 8];
261
+ case 11:
262
+ if (!(inCoinIndexes.wrapped_coin === 0 && meta_coin_addresses.length > 0 && !poolData.is_fake)) return [3 /*break*/, 15];
263
+ j = 0;
264
+ _5.label = 12;
265
+ case 12:
266
+ if (!(j < meta_coin_addresses.length)) return [3 /*break*/, 15];
267
+ // If this coin already marked or will be marked on the current step, no need to consider it on the next step
268
+ if (markedCoins.includes(meta_coin_addresses[j]) || curCoins.includes(meta_coin_addresses[j]))
269
+ return [3 /*break*/, 14];
270
+ // Looking for outputCoinAddress only on the final step
271
+ if (step === 3 && meta_coin_addresses[j] !== outputCoinAddress)
272
+ return [3 /*break*/, 14];
273
+ _q = Number;
274
+ return [4 /*yield*/, ((0, pools_1.getPool)(poolId)).stats.totalLiquidity()];
275
+ case 13:
276
+ tvl = _q.apply(void 0, [_5.sent()]);
277
+ if (tvl === 0)
278
+ return [3 /*break*/, 14];
279
+ // Skip imbalanced pools
280
+ if (IMBALANCED_POOLS.includes(poolId))
281
+ return [3 /*break*/, 14];
282
+ swapType = ([137, 43114].includes(curve_1.curve.chainId) && poolData.is_factory) ? 5 : poolData.is_crypto ? 4 : 2;
283
+ for (_r = 0, _s = routes[inCoin]; _r < _s.length; _r++) {
284
+ inCoinRoute = _s[_r];
285
+ routes[meta_coin_addresses[j]] = ((_2 = routes[meta_coin_addresses[j]]) !== null && _2 !== void 0 ? _2 : []).concat([__spreadArray(__spreadArray([], inCoinRoute, true), [
286
+ {
287
+ poolId: poolId,
288
+ poolAddress: poolAddress,
289
+ outputCoinAddress: meta_coin_addresses[j],
290
+ i: inCoinIndexes.wrapped_coin,
291
+ j: j + 1,
292
+ swapType: swapType,
293
+ swapAddress: swapType === 5 ? poolData.swap_address : ethers_1.ethers.constants.AddressZero,
294
+ },
295
+ ], false)]);
296
+ }
297
+ nextCoins.add(meta_coin_addresses[j]);
298
+ _5.label = 14;
299
+ case 14:
300
+ j++;
301
+ return [3 /*break*/, 12];
302
+ case 15:
303
+ if (!(inCoinIndexes.meta_coin >= 0 && !poolData.is_fake)) return [3 /*break*/, 17];
304
+ // If this coin already marked or will be marked on the current step, no need to consider it on the next step
305
+ if (markedCoins.includes(wrapped_coin_addresses[0]) || curCoins.includes(wrapped_coin_addresses[0]))
306
+ return [3 /*break*/, 17];
307
+ // Looking for outputCoinAddress only on the final step
308
+ if (step === 3 && wrapped_coin_addresses[0] !== outputCoinAddress)
309
+ return [3 /*break*/, 17];
310
+ _t = Number;
311
+ return [4 /*yield*/, ((0, pools_1.getPool)(poolId)).stats.totalLiquidity()];
312
+ case 16:
313
+ tvl = _t.apply(void 0, [_5.sent()]);
314
+ if (tvl === 0)
315
+ return [3 /*break*/, 17];
316
+ // Skip imbalanced pools
317
+ if (IMBALANCED_POOLS.includes(poolId))
318
+ return [3 /*break*/, 17];
319
+ swapType = ([137, 43114].includes(curve_1.curve.chainId) && poolData.is_factory) ? 5 : poolData.is_crypto ? 4 : 2;
320
+ for (_u = 0, _v = routes[inCoin]; _u < _v.length; _u++) {
321
+ inCoinRoute = _v[_u];
322
+ routes[wrapped_coin_addresses[0]] = ((_3 = routes[wrapped_coin_addresses[0]]) !== null && _3 !== void 0 ? _3 : []).concat([__spreadArray(__spreadArray([], inCoinRoute, true), [
323
+ {
324
+ poolId: poolId,
325
+ poolAddress: poolAddress,
326
+ outputCoinAddress: wrapped_coin_addresses[0],
327
+ i: inCoinIndexes.meta_coin + 1,
328
+ j: 0,
329
+ swapType: swapType,
330
+ swapAddress: swapType === 5 ? poolData.swap_address : ethers_1.ethers.constants.AddressZero,
331
+ },
332
+ ], false)]);
333
+ nextCoins.add(wrapped_coin_addresses[0]);
334
+ }
335
+ _5.label = 17;
336
+ case 17:
337
+ _b++;
338
+ return [3 /*break*/, 3];
339
+ case 18:
340
+ _a++;
341
+ return [3 /*break*/, 2];
342
+ case 19:
343
+ // If target output coin is reached, search is finished. Assumption: the shorter route, the better.
344
+ if (outputCoinAddress in routes)
345
+ return [3 /*break*/, 21];
346
+ markedCoins.push.apply(markedCoins, curCoins);
347
+ curCoins = Array.from(nextCoins);
348
+ nextCoins = new Set();
349
+ _5.label = 20;
350
+ case 20:
351
+ step++;
352
+ return [3 /*break*/, 1];
353
+ case 21: return [2 /*return*/, (_4 = routes[outputCoinAddress]) !== null && _4 !== void 0 ? _4 : []];
354
+ }
355
+ });
356
+ }); };
357
+ exports._findAllRoutes = _findAllRoutes;
358
+ var _getRouteKey = function (route, inputCoinAddress, outputCoinAddress) {
359
+ var sortedCoins = [inputCoinAddress, outputCoinAddress].sort();
360
+ var key = "".concat(sortedCoins[0], "-->");
361
+ for (var _i = 0, _a = route.steps; _i < _a.length; _i++) {
362
+ var routeStep = _a[_i];
363
+ key += "".concat(routeStep.poolId, "-->");
364
+ }
365
+ key += sortedCoins[1];
366
+ return key;
367
+ };
368
+ var _getExchangeMultipleArgs = function (inputCoinAddress, route) {
369
+ var _route = [inputCoinAddress];
370
+ var _swapParams = [];
371
+ var _factorySwapAddresses = [];
372
+ for (var _i = 0, _a = route.steps; _i < _a.length; _i++) {
373
+ var routeStep = _a[_i];
374
+ _route.push(routeStep.poolAddress, routeStep.outputCoinAddress);
375
+ _swapParams.push([routeStep.i, routeStep.j, routeStep.swapType]);
376
+ _factorySwapAddresses.push(routeStep.swapAddress);
377
+ }
378
+ _route = _route.concat(Array(9 - _route.length).fill(ethers_1.ethers.constants.AddressZero));
379
+ _swapParams = _swapParams.concat(Array(4 - _swapParams.length).fill([0, 0, 0]));
380
+ _factorySwapAddresses = _factorySwapAddresses.concat(Array(4 - _factorySwapAddresses.length).fill(ethers_1.ethers.constants.AddressZero));
381
+ return { _route: _route, _swapParams: _swapParams, _factorySwapAddresses: _factorySwapAddresses };
382
+ };
383
+ var _estimatedGasForDifferentRoutesCache = {};
384
+ var _estimateGasForDifferentRoutes = function (routes, inputCoinAddress, outputCoinAddress, _amount) { return __awaiter(void 0, void 0, void 0, function () {
385
+ var contract, gasPromises, value, _i, routes_1, route, routeKey, gasPromise, _a, _route, _swapParams, _factorySwapAddresses, _gasAmounts_1, err_1;
386
+ var _b;
387
+ return __generator(this, function (_c) {
388
+ switch (_c.label) {
389
+ case 0:
390
+ inputCoinAddress = inputCoinAddress.toLowerCase();
391
+ outputCoinAddress = outputCoinAddress.toLowerCase();
392
+ contract = curve_1.curve.contracts[curve_1.curve.constants.ALIASES.registry_exchange].contract;
393
+ gasPromises = [];
394
+ value = (0, utils_1.isEth)(inputCoinAddress) ? _amount : ethers_1.ethers.BigNumber.from(0);
395
+ for (_i = 0, routes_1 = routes; _i < routes_1.length; _i++) {
396
+ route = routes_1[_i];
397
+ routeKey = _getRouteKey(route, inputCoinAddress, outputCoinAddress);
398
+ gasPromise = void 0;
399
+ _a = _getExchangeMultipleArgs(inputCoinAddress, route), _route = _a._route, _swapParams = _a._swapParams, _factorySwapAddresses = _a._factorySwapAddresses;
400
+ if ((((_b = _estimatedGasForDifferentRoutesCache[routeKey]) === null || _b === void 0 ? void 0 : _b.time) || 0) + 3600000 < Date.now()) {
401
+ gasPromise = contract.estimateGas.exchange_multiple(_route, _swapParams, _amount, 0, _factorySwapAddresses, __assign(__assign({}, curve_1.curve.constantOptions), { value: value }));
402
+ }
403
+ else {
404
+ gasPromise = Promise.resolve(_estimatedGasForDifferentRoutesCache[routeKey].gas);
405
+ }
406
+ gasPromises.push(gasPromise);
407
+ }
408
+ _c.label = 1;
409
+ case 1:
410
+ _c.trys.push([1, 3, , 4]);
411
+ return [4 /*yield*/, Promise.all(gasPromises)];
412
+ case 2:
413
+ _gasAmounts_1 = _c.sent();
414
+ routes.forEach(function (route, i) {
415
+ var routeKey = _getRouteKey(route, inputCoinAddress, outputCoinAddress);
416
+ _estimatedGasForDifferentRoutesCache[routeKey] = { 'gas': _gasAmounts_1[i], 'time': Date.now() };
417
+ });
418
+ return [2 /*return*/, _gasAmounts_1.map(function (_g) { return Number(ethers_1.ethers.utils.formatUnits(_g, 0)); })];
419
+ case 3:
420
+ err_1 = _c.sent();
421
+ return [2 /*return*/, routes.map(function () { return 0; })];
422
+ case 4: return [2 /*return*/];
423
+ }
424
+ });
425
+ }); };
426
+ var _getBestRouteAndOutput = (0, memoizee_1.default)(function (inputCoinAddress, outputCoinAddress, amount) { return __awaiter(void 0, void 0, void 0, function () {
427
+ var _a, inputCoinDecimals, outputCoinDecimals, _amount, routesRaw, routes, calls, multicallContract, _i, routesRaw_1, route, _b, _route, _swapParams, _factorySwapAddresses, _outputAmounts, i, err_2, promises, contract, _c, routesRaw_2, route, _d, _route, _swapParams, _factorySwapAddresses, res, i, _e, gasAmounts, outputCoinUsdRate, gasData, ethUsdRate, gasPrice, expectedAmounts, expectedAmountsUsd, txCostsUsd;
428
+ return __generator(this, function (_f) {
429
+ switch (_f.label) {
430
+ case 0:
431
+ _a = (0, utils_1._getCoinDecimals)(inputCoinAddress, outputCoinAddress), inputCoinDecimals = _a[0], outputCoinDecimals = _a[1];
432
+ _amount = (0, utils_1.parseUnits)(amount, inputCoinDecimals);
433
+ return [4 /*yield*/, (0, exports._findAllRoutes)(inputCoinAddress, outputCoinAddress)];
434
+ case 1:
435
+ routesRaw = (_f.sent()).map(function (steps) { return ({ steps: steps, _output: ethers_1.ethers.BigNumber.from(0), outputUsd: 0, txCostUsd: 0 }); });
436
+ routes = [];
437
+ _f.label = 2;
438
+ case 2:
439
+ _f.trys.push([2, 4, , 6]);
440
+ calls = [];
441
+ multicallContract = curve_1.curve.contracts[curve_1.curve.constants.ALIASES.registry_exchange].multicallContract;
442
+ for (_i = 0, routesRaw_1 = routesRaw; _i < routesRaw_1.length; _i++) {
443
+ route = routesRaw_1[_i];
444
+ _b = _getExchangeMultipleArgs(inputCoinAddress, route), _route = _b._route, _swapParams = _b._swapParams, _factorySwapAddresses = _b._factorySwapAddresses;
445
+ calls.push(multicallContract.get_exchange_multiple_amount(_route, _swapParams, _amount, _factorySwapAddresses));
446
+ }
447
+ return [4 /*yield*/, curve_1.curve.multicallProvider.all(calls)];
448
+ case 3:
449
+ _outputAmounts = _f.sent();
450
+ for (i = 0; i < _outputAmounts.length; i++) {
451
+ routesRaw[i]._output = _outputAmounts[i];
452
+ routes.push(routesRaw[i]);
453
+ }
454
+ return [3 /*break*/, 6];
455
+ case 4:
456
+ err_2 = _f.sent();
457
+ promises = [];
458
+ contract = curve_1.curve.contracts[curve_1.curve.constants.ALIASES.registry_exchange].contract;
459
+ for (_c = 0, routesRaw_2 = routesRaw; _c < routesRaw_2.length; _c++) {
460
+ route = routesRaw_2[_c];
461
+ _d = _getExchangeMultipleArgs(inputCoinAddress, route), _route = _d._route, _swapParams = _d._swapParams, _factorySwapAddresses = _d._factorySwapAddresses;
462
+ promises.push(contract.get_exchange_multiple_amount(_route, _swapParams, _amount, _factorySwapAddresses, curve_1.curve.constantOptions));
463
+ }
464
+ return [4 /*yield*/, Promise.allSettled(promises)];
465
+ case 5:
466
+ res = _f.sent();
467
+ for (i = 0; i < res.length; i++) {
468
+ if (res[i].status === 'rejected') {
469
+ console.log("Route ".concat((routesRaw[i].steps.map(function (s) { return s.poolId; })).join(" --> "), " is anavailable"));
470
+ continue;
471
+ }
472
+ routesRaw[i]._output = res[i].value;
473
+ routes.push(routesRaw[i]);
474
+ }
475
+ return [3 /*break*/, 6];
476
+ case 6:
477
+ if (routes.length === 0) {
478
+ return [2 /*return*/, {
479
+ steps: [],
480
+ _output: ethers_1.ethers.BigNumber.from(0),
481
+ outputUsd: 0,
482
+ txCostUsd: 0,
483
+ }];
484
+ }
485
+ if (routes.length === 1)
486
+ return [2 /*return*/, routes[0]];
487
+ return [4 /*yield*/, Promise.all([
488
+ _estimateGasForDifferentRoutes(routes, inputCoinAddress, outputCoinAddress, _amount),
489
+ (0, utils_1._getUsdRate)(outputCoinAddress),
490
+ axios_1.default.get("https://api.curve.fi/api/getGas"),
491
+ (0, utils_1._getUsdRate)(utils_1.ETH_ADDRESS),
492
+ ])];
493
+ case 7:
494
+ _e = _f.sent(), gasAmounts = _e[0], outputCoinUsdRate = _e[1], gasData = _e[2], ethUsdRate = _e[3];
495
+ gasPrice = gasData.data.data.gas.standard;
496
+ expectedAmounts = (routes).map(function (route) { return Number(ethers_1.ethers.utils.formatUnits(route._output, outputCoinDecimals)); });
497
+ expectedAmountsUsd = expectedAmounts.map(function (a) { return a * outputCoinUsdRate; });
498
+ txCostsUsd = gasAmounts.map(function (a) { return ethUsdRate * a * gasPrice / 1e18; });
499
+ routes.forEach(function (route, i) {
500
+ route.outputUsd = expectedAmountsUsd[i];
501
+ route.txCostUsd = txCostsUsd[i];
502
+ });
503
+ return [2 /*return*/, routes.reduce(function (route1, route2) { return (route1.outputUsd - route1.txCostUsd) - (route2.outputUsd - route2.txCostUsd) >= 0 ? route1 : route2; })];
504
+ }
505
+ });
506
+ }); }, {
507
+ promise: true,
508
+ maxAge: 5 * 60 * 1000, // 5m
509
+ });
510
+ var getBestRouteAndOutput = function (inputCoin, outputCoin, amount) { return __awaiter(void 0, void 0, void 0, function () {
511
+ var _a, inputCoinAddress, outputCoinAddress, outputCoinDecimals, _b, steps, _output;
512
+ return __generator(this, function (_c) {
513
+ switch (_c.label) {
514
+ case 0:
515
+ _a = (0, utils_1._getCoinAddresses)(inputCoin, outputCoin), inputCoinAddress = _a[0], outputCoinAddress = _a[1];
516
+ outputCoinDecimals = (0, utils_1._getCoinDecimals)(outputCoinAddress)[0];
517
+ return [4 /*yield*/, _getBestRouteAndOutput(inputCoinAddress, outputCoinAddress, amount)];
518
+ case 1:
519
+ _b = _c.sent(), steps = _b.steps, _output = _b._output;
520
+ return [2 /*return*/, { route: steps, output: ethers_1.ethers.utils.formatUnits(_output, outputCoinDecimals) }];
521
+ }
522
+ });
523
+ }); };
524
+ exports.getBestRouteAndOutput = getBestRouteAndOutput;
525
+ var swapExpected = function (inputCoin, outputCoin, amount) { return __awaiter(void 0, void 0, void 0, function () {
526
+ return __generator(this, function (_a) {
527
+ switch (_a.label) {
528
+ case 0: return [4 /*yield*/, (0, exports.getBestRouteAndOutput)(inputCoin, outputCoin, amount)];
529
+ case 1: return [2 /*return*/, (_a.sent())['output']];
530
+ }
531
+ });
532
+ }); };
533
+ exports.swapExpected = swapExpected;
534
+ var swapPriceImpact = function (inputCoin, outputCoin, amount) { return __awaiter(void 0, void 0, void 0, function () {
535
+ var _a, inputCoinAddress, outputCoinAddress, _b, inputCoinDecimals, outputCoinDecimals, route, target, amountIntBN, outputIntBN, k, smallAmountIntBN, contract, _smallAmount, _c, _route, _swapParams, _factorySwapAddresses, _smallOutput, amountBN, outputBN, smallAmountBN, smallOutputBN, rateBN, smallRateBN, slippageBN;
536
+ return __generator(this, function (_d) {
537
+ switch (_d.label) {
538
+ case 0:
539
+ _a = (0, utils_1._getCoinAddresses)(inputCoin, outputCoin), inputCoinAddress = _a[0], outputCoinAddress = _a[1];
540
+ _b = (0, utils_1._getCoinDecimals)(inputCoinAddress, outputCoinAddress), inputCoinDecimals = _b[0], outputCoinDecimals = _b[1];
541
+ return [4 /*yield*/, _getBestRouteAndOutput(inputCoinAddress, outputCoinAddress, amount)];
542
+ case 1:
543
+ route = _d.sent();
544
+ target = (0, utils_1.BN)(Math.pow(10, 15));
545
+ amountIntBN = (0, utils_1.BN)(amount).times(Math.pow(10, inputCoinDecimals));
546
+ outputIntBN = (0, utils_1.toBN)(route._output, 0);
547
+ k = bignumber_js_1.default.min(bignumber_js_1.default.max(target.div(amountIntBN), target.div(outputIntBN)), 0.2);
548
+ smallAmountIntBN = bignumber_js_1.default.min(amountIntBN.times(k), (0, utils_1.BN)(Math.pow(10, inputCoinDecimals)));
549
+ if (smallAmountIntBN.toFixed(0) === '0')
550
+ return [2 /*return*/, '0'];
551
+ contract = curve_1.curve.contracts[curve_1.curve.constants.ALIASES.registry_exchange].contract;
552
+ _smallAmount = (0, utils_1.fromBN)(smallAmountIntBN.div(Math.pow(10, inputCoinDecimals)), inputCoinDecimals);
553
+ _c = _getExchangeMultipleArgs(inputCoinAddress, route), _route = _c._route, _swapParams = _c._swapParams, _factorySwapAddresses = _c._factorySwapAddresses;
554
+ return [4 /*yield*/, contract.get_exchange_multiple_amount(_route, _swapParams, _smallAmount, _factorySwapAddresses, curve_1.curve.constantOptions)];
555
+ case 2:
556
+ _smallOutput = _d.sent();
557
+ amountBN = (0, utils_1.BN)(amount);
558
+ outputBN = (0, utils_1.toBN)(route._output, outputCoinDecimals);
559
+ smallAmountBN = (0, utils_1.toBN)(_smallAmount, inputCoinDecimals);
560
+ smallOutputBN = (0, utils_1.toBN)(_smallOutput, outputCoinDecimals);
561
+ rateBN = outputBN.div(amountBN);
562
+ smallRateBN = smallOutputBN.div(smallAmountBN);
563
+ slippageBN = (0, utils_1.BN)(1).minus(rateBN.div(smallRateBN)).times(100);
564
+ return [2 /*return*/, (0, utils_1._cutZeros)(slippageBN.toFixed(6)).replace('-', '')];
565
+ }
566
+ });
567
+ }); };
568
+ exports.swapPriceImpact = swapPriceImpact;
569
+ var swapIsApproved = function (inputCoin, amount) { return __awaiter(void 0, void 0, void 0, function () {
570
+ return __generator(this, function (_a) {
571
+ switch (_a.label) {
572
+ case 0: return [4 /*yield*/, (0, utils_1.hasAllowance)([inputCoin], [amount], curve_1.curve.signerAddress, curve_1.curve.constants.ALIASES.registry_exchange)];
573
+ case 1: return [2 /*return*/, _a.sent()];
574
+ }
575
+ });
576
+ }); };
577
+ exports.swapIsApproved = swapIsApproved;
578
+ var swapApproveEstimateGas = function (inputCoin, amount) { return __awaiter(void 0, void 0, void 0, function () {
579
+ return __generator(this, function (_a) {
580
+ switch (_a.label) {
581
+ case 0: return [4 /*yield*/, (0, utils_1.ensureAllowanceEstimateGas)([inputCoin], [amount], curve_1.curve.constants.ALIASES.registry_exchange)];
582
+ case 1: return [2 /*return*/, _a.sent()];
583
+ }
584
+ });
585
+ }); };
586
+ exports.swapApproveEstimateGas = swapApproveEstimateGas;
587
+ var swapApprove = function (inputCoin, amount) { return __awaiter(void 0, void 0, void 0, function () {
588
+ return __generator(this, function (_a) {
589
+ switch (_a.label) {
590
+ case 0: return [4 /*yield*/, (0, utils_1.ensureAllowance)([inputCoin], [amount], curve_1.curve.constants.ALIASES.registry_exchange)];
591
+ case 1: return [2 /*return*/, _a.sent()];
592
+ }
593
+ });
594
+ }); };
595
+ exports.swapApprove = swapApprove;
596
+ var swapEstimateGas = function (inputCoin, outputCoin, amount) { return __awaiter(void 0, void 0, void 0, function () {
597
+ var _a, inputCoinAddress, outputCoinAddress, inputCoinDecimals, route, _amount, gas;
598
+ return __generator(this, function (_b) {
599
+ switch (_b.label) {
600
+ case 0:
601
+ _a = (0, utils_1._getCoinAddresses)(inputCoin, outputCoin), inputCoinAddress = _a[0], outputCoinAddress = _a[1];
602
+ inputCoinDecimals = (0, utils_1._getCoinDecimals)(inputCoinAddress, outputCoinAddress)[0];
603
+ return [4 /*yield*/, _getBestRouteAndOutput(inputCoinAddress, outputCoinAddress, amount)];
604
+ case 1:
605
+ route = _b.sent();
606
+ _amount = (0, utils_1.parseUnits)(amount, inputCoinDecimals);
607
+ return [4 /*yield*/, _estimateGasForDifferentRoutes([route], inputCoinAddress, outputCoinAddress, _amount)];
608
+ case 2:
609
+ gas = (_b.sent())[0];
610
+ return [2 /*return*/, gas];
611
+ }
612
+ });
613
+ }); };
614
+ exports.swapEstimateGas = swapEstimateGas;
615
+ var swap = function (inputCoin, outputCoin, amount, slippage) {
616
+ if (slippage === void 0) { slippage = 0.5; }
617
+ return __awaiter(void 0, void 0, void 0, function () {
618
+ var _a, inputCoinAddress, outputCoinAddress, _b, inputCoinDecimals, outputCoinDecimals, route, _c, _route, _swapParams, _factorySwapAddresses, _amount, minRecvAmountBN, _minRecvAmount, contract, value, gasLimit;
619
+ return __generator(this, function (_d) {
620
+ switch (_d.label) {
621
+ case 0:
622
+ _a = (0, utils_1._getCoinAddresses)(inputCoin, outputCoin), inputCoinAddress = _a[0], outputCoinAddress = _a[1];
623
+ _b = (0, utils_1._getCoinDecimals)(inputCoinAddress, outputCoinAddress), inputCoinDecimals = _b[0], outputCoinDecimals = _b[1];
624
+ return [4 /*yield*/, (0, exports.swapApprove)(inputCoin, amount)];
625
+ case 1:
626
+ _d.sent();
627
+ return [4 /*yield*/, _getBestRouteAndOutput(inputCoinAddress, outputCoinAddress, amount)];
628
+ case 2:
629
+ route = _d.sent();
630
+ if (route.steps.length === 0) {
631
+ throw new Error("This pair can't be exchanged");
632
+ }
633
+ _c = _getExchangeMultipleArgs(inputCoinAddress, route), _route = _c._route, _swapParams = _c._swapParams, _factorySwapAddresses = _c._factorySwapAddresses;
634
+ _amount = (0, utils_1.parseUnits)(amount, inputCoinDecimals);
635
+ minRecvAmountBN = (0, utils_1.toBN)(route._output, outputCoinDecimals).times(100 - slippage).div(100);
636
+ _minRecvAmount = (0, utils_1.fromBN)(minRecvAmountBN, outputCoinDecimals);
637
+ contract = curve_1.curve.contracts[curve_1.curve.constants.ALIASES.registry_exchange].contract;
638
+ value = (0, utils_1.isEth)(inputCoinAddress) ? _amount : ethers_1.ethers.BigNumber.from(0);
639
+ return [4 /*yield*/, curve_1.curve.updateFeeData()];
640
+ case 3:
641
+ _d.sent();
642
+ return [4 /*yield*/, contract.estimateGas.exchange_multiple(_route, _swapParams, _amount, _minRecvAmount, _factorySwapAddresses, __assign(__assign({}, curve_1.curve.constantOptions), { value: value }))];
643
+ case 4:
644
+ gasLimit = (_d.sent()).mul(curve_1.curve.chainId === 1 ? 130 : 160).div(100);
645
+ return [4 /*yield*/, contract.exchange_multiple(_route, _swapParams, _amount, _minRecvAmount, _factorySwapAddresses, __assign(__assign({}, curve_1.curve.options), { value: value, gasLimit: gasLimit }))];
646
+ case 5: return [2 /*return*/, (_d.sent()).hash];
647
+ }
648
+ });
649
+ });
650
+ };
651
+ exports.swap = swap;