@curvefi/api 2.31.0 → 2.32.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 (100) hide show
  1. package/lib/boosting.js +137 -402
  2. package/lib/constants/abis/stable_calc.json +151 -0
  3. package/lib/constants/abis/wbeth/swap.json +1086 -0
  4. package/lib/constants/aliases.d.ts +11 -11
  5. package/lib/constants/aliases.js +23 -15
  6. package/lib/constants/coins/arbitrum.js +6 -9
  7. package/lib/constants/coins/aurora.js +6 -9
  8. package/lib/constants/coins/avalanche.js +7 -10
  9. package/lib/constants/coins/celo.js +6 -9
  10. package/lib/constants/coins/ethereum.js +10 -13
  11. package/lib/constants/coins/fantom.js +8 -11
  12. package/lib/constants/coins/kava.js +6 -9
  13. package/lib/constants/coins/moonbeam.js +6 -9
  14. package/lib/constants/coins/optimism.js +6 -9
  15. package/lib/constants/coins/polygon.js +7 -10
  16. package/lib/constants/coins/xdai.js +6 -9
  17. package/lib/constants/pools/arbitrum.d.ts +2 -4
  18. package/lib/constants/pools/arbitrum.js +22 -28
  19. package/lib/constants/pools/aurora.d.ts +2 -4
  20. package/lib/constants/pools/aurora.js +6 -12
  21. package/lib/constants/pools/avalanche.d.ts +2 -4
  22. package/lib/constants/pools/avalanche.js +21 -27
  23. package/lib/constants/pools/celo.d.ts +2 -4
  24. package/lib/constants/pools/celo.js +2 -5
  25. package/lib/constants/pools/ethereum.js +272 -253
  26. package/lib/constants/pools/fantom.d.ts +2 -4
  27. package/lib/constants/pools/fantom.js +28 -34
  28. package/lib/constants/pools/index.d.ts +11 -11
  29. package/lib/constants/pools/index.js +12 -25
  30. package/lib/constants/pools/kava.d.ts +2 -4
  31. package/lib/constants/pools/kava.js +2 -5
  32. package/lib/constants/pools/moonbeam.d.ts +2 -4
  33. package/lib/constants/pools/moonbeam.js +6 -12
  34. package/lib/constants/pools/optimism.d.ts +2 -4
  35. package/lib/constants/pools/optimism.js +9 -15
  36. package/lib/constants/pools/polygon.d.ts +2 -4
  37. package/lib/constants/pools/polygon.js +22 -28
  38. package/lib/constants/pools/xdai.d.ts +2 -4
  39. package/lib/constants/pools/xdai.js +24 -30
  40. package/lib/constants/utils.d.ts +1 -1
  41. package/lib/constants/utils.js +20 -29
  42. package/lib/curve.d.ts +9 -7
  43. package/lib/curve.js +399 -615
  44. package/lib/external-api.d.ts +1 -1
  45. package/lib/external-api.js +47 -140
  46. package/lib/factory/common.js +6 -10
  47. package/lib/factory/constants-crypto.js +48 -54
  48. package/lib/factory/constants.js +274 -280
  49. package/lib/factory/deploy.d.ts +8 -8
  50. package/lib/factory/deploy.js +177 -347
  51. package/lib/factory/factory-api.js +195 -278
  52. package/lib/factory/factory-crypto.js +170 -323
  53. package/lib/factory/factory.js +195 -350
  54. package/lib/index.d.ts +24 -25
  55. package/lib/index.js +87 -143
  56. package/lib/interfaces.d.ts +6 -11
  57. package/lib/interfaces.js +1 -2
  58. package/lib/pools/PoolTemplate.js +1478 -2931
  59. package/lib/pools/index.d.ts +2 -2
  60. package/lib/pools/index.js +3 -7
  61. package/lib/pools/mixins/common.d.ts +3 -4
  62. package/lib/pools/mixins/common.js +23 -112
  63. package/lib/pools/mixins/depositBalancedAmountsMixins.d.ts +1 -1
  64. package/lib/pools/mixins/depositBalancedAmountsMixins.js +50 -139
  65. package/lib/pools/mixins/depositMixins.d.ts +1 -1
  66. package/lib/pools/mixins/depositMixins.js +144 -417
  67. package/lib/pools/mixins/depositWrappedMixins.d.ts +1 -1
  68. package/lib/pools/mixins/depositWrappedMixins.js +72 -227
  69. package/lib/pools/mixins/poolBalancesMixin.d.ts +1 -1
  70. package/lib/pools/mixins/poolBalancesMixin.js +25 -105
  71. package/lib/pools/mixins/swapMixins.d.ts +1 -1
  72. package/lib/pools/mixins/swapMixins.js +127 -353
  73. package/lib/pools/mixins/swapWrappedMixins.d.ts +1 -1
  74. package/lib/pools/mixins/swapWrappedMixins.js +90 -276
  75. package/lib/pools/mixins/withdrawExpectedMixins.d.ts +1 -1
  76. package/lib/pools/mixins/withdrawExpectedMixins.js +26 -110
  77. package/lib/pools/mixins/withdrawImbalanceMixins.d.ts +1 -1
  78. package/lib/pools/mixins/withdrawImbalanceMixins.js +99 -321
  79. package/lib/pools/mixins/withdrawImbalanceWrappedMixins.d.ts +1 -1
  80. package/lib/pools/mixins/withdrawImbalanceWrappedMixins.js +53 -192
  81. package/lib/pools/mixins/withdrawMixins.d.ts +1 -1
  82. package/lib/pools/mixins/withdrawMixins.js +123 -390
  83. package/lib/pools/mixins/withdrawOneCoinExpectedMixins.d.ts +1 -1
  84. package/lib/pools/mixins/withdrawOneCoinExpectedMixins.js +17 -92
  85. package/lib/pools/mixins/withdrawOneCoinMixins.d.ts +1 -1
  86. package/lib/pools/mixins/withdrawOneCoinMixins.js +124 -390
  87. package/lib/pools/mixins/withdrawOneCoinWrappedExpectedMixins.d.ts +1 -1
  88. package/lib/pools/mixins/withdrawOneCoinWrappedExpectedMixins.js +9 -66
  89. package/lib/pools/mixins/withdrawOneCoinWrappedMixins.d.ts +1 -1
  90. package/lib/pools/mixins/withdrawOneCoinWrappedMixins.js +55 -190
  91. package/lib/pools/mixins/withdrawWrappedMixins.d.ts +1 -1
  92. package/lib/pools/mixins/withdrawWrappedMixins.js +52 -191
  93. package/lib/pools/poolConstructor.d.ts +1 -1
  94. package/lib/pools/poolConstructor.js +77 -101
  95. package/lib/pools/utils.js +299 -500
  96. package/lib/router.d.ts +2 -2
  97. package/lib/router.js +221 -689
  98. package/lib/utils.d.ts +9 -9
  99. package/lib/utils.js +377 -731
  100. package/package.json +9 -8
@@ -1,1120 +1,697 @@
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 (g && (g = 0, op[0] && (_ = 0)), _) 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;
1
+ import memoize from "memoizee";
2
+ import { _getPoolsFromApi, _getSubgraphData, _getFactoryAPYsAndVolumes, _getLegacyAPYsAndVolumes } from '../external-api.js';
3
+ import { _getCoinAddresses, _getBalances, _prepareAddresses, _ensureAllowance, _getUsdRate, hasAllowance, ensureAllowance, ensureAllowanceEstimateGas, BN, toBN, toStringFromBN, parseUnits, getEthIndex, fromBN, _cutZeros, _setContracts, _get_small_x, _get_price_impact, checkNumber, _getCrvApyFromApi, _getRewardsFromApi, mulBy1_3, } from '../utils.js';
4
+ import { curve as _curve, curve } from "../curve.js";
5
+ import ERC20Abi from '../constants/abis/ERC20.json' assert { type: 'json' };
6
+ const DAY = 86400;
7
+ const WEEK = 7 * DAY;
8
+ const MONTH = 30 * DAY;
9
+ const YEAR = 365 * DAY;
10
+ export class PoolTemplate {
11
+ constructor(id) {
12
+ this.statsParameters = async () => {
13
+ const multicallContract = curve.contracts[this.address].multicallContract;
14
+ const lpMulticallContract = curve.contracts[this.lpToken].multicallContract;
15
+ const calls = [
16
+ multicallContract.get_virtual_price(),
17
+ multicallContract.fee(),
18
+ multicallContract.admin_fee(),
19
+ multicallContract.A(),
20
+ lpMulticallContract.totalSupply(),
21
+ ];
22
+ if (this.isCrypto) {
23
+ calls.push(multicallContract.gamma());
24
+ if (this.wrappedCoins.length === 2) {
25
+ calls.push(multicallContract.price_oracle());
26
+ calls.push(multicallContract.price_scale());
27
+ }
28
+ else {
29
+ for (let i = 0; i < this.wrappedCoins.length - 1; i++) {
30
+ calls.push(multicallContract.price_oracle(i));
31
+ calls.push(multicallContract.price_scale(i));
32
+ }
33
+ }
43
34
  }
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.PoolTemplate = void 0;
63
- var ethers_1 = require("ethers");
64
- var memoizee_1 = __importDefault(require("memoizee"));
65
- var external_api_1 = require("../external-api");
66
- var utils_1 = require("../utils");
67
- var curve_1 = require("../curve");
68
- var ERC20_json_1 = __importDefault(require("../constants/abis/ERC20.json"));
69
- var DAY = 86400;
70
- var WEEK = 7 * DAY;
71
- var MONTH = 30 * DAY;
72
- var YEAR = 365 * DAY;
73
- var PoolTemplate = /** @class */ (function () {
74
- function PoolTemplate(id) {
75
- var _this = this;
76
- var _c, _d;
77
- this.statsParameters = function () { return __awaiter(_this, void 0, void 0, function () {
78
- var multicallContract, lpMulticallContract, calls, i, additionalCalls, _virtualPrice, _fee, _prices, _adminFee, _A, _lpTokenSupply, _gamma, e_1, _c, virtualPrice, fee, adminFee, A, lpTokenSupply, gamma, priceOracle, priceScale, prices, i, A_PRECISION, _d, _future_A, _initial_A, _future_A_time, _initial_A_time, _e, future_A, initial_A, future_A_time, initial_A_time;
79
- var _f, _g, _h;
80
- return __generator(this, function (_j) {
81
- switch (_j.label) {
82
- case 0:
83
- multicallContract = curve_1.curve.contracts[this.address].multicallContract;
84
- lpMulticallContract = curve_1.curve.contracts[this.lpToken].multicallContract;
85
- calls = [
86
- multicallContract.get_virtual_price(),
87
- multicallContract.fee(),
88
- multicallContract.admin_fee(),
89
- multicallContract.A(),
90
- lpMulticallContract.totalSupply(),
91
- ];
92
- if (this.isCrypto) {
93
- calls.push(multicallContract.gamma());
94
- if (this.wrappedCoins.length === 2) {
95
- calls.push(multicallContract.price_oracle());
96
- calls.push(multicallContract.price_scale());
97
- }
98
- else {
99
- for (i = 0; i < this.wrappedCoins.length - 1; i++) {
100
- calls.push(multicallContract.price_oracle(i));
101
- calls.push(multicallContract.price_scale(i));
102
- }
103
- }
104
- }
105
- additionalCalls = this.isCrypto ? [] : [multicallContract.future_A()];
106
- if ('initial_A' in multicallContract) {
107
- additionalCalls.push(multicallContract.initial_A(), multicallContract.future_A_time(), multicallContract.initial_A_time());
108
- }
109
- _virtualPrice = ethers_1.ethers.BigNumber.from(0);
110
- _fee = ethers_1.ethers.BigNumber.from(0);
111
- _j.label = 1;
112
- case 1:
113
- _j.trys.push([1, 3, , 8]);
114
- return [4 /*yield*/, curve_1.curve.multicallProvider.all(calls)];
115
- case 2:
116
- _f = (_j.sent()), _virtualPrice = _f[0], _fee = _f[1], _adminFee = _f[2], _A = _f[3], _lpTokenSupply = _f[4], _gamma = _f[5], _prices = _f.slice(6);
117
- return [3 /*break*/, 8];
118
- case 3:
119
- e_1 = _j.sent();
120
- calls.shift();
121
- if (!this.isCrypto) return [3 /*break*/, 5];
122
- calls.shift();
123
- return [4 /*yield*/, curve_1.curve.multicallProvider.all(calls)];
124
- case 4:
125
- _g = (_j.sent()), _adminFee = _g[0], _A = _g[1], _lpTokenSupply = _g[2], _gamma = _g[3], _prices = _g.slice(4);
126
- return [3 /*break*/, 7];
127
- case 5: return [4 /*yield*/, curve_1.curve.multicallProvider.all(calls)];
128
- case 6:
129
- _h = (_j.sent()), _fee = _h[0], _adminFee = _h[1], _A = _h[2], _lpTokenSupply = _h[3], _gamma = _h[4], _prices = _h.slice(5);
130
- _j.label = 7;
131
- case 7: return [3 /*break*/, 8];
132
- case 8:
133
- _c = [
134
- ethers_1.ethers.utils.formatUnits(_virtualPrice),
135
- ethers_1.ethers.utils.formatUnits(_fee, 8),
136
- ethers_1.ethers.utils.formatUnits(_adminFee.mul(_fee)),
137
- ethers_1.ethers.utils.formatUnits(_A, 0),
138
- ethers_1.ethers.utils.formatUnits(_lpTokenSupply),
139
- _gamma ? ethers_1.ethers.utils.formatUnits(_gamma) : _gamma,
140
- ], virtualPrice = _c[0], fee = _c[1], adminFee = _c[2], A = _c[3], lpTokenSupply = _c[4], gamma = _c[5];
141
- if (this.isCrypto) {
142
- prices = _prices.map(function (_p) { return ethers_1.ethers.utils.formatUnits(_p); });
143
- priceOracle = [];
144
- priceScale = [];
145
- for (i = 0; i < this.wrappedCoins.length - 1; i++) {
146
- priceOracle.push(prices.shift());
147
- priceScale.push(prices.shift());
148
- }
149
- }
150
- A_PRECISION = curve_1.curve.chainId === 1 && ['compound', 'usdt', 'y', 'busd', 'susd', 'pax', 'ren', 'sbtc', 'hbtc', '3pool'].includes(this.id) ? 1 : 100;
151
- return [4 /*yield*/, curve_1.curve.multicallProvider.all(additionalCalls)];
152
- case 9:
153
- _d = _j.sent(), _future_A = _d[0], _initial_A = _d[1], _future_A_time = _d[2], _initial_A_time = _d[3];
154
- _e = [
155
- _future_A ? String(Number(ethers_1.ethers.utils.formatUnits(_future_A, 0)) / A_PRECISION) : undefined,
156
- _initial_A ? String(Number(ethers_1.ethers.utils.formatUnits(_initial_A, 0)) / A_PRECISION) : undefined,
157
- _future_A_time ? Number(ethers_1.ethers.utils.formatUnits(_future_A_time, 0)) * 1000 : undefined,
158
- _initial_A_time ? Number(ethers_1.ethers.utils.formatUnits(_initial_A_time, 0)) * 1000 : undefined,
159
- ], future_A = _e[0], initial_A = _e[1], future_A_time = _e[2], initial_A_time = _e[3];
160
- return [2 /*return*/, { lpTokenSupply: lpTokenSupply, virtualPrice: virtualPrice, fee: fee, adminFee: adminFee, A: A, future_A: future_A, initial_A: initial_A, future_A_time: future_A_time, initial_A_time: initial_A_time, gamma: gamma, priceOracle: priceOracle, priceScale: priceScale }];
35
+ const additionalCalls = this.isCrypto ? [] : [multicallContract.future_A()];
36
+ if ('initial_A' in multicallContract) {
37
+ additionalCalls.push(multicallContract.initial_A(), multicallContract.future_A_time(), multicallContract.initial_A_time());
38
+ }
39
+ let _virtualPrice = 0n;
40
+ let _fee = 0n;
41
+ let _prices, _adminFee, _A, _lpTokenSupply, _gamma;
42
+ try {
43
+ [_virtualPrice, _fee, _adminFee, _A, _lpTokenSupply, _gamma, ..._prices] = await curve.multicallProvider.all(calls);
44
+ }
45
+ catch (e) { // Empty pool
46
+ calls.shift();
47
+ if (this.isCrypto) {
48
+ calls.shift();
49
+ [_adminFee, _A, _lpTokenSupply, _gamma, ..._prices] = await curve.multicallProvider.all(calls);
161
50
  }
162
- });
163
- }); };
164
- this.statsTotalLiquidity = function (useApi) {
165
- if (useApi === void 0) { useApi = true; }
166
- return __awaiter(_this, void 0, void 0, function () {
167
- var network, poolType, poolsData, totalLiquidity_1, balances, promises, _i, _c, addr, prices, totalLiquidity;
168
- var _this = this;
169
- return __generator(this, function (_d) {
170
- switch (_d.label) {
171
- case 0:
172
- if (!useApi) return [3 /*break*/, 2];
173
- network = curve_1.curve.constants.NETWORK_NAME;
174
- poolType = !this.isFactory && !this.isCrypto ? "main" :
175
- !this.isFactory ? "crypto" :
176
- !(this.isCrypto && this.isFactory) ? "factory" :
177
- "factory-crypto";
178
- return [4 /*yield*/, (0, external_api_1._getPoolsFromApi)(network, poolType)];
179
- case 1:
180
- poolsData = (_d.sent()).poolData;
181
- try {
182
- totalLiquidity_1 = poolsData.filter(function (data) { return data.address.toLowerCase() === _this.address.toLowerCase(); })[0].usdTotal;
183
- return [2 /*return*/, String(totalLiquidity_1)];
184
- }
185
- catch (err) {
186
- console.log(this.id, err.message);
187
- }
188
- _d.label = 2;
189
- case 2: return [4 /*yield*/, this.statsUnderlyingBalances()];
190
- case 3:
191
- balances = _d.sent();
192
- promises = [];
193
- for (_i = 0, _c = this.underlyingCoinAddresses; _i < _c.length; _i++) {
194
- addr = _c[_i];
195
- promises.push((0, utils_1._getUsdRate)(addr));
196
- }
197
- return [4 /*yield*/, Promise.all(promises)];
198
- case 4:
199
- prices = _d.sent();
200
- totalLiquidity = balances.reduce(function (liquidity, b, i) { return liquidity + (Number(b) * prices[i]); }, 0);
201
- return [2 /*return*/, totalLiquidity.toFixed(8)];
202
- }
203
- });
204
- });
51
+ else {
52
+ [_fee, _adminFee, _A, _lpTokenSupply, _gamma, ..._prices] = await curve.multicallProvider.all(calls);
53
+ }
54
+ }
55
+ const [virtualPrice, fee, adminFee, A, lpTokenSupply, gamma] = [
56
+ curve.formatUnits(_virtualPrice),
57
+ curve.formatUnits(_fee, 8),
58
+ curve.formatUnits(_adminFee * _fee),
59
+ curve.formatUnits(_A, 0),
60
+ curve.formatUnits(_lpTokenSupply),
61
+ _gamma ? curve.formatUnits(_gamma) : undefined,
62
+ ];
63
+ let priceOracle, priceScale;
64
+ if (this.isCrypto) {
65
+ const prices = _prices.map((_p) => curve.formatUnits(_p));
66
+ priceOracle = [];
67
+ priceScale = [];
68
+ for (let i = 0; i < this.wrappedCoins.length - 1; i++) {
69
+ priceOracle.push(prices.shift());
70
+ priceScale.push(prices.shift());
71
+ }
72
+ }
73
+ const A_PRECISION = curve.chainId === 1 && ['compound', 'usdt', 'y', 'busd', 'susd', 'pax', 'ren', 'sbtc', 'hbtc', '3pool'].includes(this.id) ? 1 : 100;
74
+ const [_future_A, _initial_A, _future_A_time, _initial_A_time] = await curve.multicallProvider.all(additionalCalls);
75
+ const [future_A, initial_A, future_A_time, initial_A_time] = [
76
+ _future_A ? String(Number(curve.formatUnits(_future_A, 0)) / A_PRECISION) : undefined,
77
+ _initial_A ? String(Number(curve.formatUnits(_initial_A, 0)) / A_PRECISION) : undefined,
78
+ _future_A_time ? Number(curve.formatUnits(_future_A_time, 0)) * 1000 : undefined,
79
+ _initial_A_time ? Number(curve.formatUnits(_initial_A_time, 0)) * 1000 : undefined,
80
+ ];
81
+ return { lpTokenSupply, virtualPrice, fee, adminFee, A, future_A, initial_A, future_A_time, initial_A_time, gamma, priceOracle, priceScale };
205
82
  };
206
- this.statsVolume = function () { return __awaiter(_this, void 0, void 0, function () {
207
- var _c, mainPoolsData, factoryPoolsData, poolData_1, lpPrice, network, poolsData, poolData;
208
- var _this = this;
209
- var _d;
210
- return __generator(this, function (_e) {
211
- switch (_e.label) {
212
- case 0:
213
- if (![1284, 2222, 42220, 1313161554].includes(curve_1.curve.chainId)) return [3 /*break*/, 3];
214
- return [4 /*yield*/, Promise.all([
215
- (0, external_api_1._getLegacyAPYsAndVolumes)(curve_1.curve.constants.NETWORK_NAME),
216
- (0, external_api_1._getFactoryAPYsAndVolumes)(curve_1.curve.constants.NETWORK_NAME),
217
- ])];
218
- case 1:
219
- _c = _e.sent(), mainPoolsData = _c[0], factoryPoolsData = _c[1];
220
- if (this.id in mainPoolsData) {
221
- return [2 /*return*/, ((_d = mainPoolsData[this.id].volume) !== null && _d !== void 0 ? _d : 0).toString()];
222
- }
223
- poolData_1 = factoryPoolsData.find(function (d) { return d.poolAddress.toLowerCase() === _this.address; });
224
- if (!poolData_1)
225
- throw Error("Can't get Volume for ".concat(this.name, " (id: ").concat(this.id, ")"));
226
- return [4 /*yield*/, (0, utils_1._getUsdRate)(this.lpToken)];
227
- case 2:
228
- lpPrice = _e.sent();
229
- return [2 /*return*/, (poolData_1.volume * lpPrice).toString()];
230
- case 3:
231
- network = curve_1.curve.constants.NETWORK_NAME;
232
- return [4 /*yield*/, (0, external_api_1._getSubgraphData)(network)];
233
- case 4:
234
- poolsData = (_e.sent()).poolsData;
235
- poolData = poolsData.find(function (d) { return d.address.toLowerCase() === _this.address; });
236
- if (!poolData)
237
- throw Error("Can't get Volume for ".concat(this.name, " (id: ").concat(this.id, ")"));
238
- return [2 /*return*/, poolData.volumeUSD.toString()];
83
+ this.statsTotalLiquidity = async (useApi = true) => {
84
+ if (useApi) {
85
+ const network = curve.constants.NETWORK_NAME;
86
+ const poolType = !this.isFactory && !this.isCrypto ? "main" :
87
+ !this.isFactory ? "crypto" :
88
+ !(this.isCrypto && this.isFactory) ? "factory" :
89
+ "factory-crypto";
90
+ const poolsData = (await _getPoolsFromApi(network, poolType)).poolData;
91
+ try {
92
+ const totalLiquidity = poolsData.filter((data) => data.address.toLowerCase() === this.address.toLowerCase())[0].usdTotal;
93
+ return String(totalLiquidity);
94
+ }
95
+ catch (err) {
96
+ console.log(this.id, err.message);
239
97
  }
240
- });
241
- }); };
242
- this.statsBaseApy = function () { return __awaiter(_this, void 0, void 0, function () {
243
- var _c, mainPoolsData, factoryPoolsData, poolData_2, network, poolsData, poolData;
244
- var _this = this;
245
- return __generator(this, function (_d) {
246
- switch (_d.label) {
247
- case 0:
248
- if (![1284, 2222, 42220, 1313161554].includes(curve_1.curve.chainId)) return [3 /*break*/, 2];
249
- return [4 /*yield*/, Promise.all([
250
- (0, external_api_1._getLegacyAPYsAndVolumes)(curve_1.curve.constants.NETWORK_NAME),
251
- (0, external_api_1._getFactoryAPYsAndVolumes)(curve_1.curve.constants.NETWORK_NAME),
252
- ])];
253
- case 1:
254
- _c = _d.sent(), mainPoolsData = _c[0], factoryPoolsData = _c[1];
255
- if (this.id in mainPoolsData) {
256
- return [2 /*return*/, {
257
- day: mainPoolsData[this.id].apy.day.toString(),
258
- week: mainPoolsData[this.id].apy.week.toString(),
259
- }];
260
- }
261
- poolData_2 = factoryPoolsData.find(function (d) { return d.poolAddress.toLowerCase() === _this.address; });
262
- if (!poolData_2)
263
- throw Error("Can't get base APY for ".concat(this.name, " (id: ").concat(this.id, ")"));
264
- return [2 /*return*/, {
265
- day: poolData_2.apy.toString(),
266
- week: poolData_2.apy.toString(),
267
- }];
268
- case 2:
269
- network = curve_1.curve.constants.NETWORK_NAME;
270
- return [4 /*yield*/, (0, external_api_1._getSubgraphData)(network)];
271
- case 3:
272
- poolsData = (_d.sent()).poolsData;
273
- poolData = poolsData.find(function (d) { return d.address.toLowerCase() === _this.address; });
274
- if (!poolData)
275
- throw Error("Can't get base APY for ".concat(this.name, " (id: ").concat(this.id, ")"));
276
- return [2 /*return*/, {
277
- day: poolData.latestDailyApy.toString(),
278
- week: poolData.latestWeeklyApy.toString(),
279
- }];
98
+ }
99
+ const balances = await this.statsUnderlyingBalances();
100
+ const promises = [];
101
+ for (const addr of this.underlyingCoinAddresses) {
102
+ promises.push(_getUsdRate(addr));
103
+ }
104
+ const prices = await Promise.all(promises);
105
+ const totalLiquidity = balances.reduce((liquidity, b, i) => liquidity + (Number(b) * prices[i]), 0);
106
+ return totalLiquidity.toFixed(8);
107
+ };
108
+ this.statsVolume = async () => {
109
+ if ([1284, 2222, 42220, 1313161554].includes(curve.chainId)) { // Moonbeam || Kava || Celo || Aurora
110
+ const [mainPoolsData, factoryPoolsData] = await Promise.all([
111
+ _getLegacyAPYsAndVolumes(curve.constants.NETWORK_NAME),
112
+ _getFactoryAPYsAndVolumes(curve.constants.NETWORK_NAME),
113
+ ]);
114
+ if (this.id in mainPoolsData) {
115
+ return (mainPoolsData[this.id].volume ?? 0).toString();
116
+ }
117
+ const poolData = factoryPoolsData.find((d) => d.poolAddress.toLowerCase() === this.address);
118
+ if (!poolData)
119
+ throw Error(`Can't get Volume for ${this.name} (id: ${this.id})`);
120
+ const lpPrice = await _getUsdRate(this.lpToken);
121
+ return (poolData.volume * lpPrice).toString();
122
+ }
123
+ const network = curve.constants.NETWORK_NAME;
124
+ const poolsData = (await _getSubgraphData(network)).poolsData;
125
+ const poolData = poolsData.find((d) => d.address.toLowerCase() === this.address);
126
+ if (!poolData)
127
+ throw Error(`Can't get Volume for ${this.name} (id: ${this.id})`);
128
+ return poolData.volumeUSD.toString();
129
+ };
130
+ this.statsBaseApy = async () => {
131
+ if ([1284, 2222, 42220, 1313161554].includes(curve.chainId)) { // Moonbeam || Kava || Celo || Aurora
132
+ const [mainPoolsData, factoryPoolsData] = await Promise.all([
133
+ _getLegacyAPYsAndVolumes(curve.constants.NETWORK_NAME),
134
+ _getFactoryAPYsAndVolumes(curve.constants.NETWORK_NAME),
135
+ ]);
136
+ if (this.id in mainPoolsData) {
137
+ return {
138
+ day: mainPoolsData[this.id].apy.day.toString(),
139
+ week: mainPoolsData[this.id].apy.week.toString(),
140
+ };
141
+ }
142
+ const poolData = factoryPoolsData.find((d) => d.poolAddress.toLowerCase() === this.address);
143
+ if (!poolData)
144
+ throw Error(`Can't get base APY for ${this.name} (id: ${this.id})`);
145
+ return {
146
+ day: poolData.apy.toString(),
147
+ week: poolData.apy.toString(),
148
+ };
149
+ }
150
+ const network = curve.constants.NETWORK_NAME;
151
+ const poolsData = (await _getSubgraphData(network)).poolsData;
152
+ const poolData = poolsData.find((d) => d.address.toLowerCase() === this.address);
153
+ if (!poolData)
154
+ throw Error(`Can't get base APY for ${this.name} (id: ${this.id})`);
155
+ return {
156
+ day: poolData.latestDailyApy.toString(),
157
+ week: poolData.latestWeeklyApy.toString(),
158
+ };
159
+ };
160
+ this.statsTokenApy = async (useApi = true) => {
161
+ if (this.rewardsOnly())
162
+ throw Error(`${this.name} has Rewards-Only Gauge. Use stats.rewardsApy instead`);
163
+ const isDisabledChain = [1313161554].includes(curve.chainId); // Disable Aurora
164
+ if (useApi && !isDisabledChain) {
165
+ const crvAPYs = await _getCrvApyFromApi();
166
+ const poolCrvApy = crvAPYs[this.gauge] ?? [0, 0]; // new pools might be missing
167
+ return [poolCrvApy[0], poolCrvApy[1]];
168
+ }
169
+ const totalLiquidityUSD = await this.statsTotalLiquidity();
170
+ if (Number(totalLiquidityUSD) === 0)
171
+ return [0, 0];
172
+ let inflationRateBN, workingSupplyBN, totalSupplyBN;
173
+ if (curve.chainId !== 1) {
174
+ const gaugeContract = curve.contracts[this.gauge].multicallContract;
175
+ const lpTokenContract = curve.contracts[this.lpToken].multicallContract;
176
+ const crvContract = curve.contracts[curve.constants.ALIASES.crv].contract;
177
+ const currentWeek = Math.floor(Date.now() / 1000 / WEEK);
178
+ [inflationRateBN, workingSupplyBN, totalSupplyBN] = (await curve.multicallProvider.all([
179
+ gaugeContract.inflation_rate(currentWeek),
180
+ gaugeContract.working_supply(),
181
+ lpTokenContract.totalSupply(),
182
+ ])).map((value) => toBN(value));
183
+ if (inflationRateBN.eq(0)) {
184
+ inflationRateBN = toBN(await crvContract.balanceOf(this.gauge, curve.constantOptions)).div(WEEK);
280
185
  }
281
- });
282
- }); };
283
- this.statsTokenApy = function (useApi) {
284
- if (useApi === void 0) { useApi = true; }
285
- return __awaiter(_this, void 0, void 0, function () {
286
- var isDisabledChain, crvAPYs, poolCrvApy, totalLiquidityUSD, inflationRateBN, workingSupplyBN, totalSupplyBN, gaugeContract, lpTokenContract, crvContract, currentWeek, _c, gaugeContract, lpTokenContract, gaugeControllerContract, weightBN, rateBN, crvPrice, baseApyBN, boostedApyBN;
287
- var _d, _e;
288
- var _f;
289
- return __generator(this, function (_g) {
290
- switch (_g.label) {
291
- case 0:
292
- if (this.rewardsOnly())
293
- throw Error("".concat(this.name, " has Rewards-Only Gauge. Use stats.rewardsApy instead"));
294
- isDisabledChain = [1313161554].includes(curve_1.curve.chainId);
295
- if (!(useApi && !isDisabledChain)) return [3 /*break*/, 2];
296
- return [4 /*yield*/, (0, utils_1._getCrvApyFromApi)()];
297
- case 1:
298
- crvAPYs = _g.sent();
299
- poolCrvApy = (_f = crvAPYs[this.gauge]) !== null && _f !== void 0 ? _f : [0, 0];
300
- return [2 /*return*/, [poolCrvApy[0], poolCrvApy[1]]];
301
- case 2: return [4 /*yield*/, this.statsTotalLiquidity()];
302
- case 3:
303
- totalLiquidityUSD = _g.sent();
304
- if (Number(totalLiquidityUSD) === 0)
305
- return [2 /*return*/, [0, 0]];
306
- if (!(curve_1.curve.chainId !== 1)) return [3 /*break*/, 7];
307
- gaugeContract = curve_1.curve.contracts[this.gauge].multicallContract;
308
- lpTokenContract = curve_1.curve.contracts[this.lpToken].multicallContract;
309
- crvContract = curve_1.curve.contracts[curve_1.curve.constants.ALIASES.crv].contract;
310
- currentWeek = Math.floor(Date.now() / 1000 / WEEK);
311
- return [4 /*yield*/, curve_1.curve.multicallProvider.all([
312
- gaugeContract.inflation_rate(currentWeek),
313
- gaugeContract.working_supply(),
314
- lpTokenContract.totalSupply(),
315
- ])];
316
- case 4:
317
- _d = (_g.sent()).map(function (value) { return (0, utils_1.toBN)(value); }), inflationRateBN = _d[0], workingSupplyBN = _d[1], totalSupplyBN = _d[2];
318
- if (!inflationRateBN.eq(0)) return [3 /*break*/, 6];
319
- _c = utils_1.toBN;
320
- return [4 /*yield*/, crvContract.balanceOf(this.gauge, curve_1.curve.constantOptions)];
321
- case 5:
322
- inflationRateBN = _c.apply(void 0, [_g.sent()]).div(WEEK);
323
- _g.label = 6;
324
- case 6: return [3 /*break*/, 9];
325
- case 7:
326
- gaugeContract = curve_1.curve.contracts[this.gauge].multicallContract;
327
- lpTokenContract = curve_1.curve.contracts[this.lpToken].multicallContract;
328
- gaugeControllerContract = curve_1.curve.contracts[curve_1.curve.constants.ALIASES.gauge_controller].multicallContract;
329
- weightBN = void 0;
330
- return [4 /*yield*/, curve_1.curve.multicallProvider.all([
331
- gaugeContract.inflation_rate(),
332
- gaugeControllerContract.gauge_relative_weight(this.gauge),
333
- gaugeContract.working_supply(),
334
- lpTokenContract.totalSupply(),
335
- ])];
336
- case 8:
337
- _e = (_g.sent()).map(function (value) { return (0, utils_1.toBN)(value); }), inflationRateBN = _e[0], weightBN = _e[1], workingSupplyBN = _e[2], totalSupplyBN = _e[3];
338
- inflationRateBN = inflationRateBN.times(weightBN);
339
- _g.label = 9;
340
- case 9:
341
- if (inflationRateBN.eq(0))
342
- return [2 /*return*/, [0, 0]];
343
- rateBN = inflationRateBN.times(31536000).times(0.4).div(workingSupplyBN).times(totalSupplyBN).div(Number(totalLiquidityUSD));
344
- return [4 /*yield*/, (0, utils_1._getUsdRate)(curve_1.curve.constants.ALIASES.crv)];
345
- case 10:
346
- crvPrice = _g.sent();
347
- baseApyBN = rateBN.times(crvPrice);
348
- boostedApyBN = baseApyBN.times(2.5);
349
- return [2 /*return*/, [baseApyBN.times(100).toNumber(), boostedApyBN.times(100).toNumber()]];
350
- }
351
- });
352
- });
186
+ }
187
+ else {
188
+ const gaugeContract = curve.contracts[this.gauge].multicallContract;
189
+ const lpTokenContract = curve.contracts[this.lpToken].multicallContract;
190
+ const gaugeControllerContract = curve.contracts[curve.constants.ALIASES.gauge_controller].multicallContract;
191
+ let weightBN;
192
+ [inflationRateBN, weightBN, workingSupplyBN, totalSupplyBN] = (await curve.multicallProvider.all([
193
+ gaugeContract.inflation_rate(),
194
+ gaugeControllerContract.gauge_relative_weight(this.gauge),
195
+ gaugeContract.working_supply(),
196
+ lpTokenContract.totalSupply(),
197
+ ])).map((value) => toBN(value));
198
+ inflationRateBN = inflationRateBN.times(weightBN);
199
+ }
200
+ if (inflationRateBN.eq(0))
201
+ return [0, 0];
202
+ const rateBN = inflationRateBN.times(31536000).times(0.4).div(workingSupplyBN).times(totalSupplyBN).div(Number(totalLiquidityUSD));
203
+ const crvPrice = await _getUsdRate(curve.constants.ALIASES.crv);
204
+ const baseApyBN = rateBN.times(crvPrice);
205
+ const boostedApyBN = baseApyBN.times(2.5);
206
+ return [baseApyBN.times(100).toNumber(), boostedApyBN.times(100).toNumber()];
353
207
  };
354
- this.statsRewardsApy = function (useApi) {
355
- if (useApi === void 0) { useApi = true; }
356
- return __awaiter(_this, void 0, void 0, function () {
357
- var isDisabledChain, rewards, apy, rewardTokens, _i, rewardTokens_1, rewardToken, gaugeContract, lpTokenContract, rewardContract, totalLiquidityUSD, rewardRate, _c, rewardData, _stakedSupply, _totalSupply, stakedSupplyBN, totalSupplyBN, inflationBN, periodFinish, baseApy;
358
- return __generator(this, function (_d) {
359
- switch (_d.label) {
360
- case 0:
361
- if (this.gauge === ethers_1.ethers.constants.AddressZero)
362
- return [2 /*return*/, []];
363
- isDisabledChain = [1313161554].includes(curve_1.curve.chainId);
364
- if (!(curve_1.curve.chainId === 1 || (useApi && !isDisabledChain))) return [3 /*break*/, 2];
365
- return [4 /*yield*/, (0, utils_1._getRewardsFromApi)()];
366
- case 1:
367
- rewards = _d.sent();
368
- if (!rewards[this.gauge])
369
- return [2 /*return*/, []];
370
- return [2 /*return*/, rewards[this.gauge].map(function (r) { return ({ gaugeAddress: r.gaugeAddress, tokenAddress: r.tokenAddress, symbol: r.symbol, apy: r.apy }); })];
371
- case 2:
372
- apy = [];
373
- return [4 /*yield*/, this.rewardTokens(false)];
374
- case 3:
375
- rewardTokens = _d.sent();
376
- _i = 0, rewardTokens_1 = rewardTokens;
377
- _d.label = 4;
378
- case 4:
379
- if (!(_i < rewardTokens_1.length)) return [3 /*break*/, 9];
380
- rewardToken = rewardTokens_1[_i];
381
- gaugeContract = curve_1.curve.contracts[this.gauge].multicallContract;
382
- lpTokenContract = curve_1.curve.contracts[this.lpToken].multicallContract;
383
- rewardContract = curve_1.curve.contracts[this.sRewardContract || this.gauge].multicallContract;
384
- return [4 /*yield*/, this.statsTotalLiquidity()];
385
- case 5:
386
- totalLiquidityUSD = _d.sent();
387
- return [4 /*yield*/, (0, utils_1._getUsdRate)(rewardToken.token)];
388
- case 6:
389
- rewardRate = _d.sent();
390
- return [4 /*yield*/, curve_1.curve.multicallProvider.all([
391
- rewardContract.reward_data(rewardToken.token),
392
- gaugeContract.totalSupply(),
393
- lpTokenContract.totalSupply(),
394
- ])];
395
- case 7:
396
- _c = _d.sent(), rewardData = _c[0], _stakedSupply = _c[1], _totalSupply = _c[2];
397
- stakedSupplyBN = (0, utils_1.toBN)(_stakedSupply);
398
- totalSupplyBN = (0, utils_1.toBN)(_totalSupply);
399
- inflationBN = (0, utils_1.toBN)(rewardData.rate, rewardToken.decimals);
400
- periodFinish = Number(ethers_1.ethers.utils.formatUnits(rewardData.period_finish, 0)) * 1000;
401
- baseApy = periodFinish > Date.now() ?
402
- inflationBN.times(31536000).times(rewardRate).div(stakedSupplyBN).times(totalSupplyBN).div(Number(totalLiquidityUSD)) :
403
- (0, utils_1.BN)(0);
404
- apy.push({
405
- gaugeAddress: this.gauge,
406
- tokenAddress: rewardToken.token,
407
- symbol: rewardToken.symbol,
408
- apy: baseApy.times(100).toNumber(),
409
- });
410
- _d.label = 8;
411
- case 8:
412
- _i++;
413
- return [3 /*break*/, 4];
414
- case 9: return [2 /*return*/, apy];
415
- }
208
+ this.statsRewardsApy = async (useApi = true) => {
209
+ if (this.gauge === curve.constants.ZERO_ADDRESS)
210
+ return [];
211
+ const isDisabledChain = [1313161554].includes(curve.chainId); // Disable Aurora
212
+ if (curve.chainId === 1 || (useApi && !isDisabledChain)) {
213
+ const rewards = await _getRewardsFromApi();
214
+ if (!rewards[this.gauge])
215
+ return [];
216
+ return rewards[this.gauge].map((r) => ({ gaugeAddress: r.gaugeAddress, tokenAddress: r.tokenAddress, symbol: r.symbol, apy: r.apy }));
217
+ }
218
+ const apy = [];
219
+ const rewardTokens = await this.rewardTokens(false);
220
+ for (const rewardToken of rewardTokens) {
221
+ const gaugeContract = curve.contracts[this.gauge].multicallContract;
222
+ const lpTokenContract = curve.contracts[this.lpToken].multicallContract;
223
+ const rewardContract = curve.contracts[this.sRewardContract || this.gauge].multicallContract;
224
+ const totalLiquidityUSD = await this.statsTotalLiquidity();
225
+ const rewardRate = await _getUsdRate(rewardToken.token);
226
+ const [rewardData, _stakedSupply, _totalSupply] = await curve.multicallProvider.all([
227
+ rewardContract.reward_data(rewardToken.token),
228
+ gaugeContract.totalSupply(),
229
+ lpTokenContract.totalSupply(),
230
+ ]);
231
+ const stakedSupplyBN = toBN(_stakedSupply);
232
+ const totalSupplyBN = toBN(_totalSupply);
233
+ const inflationBN = toBN(rewardData.rate, rewardToken.decimals);
234
+ const periodFinish = Number(curve.formatUnits(rewardData.period_finish, 0)) * 1000;
235
+ const baseApy = periodFinish > Date.now() ?
236
+ inflationBN.times(31536000).times(rewardRate).div(stakedSupplyBN).times(totalSupplyBN).div(Number(totalLiquidityUSD)) :
237
+ BN(0);
238
+ apy.push({
239
+ gaugeAddress: this.gauge,
240
+ tokenAddress: rewardToken.token,
241
+ symbol: rewardToken.symbol,
242
+ apy: baseApy.times(100).toNumber(),
416
243
  });
417
- });
244
+ }
245
+ return apy;
418
246
  };
419
- this._calcLpTokenAmount = (0, memoizee_1.default)(function (_amounts, isDeposit, useUnderlying) {
420
- if (isDeposit === void 0) { isDeposit = true; }
421
- if (useUnderlying === void 0) { useUnderlying = true; }
422
- return __awaiter(_this, void 0, void 0, function () {
423
- var _rates, e_2, lpContract, _lpTotalSupply, decimals_1, amounts, seedAmounts_1, N_coins, decimals_2, calcContractAddress, calcContract, poolContract, lpContract, calls, res, _c, _totalSupply, _fee, _lpTokenAmount, balances, _d, totalSupplyBN, feeBN, lpTokenAmountBN, balancesBN, amountsBN, feesBN, i, _fees, _lpTokenFee, e_3, lpContract, _lpTotalSupply, decimals_3, amounts_1, seedAmounts_2, _amounts18Decimals;
424
- return __generator(this, function (_e) {
425
- switch (_e.label) {
426
- case 0:
427
- _rates = [];
428
- if (!(!this.isMeta && useUnderlying)) return [3 /*break*/, 2];
429
- return [4 /*yield*/, this._getRates()];
430
- case 1:
431
- // For lending pools. For others rate = 1
432
- _rates = _e.sent();
433
- _amounts = _amounts.map(function (_amount, i) {
434
- return _amount.mul(ethers_1.ethers.BigNumber.from(10).pow(18)).div(_rates[i]);
435
- });
436
- _e.label = 2;
437
- case 2:
438
- if (!this.isCrypto) return [3 /*break*/, 8];
439
- _e.label = 3;
440
- case 3:
441
- _e.trys.push([3, 5, , 8]);
442
- return [4 /*yield*/, this._pureCalcLpTokenAmount(_amounts, isDeposit, useUnderlying)];
443
- case 4: return [2 /*return*/, _e.sent()];
444
- case 5:
445
- e_2 = _e.sent();
446
- lpContract = curve_1.curve.contracts[this.lpToken].contract;
447
- return [4 /*yield*/, lpContract.totalSupply(curve_1.curve.constantOptions)];
448
- case 6:
449
- _lpTotalSupply = _e.sent();
450
- if (_lpTotalSupply.gt(0))
451
- throw e_2; // Already seeded
452
- if (this.isMeta && useUnderlying)
453
- throw Error("Initial deposit for crypto meta pools must be in wrapped coins");
454
- decimals_1 = useUnderlying ? this.underlyingDecimals : this.wrappedDecimals;
455
- amounts = _amounts.map(function (_a, i) { return ethers_1.ethers.utils.formatUnits(_a, decimals_1[i]); });
456
- return [4 /*yield*/, this.cryptoSeedAmounts(amounts[0])];
457
- case 7:
458
- seedAmounts_1 = _e.sent();
459
- amounts.forEach(function (a, i) {
460
- if (!(0, utils_1.BN)(a).eq((0, utils_1.BN)(seedAmounts_1[i])))
461
- throw Error("Amounts must be = ".concat(seedAmounts_1));
462
- });
463
- return [2 /*return*/, (0, utils_1.parseUnits)(Math.sqrt(Number(amounts[0]) * Number(amounts[1])))];
464
- case 8:
465
- _e.trys.push([8, 11, , 16]);
466
- N_coins = this.isMeta && useUnderlying ? this.underlyingCoins.length : this.wrappedCoins.length;
467
- decimals_2 = this.isMeta && useUnderlying ? this.underlyingDecimals : this.wrappedDecimals;
468
- calcContractAddress = this.isMeta && useUnderlying ? this.zap : this.address;
469
- calcContract = curve_1.curve.contracts[calcContractAddress].multicallContract;
470
- poolContract = curve_1.curve.contracts[this.address].multicallContract;
471
- lpContract = curve_1.curve.contracts[this.lpToken].multicallContract;
472
- calls = [lpContract.totalSupply(), poolContract.fee()];
473
- // lpAmount before fees
474
- if (this.isMetaFactory && useUnderlying) {
475
- calls.push(calcContract.calc_token_amount(this.address, _amounts, isDeposit));
476
- }
477
- else if (calcContract["calc_token_amount(uint256[".concat(N_coins, "],bool)")]) {
478
- calls.push(calcContract.calc_token_amount(_amounts, isDeposit, curve_1.curve.constantOptions));
479
- }
480
- else {
481
- calls.push(calcContract.calc_token_amount(_amounts, curve_1.curve.constantOptions));
482
- }
483
- return [4 /*yield*/, Promise.all([
484
- curve_1.curve.multicallProvider.all(calls),
485
- this.isMeta && useUnderlying ? this.stats.underlyingBalances() : this.stats.wrappedBalances(),
486
- ])];
487
- case 9:
488
- res = _e.sent();
489
- _c = res[0], _totalSupply = _c[0], _fee = _c[1], _lpTokenAmount = _c[2];
490
- balances = res[1];
491
- _d = [(0, utils_1.toBN)(_totalSupply), (0, utils_1.toBN)(_fee, 10).times(N_coins).div(4 * (N_coins - 1)), (0, utils_1.toBN)(_lpTokenAmount)], totalSupplyBN = _d[0], feeBN = _d[1], lpTokenAmountBN = _d[2];
492
- balancesBN = balances.map(function (b) { return (0, utils_1.BN)(b); });
493
- amountsBN = _amounts.map(function (_a, i) { return (0, utils_1.toBN)(_a, decimals_2[i]); });
494
- feesBN = Array(N_coins).fill((0, utils_1.BN)(0));
495
- if (totalSupplyBN.gt(0)) {
496
- for (i = 0; i < N_coins; i++) {
497
- feesBN[i] = balancesBN[i].times(lpTokenAmountBN).div(totalSupplyBN).minus(amountsBN[i]).times(feeBN);
498
- if (feesBN[i].lt(0))
499
- feesBN[i] = feesBN[i].times(-1);
500
- }
501
- }
502
- _fees = feesBN.map(function (fBN, i) { return (0, utils_1.fromBN)(fBN, decimals_2[i]); });
503
- return [4 /*yield*/, this._pureCalcLpTokenAmount(_fees, !isDeposit, this.isMeta && useUnderlying)];
504
- case 10:
505
- _lpTokenFee = _e.sent();
506
- if (isDeposit)
507
- _lpTokenFee = _lpTokenFee.mul(-1);
508
- return [2 /*return*/, _lpTokenAmount.add(_lpTokenFee)];
509
- case 11:
510
- e_3 = _e.sent();
511
- if (!isDeposit)
512
- throw e_3; // Seeding is only for deposit
513
- lpContract = curve_1.curve.contracts[this.lpToken].contract;
514
- return [4 /*yield*/, lpContract.totalSupply(curve_1.curve.constantOptions)];
515
- case 12:
516
- _lpTotalSupply = _e.sent();
517
- if (_lpTotalSupply.gt(0))
518
- throw e_3; // Already seeded
519
- decimals_3 = useUnderlying ? this.underlyingDecimals : this.wrappedDecimals;
520
- amounts_1 = _amounts.map(function (_a, i) { return ethers_1.ethers.utils.formatUnits(_a, decimals_3[i]); });
521
- if (!(this.isMeta && useUnderlying)) return [3 /*break*/, 14];
522
- return [4 /*yield*/, this.metaUnderlyingSeedAmounts(amounts_1[0])];
523
- case 13:
524
- seedAmounts_2 = _e.sent();
525
- amounts_1.forEach(function (a, i) {
526
- if (!(0, utils_1.BN)(a).eq((0, utils_1.BN)(seedAmounts_2[i])))
527
- throw Error("Amounts must be = ".concat(seedAmounts_2));
528
- });
529
- return [3 /*break*/, 15];
530
- case 14:
531
- if (_amounts[0].lte(0))
532
- throw Error("Initial deposit amounts must be >0");
533
- amounts_1.forEach(function (a) {
534
- if (a !== amounts_1[0])
535
- throw Error("Initial deposit amounts must be equal");
536
- });
537
- _e.label = 15;
538
- case 15:
539
- _amounts18Decimals = amounts_1.map(function (a) { return (0, utils_1.parseUnits)(a); });
540
- return [2 /*return*/, _amounts18Decimals.reduce(function (_a, _b) { return _a.add(_b); })];
541
- case 16: return [2 /*return*/];
542
- }
543
- });
544
- });
247
+ this._calcLpTokenAmount = memoize(async (_amounts, isDeposit = true, useUnderlying = true) => {
248
+ if (this.isCrypto) {
249
+ try {
250
+ return await this._pureCalcLpTokenAmount(_amounts, isDeposit, useUnderlying);
251
+ }
252
+ catch (e) { // Seeding
253
+ const lpContract = curve.contracts[this.lpToken].contract;
254
+ const _lpTotalSupply = await lpContract.totalSupply(curve.constantOptions);
255
+ if (_lpTotalSupply > 0n)
256
+ throw e; // Already seeded
257
+ if (this.isMeta && useUnderlying)
258
+ throw Error("Initial deposit for crypto meta pools must be in wrapped coins");
259
+ const decimals = useUnderlying ? this.underlyingDecimals : this.wrappedDecimals;
260
+ const amounts = _amounts.map((_a, i) => curve.formatUnits(_a, decimals[i]));
261
+ const seedAmounts = await this.cryptoSeedAmounts(amounts[0]); // Checks N coins == 2 and amounts > 0
262
+ amounts.forEach((a, i) => {
263
+ if (!BN(a).eq(BN(seedAmounts[i])))
264
+ throw Error(`Amounts must be = ${seedAmounts}`);
265
+ });
266
+ return parseUnits(Math.sqrt(Number(amounts[0]) * Number(amounts[1])));
267
+ }
268
+ }
269
+ try {
270
+ const contract = curve.contracts[curve.constants.ALIASES.stable_calc].contract;
271
+ if (this.isMeta) {
272
+ const basePool = new PoolTemplate(this.basePool);
273
+ return await contract.calc_token_amount_meta(this.address, this.lpToken, _amounts.concat(Array(5 - _amounts.length).fill(0n)), _amounts.length, basePool.address, basePool.lpToken, isDeposit, useUnderlying);
274
+ }
275
+ else {
276
+ return await contract.calc_token_amount(this.address, this.lpToken, _amounts.concat(Array(5 - _amounts.length).fill(0n)), _amounts.length, isDeposit, useUnderlying && this.isLending);
277
+ }
278
+ }
279
+ catch (e) { // Seeding
280
+ if (!isDeposit)
281
+ throw e; // Seeding is only for deposit
282
+ const lpContract = curve.contracts[this.lpToken].contract;
283
+ const _lpTotalSupply = await lpContract.totalSupply(curve.constantOptions);
284
+ if (_lpTotalSupply > 0n)
285
+ throw e; // Already seeded
286
+ const decimals = useUnderlying ? this.underlyingDecimals : this.wrappedDecimals;
287
+ const amounts = _amounts.map((_a, i) => curve.formatUnits(_a, decimals[i]));
288
+ if (this.isMeta && useUnderlying) {
289
+ const seedAmounts = this.metaUnderlyingSeedAmounts(amounts[0]); // Checks N coins == 2 and amounts > 0
290
+ amounts.forEach((a, i) => {
291
+ if (!BN(a).eq(BN(seedAmounts[i])))
292
+ throw Error(`Amounts must be = ${seedAmounts}`);
293
+ });
294
+ }
295
+ else {
296
+ if (_amounts[0] <= 0n)
297
+ throw Error("Initial deposit amounts must be > 0");
298
+ amounts.forEach((a) => {
299
+ if (a !== amounts[0])
300
+ throw Error("Initial deposit amounts must be equal");
301
+ });
302
+ }
303
+ const _amounts18Decimals = amounts.map((a) => parseUnits(a));
304
+ return _amounts18Decimals.reduce((_a, _b) => _a + _b);
305
+ }
545
306
  }, {
546
307
  primitive: true,
547
308
  promise: true,
548
- maxAge: 60 * 1000, // 1m
309
+ maxAge: 30 * 1000,
310
+ length: 3,
549
311
  });
550
312
  // ---------------- CRV PROFIT, CLAIM, BOOSTING ----------------
551
- this.crvProfit = function (address) {
552
- if (address === void 0) { address = ""; }
553
- return __awaiter(_this, void 0, void 0, function () {
554
- var inflationRateBN, workingSupplyBN, workingBalanceBN, gaugeContract, crvContract, currentWeek, _c, gaugeContract, gaugeControllerContract, weightBN, crvPrice, dailyIncome, weeklyIncome, monthlyIncome, annualIncome;
555
- var _d, _e;
556
- return __generator(this, function (_f) {
557
- switch (_f.label) {
558
- case 0:
559
- if (this.rewardsOnly())
560
- throw Error("".concat(this.name, " has Rewards-Only Gauge. Use rewardsProfit instead"));
561
- address = address || curve_1.curve.signerAddress;
562
- if (!address)
563
- throw Error("Need to connect wallet or pass address into args");
564
- if (!(curve_1.curve.chainId !== 1)) return [3 /*break*/, 4];
565
- gaugeContract = curve_1.curve.contracts[this.gauge].multicallContract;
566
- crvContract = curve_1.curve.contracts[curve_1.curve.constants.ALIASES.crv].contract;
567
- currentWeek = Math.floor(Date.now() / 1000 / WEEK);
568
- return [4 /*yield*/, curve_1.curve.multicallProvider.all([
569
- gaugeContract.inflation_rate(currentWeek),
570
- gaugeContract.working_balances(address),
571
- gaugeContract.working_supply(),
572
- ])];
573
- case 1:
574
- _d = (_f.sent()).map(function (value) { return (0, utils_1.toBN)(value); }), inflationRateBN = _d[0], workingBalanceBN = _d[1], workingSupplyBN = _d[2];
575
- if (!inflationRateBN.eq(0)) return [3 /*break*/, 3];
576
- _c = utils_1.toBN;
577
- return [4 /*yield*/, crvContract.balanceOf(this.gauge, curve_1.curve.constantOptions)];
578
- case 2:
579
- inflationRateBN = _c.apply(void 0, [_f.sent()]).div(WEEK);
580
- _f.label = 3;
581
- case 3: return [3 /*break*/, 6];
582
- case 4:
583
- gaugeContract = curve_1.curve.contracts[this.gauge].multicallContract;
584
- gaugeControllerContract = curve_1.curve.contracts[curve_1.curve.constants.ALIASES.gauge_controller].multicallContract;
585
- weightBN = void 0;
586
- return [4 /*yield*/, curve_1.curve.multicallProvider.all([
587
- gaugeContract.inflation_rate(),
588
- gaugeControllerContract.gauge_relative_weight(this.gauge),
589
- gaugeContract.working_balances(address),
590
- gaugeContract.working_supply(),
591
- ])];
592
- case 5:
593
- _e = (_f.sent()).map(function (value) { return (0, utils_1.toBN)(value); }), inflationRateBN = _e[0], weightBN = _e[1], workingBalanceBN = _e[2], workingSupplyBN = _e[3];
594
- inflationRateBN = inflationRateBN.times(weightBN);
595
- _f.label = 6;
596
- case 6: return [4 /*yield*/, (0, utils_1._getUsdRate)('CRV')];
597
- case 7:
598
- crvPrice = _f.sent();
599
- if (workingSupplyBN.eq(0))
600
- return [2 /*return*/, {
601
- day: "0.0",
602
- week: "0.0",
603
- month: "0.0",
604
- year: "0.0",
605
- token: curve_1.curve.constants.ALIASES.crv,
606
- symbol: 'CRV',
607
- price: crvPrice,
608
- }];
609
- dailyIncome = inflationRateBN.times(DAY).times(workingBalanceBN).div(workingSupplyBN);
610
- weeklyIncome = inflationRateBN.times(WEEK).times(workingBalanceBN).div(workingSupplyBN);
611
- monthlyIncome = inflationRateBN.times(MONTH).times(workingBalanceBN).div(workingSupplyBN);
612
- annualIncome = inflationRateBN.times(YEAR).times(workingBalanceBN).div(workingSupplyBN);
613
- return [2 /*return*/, {
614
- day: dailyIncome.toString(),
615
- week: weeklyIncome.toString(),
616
- month: monthlyIncome.toString(),
617
- year: annualIncome.toString(),
618
- token: curve_1.curve.constants.ALIASES.crv,
619
- symbol: 'CRV',
620
- price: crvPrice,
621
- }];
622
- }
623
- });
624
- });
313
+ this.crvProfit = async (address = "") => {
314
+ if (this.rewardsOnly())
315
+ throw Error(`${this.name} has Rewards-Only Gauge. Use rewardsProfit instead`);
316
+ address = address || curve.signerAddress;
317
+ if (!address)
318
+ throw Error("Need to connect wallet or pass address into args");
319
+ let inflationRateBN, workingSupplyBN, workingBalanceBN;
320
+ if (curve.chainId !== 1) {
321
+ const gaugeContract = curve.contracts[this.gauge].multicallContract;
322
+ const crvContract = curve.contracts[curve.constants.ALIASES.crv].contract;
323
+ const currentWeek = Math.floor(Date.now() / 1000 / WEEK);
324
+ [inflationRateBN, workingBalanceBN, workingSupplyBN] = (await curve.multicallProvider.all([
325
+ gaugeContract.inflation_rate(currentWeek),
326
+ gaugeContract.working_balances(address),
327
+ gaugeContract.working_supply(),
328
+ ])).map((value) => toBN(value));
329
+ if (inflationRateBN.eq(0)) {
330
+ inflationRateBN = toBN(await crvContract.balanceOf(this.gauge, curve.constantOptions)).div(WEEK);
331
+ }
332
+ }
333
+ else {
334
+ const gaugeContract = curve.contracts[this.gauge].multicallContract;
335
+ const gaugeControllerContract = curve.contracts[curve.constants.ALIASES.gauge_controller].multicallContract;
336
+ let weightBN;
337
+ [inflationRateBN, weightBN, workingBalanceBN, workingSupplyBN] = (await curve.multicallProvider.all([
338
+ gaugeContract.inflation_rate(),
339
+ gaugeControllerContract.gauge_relative_weight(this.gauge),
340
+ gaugeContract.working_balances(address),
341
+ gaugeContract.working_supply(),
342
+ ])).map((value) => toBN(value));
343
+ inflationRateBN = inflationRateBN.times(weightBN);
344
+ }
345
+ const crvPrice = await _getUsdRate('CRV');
346
+ if (workingSupplyBN.eq(0))
347
+ return {
348
+ day: "0.0",
349
+ week: "0.0",
350
+ month: "0.0",
351
+ year: "0.0",
352
+ token: curve.constants.ALIASES.crv,
353
+ symbol: 'CRV',
354
+ price: crvPrice,
355
+ };
356
+ const dailyIncome = inflationRateBN.times(DAY).times(workingBalanceBN).div(workingSupplyBN);
357
+ const weeklyIncome = inflationRateBN.times(WEEK).times(workingBalanceBN).div(workingSupplyBN);
358
+ const monthlyIncome = inflationRateBN.times(MONTH).times(workingBalanceBN).div(workingSupplyBN);
359
+ const annualIncome = inflationRateBN.times(YEAR).times(workingBalanceBN).div(workingSupplyBN);
360
+ return {
361
+ day: dailyIncome.toString(),
362
+ week: weeklyIncome.toString(),
363
+ month: monthlyIncome.toString(),
364
+ year: annualIncome.toString(),
365
+ token: curve.constants.ALIASES.crv,
366
+ symbol: 'CRV',
367
+ price: crvPrice,
368
+ };
625
369
  };
626
- this.boost = function (address) {
627
- if (address === void 0) { address = ""; }
628
- return __awaiter(_this, void 0, void 0, function () {
629
- var gaugeContract, _c, workingBalanceBN, balanceBN, boostBN;
630
- return __generator(this, function (_d) {
631
- switch (_d.label) {
632
- case 0:
633
- if (curve_1.curve.chainId !== 1)
634
- throw Error("Boosting is available only on Ethereum network");
635
- if (this.gauge === ethers_1.ethers.constants.AddressZero)
636
- throw Error("".concat(this.name, " doesn't have gauge"));
637
- address = address || curve_1.curve.signerAddress;
638
- if (!address)
639
- throw Error("Need to connect wallet or pass address into args");
640
- gaugeContract = curve_1.curve.contracts[this.gauge].multicallContract;
641
- return [4 /*yield*/, curve_1.curve.multicallProvider.all([
642
- gaugeContract.working_balances(address),
643
- gaugeContract.balanceOf(address),
644
- ])];
645
- case 1:
646
- _c = (_d.sent()).map(function (value) { return (0, utils_1.toBN)(value); }), workingBalanceBN = _c[0], balanceBN = _c[1];
647
- boostBN = workingBalanceBN.div(0.4).div(balanceBN);
648
- return [2 /*return*/, boostBN.toFixed(4).replace(/([0-9])0+$/, '$1')];
649
- }
650
- });
651
- });
370
+ this.boost = async (address = "") => {
371
+ if (curve.chainId !== 1)
372
+ throw Error("Boosting is available only on Ethereum network");
373
+ if (this.gauge === curve.constants.ZERO_ADDRESS)
374
+ throw Error(`${this.name} doesn't have gauge`);
375
+ address = address || curve.signerAddress;
376
+ if (!address)
377
+ throw Error("Need to connect wallet or pass address into args");
378
+ const gaugeContract = curve.contracts[this.gauge].multicallContract;
379
+ const [workingBalanceBN, balanceBN] = (await curve.multicallProvider.all([
380
+ gaugeContract.working_balances(address),
381
+ gaugeContract.balanceOf(address),
382
+ ])).map((value) => toBN(value));
383
+ const boostBN = workingBalanceBN.div(0.4).div(balanceBN);
384
+ return boostBN.toFixed(4).replace(/([0-9])0+$/, '$1');
652
385
  };
653
- this.currentCrvApy = function (address) {
654
- if (address === void 0) { address = ""; }
655
- return __awaiter(_this, void 0, void 0, function () {
656
- var _c, baseApy, maxApy, boost;
657
- return __generator(this, function (_d) {
658
- switch (_d.label) {
659
- case 0:
660
- address = address || curve_1.curve.signerAddress;
661
- if (!address)
662
- throw Error("Need to connect wallet or pass address into args");
663
- return [4 /*yield*/, this.statsTokenApy()];
664
- case 1:
665
- _c = _d.sent(), baseApy = _c[0], maxApy = _c[1];
666
- if (curve_1.curve.chainId !== 1)
667
- return [2 /*return*/, baseApy];
668
- return [4 /*yield*/, this.boost(address)];
669
- case 2:
670
- boost = _d.sent();
671
- if (boost == "2.5")
672
- return [2 /*return*/, maxApy];
673
- if (boost === "NaN")
674
- return [2 /*return*/, NaN];
675
- return [2 /*return*/, (0, utils_1.BN)(baseApy).times((0, utils_1.BN)(boost)).toNumber()];
676
- }
677
- });
678
- });
386
+ this.currentCrvApy = async (address = "") => {
387
+ address = address || curve.signerAddress;
388
+ if (!address)
389
+ throw Error("Need to connect wallet or pass address into args");
390
+ const [baseApy, maxApy] = await this.statsTokenApy();
391
+ if (curve.chainId !== 1)
392
+ return baseApy;
393
+ const boost = await this.boost(address);
394
+ if (boost == "2.5")
395
+ return maxApy;
396
+ if (boost === "NaN")
397
+ return NaN;
398
+ return BN(baseApy).times(BN(boost)).toNumber();
679
399
  };
680
- this.maxBoostedStake = function () {
681
- var addresses = [];
682
- for (var _i = 0; _i < arguments.length; _i++) {
683
- addresses[_i] = arguments[_i];
400
+ this.maxBoostedStake = async (...addresses) => {
401
+ if (curve.chainId !== 1)
402
+ throw Error("Boosting is available only on Ethereum network");
403
+ if (this.gauge === curve.constants.ZERO_ADDRESS)
404
+ throw Error(`${this.name} doesn't have gauge`);
405
+ if (addresses.length == 1 && Array.isArray(addresses[0]))
406
+ addresses = addresses[0];
407
+ if (addresses.length === 0 && curve.signerAddress !== '')
408
+ addresses = [curve.signerAddress];
409
+ if (addresses.length === 0)
410
+ throw Error("Need to connect wallet or pass addresses into args");
411
+ const votingEscrowContract = curve.contracts[curve.constants.ALIASES.voting_escrow].multicallContract;
412
+ const gaugeContract = curve.contracts[this.gauge].multicallContract;
413
+ const contractCalls = [votingEscrowContract.totalSupply(), gaugeContract.totalSupply()];
414
+ addresses.forEach((account) => {
415
+ contractCalls.push(votingEscrowContract.balanceOf(account));
416
+ });
417
+ const _response = await curve.multicallProvider.all(contractCalls);
418
+ const responseBN = _response.map((value) => toBN(value));
419
+ const [veTotalSupplyBN, gaugeTotalSupplyBN] = responseBN.splice(0, 2);
420
+ const resultBN = {};
421
+ addresses.forEach((acct, i) => {
422
+ resultBN[acct] = responseBN[i].div(veTotalSupplyBN).times(gaugeTotalSupplyBN);
423
+ });
424
+ const result = {};
425
+ for (const entry of Object.entries(resultBN)) {
426
+ result[entry[0]] = toStringFromBN(entry[1]);
684
427
  }
685
- return __awaiter(_this, void 0, void 0, function () {
686
- var votingEscrowContract, gaugeContract, contractCalls, _response, responseBN, _c, veTotalSupplyBN, gaugeTotalSupplyBN, resultBN, result, _d, _e, entry;
687
- return __generator(this, function (_f) {
688
- switch (_f.label) {
689
- case 0:
690
- if (curve_1.curve.chainId !== 1)
691
- throw Error("Boosting is available only on Ethereum network");
692
- if (this.gauge === ethers_1.ethers.constants.AddressZero)
693
- throw Error("".concat(this.name, " doesn't have gauge"));
694
- if (addresses.length == 1 && Array.isArray(addresses[0]))
695
- addresses = addresses[0];
696
- if (addresses.length === 0 && curve_1.curve.signerAddress !== '')
697
- addresses = [curve_1.curve.signerAddress];
698
- if (addresses.length === 0)
699
- throw Error("Need to connect wallet or pass addresses into args");
700
- votingEscrowContract = curve_1.curve.contracts[curve_1.curve.constants.ALIASES.voting_escrow].multicallContract;
701
- gaugeContract = curve_1.curve.contracts[this.gauge].multicallContract;
702
- contractCalls = [votingEscrowContract.totalSupply(), gaugeContract.totalSupply()];
703
- addresses.forEach(function (account) {
704
- contractCalls.push(votingEscrowContract.balanceOf(account));
705
- });
706
- return [4 /*yield*/, curve_1.curve.multicallProvider.all(contractCalls)];
707
- case 1:
708
- _response = _f.sent();
709
- responseBN = _response.map(function (value) { return (0, utils_1.toBN)(value); });
710
- _c = responseBN.splice(0, 2), veTotalSupplyBN = _c[0], gaugeTotalSupplyBN = _c[1];
711
- resultBN = {};
712
- addresses.forEach(function (acct, i) {
713
- resultBN[acct] = responseBN[i].div(veTotalSupplyBN).times(gaugeTotalSupplyBN);
714
- });
715
- result = {};
716
- for (_d = 0, _e = Object.entries(resultBN); _d < _e.length; _d++) {
717
- entry = _e[_d];
718
- result[entry[0]] = (0, utils_1.toStringFromBN)(entry[1]);
719
- }
720
- return [2 /*return*/, addresses.length === 1 ? result[addresses[0]] : result];
721
- }
722
- });
723
- });
428
+ return addresses.length === 1 ? result[addresses[0]] : result;
724
429
  };
725
430
  // ---------------- REWARDS PROFIT, CLAIM ----------------
726
- this.rewardTokens = (0, memoizee_1.default)(function (useApi) {
727
- if (useApi === void 0) { useApi = true; }
728
- return __awaiter(_this, void 0, void 0, function () {
729
- var rewards, gaugeContract, gaugeMulticallContract, rewardCount, _c, _d, _e, tokenCalls, i, tokens, tokenInfoCalls, _i, tokens_1, token, tokenMulticallContract, tokenInfo_1, i, rewardContract, method, token, tokenMulticallContract, res, symbol, decimals;
730
- return __generator(this, function (_f) {
731
- switch (_f.label) {
732
- case 0:
733
- if (this.gauge === ethers_1.ethers.constants.AddressZero)
734
- return [2 /*return*/, []];
735
- if (!useApi) return [3 /*break*/, 2];
736
- return [4 /*yield*/, (0, utils_1._getRewardsFromApi)()];
737
- case 1:
738
- rewards = _f.sent();
739
- if (!rewards[this.gauge])
740
- return [2 /*return*/, []];
741
- rewards[this.gauge].forEach(function (r) { return (0, utils_1._setContracts)(r.tokenAddress, ERC20_json_1.default); });
742
- return [2 /*return*/, rewards[this.gauge].map(function (r) { return ({ token: r.tokenAddress, symbol: r.symbol, decimals: r.decimals }); })];
743
- case 2:
744
- gaugeContract = curve_1.curve.contracts[this.gauge].contract;
745
- gaugeMulticallContract = curve_1.curve.contracts[this.gauge].multicallContract;
746
- if (!("reward_tokens(uint256)" in gaugeContract)) return [3 /*break*/, 7];
747
- rewardCount = 8;
748
- if (!("reward_count()" in gaugeContract)) return [3 /*break*/, 4];
749
- _c = Number;
750
- _e = (_d = ethers_1.ethers.utils).formatUnits;
751
- return [4 /*yield*/, gaugeContract.reward_count(curve_1.curve.constantOptions)];
752
- case 3:
753
- rewardCount = _c.apply(void 0, [_e.apply(_d, [_f.sent(), 0])]);
754
- _f.label = 4;
755
- case 4:
756
- tokenCalls = [];
757
- for (i = 0; i < rewardCount; i++) {
758
- tokenCalls.push(gaugeMulticallContract.reward_tokens(i));
759
- }
760
- return [4 /*yield*/, curve_1.curve.multicallProvider.all(tokenCalls)];
761
- case 5:
762
- tokens = (_f.sent())
763
- .filter(function (addr) { return addr !== ethers_1.ethers.constants.AddressZero; })
764
- .map(function (addr) { return addr.toLowerCase(); });
765
- tokenInfoCalls = [];
766
- for (_i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {
767
- token = tokens_1[_i];
768
- (0, utils_1._setContracts)(token, ERC20_json_1.default);
769
- tokenMulticallContract = curve_1.curve.contracts[token].multicallContract;
770
- tokenInfoCalls.push(tokenMulticallContract.symbol(), tokenMulticallContract.decimals());
771
- }
772
- return [4 /*yield*/, curve_1.curve.multicallProvider.all(tokenInfoCalls)];
773
- case 6:
774
- tokenInfo_1 = _f.sent();
775
- for (i = 0; i < tokens.length; i++) {
776
- curve_1.curve.constants.DECIMALS[tokens[i]] = tokenInfo_1[(i * 2) + 1];
777
- }
778
- return [2 /*return*/, tokens.map(function (token, i) { return ({ token: token, symbol: tokenInfo_1[i * 2], decimals: tokenInfo_1[(i * 2) + 1] }); })];
779
- case 7:
780
- if (!('claimable_reward(address)' in gaugeContract)) return [3 /*break*/, 10];
781
- rewardContract = curve_1.curve.contracts[this.sRewardContract].contract;
782
- method = "snx()" in rewardContract ? "snx" : "rewardsToken" // susd, tbtc : dusd, musd, rsv, sbtc
783
- ;
784
- return [4 /*yield*/, rewardContract[method](curve_1.curve.constantOptions)];
785
- case 8:
786
- token = (_f.sent()).toLowerCase();
787
- (0, utils_1._setContracts)(token, ERC20_json_1.default);
788
- tokenMulticallContract = curve_1.curve.contracts[token].multicallContract;
789
- return [4 /*yield*/, curve_1.curve.multicallProvider.all([
790
- tokenMulticallContract.symbol(),
791
- tokenMulticallContract.decimals(),
792
- ])];
793
- case 9:
794
- res = _f.sent();
795
- symbol = res[0];
796
- decimals = res[1];
797
- return [2 /*return*/, [{ token: token, symbol: symbol, decimals: decimals }]];
798
- case 10: return [2 /*return*/, []]; // gauge
799
- }
800
- });
801
- });
431
+ this.rewardTokens = memoize(async (useApi = true) => {
432
+ if (this.gauge === curve.constants.ZERO_ADDRESS)
433
+ return [];
434
+ if (useApi) {
435
+ const rewards = await _getRewardsFromApi();
436
+ if (!rewards[this.gauge])
437
+ return [];
438
+ rewards[this.gauge].forEach((r) => _setContracts(r.tokenAddress, ERC20Abi));
439
+ return rewards[this.gauge].map((r) => ({ token: r.tokenAddress, symbol: r.symbol, decimals: Number(r.decimals) }));
440
+ }
441
+ const gaugeContract = curve.contracts[this.gauge].contract;
442
+ const gaugeMulticallContract = curve.contracts[this.gauge].multicallContract;
443
+ if ("reward_tokens(uint256)" in gaugeContract) {
444
+ let rewardCount = 8; // gauge_v2, gauge_v3, gauge_rewards_only, gauge_child
445
+ if ("reward_count()" in gaugeContract) { // gauge_v4, gauge_v5, gauge_factory
446
+ rewardCount = Number(curve.formatUnits(await gaugeContract.reward_count(curve.constantOptions), 0));
447
+ }
448
+ const tokenCalls = [];
449
+ for (let i = 0; i < rewardCount; i++) {
450
+ tokenCalls.push(gaugeMulticallContract.reward_tokens(i));
451
+ }
452
+ const tokens = (await curve.multicallProvider.all(tokenCalls))
453
+ .filter((addr) => addr !== curve.constants.ZERO_ADDRESS)
454
+ .map((addr) => addr.toLowerCase());
455
+ const tokenInfoCalls = [];
456
+ for (const token of tokens) {
457
+ _setContracts(token, ERC20Abi);
458
+ const tokenMulticallContract = curve.contracts[token].multicallContract;
459
+ tokenInfoCalls.push(tokenMulticallContract.symbol(), tokenMulticallContract.decimals());
460
+ }
461
+ const tokenInfo = await curve.multicallProvider.all(tokenInfoCalls);
462
+ for (let i = 0; i < tokens.length; i++) {
463
+ curve.constants.DECIMALS[tokens[i]] = tokenInfo[(i * 2) + 1];
464
+ }
465
+ return tokens.map((token, i) => ({ token, symbol: tokenInfo[i * 2], decimals: tokenInfo[(i * 2) + 1] }));
466
+ }
467
+ else if ('claimable_reward(address)' in gaugeContract) { // gauge_synthetix
468
+ const rewardContract = curve.contracts[this.sRewardContract].contract;
469
+ const method = "snx()" in rewardContract ? "snx" : "rewardsToken"; // susd, tbtc : dusd, musd, rsv, sbtc
470
+ const token = (await rewardContract[method](curve.constantOptions)).toLowerCase();
471
+ _setContracts(token, ERC20Abi);
472
+ const tokenMulticallContract = curve.contracts[token].multicallContract;
473
+ const res = await curve.multicallProvider.all([
474
+ tokenMulticallContract.symbol(),
475
+ tokenMulticallContract.decimals(),
476
+ ]);
477
+ const symbol = res[0];
478
+ const decimals = res[1];
479
+ return [{ token, symbol, decimals }];
480
+ }
481
+ return []; // gauge
802
482
  }, {
803
483
  promise: true,
804
484
  maxAge: 30 * 60 * 1000, // 30m
805
485
  });
806
- this.rewardsProfit = function (address) {
807
- if (address === void 0) { address = ""; }
808
- return __awaiter(_this, void 0, void 0, function () {
809
- var rewardTokens, gaugeContract, result, calls, _i, rewardTokens_2, rewardToken, res, balanceBN, totalSupplyBN, _c, rewardTokens_3, rewardToken, _rewardData, periodFinish, inflationRateBN, tokenPrice, rewardToken, sRewardContract, _d, _inflationRate, _periodFinish, _balance, _totalSupply, periodFinish, inflationRateBN, balanceBN, totalSupplyBN, tokenPrice, _e, rewardTokens_4, rewardToken, tokenPrice;
810
- return __generator(this, function (_f) {
811
- switch (_f.label) {
812
- case 0:
813
- if (this.gauge === ethers_1.ethers.constants.AddressZero)
814
- throw Error("".concat(this.name, " doesn't have gauge"));
815
- address = address || curve_1.curve.signerAddress;
816
- if (!address)
817
- throw Error("Need to connect wallet or pass address into args");
818
- return [4 /*yield*/, this.rewardTokens()];
819
- case 1:
820
- rewardTokens = _f.sent();
821
- gaugeContract = curve_1.curve.contracts[this.gauge].multicallContract;
822
- result = [];
823
- if (!('reward_data(address)' in curve_1.curve.contracts[this.gauge].contract)) return [3 /*break*/, 7];
824
- calls = [gaugeContract.balanceOf(address), gaugeContract.totalSupply()];
825
- for (_i = 0, rewardTokens_2 = rewardTokens; _i < rewardTokens_2.length; _i++) {
826
- rewardToken = rewardTokens_2[_i];
827
- calls.push(gaugeContract.reward_data(rewardToken.token));
828
- }
829
- return [4 /*yield*/, curve_1.curve.multicallProvider.all(calls)];
830
- case 2:
831
- res = _f.sent();
832
- balanceBN = (0, utils_1.toBN)(res.shift());
833
- totalSupplyBN = (0, utils_1.toBN)(res.shift());
834
- _c = 0, rewardTokens_3 = rewardTokens;
835
- _f.label = 3;
836
- case 3:
837
- if (!(_c < rewardTokens_3.length)) return [3 /*break*/, 6];
838
- rewardToken = rewardTokens_3[_c];
839
- _rewardData = res.shift();
840
- periodFinish = Number(ethers_1.ethers.utils.formatUnits(_rewardData.period_finish, 0)) * 1000;
841
- inflationRateBN = periodFinish > Date.now() ? (0, utils_1.toBN)(_rewardData.rate, rewardToken.decimals) : (0, utils_1.BN)(0);
842
- return [4 /*yield*/, (0, utils_1._getUsdRate)(rewardToken.token)];
843
- case 4:
844
- tokenPrice = _f.sent();
845
- result.push({
846
- day: inflationRateBN.times(DAY).times(balanceBN).div(totalSupplyBN).toString(),
847
- week: inflationRateBN.times(WEEK).times(balanceBN).div(totalSupplyBN).toString(),
848
- month: inflationRateBN.times(MONTH).times(balanceBN).div(totalSupplyBN).toString(),
849
- year: inflationRateBN.times(YEAR).times(balanceBN).div(totalSupplyBN).toString(),
850
- token: rewardToken.token,
851
- symbol: rewardToken.symbol,
852
- price: tokenPrice,
853
- });
854
- _f.label = 5;
855
- case 5:
856
- _c++;
857
- return [3 /*break*/, 3];
858
- case 6: return [3 /*break*/, 14];
859
- case 7:
860
- if (!(this.sRewardContract && "rewardRate()" in curve_1.curve.contracts[this.sRewardContract].contract && "periodFinish()" && rewardTokens.length === 1)) return [3 /*break*/, 10];
861
- rewardToken = rewardTokens[0];
862
- sRewardContract = curve_1.curve.contracts[this.sRewardContract].multicallContract;
863
- return [4 /*yield*/, curve_1.curve.multicallProvider.all([
864
- sRewardContract.rewardRate(),
865
- sRewardContract.periodFinish(),
866
- gaugeContract.balanceOf(address),
867
- gaugeContract.totalSupply(),
868
- ])];
869
- case 8:
870
- _d = _f.sent(), _inflationRate = _d[0], _periodFinish = _d[1], _balance = _d[2], _totalSupply = _d[3];
871
- periodFinish = _periodFinish.toNumber() * 1000;
872
- inflationRateBN = periodFinish > Date.now() ? (0, utils_1.toBN)(_inflationRate, rewardToken.decimals) : (0, utils_1.BN)(0);
873
- balanceBN = (0, utils_1.toBN)(_balance);
874
- totalSupplyBN = (0, utils_1.toBN)(_totalSupply);
875
- return [4 /*yield*/, (0, utils_1._getUsdRate)(rewardToken.token)];
876
- case 9:
877
- tokenPrice = _f.sent();
878
- result.push({
879
- day: inflationRateBN.times(DAY).times(balanceBN).div(totalSupplyBN).toString(),
880
- week: inflationRateBN.times(WEEK).times(balanceBN).div(totalSupplyBN).toString(),
881
- month: inflationRateBN.times(MONTH).times(balanceBN).div(totalSupplyBN).toString(),
882
- year: inflationRateBN.times(YEAR).times(balanceBN).div(totalSupplyBN).toString(),
883
- token: rewardToken.token,
884
- symbol: rewardToken.symbol,
885
- price: tokenPrice,
886
- });
887
- return [3 /*break*/, 14];
888
- case 10:
889
- if (!['aave', 'saave', 'ankreth'].includes(this.id)) return [3 /*break*/, 14];
890
- _e = 0, rewardTokens_4 = rewardTokens;
891
- _f.label = 11;
892
- case 11:
893
- if (!(_e < rewardTokens_4.length)) return [3 /*break*/, 14];
894
- rewardToken = rewardTokens_4[_e];
895
- return [4 /*yield*/, (0, utils_1._getUsdRate)(rewardToken.token)];
896
- case 12:
897
- tokenPrice = _f.sent();
898
- result.push({
899
- day: "0",
900
- week: "0",
901
- month: "0",
902
- year: "0",
903
- token: rewardToken.token,
904
- symbol: rewardToken.symbol,
905
- price: tokenPrice,
906
- });
907
- _f.label = 13;
908
- case 13:
909
- _e++;
910
- return [3 /*break*/, 11];
911
- case 14: return [2 /*return*/, result];
912
- }
486
+ this.rewardsProfit = async (address = "") => {
487
+ if (this.gauge === curve.constants.ZERO_ADDRESS)
488
+ throw Error(`${this.name} doesn't have gauge`);
489
+ address = address || curve.signerAddress;
490
+ if (!address)
491
+ throw Error("Need to connect wallet or pass address into args");
492
+ const rewardTokens = await this.rewardTokens();
493
+ const gaugeContract = curve.contracts[this.gauge].multicallContract;
494
+ const result = [];
495
+ if ('reward_data(address)' in curve.contracts[this.gauge].contract) {
496
+ const calls = [gaugeContract.balanceOf(address), gaugeContract.totalSupply()];
497
+ for (const rewardToken of rewardTokens) {
498
+ calls.push(gaugeContract.reward_data(rewardToken.token));
499
+ }
500
+ const res = await curve.multicallProvider.all(calls);
501
+ const balanceBN = toBN(res.shift());
502
+ const totalSupplyBN = toBN(res.shift());
503
+ for (const rewardToken of rewardTokens) {
504
+ const _rewardData = res.shift();
505
+ const periodFinish = Number(curve.formatUnits(_rewardData.period_finish, 0)) * 1000;
506
+ const inflationRateBN = periodFinish > Date.now() ? toBN(_rewardData.rate, rewardToken.decimals) : BN(0);
507
+ const tokenPrice = await _getUsdRate(rewardToken.token);
508
+ result.push({
509
+ day: inflationRateBN.times(DAY).times(balanceBN).div(totalSupplyBN).toString(),
510
+ week: inflationRateBN.times(WEEK).times(balanceBN).div(totalSupplyBN).toString(),
511
+ month: inflationRateBN.times(MONTH).times(balanceBN).div(totalSupplyBN).toString(),
512
+ year: inflationRateBN.times(YEAR).times(balanceBN).div(totalSupplyBN).toString(),
513
+ token: rewardToken.token,
514
+ symbol: rewardToken.symbol,
515
+ price: tokenPrice,
516
+ });
517
+ }
518
+ }
519
+ else if (this.sRewardContract && "rewardRate()" in _curve.contracts[this.sRewardContract].contract && "periodFinish()" && rewardTokens.length === 1) {
520
+ const rewardToken = rewardTokens[0];
521
+ const sRewardContract = curve.contracts[this.sRewardContract].multicallContract;
522
+ const [_inflationRate, _periodFinish, _balance, _totalSupply] = await curve.multicallProvider.all([
523
+ sRewardContract.rewardRate(),
524
+ sRewardContract.periodFinish(),
525
+ gaugeContract.balanceOf(address),
526
+ gaugeContract.totalSupply(),
527
+ ]);
528
+ const periodFinish = Number(_periodFinish) * 1000;
529
+ const inflationRateBN = periodFinish > Date.now() ? toBN(_inflationRate, rewardToken.decimals) : BN(0);
530
+ const balanceBN = toBN(_balance);
531
+ const totalSupplyBN = toBN(_totalSupply);
532
+ const tokenPrice = await _getUsdRate(rewardToken.token);
533
+ result.push({
534
+ day: inflationRateBN.times(DAY).times(balanceBN).div(totalSupplyBN).toString(),
535
+ week: inflationRateBN.times(WEEK).times(balanceBN).div(totalSupplyBN).toString(),
536
+ month: inflationRateBN.times(MONTH).times(balanceBN).div(totalSupplyBN).toString(),
537
+ year: inflationRateBN.times(YEAR).times(balanceBN).div(totalSupplyBN).toString(),
538
+ token: rewardToken.token,
539
+ symbol: rewardToken.symbol,
540
+ price: tokenPrice,
913
541
  });
914
- });
542
+ }
543
+ else if (['aave', 'saave', 'ankreth'].includes(this.id)) {
544
+ for (const rewardToken of rewardTokens) {
545
+ const tokenPrice = await _getUsdRate(rewardToken.token);
546
+ result.push({
547
+ day: "0",
548
+ week: "0",
549
+ month: "0",
550
+ year: "0",
551
+ token: rewardToken.token,
552
+ symbol: rewardToken.symbol,
553
+ price: tokenPrice,
554
+ });
555
+ }
556
+ }
557
+ return result;
915
558
  };
916
559
  // ---------------- ... ----------------
917
- this.gaugeOptimalDeposits = function () {
918
- var accounts = [];
919
- for (var _i = 0; _i < arguments.length; _i++) {
920
- accounts[_i] = arguments[_i];
560
+ this.gaugeOptimalDeposits = async (...accounts) => {
561
+ if (this.gauge === curve.constants.ZERO_ADDRESS)
562
+ throw Error(`${this.name} doesn't have gauge`);
563
+ if (accounts.length == 1 && Array.isArray(accounts[0]))
564
+ accounts = accounts[0];
565
+ const votingEscrowContract = curve.contracts[curve.constants.ALIASES.voting_escrow].multicallContract;
566
+ const lpTokenContract = curve.contracts[this.lpToken].multicallContract;
567
+ const gaugeContract = curve.contracts[this.gauge].multicallContract;
568
+ const contractCalls = [votingEscrowContract.totalSupply(), gaugeContract.totalSupply()];
569
+ accounts.forEach((account) => {
570
+ contractCalls.push(votingEscrowContract.balanceOf(account), lpTokenContract.balanceOf(account), gaugeContract.balanceOf(account));
571
+ });
572
+ const _response = await curve.multicallProvider.all(contractCalls);
573
+ const response = _response.map((value) => toBN(value));
574
+ const [veTotalSupply, gaugeTotalSupply] = response.splice(0, 2);
575
+ const votingPower = {};
576
+ let totalBalance = BN(0);
577
+ for (const acct of accounts) {
578
+ votingPower[acct] = response[0];
579
+ totalBalance = totalBalance.plus(response[1]).plus(response[2]);
580
+ response.splice(0, 3);
921
581
  }
922
- return __awaiter(_this, void 0, void 0, function () {
923
- var votingEscrowContract, lpTokenContract, gaugeContract, contractCalls, _response, response, _c, veTotalSupply, gaugeTotalSupply, votingPower, totalBalance, _d, accounts_1, acct, totalPower, optimalBN, _e, accounts_2, acct, amount, _f, accounts_3, acct, optimal, _g, _h, entry;
924
- return __generator(this, function (_j) {
925
- switch (_j.label) {
926
- case 0:
927
- if (this.gauge === ethers_1.ethers.constants.AddressZero)
928
- throw Error("".concat(this.name, " doesn't have gauge"));
929
- if (accounts.length == 1 && Array.isArray(accounts[0]))
930
- accounts = accounts[0];
931
- votingEscrowContract = curve_1.curve.contracts[curve_1.curve.constants.ALIASES.voting_escrow].multicallContract;
932
- lpTokenContract = curve_1.curve.contracts[this.lpToken].multicallContract;
933
- gaugeContract = curve_1.curve.contracts[this.gauge].multicallContract;
934
- contractCalls = [votingEscrowContract.totalSupply(), gaugeContract.totalSupply()];
935
- accounts.forEach(function (account) {
936
- contractCalls.push(votingEscrowContract.balanceOf(account), lpTokenContract.balanceOf(account), gaugeContract.balanceOf(account));
937
- });
938
- return [4 /*yield*/, curve_1.curve.multicallProvider.all(contractCalls)];
939
- case 1:
940
- _response = _j.sent();
941
- response = _response.map(function (value) { return (0, utils_1.toBN)(value); });
942
- _c = response.splice(0, 2), veTotalSupply = _c[0], gaugeTotalSupply = _c[1];
943
- votingPower = {};
944
- totalBalance = (0, utils_1.BN)(0);
945
- for (_d = 0, accounts_1 = accounts; _d < accounts_1.length; _d++) {
946
- acct = accounts_1[_d];
947
- votingPower[acct] = response[0];
948
- totalBalance = totalBalance.plus(response[1]).plus(response[2]);
949
- response.splice(0, 3);
950
- }
951
- totalPower = Object.values(votingPower).reduce(function (sum, item) { return sum.plus(item); });
952
- optimalBN = Object.fromEntries(accounts.map(function (acc) { return [acc, (0, utils_1.BN)(0)]; }));
953
- if (totalBalance.lt(gaugeTotalSupply.times(totalPower).div(veTotalSupply))) {
954
- for (_e = 0, accounts_2 = accounts; _e < accounts_2.length; _e++) {
955
- acct = accounts_2[_e];
956
- amount = gaugeTotalSupply.times(votingPower[acct]).div(veTotalSupply).lt(totalBalance) ?
957
- gaugeTotalSupply.times(votingPower[acct]).div(veTotalSupply) : totalBalance;
958
- optimalBN[acct] = amount;
959
- totalBalance = totalBalance.minus(amount);
960
- if (totalBalance.lte(0)) {
961
- break;
962
- }
963
- }
964
- }
965
- else {
966
- if (totalPower.lt(0)) {
967
- for (_f = 0, accounts_3 = accounts; _f < accounts_3.length; _f++) {
968
- acct = accounts_3[_f];
969
- optimalBN[acct] = totalBalance.times(votingPower[acct]).div(totalPower);
970
- }
971
- }
972
- optimalBN[accounts[0]] = optimalBN[accounts[0]].plus(totalBalance.minus(Object.values(optimalBN).reduce(function (sum, item) { return sum.plus(item); })));
973
- }
974
- optimal = {};
975
- for (_g = 0, _h = Object.entries(optimalBN); _g < _h.length; _g++) {
976
- entry = _h[_g];
977
- optimal[entry[0]] = (0, utils_1.toStringFromBN)(entry[1]);
978
- }
979
- return [2 /*return*/, optimal];
582
+ const totalPower = Object.values(votingPower).reduce((sum, item) => sum.plus(item));
583
+ // @ts-ignore
584
+ const optimalBN = Object.fromEntries(accounts.map((acc) => [acc, BN(0)]));
585
+ if (totalBalance.lt(gaugeTotalSupply.times(totalPower).div(veTotalSupply))) {
586
+ for (const acct of accounts) {
587
+ // min(voting, lp)
588
+ const amount = gaugeTotalSupply.times(votingPower[acct]).div(veTotalSupply).lt(totalBalance) ?
589
+ gaugeTotalSupply.times(votingPower[acct]).div(veTotalSupply) : totalBalance;
590
+ optimalBN[acct] = amount;
591
+ totalBalance = totalBalance.minus(amount);
592
+ if (totalBalance.lte(0)) {
593
+ break;
980
594
  }
981
- });
982
- });
595
+ }
596
+ }
597
+ else {
598
+ if (totalPower.lt(0)) {
599
+ for (const acct of accounts) {
600
+ optimalBN[acct] = totalBalance.times(votingPower[acct]).div(totalPower);
601
+ }
602
+ }
603
+ optimalBN[accounts[0]] = optimalBN[accounts[0]].plus(totalBalance.minus(Object.values(optimalBN).reduce((sum, item) => sum.plus(item))));
604
+ }
605
+ const optimal = {};
606
+ for (const entry of Object.entries(optimalBN)) {
607
+ optimal[entry[0]] = toStringFromBN(entry[1]);
608
+ }
609
+ return optimal;
983
610
  };
984
- this._getCoinIdx = function (coin, useUnderlying) {
985
- if (useUnderlying === void 0) { useUnderlying = true; }
611
+ this._getCoinIdx = (coin, useUnderlying = true) => {
986
612
  if (typeof coin === 'number') {
987
- var coins_N = useUnderlying ? _this.underlyingCoins.length : _this.wrappedCoins.length;
988
- var idx_1 = coin;
989
- if (!Number.isInteger(idx_1)) {
613
+ const coins_N = useUnderlying ? this.underlyingCoins.length : this.wrappedCoins.length;
614
+ const idx = coin;
615
+ if (!Number.isInteger(idx)) {
990
616
  throw Error('Index must be integer');
991
617
  }
992
- if (idx_1 < 0) {
618
+ if (idx < 0) {
993
619
  throw Error('Index must be >= 0');
994
620
  }
995
- if (idx_1 > coins_N - 1) {
996
- throw Error("Index must be < ".concat(coins_N));
621
+ if (idx > coins_N - 1) {
622
+ throw Error(`Index must be < ${coins_N}`);
997
623
  }
998
- return idx_1;
624
+ return idx;
999
625
  }
1000
- var coinAddress = (0, utils_1._getCoinAddresses)(coin)[0];
1001
- var lowerCaseCoinAddresses = useUnderlying ?
1002
- _this.underlyingCoinAddresses.map(function (c) { return c.toLowerCase(); }) :
1003
- _this.wrappedCoinAddresses.map(function (c) { return c.toLowerCase(); });
1004
- var idx = lowerCaseCoinAddresses.indexOf(coinAddress.toLowerCase());
626
+ const [coinAddress] = _getCoinAddresses(coin);
627
+ const lowerCaseCoinAddresses = useUnderlying ?
628
+ this.underlyingCoinAddresses.map((c) => c.toLowerCase()) :
629
+ this.wrappedCoinAddresses.map((c) => c.toLowerCase());
630
+ const idx = lowerCaseCoinAddresses.indexOf(coinAddress.toLowerCase());
1005
631
  if (idx === -1) {
1006
- throw Error("There is no ".concat(coin, " among ").concat(_this.name, " pool ").concat(useUnderlying ? 'underlying' : 'wrapped', " coins"));
632
+ throw Error(`There is no ${coin} among ${this.name} pool ${useUnderlying ? 'underlying' : 'wrapped'} coins`);
1007
633
  }
1008
634
  return idx;
1009
635
  };
1010
- this._getRates = function () { return __awaiter(_this, void 0, void 0, function () {
1011
- var _rates, i, addr, _c, _d, _e, _f;
1012
- return __generator(this, function (_g) {
1013
- switch (_g.label) {
1014
- case 0:
1015
- _rates = [];
1016
- i = 0;
1017
- _g.label = 1;
1018
- case 1:
1019
- if (!(i < this.wrappedCoinAddresses.length)) return [3 /*break*/, 9];
1020
- addr = this.wrappedCoinAddresses[i];
1021
- if (!this.useLending[i]) return [3 /*break*/, 7];
1022
- if (!['compound', 'usdt', 'ib'].includes(this.id)) return [3 /*break*/, 3];
1023
- _d = (_c = _rates).push;
1024
- return [4 /*yield*/, curve_1.curve.contracts[addr].contract.exchangeRateStored()];
1025
- case 2:
1026
- _d.apply(_c, [_g.sent()]);
1027
- return [3 /*break*/, 6];
1028
- case 3:
1029
- if (!['y', 'busd', 'pax'].includes(this.id)) return [3 /*break*/, 5];
1030
- _f = (_e = _rates).push;
1031
- return [4 /*yield*/, curve_1.curve.contracts[addr].contract.getPricePerFullShare()];
1032
- case 4:
1033
- _f.apply(_e, [_g.sent()]);
1034
- return [3 /*break*/, 6];
1035
- case 5:
1036
- _rates.push(ethers_1.ethers.BigNumber.from(10).pow(18)); // Aave ratio 1:1
1037
- _g.label = 6;
1038
- case 6: return [3 /*break*/, 8];
1039
- case 7:
1040
- _rates.push(ethers_1.ethers.BigNumber.from(10).pow(18));
1041
- _g.label = 8;
1042
- case 8:
1043
- i++;
1044
- return [3 /*break*/, 1];
1045
- case 9: return [2 /*return*/, _rates];
636
+ // Used by mixins
637
+ this._getRates = async () => {
638
+ const _rates = [];
639
+ for (let i = 0; i < this.wrappedCoinAddresses.length; i++) {
640
+ const addr = this.wrappedCoinAddresses[i];
641
+ if (this.useLending[i]) {
642
+ if (['compound', 'usdt', 'ib'].includes(this.id)) {
643
+ _rates.push(await curve.contracts[addr].contract.exchangeRateStored());
644
+ }
645
+ else if (['y', 'busd', 'pax'].includes(this.id)) {
646
+ _rates.push(await curve.contracts[addr].contract.getPricePerFullShare());
647
+ }
648
+ else {
649
+ _rates.push(10n ** 18n); // Aave ratio 1:1
650
+ }
651
+ }
652
+ else {
653
+ _rates.push(10n ** 18n);
1046
654
  }
1047
- });
1048
- }); };
1049
- this._balances = function (rawCoinNames, rawCoinAddresses) {
1050
- var addresses = [];
1051
- for (var _i = 2; _i < arguments.length; _i++) {
1052
- addresses[_i - 2] = arguments[_i];
1053
655
  }
1054
- return __awaiter(_this, void 0, void 0, function () {
1055
- var coinNames, coinAddresses, i, rawBalances, balances, _c, addresses_1, address, _d, coinNames_1, coinName;
1056
- return __generator(this, function (_e) {
1057
- switch (_e.label) {
1058
- case 0:
1059
- coinNames = [];
1060
- coinAddresses = [];
1061
- // removing duplicates
1062
- for (i = 0; i < rawCoinAddresses.length; i++) {
1063
- if (!coinAddresses.includes(rawCoinAddresses[i])) {
1064
- coinNames.push(rawCoinNames[i]);
1065
- coinAddresses.push(rawCoinAddresses[i]);
1066
- }
1067
- }
1068
- addresses = (0, utils_1._prepareAddresses)(addresses);
1069
- return [4 /*yield*/, (0, utils_1._getBalances)(coinAddresses, addresses)];
1070
- case 1:
1071
- rawBalances = _e.sent();
1072
- balances = {};
1073
- for (_c = 0, addresses_1 = addresses; _c < addresses_1.length; _c++) {
1074
- address = addresses_1[_c];
1075
- balances[address] = {};
1076
- for (_d = 0, coinNames_1 = coinNames; _d < coinNames_1.length; _d++) {
1077
- coinName = coinNames_1[_d];
1078
- balances[address][coinName] = rawBalances[address].shift();
1079
- }
1080
- }
1081
- return [2 /*return*/, addresses.length === 1 ? balances[addresses[0]] : balances];
1082
- }
1083
- });
1084
- });
656
+ return _rates;
1085
657
  };
1086
- this._underlyingPrices = function () { return __awaiter(_this, void 0, void 0, function () {
1087
- var promises, _i, _c, addr;
1088
- return __generator(this, function (_d) {
1089
- switch (_d.label) {
1090
- case 0:
1091
- promises = [];
1092
- for (_i = 0, _c = this.underlyingCoinAddresses; _i < _c.length; _i++) {
1093
- addr = _c[_i];
1094
- promises.push((0, utils_1._getUsdRate)(addr));
1095
- }
1096
- return [4 /*yield*/, Promise.all(promises)];
1097
- case 1: return [2 /*return*/, _d.sent()];
658
+ this._balances = async (rawCoinNames, rawCoinAddresses, ...addresses) => {
659
+ const coinNames = [];
660
+ const coinAddresses = [];
661
+ // removing duplicates
662
+ for (let i = 0; i < rawCoinAddresses.length; i++) {
663
+ if (!coinAddresses.includes(rawCoinAddresses[i])) {
664
+ coinNames.push(rawCoinNames[i]);
665
+ coinAddresses.push(rawCoinAddresses[i]);
1098
666
  }
1099
- });
1100
- }); };
1101
- // NOTE! It may crash!
1102
- this._wrappedPrices = function () { return __awaiter(_this, void 0, void 0, function () {
1103
- var promises, _i, _c, addr;
1104
- return __generator(this, function (_d) {
1105
- switch (_d.label) {
1106
- case 0:
1107
- promises = [];
1108
- for (_i = 0, _c = this.wrappedCoinAddresses; _i < _c.length; _i++) {
1109
- addr = _c[_i];
1110
- promises.push((0, utils_1._getUsdRate)(addr));
1111
- }
1112
- return [4 /*yield*/, Promise.all(promises)];
1113
- case 1: return [2 /*return*/, _d.sent()];
667
+ }
668
+ addresses = _prepareAddresses(addresses);
669
+ const rawBalances = await _getBalances(coinAddresses, addresses);
670
+ const balances = {};
671
+ for (const address of addresses) {
672
+ balances[address] = {};
673
+ for (const coinName of coinNames) {
674
+ balances[address][coinName] = rawBalances[address].shift();
1114
675
  }
1115
- });
1116
- }); };
1117
- var poolData = __assign(__assign(__assign({}, curve_1.curve.constants.POOLS_DATA), curve_1.curve.constants.FACTORY_POOLS_DATA), curve_1.curve.constants.CRYPTO_FACTORY_POOLS_DATA)[id];
676
+ }
677
+ return addresses.length === 1 ? balances[addresses[0]] : balances;
678
+ };
679
+ this._underlyingPrices = async () => {
680
+ const promises = [];
681
+ for (const addr of this.underlyingCoinAddresses) {
682
+ promises.push(_getUsdRate(addr));
683
+ }
684
+ return await Promise.all(promises);
685
+ };
686
+ // NOTE! It may crash!
687
+ this._wrappedPrices = async () => {
688
+ const promises = [];
689
+ for (const addr of this.wrappedCoinAddresses) {
690
+ promises.push(_getUsdRate(addr));
691
+ }
692
+ return await Promise.all(promises);
693
+ };
694
+ const poolData = { ...curve.constants.POOLS_DATA, ...curve.constants.FACTORY_POOLS_DATA, ...curve.constants.CRYPTO_FACTORY_POOLS_DATA }[id];
1118
695
  this.id = id;
1119
696
  this.name = poolData.name;
1120
697
  this.fullName = poolData.full_name;
@@ -1134,15 +711,15 @@ var PoolTemplate = /** @class */ (function () {
1134
711
  this.isFactory = poolData.is_factory || false;
1135
712
  this.isMetaFactory = (this.isMeta && this.isFactory) || this.zap === '0xa79828df1850e8a3a3064576f380d90aecdd3359';
1136
713
  this.basePool = poolData.base_pool || '';
1137
- this.metaCoinIdx = this.isMeta ? (_c = poolData.meta_coin_idx) !== null && _c !== void 0 ? _c : poolData.wrapped_coins.length - 1 : -1;
714
+ this.metaCoinIdx = this.isMeta ? poolData.meta_coin_idx ?? poolData.wrapped_coins.length - 1 : -1;
1138
715
  this.underlyingCoins = poolData.underlying_coins;
1139
716
  this.wrappedCoins = poolData.wrapped_coins;
1140
717
  this.underlyingCoinAddresses = poolData.underlying_coin_addresses;
1141
718
  this.wrappedCoinAddresses = poolData.wrapped_coin_addresses;
1142
719
  this.underlyingDecimals = poolData.underlying_decimals;
1143
720
  this.wrappedDecimals = poolData.wrapped_decimals;
1144
- this.useLending = poolData.use_lending || poolData.underlying_coin_addresses.map(function () { return false; });
1145
- this.inApi = (_d = poolData.in_api) !== null && _d !== void 0 ? _d : false;
721
+ this.useLending = poolData.use_lending || poolData.underlying_coin_addresses.map(() => false);
722
+ this.inApi = poolData.in_api ?? false;
1146
723
  this.estimateGas = {
1147
724
  depositApprove: this.depositApproveEstimateGas.bind(this),
1148
725
  deposit: this.depositEstimateGas.bind(this),
@@ -1189,168 +766,92 @@ var PoolTemplate = /** @class */ (function () {
1189
766
  allCoinBalances: this.walletAllCoinBalances.bind(this),
1190
767
  };
1191
768
  }
1192
- PoolTemplate.prototype.rewardsOnly = function () {
1193
- if (curve_1.curve.chainId === 2222)
769
+ rewardsOnly() {
770
+ if (curve.chainId === 2222)
1194
771
  return true; // TODO remove this for Kava and Celo
1195
- if (this.gauge === ethers_1.ethers.constants.AddressZero)
1196
- throw Error("".concat(this.name, " doesn't have gauge"));
1197
- var gaugeContract = curve_1.curve.contracts[this.gauge].contract;
772
+ if (this.gauge === curve.constants.ZERO_ADDRESS)
773
+ throw Error(`${this.name} doesn't have gauge`);
774
+ const gaugeContract = curve.contracts[this.gauge].contract;
1198
775
  return !('inflation_rate()' in gaugeContract || 'inflation_rate(uint256)' in gaugeContract);
1199
- };
1200
- PoolTemplate.prototype.statsWrappedBalances = function () {
1201
- return __awaiter(this, void 0, void 0, function () {
1202
- var swapContract, contractCalls, _wrappedBalances;
1203
- var _this = this;
1204
- return __generator(this, function (_c) {
1205
- switch (_c.label) {
1206
- case 0:
1207
- swapContract = curve_1.curve.contracts[this.address].multicallContract;
1208
- contractCalls = this.wrappedCoins.map(function (_, i) { return swapContract.balances(i); });
1209
- return [4 /*yield*/, curve_1.curve.multicallProvider.all(contractCalls)];
1210
- case 1:
1211
- _wrappedBalances = _c.sent();
1212
- return [2 /*return*/, _wrappedBalances.map(function (_b, i) { return ethers_1.ethers.utils.formatUnits(_b, _this.wrappedDecimals[i]); })];
1213
- }
1214
- });
1215
- });
1216
- };
776
+ }
777
+ async statsWrappedBalances() {
778
+ const swapContract = curve.contracts[this.address].multicallContract;
779
+ const contractCalls = this.wrappedCoins.map((_, i) => swapContract.balances(i));
780
+ const _wrappedBalances = await curve.multicallProvider.all(contractCalls);
781
+ return _wrappedBalances.map((_b, i) => curve.formatUnits(_b, this.wrappedDecimals[i]));
782
+ }
1217
783
  // OVERRIDE
1218
- PoolTemplate.prototype.statsUnderlyingBalances = function () {
1219
- return __awaiter(this, void 0, void 0, function () {
1220
- return __generator(this, function (_c) {
1221
- switch (_c.label) {
1222
- case 0: return [4 /*yield*/, this.statsWrappedBalances()];
1223
- case 1: return [2 /*return*/, _c.sent()];
1224
- }
1225
- });
1226
- });
1227
- };
1228
- PoolTemplate.prototype._pureCalcLpTokenAmount = function (_amounts, isDeposit, useUnderlying) {
1229
- if (isDeposit === void 0) { isDeposit = true; }
1230
- if (useUnderlying === void 0) { useUnderlying = true; }
1231
- return __awaiter(this, void 0, void 0, function () {
1232
- var calcContractAddress, N_coins, contract;
1233
- return __generator(this, function (_c) {
1234
- switch (_c.label) {
1235
- case 0:
1236
- calcContractAddress = this.isMeta && useUnderlying ? this.zap : this.address;
1237
- N_coins = useUnderlying ? this.underlyingCoins.length : this.wrappedCoins.length;
1238
- contract = curve_1.curve.contracts[calcContractAddress].contract;
1239
- if (!(this.isMetaFactory && useUnderlying)) return [3 /*break*/, 4];
1240
- if (!contract["calc_token_amount(address,uint256[".concat(N_coins, "],bool)")]) return [3 /*break*/, 2];
1241
- return [4 /*yield*/, contract.calc_token_amount(this.address, _amounts, isDeposit, curve_1.curve.constantOptions)];
1242
- case 1: return [2 /*return*/, _c.sent()];
1243
- case 2: return [4 /*yield*/, contract.calc_token_amount(this.address, _amounts, curve_1.curve.constantOptions)];
1244
- case 3: return [2 /*return*/, _c.sent()];
1245
- case 4:
1246
- if (!contract["calc_token_amount(uint256[".concat(N_coins, "],bool)")]) return [3 /*break*/, 6];
1247
- return [4 /*yield*/, contract.calc_token_amount(_amounts, isDeposit, curve_1.curve.constantOptions)];
1248
- case 5: return [2 /*return*/, _c.sent()];
1249
- case 6: return [4 /*yield*/, contract.calc_token_amount(_amounts, curve_1.curve.constantOptions)];
1250
- case 7: return [2 /*return*/, _c.sent()];
1251
- }
1252
- });
1253
- });
1254
- };
1255
- PoolTemplate.prototype.calcLpTokenAmount = function (amounts, isDeposit) {
1256
- if (isDeposit === void 0) { isDeposit = true; }
1257
- return __awaiter(this, void 0, void 0, function () {
1258
- var _underlyingAmounts, _expected;
1259
- var _this = this;
1260
- return __generator(this, function (_c) {
1261
- switch (_c.label) {
1262
- case 0:
1263
- if (amounts.length !== this.underlyingCoinAddresses.length) {
1264
- throw Error("".concat(this.name, " pool has ").concat(this.underlyingCoinAddresses.length, " coins (amounts provided for ").concat(amounts.length, ")"));
1265
- }
1266
- _underlyingAmounts = amounts.map(function (amount, i) { return (0, utils_1.parseUnits)(amount, _this.underlyingDecimals[i]); });
1267
- return [4 /*yield*/, this._calcLpTokenAmount(_underlyingAmounts, isDeposit, true)];
1268
- case 1:
1269
- _expected = _c.sent();
1270
- return [2 /*return*/, ethers_1.ethers.utils.formatUnits(_expected)];
1271
- }
1272
- });
1273
- });
1274
- };
1275
- PoolTemplate.prototype.calcLpTokenAmountWrapped = function (amounts, isDeposit) {
1276
- if (isDeposit === void 0) { isDeposit = true; }
1277
- return __awaiter(this, void 0, void 0, function () {
1278
- var _amounts, _expected;
1279
- var _this = this;
1280
- return __generator(this, function (_c) {
1281
- switch (_c.label) {
1282
- case 0:
1283
- if (amounts.length !== this.wrappedCoinAddresses.length) {
1284
- throw Error("".concat(this.name, " pool has ").concat(this.wrappedCoinAddresses.length, " coins (amounts provided for ").concat(amounts.length, ")"));
1285
- }
1286
- if (this.isFake) {
1287
- throw Error("".concat(this.name, " pool doesn't have this method"));
1288
- }
1289
- _amounts = amounts.map(function (amount, i) { return (0, utils_1.parseUnits)(amount, _this.wrappedDecimals[i]); });
1290
- return [4 /*yield*/, this._calcLpTokenAmount(_amounts, isDeposit, false)];
1291
- case 1:
1292
- _expected = _c.sent();
1293
- return [2 /*return*/, ethers_1.ethers.utils.formatUnits(_expected)];
1294
- }
1295
- });
1296
- });
1297
- };
784
+ async statsUnderlyingBalances() {
785
+ return await this.statsWrappedBalances();
786
+ }
787
+ async _pureCalcLpTokenAmount(_amounts, isDeposit = true, useUnderlying = true) {
788
+ const calcContractAddress = this.isMeta && useUnderlying ? this.zap : this.address;
789
+ const N_coins = useUnderlying ? this.underlyingCoins.length : this.wrappedCoins.length;
790
+ const contract = curve.contracts[calcContractAddress].contract;
791
+ if (this.isMetaFactory && useUnderlying) {
792
+ if (contract[`calc_token_amount(address,uint256[${N_coins}],bool)`]) {
793
+ return await contract.calc_token_amount(this.address, _amounts, isDeposit, curve.constantOptions);
794
+ }
795
+ return await contract.calc_token_amount(this.address, _amounts, curve.constantOptions);
796
+ }
797
+ if (contract[`calc_token_amount(uint256[${N_coins}],bool)`]) {
798
+ return await contract.calc_token_amount(_amounts, isDeposit, curve.constantOptions);
799
+ }
800
+ return await contract.calc_token_amount(_amounts, curve.constantOptions);
801
+ }
802
+ async calcLpTokenAmount(amounts, isDeposit = true) {
803
+ if (amounts.length !== this.underlyingCoinAddresses.length) {
804
+ throw Error(`${this.name} pool has ${this.underlyingCoinAddresses.length} coins (amounts provided for ${amounts.length})`);
805
+ }
806
+ const _underlyingAmounts = amounts.map((amount, i) => parseUnits(amount, this.underlyingDecimals[i]));
807
+ const _expected = await this._calcLpTokenAmount(_underlyingAmounts, isDeposit, true);
808
+ return curve.formatUnits(_expected);
809
+ }
810
+ async calcLpTokenAmountWrapped(amounts, isDeposit = true) {
811
+ if (amounts.length !== this.wrappedCoinAddresses.length) {
812
+ throw Error(`${this.name} pool has ${this.wrappedCoinAddresses.length} coins (amounts provided for ${amounts.length})`);
813
+ }
814
+ if (this.isFake) {
815
+ throw Error(`${this.name} pool doesn't have this method`);
816
+ }
817
+ const _amounts = amounts.map((amount, i) => parseUnits(amount, this.wrappedDecimals[i]));
818
+ const _expected = await this._calcLpTokenAmount(_amounts, isDeposit, false);
819
+ return curve.formatUnits(_expected);
820
+ }
1298
821
  // ---------------- DEPOSIT ----------------
1299
- PoolTemplate.prototype.metaUnderlyingSeedAmounts = function (amount1) {
822
+ metaUnderlyingSeedAmounts(amount1) {
1300
823
  if (this.isCrypto)
1301
- throw Error("Use cryptoSeedAmounts method for ".concat(this.name, " pool"));
824
+ throw Error(`Use cryptoSeedAmounts method for ${this.name} pool`);
1302
825
  if (!this.isMeta)
1303
826
  throw Error("metaUnderlyingSeedAmounts method exists only for meta stable pools");
1304
- var amount1BN = (0, utils_1.BN)(amount1);
827
+ const amount1BN = BN(amount1);
1305
828
  if (amount1BN.lte(0))
1306
829
  throw Error("Initial deposit amounts must be > 0");
1307
- var amounts = [(0, utils_1._cutZeros)(amount1BN.toFixed(this.underlyingDecimals[0]))];
1308
- for (var i = 1; i < this.underlyingDecimals.length; i++) {
830
+ const amounts = [_cutZeros(amount1BN.toFixed(this.underlyingDecimals[0]))];
831
+ for (let i = 1; i < this.underlyingDecimals.length; i++) {
1309
832
  amounts.push(amount1BN.div(this.underlyingDecimals.length - 1).toFixed(this.underlyingDecimals[i]));
1310
833
  }
1311
834
  return amounts;
1312
- };
1313
- PoolTemplate.prototype.cryptoSeedAmounts = function (amount1) {
1314
- return __awaiter(this, void 0, void 0, function () {
1315
- var decimals, amount1BN, priceScaleBN, _c;
1316
- return __generator(this, function (_d) {
1317
- switch (_d.label) {
1318
- case 0:
1319
- if (!this.isCrypto)
1320
- throw Error("cryptoSeedAmounts method doesn't exist for stable pools");
1321
- decimals = this.isMeta ? this.wrappedDecimals : this.underlyingDecimals;
1322
- if (decimals.length > 2)
1323
- throw Error("cryptoSeedAmounts method doesn't exist for pools with N coins > 2");
1324
- amount1BN = (0, utils_1.BN)(amount1);
1325
- if (amount1BN.lte(0))
1326
- throw Error("Initial deposit amounts must be > 0");
1327
- _c = utils_1.toBN;
1328
- return [4 /*yield*/, curve_1.curve.contracts[this.address].contract.price_scale(curve_1.curve.constantOptions)];
1329
- case 1:
1330
- priceScaleBN = _c.apply(void 0, [_d.sent()]);
1331
- return [2 /*return*/, [(0, utils_1._cutZeros)(amount1BN.toFixed(decimals[0])), (0, utils_1._cutZeros)(amount1BN.div(priceScaleBN).toFixed(decimals[1]))]];
1332
- }
1333
- });
1334
- });
1335
- };
835
+ }
836
+ async cryptoSeedAmounts(amount1) {
837
+ if (!this.isCrypto)
838
+ throw Error("cryptoSeedAmounts method doesn't exist for stable pools");
839
+ const decimals = this.isMeta ? this.wrappedDecimals : this.underlyingDecimals;
840
+ if (decimals.length > 2)
841
+ throw Error("cryptoSeedAmounts method doesn't exist for pools with N coins > 2");
842
+ const amount1BN = BN(amount1);
843
+ if (amount1BN.lte(0))
844
+ throw Error("Initial deposit amounts must be > 0");
845
+ const priceScaleBN = toBN(await curve.contracts[this.address].contract.price_scale(curve.constantOptions));
846
+ return [_cutZeros(amount1BN.toFixed(decimals[0])), _cutZeros(amount1BN.div(priceScaleBN).toFixed(decimals[1]))];
847
+ }
1336
848
  // OVERRIDE
1337
- PoolTemplate.prototype.depositBalancedAmounts = function () {
1338
- return __awaiter(this, void 0, void 0, function () {
1339
- return __generator(this, function (_c) {
1340
- throw Error("depositBalancedAmounts method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
1341
- });
1342
- });
1343
- };
1344
- PoolTemplate.prototype.depositExpected = function (amounts) {
1345
- return __awaiter(this, void 0, void 0, function () {
1346
- return __generator(this, function (_c) {
1347
- switch (_c.label) {
1348
- case 0: return [4 /*yield*/, this.calcLpTokenAmount(amounts)];
1349
- case 1: return [2 /*return*/, _c.sent()];
1350
- }
1351
- });
1352
- });
1353
- };
849
+ async depositBalancedAmounts() {
850
+ throw Error(`depositBalancedAmounts method doesn't exist for pool ${this.name} (id: ${this.name})`);
851
+ }
852
+ async depositExpected(amounts) {
853
+ return await this.calcLpTokenAmount(amounts);
854
+ }
1354
855
  // | balanced[i] / sum(balanced[j]) = balance[i] / sum(balance[j]) |
1355
856
  // | sum(pj * balanced[j]) = sum(aj * pj) |
1356
857
  //
@@ -1361,1761 +862,807 @@ var PoolTemplate = /** @class */ (function () {
1361
862
  // totalBalanceBN = sum(balance[j])
1362
863
  // ratiosBN[i] = balancesBN[i] / totalBalanceBN = ri = balance[i] / sum(balance[j])
1363
864
  // denominatorBN = sum(rj * pj / ri)
1364
- PoolTemplate.prototype._balancedAmountsWithSameValue = function (amountsBN, pricesBN, balancesBN) {
1365
- var valuesBN = amountsBN.map(function (aBN, i) { return aBN.times(pricesBN[i]); });
1366
- var totalValueBN = valuesBN.reduce(function (v1BN, v2BN) { return v1BN.plus(v2BN); });
1367
- var totalBalanceBN = balancesBN.reduce(function (b1BN, b2BN) { return b1BN.plus(b2BN); });
1368
- var ratiosBN = balancesBN.map(function (bBN) { return bBN.div(totalBalanceBN); });
1369
- var balancedAmountsBN = [];
1370
- var _loop_1 = function (i) {
1371
- var denominatorBN = ratiosBN.map(function (rBN, j) { return rBN.times(pricesBN[j])
1372
- .div(ratiosBN[i]); }).reduce(function (xBN, yBN) { return xBN.plus(yBN); });
865
+ _balancedAmountsWithSameValue(amountsBN, pricesBN, balancesBN) {
866
+ const valuesBN = amountsBN.map((aBN, i) => aBN.times(pricesBN[i]));
867
+ const totalValueBN = valuesBN.reduce((v1BN, v2BN) => v1BN.plus(v2BN));
868
+ const totalBalanceBN = balancesBN.reduce((b1BN, b2BN) => b1BN.plus(b2BN));
869
+ const ratiosBN = balancesBN.map((bBN) => bBN.div(totalBalanceBN));
870
+ const balancedAmountsBN = [];
871
+ for (let i = 0; i < amountsBN.length; i++) {
872
+ const denominatorBN = ratiosBN.map((rBN, j) => rBN.times(pricesBN[j])
873
+ .div(ratiosBN[i])).reduce((xBN, yBN) => xBN.plus(yBN));
1373
874
  balancedAmountsBN.push(totalValueBN.div(denominatorBN));
1374
- };
1375
- for (var i = 0; i < amountsBN.length; i++) {
1376
- _loop_1(i);
1377
875
  }
1378
876
  return balancedAmountsBN.map(String);
1379
- };
1380
- PoolTemplate.prototype.depositBonus = function (amounts) {
1381
- return __awaiter(this, void 0, void 0, function () {
1382
- var amountsBN, prices, _c, pricesBN, balancesBN, balancedAmounts, expectedBN, _d, balancedExpectedBN, _e;
1383
- return __generator(this, function (_f) {
1384
- switch (_f.label) {
1385
- case 0:
1386
- amountsBN = amounts.map(utils_1.BN);
1387
- if (!(this.isCrypto || this.id === 'wsteth')) return [3 /*break*/, 2];
1388
- return [4 /*yield*/, this._underlyingPrices()];
1389
- case 1:
1390
- _c = _f.sent();
1391
- return [3 /*break*/, 3];
1392
- case 2:
1393
- _c = this.underlyingCoins.map(function () { return 1; });
1394
- _f.label = 3;
1395
- case 3:
1396
- prices = _c;
1397
- pricesBN = prices.map(utils_1.BN);
1398
- return [4 /*yield*/, this.stats.underlyingBalances()];
1399
- case 4:
1400
- balancesBN = (_f.sent()).map(utils_1.BN);
1401
- balancedAmounts = this._balancedAmountsWithSameValue(amountsBN, pricesBN, balancesBN);
1402
- _d = utils_1.BN;
1403
- return [4 /*yield*/, this.depositExpected(amounts)];
1404
- case 5:
1405
- expectedBN = _d.apply(void 0, [_f.sent()]);
1406
- _e = utils_1.BN;
1407
- return [4 /*yield*/, this.depositExpected(balancedAmounts)];
1408
- case 6:
1409
- balancedExpectedBN = _e.apply(void 0, [_f.sent()]);
1410
- return [2 /*return*/, String(expectedBN.minus(balancedExpectedBN).div(balancedExpectedBN).times(100))];
1411
- }
1412
- });
1413
- });
1414
- };
1415
- PoolTemplate.prototype.depositIsApproved = function (amounts) {
1416
- return __awaiter(this, void 0, void 0, function () {
1417
- return __generator(this, function (_c) {
1418
- switch (_c.label) {
1419
- case 0: return [4 /*yield*/, (0, utils_1.hasAllowance)(this.underlyingCoinAddresses, amounts, curve_1.curve.signerAddress, this.zap || this.address)];
1420
- case 1: return [2 /*return*/, _c.sent()];
1421
- }
1422
- });
1423
- });
1424
- };
1425
- PoolTemplate.prototype.depositApproveEstimateGas = function (amounts) {
1426
- return __awaiter(this, void 0, void 0, function () {
1427
- return __generator(this, function (_c) {
1428
- switch (_c.label) {
1429
- case 0: return [4 /*yield*/, (0, utils_1.ensureAllowanceEstimateGas)(this.underlyingCoinAddresses, amounts, this.zap || this.address)];
1430
- case 1: return [2 /*return*/, _c.sent()];
1431
- }
1432
- });
1433
- });
1434
- };
1435
- PoolTemplate.prototype.depositApprove = function (amounts) {
1436
- return __awaiter(this, void 0, void 0, function () {
1437
- return __generator(this, function (_c) {
1438
- switch (_c.label) {
1439
- case 0: return [4 /*yield*/, (0, utils_1.ensureAllowance)(this.underlyingCoinAddresses, amounts, this.zap || this.address)];
1440
- case 1: return [2 /*return*/, _c.sent()];
1441
- }
1442
- });
1443
- });
1444
- };
877
+ }
878
+ async depositBonus(amounts) {
879
+ const amountsBN = amounts.map(BN);
880
+ const prices = (this.isCrypto || this.id === 'wsteth') ? await this._underlyingPrices() : this.underlyingCoins.map(() => 1);
881
+ const pricesBN = prices.map(BN);
882
+ const balancesBN = (await this.stats.underlyingBalances()).map(BN);
883
+ const balancedAmounts = this._balancedAmountsWithSameValue(amountsBN, pricesBN, balancesBN);
884
+ const expectedBN = BN(await this.depositExpected(amounts));
885
+ const balancedExpectedBN = BN(await this.depositExpected(balancedAmounts));
886
+ return String(expectedBN.minus(balancedExpectedBN).div(balancedExpectedBN).times(100));
887
+ }
888
+ async depositIsApproved(amounts) {
889
+ return await hasAllowance(this.underlyingCoinAddresses, amounts, curve.signerAddress, this.zap || this.address);
890
+ }
891
+ async depositApproveEstimateGas(amounts) {
892
+ return await ensureAllowanceEstimateGas(this.underlyingCoinAddresses, amounts, this.zap || this.address);
893
+ }
894
+ async depositApprove(amounts) {
895
+ return await ensureAllowance(this.underlyingCoinAddresses, amounts, this.zap || this.address);
896
+ }
1445
897
  // OVERRIDE
1446
- PoolTemplate.prototype.depositEstimateGas = function (amounts) {
1447
- return __awaiter(this, void 0, void 0, function () {
1448
- return __generator(this, function (_c) {
1449
- throw Error("depositEstimateGas method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
1450
- });
1451
- });
1452
- };
898
+ async depositEstimateGas(amounts) {
899
+ throw Error(`depositEstimateGas method doesn't exist for pool ${this.name} (id: ${this.name})`);
900
+ }
1453
901
  // OVERRIDE
1454
- PoolTemplate.prototype.deposit = function (amounts, slippage) {
1455
- if (slippage === void 0) { slippage = 0.5; }
1456
- return __awaiter(this, void 0, void 0, function () {
1457
- return __generator(this, function (_c) {
1458
- throw Error("deposit method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
1459
- });
1460
- });
1461
- };
902
+ async deposit(amounts, slippage = 0.5) {
903
+ throw Error(`deposit method doesn't exist for pool ${this.name} (id: ${this.name})`);
904
+ }
1462
905
  // ---------------- DEPOSIT WRAPPED ----------------
1463
- PoolTemplate.prototype.depositWrappedBalancedAmounts = function () {
1464
- return __awaiter(this, void 0, void 0, function () {
1465
- return __generator(this, function (_c) {
1466
- throw Error("depositWrappedBalancedAmounts method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
1467
- });
1468
- });
1469
- };
1470
- PoolTemplate.prototype.depositWrappedExpected = function (amounts) {
1471
- return __awaiter(this, void 0, void 0, function () {
1472
- return __generator(this, function (_c) {
1473
- switch (_c.label) {
1474
- case 0:
1475
- if (this.isFake) {
1476
- throw Error("depositWrappedExpected method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
1477
- }
1478
- return [4 /*yield*/, this.calcLpTokenAmountWrapped(amounts)];
1479
- case 1: return [2 /*return*/, _c.sent()];
1480
- }
1481
- });
1482
- });
1483
- };
1484
- PoolTemplate.prototype.depositWrappedBonus = function (amounts) {
1485
- return __awaiter(this, void 0, void 0, function () {
1486
- var amountsBN, pricesBN, balancesBN, balancedAmounts, expectedBN, _c, balancedExpectedBN, _d;
1487
- return __generator(this, function (_e) {
1488
- switch (_e.label) {
1489
- case 0:
1490
- amountsBN = amounts.map(utils_1.BN);
1491
- return [4 /*yield*/, this._wrappedPrices()];
1492
- case 1:
1493
- pricesBN = (_e.sent()).map(utils_1.BN);
1494
- return [4 /*yield*/, this.stats.wrappedBalances()];
1495
- case 2:
1496
- balancesBN = (_e.sent()).map(utils_1.BN);
1497
- balancedAmounts = this._balancedAmountsWithSameValue(amountsBN, pricesBN, balancesBN);
1498
- _c = utils_1.BN;
1499
- return [4 /*yield*/, this.depositWrappedExpected(amounts)];
1500
- case 3:
1501
- expectedBN = _c.apply(void 0, [_e.sent()]);
1502
- _d = utils_1.BN;
1503
- return [4 /*yield*/, this.depositWrappedExpected(balancedAmounts)];
1504
- case 4:
1505
- balancedExpectedBN = _d.apply(void 0, [_e.sent()]);
1506
- return [2 /*return*/, String(expectedBN.minus(balancedExpectedBN).div(balancedExpectedBN).times(100))];
1507
- }
1508
- });
1509
- });
1510
- };
1511
- PoolTemplate.prototype.depositWrappedIsApproved = function (amounts) {
1512
- return __awaiter(this, void 0, void 0, function () {
1513
- return __generator(this, function (_c) {
1514
- switch (_c.label) {
1515
- case 0:
1516
- if (this.isFake) {
1517
- throw Error("depositWrappedIsApproved method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
1518
- }
1519
- return [4 /*yield*/, (0, utils_1.hasAllowance)(this.wrappedCoinAddresses, amounts, curve_1.curve.signerAddress, this.address)];
1520
- case 1: return [2 /*return*/, _c.sent()];
1521
- }
1522
- });
1523
- });
1524
- };
1525
- PoolTemplate.prototype.depositWrappedApproveEstimateGas = function (amounts) {
1526
- return __awaiter(this, void 0, void 0, function () {
1527
- return __generator(this, function (_c) {
1528
- switch (_c.label) {
1529
- case 0:
1530
- if (this.isFake) {
1531
- throw Error("depositWrappedApprove method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
1532
- }
1533
- return [4 /*yield*/, (0, utils_1.ensureAllowanceEstimateGas)(this.wrappedCoinAddresses, amounts, this.address)];
1534
- case 1: return [2 /*return*/, _c.sent()];
1535
- }
1536
- });
1537
- });
1538
- };
1539
- PoolTemplate.prototype.depositWrappedApprove = function (amounts) {
1540
- return __awaiter(this, void 0, void 0, function () {
1541
- return __generator(this, function (_c) {
1542
- switch (_c.label) {
1543
- case 0:
1544
- if (this.isFake) {
1545
- throw Error("depositWrappedApprove method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
1546
- }
1547
- return [4 /*yield*/, (0, utils_1.ensureAllowance)(this.wrappedCoinAddresses, amounts, this.address)];
1548
- case 1: return [2 /*return*/, _c.sent()];
1549
- }
1550
- });
1551
- });
1552
- };
906
+ async depositWrappedBalancedAmounts() {
907
+ throw Error(`depositWrappedBalancedAmounts method doesn't exist for pool ${this.name} (id: ${this.name})`);
908
+ }
909
+ async depositWrappedExpected(amounts) {
910
+ if (this.isFake) {
911
+ throw Error(`depositWrappedExpected method doesn't exist for pool ${this.name} (id: ${this.name})`);
912
+ }
913
+ return await this.calcLpTokenAmountWrapped(amounts);
914
+ }
915
+ async depositWrappedBonus(amounts) {
916
+ const amountsBN = amounts.map(BN);
917
+ const pricesBN = (await this._wrappedPrices()).map(BN);
918
+ const balancesBN = (await this.stats.wrappedBalances()).map(BN);
919
+ const balancedAmounts = this._balancedAmountsWithSameValue(amountsBN, pricesBN, balancesBN);
920
+ const expectedBN = BN(await this.depositWrappedExpected(amounts));
921
+ const balancedExpectedBN = BN(await this.depositWrappedExpected(balancedAmounts));
922
+ return String(expectedBN.minus(balancedExpectedBN).div(balancedExpectedBN).times(100));
923
+ }
924
+ async depositWrappedIsApproved(amounts) {
925
+ if (this.isFake) {
926
+ throw Error(`depositWrappedIsApproved method doesn't exist for pool ${this.name} (id: ${this.name})`);
927
+ }
928
+ return await hasAllowance(this.wrappedCoinAddresses, amounts, curve.signerAddress, this.address);
929
+ }
930
+ async depositWrappedApproveEstimateGas(amounts) {
931
+ if (this.isFake) {
932
+ throw Error(`depositWrappedApprove method doesn't exist for pool ${this.name} (id: ${this.name})`);
933
+ }
934
+ return await ensureAllowanceEstimateGas(this.wrappedCoinAddresses, amounts, this.address);
935
+ }
936
+ async depositWrappedApprove(amounts) {
937
+ if (this.isFake) {
938
+ throw Error(`depositWrappedApprove method doesn't exist for pool ${this.name} (id: ${this.name})`);
939
+ }
940
+ return await ensureAllowance(this.wrappedCoinAddresses, amounts, this.address);
941
+ }
1553
942
  // OVERRIDE
1554
- PoolTemplate.prototype.depositWrappedEstimateGas = function (amounts) {
1555
- return __awaiter(this, void 0, void 0, function () {
1556
- return __generator(this, function (_c) {
1557
- throw Error("depositWrapped method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
1558
- });
1559
- });
1560
- };
943
+ async depositWrappedEstimateGas(amounts) {
944
+ throw Error(`depositWrapped method doesn't exist for pool ${this.name} (id: ${this.name})`);
945
+ }
1561
946
  // OVERRIDE
1562
- PoolTemplate.prototype.depositWrapped = function (amounts, slippage) {
1563
- if (slippage === void 0) { slippage = 0.5; }
1564
- return __awaiter(this, void 0, void 0, function () {
1565
- return __generator(this, function (_c) {
1566
- throw Error("depositWrapped method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
1567
- });
1568
- });
1569
- };
947
+ async depositWrapped(amounts, slippage = 0.5) {
948
+ throw Error(`depositWrapped method doesn't exist for pool ${this.name} (id: ${this.name})`);
949
+ }
1570
950
  // ---------------- STAKING ----------------
1571
- PoolTemplate.prototype.stakeIsApproved = function (lpTokenAmount) {
1572
- return __awaiter(this, void 0, void 0, function () {
1573
- return __generator(this, function (_c) {
1574
- switch (_c.label) {
1575
- case 0:
1576
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1577
- throw Error("stakeIsApproved method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1578
- }
1579
- return [4 /*yield*/, (0, utils_1.hasAllowance)([this.lpToken], [lpTokenAmount], curve_1.curve.signerAddress, this.gauge)];
1580
- case 1: return [2 /*return*/, _c.sent()];
1581
- }
1582
- });
1583
- });
1584
- };
1585
- PoolTemplate.prototype.stakeApproveEstimateGas = function (lpTokenAmount) {
1586
- return __awaiter(this, void 0, void 0, function () {
1587
- return __generator(this, function (_c) {
1588
- switch (_c.label) {
1589
- case 0:
1590
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1591
- throw Error("stakeApproveEstimateGas method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1592
- }
1593
- return [4 /*yield*/, (0, utils_1.ensureAllowanceEstimateGas)([this.lpToken], [lpTokenAmount], this.gauge)];
1594
- case 1: return [2 /*return*/, _c.sent()];
1595
- }
1596
- });
1597
- });
1598
- };
1599
- PoolTemplate.prototype.stakeApprove = function (lpTokenAmount) {
1600
- return __awaiter(this, void 0, void 0, function () {
1601
- return __generator(this, function (_c) {
1602
- switch (_c.label) {
1603
- case 0:
1604
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1605
- throw Error("stakeApprove method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1606
- }
1607
- return [4 /*yield*/, (0, utils_1.ensureAllowance)([this.lpToken], [lpTokenAmount], this.gauge)];
1608
- case 1: return [2 /*return*/, _c.sent()];
1609
- }
1610
- });
1611
- });
1612
- };
1613
- PoolTemplate.prototype.stakeEstimateGas = function (lpTokenAmount) {
1614
- return __awaiter(this, void 0, void 0, function () {
1615
- var _lpTokenAmount;
1616
- return __generator(this, function (_c) {
1617
- switch (_c.label) {
1618
- case 0:
1619
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1620
- throw Error("stakeEstimateGas method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1621
- }
1622
- _lpTokenAmount = (0, utils_1.parseUnits)(lpTokenAmount);
1623
- return [4 /*yield*/, curve_1.curve.contracts[this.gauge].contract.estimateGas.deposit(_lpTokenAmount, curve_1.curve.constantOptions)];
1624
- case 1: return [2 /*return*/, (_c.sent()).toNumber()];
1625
- }
1626
- });
1627
- });
1628
- };
1629
- PoolTemplate.prototype.stake = function (lpTokenAmount) {
1630
- return __awaiter(this, void 0, void 0, function () {
1631
- var _lpTokenAmount, gasLimit;
1632
- return __generator(this, function (_c) {
1633
- switch (_c.label) {
1634
- case 0:
1635
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1636
- throw Error("stake method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1637
- }
1638
- _lpTokenAmount = (0, utils_1.parseUnits)(lpTokenAmount);
1639
- return [4 /*yield*/, (0, utils_1._ensureAllowance)([this.lpToken], [_lpTokenAmount], this.gauge)];
1640
- case 1:
1641
- _c.sent();
1642
- return [4 /*yield*/, curve_1.curve.updateFeeData()];
1643
- case 2:
1644
- _c.sent();
1645
- return [4 /*yield*/, curve_1.curve.contracts[this.gauge].contract.estimateGas.deposit(_lpTokenAmount, curve_1.curve.constantOptions)];
1646
- case 3:
1647
- gasLimit = (_c.sent()).mul(150).div(100);
1648
- return [4 /*yield*/, curve_1.curve.contracts[this.gauge].contract.deposit(_lpTokenAmount, __assign(__assign({}, curve_1.curve.options), { gasLimit: gasLimit }))];
1649
- case 4: return [2 /*return*/, (_c.sent()).hash];
1650
- }
1651
- });
1652
- });
1653
- };
1654
- PoolTemplate.prototype.unstakeEstimateGas = function (lpTokenAmount) {
1655
- return __awaiter(this, void 0, void 0, function () {
1656
- var _lpTokenAmount;
1657
- return __generator(this, function (_c) {
1658
- switch (_c.label) {
1659
- case 0:
1660
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1661
- throw Error("unstakeEstimateGas method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1662
- }
1663
- _lpTokenAmount = (0, utils_1.parseUnits)(lpTokenAmount);
1664
- return [4 /*yield*/, curve_1.curve.contracts[this.gauge].contract.estimateGas.withdraw(_lpTokenAmount, curve_1.curve.constantOptions)];
1665
- case 1: return [2 /*return*/, (_c.sent()).toNumber()];
1666
- }
1667
- });
1668
- });
1669
- };
1670
- PoolTemplate.prototype.unstake = function (lpTokenAmount) {
1671
- return __awaiter(this, void 0, void 0, function () {
1672
- var _lpTokenAmount, gasLimit;
1673
- return __generator(this, function (_c) {
1674
- switch (_c.label) {
1675
- case 0:
1676
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1677
- throw Error("unstake method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1678
- }
1679
- _lpTokenAmount = (0, utils_1.parseUnits)(lpTokenAmount);
1680
- return [4 /*yield*/, curve_1.curve.updateFeeData()];
1681
- case 1:
1682
- _c.sent();
1683
- return [4 /*yield*/, curve_1.curve.contracts[this.gauge].contract.estimateGas.withdraw(_lpTokenAmount, curve_1.curve.constantOptions)];
1684
- case 2:
1685
- gasLimit = (_c.sent()).mul(200).div(100);
1686
- return [4 /*yield*/, curve_1.curve.contracts[this.gauge].contract.withdraw(_lpTokenAmount, __assign(__assign({}, curve_1.curve.options), { gasLimit: gasLimit }))];
1687
- case 3: return [2 /*return*/, (_c.sent()).hash];
1688
- }
1689
- });
1690
- });
1691
- };
1692
- PoolTemplate.prototype.claimableCrv = function (address) {
1693
- if (address === void 0) { address = ""; }
1694
- return __awaiter(this, void 0, void 0, function () {
1695
- var _c, _d;
1696
- return __generator(this, function (_e) {
1697
- switch (_e.label) {
1698
- case 0:
1699
- if (this.rewardsOnly())
1700
- throw Error("".concat(this.name, " has Rewards-Only Gauge. Use claimableRewards instead"));
1701
- address = address || curve_1.curve.signerAddress;
1702
- if (!address)
1703
- throw Error("Need to connect wallet or pass address into args");
1704
- _d = (_c = ethers_1.ethers.utils).formatUnits;
1705
- return [4 /*yield*/, curve_1.curve.contracts[this.gauge].contract.claimable_tokens(address, curve_1.curve.constantOptions)];
1706
- case 1: return [2 /*return*/, _d.apply(_c, [_e.sent()])];
1707
- }
1708
- });
1709
- });
1710
- };
1711
- PoolTemplate.prototype.claimCrvEstimateGas = function () {
1712
- return __awaiter(this, void 0, void 0, function () {
1713
- return __generator(this, function (_c) {
1714
- switch (_c.label) {
1715
- case 0:
1716
- if (this.rewardsOnly())
1717
- throw Error("".concat(this.name, " has Rewards-Only Gauge. Use claimRewards instead"));
1718
- return [4 /*yield*/, curve_1.curve.contracts[curve_1.curve.constants.ALIASES.minter].contract.estimateGas.mint(this.gauge, curve_1.curve.constantOptions)];
1719
- case 1: return [2 /*return*/, (_c.sent()).toNumber()];
1720
- }
1721
- });
1722
- });
1723
- };
1724
- PoolTemplate.prototype.claimCrv = function () {
1725
- return __awaiter(this, void 0, void 0, function () {
1726
- var contract, gasLimit;
1727
- return __generator(this, function (_c) {
1728
- switch (_c.label) {
1729
- case 0:
1730
- if (this.rewardsOnly())
1731
- throw Error("".concat(this.name, " has Rewards-Only Gauge. Use claimRewards instead"));
1732
- contract = curve_1.curve.contracts[curve_1.curve.constants.ALIASES.minter].contract;
1733
- return [4 /*yield*/, contract.estimateGas.mint(this.gauge, curve_1.curve.constantOptions)];
1734
- case 1:
1735
- gasLimit = (_c.sent()).mul(130).div(100);
1736
- return [4 /*yield*/, contract.mint(this.gauge, __assign(__assign({}, curve_1.curve.options), { gasLimit: gasLimit }))];
1737
- case 2: return [2 /*return*/, (_c.sent()).hash];
1738
- }
1739
- });
1740
- });
1741
- };
951
+ async stakeIsApproved(lpTokenAmount) {
952
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
953
+ throw Error(`stakeIsApproved method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
954
+ }
955
+ return await hasAllowance([this.lpToken], [lpTokenAmount], curve.signerAddress, this.gauge);
956
+ }
957
+ async stakeApproveEstimateGas(lpTokenAmount) {
958
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
959
+ throw Error(`stakeApproveEstimateGas method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
960
+ }
961
+ return await ensureAllowanceEstimateGas([this.lpToken], [lpTokenAmount], this.gauge);
962
+ }
963
+ async stakeApprove(lpTokenAmount) {
964
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
965
+ throw Error(`stakeApprove method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
966
+ }
967
+ return await ensureAllowance([this.lpToken], [lpTokenAmount], this.gauge);
968
+ }
969
+ async stakeEstimateGas(lpTokenAmount) {
970
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
971
+ throw Error(`stakeEstimateGas method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
972
+ }
973
+ const _lpTokenAmount = parseUnits(lpTokenAmount);
974
+ return Number(await curve.contracts[this.gauge].contract.deposit.estimateGas(_lpTokenAmount, curve.constantOptions));
975
+ }
976
+ async stake(lpTokenAmount) {
977
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
978
+ throw Error(`stake method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
979
+ }
980
+ const _lpTokenAmount = parseUnits(lpTokenAmount);
981
+ await _ensureAllowance([this.lpToken], [_lpTokenAmount], this.gauge);
982
+ await curve.updateFeeData();
983
+ const gasLimit = mulBy1_3(await curve.contracts[this.gauge].contract.deposit.estimateGas(_lpTokenAmount, curve.constantOptions));
984
+ return (await curve.contracts[this.gauge].contract.deposit(_lpTokenAmount, { ...curve.options, gasLimit })).hash;
985
+ }
986
+ async unstakeEstimateGas(lpTokenAmount) {
987
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
988
+ throw Error(`unstakeEstimateGas method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
989
+ }
990
+ const _lpTokenAmount = parseUnits(lpTokenAmount);
991
+ return Number(await curve.contracts[this.gauge].contract.withdraw.estimateGas(_lpTokenAmount, curve.constantOptions));
992
+ }
993
+ async unstake(lpTokenAmount) {
994
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
995
+ throw Error(`unstake method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
996
+ }
997
+ const _lpTokenAmount = parseUnits(lpTokenAmount);
998
+ await curve.updateFeeData();
999
+ const gasLimit = (await curve.contracts[this.gauge].contract.withdraw.estimateGas(_lpTokenAmount, curve.constantOptions)) * 200n / 100n;
1000
+ return (await curve.contracts[this.gauge].contract.withdraw(_lpTokenAmount, { ...curve.options, gasLimit })).hash;
1001
+ }
1002
+ async claimableCrv(address = "") {
1003
+ if (this.rewardsOnly())
1004
+ throw Error(`${this.name} has Rewards-Only Gauge. Use claimableRewards instead`);
1005
+ address = address || curve.signerAddress;
1006
+ if (!address)
1007
+ throw Error("Need to connect wallet or pass address into args");
1008
+ return curve.formatUnits(await curve.contracts[this.gauge].contract.claimable_tokens(address, curve.constantOptions));
1009
+ }
1010
+ async claimCrvEstimateGas() {
1011
+ if (this.rewardsOnly())
1012
+ throw Error(`${this.name} has Rewards-Only Gauge. Use claimRewards instead`);
1013
+ return Number(await curve.contracts[curve.constants.ALIASES.minter].contract.mint.estimateGas(this.gauge, curve.constantOptions));
1014
+ }
1015
+ async claimCrv() {
1016
+ if (this.rewardsOnly())
1017
+ throw Error(`${this.name} has Rewards-Only Gauge. Use claimRewards instead`);
1018
+ const contract = curve.contracts[curve.constants.ALIASES.minter].contract;
1019
+ const gasLimit = mulBy1_3(await contract.mint.estimateGas(this.gauge, curve.constantOptions));
1020
+ return (await contract.mint(this.gauge, { ...curve.options, gasLimit })).hash;
1021
+ }
1742
1022
  // TODO 1. Fix aave and saave error
1743
- PoolTemplate.prototype.claimableRewards = function (address) {
1744
- if (address === void 0) { address = ""; }
1745
- return __awaiter(this, void 0, void 0, function () {
1746
- var gaugeContract, rewardTokens, rewards, _i, rewardTokens_5, rewardToken, _amount, rewardToken, _totalAmount, _claimedAmount;
1747
- return __generator(this, function (_c) {
1748
- switch (_c.label) {
1749
- case 0:
1750
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1751
- throw Error("claimableRewards method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1752
- }
1753
- address = address || curve_1.curve.signerAddress;
1754
- if (!address)
1755
- throw Error("Need to connect wallet or pass address into args");
1756
- gaugeContract = curve_1.curve.contracts[this.gauge].contract;
1757
- return [4 /*yield*/, this.rewardTokens()];
1758
- case 1:
1759
- rewardTokens = _c.sent();
1760
- rewards = [];
1761
- if (!('claimable_reward(address,address)' in gaugeContract)) return [3 /*break*/, 6];
1762
- _i = 0, rewardTokens_5 = rewardTokens;
1763
- _c.label = 2;
1764
- case 2:
1765
- if (!(_i < rewardTokens_5.length)) return [3 /*break*/, 5];
1766
- rewardToken = rewardTokens_5[_i];
1767
- return [4 /*yield*/, gaugeContract.claimable_reward(address, rewardToken.token, curve_1.curve.constantOptions)];
1768
- case 3:
1769
- _amount = _c.sent();
1770
- rewards.push({
1771
- token: rewardToken.token,
1772
- symbol: rewardToken.symbol,
1773
- amount: ethers_1.ethers.utils.formatUnits(_amount, rewardToken.decimals),
1774
- });
1775
- _c.label = 4;
1776
- case 4:
1777
- _i++;
1778
- return [3 /*break*/, 2];
1779
- case 5: return [3 /*break*/, 9];
1780
- case 6:
1781
- if (!('claimable_reward(address)' in gaugeContract && rewardTokens.length > 0)) return [3 /*break*/, 9];
1782
- rewardToken = rewardTokens[0];
1783
- return [4 /*yield*/, gaugeContract.claimable_reward(address, curve_1.curve.constantOptions)];
1784
- case 7:
1785
- _totalAmount = _c.sent();
1786
- return [4 /*yield*/, gaugeContract.claimed_rewards_for(address, curve_1.curve.constantOptions)];
1787
- case 8:
1788
- _claimedAmount = _c.sent();
1789
- rewards.push({
1790
- token: rewardToken.token,
1791
- symbol: rewardToken.symbol,
1792
- amount: ethers_1.ethers.utils.formatUnits(_totalAmount.sub(_claimedAmount), rewardToken.decimals),
1793
- });
1794
- _c.label = 9;
1795
- case 9: return [2 /*return*/, rewards];
1796
- }
1797
- });
1798
- });
1799
- };
1800
- PoolTemplate.prototype.claimRewardsEstimateGas = function () {
1801
- return __awaiter(this, void 0, void 0, function () {
1802
- var gaugeContract;
1803
- return __generator(this, function (_c) {
1804
- switch (_c.label) {
1805
- case 0:
1806
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1807
- throw Error("claimRewards method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1808
- }
1809
- gaugeContract = curve_1.curve.contracts[this.gauge].contract;
1810
- if (!("claim_rewards()" in gaugeContract))
1811
- throw Error("".concat(this.name, " pool doesn't have such method"));
1812
- return [4 /*yield*/, gaugeContract.estimateGas.claim_rewards(curve_1.curve.constantOptions)];
1813
- case 1: return [2 /*return*/, (_c.sent()).toNumber()];
1814
- }
1815
- });
1816
- });
1817
- };
1818
- PoolTemplate.prototype.claimRewards = function () {
1819
- return __awaiter(this, void 0, void 0, function () {
1820
- var gaugeContract, gasLimit;
1821
- return __generator(this, function (_c) {
1822
- switch (_c.label) {
1823
- case 0:
1824
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1825
- throw Error("claimRewards method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1826
- }
1827
- gaugeContract = curve_1.curve.contracts[this.gauge].contract;
1828
- if (!("claim_rewards()" in gaugeContract))
1829
- throw Error("".concat(this.name, " pool doesn't have such method"));
1830
- return [4 /*yield*/, gaugeContract.estimateGas.claim_rewards(curve_1.curve.constantOptions)];
1831
- case 1:
1832
- gasLimit = (_c.sent()).mul(130).div(100);
1833
- return [4 /*yield*/, gaugeContract.claim_rewards(__assign(__assign({}, curve_1.curve.options), { gasLimit: gasLimit }))];
1834
- case 2: return [2 /*return*/, (_c.sent()).hash];
1835
- }
1023
+ async claimableRewards(address = "") {
1024
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1025
+ throw Error(`claimableRewards method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1026
+ }
1027
+ address = address || curve.signerAddress;
1028
+ if (!address)
1029
+ throw Error("Need to connect wallet or pass address into args");
1030
+ const gaugeContract = curve.contracts[this.gauge].contract;
1031
+ const rewardTokens = await this.rewardTokens();
1032
+ const rewards = [];
1033
+ if ('claimable_reward(address,address)' in gaugeContract) {
1034
+ for (const rewardToken of rewardTokens) {
1035
+ const _amount = await gaugeContract.claimable_reward(address, rewardToken.token, curve.constantOptions);
1036
+ rewards.push({
1037
+ token: rewardToken.token,
1038
+ symbol: rewardToken.symbol,
1039
+ amount: curve.formatUnits(_amount, rewardToken.decimals),
1040
+ });
1041
+ }
1042
+ }
1043
+ else if ('claimable_reward(address)' in gaugeContract && rewardTokens.length > 0) { // Synthetix Gauge
1044
+ const rewardToken = rewardTokens[0];
1045
+ const _totalAmount = await gaugeContract.claimable_reward(address, curve.constantOptions);
1046
+ const _claimedAmount = await gaugeContract.claimed_rewards_for(address, curve.constantOptions);
1047
+ rewards.push({
1048
+ token: rewardToken.token,
1049
+ symbol: rewardToken.symbol,
1050
+ amount: curve.formatUnits(_totalAmount.sub(_claimedAmount), rewardToken.decimals),
1836
1051
  });
1837
- });
1838
- };
1839
- // ---------------- DEPOSIT & STAKE ----------------
1840
- PoolTemplate.prototype.depositAndStakeExpected = function (amounts) {
1841
- return __awaiter(this, void 0, void 0, function () {
1842
- return __generator(this, function (_c) {
1843
- switch (_c.label) {
1844
- case 0:
1845
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1846
- throw Error("depositAndStakeExpected method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1847
- }
1848
- return [4 /*yield*/, this.depositExpected(amounts)];
1849
- case 1: return [2 /*return*/, _c.sent()];
1850
- }
1851
- });
1852
- });
1853
- };
1854
- PoolTemplate.prototype.depositAndStakeBonus = function (amounts) {
1855
- return __awaiter(this, void 0, void 0, function () {
1856
- return __generator(this, function (_c) {
1857
- switch (_c.label) {
1858
- case 0:
1859
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1860
- throw Error("depositAndStakeBonus method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1861
- }
1862
- return [4 /*yield*/, this.depositBonus(amounts)];
1863
- case 1: return [2 /*return*/, _c.sent()];
1864
- }
1865
- });
1866
- });
1867
- };
1868
- PoolTemplate.prototype.depositAndStakeIsApproved = function (amounts) {
1869
- return __awaiter(this, void 0, void 0, function () {
1870
- var coinsAllowance, gaugeContract, gaugeAllowance;
1871
- return __generator(this, function (_c) {
1872
- switch (_c.label) {
1873
- case 0:
1874
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1875
- throw Error("depositAndStakeIsApproved method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1876
- }
1877
- return [4 /*yield*/, (0, utils_1.hasAllowance)(this.underlyingCoinAddresses, amounts, curve_1.curve.signerAddress, curve_1.curve.constants.ALIASES.deposit_and_stake)];
1878
- case 1:
1879
- coinsAllowance = _c.sent();
1880
- gaugeContract = curve_1.curve.contracts[this.gauge].contract;
1881
- if (!Object.prototype.hasOwnProperty.call(gaugeContract, 'approved_to_deposit')) return [3 /*break*/, 3];
1882
- return [4 /*yield*/, gaugeContract.approved_to_deposit(curve_1.curve.constants.ALIASES.deposit_and_stake, curve_1.curve.signerAddress, curve_1.curve.constantOptions)];
1883
- case 2:
1884
- gaugeAllowance = _c.sent();
1885
- return [2 /*return*/, coinsAllowance && gaugeAllowance];
1886
- case 3: return [2 /*return*/, coinsAllowance];
1887
- }
1888
- });
1889
- });
1890
- };
1891
- PoolTemplate.prototype.depositAndStakeApproveEstimateGas = function (amounts) {
1892
- return __awaiter(this, void 0, void 0, function () {
1893
- var approveCoinsGas, gaugeContract, gaugeAllowance, approveGaugeGas;
1894
- return __generator(this, function (_c) {
1895
- switch (_c.label) {
1896
- case 0:
1897
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1898
- throw Error("depositAndStakeApprove method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1899
- }
1900
- return [4 /*yield*/, (0, utils_1.ensureAllowanceEstimateGas)(this.underlyingCoinAddresses, amounts, curve_1.curve.constants.ALIASES.deposit_and_stake)];
1901
- case 1:
1902
- approveCoinsGas = _c.sent();
1903
- gaugeContract = curve_1.curve.contracts[this.gauge].contract;
1904
- if (!Object.prototype.hasOwnProperty.call(gaugeContract, 'approved_to_deposit')) return [3 /*break*/, 4];
1905
- return [4 /*yield*/, gaugeContract.approved_to_deposit(curve_1.curve.constants.ALIASES.deposit_and_stake, curve_1.curve.signerAddress, curve_1.curve.constantOptions)];
1906
- case 2:
1907
- gaugeAllowance = _c.sent();
1908
- if (!!gaugeAllowance) return [3 /*break*/, 4];
1909
- return [4 /*yield*/, gaugeContract.estimateGas.set_approve_deposit(curve_1.curve.constants.ALIASES.deposit_and_stake, true, curve_1.curve.constantOptions)];
1910
- case 3:
1911
- approveGaugeGas = (_c.sent()).toNumber();
1912
- return [2 /*return*/, approveCoinsGas + approveGaugeGas];
1913
- case 4: return [2 /*return*/, approveCoinsGas];
1914
- }
1915
- });
1916
- });
1917
- };
1918
- PoolTemplate.prototype.depositAndStakeApprove = function (amounts) {
1919
- return __awaiter(this, void 0, void 0, function () {
1920
- var approveCoinsTx, gaugeContract, gaugeAllowance, gasLimit, approveGaugeTx;
1921
- return __generator(this, function (_c) {
1922
- switch (_c.label) {
1923
- case 0:
1924
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1925
- throw Error("depositAndStakeApprove method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1926
- }
1927
- return [4 /*yield*/, (0, utils_1.ensureAllowance)(this.underlyingCoinAddresses, amounts, curve_1.curve.constants.ALIASES.deposit_and_stake)];
1928
- case 1:
1929
- approveCoinsTx = _c.sent();
1930
- gaugeContract = curve_1.curve.contracts[this.gauge].contract;
1931
- if (!Object.prototype.hasOwnProperty.call(gaugeContract, 'approved_to_deposit')) return [3 /*break*/, 5];
1932
- return [4 /*yield*/, gaugeContract.approved_to_deposit(curve_1.curve.constants.ALIASES.deposit_and_stake, curve_1.curve.signerAddress, curve_1.curve.constantOptions)];
1933
- case 2:
1934
- gaugeAllowance = _c.sent();
1935
- if (!!gaugeAllowance) return [3 /*break*/, 5];
1936
- return [4 /*yield*/, gaugeContract.estimateGas.set_approve_deposit(curve_1.curve.constants.ALIASES.deposit_and_stake, true, curve_1.curve.constantOptions)];
1937
- case 3:
1938
- gasLimit = (_c.sent()).mul(130).div(100);
1939
- return [4 /*yield*/, gaugeContract.set_approve_deposit(curve_1.curve.constants.ALIASES.deposit_and_stake, true, __assign(__assign({}, curve_1.curve.options), { gasLimit: gasLimit }))];
1940
- case 4:
1941
- approveGaugeTx = (_c.sent()).hash;
1942
- return [2 /*return*/, __spreadArray(__spreadArray([], approveCoinsTx, true), [approveGaugeTx], false)];
1943
- case 5: return [2 /*return*/, approveCoinsTx];
1944
- }
1945
- });
1946
- });
1947
- };
1948
- PoolTemplate.prototype.depositAndStakeEstimateGas = function (amounts) {
1949
- return __awaiter(this, void 0, void 0, function () {
1950
- return __generator(this, function (_c) {
1951
- switch (_c.label) {
1952
- case 0:
1953
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1954
- throw Error("depositAndStake method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1955
- }
1956
- return [4 /*yield*/, this._depositAndStake(amounts, 1, true, true)];
1957
- case 1: return [2 /*return*/, _c.sent()];
1958
- }
1959
- });
1960
- });
1961
- };
1962
- PoolTemplate.prototype.depositAndStake = function (amounts, slippage) {
1963
- if (slippage === void 0) { slippage = 0.1; }
1964
- return __awaiter(this, void 0, void 0, function () {
1965
- return __generator(this, function (_c) {
1966
- switch (_c.label) {
1967
- case 0:
1968
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1969
- throw Error("depositAndStake method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1970
- }
1971
- return [4 /*yield*/, this._depositAndStake(amounts, slippage, true, false)];
1972
- case 1: return [2 /*return*/, _c.sent()];
1973
- }
1974
- });
1975
- });
1976
- };
1052
+ }
1053
+ return rewards;
1054
+ }
1055
+ async claimRewardsEstimateGas() {
1056
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1057
+ throw Error(`claimRewards method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1058
+ }
1059
+ const gaugeContract = curve.contracts[this.gauge].contract;
1060
+ if (!("claim_rewards()" in gaugeContract))
1061
+ throw Error(`${this.name} pool doesn't have such method`);
1062
+ return Number(await gaugeContract.claim_rewards.estimateGas(curve.constantOptions));
1063
+ }
1064
+ async claimRewards() {
1065
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1066
+ throw Error(`claimRewards method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1067
+ }
1068
+ const gaugeContract = curve.contracts[this.gauge].contract;
1069
+ if (!("claim_rewards()" in gaugeContract))
1070
+ throw Error(`${this.name} pool doesn't have such method`);
1071
+ const gasLimit = mulBy1_3(await gaugeContract.claim_rewards.estimateGas(curve.constantOptions));
1072
+ return (await gaugeContract.claim_rewards({ ...curve.options, gasLimit })).hash;
1073
+ }
1074
+ // ---------------- DEPOSIT & STAKE ----------------
1075
+ async depositAndStakeExpected(amounts) {
1076
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1077
+ throw Error(`depositAndStakeExpected method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1078
+ }
1079
+ return await this.depositExpected(amounts);
1080
+ }
1081
+ async depositAndStakeBonus(amounts) {
1082
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1083
+ throw Error(`depositAndStakeBonus method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1084
+ }
1085
+ return await this.depositBonus(amounts);
1086
+ }
1087
+ async depositAndStakeIsApproved(amounts) {
1088
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1089
+ throw Error(`depositAndStakeIsApproved method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1090
+ }
1091
+ const coinsAllowance = await hasAllowance(this.underlyingCoinAddresses, amounts, curve.signerAddress, curve.constants.ALIASES.deposit_and_stake);
1092
+ const gaugeContract = curve.contracts[this.gauge].contract;
1093
+ if ('approved_to_deposit' in gaugeContract) {
1094
+ const gaugeAllowance = await gaugeContract.approved_to_deposit(curve.constants.ALIASES.deposit_and_stake, curve.signerAddress, curve.constantOptions);
1095
+ return coinsAllowance && gaugeAllowance;
1096
+ }
1097
+ return coinsAllowance;
1098
+ }
1099
+ async depositAndStakeApproveEstimateGas(amounts) {
1100
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1101
+ throw Error(`depositAndStakeApprove method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1102
+ }
1103
+ const approveCoinsGas = await ensureAllowanceEstimateGas(this.underlyingCoinAddresses, amounts, curve.constants.ALIASES.deposit_and_stake);
1104
+ const gaugeContract = curve.contracts[this.gauge].contract;
1105
+ if ('approved_to_deposit' in gaugeContract) {
1106
+ const gaugeAllowance = await gaugeContract.approved_to_deposit(curve.constants.ALIASES.deposit_and_stake, curve.signerAddress, curve.constantOptions);
1107
+ if (!gaugeAllowance) {
1108
+ const approveGaugeGas = Number(await gaugeContract.set_approve_deposit.estimateGas(curve.constants.ALIASES.deposit_and_stake, true, curve.constantOptions));
1109
+ return approveCoinsGas + approveGaugeGas;
1110
+ }
1111
+ }
1112
+ return approveCoinsGas;
1113
+ }
1114
+ async depositAndStakeApprove(amounts) {
1115
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1116
+ throw Error(`depositAndStakeApprove method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1117
+ }
1118
+ const approveCoinsTx = await ensureAllowance(this.underlyingCoinAddresses, amounts, curve.constants.ALIASES.deposit_and_stake);
1119
+ const gaugeContract = curve.contracts[this.gauge].contract;
1120
+ if ('approved_to_deposit' in gaugeContract) {
1121
+ const gaugeAllowance = await gaugeContract.approved_to_deposit(curve.constants.ALIASES.deposit_and_stake, curve.signerAddress, curve.constantOptions);
1122
+ if (!gaugeAllowance) {
1123
+ const gasLimit = mulBy1_3(await gaugeContract.set_approve_deposit.estimateGas(curve.constants.ALIASES.deposit_and_stake, true, curve.constantOptions));
1124
+ const approveGaugeTx = (await gaugeContract.set_approve_deposit(curve.constants.ALIASES.deposit_and_stake, true, { ...curve.options, gasLimit })).hash;
1125
+ return [...approveCoinsTx, approveGaugeTx];
1126
+ }
1127
+ }
1128
+ return approveCoinsTx;
1129
+ }
1130
+ async depositAndStakeEstimateGas(amounts) {
1131
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1132
+ throw Error(`depositAndStake method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1133
+ }
1134
+ return await this._depositAndStake(amounts, 1, true, true);
1135
+ }
1136
+ async depositAndStake(amounts, slippage = 0.1) {
1137
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1138
+ throw Error(`depositAndStake method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1139
+ }
1140
+ return await this._depositAndStake(amounts, slippage, true, false);
1141
+ }
1977
1142
  // ---------------- DEPOSIT & STAKE WRAPPED ----------------
1978
- PoolTemplate.prototype.depositAndStakeWrappedExpected = function (amounts) {
1979
- return __awaiter(this, void 0, void 0, function () {
1980
- return __generator(this, function (_c) {
1981
- switch (_c.label) {
1982
- case 0:
1983
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
1984
- throw Error("depositAndStakeWrappedExpected method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1985
- }
1986
- if (this.isPlain || this.isFake)
1987
- throw Error("depositAndStakeWrappedExpected method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
1988
- return [4 /*yield*/, this.depositWrappedExpected(amounts)];
1989
- case 1: return [2 /*return*/, _c.sent()];
1990
- }
1991
- });
1992
- });
1993
- };
1994
- PoolTemplate.prototype.depositAndStakeWrappedBonus = function (amounts) {
1995
- return __awaiter(this, void 0, void 0, function () {
1996
- return __generator(this, function (_c) {
1997
- switch (_c.label) {
1998
- case 0:
1999
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
2000
- throw Error("depositAndStakeWrappedBonus method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
2001
- }
2002
- if (this.isPlain || this.isFake)
2003
- throw Error("depositAndStakeWrappedBonus method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2004
- return [4 /*yield*/, this.depositWrappedBonus(amounts)];
2005
- case 1: return [2 /*return*/, _c.sent()];
2006
- }
2007
- });
2008
- });
2009
- };
2010
- PoolTemplate.prototype.depositAndStakeWrappedIsApproved = function (amounts) {
2011
- return __awaiter(this, void 0, void 0, function () {
2012
- var coinsAllowance, gaugeContract, gaugeAllowance;
2013
- return __generator(this, function (_c) {
2014
- switch (_c.label) {
2015
- case 0:
2016
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
2017
- throw Error("depositAndStakeWrappedIsApproved method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
2018
- }
2019
- if (this.isPlain || this.isFake)
2020
- throw Error("depositAndStakeWrappedIsApproved method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2021
- return [4 /*yield*/, (0, utils_1.hasAllowance)(this.wrappedCoinAddresses, amounts, curve_1.curve.signerAddress, curve_1.curve.constants.ALIASES.deposit_and_stake)];
2022
- case 1:
2023
- coinsAllowance = _c.sent();
2024
- gaugeContract = curve_1.curve.contracts[this.gauge].contract;
2025
- if (!Object.prototype.hasOwnProperty.call(gaugeContract, 'approved_to_deposit')) return [3 /*break*/, 3];
2026
- return [4 /*yield*/, gaugeContract.approved_to_deposit(curve_1.curve.constants.ALIASES.deposit_and_stake, curve_1.curve.signerAddress, curve_1.curve.constantOptions)];
2027
- case 2:
2028
- gaugeAllowance = _c.sent();
2029
- return [2 /*return*/, coinsAllowance && gaugeAllowance];
2030
- case 3: return [2 /*return*/, coinsAllowance];
2031
- }
2032
- });
2033
- });
2034
- };
2035
- PoolTemplate.prototype.depositAndStakeWrappedApproveEstimateGas = function (amounts) {
2036
- return __awaiter(this, void 0, void 0, function () {
2037
- var approveCoinsGas, gaugeContract, gaugeAllowance, approveGaugeGas;
2038
- return __generator(this, function (_c) {
2039
- switch (_c.label) {
2040
- case 0:
2041
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
2042
- throw Error("depositAndStakeWrappedApprove method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
2043
- }
2044
- if (this.isPlain || this.isFake)
2045
- throw Error("depositAndStakeWrappedApprove method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2046
- return [4 /*yield*/, (0, utils_1.ensureAllowanceEstimateGas)(this.wrappedCoinAddresses, amounts, curve_1.curve.constants.ALIASES.deposit_and_stake)];
2047
- case 1:
2048
- approveCoinsGas = _c.sent();
2049
- gaugeContract = curve_1.curve.contracts[this.gauge].contract;
2050
- if (!Object.prototype.hasOwnProperty.call(gaugeContract, 'approved_to_deposit')) return [3 /*break*/, 4];
2051
- return [4 /*yield*/, gaugeContract.approved_to_deposit(curve_1.curve.constants.ALIASES.deposit_and_stake, curve_1.curve.signerAddress, curve_1.curve.constantOptions)];
2052
- case 2:
2053
- gaugeAllowance = _c.sent();
2054
- if (!!gaugeAllowance) return [3 /*break*/, 4];
2055
- return [4 /*yield*/, gaugeContract.estimateGas.set_approve_deposit(curve_1.curve.constants.ALIASES.deposit_and_stake, true, curve_1.curve.constantOptions)];
2056
- case 3:
2057
- approveGaugeGas = (_c.sent()).toNumber();
2058
- return [2 /*return*/, approveCoinsGas + approveGaugeGas];
2059
- case 4: return [2 /*return*/, approveCoinsGas];
2060
- }
2061
- });
2062
- });
2063
- };
2064
- PoolTemplate.prototype.depositAndStakeWrappedApprove = function (amounts) {
2065
- return __awaiter(this, void 0, void 0, function () {
2066
- var approveCoinsTx, gaugeContract, gaugeAllowance, gasLimit, approveGaugeTx;
2067
- return __generator(this, function (_c) {
2068
- switch (_c.label) {
2069
- case 0:
2070
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
2071
- throw Error("depositAndStakeWrappedApprove method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
2072
- }
2073
- if (this.isPlain || this.isFake)
2074
- throw Error("depositAndStakeWrappedApprove method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2075
- return [4 /*yield*/, (0, utils_1.ensureAllowance)(this.wrappedCoinAddresses, amounts, curve_1.curve.constants.ALIASES.deposit_and_stake)];
2076
- case 1:
2077
- approveCoinsTx = _c.sent();
2078
- gaugeContract = curve_1.curve.contracts[this.gauge].contract;
2079
- if (!Object.prototype.hasOwnProperty.call(gaugeContract, 'approved_to_deposit')) return [3 /*break*/, 5];
2080
- return [4 /*yield*/, gaugeContract.approved_to_deposit(curve_1.curve.constants.ALIASES.deposit_and_stake, curve_1.curve.signerAddress, curve_1.curve.constantOptions)];
2081
- case 2:
2082
- gaugeAllowance = _c.sent();
2083
- if (!!gaugeAllowance) return [3 /*break*/, 5];
2084
- return [4 /*yield*/, gaugeContract.estimateGas.set_approve_deposit(curve_1.curve.constants.ALIASES.deposit_and_stake, true, curve_1.curve.constantOptions)];
2085
- case 3:
2086
- gasLimit = (_c.sent()).mul(130).div(100);
2087
- return [4 /*yield*/, gaugeContract.set_approve_deposit(curve_1.curve.constants.ALIASES.deposit_and_stake, true, __assign(__assign({}, curve_1.curve.options), { gasLimit: gasLimit }))];
2088
- case 4:
2089
- approveGaugeTx = (_c.sent()).hash;
2090
- return [2 /*return*/, __spreadArray(__spreadArray([], approveCoinsTx, true), [approveGaugeTx], false)];
2091
- case 5: return [2 /*return*/, approveCoinsTx];
2092
- }
2093
- });
2094
- });
2095
- };
2096
- PoolTemplate.prototype.depositAndStakeWrappedEstimateGas = function (amounts) {
2097
- return __awaiter(this, void 0, void 0, function () {
2098
- return __generator(this, function (_c) {
2099
- switch (_c.label) {
2100
- case 0:
2101
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
2102
- throw Error("depositAndStakeWrapped method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
2103
- }
2104
- if (this.isPlain || this.isFake)
2105
- throw Error("depositAndStakeWrapped method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2106
- return [4 /*yield*/, this._depositAndStake(amounts, 1, false, true)];
2107
- case 1: return [2 /*return*/, _c.sent()];
2108
- }
2109
- });
2110
- });
2111
- };
2112
- PoolTemplate.prototype.depositAndStakeWrapped = function (amounts, slippage) {
2113
- if (slippage === void 0) { slippage = 0.1; }
2114
- return __awaiter(this, void 0, void 0, function () {
2115
- return __generator(this, function (_c) {
2116
- switch (_c.label) {
2117
- case 0:
2118
- if (this.gauge === ethers_1.ethers.constants.AddressZero) {
2119
- throw Error("depositAndStakeWrapped method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
2120
- }
2121
- if (this.isPlain || this.isFake)
2122
- throw Error("depositAndStakeWrapped method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2123
- return [4 /*yield*/, this._depositAndStake(amounts, slippage, false, false)];
2124
- case 1: return [2 /*return*/, _c.sent()];
2125
- }
2126
- });
2127
- });
2128
- };
2129
- PoolTemplate.prototype._depositAndStake = function (amounts, slippage, isUnderlying, estimateGas) {
2130
- return __awaiter(this, void 0, void 0, function () {
2131
- var coinAddresses, coins, decimals, depositAddress, balances, _c, _d, _e, _f, _g, i, allowance, _h, _amounts, contract, useUnderlying, _expectedLpTokenAmount, _j, _k, _l, _m, _o, minAmountBN, _minMintAmount, ethIndex, value, maxCoins, i, _gas, gasLimit;
2132
- return __generator(this, function (_q) {
2133
- switch (_q.label) {
2134
- case 0:
2135
- coinAddresses = isUnderlying ? __spreadArray([], this.underlyingCoinAddresses, true) : __spreadArray([], this.wrappedCoinAddresses, true);
2136
- coins = isUnderlying ? this.underlyingCoins : this.wrappedCoinAddresses;
2137
- decimals = isUnderlying ? this.underlyingDecimals : this.wrappedDecimals;
2138
- depositAddress = isUnderlying ? this.zap || this.address : this.address;
2139
- if (amounts.length !== coinAddresses.length) {
2140
- throw Error("".concat(this.name, " pool has ").concat(coinAddresses.length, " coins (amounts provided for ").concat(amounts.length, ")"));
2141
- }
2142
- if (!isUnderlying) return [3 /*break*/, 2];
2143
- _e = (_d = Object).values;
2144
- return [4 /*yield*/, this.walletUnderlyingCoinBalances()];
2145
- case 1:
2146
- _c = _e.apply(_d, [_q.sent()]);
2147
- return [3 /*break*/, 4];
2148
- case 2:
2149
- _g = (_f = Object).values;
2150
- return [4 /*yield*/, this.walletWrappedCoinBalances()];
2151
- case 3:
2152
- _c = _g.apply(_f, [_q.sent()]);
2153
- _q.label = 4;
2154
- case 4:
2155
- balances = _c;
2156
- for (i = 0; i < balances.length; i++) {
2157
- if (Number(balances[i]) < Number(amounts[i])) {
2158
- throw Error("Not enough ".concat(coins[i], ". Actual: ").concat(balances[i], ", required: ").concat(amounts[i]));
2159
- }
2160
- }
2161
- if (!isUnderlying) return [3 /*break*/, 6];
2162
- return [4 /*yield*/, this.depositAndStakeIsApproved(amounts)];
2163
- case 5:
2164
- _h = _q.sent();
2165
- return [3 /*break*/, 8];
2166
- case 6: return [4 /*yield*/, this.depositAndStakeWrappedIsApproved(amounts)];
2167
- case 7:
2168
- _h = _q.sent();
2169
- _q.label = 8;
2170
- case 8:
2171
- allowance = _h;
2172
- if (estimateGas && !allowance) {
2173
- throw Error("Token allowance is needed to estimate gas");
2174
- }
2175
- if (!!estimateGas) return [3 /*break*/, 12];
2176
- if (!isUnderlying) return [3 /*break*/, 10];
2177
- return [4 /*yield*/, this.depositAndStakeApprove(amounts)];
2178
- case 9:
2179
- _q.sent();
2180
- return [3 /*break*/, 12];
2181
- case 10: return [4 /*yield*/, this.depositAndStakeWrappedApprove(amounts)];
2182
- case 11:
2183
- _q.sent();
2184
- _q.label = 12;
2185
- case 12:
2186
- _amounts = amounts.map(function (amount, i) { return (0, utils_1.parseUnits)(amount, decimals[i]); });
2187
- contract = curve_1.curve.contracts[curve_1.curve.constants.ALIASES.deposit_and_stake].contract;
2188
- useUnderlying = isUnderlying && (this.isLending || (this.isCrypto && !this.isPlain)) && (!this.zap || this.id == 'avaxcrypto');
2189
- if (!isUnderlying) return [3 /*break*/, 14];
2190
- _l = (_k = ethers_1.ethers.utils).parseUnits;
2191
- return [4 /*yield*/, this.depositAndStakeExpected(amounts)];
2192
- case 13:
2193
- _j = _l.apply(_k, [_q.sent()]);
2194
- return [3 /*break*/, 16];
2195
- case 14:
2196
- _o = (_m = ethers_1.ethers.utils).parseUnits;
2197
- return [4 /*yield*/, this.depositAndStakeWrappedExpected(amounts)];
2198
- case 15:
2199
- _j = _o.apply(_m, [_q.sent()]);
2200
- _q.label = 16;
2201
- case 16:
2202
- _expectedLpTokenAmount = _j;
2203
- minAmountBN = (0, utils_1.toBN)(_expectedLpTokenAmount).times(100 - slippage).div(100);
2204
- _minMintAmount = (0, utils_1.fromBN)(minAmountBN);
2205
- ethIndex = (0, utils_1.getEthIndex)(coinAddresses);
2206
- value = _amounts[ethIndex] || ethers_1.ethers.BigNumber.from(0);
2207
- maxCoins = curve_1.curve.chainId === 137 ? 6 : 5;
2208
- for (i = 0; i < maxCoins; i++) {
2209
- coinAddresses[i] = coinAddresses[i] || ethers_1.ethers.constants.AddressZero;
2210
- _amounts[i] = _amounts[i] || ethers_1.ethers.BigNumber.from(0);
2211
- }
2212
- return [4 /*yield*/, contract.estimateGas.deposit_and_stake(depositAddress, this.lpToken, this.gauge, coins.length, coinAddresses, _amounts, _minMintAmount, useUnderlying, this.isMetaFactory && isUnderlying ? this.address : ethers_1.ethers.constants.AddressZero, __assign(__assign({}, curve_1.curve.constantOptions), { value: value }))];
2213
- case 17:
2214
- _gas = (_q.sent());
2215
- if (estimateGas)
2216
- return [2 /*return*/, _gas.toNumber()];
2217
- return [4 /*yield*/, curve_1.curve.updateFeeData()];
2218
- case 18:
2219
- _q.sent();
2220
- gasLimit = _gas.mul(200).div(100);
2221
- return [4 /*yield*/, contract.deposit_and_stake(depositAddress, this.lpToken, this.gauge, coins.length, coinAddresses, _amounts, _minMintAmount, useUnderlying, this.isMetaFactory && isUnderlying ? this.address : ethers_1.ethers.constants.AddressZero, __assign(__assign({}, curve_1.curve.options), { gasLimit: gasLimit, value: value }))];
2222
- case 19: return [2 /*return*/, (_q.sent()).hash];
2223
- }
2224
- });
2225
- });
2226
- };
1143
+ async depositAndStakeWrappedExpected(amounts) {
1144
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1145
+ throw Error(`depositAndStakeWrappedExpected method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1146
+ }
1147
+ if (this.isPlain || this.isFake)
1148
+ throw Error(`depositAndStakeWrappedExpected method doesn't exist for pool ${this.name} (id: ${this.name})`);
1149
+ return await this.depositWrappedExpected(amounts);
1150
+ }
1151
+ async depositAndStakeWrappedBonus(amounts) {
1152
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1153
+ throw Error(`depositAndStakeWrappedBonus method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1154
+ }
1155
+ if (this.isPlain || this.isFake)
1156
+ throw Error(`depositAndStakeWrappedBonus method doesn't exist for pool ${this.name} (id: ${this.name})`);
1157
+ return await this.depositWrappedBonus(amounts);
1158
+ }
1159
+ async depositAndStakeWrappedIsApproved(amounts) {
1160
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1161
+ throw Error(`depositAndStakeWrappedIsApproved method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1162
+ }
1163
+ if (this.isPlain || this.isFake)
1164
+ throw Error(`depositAndStakeWrappedIsApproved method doesn't exist for pool ${this.name} (id: ${this.name})`);
1165
+ const coinsAllowance = await hasAllowance(this.wrappedCoinAddresses, amounts, curve.signerAddress, curve.constants.ALIASES.deposit_and_stake);
1166
+ const gaugeContract = curve.contracts[this.gauge].contract;
1167
+ if ('approved_to_deposit' in gaugeContract) {
1168
+ const gaugeAllowance = await gaugeContract.approved_to_deposit(curve.constants.ALIASES.deposit_and_stake, curve.signerAddress, curve.constantOptions);
1169
+ return coinsAllowance && gaugeAllowance;
1170
+ }
1171
+ return coinsAllowance;
1172
+ }
1173
+ async depositAndStakeWrappedApproveEstimateGas(amounts) {
1174
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1175
+ throw Error(`depositAndStakeWrappedApprove method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1176
+ }
1177
+ if (this.isPlain || this.isFake)
1178
+ throw Error(`depositAndStakeWrappedApprove method doesn't exist for pool ${this.name} (id: ${this.name})`);
1179
+ const approveCoinsGas = await ensureAllowanceEstimateGas(this.wrappedCoinAddresses, amounts, curve.constants.ALIASES.deposit_and_stake);
1180
+ const gaugeContract = curve.contracts[this.gauge].contract;
1181
+ if ('approved_to_deposit' in gaugeContract) {
1182
+ const gaugeAllowance = await gaugeContract.approved_to_deposit(curve.constants.ALIASES.deposit_and_stake, curve.signerAddress, curve.constantOptions);
1183
+ if (!gaugeAllowance) {
1184
+ const approveGaugeGas = Number(await gaugeContract.set_approve_deposit.estimateGas(curve.constants.ALIASES.deposit_and_stake, true, curve.constantOptions));
1185
+ return approveCoinsGas + approveGaugeGas;
1186
+ }
1187
+ }
1188
+ return approveCoinsGas;
1189
+ }
1190
+ async depositAndStakeWrappedApprove(amounts) {
1191
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1192
+ throw Error(`depositAndStakeWrappedApprove method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1193
+ }
1194
+ if (this.isPlain || this.isFake)
1195
+ throw Error(`depositAndStakeWrappedApprove method doesn't exist for pool ${this.name} (id: ${this.name})`);
1196
+ const approveCoinsTx = await ensureAllowance(this.wrappedCoinAddresses, amounts, curve.constants.ALIASES.deposit_and_stake);
1197
+ const gaugeContract = curve.contracts[this.gauge].contract;
1198
+ if ('approved_to_deposit' in gaugeContract) {
1199
+ const gaugeAllowance = await gaugeContract.approved_to_deposit(curve.constants.ALIASES.deposit_and_stake, curve.signerAddress, curve.constantOptions);
1200
+ if (!gaugeAllowance) {
1201
+ const gasLimit = mulBy1_3(await gaugeContract.set_approve_deposit.estimateGas(curve.constants.ALIASES.deposit_and_stake, true, curve.constantOptions));
1202
+ const approveGaugeTx = (await gaugeContract.set_approve_deposit(curve.constants.ALIASES.deposit_and_stake, true, { ...curve.options, gasLimit })).hash;
1203
+ return [...approveCoinsTx, approveGaugeTx];
1204
+ }
1205
+ }
1206
+ return approveCoinsTx;
1207
+ }
1208
+ async depositAndStakeWrappedEstimateGas(amounts) {
1209
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1210
+ throw Error(`depositAndStakeWrapped method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1211
+ }
1212
+ if (this.isPlain || this.isFake)
1213
+ throw Error(`depositAndStakeWrapped method doesn't exist for pool ${this.name} (id: ${this.name})`);
1214
+ return await this._depositAndStake(amounts, 1, false, true);
1215
+ }
1216
+ async depositAndStakeWrapped(amounts, slippage = 0.1) {
1217
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1218
+ throw Error(`depositAndStakeWrapped method doesn't exist for pool ${this.name} (id: ${this.name}). There is no gauge`);
1219
+ }
1220
+ if (this.isPlain || this.isFake)
1221
+ throw Error(`depositAndStakeWrapped method doesn't exist for pool ${this.name} (id: ${this.name})`);
1222
+ return await this._depositAndStake(amounts, slippage, false, false);
1223
+ }
1224
+ async _depositAndStake(amounts, slippage, isUnderlying, estimateGas) {
1225
+ const coinAddresses = isUnderlying ? [...this.underlyingCoinAddresses] : [...this.wrappedCoinAddresses];
1226
+ const coins = isUnderlying ? this.underlyingCoins : this.wrappedCoinAddresses;
1227
+ const decimals = isUnderlying ? this.underlyingDecimals : this.wrappedDecimals;
1228
+ const depositAddress = isUnderlying ? this.zap || this.address : this.address;
1229
+ if (amounts.length !== coinAddresses.length) {
1230
+ throw Error(`${this.name} pool has ${coinAddresses.length} coins (amounts provided for ${amounts.length})`);
1231
+ }
1232
+ const balances = isUnderlying ? Object.values(await this.walletUnderlyingCoinBalances()) : Object.values(await this.walletWrappedCoinBalances());
1233
+ for (let i = 0; i < balances.length; i++) {
1234
+ if (Number(balances[i]) < Number(amounts[i])) {
1235
+ throw Error(`Not enough ${coins[i]}. Actual: ${balances[i]}, required: ${amounts[i]}`);
1236
+ }
1237
+ }
1238
+ const allowance = isUnderlying ? await this.depositAndStakeIsApproved(amounts) : await this.depositAndStakeWrappedIsApproved(amounts);
1239
+ if (estimateGas && !allowance) {
1240
+ throw Error("Token allowance is needed to estimate gas");
1241
+ }
1242
+ if (!estimateGas) {
1243
+ if (isUnderlying) {
1244
+ await this.depositAndStakeApprove(amounts);
1245
+ }
1246
+ else {
1247
+ await this.depositAndStakeWrappedApprove(amounts);
1248
+ }
1249
+ }
1250
+ const _amounts = amounts.map((amount, i) => parseUnits(amount, decimals[i]));
1251
+ const contract = curve.contracts[curve.constants.ALIASES.deposit_and_stake].contract;
1252
+ const useUnderlying = isUnderlying && (this.isLending || (this.isCrypto && !this.isPlain)) && (!this.zap || this.id == 'avaxcrypto');
1253
+ const _expectedLpTokenAmount = isUnderlying ?
1254
+ curve.parseUnits(await this.depositAndStakeExpected(amounts)) :
1255
+ curve.parseUnits(await this.depositAndStakeWrappedExpected(amounts));
1256
+ const minAmountBN = toBN(_expectedLpTokenAmount).times(100 - slippage).div(100);
1257
+ const _minMintAmount = fromBN(minAmountBN);
1258
+ const ethIndex = getEthIndex(coinAddresses);
1259
+ const value = _amounts[ethIndex] || 0n;
1260
+ const maxCoins = curve.chainId === 137 ? 6 : 5;
1261
+ for (let i = 0; i < maxCoins; i++) {
1262
+ coinAddresses[i] = coinAddresses[i] || curve.constants.ZERO_ADDRESS;
1263
+ _amounts[i] = _amounts[i] || 0n;
1264
+ }
1265
+ const _gas = (await contract.deposit_and_stake.estimateGas(depositAddress, this.lpToken, this.gauge, coins.length, coinAddresses, _amounts, _minMintAmount, useUnderlying, this.isMetaFactory && isUnderlying ? this.address : curve.constants.ZERO_ADDRESS, { ...curve.constantOptions, value }));
1266
+ if (estimateGas)
1267
+ return Number(_gas);
1268
+ await curve.updateFeeData();
1269
+ const gasLimit = _gas * 200n / 100n;
1270
+ return (await contract.deposit_and_stake(depositAddress, this.lpToken, this.gauge, coins.length, coinAddresses, _amounts, _minMintAmount, useUnderlying, this.isMetaFactory && isUnderlying ? this.address : curve.constants.ZERO_ADDRESS, { ...curve.options, gasLimit, value })).hash;
1271
+ }
2227
1272
  // ---------------- WITHDRAW ----------------
2228
1273
  // OVERRIDE
2229
- PoolTemplate.prototype.withdrawExpected = function (lpTokenAmount) {
2230
- return __awaiter(this, void 0, void 0, function () {
2231
- return __generator(this, function (_c) {
2232
- throw Error("withdrawExpected method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2233
- });
2234
- });
2235
- };
2236
- PoolTemplate.prototype.withdrawIsApproved = function (lpTokenAmount) {
2237
- return __awaiter(this, void 0, void 0, function () {
2238
- return __generator(this, function (_c) {
2239
- switch (_c.label) {
2240
- case 0:
2241
- if (!this.zap)
2242
- return [2 /*return*/, true];
2243
- return [4 /*yield*/, (0, utils_1.hasAllowance)([this.lpToken], [lpTokenAmount], curve_1.curve.signerAddress, this.zap)];
2244
- case 1: return [2 /*return*/, _c.sent()];
2245
- }
2246
- });
2247
- });
2248
- };
2249
- PoolTemplate.prototype.withdrawApproveEstimateGas = function (lpTokenAmount) {
2250
- return __awaiter(this, void 0, void 0, function () {
2251
- return __generator(this, function (_c) {
2252
- switch (_c.label) {
2253
- case 0:
2254
- if (!this.zap)
2255
- return [2 /*return*/, 0];
2256
- return [4 /*yield*/, (0, utils_1.ensureAllowanceEstimateGas)([this.lpToken], [lpTokenAmount], this.zap)];
2257
- case 1: return [2 /*return*/, _c.sent()];
2258
- }
2259
- });
2260
- });
2261
- };
2262
- PoolTemplate.prototype.withdrawApprove = function (lpTokenAmount) {
2263
- return __awaiter(this, void 0, void 0, function () {
2264
- return __generator(this, function (_c) {
2265
- switch (_c.label) {
2266
- case 0:
2267
- if (!this.zap)
2268
- return [2 /*return*/, []];
2269
- return [4 /*yield*/, (0, utils_1.ensureAllowance)([this.lpToken], [lpTokenAmount], this.zap)];
2270
- case 1: return [2 /*return*/, _c.sent()];
2271
- }
2272
- });
2273
- });
2274
- };
1274
+ async withdrawExpected(lpTokenAmount) {
1275
+ throw Error(`withdrawExpected method doesn't exist for pool ${this.name} (id: ${this.name})`);
1276
+ }
1277
+ async withdrawIsApproved(lpTokenAmount) {
1278
+ if (!this.zap)
1279
+ return true;
1280
+ return await hasAllowance([this.lpToken], [lpTokenAmount], curve.signerAddress, this.zap);
1281
+ }
1282
+ async withdrawApproveEstimateGas(lpTokenAmount) {
1283
+ if (!this.zap)
1284
+ return 0;
1285
+ return await ensureAllowanceEstimateGas([this.lpToken], [lpTokenAmount], this.zap);
1286
+ }
1287
+ async withdrawApprove(lpTokenAmount) {
1288
+ if (!this.zap)
1289
+ return [];
1290
+ return await ensureAllowance([this.lpToken], [lpTokenAmount], this.zap);
1291
+ }
2275
1292
  // OVERRIDE
2276
- PoolTemplate.prototype.withdrawEstimateGas = function (lpTokenAmount) {
2277
- return __awaiter(this, void 0, void 0, function () {
2278
- return __generator(this, function (_c) {
2279
- throw Error("withdraw method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2280
- });
2281
- });
2282
- };
1293
+ async withdrawEstimateGas(lpTokenAmount) {
1294
+ throw Error(`withdraw method doesn't exist for pool ${this.name} (id: ${this.name})`);
1295
+ }
2283
1296
  // OVERRIDE
2284
- PoolTemplate.prototype.withdraw = function (lpTokenAmount, slippage) {
2285
- if (slippage === void 0) { slippage = 0.5; }
2286
- return __awaiter(this, void 0, void 0, function () {
2287
- return __generator(this, function (_c) {
2288
- throw Error("withdraw method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2289
- });
2290
- });
2291
- };
1297
+ async withdraw(lpTokenAmount, slippage = 0.5) {
1298
+ throw Error(`withdraw method doesn't exist for pool ${this.name} (id: ${this.name})`);
1299
+ }
2292
1300
  // ---------------- WITHDRAW WRAPPED ----------------
2293
1301
  // OVERRIDE
2294
- PoolTemplate.prototype.withdrawWrappedExpected = function (lpTokenAmount) {
2295
- return __awaiter(this, void 0, void 0, function () {
2296
- return __generator(this, function (_c) {
2297
- throw Error("withdrawWrappedExpected method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2298
- });
2299
- });
2300
- };
1302
+ async withdrawWrappedExpected(lpTokenAmount) {
1303
+ throw Error(`withdrawWrappedExpected method doesn't exist for pool ${this.name} (id: ${this.name})`);
1304
+ }
2301
1305
  // OVERRIDE
2302
- PoolTemplate.prototype.withdrawWrappedEstimateGas = function (lpTokenAmount) {
2303
- return __awaiter(this, void 0, void 0, function () {
2304
- return __generator(this, function (_c) {
2305
- throw Error("withdrawWrapped method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2306
- });
2307
- });
2308
- };
1306
+ async withdrawWrappedEstimateGas(lpTokenAmount) {
1307
+ throw Error(`withdrawWrapped method doesn't exist for pool ${this.name} (id: ${this.name})`);
1308
+ }
2309
1309
  // OVERRIDE
2310
- PoolTemplate.prototype.withdrawWrapped = function (lpTokenAmount, slippage) {
2311
- if (slippage === void 0) { slippage = 0.5; }
2312
- return __awaiter(this, void 0, void 0, function () {
2313
- return __generator(this, function (_c) {
2314
- throw Error("withdrawWrapped method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2315
- });
2316
- });
2317
- };
1310
+ async withdrawWrapped(lpTokenAmount, slippage = 0.5) {
1311
+ throw Error(`withdrawWrapped method doesn't exist for pool ${this.name} (id: ${this.name})`);
1312
+ }
2318
1313
  // ---------------- WITHDRAW IMBALANCE ----------------
2319
- PoolTemplate.prototype.withdrawImbalanceExpected = function (amounts) {
2320
- return __awaiter(this, void 0, void 0, function () {
2321
- return __generator(this, function (_c) {
2322
- switch (_c.label) {
2323
- case 0:
2324
- if (this.isCrypto)
2325
- throw Error("withdrawImbalanceExpected method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2326
- return [4 /*yield*/, this.calcLpTokenAmount(amounts, false)];
2327
- case 1: return [2 /*return*/, _c.sent()];
2328
- }
2329
- });
2330
- });
2331
- };
2332
- PoolTemplate.prototype.withdrawImbalanceBonus = function (amounts) {
2333
- return __awaiter(this, void 0, void 0, function () {
2334
- var prices, _c, value, lpTokenAmount, balancedAmounts, balancedValue;
2335
- return __generator(this, function (_d) {
2336
- switch (_d.label) {
2337
- case 0:
2338
- if (!(this.isCrypto || this.id === 'wsteth')) return [3 /*break*/, 2];
2339
- return [4 /*yield*/, this._underlyingPrices()];
2340
- case 1:
2341
- _c = _d.sent();
2342
- return [3 /*break*/, 3];
2343
- case 2:
2344
- _c = this.underlyingCoins.map(function () { return 1; });
2345
- _d.label = 3;
2346
- case 3:
2347
- prices = _c;
2348
- value = amounts.map(utils_1.checkNumber).map(Number).reduce(function (s, a, i) { return s + (a * prices[i]); }, 0);
2349
- return [4 /*yield*/, this.withdrawImbalanceExpected(amounts)];
2350
- case 4:
2351
- lpTokenAmount = _d.sent();
2352
- return [4 /*yield*/, this.withdrawExpected(lpTokenAmount)];
2353
- case 5:
2354
- balancedAmounts = _d.sent();
2355
- balancedValue = balancedAmounts.map(Number).reduce(function (s, a, i) { return s + (a * prices[i]); }, 0);
2356
- return [2 /*return*/, String((value - balancedValue) / balancedValue * 100)];
2357
- }
2358
- });
2359
- });
2360
- };
2361
- PoolTemplate.prototype.withdrawImbalanceIsApproved = function (amounts) {
2362
- return __awaiter(this, void 0, void 0, function () {
2363
- var _amounts, _maxBurnAmount;
2364
- var _this = this;
2365
- return __generator(this, function (_c) {
2366
- switch (_c.label) {
2367
- case 0:
2368
- if (this.isCrypto)
2369
- throw Error("withdrawImbalanceIsApproved method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2370
- if (!this.zap) return [3 /*break*/, 3];
2371
- _amounts = amounts.map(function (amount, i) { return (0, utils_1.parseUnits)(amount, _this.underlyingDecimals[i]); });
2372
- return [4 /*yield*/, this._calcLpTokenAmount(_amounts, false)];
2373
- case 1:
2374
- _maxBurnAmount = (_c.sent()).mul(101).div(100);
2375
- return [4 /*yield*/, (0, utils_1.hasAllowance)([this.lpToken], [ethers_1.ethers.utils.formatUnits(_maxBurnAmount, 18)], curve_1.curve.signerAddress, this.zap)];
2376
- case 2: return [2 /*return*/, _c.sent()];
2377
- case 3: return [2 /*return*/, true];
2378
- }
2379
- });
2380
- });
2381
- };
2382
- PoolTemplate.prototype.withdrawImbalanceApproveEstimateGas = function (amounts) {
2383
- return __awaiter(this, void 0, void 0, function () {
2384
- var _amounts, _maxBurnAmount;
2385
- var _this = this;
2386
- return __generator(this, function (_c) {
2387
- switch (_c.label) {
2388
- case 0:
2389
- if (this.isCrypto)
2390
- throw Error("withdrawImbalanceApprove method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2391
- if (!this.zap) return [3 /*break*/, 3];
2392
- _amounts = amounts.map(function (amount, i) { return (0, utils_1.parseUnits)(amount, _this.underlyingDecimals[i]); });
2393
- return [4 /*yield*/, this._calcLpTokenAmount(_amounts, false)];
2394
- case 1:
2395
- _maxBurnAmount = (_c.sent()).mul(101).div(100);
2396
- return [4 /*yield*/, (0, utils_1.ensureAllowanceEstimateGas)([this.lpToken], [ethers_1.ethers.utils.formatUnits(_maxBurnAmount, 18)], this.zap)];
2397
- case 2: return [2 /*return*/, _c.sent()];
2398
- case 3: return [2 /*return*/, 0];
2399
- }
2400
- });
2401
- });
2402
- };
2403
- PoolTemplate.prototype.withdrawImbalanceApprove = function (amounts) {
2404
- return __awaiter(this, void 0, void 0, function () {
2405
- var _amounts, _maxBurnAmount;
2406
- var _this = this;
2407
- return __generator(this, function (_c) {
2408
- switch (_c.label) {
2409
- case 0:
2410
- if (this.isCrypto)
2411
- throw Error("withdrawImbalanceApprove method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2412
- if (!this.zap) return [3 /*break*/, 3];
2413
- _amounts = amounts.map(function (amount, i) { return (0, utils_1.parseUnits)(amount, _this.underlyingDecimals[i]); });
2414
- return [4 /*yield*/, this._calcLpTokenAmount(_amounts, false)];
2415
- case 1:
2416
- _maxBurnAmount = (_c.sent()).mul(101).div(100);
2417
- return [4 /*yield*/, (0, utils_1.ensureAllowance)([this.lpToken], [ethers_1.ethers.utils.formatUnits(_maxBurnAmount, 18)], this.zap)];
2418
- case 2: return [2 /*return*/, _c.sent()];
2419
- case 3: return [2 /*return*/, []];
2420
- }
2421
- });
2422
- });
2423
- };
1314
+ async withdrawImbalanceExpected(amounts) {
1315
+ if (this.isCrypto)
1316
+ throw Error(`withdrawImbalanceExpected method doesn't exist for pool ${this.name} (id: ${this.name})`);
1317
+ return await this.calcLpTokenAmount(amounts, false);
1318
+ }
1319
+ async withdrawImbalanceBonus(amounts) {
1320
+ const prices = (this.isCrypto || this.id === 'wsteth') ? await this._underlyingPrices() : this.underlyingCoins.map(() => 1);
1321
+ const value = amounts.map(checkNumber).map(Number).reduce((s, a, i) => s + (a * prices[i]), 0);
1322
+ const lpTokenAmount = await this.withdrawImbalanceExpected(amounts);
1323
+ const balancedAmounts = await this.withdrawExpected(lpTokenAmount);
1324
+ const balancedValue = balancedAmounts.map(Number).reduce((s, a, i) => s + (a * prices[i]), 0);
1325
+ return String((value - balancedValue) / balancedValue * 100);
1326
+ }
1327
+ async withdrawImbalanceIsApproved(amounts) {
1328
+ if (this.isCrypto)
1329
+ throw Error(`withdrawImbalanceIsApproved method doesn't exist for pool ${this.name} (id: ${this.name})`);
1330
+ if (this.zap) {
1331
+ const _amounts = amounts.map((amount, i) => parseUnits(amount, this.underlyingDecimals[i]));
1332
+ const _maxBurnAmount = (await this._calcLpTokenAmount(_amounts, false)) * 101n / 100n;
1333
+ return await hasAllowance([this.lpToken], [curve.formatUnits(_maxBurnAmount, 18)], curve.signerAddress, this.zap);
1334
+ }
1335
+ return true;
1336
+ }
1337
+ async withdrawImbalanceApproveEstimateGas(amounts) {
1338
+ if (this.isCrypto)
1339
+ throw Error(`withdrawImbalanceApprove method doesn't exist for pool ${this.name} (id: ${this.name})`);
1340
+ if (this.zap) {
1341
+ const _amounts = amounts.map((amount, i) => parseUnits(amount, this.underlyingDecimals[i]));
1342
+ const _maxBurnAmount = (await this._calcLpTokenAmount(_amounts, false)) * 101n / 100n;
1343
+ return await ensureAllowanceEstimateGas([this.lpToken], [curve.formatUnits(_maxBurnAmount, 18)], this.zap);
1344
+ }
1345
+ return 0;
1346
+ }
1347
+ async withdrawImbalanceApprove(amounts) {
1348
+ if (this.isCrypto)
1349
+ throw Error(`withdrawImbalanceApprove method doesn't exist for pool ${this.name} (id: ${this.name})`);
1350
+ if (this.zap) {
1351
+ const _amounts = amounts.map((amount, i) => parseUnits(amount, this.underlyingDecimals[i]));
1352
+ const _maxBurnAmount = (await this._calcLpTokenAmount(_amounts, false)) * 101n / 100n;
1353
+ return await ensureAllowance([this.lpToken], [curve.formatUnits(_maxBurnAmount, 18)], this.zap);
1354
+ }
1355
+ return [];
1356
+ }
2424
1357
  // OVERRIDE
2425
- PoolTemplate.prototype.withdrawImbalanceEstimateGas = function (amounts) {
2426
- return __awaiter(this, void 0, void 0, function () {
2427
- return __generator(this, function (_c) {
2428
- throw Error("withdrawImbalance method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2429
- });
2430
- });
2431
- };
1358
+ async withdrawImbalanceEstimateGas(amounts) {
1359
+ throw Error(`withdrawImbalance method doesn't exist for pool ${this.name} (id: ${this.name})`);
1360
+ }
2432
1361
  // OVERRIDE
2433
- PoolTemplate.prototype.withdrawImbalance = function (amounts, slippage) {
2434
- if (slippage === void 0) { slippage = 0.5; }
2435
- return __awaiter(this, void 0, void 0, function () {
2436
- return __generator(this, function (_c) {
2437
- throw Error("withdrawImbalance method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2438
- });
2439
- });
2440
- };
1362
+ async withdrawImbalance(amounts, slippage = 0.5) {
1363
+ throw Error(`withdrawImbalance method doesn't exist for pool ${this.name} (id: ${this.name})`);
1364
+ }
2441
1365
  // ---------------- WITHDRAW IMBALANCE WRAPPED ----------------
2442
- PoolTemplate.prototype.withdrawImbalanceWrappedExpected = function (amounts) {
2443
- return __awaiter(this, void 0, void 0, function () {
2444
- return __generator(this, function (_c) {
2445
- switch (_c.label) {
2446
- case 0:
2447
- if (this.isCrypto || this.isPlain || this.isFake)
2448
- throw Error("withdrawImbalanceWrappedExpected method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2449
- return [4 /*yield*/, this.calcLpTokenAmountWrapped(amounts, false)];
2450
- case 1: return [2 /*return*/, _c.sent()];
2451
- }
2452
- });
2453
- });
2454
- };
2455
- PoolTemplate.prototype.withdrawImbalanceWrappedBonus = function (amounts) {
2456
- return __awaiter(this, void 0, void 0, function () {
2457
- var prices, value, lpTokenAmount, _c, balancedAmounts, balancedValue;
2458
- return __generator(this, function (_d) {
2459
- switch (_d.label) {
2460
- case 0: return [4 /*yield*/, this._wrappedPrices()];
2461
- case 1:
2462
- prices = _d.sent();
2463
- value = amounts.map(utils_1.checkNumber).map(Number).reduce(function (s, a, i) { return s + (a * prices[i]); }, 0);
2464
- _c = Number;
2465
- return [4 /*yield*/, this.withdrawImbalanceWrappedExpected(amounts)];
2466
- case 2:
2467
- lpTokenAmount = _c.apply(void 0, [_d.sent()]);
2468
- return [4 /*yield*/, this.withdrawWrappedExpected(lpTokenAmount)];
2469
- case 3:
2470
- balancedAmounts = _d.sent();
2471
- balancedValue = balancedAmounts.map(Number).reduce(function (s, a, i) { return s + (a * prices[i]); }, 0);
2472
- return [2 /*return*/, String((value - balancedValue) / balancedValue * 100)];
2473
- }
2474
- });
2475
- });
2476
- };
1366
+ async withdrawImbalanceWrappedExpected(amounts) {
1367
+ if (this.isCrypto || this.isPlain || this.isFake)
1368
+ throw Error(`withdrawImbalanceWrappedExpected method doesn't exist for pool ${this.name} (id: ${this.name})`);
1369
+ return await this.calcLpTokenAmountWrapped(amounts, false);
1370
+ }
1371
+ async withdrawImbalanceWrappedBonus(amounts) {
1372
+ const prices = await this._wrappedPrices();
1373
+ const value = amounts.map(checkNumber).map(Number).reduce((s, a, i) => s + (a * prices[i]), 0);
1374
+ const lpTokenAmount = Number(await this.withdrawImbalanceWrappedExpected(amounts));
1375
+ const balancedAmounts = await this.withdrawWrappedExpected(lpTokenAmount);
1376
+ const balancedValue = balancedAmounts.map(Number).reduce((s, a, i) => s + (a * prices[i]), 0);
1377
+ return String((value - balancedValue) / balancedValue * 100);
1378
+ }
2477
1379
  // OVERRIDE
2478
- PoolTemplate.prototype.withdrawImbalanceWrappedEstimateGas = function (amounts) {
2479
- return __awaiter(this, void 0, void 0, function () {
2480
- return __generator(this, function (_c) {
2481
- throw Error("withdrawImbalanceWrapped method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2482
- });
2483
- });
2484
- };
1380
+ async withdrawImbalanceWrappedEstimateGas(amounts) {
1381
+ throw Error(`withdrawImbalanceWrapped method doesn't exist for pool ${this.name} (id: ${this.name})`);
1382
+ }
2485
1383
  // OVERRIDE
2486
- PoolTemplate.prototype.withdrawImbalanceWrapped = function (amounts, slippage) {
2487
- if (slippage === void 0) { slippage = 0.5; }
2488
- return __awaiter(this, void 0, void 0, function () {
2489
- return __generator(this, function (_c) {
2490
- throw Error("withdrawImbalanceWrapped method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2491
- });
2492
- });
2493
- };
1384
+ async withdrawImbalanceWrapped(amounts, slippage = 0.5) {
1385
+ throw Error(`withdrawImbalanceWrapped method doesn't exist for pool ${this.name} (id: ${this.name})`);
1386
+ }
2494
1387
  // ---------------- WITHDRAW ONE COIN ----------------
2495
1388
  // OVERRIDE
2496
- PoolTemplate.prototype._withdrawOneCoinExpected = function (_lpTokenAmount, i) {
2497
- return __awaiter(this, void 0, void 0, function () {
2498
- return __generator(this, function (_c) {
2499
- throw Error("withdrawOneCoinExpected method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2500
- });
2501
- });
2502
- };
2503
- PoolTemplate.prototype.withdrawOneCoinExpected = function (lpTokenAmount, coin) {
2504
- return __awaiter(this, void 0, void 0, function () {
2505
- var i, _lpTokenAmount, _expected;
2506
- return __generator(this, function (_c) {
2507
- switch (_c.label) {
2508
- case 0:
2509
- i = this._getCoinIdx(coin);
2510
- _lpTokenAmount = (0, utils_1.parseUnits)(lpTokenAmount);
2511
- return [4 /*yield*/, this._withdrawOneCoinExpected(_lpTokenAmount, i)];
2512
- case 1:
2513
- _expected = _c.sent();
2514
- return [2 /*return*/, ethers_1.ethers.utils.formatUnits(_expected, this.underlyingDecimals[i])];
2515
- }
2516
- });
2517
- });
2518
- };
2519
- PoolTemplate.prototype.withdrawOneCoinBonus = function (lpTokenAmount, coin) {
2520
- return __awaiter(this, void 0, void 0, function () {
2521
- var prices, _c, coinPrice, amount, _d, value, balancedAmounts, balancedValue;
2522
- return __generator(this, function (_e) {
2523
- switch (_e.label) {
2524
- case 0:
2525
- if (!(this.isCrypto || this.id === 'wsteth')) return [3 /*break*/, 2];
2526
- return [4 /*yield*/, this._underlyingPrices()];
2527
- case 1:
2528
- _c = _e.sent();
2529
- return [3 /*break*/, 3];
2530
- case 2:
2531
- _c = this.underlyingCoins.map(function () { return 1; });
2532
- _e.label = 3;
2533
- case 3:
2534
- prices = _c;
2535
- coinPrice = prices[this._getCoinIdx(coin)];
2536
- _d = Number;
2537
- return [4 /*yield*/, this.withdrawOneCoinExpected(lpTokenAmount, coin)];
2538
- case 4:
2539
- amount = _d.apply(void 0, [_e.sent()]);
2540
- value = amount * coinPrice;
2541
- return [4 /*yield*/, this.withdrawExpected(lpTokenAmount)];
2542
- case 5:
2543
- balancedAmounts = _e.sent();
2544
- balancedValue = balancedAmounts.map(Number).reduce(function (s, a, i) { return s + (a * prices[i]); }, 0);
2545
- return [2 /*return*/, String((value - balancedValue) / balancedValue * 100)];
2546
- }
2547
- });
2548
- });
2549
- };
2550
- PoolTemplate.prototype.withdrawOneCoinIsApproved = function (lpTokenAmount) {
2551
- return __awaiter(this, void 0, void 0, function () {
2552
- return __generator(this, function (_c) {
2553
- switch (_c.label) {
2554
- case 0:
2555
- if (!this.zap)
2556
- return [2 /*return*/, true];
2557
- return [4 /*yield*/, (0, utils_1.hasAllowance)([this.lpToken], [lpTokenAmount], curve_1.curve.signerAddress, this.zap)];
2558
- case 1: return [2 /*return*/, _c.sent()];
2559
- }
2560
- });
2561
- });
2562
- };
2563
- PoolTemplate.prototype.withdrawOneCoinApproveEstimateGas = function (lpTokenAmount) {
2564
- return __awaiter(this, void 0, void 0, function () {
2565
- return __generator(this, function (_c) {
2566
- switch (_c.label) {
2567
- case 0:
2568
- if (!this.zap)
2569
- return [2 /*return*/, 0];
2570
- return [4 /*yield*/, (0, utils_1.ensureAllowanceEstimateGas)([this.lpToken], [lpTokenAmount], this.zap)];
2571
- case 1: return [2 /*return*/, _c.sent()];
2572
- }
2573
- });
2574
- });
2575
- };
2576
- PoolTemplate.prototype.withdrawOneCoinApprove = function (lpTokenAmount) {
2577
- return __awaiter(this, void 0, void 0, function () {
2578
- return __generator(this, function (_c) {
2579
- switch (_c.label) {
2580
- case 0:
2581
- if (!this.zap)
2582
- return [2 /*return*/, []];
2583
- return [4 /*yield*/, (0, utils_1.ensureAllowance)([this.lpToken], [lpTokenAmount], this.zap)];
2584
- case 1: return [2 /*return*/, _c.sent()];
2585
- }
2586
- });
2587
- });
2588
- };
1389
+ async _withdrawOneCoinExpected(_lpTokenAmount, i) {
1390
+ throw Error(`withdrawOneCoinExpected method doesn't exist for pool ${this.name} (id: ${this.name})`);
1391
+ }
1392
+ async withdrawOneCoinExpected(lpTokenAmount, coin) {
1393
+ const i = this._getCoinIdx(coin);
1394
+ const _lpTokenAmount = parseUnits(lpTokenAmount);
1395
+ const _expected = await this._withdrawOneCoinExpected(_lpTokenAmount, i);
1396
+ return curve.formatUnits(_expected, this.underlyingDecimals[i]);
1397
+ }
1398
+ async withdrawOneCoinBonus(lpTokenAmount, coin) {
1399
+ const prices = (this.isCrypto || this.id === 'wsteth') ? await this._underlyingPrices() : this.underlyingCoins.map(() => 1);
1400
+ const coinPrice = prices[this._getCoinIdx(coin)];
1401
+ const amount = Number(await this.withdrawOneCoinExpected(lpTokenAmount, coin));
1402
+ const value = amount * coinPrice;
1403
+ const balancedAmounts = await this.withdrawExpected(lpTokenAmount);
1404
+ const balancedValue = balancedAmounts.map(Number).reduce((s, a, i) => s + (a * prices[i]), 0);
1405
+ return String((value - balancedValue) / balancedValue * 100);
1406
+ }
1407
+ async withdrawOneCoinIsApproved(lpTokenAmount) {
1408
+ if (!this.zap)
1409
+ return true;
1410
+ return await hasAllowance([this.lpToken], [lpTokenAmount], curve.signerAddress, this.zap);
1411
+ }
1412
+ async withdrawOneCoinApproveEstimateGas(lpTokenAmount) {
1413
+ if (!this.zap)
1414
+ return 0;
1415
+ return await ensureAllowanceEstimateGas([this.lpToken], [lpTokenAmount], this.zap);
1416
+ }
1417
+ async withdrawOneCoinApprove(lpTokenAmount) {
1418
+ if (!this.zap)
1419
+ return [];
1420
+ return await ensureAllowance([this.lpToken], [lpTokenAmount], this.zap);
1421
+ }
2589
1422
  // OVERRIDE
2590
- PoolTemplate.prototype.withdrawOneCoinEstimateGas = function (lpTokenAmount, coin) {
2591
- return __awaiter(this, void 0, void 0, function () {
2592
- return __generator(this, function (_c) {
2593
- throw Error("withdrawOneCoin method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2594
- });
2595
- });
2596
- };
1423
+ async withdrawOneCoinEstimateGas(lpTokenAmount, coin) {
1424
+ throw Error(`withdrawOneCoin method doesn't exist for pool ${this.name} (id: ${this.name})`);
1425
+ }
2597
1426
  // OVERRIDE
2598
- PoolTemplate.prototype.withdrawOneCoin = function (lpTokenAmount, coin, slippage) {
2599
- if (slippage === void 0) { slippage = 0.5; }
2600
- return __awaiter(this, void 0, void 0, function () {
2601
- return __generator(this, function (_c) {
2602
- throw Error("withdrawOneCoin method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2603
- });
2604
- });
2605
- };
1427
+ async withdrawOneCoin(lpTokenAmount, coin, slippage = 0.5) {
1428
+ throw Error(`withdrawOneCoin method doesn't exist for pool ${this.name} (id: ${this.name})`);
1429
+ }
2606
1430
  // ---------------- WITHDRAW ONE COIN WRAPPED ----------------
2607
1431
  // OVERRIDE
2608
- PoolTemplate.prototype._withdrawOneCoinWrappedExpected = function (_lpTokenAmount, i) {
2609
- return __awaiter(this, void 0, void 0, function () {
2610
- return __generator(this, function (_c) {
2611
- throw Error("withdrawOneCoinWrappedExpected method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2612
- });
2613
- });
2614
- };
2615
- PoolTemplate.prototype.withdrawOneCoinWrappedExpected = function (lpTokenAmount, coin) {
2616
- return __awaiter(this, void 0, void 0, function () {
2617
- var i, _lpTokenAmount, _expected;
2618
- return __generator(this, function (_c) {
2619
- switch (_c.label) {
2620
- case 0:
2621
- i = this._getCoinIdx(coin, false);
2622
- _lpTokenAmount = (0, utils_1.parseUnits)(lpTokenAmount);
2623
- return [4 /*yield*/, this._withdrawOneCoinWrappedExpected(_lpTokenAmount, i)];
2624
- case 1:
2625
- _expected = _c.sent();
2626
- return [2 /*return*/, ethers_1.ethers.utils.formatUnits(_expected, this.wrappedDecimals[i])];
2627
- }
2628
- });
2629
- });
2630
- };
2631
- PoolTemplate.prototype.withdrawOneCoinWrappedBonus = function (lpTokenAmount, coin) {
2632
- return __awaiter(this, void 0, void 0, function () {
2633
- var prices, coinPrice, amount, _c, value, balancedAmounts, balancedValue;
2634
- return __generator(this, function (_d) {
2635
- switch (_d.label) {
2636
- case 0: return [4 /*yield*/, this._wrappedPrices()];
2637
- case 1:
2638
- prices = _d.sent();
2639
- coinPrice = prices[this._getCoinIdx(coin, false)];
2640
- _c = Number;
2641
- return [4 /*yield*/, this.withdrawOneCoinWrappedExpected(lpTokenAmount, coin)];
2642
- case 2:
2643
- amount = _c.apply(void 0, [_d.sent()]);
2644
- value = amount * coinPrice;
2645
- return [4 /*yield*/, this.withdrawWrappedExpected(lpTokenAmount)];
2646
- case 3:
2647
- balancedAmounts = _d.sent();
2648
- balancedValue = balancedAmounts.map(Number).reduce(function (s, a, i) { return s + (a * prices[i]); }, 0);
2649
- return [2 /*return*/, String((value - balancedValue) / balancedValue * 100)];
2650
- }
2651
- });
2652
- });
2653
- };
1432
+ async _withdrawOneCoinWrappedExpected(_lpTokenAmount, i) {
1433
+ throw Error(`withdrawOneCoinWrappedExpected method doesn't exist for pool ${this.name} (id: ${this.name})`);
1434
+ }
1435
+ async withdrawOneCoinWrappedExpected(lpTokenAmount, coin) {
1436
+ const i = this._getCoinIdx(coin, false);
1437
+ const _lpTokenAmount = parseUnits(lpTokenAmount);
1438
+ const _expected = await this._withdrawOneCoinWrappedExpected(_lpTokenAmount, i);
1439
+ return curve.formatUnits(_expected, this.wrappedDecimals[i]);
1440
+ }
1441
+ async withdrawOneCoinWrappedBonus(lpTokenAmount, coin) {
1442
+ const prices = await this._wrappedPrices();
1443
+ const coinPrice = prices[this._getCoinIdx(coin, false)];
1444
+ const amount = Number(await this.withdrawOneCoinWrappedExpected(lpTokenAmount, coin));
1445
+ const value = amount * coinPrice;
1446
+ const balancedAmounts = await this.withdrawWrappedExpected(lpTokenAmount);
1447
+ const balancedValue = balancedAmounts.map(Number).reduce((s, a, i) => s + (a * prices[i]), 0);
1448
+ return String((value - balancedValue) / balancedValue * 100);
1449
+ }
2654
1450
  // OVERRIDE
2655
- PoolTemplate.prototype.withdrawOneCoinWrappedEstimateGas = function (lpTokenAmount, coin) {
2656
- return __awaiter(this, void 0, void 0, function () {
2657
- return __generator(this, function (_c) {
2658
- throw Error("withdrawOneCoinWrapped method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2659
- });
2660
- });
2661
- };
1451
+ async withdrawOneCoinWrappedEstimateGas(lpTokenAmount, coin) {
1452
+ throw Error(`withdrawOneCoinWrapped method doesn't exist for pool ${this.name} (id: ${this.name})`);
1453
+ }
2662
1454
  // OVERRIDE
2663
- PoolTemplate.prototype.withdrawOneCoinWrapped = function (lpTokenAmount, coin, slippage) {
2664
- if (slippage === void 0) { slippage = 0.5; }
2665
- return __awaiter(this, void 0, void 0, function () {
2666
- return __generator(this, function (_c) {
2667
- throw Error("withdrawOneCoinWrapped method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
2668
- });
2669
- });
2670
- };
1455
+ async withdrawOneCoinWrapped(lpTokenAmount, coin, slippage = 0.5) {
1456
+ throw Error(`withdrawOneCoinWrapped method doesn't exist for pool ${this.name} (id: ${this.name})`);
1457
+ }
2671
1458
  // ---------------- WALLET BALANCES ----------------
2672
- PoolTemplate.prototype.walletBalances = function () {
2673
- var addresses = [];
2674
- for (var _i = 0; _i < arguments.length; _i++) {
2675
- addresses[_i] = arguments[_i];
2676
- }
2677
- return __awaiter(this, void 0, void 0, function () {
2678
- return __generator(this, function (_c) {
2679
- switch (_c.label) {
2680
- case 0:
2681
- if (!(this.gauge === ethers_1.ethers.constants.AddressZero)) return [3 /*break*/, 2];
2682
- return [4 /*yield*/, this._balances.apply(this, __spreadArray([__spreadArray(__spreadArray(['lpToken'], this.underlyingCoinAddresses, true), this.wrappedCoinAddresses, true), __spreadArray(__spreadArray([this.lpToken], this.underlyingCoinAddresses, true), this.wrappedCoinAddresses, true)], addresses, false))];
2683
- case 1: return [2 /*return*/, _c.sent()];
2684
- case 2: return [4 /*yield*/, this._balances.apply(this, __spreadArray([__spreadArray(__spreadArray(['lpToken', 'gauge'], this.underlyingCoinAddresses, true), this.wrappedCoinAddresses, true), __spreadArray(__spreadArray([this.lpToken, this.gauge], this.underlyingCoinAddresses, true), this.wrappedCoinAddresses, true)], addresses, false))];
2685
- case 3: return [2 /*return*/, _c.sent()];
2686
- }
2687
- });
2688
- });
2689
- };
2690
- PoolTemplate.prototype.walletLpTokenBalances = function () {
2691
- var addresses = [];
2692
- for (var _i = 0; _i < arguments.length; _i++) {
2693
- addresses[_i] = arguments[_i];
1459
+ async walletBalances(...addresses) {
1460
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1461
+ return await this._balances(['lpToken', ...this.underlyingCoinAddresses, ...this.wrappedCoinAddresses], [this.lpToken, ...this.underlyingCoinAddresses, ...this.wrappedCoinAddresses], ...addresses);
2694
1462
  }
2695
- return __awaiter(this, void 0, void 0, function () {
2696
- return __generator(this, function (_c) {
2697
- switch (_c.label) {
2698
- case 0:
2699
- if (!(this.gauge === ethers_1.ethers.constants.AddressZero)) return [3 /*break*/, 2];
2700
- return [4 /*yield*/, this._balances.apply(this, __spreadArray([['lpToken'], [this.lpToken]], addresses, false))];
2701
- case 1: return [2 /*return*/, _c.sent()];
2702
- case 2: return [4 /*yield*/, this._balances.apply(this, __spreadArray([['lpToken', 'gauge'], [this.lpToken, this.gauge]], addresses, false))];
2703
- case 3: return [2 /*return*/, _c.sent()];
2704
- }
2705
- });
2706
- });
2707
- };
2708
- PoolTemplate.prototype.walletUnderlyingCoinBalances = function () {
2709
- var addresses = [];
2710
- for (var _i = 0; _i < arguments.length; _i++) {
2711
- addresses[_i] = arguments[_i];
1463
+ else {
1464
+ return await this._balances(['lpToken', 'gauge', ...this.underlyingCoinAddresses, ...this.wrappedCoinAddresses], [this.lpToken, this.gauge, ...this.underlyingCoinAddresses, ...this.wrappedCoinAddresses], ...addresses);
2712
1465
  }
2713
- return __awaiter(this, void 0, void 0, function () {
2714
- return __generator(this, function (_c) {
2715
- switch (_c.label) {
2716
- case 0: return [4 /*yield*/, this._balances.apply(this, __spreadArray([this.underlyingCoinAddresses, this.underlyingCoinAddresses], addresses, false))];
2717
- case 1: return [2 /*return*/, _c.sent()];
2718
- }
2719
- });
2720
- });
2721
- };
2722
- PoolTemplate.prototype.walletWrappedCoinBalances = function () {
2723
- var addresses = [];
2724
- for (var _i = 0; _i < arguments.length; _i++) {
2725
- addresses[_i] = arguments[_i];
1466
+ }
1467
+ async walletLpTokenBalances(...addresses) {
1468
+ if (this.gauge === curve.constants.ZERO_ADDRESS) {
1469
+ return await this._balances(['lpToken'], [this.lpToken], ...addresses);
2726
1470
  }
2727
- return __awaiter(this, void 0, void 0, function () {
2728
- return __generator(this, function (_c) {
2729
- switch (_c.label) {
2730
- case 0: return [4 /*yield*/, this._balances.apply(this, __spreadArray([this.wrappedCoinAddresses, this.wrappedCoinAddresses], addresses, false))];
2731
- case 1: return [2 /*return*/, _c.sent()];
2732
- }
2733
- });
2734
- });
2735
- };
2736
- PoolTemplate.prototype.walletAllCoinBalances = function () {
2737
- var addresses = [];
2738
- for (var _i = 0; _i < arguments.length; _i++) {
2739
- addresses[_i] = arguments[_i];
1471
+ else {
1472
+ return await this._balances(['lpToken', 'gauge'], [this.lpToken, this.gauge], ...addresses);
2740
1473
  }
2741
- return __awaiter(this, void 0, void 0, function () {
2742
- return __generator(this, function (_c) {
2743
- switch (_c.label) {
2744
- case 0: return [4 /*yield*/, this._balances.apply(this, __spreadArray([__spreadArray(__spreadArray([], this.underlyingCoinAddresses, true), this.wrappedCoinAddresses, true), __spreadArray(__spreadArray([], this.underlyingCoinAddresses, true), this.wrappedCoinAddresses, true)], addresses, false))];
2745
- case 1: return [2 /*return*/, _c.sent()];
2746
- }
2747
- });
2748
- });
2749
- };
1474
+ }
1475
+ async walletUnderlyingCoinBalances(...addresses) {
1476
+ return await this._balances(this.underlyingCoinAddresses, this.underlyingCoinAddresses, ...addresses);
1477
+ }
1478
+ async walletWrappedCoinBalances(...addresses) {
1479
+ return await this._balances(this.wrappedCoinAddresses, this.wrappedCoinAddresses, ...addresses);
1480
+ }
1481
+ async walletAllCoinBalances(...addresses) {
1482
+ return await this._balances([...this.underlyingCoinAddresses, ...this.wrappedCoinAddresses], [...this.underlyingCoinAddresses, ...this.wrappedCoinAddresses], ...addresses);
1483
+ }
2750
1484
  // ---------------- USER BALANCES, BASE PROFIT AND SHARE ----------------
2751
- PoolTemplate.prototype._userLpTotalBalance = function (address) {
2752
- return __awaiter(this, void 0, void 0, function () {
2753
- var lpBalances, lpTotalBalanceBN;
2754
- return __generator(this, function (_c) {
2755
- switch (_c.label) {
2756
- case 0: return [4 /*yield*/, this.walletLpTokenBalances(address)];
2757
- case 1:
2758
- lpBalances = _c.sent();
2759
- lpTotalBalanceBN = (0, utils_1.BN)(lpBalances.lpToken);
2760
- if ('gauge' in lpBalances)
2761
- lpTotalBalanceBN = lpTotalBalanceBN.plus((0, utils_1.BN)(lpBalances.gauge));
2762
- return [2 /*return*/, lpTotalBalanceBN];
2763
- }
2764
- });
2765
- });
2766
- };
2767
- PoolTemplate.prototype.userBalances = function (address) {
2768
- if (address === void 0) { address = ""; }
2769
- return __awaiter(this, void 0, void 0, function () {
2770
- var lpTotalBalanceBN;
2771
- return __generator(this, function (_c) {
2772
- switch (_c.label) {
2773
- case 0:
2774
- address = address || curve_1.curve.signerAddress;
2775
- if (!address)
2776
- throw Error("Need to connect wallet or pass address into args");
2777
- return [4 /*yield*/, this._userLpTotalBalance(address)];
2778
- case 1:
2779
- lpTotalBalanceBN = _c.sent();
2780
- if (lpTotalBalanceBN.eq(0))
2781
- return [2 /*return*/, this.underlyingCoins.map(function () { return "0"; })];
2782
- return [4 /*yield*/, this.withdrawExpected(lpTotalBalanceBN.toFixed(18))];
2783
- case 2: return [2 /*return*/, _c.sent()];
2784
- }
2785
- });
2786
- });
2787
- };
2788
- PoolTemplate.prototype.userWrappedBalances = function (address) {
2789
- if (address === void 0) { address = ""; }
2790
- return __awaiter(this, void 0, void 0, function () {
2791
- var lpTotalBalanceBN;
2792
- return __generator(this, function (_c) {
2793
- switch (_c.label) {
2794
- case 0:
2795
- address = address || curve_1.curve.signerAddress;
2796
- if (!address)
2797
- throw Error("Need to connect wallet or pass address into args");
2798
- return [4 /*yield*/, this._userLpTotalBalance(address)];
2799
- case 1:
2800
- lpTotalBalanceBN = _c.sent();
2801
- if (lpTotalBalanceBN.eq(0))
2802
- return [2 /*return*/, this.wrappedCoins.map(function () { return "0"; })];
2803
- return [4 /*yield*/, this.withdrawWrappedExpected(lpTotalBalanceBN.toFixed(18))];
2804
- case 2: return [2 /*return*/, _c.sent()];
2805
- }
2806
- });
2807
- });
2808
- };
2809
- PoolTemplate.prototype.userLiquidityUSD = function (address) {
2810
- if (address === void 0) { address = ""; }
2811
- return __awaiter(this, void 0, void 0, function () {
2812
- var lpBalanceBN, lpPrice;
2813
- return __generator(this, function (_c) {
2814
- switch (_c.label) {
2815
- case 0: return [4 /*yield*/, this._userLpTotalBalance(address)];
2816
- case 1:
2817
- lpBalanceBN = _c.sent();
2818
- return [4 /*yield*/, (0, utils_1._getUsdRate)(this.lpToken)];
2819
- case 2:
2820
- lpPrice = _c.sent();
2821
- return [2 /*return*/, lpBalanceBN.times(lpPrice).toFixed(8)];
2822
- }
2823
- });
2824
- });
2825
- };
2826
- PoolTemplate.prototype.baseProfit = function (address) {
2827
- if (address === void 0) { address = ""; }
2828
- return __awaiter(this, void 0, void 0, function () {
2829
- var apyData, apyBN, totalLiquidityBN, _c, annualProfitBN, monthlyProfitBN, weeklyProfitBN, dailyProfitBN;
2830
- return __generator(this, function (_d) {
2831
- switch (_d.label) {
2832
- case 0: return [4 /*yield*/, this.statsBaseApy()];
2833
- case 1:
2834
- apyData = _d.sent();
2835
- if (!('week' in apyData))
2836
- return [2 /*return*/, { day: "0", week: "0", month: "0", year: "0" }];
2837
- apyBN = (0, utils_1.BN)(apyData.week).div(100);
2838
- _c = utils_1.BN;
2839
- return [4 /*yield*/, this.userLiquidityUSD(address)];
2840
- case 2:
2841
- totalLiquidityBN = _c.apply(void 0, [_d.sent()]);
2842
- annualProfitBN = apyBN.times(totalLiquidityBN);
2843
- monthlyProfitBN = annualProfitBN.div(12);
2844
- weeklyProfitBN = annualProfitBN.div(52);
2845
- dailyProfitBN = annualProfitBN.div(365);
2846
- return [2 /*return*/, {
2847
- day: dailyProfitBN.toString(),
2848
- week: weeklyProfitBN.toString(),
2849
- month: monthlyProfitBN.toString(),
2850
- year: annualProfitBN.toString(),
2851
- }];
2852
- }
2853
- });
2854
- });
2855
- };
2856
- PoolTemplate.prototype.userShare = function (address) {
2857
- if (address === void 0) { address = ""; }
2858
- return __awaiter(this, void 0, void 0, function () {
2859
- var withGauge, userLpBalance, userLpTotalBalanceBN, totalLp, gaugeLp, _c, _d;
2860
- var _e;
2861
- return __generator(this, function (_f) {
2862
- switch (_f.label) {
2863
- case 0:
2864
- withGauge = this.gauge !== ethers_1.ethers.constants.AddressZero;
2865
- address = address || curve_1.curve.signerAddress;
2866
- if (!address)
2867
- throw Error("Need to connect wallet or pass address into args");
2868
- return [4 /*yield*/, this.walletLpTokenBalances(address)];
2869
- case 1:
2870
- userLpBalance = _f.sent();
2871
- userLpTotalBalanceBN = (0, utils_1.BN)(userLpBalance.lpToken);
2872
- if (withGauge)
2873
- userLpTotalBalanceBN = userLpTotalBalanceBN.plus((0, utils_1.BN)(userLpBalance.gauge));
2874
- if (!withGauge) return [3 /*break*/, 3];
2875
- return [4 /*yield*/, curve_1.curve.multicallProvider.all([
2876
- curve_1.curve.contracts[this.lpToken].multicallContract.totalSupply(),
2877
- curve_1.curve.contracts[this.gauge].multicallContract.totalSupply(),
2878
- ])];
2879
- case 2:
2880
- _e = (_f.sent()).map(function (_supply) { return ethers_1.ethers.utils.formatUnits(_supply); }), totalLp = _e[0], gaugeLp = _e[1];
2881
- return [3 /*break*/, 5];
2882
- case 3:
2883
- _d = (_c = ethers_1.ethers.utils).formatUnits;
2884
- return [4 /*yield*/, curve_1.curve.contracts[this.lpToken].contract.totalSupply(curve_1.curve.constantOptions)];
2885
- case 4:
2886
- totalLp = _d.apply(_c, [_f.sent()]);
2887
- _f.label = 5;
2888
- case 5: return [2 /*return*/, {
2889
- lpUser: userLpTotalBalanceBN.toString(),
2890
- lpTotal: totalLp,
2891
- lpShare: (0, utils_1.BN)(totalLp).gt(0) ? userLpTotalBalanceBN.div(totalLp).times(100).toString() : '0',
2892
- gaugeUser: userLpBalance.gauge,
2893
- gaugeTotal: gaugeLp,
2894
- gaugeShare: !withGauge ? undefined : (0, utils_1.BN)(gaugeLp).gt(0) ? (0, utils_1.BN)(userLpBalance.gauge).div(gaugeLp).times(100).toString() : '0',
2895
- }];
2896
- }
2897
- });
2898
- });
2899
- };
1485
+ async _userLpTotalBalance(address) {
1486
+ const lpBalances = await this.walletLpTokenBalances(address);
1487
+ let lpTotalBalanceBN = BN(lpBalances.lpToken);
1488
+ if ('gauge' in lpBalances)
1489
+ lpTotalBalanceBN = lpTotalBalanceBN.plus(BN(lpBalances.gauge));
1490
+ return lpTotalBalanceBN;
1491
+ }
1492
+ async userBalances(address = "") {
1493
+ address = address || curve.signerAddress;
1494
+ if (!address)
1495
+ throw Error("Need to connect wallet or pass address into args");
1496
+ const lpTotalBalanceBN = await this._userLpTotalBalance(address);
1497
+ if (lpTotalBalanceBN.eq(0))
1498
+ return this.underlyingCoins.map(() => "0");
1499
+ return await this.withdrawExpected(lpTotalBalanceBN.toFixed(18));
1500
+ }
1501
+ async userWrappedBalances(address = "") {
1502
+ address = address || curve.signerAddress;
1503
+ if (!address)
1504
+ throw Error("Need to connect wallet or pass address into args");
1505
+ const lpTotalBalanceBN = await this._userLpTotalBalance(address);
1506
+ if (lpTotalBalanceBN.eq(0))
1507
+ return this.wrappedCoins.map(() => "0");
1508
+ return await this.withdrawWrappedExpected(lpTotalBalanceBN.toFixed(18));
1509
+ }
1510
+ async userLiquidityUSD(address = "") {
1511
+ const lpBalanceBN = await this._userLpTotalBalance(address);
1512
+ const lpPrice = await _getUsdRate(this.lpToken);
1513
+ return lpBalanceBN.times(lpPrice).toFixed(8);
1514
+ }
1515
+ async baseProfit(address = "") {
1516
+ const apyData = await this.statsBaseApy();
1517
+ if (!('week' in apyData))
1518
+ return { day: "0", week: "0", month: "0", year: "0" };
1519
+ const apyBN = BN(apyData.week).div(100);
1520
+ const totalLiquidityBN = BN(await this.userLiquidityUSD(address));
1521
+ const annualProfitBN = apyBN.times(totalLiquidityBN);
1522
+ const monthlyProfitBN = annualProfitBN.div(12);
1523
+ const weeklyProfitBN = annualProfitBN.div(52);
1524
+ const dailyProfitBN = annualProfitBN.div(365);
1525
+ return {
1526
+ day: dailyProfitBN.toString(),
1527
+ week: weeklyProfitBN.toString(),
1528
+ month: monthlyProfitBN.toString(),
1529
+ year: annualProfitBN.toString(),
1530
+ };
1531
+ }
1532
+ async userShare(address = "") {
1533
+ const withGauge = this.gauge !== curve.constants.ZERO_ADDRESS;
1534
+ address = address || curve.signerAddress;
1535
+ if (!address)
1536
+ throw Error("Need to connect wallet or pass address into args");
1537
+ const userLpBalance = await this.walletLpTokenBalances(address);
1538
+ let userLpTotalBalanceBN = BN(userLpBalance.lpToken);
1539
+ if (withGauge)
1540
+ userLpTotalBalanceBN = userLpTotalBalanceBN.plus(BN(userLpBalance.gauge));
1541
+ let totalLp, gaugeLp;
1542
+ if (withGauge) {
1543
+ [totalLp, gaugeLp] = (await curve.multicallProvider.all([
1544
+ curve.contracts[this.lpToken].multicallContract.totalSupply(),
1545
+ curve.contracts[this.gauge].multicallContract.totalSupply(),
1546
+ ])).map((_supply) => curve.formatUnits(_supply));
1547
+ }
1548
+ else {
1549
+ totalLp = curve.formatUnits(await curve.contracts[this.lpToken].contract.totalSupply(curve.constantOptions));
1550
+ }
1551
+ return {
1552
+ lpUser: userLpTotalBalanceBN.toString(),
1553
+ lpTotal: totalLp,
1554
+ lpShare: BN(totalLp).gt(0) ? userLpTotalBalanceBN.div(totalLp).times(100).toString() : '0',
1555
+ gaugeUser: userLpBalance.gauge,
1556
+ gaugeTotal: gaugeLp,
1557
+ gaugeShare: !withGauge ? undefined : BN(gaugeLp).gt(0) ? BN(userLpBalance.gauge).div(gaugeLp).times(100).toString() : '0',
1558
+ };
1559
+ }
2900
1560
  // ---------------- SWAP ----------------
2901
- PoolTemplate.prototype._swapExpected = function (i, j, _amount) {
2902
- return __awaiter(this, void 0, void 0, function () {
2903
- var contractAddress, contract;
2904
- return __generator(this, function (_c) {
2905
- switch (_c.label) {
2906
- case 0:
2907
- contractAddress = this.isCrypto && this.isMeta ? this.zap : this.address;
2908
- contract = curve_1.curve.contracts[contractAddress].contract;
2909
- if (!Object.prototype.hasOwnProperty.call(contract, 'get_dy_underlying')) return [3 /*break*/, 2];
2910
- return [4 /*yield*/, contract.get_dy_underlying(i, j, _amount, curve_1.curve.constantOptions)];
2911
- case 1: return [2 /*return*/, _c.sent()];
2912
- case 2:
2913
- if (!('get_dy(address,uint256,uint256,uint256)' in contract)) return [3 /*break*/, 4];
2914
- return [4 /*yield*/, contract.get_dy(this.address, i, j, _amount, curve_1.curve.constantOptions)];
2915
- case 3: // atricrypto3 based metapools
2916
- return [2 /*return*/, _c.sent()];
2917
- case 4: return [4 /*yield*/, contract.get_dy(i, j, _amount, curve_1.curve.constantOptions)];
2918
- case 5: return [2 /*return*/, _c.sent()];
2919
- }
2920
- });
2921
- });
2922
- };
2923
- PoolTemplate.prototype.swapExpected = function (inputCoin, outputCoin, amount) {
2924
- return __awaiter(this, void 0, void 0, function () {
2925
- var i, j, _amount, _expected;
2926
- return __generator(this, function (_c) {
2927
- switch (_c.label) {
2928
- case 0:
2929
- i = this._getCoinIdx(inputCoin);
2930
- j = this._getCoinIdx(outputCoin);
2931
- _amount = (0, utils_1.parseUnits)(amount, this.underlyingDecimals[i]);
2932
- return [4 /*yield*/, this._swapExpected(i, j, _amount)];
2933
- case 1:
2934
- _expected = _c.sent();
2935
- return [2 /*return*/, ethers_1.ethers.utils.formatUnits(_expected, this.underlyingDecimals[j])];
2936
- }
2937
- });
2938
- });
2939
- };
2940
- PoolTemplate.prototype.swapPriceImpact = function (inputCoin, outputCoin, amount) {
2941
- return __awaiter(this, void 0, void 0, function () {
2942
- var i, j, _c, inputCoinDecimals, outputCoinDecimals, _amount, _output, smallAmountIntBN, amountIntBN, _smallAmount, _smallOutput, priceImpactBN;
2943
- return __generator(this, function (_d) {
2944
- switch (_d.label) {
2945
- case 0:
2946
- i = this._getCoinIdx(inputCoin);
2947
- j = this._getCoinIdx(outputCoin);
2948
- _c = [this.underlyingDecimals[i], this.underlyingDecimals[j]], inputCoinDecimals = _c[0], outputCoinDecimals = _c[1];
2949
- _amount = (0, utils_1.parseUnits)(amount, inputCoinDecimals);
2950
- return [4 /*yield*/, this._swapExpected(i, j, _amount)];
2951
- case 1:
2952
- _output = _d.sent();
2953
- smallAmountIntBN = (0, utils_1._get_small_x)(_amount, _output, inputCoinDecimals, outputCoinDecimals);
2954
- amountIntBN = (0, utils_1.toBN)(_amount, 0);
2955
- if (smallAmountIntBN.gte(amountIntBN))
2956
- return [2 /*return*/, 0];
2957
- _smallAmount = (0, utils_1.fromBN)(smallAmountIntBN.div(Math.pow(10, inputCoinDecimals)), inputCoinDecimals);
2958
- return [4 /*yield*/, this._swapExpected(i, j, _smallAmount)];
2959
- case 2:
2960
- _smallOutput = _d.sent();
2961
- priceImpactBN = (0, utils_1._get_price_impact)(_amount, _output, _smallAmount, _smallOutput, inputCoinDecimals, outputCoinDecimals);
2962
- return [2 /*return*/, Number((0, utils_1._cutZeros)(priceImpactBN.toFixed(4)))];
2963
- }
2964
- });
2965
- });
2966
- };
2967
- PoolTemplate.prototype._swapContractAddress = function () {
1561
+ async _swapExpected(i, j, _amount) {
1562
+ const contractAddress = this.isCrypto && this.isMeta ? this.zap : this.address;
1563
+ const contract = curve.contracts[contractAddress].contract;
1564
+ if ('get_dy_underlying' in contract) {
1565
+ return await contract.get_dy_underlying(i, j, _amount, curve.constantOptions);
1566
+ }
1567
+ else {
1568
+ if ('get_dy(address,uint256,uint256,uint256)' in contract) { // atricrypto3 based metapools
1569
+ return await contract.get_dy(this.address, i, j, _amount, curve.constantOptions);
1570
+ }
1571
+ return await contract.get_dy(i, j, _amount, curve.constantOptions);
1572
+ }
1573
+ }
1574
+ async swapExpected(inputCoin, outputCoin, amount) {
1575
+ const i = this._getCoinIdx(inputCoin);
1576
+ const j = this._getCoinIdx(outputCoin);
1577
+ const _amount = parseUnits(amount, this.underlyingDecimals[i]);
1578
+ const _expected = await this._swapExpected(i, j, _amount);
1579
+ return curve.formatUnits(_expected, this.underlyingDecimals[j]);
1580
+ }
1581
+ async swapPriceImpact(inputCoin, outputCoin, amount) {
1582
+ const i = this._getCoinIdx(inputCoin);
1583
+ const j = this._getCoinIdx(outputCoin);
1584
+ const [inputCoinDecimals, outputCoinDecimals] = [this.underlyingDecimals[i], this.underlyingDecimals[j]];
1585
+ const _amount = parseUnits(amount, inputCoinDecimals);
1586
+ const _output = await this._swapExpected(i, j, _amount);
1587
+ const smallAmountIntBN = _get_small_x(_amount, _output, inputCoinDecimals, outputCoinDecimals);
1588
+ const amountIntBN = toBN(_amount, 0);
1589
+ if (smallAmountIntBN.gte(amountIntBN))
1590
+ return 0;
1591
+ const _smallAmount = fromBN(smallAmountIntBN.div(10 ** inputCoinDecimals), inputCoinDecimals);
1592
+ const _smallOutput = await this._swapExpected(i, j, _smallAmount);
1593
+ const priceImpactBN = _get_price_impact(_amount, _output, _smallAmount, _smallOutput, inputCoinDecimals, outputCoinDecimals);
1594
+ return Number(_cutZeros(priceImpactBN.toFixed(4)));
1595
+ }
1596
+ _swapContractAddress() {
2968
1597
  return (this.isCrypto && this.isMeta) || (this.isMetaFactory && (new PoolTemplate(this.basePool).isLending)) ? this.zap : this.address;
2969
- };
2970
- PoolTemplate.prototype.swapIsApproved = function (inputCoin, amount) {
2971
- return __awaiter(this, void 0, void 0, function () {
2972
- var contractAddress, i;
2973
- return __generator(this, function (_c) {
2974
- switch (_c.label) {
2975
- case 0:
2976
- contractAddress = this._swapContractAddress();
2977
- i = this._getCoinIdx(inputCoin);
2978
- return [4 /*yield*/, (0, utils_1.hasAllowance)([this.underlyingCoinAddresses[i]], [amount], curve_1.curve.signerAddress, contractAddress)];
2979
- case 1: return [2 /*return*/, _c.sent()];
2980
- }
2981
- });
2982
- });
2983
- };
2984
- PoolTemplate.prototype.swapApproveEstimateGas = function (inputCoin, amount) {
2985
- return __awaiter(this, void 0, void 0, function () {
2986
- var contractAddress, i;
2987
- return __generator(this, function (_c) {
2988
- switch (_c.label) {
2989
- case 0:
2990
- contractAddress = this._swapContractAddress();
2991
- i = this._getCoinIdx(inputCoin);
2992
- return [4 /*yield*/, (0, utils_1.ensureAllowanceEstimateGas)([this.underlyingCoinAddresses[i]], [amount], contractAddress)];
2993
- case 1: return [2 /*return*/, _c.sent()];
2994
- }
2995
- });
2996
- });
2997
- };
2998
- PoolTemplate.prototype.swapApprove = function (inputCoin, amount) {
2999
- return __awaiter(this, void 0, void 0, function () {
3000
- var contractAddress, i;
3001
- return __generator(this, function (_c) {
3002
- switch (_c.label) {
3003
- case 0:
3004
- contractAddress = this._swapContractAddress();
3005
- i = this._getCoinIdx(inputCoin);
3006
- return [4 /*yield*/, (0, utils_1.ensureAllowance)([this.underlyingCoinAddresses[i]], [amount], contractAddress)];
3007
- case 1: return [2 /*return*/, _c.sent()];
3008
- }
3009
- });
3010
- });
3011
- };
1598
+ }
1599
+ async swapIsApproved(inputCoin, amount) {
1600
+ const contractAddress = this._swapContractAddress();
1601
+ const i = this._getCoinIdx(inputCoin);
1602
+ return await hasAllowance([this.underlyingCoinAddresses[i]], [amount], curve.signerAddress, contractAddress);
1603
+ }
1604
+ async swapApproveEstimateGas(inputCoin, amount) {
1605
+ const contractAddress = this._swapContractAddress();
1606
+ const i = this._getCoinIdx(inputCoin);
1607
+ return await ensureAllowanceEstimateGas([this.underlyingCoinAddresses[i]], [amount], contractAddress);
1608
+ }
1609
+ async swapApprove(inputCoin, amount) {
1610
+ const contractAddress = this._swapContractAddress();
1611
+ const i = this._getCoinIdx(inputCoin);
1612
+ return await ensureAllowance([this.underlyingCoinAddresses[i]], [amount], contractAddress);
1613
+ }
3012
1614
  // OVERRIDE
3013
- PoolTemplate.prototype.swapEstimateGas = function (inputCoin, outputCoin, amount) {
3014
- return __awaiter(this, void 0, void 0, function () {
3015
- return __generator(this, function (_c) {
3016
- throw Error("swap method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
3017
- });
3018
- });
3019
- };
1615
+ async swapEstimateGas(inputCoin, outputCoin, amount) {
1616
+ throw Error(`swap method doesn't exist for pool ${this.name} (id: ${this.name})`);
1617
+ }
3020
1618
  // OVERRIDE
3021
- PoolTemplate.prototype.swap = function (inputCoin, outputCoin, amount, slippage) {
3022
- if (slippage === void 0) { slippage = 0.5; }
3023
- return __awaiter(this, void 0, void 0, function () {
3024
- return __generator(this, function (_c) {
3025
- throw Error("swap method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
3026
- });
3027
- });
3028
- };
1619
+ async swap(inputCoin, outputCoin, amount, slippage = 0.5) {
1620
+ throw Error(`swap method doesn't exist for pool ${this.name} (id: ${this.name})`);
1621
+ }
3029
1622
  // ---------------- SWAP WRAPPED ----------------
3030
- PoolTemplate.prototype._swapWrappedExpected = function (i, j, _amount) {
3031
- return __awaiter(this, void 0, void 0, function () {
3032
- return __generator(this, function (_c) {
3033
- switch (_c.label) {
3034
- case 0: return [4 /*yield*/, curve_1.curve.contracts[this.address].contract.get_dy(i, j, _amount, curve_1.curve.constantOptions)];
3035
- case 1: return [2 /*return*/, _c.sent()];
3036
- }
3037
- });
3038
- });
3039
- };
1623
+ async _swapWrappedExpected(i, j, _amount) {
1624
+ return await curve.contracts[this.address].contract.get_dy(i, j, _amount, curve.constantOptions);
1625
+ }
3040
1626
  // OVERRIDE
3041
- PoolTemplate.prototype.swapWrappedExpected = function (inputCoin, outputCoin, amount) {
3042
- return __awaiter(this, void 0, void 0, function () {
3043
- return __generator(this, function (_c) {
3044
- throw Error("swapWrappedExpected method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
3045
- });
3046
- });
3047
- };
3048
- PoolTemplate.prototype.swapWrappedPriceImpact = function (inputCoin, outputCoin, amount) {
3049
- return __awaiter(this, void 0, void 0, function () {
3050
- var i, j, _c, inputCoinDecimals, outputCoinDecimals, _amount, _output, smallAmountIntBN, amountIntBN, _smallAmount, _smallOutput, priceImpactBN;
3051
- return __generator(this, function (_d) {
3052
- switch (_d.label) {
3053
- case 0:
3054
- if (this.isPlain || this.isFake) {
3055
- throw Error("swapWrappedPriceImpact method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
3056
- }
3057
- i = this._getCoinIdx(inputCoin, false);
3058
- j = this._getCoinIdx(outputCoin, false);
3059
- _c = [this.wrappedDecimals[i], this.wrappedDecimals[j]], inputCoinDecimals = _c[0], outputCoinDecimals = _c[1];
3060
- _amount = (0, utils_1.parseUnits)(amount, inputCoinDecimals);
3061
- return [4 /*yield*/, this._swapWrappedExpected(i, j, _amount)];
3062
- case 1:
3063
- _output = _d.sent();
3064
- smallAmountIntBN = (0, utils_1._get_small_x)(_amount, _output, inputCoinDecimals, outputCoinDecimals);
3065
- amountIntBN = (0, utils_1.toBN)(_amount, 0);
3066
- if (smallAmountIntBN.gte(amountIntBN))
3067
- return [2 /*return*/, 0];
3068
- _smallAmount = (0, utils_1.fromBN)(smallAmountIntBN.div(Math.pow(10, inputCoinDecimals)), inputCoinDecimals);
3069
- return [4 /*yield*/, this._swapWrappedExpected(i, j, _smallAmount)];
3070
- case 2:
3071
- _smallOutput = _d.sent();
3072
- priceImpactBN = (0, utils_1._get_price_impact)(_amount, _output, _smallAmount, _smallOutput, inputCoinDecimals, outputCoinDecimals);
3073
- return [2 /*return*/, Number((0, utils_1._cutZeros)(priceImpactBN.toFixed(4)))];
3074
- }
3075
- });
3076
- });
3077
- };
1627
+ async swapWrappedExpected(inputCoin, outputCoin, amount) {
1628
+ throw Error(`swapWrappedExpected method doesn't exist for pool ${this.name} (id: ${this.name})`);
1629
+ }
1630
+ async swapWrappedPriceImpact(inputCoin, outputCoin, amount) {
1631
+ if (this.isPlain || this.isFake) {
1632
+ throw Error(`swapWrappedPriceImpact method doesn't exist for pool ${this.name} (id: ${this.name})`);
1633
+ }
1634
+ const i = this._getCoinIdx(inputCoin, false);
1635
+ const j = this._getCoinIdx(outputCoin, false);
1636
+ const [inputCoinDecimals, outputCoinDecimals] = [this.wrappedDecimals[i], this.wrappedDecimals[j]];
1637
+ const _amount = parseUnits(amount, inputCoinDecimals);
1638
+ const _output = await this._swapWrappedExpected(i, j, _amount);
1639
+ const smallAmountIntBN = _get_small_x(_amount, _output, inputCoinDecimals, outputCoinDecimals);
1640
+ const amountIntBN = toBN(_amount, 0);
1641
+ if (smallAmountIntBN.gte(amountIntBN))
1642
+ return 0;
1643
+ const _smallAmount = fromBN(smallAmountIntBN.div(10 ** inputCoinDecimals), inputCoinDecimals);
1644
+ const _smallOutput = await this._swapWrappedExpected(i, j, _smallAmount);
1645
+ const priceImpactBN = _get_price_impact(_amount, _output, _smallAmount, _smallOutput, inputCoinDecimals, outputCoinDecimals);
1646
+ return Number(_cutZeros(priceImpactBN.toFixed(4)));
1647
+ }
3078
1648
  // OVERRIDE
3079
- PoolTemplate.prototype.swapWrappedIsApproved = function (inputCoin, amount) {
3080
- return __awaiter(this, void 0, void 0, function () {
3081
- return __generator(this, function (_c) {
3082
- throw Error("swapWrappedIsApproved method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
3083
- });
3084
- });
3085
- };
1649
+ async swapWrappedIsApproved(inputCoin, amount) {
1650
+ throw Error(`swapWrappedIsApproved method doesn't exist for pool ${this.name} (id: ${this.name})`);
1651
+ }
3086
1652
  // OVERRIDE
3087
- PoolTemplate.prototype.swapWrappedApproveEstimateGas = function (inputCoin, amount) {
3088
- return __awaiter(this, void 0, void 0, function () {
3089
- return __generator(this, function (_c) {
3090
- throw Error("swapWrappedApprove method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
3091
- });
3092
- });
3093
- };
1653
+ async swapWrappedApproveEstimateGas(inputCoin, amount) {
1654
+ throw Error(`swapWrappedApprove method doesn't exist for pool ${this.name} (id: ${this.name})`);
1655
+ }
3094
1656
  // OVERRIDE
3095
- PoolTemplate.prototype.swapWrappedApprove = function (inputCoin, amount) {
3096
- return __awaiter(this, void 0, void 0, function () {
3097
- return __generator(this, function (_c) {
3098
- throw Error("swapWrappedApprove method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
3099
- });
3100
- });
3101
- };
1657
+ async swapWrappedApprove(inputCoin, amount) {
1658
+ throw Error(`swapWrappedApprove method doesn't exist for pool ${this.name} (id: ${this.name})`);
1659
+ }
3102
1660
  // OVERRIDE
3103
- PoolTemplate.prototype.swapWrappedEstimateGas = function (inputCoin, outputCoin, amount) {
3104
- return __awaiter(this, void 0, void 0, function () {
3105
- return __generator(this, function (_c) {
3106
- throw Error("swapWrapped method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
3107
- });
3108
- });
3109
- };
1661
+ async swapWrappedEstimateGas(inputCoin, outputCoin, amount) {
1662
+ throw Error(`swapWrapped method doesn't exist for pool ${this.name} (id: ${this.name})`);
1663
+ }
3110
1664
  // OVERRIDE
3111
- PoolTemplate.prototype.swapWrapped = function (inputCoin, outputCoin, amount, slippage) {
3112
- if (slippage === void 0) { slippage = 0.5; }
3113
- return __awaiter(this, void 0, void 0, function () {
3114
- return __generator(this, function (_c) {
3115
- throw Error("swapWrapped method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, ")"));
3116
- });
3117
- });
3118
- };
3119
- return PoolTemplate;
3120
- }());
3121
- exports.PoolTemplate = PoolTemplate;
1665
+ async swapWrapped(inputCoin, outputCoin, amount, slippage = 0.5) {
1666
+ throw Error(`swapWrapped method doesn't exist for pool ${this.name} (id: ${this.name})`);
1667
+ }
1668
+ }