@curvefi/llamalend-api 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/llamalend.js CHANGED
@@ -1,14 +1,3 @@
1
- var __assign = (this && this.__assign) || function () {
2
- __assign = Object.assign || function(t) {
3
- for (var s, i = 1, n = arguments.length; i < n; i++) {
4
- s = arguments[i];
5
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
- t[p] = s[p];
7
- }
8
- return t;
9
- };
10
- return __assign.apply(this, arguments);
11
- };
12
1
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13
2
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
14
3
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -18,42 +7,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
18
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
19
8
  });
20
9
  };
21
- var __generator = (this && this.__generator) || function (thisArg, body) {
22
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
23
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
24
- function verb(n) { return function (v) { return step([n, v]); }; }
25
- function step(op) {
26
- if (f) throw new TypeError("Generator is already executing.");
27
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
28
- 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;
29
- if (y = 0, t) op = [op[0] & 2, t.value];
30
- switch (op[0]) {
31
- case 0: case 1: t = op; break;
32
- case 4: _.label++; return { value: op[1], done: false };
33
- case 5: _.label++; y = op[1]; op = [0]; continue;
34
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
35
- default:
36
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
37
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
38
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
39
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
40
- if (t[2]) _.ops.pop();
41
- _.trys.pop(); continue;
42
- }
43
- op = body.call(thisArg, _);
44
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
45
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
46
- }
47
- };
48
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
49
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
50
- if (ar || !(i in from)) {
51
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
52
- ar[i] = from[i];
53
- }
54
- }
55
- return to.concat(ar || Array.prototype.slice.call(from));
56
- };
57
10
  import { ethers, Contract, AbstractProvider } from "ethers";
58
11
  import { Provider as MulticallProvider, Contract as MulticallContract } from '@curvefi/ethcall';
59
12
  // OneWayMarket ABIs
@@ -91,7 +44,7 @@ import { createCall, handleMultiCallResponse } from "./utils.js";
91
44
  import { cacheKey, cacheStats } from "./cache/index.js";
92
45
  import { _getMarketsData } from "./external-api.js";
93
46
  import { extractDecimals } from "./constants/utils.js";
94
- export var NETWORK_CONSTANTS = {
47
+ export const NETWORK_CONSTANTS = {
95
48
  1: {
96
49
  NAME: 'ethereum',
97
50
  ALIASES: ALIASES_ETHEREUM,
@@ -175,301 +128,220 @@ export var NETWORK_CONSTANTS = {
175
128
  COINS: COINS_AURORA,
176
129
  },
177
130
  };
178
- var Llamalend = /** @class */ (function () {
179
- function Llamalend() {
180
- var _this = this;
181
- this.getLendMarketList = function () { return Object.keys(_this.constants.ONE_WAY_MARKETS); };
182
- this.getMintMarketList = function () { return Object.keys(_this.constants.LLAMMAS); };
183
- this.getFactoryMarketData = function () { return __awaiter(_this, void 0, void 0, function () {
184
- var factory, factoryContract, markets_count, callsMap, calls, _loop_1, i, res;
185
- return __generator(this, function (_a) {
186
- switch (_a.label) {
187
- case 0:
188
- factory = this.contracts[this.constants.ALIASES['one_way_factory']];
189
- factoryContract = this.contracts[this.constants.ALIASES['one_way_factory']].contract;
190
- return [4 /*yield*/, factoryContract.market_count()];
191
- case 1:
192
- markets_count = _a.sent();
193
- callsMap = ['names', 'amms', 'controllers', 'borrowed_tokens', 'collateral_tokens', 'monetary_policies', 'vaults', 'gauges'];
194
- calls = [];
195
- _loop_1 = function (i) {
196
- callsMap.forEach(function (item) {
197
- calls.push(createCall(factory, item, [i]));
198
- });
199
- };
200
- for (i = 0; i < markets_count; i++) {
201
- _loop_1(i);
202
- }
203
- return [4 /*yield*/, this.multicallProvider.all(calls)];
204
- case 2:
205
- res = (_a.sent()).map(function (addr) { return addr.toLowerCase(); });
206
- return [2 /*return*/, handleMultiCallResponse(callsMap, res)];
207
- }
131
+ class Llamalend {
132
+ constructor() {
133
+ this.getLendMarketList = () => Object.keys(this.constants.ONE_WAY_MARKETS);
134
+ this.getMintMarketList = () => Object.keys(this.constants.LLAMMAS);
135
+ this.getFactoryMarketData = () => __awaiter(this, void 0, void 0, function* () {
136
+ const factory = this.contracts[this.constants.ALIASES['one_way_factory']];
137
+ const factoryContract = this.contracts[this.constants.ALIASES['one_way_factory']].contract;
138
+ const markets_count = yield factoryContract.market_count();
139
+ const callsMap = ['names', 'amms', 'controllers', 'borrowed_tokens', 'collateral_tokens', 'monetary_policies', 'vaults', 'gauges'];
140
+ const calls = [];
141
+ for (let i = 0; i < markets_count; i++) {
142
+ callsMap.forEach((item) => {
143
+ calls.push(createCall(factory, item, [i]));
144
+ });
145
+ }
146
+ const res = (yield this.multicallProvider.all(calls)).map((addr) => addr.toLowerCase());
147
+ return handleMultiCallResponse(callsMap, res);
148
+ });
149
+ this.getFactoryMarketDataByAPI = () => __awaiter(this, void 0, void 0, function* () {
150
+ const apiData = (yield _getMarketsData(this.constants.NETWORK_NAME)).lendingVaultData;
151
+ const result = {
152
+ names: [],
153
+ amms: [],
154
+ controllers: [],
155
+ borrowed_tokens: [],
156
+ collateral_tokens: [],
157
+ monetary_policies: [],
158
+ vaults: [],
159
+ gauges: [],
160
+ };
161
+ apiData.forEach((market) => {
162
+ var _a;
163
+ result.names.push(market.name);
164
+ result.amms.push(market.ammAddress.toLowerCase());
165
+ result.controllers.push(market.controllerAddress.toLowerCase());
166
+ result.borrowed_tokens.push(market.assets.borrowed.address.toLowerCase());
167
+ result.collateral_tokens.push(market.assets.collateral.address.toLowerCase());
168
+ result.monetary_policies.push(market.monetaryPolicyAddress.toLowerCase());
169
+ result.vaults.push(market.address.toLowerCase());
170
+ result.gauges.push(((_a = market.gaugeAddress) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || this.constants.ZERO_ADDRESS);
208
171
  });
209
- }); };
210
- this.getFactoryMarketDataByAPI = function () { return __awaiter(_this, void 0, void 0, function () {
211
- var apiData, result;
212
- var _this = this;
213
- return __generator(this, function (_a) {
214
- switch (_a.label) {
215
- case 0: return [4 /*yield*/, _getMarketsData(this.constants.NETWORK_NAME)];
216
- case 1:
217
- apiData = (_a.sent()).lendingVaultData;
218
- result = {
219
- names: [],
220
- amms: [],
221
- controllers: [],
222
- borrowed_tokens: [],
223
- collateral_tokens: [],
224
- monetary_policies: [],
225
- vaults: [],
226
- gauges: [],
172
+ return result;
173
+ });
174
+ this.getCoins = (collateral_tokens_1, borrowed_tokens_1, ...args_1) => __awaiter(this, [collateral_tokens_1, borrowed_tokens_1, ...args_1], void 0, function* (collateral_tokens, borrowed_tokens, useApi = false) {
175
+ const coins = new Set([...collateral_tokens, ...borrowed_tokens]);
176
+ const COINS_DATA = {};
177
+ if (useApi) {
178
+ const apiData = (yield _getMarketsData(this.constants.NETWORK_NAME)).lendingVaultData;
179
+ apiData.forEach((market) => {
180
+ const borrowedCoin = market.assets.borrowed;
181
+ const collateralCoin = market.assets.collateral;
182
+ if (coins.has(borrowedCoin.address)) {
183
+ this.setContract(borrowedCoin.address, ERC20ABI);
184
+ COINS_DATA[borrowedCoin.address] = {
185
+ address: borrowedCoin.address,
186
+ decimals: borrowedCoin.decimals,
187
+ name: borrowedCoin.symbol,
188
+ symbol: borrowedCoin.symbol,
227
189
  };
228
- apiData.forEach(function (market) {
229
- var _a;
230
- result.names.push(market.name);
231
- result.amms.push(market.ammAddress.toLowerCase());
232
- result.controllers.push(market.controllerAddress.toLowerCase());
233
- result.borrowed_tokens.push(market.assets.borrowed.address.toLowerCase());
234
- result.collateral_tokens.push(market.assets.collateral.address.toLowerCase());
235
- result.monetary_policies.push(market.monetaryPolicyAddress.toLowerCase());
236
- result.vaults.push(market.address.toLowerCase());
237
- result.gauges.push(((_a = market.gaugeAddress) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || _this.constants.ZERO_ADDRESS);
238
- });
239
- return [2 /*return*/, result];
240
- }
241
- });
242
- }); };
243
- this.getCoins = function (collateral_tokens, borrowed_tokens, useApi) {
244
- if (useApi === void 0) { useApi = false; }
245
- return __awaiter(_this, void 0, void 0, function () {
246
- var coins, COINS_DATA, apiData, calls_1, callsMap_1, res, _a, name_1, decimals_1, symbol_1;
247
- var _this = this;
248
- return __generator(this, function (_b) {
249
- switch (_b.label) {
250
- case 0:
251
- coins = new Set(__spreadArray(__spreadArray([], collateral_tokens, true), borrowed_tokens, true));
252
- COINS_DATA = {};
253
- if (!useApi) return [3 /*break*/, 2];
254
- return [4 /*yield*/, _getMarketsData(this.constants.NETWORK_NAME)];
255
- case 1:
256
- apiData = (_b.sent()).lendingVaultData;
257
- apiData.forEach(function (market) {
258
- var borrowedCoin = market.assets.borrowed;
259
- var collateralCoin = market.assets.collateral;
260
- if (coins.has(borrowedCoin.address)) {
261
- _this.setContract(borrowedCoin.address, ERC20ABI);
262
- COINS_DATA[borrowedCoin.address] = {
263
- address: borrowedCoin.address,
264
- decimals: borrowedCoin.decimals,
265
- name: borrowedCoin.symbol,
266
- symbol: borrowedCoin.symbol,
267
- };
268
- }
269
- if (coins.has(collateralCoin.address)) {
270
- _this.setContract(collateralCoin.address, ERC20ABI);
271
- COINS_DATA[collateralCoin.address] = {
272
- address: collateralCoin.address,
273
- decimals: collateralCoin.decimals,
274
- name: collateralCoin.symbol,
275
- symbol: collateralCoin.symbol,
276
- };
277
- }
278
- });
279
- return [3 /*break*/, 4];
280
- case 2:
281
- calls_1 = [];
282
- callsMap_1 = ['name', 'decimals', 'symbol'];
283
- coins.forEach(function (coin) {
284
- _this.setContract(coin, ERC20ABI);
285
- callsMap_1.forEach(function (item) {
286
- calls_1.push(createCall(_this.contracts[coin], item, []));
287
- });
288
- });
289
- return [4 /*yield*/, this.multicallProvider.all(calls_1)];
290
- case 3:
291
- res = _b.sent();
292
- _a = handleMultiCallResponse(callsMap_1, res), name_1 = _a.name, decimals_1 = _a.decimals, symbol_1 = _a.symbol;
293
- Array.from(coins).forEach(function (coin, index) {
294
- COINS_DATA[coin] = {
295
- address: coin,
296
- decimals: Number(decimals_1[index]),
297
- name: name_1[index],
298
- symbol: symbol_1[index],
299
- };
300
- });
301
- _b.label = 4;
302
- case 4: return [2 /*return*/, COINS_DATA];
303
190
  }
304
- });
305
- });
306
- };
307
- this.fetchStats = function (amms, controllers, vaults, borrowed_tokens, collateral_tokens) { return __awaiter(_this, void 0, void 0, function () {
308
- var marketCount, calls, i, res, i;
309
- return __generator(this, function (_a) {
310
- switch (_a.label) {
311
- case 0:
312
- cacheStats.clear();
313
- marketCount = controllers.length;
314
- calls = [];
315
- for (i = 0; i < marketCount; i++) {
316
- calls.push(createCall(this.contracts[controllers[i]], 'total_debt', []));
317
- calls.push(createCall(this.contracts[vaults[i]], 'totalAssets', [controllers[i]]));
318
- calls.push(createCall(this.contracts[borrowed_tokens[i]], 'balanceOf', [controllers[i]]));
319
- calls.push(createCall(this.contracts[amms[i]], 'rate', []));
320
- calls.push(createCall(this.contracts[borrowed_tokens[i]], 'balanceOf', [amms[i]]));
321
- calls.push(createCall(this.contracts[amms[i]], 'admin_fees_x', []));
322
- calls.push(createCall(this.contracts[amms[i]], 'admin_fees_y', []));
323
- calls.push(createCall(this.contracts[collateral_tokens[i]], 'balanceOf', [amms[i]]));
324
- }
325
- return [4 /*yield*/, this.multicallProvider.all(calls)];
326
- case 1:
327
- res = _a.sent();
328
- for (i = 0; i < marketCount; i++) {
329
- cacheStats.set(cacheKey(controllers[i], 'total_debt'), res[(i * 8) + 0]);
330
- cacheStats.set(cacheKey(vaults[i], 'totalAssets', controllers[i]), res[(i * 8) + 1]);
331
- cacheStats.set(cacheKey(borrowed_tokens[i], 'balanceOf', controllers[i]), res[(i * 8) + 2]);
332
- cacheStats.set(cacheKey(amms[i], 'rate'), res[(i * 8) + 3]);
333
- cacheStats.set(cacheKey(borrowed_tokens[i], 'balanceOf', amms[i]), res[(i * 8) + 4]);
334
- cacheStats.set(cacheKey(amms[i], 'admin_fees_x'), res[(i * 8) + 5]);
335
- cacheStats.set(cacheKey(amms[i], 'admin_fees_y'), res[(i * 8) + 6]);
336
- cacheStats.set(cacheKey(collateral_tokens[i], 'balanceOf', amms[i]), res[(i * 8) + 7]);
337
- }
338
- return [2 /*return*/];
339
- }
340
- });
341
- }); };
342
- this.fetchLendMarkets = function (useAPI) {
343
- if (useAPI === void 0) { useAPI = true; }
344
- return __awaiter(_this, void 0, void 0, function () {
345
- return __generator(this, function (_a) {
346
- switch (_a.label) {
347
- case 0:
348
- if (!useAPI) return [3 /*break*/, 2];
349
- return [4 /*yield*/, this._fetchOneWayMarketsByAPI()];
350
- case 1:
351
- _a.sent();
352
- return [3 /*break*/, 4];
353
- case 2: return [4 /*yield*/, this._fetchOneWayMarketsByBlockchain()];
354
- case 3:
355
- _a.sent();
356
- _a.label = 4;
357
- case 4: return [2 /*return*/];
191
+ if (coins.has(collateralCoin.address)) {
192
+ this.setContract(collateralCoin.address, ERC20ABI);
193
+ COINS_DATA[collateralCoin.address] = {
194
+ address: collateralCoin.address,
195
+ decimals: collateralCoin.decimals,
196
+ name: collateralCoin.symbol,
197
+ symbol: collateralCoin.symbol,
198
+ };
358
199
  }
359
200
  });
201
+ }
202
+ else {
203
+ const calls = [];
204
+ const callsMap = ['name', 'decimals', 'symbol'];
205
+ coins.forEach((coin) => {
206
+ this.setContract(coin, ERC20ABI);
207
+ callsMap.forEach((item) => {
208
+ calls.push(createCall(this.contracts[coin], item, []));
209
+ });
210
+ });
211
+ const res = yield this.multicallProvider.all(calls);
212
+ const { name, decimals, symbol } = handleMultiCallResponse(callsMap, res);
213
+ Array.from(coins).forEach((coin, index) => {
214
+ COINS_DATA[coin] = {
215
+ address: coin,
216
+ decimals: Number(decimals[index]),
217
+ name: name[index],
218
+ symbol: symbol[index],
219
+ };
220
+ });
221
+ }
222
+ return COINS_DATA;
223
+ });
224
+ this.fetchStats = (amms, controllers, vaults, borrowed_tokens, collateral_tokens) => __awaiter(this, void 0, void 0, function* () {
225
+ cacheStats.clear();
226
+ const marketCount = controllers.length;
227
+ const calls = [];
228
+ for (let i = 0; i < marketCount; i++) {
229
+ calls.push(createCall(this.contracts[controllers[i]], 'total_debt', []));
230
+ calls.push(createCall(this.contracts[vaults[i]], 'totalAssets', [controllers[i]]));
231
+ calls.push(createCall(this.contracts[borrowed_tokens[i]], 'balanceOf', [controllers[i]]));
232
+ calls.push(createCall(this.contracts[amms[i]], 'rate', []));
233
+ calls.push(createCall(this.contracts[borrowed_tokens[i]], 'balanceOf', [amms[i]]));
234
+ calls.push(createCall(this.contracts[amms[i]], 'admin_fees_x', []));
235
+ calls.push(createCall(this.contracts[amms[i]], 'admin_fees_y', []));
236
+ calls.push(createCall(this.contracts[collateral_tokens[i]], 'balanceOf', [amms[i]]));
237
+ }
238
+ const res = yield this.multicallProvider.all(calls);
239
+ for (let i = 0; i < marketCount; i++) {
240
+ cacheStats.set(cacheKey(controllers[i], 'total_debt'), res[(i * 8) + 0]);
241
+ cacheStats.set(cacheKey(vaults[i], 'totalAssets', controllers[i]), res[(i * 8) + 1]);
242
+ cacheStats.set(cacheKey(borrowed_tokens[i], 'balanceOf', controllers[i]), res[(i * 8) + 2]);
243
+ cacheStats.set(cacheKey(amms[i], 'rate'), res[(i * 8) + 3]);
244
+ cacheStats.set(cacheKey(borrowed_tokens[i], 'balanceOf', amms[i]), res[(i * 8) + 4]);
245
+ cacheStats.set(cacheKey(amms[i], 'admin_fees_x'), res[(i * 8) + 5]);
246
+ cacheStats.set(cacheKey(amms[i], 'admin_fees_y'), res[(i * 8) + 6]);
247
+ cacheStats.set(cacheKey(collateral_tokens[i], 'balanceOf', amms[i]), res[(i * 8) + 7]);
248
+ }
249
+ });
250
+ this.fetchLendMarkets = (...args_1) => __awaiter(this, [...args_1], void 0, function* (useAPI = true) {
251
+ if (useAPI) {
252
+ yield this._fetchOneWayMarketsByAPI();
253
+ }
254
+ else {
255
+ yield this._fetchOneWayMarketsByBlockchain();
256
+ }
257
+ });
258
+ this._fetchOneWayMarketsByBlockchain = () => __awaiter(this, void 0, void 0, function* () {
259
+ const { names, amms, controllers, borrowed_tokens, collateral_tokens, monetary_policies, vaults, gauges } = yield this.getFactoryMarketData();
260
+ const COIN_DATA = yield this.getCoins(collateral_tokens, borrowed_tokens);
261
+ for (const c in COIN_DATA) {
262
+ this.constants.DECIMALS[c] = COIN_DATA[c].decimals;
263
+ }
264
+ amms.forEach((amm, index) => {
265
+ this.setContract(amm, LlammaABI);
266
+ this.setContract(controllers[index], ControllerABI);
267
+ this.setContract(monetary_policies[index], MonetaryPolicyABI);
268
+ this.setContract(vaults[index], VaultABI);
269
+ this.setContract(gauges[index], this.chainId === 1 ? GaugeABI : SidechainGaugeABI);
270
+ COIN_DATA[vaults[index]] = {
271
+ address: vaults[index],
272
+ decimals: 18,
273
+ name: "Curve Vault for " + COIN_DATA[borrowed_tokens[index]].name,
274
+ symbol: "cv" + COIN_DATA[borrowed_tokens[index]].symbol,
275
+ };
276
+ COIN_DATA[gauges[index]] = {
277
+ address: gauges[index],
278
+ decimals: 18,
279
+ name: "Curve.fi " + COIN_DATA[borrowed_tokens[index]].name + " Gauge Deposit",
280
+ symbol: "cv" + COIN_DATA[borrowed_tokens[index]].symbol + "-gauge",
281
+ };
282
+ this.constants.DECIMALS[vaults[index]] = 18;
283
+ this.constants.DECIMALS[gauges[index]] = 18;
284
+ this.constants.ONE_WAY_MARKETS[`one-way-market-${index}`] = {
285
+ name: names[index],
286
+ addresses: {
287
+ amm: amms[index],
288
+ controller: controllers[index],
289
+ borrowed_token: borrowed_tokens[index],
290
+ collateral_token: collateral_tokens[index],
291
+ monetary_policy: monetary_policies[index],
292
+ vault: vaults[index],
293
+ gauge: gauges[index],
294
+ },
295
+ borrowed_token: COIN_DATA[borrowed_tokens[index]],
296
+ collateral_token: COIN_DATA[collateral_tokens[index]],
297
+ };
360
298
  });
361
- };
362
- this._fetchOneWayMarketsByBlockchain = function () { return __awaiter(_this, void 0, void 0, function () {
363
- var _a, names, amms, controllers, borrowed_tokens, collateral_tokens, monetary_policies, vaults, gauges, COIN_DATA, c;
364
- var _this = this;
365
- return __generator(this, function (_b) {
366
- switch (_b.label) {
367
- case 0: return [4 /*yield*/, this.getFactoryMarketData()];
368
- case 1:
369
- _a = _b.sent(), names = _a.names, amms = _a.amms, controllers = _a.controllers, borrowed_tokens = _a.borrowed_tokens, collateral_tokens = _a.collateral_tokens, monetary_policies = _a.monetary_policies, vaults = _a.vaults, gauges = _a.gauges;
370
- return [4 /*yield*/, this.getCoins(collateral_tokens, borrowed_tokens)];
371
- case 2:
372
- COIN_DATA = _b.sent();
373
- for (c in COIN_DATA) {
374
- this.constants.DECIMALS[c] = COIN_DATA[c].decimals;
375
- }
376
- amms.forEach(function (amm, index) {
377
- _this.setContract(amm, LlammaABI);
378
- _this.setContract(controllers[index], ControllerABI);
379
- _this.setContract(monetary_policies[index], MonetaryPolicyABI);
380
- _this.setContract(vaults[index], VaultABI);
381
- _this.setContract(gauges[index], _this.chainId === 1 ? GaugeABI : SidechainGaugeABI);
382
- COIN_DATA[vaults[index]] = {
383
- address: vaults[index],
384
- decimals: 18,
385
- name: "Curve Vault for " + COIN_DATA[borrowed_tokens[index]].name,
386
- symbol: "cv" + COIN_DATA[borrowed_tokens[index]].symbol,
387
- };
388
- COIN_DATA[gauges[index]] = {
389
- address: gauges[index],
390
- decimals: 18,
391
- name: "Curve.fi " + COIN_DATA[borrowed_tokens[index]].name + " Gauge Deposit",
392
- symbol: "cv" + COIN_DATA[borrowed_tokens[index]].symbol + "-gauge",
393
- };
394
- _this.constants.DECIMALS[vaults[index]] = 18;
395
- _this.constants.DECIMALS[gauges[index]] = 18;
396
- _this.constants.ONE_WAY_MARKETS["one-way-market-".concat(index)] = {
397
- name: names[index],
398
- addresses: {
399
- amm: amms[index],
400
- controller: controllers[index],
401
- borrowed_token: borrowed_tokens[index],
402
- collateral_token: collateral_tokens[index],
403
- monetary_policy: monetary_policies[index],
404
- vault: vaults[index],
405
- gauge: gauges[index],
406
- },
407
- borrowed_token: COIN_DATA[borrowed_tokens[index]],
408
- collateral_token: COIN_DATA[collateral_tokens[index]],
409
- };
410
- });
411
- return [4 /*yield*/, this.fetchStats(amms, controllers, vaults, borrowed_tokens, collateral_tokens)];
412
- case 3:
413
- _b.sent();
414
- return [2 /*return*/];
415
- }
416
- });
417
- }); };
418
- this._fetchOneWayMarketsByAPI = function () { return __awaiter(_this, void 0, void 0, function () {
419
- var _a, names, amms, controllers, borrowed_tokens, collateral_tokens, monetary_policies, vaults, gauges, COIN_DATA, c;
420
- var _this = this;
421
- return __generator(this, function (_b) {
422
- switch (_b.label) {
423
- case 0: return [4 /*yield*/, this.getFactoryMarketDataByAPI()];
424
- case 1:
425
- _a = _b.sent(), names = _a.names, amms = _a.amms, controllers = _a.controllers, borrowed_tokens = _a.borrowed_tokens, collateral_tokens = _a.collateral_tokens, monetary_policies = _a.monetary_policies, vaults = _a.vaults, gauges = _a.gauges;
426
- return [4 /*yield*/, this.getCoins(collateral_tokens, borrowed_tokens, true)];
427
- case 2:
428
- COIN_DATA = _b.sent();
429
- for (c in COIN_DATA) {
430
- this.constants.DECIMALS[c] = COIN_DATA[c].decimals;
431
- }
432
- amms.forEach(function (amm, index) {
433
- _this.setContract(amms[index], LlammaABI);
434
- _this.setContract(controllers[index], ControllerABI);
435
- _this.setContract(monetary_policies[index], MonetaryPolicyABI);
436
- _this.setContract(vaults[index], VaultABI);
437
- if (gauges[index]) {
438
- _this.setContract(gauges[index], _this.chainId === 1 ? GaugeABI : SidechainGaugeABI);
439
- }
440
- COIN_DATA[vaults[index]] = {
441
- address: vaults[index],
442
- decimals: 18,
443
- name: "Curve Vault for " + COIN_DATA[borrowed_tokens[index]].name,
444
- symbol: "cv" + COIN_DATA[borrowed_tokens[index]].symbol,
445
- };
446
- COIN_DATA[gauges[index]] = {
447
- address: gauges[index],
448
- decimals: 18,
449
- name: "Curve.fi " + COIN_DATA[borrowed_tokens[index]].name + " Gauge Deposit",
450
- symbol: "cv" + COIN_DATA[borrowed_tokens[index]].symbol + "-gauge",
451
- };
452
- _this.constants.DECIMALS[vaults[index]] = 18;
453
- _this.constants.DECIMALS[gauges[index]] = 18;
454
- _this.constants.ONE_WAY_MARKETS["one-way-market-".concat(index)] = {
455
- name: names[index],
456
- addresses: {
457
- amm: amms[index],
458
- controller: controllers[index],
459
- borrowed_token: borrowed_tokens[index],
460
- collateral_token: collateral_tokens[index],
461
- monetary_policy: monetary_policies[index],
462
- vault: vaults[index],
463
- gauge: gauges[index],
464
- },
465
- borrowed_token: COIN_DATA[borrowed_tokens[index]],
466
- collateral_token: COIN_DATA[collateral_tokens[index]],
467
- };
468
- });
469
- return [2 /*return*/];
299
+ yield this.fetchStats(amms, controllers, vaults, borrowed_tokens, collateral_tokens);
300
+ });
301
+ this._fetchOneWayMarketsByAPI = () => __awaiter(this, void 0, void 0, function* () {
302
+ const { names, amms, controllers, borrowed_tokens, collateral_tokens, monetary_policies, vaults, gauges } = yield this.getFactoryMarketDataByAPI();
303
+ const COIN_DATA = yield this.getCoins(collateral_tokens, borrowed_tokens, true);
304
+ for (const c in COIN_DATA) {
305
+ this.constants.DECIMALS[c] = COIN_DATA[c].decimals;
306
+ }
307
+ amms.forEach((amm, index) => {
308
+ this.setContract(amms[index], LlammaABI);
309
+ this.setContract(controllers[index], ControllerABI);
310
+ this.setContract(monetary_policies[index], MonetaryPolicyABI);
311
+ this.setContract(vaults[index], VaultABI);
312
+ if (gauges[index]) {
313
+ this.setContract(gauges[index], this.chainId === 1 ? GaugeABI : SidechainGaugeABI);
470
314
  }
315
+ COIN_DATA[vaults[index]] = {
316
+ address: vaults[index],
317
+ decimals: 18,
318
+ name: "Curve Vault for " + COIN_DATA[borrowed_tokens[index]].name,
319
+ symbol: "cv" + COIN_DATA[borrowed_tokens[index]].symbol,
320
+ };
321
+ COIN_DATA[gauges[index]] = {
322
+ address: gauges[index],
323
+ decimals: 18,
324
+ name: "Curve.fi " + COIN_DATA[borrowed_tokens[index]].name + " Gauge Deposit",
325
+ symbol: "cv" + COIN_DATA[borrowed_tokens[index]].symbol + "-gauge",
326
+ };
327
+ this.constants.DECIMALS[vaults[index]] = 18;
328
+ this.constants.DECIMALS[gauges[index]] = 18;
329
+ this.constants.ONE_WAY_MARKETS[`one-way-market-${index}`] = {
330
+ name: names[index],
331
+ addresses: {
332
+ amm: amms[index],
333
+ controller: controllers[index],
334
+ borrowed_token: borrowed_tokens[index],
335
+ collateral_token: collateral_tokens[index],
336
+ monetary_policy: monetary_policies[index],
337
+ vault: vaults[index],
338
+ gauge: gauges[index],
339
+ },
340
+ borrowed_token: COIN_DATA[borrowed_tokens[index]],
341
+ collateral_token: COIN_DATA[collateral_tokens[index]],
342
+ };
471
343
  });
472
- }); };
344
+ });
473
345
  this.address = '00000'; //COINS.lending.toLowerCase();
474
346
  // @ts-ignore
475
347
  this.provider = null;
@@ -484,7 +356,7 @@ var Llamalend = /** @class */ (function () {
484
356
  this.options = {};
485
357
  this.constants = {
486
358
  ONE_WAY_MARKETS: {},
487
- LLAMMAS: LLAMMAS,
359
+ LLAMMAS,
488
360
  COINS: {},
489
361
  DECIMALS: {},
490
362
  NETWORK_NAME: 'ethereum',
@@ -502,357 +374,282 @@ var Llamalend = /** @class */ (function () {
502
374
  WETH: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2".toLowerCase(),
503
375
  };
504
376
  }
505
- Llamalend.prototype.init = function (providerType, providerSettings, options // gasPrice in Gwei
506
- ) {
507
- var _a;
508
- if (options === void 0) { options = {}; }
509
- return __awaiter(this, void 0, void 0, function () {
510
- var jsonRpcApiProviderOptions, _b, e_1, _c, network, _d, err_1, _i, _e, llamma, monetary_policy_address, _f, _g, pegKeeper, factoryContract, factoryMulticallContract, N1, N2, calls, i, res, collaterals, amms, controllers, _h, collaterals_1, collateral, _j, collaterals_2, collateral, res_1, _k, amms_1, amm, AParams, i, is_eth, _l, collateral_symbol, collateral_decimals, monetary_policy_address, _llammaId, llammaId, j, lendingInstance_1, originalEstimate_1, oldEstimate, newEstimate;
511
- return __generator(this, function (_m) {
512
- switch (_m.label) {
513
- case 0:
514
- // @ts-ignore
515
- this.provider = null;
516
- // @ts-ignore
517
- this.signer = null;
518
- this.signerAddress = "";
519
- this.chainId = 1;
520
- // @ts-ignore
521
- this.multicallProvider = null;
522
- this.contracts = {};
523
- this.feeData = {};
524
- this.constantOptions = { gasLimit: 12000000 };
525
- this.options = {};
526
- this.constants = {
527
- ONE_WAY_MARKETS: {},
528
- LLAMMAS: LLAMMAS,
529
- COINS: {},
530
- DECIMALS: {},
531
- NETWORK_NAME: 'ethereum',
532
- ALIASES: {},
533
- ZERO_ADDRESS: ethers.ZeroAddress,
534
- EXCLUDED_PROTOCOLS_1INCH: "",
535
- FACTORY: "0xC9332fdCB1C491Dcc683bAe86Fe3cb70360738BC".toLowerCase(),
536
- PEG_KEEPERS: [
537
- '0x9201da0d97caaaff53f01b2fb56767c7072de340'.toLowerCase(),
538
- '0xfb726f57d251ab5c731e5c64ed4f5f94351ef9f3'.toLowerCase(),
539
- '0x3fa20eaa107de08b38a8734063d605d5842fe09c'.toLowerCase(),
540
- '0x0a05ff644878b908ef8eb29542aa88c07d9797d3'.toLowerCase(),
541
- '0x503E1Bf274e7a6c64152395aE8eB57ec391F91F8'.toLowerCase(),
542
- ],
543
- WETH: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2".toLowerCase(),
544
- };
545
- if (!(providerType.toLowerCase() === 'JsonRpc'.toLowerCase())) return [3 /*break*/, 6];
546
- providerSettings = providerSettings;
547
- jsonRpcApiProviderOptions = void 0;
548
- if (providerSettings.batchMaxCount) {
549
- jsonRpcApiProviderOptions = {
550
- batchMaxCount: providerSettings.batchMaxCount,
551
- };
552
- }
553
- if (providerSettings.url) {
554
- this.provider = new ethers.JsonRpcProvider(providerSettings.url, undefined, jsonRpcApiProviderOptions);
555
- }
556
- else {
557
- this.provider = new ethers.JsonRpcProvider('http://localhost:8545/', undefined, jsonRpcApiProviderOptions);
558
- }
559
- if (!providerSettings.privateKey) return [3 /*break*/, 1];
560
- this.signer = new ethers.Wallet(providerSettings.privateKey, this.provider);
561
- return [3 /*break*/, 5];
562
- case 1:
563
- if (!!((_a = providerSettings.url) === null || _a === void 0 ? void 0 : _a.startsWith("https://rpc.gnosischain.com"))) return [3 /*break*/, 5];
564
- _m.label = 2;
565
- case 2:
566
- _m.trys.push([2, 4, , 5]);
567
- _b = this;
568
- return [4 /*yield*/, this.provider.getSigner()];
569
- case 3:
570
- _b.signer = _m.sent();
571
- return [3 /*break*/, 5];
572
- case 4:
573
- e_1 = _m.sent();
574
- this.signer = null;
575
- return [3 /*break*/, 5];
576
- case 5: return [3 /*break*/, 9];
577
- case 6:
578
- if (!(providerType.toLowerCase() === 'Web3'.toLowerCase())) return [3 /*break*/, 8];
579
- providerSettings = providerSettings;
580
- this.provider = new ethers.BrowserProvider(providerSettings.externalProvider);
581
- _c = this;
582
- return [4 /*yield*/, this.provider.getSigner()];
583
- case 7:
584
- _c.signer = _m.sent();
585
- return [3 /*break*/, 9];
586
- case 8:
587
- if (providerType.toLowerCase() === 'Infura'.toLowerCase()) {
588
- providerSettings = providerSettings;
589
- this.provider = new ethers.InfuraProvider(providerSettings.network, providerSettings.apiKey);
590
- this.signer = null;
591
- // Alchemy provider
592
- }
593
- else if (providerType.toLowerCase() === 'Alchemy'.toLowerCase()) {
594
- providerSettings = providerSettings;
595
- this.provider = new ethers.AlchemyProvider(providerSettings.network, providerSettings.apiKey);
596
- this.signer = null;
597
- }
598
- else {
599
- throw Error('Wrong providerType');
600
- }
601
- _m.label = 9;
602
- case 9: return [4 /*yield*/, this.provider.getNetwork()];
603
- case 10:
604
- network = _m.sent();
605
- this.chainId = Number(network.chainId) === 133 || Number(network.chainId) === 31337 ? 1 : Number(network.chainId);
606
- console.log("CURVE-LENDING-JS IS CONNECTED TO NETWORK:", { name: network.name.toUpperCase(), chainId: Number(this.chainId) });
607
- if (this.chainId === 42161) {
608
- this.constantOptions = { gasLimit: 1125899906842624 }; // https://arbiscan.io/chart/gaslimit
609
- }
610
- this.constants.NETWORK_NAME = NETWORK_CONSTANTS[this.chainId].NAME;
611
- this.constants.ALIASES = NETWORK_CONSTANTS[this.chainId].ALIASES;
612
- this.constants.COINS = NETWORK_CONSTANTS[this.chainId].COINS;
613
- this.constants.EXCLUDED_PROTOCOLS_1INCH = NETWORK_CONSTANTS[this.chainId].EXCLUDED_PROTOCOLS_1INCH;
614
- this.setContract(this.constants.ALIASES.crv, ERC20ABI);
615
- this.setContract(this.constants.ALIASES.crvUSD, ERC20ABI);
616
- this.setContract(this.constants.ALIASES.st_crvUSD, ERC4626ABI);
617
- this.constants.DECIMALS[this.constants.ALIASES.crv] = 18;
618
- this.constants.DECIMALS[this.constants.ALIASES.crvUSD] = 18;
619
- this.constants.DECIMALS[this.constants.ALIASES.st_crvUSD] = 18;
620
- this.multicallProvider = new MulticallProvider(this.chainId, this.provider);
621
- if (!this.signer) return [3 /*break*/, 15];
622
- _m.label = 11;
623
- case 11:
624
- _m.trys.push([11, 13, , 14]);
625
- _d = this;
626
- return [4 /*yield*/, this.signer.getAddress()];
627
- case 12:
628
- _d.signerAddress = _m.sent();
629
- return [3 /*break*/, 14];
630
- case 13:
631
- err_1 = _m.sent();
377
+ init(providerType_1, providerSettings_1) {
378
+ return __awaiter(this, arguments, void 0, function* (providerType, providerSettings, options = {} // gasPrice in Gwei
379
+ ) {
380
+ var _a;
381
+ // @ts-ignore
382
+ this.provider = null;
383
+ // @ts-ignore
384
+ this.signer = null;
385
+ this.signerAddress = "";
386
+ this.chainId = 1;
387
+ // @ts-ignore
388
+ this.multicallProvider = null;
389
+ this.contracts = {};
390
+ this.feeData = {};
391
+ this.constantOptions = { gasLimit: 12000000 };
392
+ this.options = {};
393
+ this.constants = {
394
+ ONE_WAY_MARKETS: {},
395
+ LLAMMAS,
396
+ COINS: {},
397
+ DECIMALS: {},
398
+ NETWORK_NAME: 'ethereum',
399
+ ALIASES: {},
400
+ ZERO_ADDRESS: ethers.ZeroAddress,
401
+ EXCLUDED_PROTOCOLS_1INCH: "",
402
+ FACTORY: "0xC9332fdCB1C491Dcc683bAe86Fe3cb70360738BC".toLowerCase(),
403
+ PEG_KEEPERS: [
404
+ '0x9201da0d97caaaff53f01b2fb56767c7072de340'.toLowerCase(),
405
+ '0xfb726f57d251ab5c731e5c64ed4f5f94351ef9f3'.toLowerCase(),
406
+ '0x3fa20eaa107de08b38a8734063d605d5842fe09c'.toLowerCase(),
407
+ '0x0a05ff644878b908ef8eb29542aa88c07d9797d3'.toLowerCase(),
408
+ '0x503E1Bf274e7a6c64152395aE8eB57ec391F91F8'.toLowerCase(),
409
+ ],
410
+ WETH: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2".toLowerCase(),
411
+ };
412
+ // JsonRpc provider
413
+ if (providerType.toLowerCase() === 'JsonRpc'.toLowerCase()) {
414
+ providerSettings = providerSettings;
415
+ let jsonRpcApiProviderOptions;
416
+ if (providerSettings.batchMaxCount) {
417
+ jsonRpcApiProviderOptions = {
418
+ batchMaxCount: providerSettings.batchMaxCount,
419
+ };
420
+ }
421
+ if (providerSettings.url) {
422
+ this.provider = new ethers.JsonRpcProvider(providerSettings.url, undefined, jsonRpcApiProviderOptions);
423
+ }
424
+ else {
425
+ this.provider = new ethers.JsonRpcProvider('http://localhost:8545/', undefined, jsonRpcApiProviderOptions);
426
+ }
427
+ if (providerSettings.privateKey) {
428
+ this.signer = new ethers.Wallet(providerSettings.privateKey, this.provider);
429
+ }
430
+ else if (!((_a = providerSettings.url) === null || _a === void 0 ? void 0 : _a.startsWith("https://rpc.gnosischain.com"))) {
431
+ try {
432
+ this.signer = yield this.provider.getSigner();
433
+ }
434
+ catch (_b) {
632
435
  this.signer = null;
633
- return [3 /*break*/, 14];
634
- case 14: return [3 /*break*/, 16];
635
- case 15:
636
- this.signerAddress = '';
637
- _m.label = 16;
638
- case 16:
639
- this.feeData = { gasPrice: options.gasPrice, maxFeePerGas: options.maxFeePerGas, maxPriorityFeePerGas: options.maxPriorityFeePerGas };
640
- return [4 /*yield*/, this.updateFeeData()];
641
- case 17:
642
- _m.sent();
643
- // oneWayMarkets contracts
644
- this.setContract(this.constants.ALIASES['one_way_factory'], OneWayLendingFactoryABI);
645
- this.setContract(this.constants.ALIASES['gauge_controller'], GaugeControllerABI);
646
- this.setContract(this.constants.ALIASES['leverage_zap'], LeverageZapABI);
647
- if (this.chainId === 1) {
648
- this.setContract(this.constants.ALIASES.minter, MinterABI);
649
- this.setContract(this.constants.ALIASES.gauge_factory, GaugeFactoryMainnetABI);
650
- }
651
- else {
652
- if (this.constants.ALIASES.gauge_factory_old && this.constants.ALIASES.gauge_factory_old !== this.constants.ZERO_ADDRESS) {
653
- // set old gauge factory
654
- this.constants.ALIASES.minter_old = this.constants.ALIASES.gauge_factory_old;
655
- this.setContract(this.constants.ALIASES.gauge_factory_old, GaugeFactorySidechainABI);
656
- // set new gauge factory
657
- this.constants.ALIASES.minter = this.constants.ALIASES.gauge_factory;
658
- this.setContract(this.constants.ALIASES.gauge_factory, GaugeFactorySidechainABI);
659
- }
660
- else {
661
- this.constants.ALIASES.minter = this.constants.ALIASES.gauge_factory;
662
- this.setContract(this.constants.ALIASES.gauge_factory, GaugeFactorySidechainABI);
663
- }
664
- }
665
- if (!(this.chainId === 1)) return [3 /*break*/, 22];
666
- this.setContract(this.constants.COINS.crvusd.toLowerCase(), ERC20ABI);
667
- _i = 0, _e = Object.values(this.constants.LLAMMAS);
668
- _m.label = 18;
669
- case 18:
670
- if (!(_i < _e.length)) return [3 /*break*/, 21];
671
- llamma = _e[_i];
672
- this.setContract(llamma.amm_address, llammaABI);
673
- this.setContract(llamma.controller_address, controllerABI);
674
- return [4 /*yield*/, this.contracts[llamma.controller_address].contract.monetary_policy(this.constantOptions)];
675
- case 19:
676
- monetary_policy_address = _m.sent();
677
- llamma.monetary_policy_address = monetary_policy_address.toLowerCase();
678
- this.setContract(llamma.monetary_policy_address, llamma.monetary_policy_abi);
679
- if (llamma.collateral_address === "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee") {
680
- this.setContract(this.constants.WETH, ERC20ABI);
681
- }
682
- else {
683
- this.setContract(llamma.collateral_address, ERC20ABI);
684
- }
685
- this.setContract(llamma.leverage_zap, LeverageZapCrvUSDABI);
686
- this.setContract(llamma.deleverage_zap, DeleverageZapABI);
687
- if (llamma.health_calculator_zap)
688
- this.setContract(llamma.health_calculator_zap, HealthCalculatorZapABI);
689
- _m.label = 20;
690
- case 20:
691
- _i++;
692
- return [3 /*break*/, 18];
693
- case 21:
694
- for (_f = 0, _g = this.constants.PEG_KEEPERS; _f < _g.length; _f++) {
695
- pegKeeper = _g[_f];
696
- this.setContract(pegKeeper, PegKeeper);
697
- }
698
- _m.label = 22;
699
- case 22:
700
- // TODO Put it in a separate method
701
- // Fetch new llammas
702
- this.setContract(this.constants.FACTORY, FactoryABI);
703
- factoryContract = this.contracts[this.constants.FACTORY].contract;
704
- factoryMulticallContract = this.contracts[this.constants.FACTORY].multicallContract;
705
- N1 = Object.keys(this.constants.LLAMMAS).length;
706
- return [4 /*yield*/, factoryContract.n_collaterals(this.constantOptions)];
707
- case 23:
708
- N2 = _m.sent();
709
- calls = [];
710
- for (i = N1; i < N2; i++) {
711
- calls.push(factoryMulticallContract.collaterals(i), factoryMulticallContract.amms(i), factoryMulticallContract.controllers(i));
712
- }
713
- return [4 /*yield*/, this.multicallProvider.all(calls)];
714
- case 24:
715
- res = (_m.sent()).map(function (c) { return c.toLowerCase(); });
716
- collaterals = res.filter(function (a, i) { return i % 3 == 0; });
717
- amms = res.filter(function (a, i) { return i % 3 == 1; });
718
- controllers = res.filter(function (a, i) { return i % 3 == 2; });
719
- if (!(collaterals.length > 0)) return [3 /*break*/, 30];
720
- for (_h = 0, collaterals_1 = collaterals; _h < collaterals_1.length; _h++) {
721
- collateral = collaterals_1[_h];
722
- this.setContract(collateral, ERC20ABI);
723
- }
724
- calls = [];
725
- for (_j = 0, collaterals_2 = collaterals; _j < collaterals_2.length; _j++) {
726
- collateral = collaterals_2[_j];
727
- calls.push(this.contracts[collateral].multicallContract.symbol(), this.contracts[collateral].multicallContract.decimals());
728
- }
729
- return [4 /*yield*/, this.multicallProvider.all(calls)];
730
- case 25:
731
- res_1 = (_m.sent()).map(function (x) {
732
- if (typeof x === "string")
733
- return x.toLowerCase();
734
- return x;
735
- });
736
- calls = [];
737
- for (_k = 0, amms_1 = amms; _k < amms_1.length; _k++) {
738
- amm = amms_1[_k];
739
- this.setContract(amm, llammaABI);
740
- calls.push(this.contracts[amm].multicallContract.A());
741
- }
742
- return [4 /*yield*/, this.multicallProvider.all(calls)];
743
- case 26:
744
- AParams = (_m.sent()).map(function (x) {
745
- return Number(x);
746
- });
747
- i = 0;
748
- _m.label = 27;
749
- case 27:
750
- if (!(i < collaterals.length)) return [3 /*break*/, 30];
751
- is_eth = collaterals[i] === this.constants.WETH;
752
- _l = res_1.splice(0, 2), collateral_symbol = _l[0], collateral_decimals = _l[1];
753
- if (i >= collaterals.length - 3) {
754
- this.setContract(controllers[i], controllerV2ABI);
755
- }
756
- else {
757
- this.setContract(controllers[i], controllerABI);
758
- }
436
+ }
437
+ }
438
+ // Web3 provider
439
+ }
440
+ else if (providerType.toLowerCase() === 'Web3'.toLowerCase()) {
441
+ providerSettings = providerSettings;
442
+ this.provider = new ethers.BrowserProvider(providerSettings.externalProvider);
443
+ this.signer = yield this.provider.getSigner();
444
+ // Infura provider
445
+ }
446
+ else if (providerType.toLowerCase() === 'Infura'.toLowerCase()) {
447
+ providerSettings = providerSettings;
448
+ this.provider = new ethers.InfuraProvider(providerSettings.network, providerSettings.apiKey);
449
+ this.signer = null;
450
+ // Alchemy provider
451
+ }
452
+ else if (providerType.toLowerCase() === 'Alchemy'.toLowerCase()) {
453
+ providerSettings = providerSettings;
454
+ this.provider = new ethers.AlchemyProvider(providerSettings.network, providerSettings.apiKey);
455
+ this.signer = null;
456
+ }
457
+ else {
458
+ throw Error('Wrong providerType');
459
+ }
460
+ const network = yield this.provider.getNetwork();
461
+ this.chainId = Number(network.chainId) === 133 || Number(network.chainId) === 31337 ? 1 : Number(network.chainId);
462
+ console.log("CURVE-LENDING-JS IS CONNECTED TO NETWORK:", { name: network.name.toUpperCase(), chainId: Number(this.chainId) });
463
+ if (this.chainId === 42161) {
464
+ this.constantOptions = { gasLimit: 1125899906842624 }; // https://arbiscan.io/chart/gaslimit
465
+ }
466
+ this.constants.NETWORK_NAME = NETWORK_CONSTANTS[this.chainId].NAME;
467
+ this.constants.ALIASES = NETWORK_CONSTANTS[this.chainId].ALIASES;
468
+ this.constants.COINS = NETWORK_CONSTANTS[this.chainId].COINS;
469
+ this.constants.EXCLUDED_PROTOCOLS_1INCH = NETWORK_CONSTANTS[this.chainId].EXCLUDED_PROTOCOLS_1INCH;
470
+ this.setContract(this.constants.ALIASES.crv, ERC20ABI);
471
+ this.setContract(this.constants.ALIASES.crvUSD, ERC20ABI);
472
+ this.setContract(this.constants.ALIASES.st_crvUSD, ERC4626ABI);
473
+ this.constants.DECIMALS[this.constants.ALIASES.crv] = 18;
474
+ this.constants.DECIMALS[this.constants.ALIASES.crvUSD] = 18;
475
+ this.constants.DECIMALS[this.constants.ALIASES.st_crvUSD] = 18;
476
+ this.multicallProvider = new MulticallProvider(this.chainId, this.provider);
477
+ if (this.signer) {
478
+ try {
479
+ this.signerAddress = yield this.signer.getAddress();
480
+ }
481
+ catch (_c) {
482
+ this.signer = null;
483
+ }
484
+ }
485
+ else {
486
+ this.signerAddress = '';
487
+ }
488
+ this.feeData = { gasPrice: options.gasPrice, maxFeePerGas: options.maxFeePerGas, maxPriorityFeePerGas: options.maxPriorityFeePerGas };
489
+ yield this.updateFeeData();
490
+ // oneWayMarkets contracts
491
+ this.setContract(this.constants.ALIASES['one_way_factory'], OneWayLendingFactoryABI);
492
+ this.setContract(this.constants.ALIASES['gauge_controller'], GaugeControllerABI);
493
+ this.setContract(this.constants.ALIASES['leverage_zap'], LeverageZapABI);
494
+ if (this.chainId === 1) {
495
+ this.setContract(this.constants.ALIASES.minter, MinterABI);
496
+ this.setContract(this.constants.ALIASES.gauge_factory, GaugeFactoryMainnetABI);
497
+ }
498
+ else {
499
+ if (this.constants.ALIASES.gauge_factory_old && this.constants.ALIASES.gauge_factory_old !== this.constants.ZERO_ADDRESS) {
500
+ // set old gauge factory
501
+ this.constants.ALIASES.minter_old = this.constants.ALIASES.gauge_factory_old;
502
+ this.setContract(this.constants.ALIASES.gauge_factory_old, GaugeFactorySidechainABI);
503
+ // set new gauge factory
504
+ this.constants.ALIASES.minter = this.constants.ALIASES.gauge_factory;
505
+ this.setContract(this.constants.ALIASES.gauge_factory, GaugeFactorySidechainABI);
506
+ }
507
+ else {
508
+ this.constants.ALIASES.minter = this.constants.ALIASES.gauge_factory;
509
+ this.setContract(this.constants.ALIASES.gauge_factory, GaugeFactorySidechainABI);
510
+ }
511
+ }
512
+ // crvUSD contracts
513
+ if (this.chainId === 1) {
514
+ this.setContract(this.constants.COINS.crvusd.toLowerCase(), ERC20ABI);
515
+ for (const llamma of Object.values(this.constants.LLAMMAS)) {
516
+ this.setContract(llamma.amm_address, llammaABI);
517
+ this.setContract(llamma.controller_address, controllerABI);
518
+ const monetary_policy_address = yield this.contracts[llamma.controller_address].contract.monetary_policy(this.constantOptions);
519
+ llamma.monetary_policy_address = monetary_policy_address.toLowerCase();
520
+ this.setContract(llamma.monetary_policy_address, llamma.monetary_policy_abi);
521
+ if (llamma.collateral_address === "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee") {
522
+ this.setContract(this.constants.WETH, ERC20ABI);
523
+ }
524
+ else {
525
+ this.setContract(llamma.collateral_address, ERC20ABI);
526
+ }
527
+ this.setContract(llamma.leverage_zap, LeverageZapCrvUSDABI);
528
+ this.setContract(llamma.deleverage_zap, DeleverageZapABI);
529
+ if (llamma.health_calculator_zap)
530
+ this.setContract(llamma.health_calculator_zap, HealthCalculatorZapABI);
531
+ }
532
+ for (const pegKeeper of this.constants.PEG_KEEPERS) {
533
+ this.setContract(pegKeeper, PegKeeper);
534
+ }
535
+ }
536
+ // TODO Put it in a separate method
537
+ // Fetch new llammas
538
+ this.setContract(this.constants.FACTORY, FactoryABI);
539
+ const factoryContract = this.contracts[this.constants.FACTORY].contract;
540
+ const factoryMulticallContract = this.contracts[this.constants.FACTORY].multicallContract;
541
+ const N1 = Object.keys(this.constants.LLAMMAS).length;
542
+ const N2 = yield factoryContract.n_collaterals(this.constantOptions);
543
+ let calls = [];
544
+ for (let i = N1; i < N2; i++) {
545
+ calls.push(factoryMulticallContract.collaterals(i), factoryMulticallContract.amms(i), factoryMulticallContract.controllers(i));
546
+ }
547
+ const res = (yield this.multicallProvider.all(calls)).map((c) => c.toLowerCase());
548
+ const collaterals = res.filter((a, i) => i % 3 == 0);
549
+ const amms = res.filter((a, i) => i % 3 == 1);
550
+ const controllers = res.filter((a, i) => i % 3 == 2);
551
+ if (collaterals.length > 0) {
552
+ for (const collateral of collaterals)
553
+ this.setContract(collateral, ERC20ABI);
554
+ calls = [];
555
+ for (const collateral of collaterals) {
556
+ calls.push(this.contracts[collateral].multicallContract.symbol(), this.contracts[collateral].multicallContract.decimals());
557
+ }
558
+ const res = (yield this.multicallProvider.all(calls)).map((x) => {
559
+ if (typeof x === "string")
560
+ return x.toLowerCase();
561
+ return x;
562
+ });
563
+ calls = [];
564
+ for (const amm of amms) {
565
+ this.setContract(amm, llammaABI);
566
+ calls.push(this.contracts[amm].multicallContract.A());
567
+ }
568
+ const AParams = (yield this.multicallProvider.all(calls)).map((x) => {
569
+ return Number(x);
570
+ });
571
+ for (let i = 0; i < collaterals.length; i++) {
572
+ const is_eth = collaterals[i] === this.constants.WETH;
573
+ const [collateral_symbol, collateral_decimals] = res.splice(0, 2);
574
+ if (i >= collaterals.length - 3) {
575
+ this.setContract(controllers[i], controllerV2ABI);
576
+ }
577
+ else {
759
578
  this.setContract(controllers[i], controllerABI);
760
- return [4 /*yield*/, this.contracts[controllers[i]].contract.monetary_policy(this.constantOptions)];
761
- case 28:
762
- monetary_policy_address = (_m.sent()).toLowerCase();
763
- this.setContract(monetary_policy_address, MonetaryPolicy2ABI);
764
- _llammaId = is_eth ? "eth" : collateral_symbol.toLowerCase();
765
- llammaId = _llammaId;
766
- j = 2;
767
- while (llammaId in this.constants.LLAMMAS)
768
- llammaId = _llammaId + j++;
769
- this.constants.LLAMMAS[llammaId] = {
770
- amm_address: amms[i],
771
- controller_address: controllers[i],
772
- monetary_policy_address: monetary_policy_address,
773
- collateral_address: is_eth ? "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" : collaterals[i],
774
- leverage_zap: "0x0000000000000000000000000000000000000000",
775
- deleverage_zap: "0x0000000000000000000000000000000000000000",
776
- collateral_symbol: is_eth ? "ETH" : collateral_symbol,
777
- collateral_decimals: collateral_decimals,
778
- min_bands: 4,
779
- max_bands: 50,
780
- default_bands: 10,
781
- A: AParams[i],
782
- monetary_policy_abi: MonetaryPolicy2ABI,
783
- };
784
- _m.label = 29;
785
- case 29:
786
- i++;
787
- return [3 /*break*/, 27];
788
- case 30:
789
- this.constants.DECIMALS = extractDecimals(this.constants.LLAMMAS);
790
- this.constants.DECIMALS[this.address] = 18;
791
- if (L2Networks.includes(this.chainId)) {
792
- lendingInstance_1 = this;
793
- lendingInstance_1.setContract(lendingInstance_1.constants.ALIASES.gas_oracle, gasOracleABI);
794
- lendingInstance_1.setContract(lendingInstance_1.constants.ALIASES.gas_oracle_blob, gasOracleBlobABI);
795
- // @ts-ignore
796
- if (AbstractProvider.prototype.originalEstimate) {
797
- // @ts-ignore
798
- AbstractProvider.prototype.estimateGas = AbstractProvider.prototype.originalEstimate;
799
- }
800
- originalEstimate_1 = AbstractProvider.prototype.estimateGas;
801
- oldEstimate = function (arg) {
802
- return __awaiter(this, void 0, void 0, function () {
803
- var originalEstimateFunc, gas;
804
- return __generator(this, function (_a) {
805
- switch (_a.label) {
806
- case 0:
807
- originalEstimateFunc = originalEstimate_1.bind(this);
808
- return [4 /*yield*/, originalEstimateFunc(arg)];
809
- case 1:
810
- gas = _a.sent();
811
- return [2 /*return*/, gas];
812
- }
813
- });
814
- });
815
- };
816
- newEstimate = function (arg) {
817
- return __awaiter(this, void 0, void 0, function () {
818
- var L2EstimateGas, L1GasUsed, L1Fee, L2GasUsed;
819
- return __generator(this, function (_a) {
820
- switch (_a.label) {
821
- case 0:
822
- L2EstimateGas = originalEstimate_1.bind(this);
823
- return [4 /*yield*/, lendingInstance_1.contracts[lendingInstance_1.constants.ALIASES.gas_oracle_blob].contract.getL1GasUsed(arg.data)];
824
- case 1:
825
- L1GasUsed = _a.sent();
826
- return [4 /*yield*/, lendingInstance_1.contracts[lendingInstance_1.constants.ALIASES.gas_oracle_blob].contract.getL1Fee(arg.data)];
827
- case 2:
828
- L1Fee = _a.sent();
829
- lendingInstance_1.L1WeightedGasPrice = Number(L1Fee) / Number(L1GasUsed);
830
- return [4 /*yield*/, L2EstimateGas(arg)];
831
- case 3:
832
- L2GasUsed = _a.sent();
833
- return [2 /*return*/, [L2GasUsed, L1GasUsed]];
834
- }
835
- });
836
- });
837
- };
838
- // @ts-ignore
839
- AbstractProvider.prototype.estimateGas = newEstimate;
840
- // @ts-ignore
841
- AbstractProvider.prototype.originalEstimate = oldEstimate;
842
- }
843
- else {
844
- // @ts-ignore
845
- if (AbstractProvider.prototype.originalEstimate) {
846
- // @ts-ignore
847
- AbstractProvider.prototype.estimateGas = AbstractProvider.prototype.originalEstimate;
848
- }
849
- }
850
- return [2 /*return*/];
579
+ }
580
+ this.setContract(controllers[i], controllerABI);
581
+ const monetary_policy_address = (yield this.contracts[controllers[i]].contract.monetary_policy(this.constantOptions)).toLowerCase();
582
+ this.setContract(monetary_policy_address, MonetaryPolicy2ABI);
583
+ const _llammaId = is_eth ? "eth" : collateral_symbol.toLowerCase();
584
+ let llammaId = _llammaId;
585
+ let j = 2;
586
+ while (llammaId in this.constants.LLAMMAS)
587
+ llammaId = _llammaId + j++;
588
+ this.constants.LLAMMAS[llammaId] = {
589
+ amm_address: amms[i],
590
+ controller_address: controllers[i],
591
+ monetary_policy_address,
592
+ collateral_address: is_eth ? "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" : collaterals[i],
593
+ leverage_zap: "0x0000000000000000000000000000000000000000",
594
+ deleverage_zap: "0x0000000000000000000000000000000000000000",
595
+ collateral_symbol: is_eth ? "ETH" : collateral_symbol,
596
+ collateral_decimals,
597
+ min_bands: 4,
598
+ max_bands: 50,
599
+ default_bands: 10,
600
+ A: AParams[i],
601
+ monetary_policy_abi: MonetaryPolicy2ABI,
602
+ };
851
603
  }
852
- });
604
+ }
605
+ this.constants.DECIMALS = extractDecimals(this.constants.LLAMMAS);
606
+ this.constants.DECIMALS[this.address] = 18;
607
+ if (L2Networks.includes(this.chainId)) {
608
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
609
+ const lendingInstance = this;
610
+ lendingInstance.setContract(lendingInstance.constants.ALIASES.gas_oracle, gasOracleABI);
611
+ lendingInstance.setContract(lendingInstance.constants.ALIASES.gas_oracle_blob, gasOracleBlobABI);
612
+ // @ts-ignore
613
+ if (AbstractProvider.prototype.originalEstimate) {
614
+ // @ts-ignore
615
+ AbstractProvider.prototype.estimateGas = AbstractProvider.prototype.originalEstimate;
616
+ }
617
+ const originalEstimate = AbstractProvider.prototype.estimateGas;
618
+ const oldEstimate = function (arg) {
619
+ return __awaiter(this, void 0, void 0, function* () {
620
+ // @ts-ignore
621
+ const originalEstimateFunc = originalEstimate.bind(this);
622
+ const gas = yield originalEstimateFunc(arg);
623
+ return gas;
624
+ });
625
+ };
626
+ //Override
627
+ const newEstimate = function (arg) {
628
+ return __awaiter(this, void 0, void 0, function* () {
629
+ // @ts-ignore
630
+ const L2EstimateGas = originalEstimate.bind(this);
631
+ const L1GasUsed = yield lendingInstance.contracts[lendingInstance.constants.ALIASES.gas_oracle_blob].contract.getL1GasUsed(arg.data);
632
+ const L1Fee = yield lendingInstance.contracts[lendingInstance.constants.ALIASES.gas_oracle_blob].contract.getL1Fee(arg.data);
633
+ lendingInstance.L1WeightedGasPrice = Number(L1Fee) / Number(L1GasUsed);
634
+ const L2GasUsed = yield L2EstimateGas(arg);
635
+ return [L2GasUsed, L1GasUsed];
636
+ });
637
+ };
638
+ // @ts-ignore
639
+ AbstractProvider.prototype.estimateGas = newEstimate;
640
+ // @ts-ignore
641
+ AbstractProvider.prototype.originalEstimate = oldEstimate;
642
+ }
643
+ else {
644
+ // @ts-ignore
645
+ if (AbstractProvider.prototype.originalEstimate) {
646
+ // @ts-ignore
647
+ AbstractProvider.prototype.estimateGas = AbstractProvider.prototype.originalEstimate;
648
+ }
649
+ }
853
650
  });
854
- };
855
- Llamalend.prototype.setContract = function (address, abi) {
651
+ }
652
+ setContract(address, abi) {
856
653
  if (address === this.constants.ZERO_ADDRESS || address === undefined)
857
654
  return;
858
655
  this.contracts[address] = {
@@ -861,45 +658,36 @@ var Llamalend = /** @class */ (function () {
861
658
  address: address,
862
659
  abi: abi,
863
660
  };
864
- };
865
- Llamalend.prototype.setCustomFeeData = function (customFeeData) {
866
- this.feeData = __assign(__assign({}, this.feeData), customFeeData);
867
- };
868
- Llamalend.prototype.formatUnits = function (value, unit) {
661
+ }
662
+ setCustomFeeData(customFeeData) {
663
+ this.feeData = Object.assign(Object.assign({}, this.feeData), customFeeData);
664
+ }
665
+ formatUnits(value, unit) {
869
666
  return ethers.formatUnits(value, unit);
870
- };
871
- Llamalend.prototype.parseUnits = function (value, unit) {
667
+ }
668
+ parseUnits(value, unit) {
872
669
  return ethers.parseUnits(value, unit);
873
- };
874
- Llamalend.prototype.updateFeeData = function () {
875
- return __awaiter(this, void 0, void 0, function () {
876
- var feeData;
877
- return __generator(this, function (_a) {
878
- switch (_a.label) {
879
- case 0: return [4 /*yield*/, this.provider.getFeeData()];
880
- case 1:
881
- feeData = _a.sent();
882
- if (feeData.maxFeePerGas === null || feeData.maxPriorityFeePerGas === null) {
883
- delete this.options.maxFeePerGas;
884
- delete this.options.maxPriorityFeePerGas;
885
- this.options.gasPrice = this.feeData.gasPrice !== undefined ?
886
- this.parseUnits(this.feeData.gasPrice.toString(), "gwei") :
887
- (feeData.gasPrice || this.parseUnits("20", "gwei"));
888
- }
889
- else {
890
- delete this.options.gasPrice;
891
- this.options.maxFeePerGas = this.feeData.maxFeePerGas !== undefined ?
892
- this.parseUnits(this.feeData.maxFeePerGas.toString(), "gwei") :
893
- feeData.maxFeePerGas;
894
- this.options.maxPriorityFeePerGas = this.feeData.maxPriorityFeePerGas !== undefined ?
895
- this.parseUnits(this.feeData.maxPriorityFeePerGas.toString(), "gwei") :
896
- feeData.maxPriorityFeePerGas;
897
- }
898
- return [2 /*return*/];
899
- }
900
- });
670
+ }
671
+ updateFeeData() {
672
+ return __awaiter(this, void 0, void 0, function* () {
673
+ const feeData = yield this.provider.getFeeData();
674
+ if (feeData.maxFeePerGas === null || feeData.maxPriorityFeePerGas === null) {
675
+ delete this.options.maxFeePerGas;
676
+ delete this.options.maxPriorityFeePerGas;
677
+ this.options.gasPrice = this.feeData.gasPrice !== undefined ?
678
+ this.parseUnits(this.feeData.gasPrice.toString(), "gwei") :
679
+ (feeData.gasPrice || this.parseUnits("20", "gwei"));
680
+ }
681
+ else {
682
+ delete this.options.gasPrice;
683
+ this.options.maxFeePerGas = this.feeData.maxFeePerGas !== undefined ?
684
+ this.parseUnits(this.feeData.maxFeePerGas.toString(), "gwei") :
685
+ feeData.maxFeePerGas;
686
+ this.options.maxPriorityFeePerGas = this.feeData.maxPriorityFeePerGas !== undefined ?
687
+ this.parseUnits(this.feeData.maxPriorityFeePerGas.toString(), "gwei") :
688
+ feeData.maxPriorityFeePerGas;
689
+ }
901
690
  });
902
- };
903
- return Llamalend;
904
- }());
905
- export var llamalend = new Llamalend();
691
+ }
692
+ }
693
+ export const llamalend = new Llamalend();