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