@curvefi/llamalend-api 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/.eslintrc.json +40 -0
  2. package/.github/workflows/lint.yml +15 -0
  3. package/.github/workflows/publish.yml +55 -0
  4. package/LICENSE +21 -0
  5. package/README.md +1976 -0
  6. package/lib/cache/index.d.ts +14 -0
  7. package/lib/cache/index.js +31 -0
  8. package/lib/constants/L2Networks.d.ts +1 -0
  9. package/lib/constants/L2Networks.js +1 -0
  10. package/lib/constants/abis/Controller.json +1027 -0
  11. package/lib/constants/abis/ERC20.json +222 -0
  12. package/lib/constants/abis/ERC4626.json +1674 -0
  13. package/lib/constants/abis/GaugeController.json +794 -0
  14. package/lib/constants/abis/GaugeFactoryMainnet.json +1 -0
  15. package/lib/constants/abis/GaugeFactorySidechain.json +475 -0
  16. package/lib/constants/abis/GaugeV5.json +958 -0
  17. package/lib/constants/abis/LeverageZap.json +35 -0
  18. package/lib/constants/abis/Llamma.json +984 -0
  19. package/lib/constants/abis/Minter.json +1 -0
  20. package/lib/constants/abis/MonetaryPolicy.json +221 -0
  21. package/lib/constants/abis/OneWayLendingFactoryABI.json +899 -0
  22. package/lib/constants/abis/SidechainGauge.json +939 -0
  23. package/lib/constants/abis/Vault.json +721 -0
  24. package/lib/constants/abis/crvUSD/DeleverageZap.json +248 -0
  25. package/lib/constants/abis/crvUSD/Factory.json +514 -0
  26. package/lib/constants/abis/crvUSD/HealthCalculatorZap.json +54 -0
  27. package/lib/constants/abis/crvUSD/LeverageZap.json +312 -0
  28. package/lib/constants/abis/crvUSD/MonetaryPolicy.json +294 -0
  29. package/lib/constants/abis/crvUSD/MonetaryPolicy2.json +299 -0
  30. package/lib/constants/abis/crvUSD/PegKeeper.json +411 -0
  31. package/lib/constants/abis/crvUSD/controller.json +991 -0
  32. package/lib/constants/abis/crvUSD/llamma.json +984 -0
  33. package/lib/constants/abis/gas_oracle_optimism.json +149 -0
  34. package/lib/constants/abis/gas_oracle_optimism_blob.json +203 -0
  35. package/lib/constants/aliases.d.ts +16 -0
  36. package/lib/constants/aliases.js +124 -0
  37. package/lib/constants/coins.d.ts +16 -0
  38. package/lib/constants/coins.js +24 -0
  39. package/lib/constants/llammas.d.ts +2 -0
  40. package/lib/constants/llammas.js +96 -0
  41. package/lib/constants/utils.d.ts +4 -0
  42. package/lib/constants/utils.js +27 -0
  43. package/lib/external-api.d.ts +13 -0
  44. package/lib/external-api.js +436 -0
  45. package/lib/index.d.ts +104 -0
  46. package/lib/index.js +123 -0
  47. package/lib/interfaces.d.ts +228 -0
  48. package/lib/interfaces.js +1 -0
  49. package/lib/lendMarkets/LendMarketTemplate.d.ts +510 -0
  50. package/lib/lendMarkets/LendMarketTemplate.js +4682 -0
  51. package/lib/lendMarkets/index.d.ts +3 -0
  52. package/lib/lendMarkets/index.js +3 -0
  53. package/lib/lendMarkets/lendMarketConstructor.d.ts +2 -0
  54. package/lib/lendMarkets/lendMarketConstructor.js +6 -0
  55. package/lib/llamalend.d.ts +80 -0
  56. package/lib/llamalend.js +878 -0
  57. package/lib/mintMarkets/MintMarketTemplate.d.ts +308 -0
  58. package/lib/mintMarkets/MintMarketTemplate.js +2998 -0
  59. package/lib/mintMarkets/index.d.ts +3 -0
  60. package/lib/mintMarkets/index.js +3 -0
  61. package/lib/mintMarkets/mintMarketConstructor.d.ts +2 -0
  62. package/lib/mintMarkets/mintMarketConstructor.js +4 -0
  63. package/lib/st-crvUSD.d.ts +35 -0
  64. package/lib/st-crvUSD.js +505 -0
  65. package/lib/utils.d.ts +58 -0
  66. package/lib/utils.js +661 -0
  67. package/package.json +42 -0
  68. package/src/cache/index.ts +41 -0
  69. package/src/constants/L2Networks.ts +1 -0
  70. package/src/constants/abis/Controller.json +1027 -0
  71. package/src/constants/abis/ERC20.json +222 -0
  72. package/src/constants/abis/ERC4626.json +1674 -0
  73. package/src/constants/abis/GaugeController.json +794 -0
  74. package/src/constants/abis/GaugeFactoryMainnet.json +1 -0
  75. package/src/constants/abis/GaugeFactorySidechain.json +475 -0
  76. package/src/constants/abis/GaugeV5.json +958 -0
  77. package/src/constants/abis/LeverageZap.json +35 -0
  78. package/src/constants/abis/Llamma.json +984 -0
  79. package/src/constants/abis/Minter.json +1 -0
  80. package/src/constants/abis/MonetaryPolicy.json +221 -0
  81. package/src/constants/abis/OneWayLendingFactoryABI.json +899 -0
  82. package/src/constants/abis/SidechainGauge.json +939 -0
  83. package/src/constants/abis/Vault.json +721 -0
  84. package/src/constants/abis/crvUSD/DeleverageZap.json +248 -0
  85. package/src/constants/abis/crvUSD/ERC20.json +222 -0
  86. package/src/constants/abis/crvUSD/Factory.json +514 -0
  87. package/src/constants/abis/crvUSD/HealthCalculatorZap.json +54 -0
  88. package/src/constants/abis/crvUSD/LeverageZap.json +312 -0
  89. package/src/constants/abis/crvUSD/MonetaryPolicy.json +294 -0
  90. package/src/constants/abis/crvUSD/MonetaryPolicy2.json +299 -0
  91. package/src/constants/abis/crvUSD/PegKeeper.json +411 -0
  92. package/src/constants/abis/crvUSD/controller.json +991 -0
  93. package/src/constants/abis/crvUSD/llamma.json +984 -0
  94. package/src/constants/abis/gas_oracle_optimism.json +149 -0
  95. package/src/constants/abis/gas_oracle_optimism_blob.json +203 -0
  96. package/src/constants/aliases.ts +141 -0
  97. package/src/constants/coins.ts +41 -0
  98. package/src/constants/llammas.ts +99 -0
  99. package/src/constants/utils.ts +33 -0
  100. package/src/external-api.ts +325 -0
  101. package/src/index.ts +128 -0
  102. package/src/interfaces.ts +237 -0
  103. package/src/lendMarkets/LendMarketTemplate.ts +3022 -0
  104. package/src/lendMarkets/index.ts +7 -0
  105. package/src/lendMarkets/lendMarketConstructor.ts +7 -0
  106. package/src/llamalend.ts +785 -0
  107. package/src/mintMarkets/MintMarketTemplate.ts +1781 -0
  108. package/src/mintMarkets/index.ts +7 -0
  109. package/src/mintMarkets/mintMarketConstructor.ts +5 -0
  110. package/src/st-crvUSD.ts +244 -0
  111. package/src/utils.ts +497 -0
  112. package/test/fetch.test.ts +152 -0
  113. package/test/general.test.ts +216 -0
  114. package/test/leverageBorrowMore.test.ts +245 -0
  115. package/test/leverageCreateLoan.test.ts +236 -0
  116. package/test/leverageRepay.test.ts +240 -0
  117. package/test/readme.test.ts +475 -0
  118. package/test/selfLiquidate.test.ts +57 -0
  119. package/test/selfLiquidateCrvUSD.test.ts +54 -0
  120. package/test/st_crvUSD.test.ts +68 -0
  121. package/test/swap.test.ts +62 -0
  122. package/test/swapCrvUSD.test.ts +56 -0
  123. package/test/vault.test.ts +112 -0
  124. package/tsconfig.build.json +10 -0
  125. package/tsconfig.json +72 -0
@@ -0,0 +1,4682 @@
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
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
14
+ return new (P || (P = Promise))(function (resolve, reject) {
15
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
16
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
17
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
18
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
19
+ });
20
+ };
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
+ import memoize from "memoizee";
58
+ import BigNumber from "bignumber.js";
59
+ import { llamalend } from "../llamalend.js";
60
+ import { _getAddress, parseUnits, BN, toBN, fromBN, getBalances, _ensureAllowance, ensureAllowance, hasAllowance, ensureAllowanceEstimateGas, _cutZeros, formatUnits, formatNumber, MAX_ALLOWANCE, MAX_ACTIVE_BAND, _mulBy1_3, _getUsdRate, DIGas, smartNumber, } from "../utils.js";
61
+ import { _getExpectedOdos, _getQuoteOdos, _assembleTxOdos, _getUserCollateral, _getMarketsData } from "../external-api.js";
62
+ import ERC20Abi from '../constants/abis/ERC20.json' assert { type: 'json' };
63
+ import { cacheKey, cacheStats } from "../cache/index.js";
64
+ var DAY = 86400;
65
+ var WEEK = 7 * DAY;
66
+ var LendMarketTemplate = /** @class */ (function () {
67
+ function LendMarketTemplate(id, marketData) {
68
+ var _this = this;
69
+ this.swapDataCache = {};
70
+ this._getMarketId = function () { return Number(_this.id.split("-").slice(-1)[0]); };
71
+ this._calcCrvApr = function (futureWorkingSupplyBN) {
72
+ if (futureWorkingSupplyBN === void 0) { futureWorkingSupplyBN = null; }
73
+ return __awaiter(_this, void 0, void 0, function () {
74
+ var totalLiquidityUSD, inflationRateBN, workingSupplyBN, totalSupplyBN, gaugeContract, lpTokenContract, crvContract, currentWeek, _a, gaugeContract, lpTokenContract, gaugeControllerContract, weightBN, rateBN, crvPrice, baseApyBN, boostedApyBN;
75
+ var _c, _d;
76
+ return __generator(this, function (_e) {
77
+ switch (_e.label) {
78
+ case 0: return [4 /*yield*/, this.vaultTotalLiquidity()];
79
+ case 1:
80
+ totalLiquidityUSD = _e.sent();
81
+ if (Number(totalLiquidityUSD) === 0)
82
+ return [2 /*return*/, [0, 0]];
83
+ if (!(llamalend.chainId !== 1)) return [3 /*break*/, 5];
84
+ gaugeContract = llamalend.contracts[this.addresses.gauge].multicallContract;
85
+ lpTokenContract = llamalend.contracts[this.addresses.vault].multicallContract;
86
+ crvContract = llamalend.contracts[llamalend.constants.ALIASES.crv].contract;
87
+ currentWeek = Math.floor(Date.now() / 1000 / WEEK);
88
+ return [4 /*yield*/, llamalend.multicallProvider.all([
89
+ gaugeContract.inflation_rate(currentWeek),
90
+ gaugeContract.working_supply(),
91
+ lpTokenContract.totalSupply(),
92
+ ])];
93
+ case 2:
94
+ _c = (_e.sent()).map(function (value) { return toBN(value); }), inflationRateBN = _c[0], workingSupplyBN = _c[1], totalSupplyBN = _c[2];
95
+ if (!inflationRateBN.eq(0)) return [3 /*break*/, 4];
96
+ _a = toBN;
97
+ return [4 /*yield*/, crvContract.balanceOf(this.addresses.gauge, llamalend.constantOptions)];
98
+ case 3:
99
+ inflationRateBN = _a.apply(void 0, [_e.sent()]).div(WEEK);
100
+ _e.label = 4;
101
+ case 4: return [3 /*break*/, 7];
102
+ case 5:
103
+ gaugeContract = llamalend.contracts[this.addresses.gauge].multicallContract;
104
+ lpTokenContract = llamalend.contracts[this.addresses.vault].multicallContract;
105
+ gaugeControllerContract = llamalend.contracts[llamalend.constants.ALIASES.gauge_controller].multicallContract;
106
+ weightBN = void 0;
107
+ return [4 /*yield*/, llamalend.multicallProvider.all([
108
+ gaugeContract.inflation_rate(),
109
+ gaugeControllerContract.gauge_relative_weight(this.addresses.gauge),
110
+ gaugeContract.working_supply(),
111
+ lpTokenContract.totalSupply(),
112
+ ])];
113
+ case 6:
114
+ _d = (_e.sent()).map(function (value) { return toBN(value); }), inflationRateBN = _d[0], weightBN = _d[1], workingSupplyBN = _d[2], totalSupplyBN = _d[3];
115
+ inflationRateBN = inflationRateBN.times(weightBN);
116
+ _e.label = 7;
117
+ case 7:
118
+ if (inflationRateBN.eq(0))
119
+ return [2 /*return*/, [0, 0]];
120
+ if (futureWorkingSupplyBN !== null)
121
+ workingSupplyBN = futureWorkingSupplyBN;
122
+ rateBN = inflationRateBN.times(31536000).div(workingSupplyBN).times(totalSupplyBN).div(Number(totalLiquidityUSD)).times(0.4);
123
+ return [4 /*yield*/, _getUsdRate(llamalend.constants.ALIASES.crv)];
124
+ case 8:
125
+ crvPrice = _e.sent();
126
+ baseApyBN = rateBN.times(crvPrice);
127
+ boostedApyBN = baseApyBN.times(2.5);
128
+ return [2 /*return*/, [baseApyBN.times(100).toNumber(), boostedApyBN.times(100).toNumber()]];
129
+ }
130
+ });
131
+ });
132
+ };
133
+ this.vaultRewardTokens = memoize(function (useApi) {
134
+ if (useApi === void 0) { useApi = true; }
135
+ return __awaiter(_this, void 0, void 0, function () {
136
+ var gaugeContract, gaugeMulticallContract, rewardCount, _a, _c, _d, tokenCalls, i, tokens, tokenInfoCalls, _e, tokens_1, token, tokenMulticallContract, tokenInfo, i;
137
+ return __generator(this, function (_f) {
138
+ switch (_f.label) {
139
+ case 0:
140
+ if (this.addresses.gauge === llamalend.constants.ZERO_ADDRESS)
141
+ return [2 /*return*/, []
142
+ // if (useApi) {
143
+ // const rewards = await _getRewardsFromApi();
144
+ // if (!rewards[this.addresses.gauge]) return [];
145
+ // rewards[this.addresses.gauge].forEach((r) => _setContracts(r.tokenAddress, ERC20Abi));
146
+ // return rewards[this.addresses.gauge].map((r) => ({ token: r.tokenAddress, symbol: r.symbol, decimals: Number(r.decimals) }));
147
+ // }
148
+ ];
149
+ gaugeContract = llamalend.contracts[this.addresses.gauge].contract;
150
+ gaugeMulticallContract = llamalend.contracts[this.addresses.gauge].multicallContract;
151
+ _a = Number;
152
+ _d = (_c = llamalend).formatUnits;
153
+ return [4 /*yield*/, gaugeContract.reward_count(llamalend.constantOptions)];
154
+ case 1:
155
+ rewardCount = _a.apply(void 0, [_d.apply(_c, [_f.sent(), 0])]);
156
+ tokenCalls = [];
157
+ for (i = 0; i < rewardCount; i++) {
158
+ tokenCalls.push(gaugeMulticallContract.reward_tokens(i));
159
+ }
160
+ return [4 /*yield*/, llamalend.multicallProvider.all(tokenCalls)];
161
+ case 2:
162
+ tokens = (_f.sent())
163
+ .filter(function (addr) { return addr !== llamalend.constants.ZERO_ADDRESS; })
164
+ .map(function (addr) { return addr.toLowerCase(); })
165
+ .filter(function (addr) { return llamalend.chainId === 1 || addr !== llamalend.constants.COINS.crv; });
166
+ tokenInfoCalls = [];
167
+ for (_e = 0, tokens_1 = tokens; _e < tokens_1.length; _e++) {
168
+ token = tokens_1[_e];
169
+ llamalend.setContract(token, ERC20Abi);
170
+ tokenMulticallContract = llamalend.contracts[token].multicallContract;
171
+ tokenInfoCalls.push(tokenMulticallContract.symbol(), tokenMulticallContract.decimals());
172
+ }
173
+ return [4 /*yield*/, llamalend.multicallProvider.all(tokenInfoCalls)];
174
+ case 3:
175
+ tokenInfo = _f.sent();
176
+ for (i = 0; i < tokens.length; i++) {
177
+ llamalend.constants.DECIMALS[tokens[i]] = Number(tokenInfo[(i * 2) + 1]);
178
+ }
179
+ return [2 /*return*/, tokens.map(function (token, i) { return ({ token: token, symbol: tokenInfo[i * 2], decimals: Number(tokenInfo[(i * 2) + 1]) }); })];
180
+ }
181
+ });
182
+ });
183
+ }, {
184
+ promise: true,
185
+ maxAge: 30 * 60 * 1000, // 30m
186
+ });
187
+ this.vaultRewardsApr = function (useApi) {
188
+ if (useApi === void 0) { useApi = true; }
189
+ return __awaiter(_this, void 0, void 0, function () {
190
+ var response, market, apy, rewardTokens, _a, rewardTokens_1, rewardToken, gaugeContract, lpTokenContract, rewardContract, totalLiquidityUSD, rewardRate, _c, rewardData, _stakedSupply, _totalSupply, stakedSupplyBN, totalSupplyBN, inflationBN, periodFinish, baseApy;
191
+ var _this = this;
192
+ return __generator(this, function (_d) {
193
+ switch (_d.label) {
194
+ case 0:
195
+ if (!useApi) return [3 /*break*/, 2];
196
+ return [4 /*yield*/, _getMarketsData(llamalend.constants.NETWORK_NAME)];
197
+ case 1:
198
+ response = _d.sent();
199
+ market = response.lendingVaultData.find(function (item) { return item.address.toLowerCase() === _this.addresses.vault.toLowerCase(); });
200
+ if (market) {
201
+ return [2 /*return*/, market.gaugeRewards];
202
+ }
203
+ else {
204
+ throw new Error('Market not found in API');
205
+ }
206
+ return [3 /*break*/, 10];
207
+ case 2:
208
+ if (this.addresses.gauge === llamalend.constants.ZERO_ADDRESS)
209
+ return [2 /*return*/, []];
210
+ apy = [];
211
+ return [4 /*yield*/, this.vaultRewardTokens(false)];
212
+ case 3:
213
+ rewardTokens = _d.sent();
214
+ _a = 0, rewardTokens_1 = rewardTokens;
215
+ _d.label = 4;
216
+ case 4:
217
+ if (!(_a < rewardTokens_1.length)) return [3 /*break*/, 9];
218
+ rewardToken = rewardTokens_1[_a];
219
+ gaugeContract = llamalend.contracts[this.addresses.gauge].multicallContract;
220
+ lpTokenContract = llamalend.contracts[this.addresses.vault].multicallContract;
221
+ rewardContract = llamalend.contracts[this.addresses.gauge].multicallContract;
222
+ return [4 /*yield*/, this.vaultTotalLiquidity()];
223
+ case 5:
224
+ totalLiquidityUSD = _d.sent();
225
+ return [4 /*yield*/, _getUsdRate(rewardToken.token)];
226
+ case 6:
227
+ rewardRate = _d.sent();
228
+ return [4 /*yield*/, llamalend.multicallProvider.all([
229
+ rewardContract.reward_data(rewardToken.token),
230
+ gaugeContract.totalSupply(),
231
+ lpTokenContract.totalSupply(),
232
+ ])];
233
+ case 7:
234
+ _c = _d.sent(), rewardData = _c[0], _stakedSupply = _c[1], _totalSupply = _c[2];
235
+ stakedSupplyBN = toBN(_stakedSupply);
236
+ totalSupplyBN = toBN(_totalSupply);
237
+ inflationBN = toBN(rewardData.rate, rewardToken.decimals);
238
+ periodFinish = Number(llamalend.formatUnits(rewardData.period_finish, 0)) * 1000;
239
+ baseApy = periodFinish > Date.now() ?
240
+ inflationBN.times(31536000).times(rewardRate).div(stakedSupplyBN).times(totalSupplyBN).div(Number(totalLiquidityUSD)) :
241
+ BN(0);
242
+ apy.push({
243
+ gaugeAddress: this.addresses.gauge,
244
+ tokenAddress: rewardToken.token,
245
+ symbol: rewardToken.symbol,
246
+ apy: baseApy.times(100).toNumber(),
247
+ });
248
+ _d.label = 8;
249
+ case 8:
250
+ _a++;
251
+ return [3 /*break*/, 4];
252
+ case 9: return [2 /*return*/, apy];
253
+ case 10: return [2 /*return*/];
254
+ }
255
+ });
256
+ });
257
+ };
258
+ // ---------------- STATS ----------------
259
+ this.statsParameters = memoize(function () { return __awaiter(_this, void 0, void 0, function () {
260
+ var llammaContract, controllerContract, calls, _a, _fee, _admin_fee, _liquidation_discount, _loan_discount, _base_price, _A, A, base_price, _c, fee, admin_fee, liquidation_discount, loan_discount;
261
+ return __generator(this, function (_d) {
262
+ switch (_d.label) {
263
+ case 0:
264
+ llammaContract = llamalend.contracts[this.addresses.amm].multicallContract;
265
+ controllerContract = llamalend.contracts[this.addresses.controller].multicallContract;
266
+ calls = [
267
+ llammaContract.fee(),
268
+ llammaContract.admin_fee(),
269
+ controllerContract.liquidation_discount(),
270
+ controllerContract.loan_discount(),
271
+ llammaContract.get_base_price(),
272
+ llammaContract.A(),
273
+ ];
274
+ return [4 /*yield*/, llamalend.multicallProvider.all(calls)];
275
+ case 1:
276
+ _a = _d.sent(), _fee = _a[0], _admin_fee = _a[1], _liquidation_discount = _a[2], _loan_discount = _a[3], _base_price = _a[4], _A = _a[5];
277
+ A = formatUnits(_A, 0);
278
+ base_price = formatUnits(_base_price);
279
+ _c = [_fee, _admin_fee, _liquidation_discount, _loan_discount]
280
+ .map(function (_x) { return formatUnits(_x * BigInt(100)); }), fee = _c[0], admin_fee = _c[1], liquidation_discount = _c[2], loan_discount = _c[3];
281
+ return [2 /*return*/, { fee: fee, admin_fee: admin_fee, liquidation_discount: liquidation_discount, loan_discount: loan_discount, base_price: base_price, A: A }];
282
+ }
283
+ });
284
+ }); }, {
285
+ promise: true,
286
+ maxAge: 5 * 60 * 1000, // 5m
287
+ });
288
+ this._getRate = function (isGetter) {
289
+ if (isGetter === void 0) { isGetter = true; }
290
+ return __awaiter(_this, void 0, void 0, function () {
291
+ var _rate;
292
+ return __generator(this, function (_a) {
293
+ switch (_a.label) {
294
+ case 0:
295
+ if (!isGetter) return [3 /*break*/, 1];
296
+ _rate = cacheStats.get(cacheKey(this.addresses.amm, 'rate'));
297
+ return [3 /*break*/, 3];
298
+ case 1: return [4 /*yield*/, llamalend.contracts[this.addresses.amm].contract.rate(llamalend.constantOptions)];
299
+ case 2:
300
+ _rate = _a.sent();
301
+ cacheStats.set(cacheKey(this.addresses.controller, 'rate'), _rate);
302
+ _a.label = 3;
303
+ case 3: return [2 /*return*/, _rate];
304
+ }
305
+ });
306
+ });
307
+ };
308
+ this._getFutureRate = function (_dReserves, _dDebt) { return __awaiter(_this, void 0, void 0, function () {
309
+ var mpContract;
310
+ return __generator(this, function (_a) {
311
+ switch (_a.label) {
312
+ case 0:
313
+ mpContract = llamalend.contracts[this.addresses.monetary_policy].contract;
314
+ return [4 /*yield*/, mpContract.future_rate(this.addresses.controller, _dReserves, _dDebt)];
315
+ case 1: return [2 /*return*/, _a.sent()];
316
+ }
317
+ });
318
+ }); };
319
+ this.statsBandsInfo = memoize(function () { return __awaiter(_this, void 0, void 0, function () {
320
+ var ammContract, calls, _a, activeBand, maxBand, minBand, _c, borrowed, collateral, liquidationBand;
321
+ return __generator(this, function (_d) {
322
+ switch (_d.label) {
323
+ case 0:
324
+ ammContract = llamalend.contracts[this.addresses.amm].multicallContract;
325
+ calls = [
326
+ ammContract.active_band(),
327
+ ammContract.max_band(),
328
+ ammContract.min_band(),
329
+ ];
330
+ return [4 /*yield*/, llamalend.multicallProvider.all(calls)];
331
+ case 1:
332
+ _a = (_d.sent()).map(function (_b) { return Number(_b); }), activeBand = _a[0], maxBand = _a[1], minBand = _a[2];
333
+ return [4 /*yield*/, this.statsBandBalances(activeBand)];
334
+ case 2:
335
+ _c = _d.sent(), borrowed = _c.borrowed, collateral = _c.collateral;
336
+ liquidationBand = null;
337
+ if (Number(borrowed) > 0 && Number(collateral) > 0)
338
+ liquidationBand = activeBand;
339
+ return [2 /*return*/, { activeBand: activeBand, maxBand: maxBand, minBand: minBand, liquidationBand: liquidationBand }];
340
+ }
341
+ });
342
+ }); }, {
343
+ promise: true,
344
+ maxAge: 60 * 1000, // 1m
345
+ });
346
+ this.statsAmmBalances = function (isGetter, useAPI) {
347
+ if (isGetter === void 0) { isGetter = true; }
348
+ if (useAPI === void 0) { useAPI = false; }
349
+ return __awaiter(_this, void 0, void 0, function () {
350
+ var response, market, borrowedContract, collateralContract, ammContract, _balance_x, _fee_x, _balance_y, _fee_y;
351
+ var _a, _c;
352
+ var _this = this;
353
+ return __generator(this, function (_d) {
354
+ switch (_d.label) {
355
+ case 0:
356
+ if (!useAPI) return [3 /*break*/, 2];
357
+ return [4 /*yield*/, _getMarketsData(llamalend.constants.NETWORK_NAME)];
358
+ case 1:
359
+ response = _d.sent();
360
+ market = response.lendingVaultData.find(function (item) { return item.address.toLowerCase() === _this.addresses.vault.toLowerCase(); });
361
+ if (market) {
362
+ return [2 /*return*/, {
363
+ borrowed: market.ammBalances.ammBalanceBorrowed.toString(),
364
+ collateral: market.ammBalances.ammBalanceCollateral.toString(),
365
+ }];
366
+ }
367
+ else {
368
+ throw new Error('Market not found in API');
369
+ }
370
+ return [3 /*break*/, 6];
371
+ case 2:
372
+ borrowedContract = llamalend.contracts[this.addresses.borrowed_token].multicallContract;
373
+ collateralContract = llamalend.contracts[this.addresses.collateral_token].multicallContract;
374
+ ammContract = llamalend.contracts[this.addresses.amm].multicallContract;
375
+ _balance_x = void 0, _fee_x = void 0, _balance_y = void 0, _fee_y = void 0;
376
+ if (!isGetter) return [3 /*break*/, 3];
377
+ _a = [
378
+ cacheStats.get(cacheKey(this.addresses.borrowed_token, 'balanceOf', this.addresses.amm)),
379
+ cacheStats.get(cacheKey(this.addresses.amm, 'admin_fees_x')),
380
+ cacheStats.get(cacheKey(this.addresses.collateral_token, 'balanceOf', this.addresses.amm)),
381
+ cacheStats.get(cacheKey(this.addresses.amm, 'admin_fees_y')),
382
+ ], _balance_x = _a[0], _fee_x = _a[1], _balance_y = _a[2], _fee_y = _a[3];
383
+ return [3 /*break*/, 5];
384
+ case 3: return [4 /*yield*/, llamalend.multicallProvider.all([
385
+ borrowedContract.balanceOf(this.addresses.amm),
386
+ ammContract.admin_fees_x(),
387
+ collateralContract.balanceOf(this.addresses.amm),
388
+ ammContract.admin_fees_y(),
389
+ ])];
390
+ case 4:
391
+ _c = _d.sent(), _balance_x = _c[0], _fee_x = _c[1], _balance_y = _c[2], _fee_y = _c[3];
392
+ cacheStats.set(cacheKey(this.addresses.borrowed_token, 'balanceOf', this.addresses.amm), _balance_x);
393
+ cacheStats.set(cacheKey(this.addresses.amm, 'admin_fees_x'), _fee_x);
394
+ cacheStats.set(cacheKey(this.addresses.collateral_token, 'balanceOf', this.addresses.amm), _balance_y);
395
+ cacheStats.set(cacheKey(this.addresses.amm, 'admin_fees_y'), _fee_y);
396
+ _d.label = 5;
397
+ case 5: return [2 /*return*/, {
398
+ borrowed: toBN(_balance_x, this.borrowed_token.decimals).minus(toBN(_fee_x, this.borrowed_token.decimals)).toString(),
399
+ collateral: toBN(_balance_y, this.collateral_token.decimals).minus(toBN(_fee_y, this.collateral_token.decimals)).toString(),
400
+ }];
401
+ case 6: return [2 /*return*/];
402
+ }
403
+ });
404
+ });
405
+ };
406
+ // ---------------- PRICES ----------------
407
+ this.A = memoize(function () { return __awaiter(_this, void 0, void 0, function () {
408
+ var _A;
409
+ return __generator(this, function (_a) {
410
+ switch (_a.label) {
411
+ case 0: return [4 /*yield*/, llamalend.contracts[this.addresses.amm].contract.A(llamalend.constantOptions)];
412
+ case 1:
413
+ _A = _a.sent();
414
+ return [2 /*return*/, formatUnits(_A, 0)];
415
+ }
416
+ });
417
+ }); }, {
418
+ promise: true,
419
+ maxAge: 86400 * 1000, // 1d
420
+ });
421
+ this.basePrice = memoize(function () { return __awaiter(_this, void 0, void 0, function () {
422
+ var _price;
423
+ return __generator(this, function (_a) {
424
+ switch (_a.label) {
425
+ case 0: return [4 /*yield*/, llamalend.contracts[this.addresses.amm].contract.get_base_price(llamalend.constantOptions)];
426
+ case 1:
427
+ _price = _a.sent();
428
+ return [2 /*return*/, formatUnits(_price)];
429
+ }
430
+ });
431
+ }); }, {
432
+ promise: true,
433
+ maxAge: 86400 * 1000, // 1d
434
+ });
435
+ this.oraclePrice = memoize(function () { return __awaiter(_this, void 0, void 0, function () {
436
+ var _price;
437
+ return __generator(this, function (_a) {
438
+ switch (_a.label) {
439
+ case 0: return [4 /*yield*/, llamalend.contracts[this.addresses.amm].contract.price_oracle(llamalend.constantOptions)];
440
+ case 1:
441
+ _price = _a.sent();
442
+ return [2 /*return*/, formatUnits(_price)];
443
+ }
444
+ });
445
+ }); }, {
446
+ promise: true,
447
+ maxAge: 60 * 1000, // 1m
448
+ });
449
+ this._userState = memoize(function (address) {
450
+ if (address === void 0) { address = ""; }
451
+ return __awaiter(_this, void 0, void 0, function () {
452
+ var contract, _a, _collateral, _borrowed, _debt, _N;
453
+ return __generator(this, function (_c) {
454
+ switch (_c.label) {
455
+ case 0:
456
+ address = _getAddress(address);
457
+ contract = llamalend.contracts[this.addresses.controller].contract;
458
+ return [4 /*yield*/, contract.user_state(address, llamalend.constantOptions)];
459
+ case 1:
460
+ _a = _c.sent(), _collateral = _a[0], _borrowed = _a[1], _debt = _a[2], _N = _a[3];
461
+ return [2 /*return*/, { _collateral: _collateral, _borrowed: _borrowed, _debt: _debt, _N: _N }];
462
+ }
463
+ });
464
+ });
465
+ }, {
466
+ promise: true,
467
+ maxAge: 10 * 1000, // 10s
468
+ });
469
+ this.createLoanMaxRecvAllRanges = memoize(function (collateral) { return __awaiter(_this, void 0, void 0, function () {
470
+ var _collateral, calls, N, _amounts, res, N;
471
+ return __generator(this, function (_a) {
472
+ switch (_a.label) {
473
+ case 0:
474
+ _collateral = parseUnits(collateral, this.collateral_token.decimals);
475
+ calls = [];
476
+ for (N = this.minBands; N <= this.maxBands; N++) {
477
+ calls.push(llamalend.contracts[this.addresses.controller].multicallContract.max_borrowable(_collateral, N, 0));
478
+ }
479
+ return [4 /*yield*/, llamalend.multicallProvider.all(calls)];
480
+ case 1:
481
+ _amounts = _a.sent();
482
+ res = {};
483
+ for (N = this.minBands; N <= this.maxBands; N++) {
484
+ res[N] = formatUnits(_amounts[N - this.minBands], this.borrowed_token.decimals);
485
+ }
486
+ return [2 /*return*/, res];
487
+ }
488
+ });
489
+ }); }, {
490
+ promise: true,
491
+ maxAge: 5 * 60 * 1000, // 5m
492
+ });
493
+ // ---------------- LEVERAGE CREATE LOAN ----------------
494
+ this.hasLeverage = function () {
495
+ return llamalend.constants.ALIASES.leverage_zap !== llamalend.constants.ZERO_ADDRESS &&
496
+ _this._getMarketId() >= Number(llamalend.constants.ALIASES["leverage_markets_start_id"]);
497
+ };
498
+ this.leverageCreateLoanMaxRecvAllRanges = memoize(function (userCollateral, userBorrowed) { return __awaiter(_this, void 0, void 0, function () {
499
+ var _userCollateral, contract, oraclePriceBand, pAvgApproxBN, _a, pAvgBN, arrLength, maxLeverageCollateralBN, _maxLeverageCollateral, maxBorrowablePrevBN, maxBorrowableBN, _maxBorrowable, i, pBN, _userEffectiveCollateral, calls, N, j, deltaBN, _y, _c, yBN, userEffectiveCollateralBN, res, N, j;
500
+ var _this = this;
501
+ return __generator(this, function (_d) {
502
+ switch (_d.label) {
503
+ case 0:
504
+ this._checkLeverageZap();
505
+ _userCollateral = parseUnits(userCollateral, this.collateral_token.decimals);
506
+ contract = llamalend.contracts[llamalend.constants.ALIASES.leverage_zap].multicallContract;
507
+ return [4 /*yield*/, this.oraclePriceBand()];
508
+ case 1:
509
+ oraclePriceBand = _d.sent();
510
+ _a = BN;
511
+ return [4 /*yield*/, this.calcTickPrice(oraclePriceBand)];
512
+ case 2:
513
+ pAvgApproxBN = _a.apply(void 0, [_d.sent()]);
514
+ pAvgBN = null;
515
+ arrLength = this.maxBands - this.minBands + 1;
516
+ maxLeverageCollateralBN = new Array(arrLength).fill(BN(0));
517
+ _maxLeverageCollateral = new Array(arrLength).fill(BigInt(0));
518
+ maxBorrowablePrevBN = new Array(arrLength).fill(BN(0));
519
+ maxBorrowableBN = new Array(arrLength).fill(BN(0));
520
+ _maxBorrowable = new Array(arrLength).fill(BigInt(0));
521
+ i = 0;
522
+ _d.label = 3;
523
+ case 3:
524
+ if (!(i < 5)) return [3 /*break*/, 8];
525
+ pBN = pAvgBN !== null && pAvgBN !== void 0 ? pAvgBN : pAvgApproxBN;
526
+ maxBorrowablePrevBN = maxBorrowableBN;
527
+ _userEffectiveCollateral = _userCollateral + fromBN(BN(userBorrowed).div(pBN), this.collateral_token.decimals);
528
+ calls = [];
529
+ for (N = this.minBands; N <= this.maxBands; N++) {
530
+ j = N - this.minBands;
531
+ calls.push(contract.max_borrowable(this.addresses.controller, _userEffectiveCollateral, _maxLeverageCollateral[j], N, fromBN(pBN)));
532
+ }
533
+ return [4 /*yield*/, llamalend.multicallProvider.all(calls)];
534
+ case 4:
535
+ _maxBorrowable = (_d.sent()).map(function (_mb) { return _mb * BigInt(998) / BigInt(1000); });
536
+ maxBorrowableBN = _maxBorrowable.map(function (_mb) { return toBN(_mb, _this.borrowed_token.decimals); });
537
+ deltaBN = maxBorrowableBN.map(function (mb, l) { return mb.minus(maxBorrowablePrevBN[l]).abs().div(mb); });
538
+ if (BigNumber.max.apply(BigNumber, deltaBN).lt(0.0005)) {
539
+ maxBorrowableBN = maxBorrowablePrevBN;
540
+ return [3 /*break*/, 8];
541
+ }
542
+ if (!(pAvgBN === null)) return [3 /*break*/, 6];
543
+ _c = BigInt;
544
+ return [4 /*yield*/, _getExpectedOdos(this.addresses.borrowed_token, this.addresses.collateral_token, _maxBorrowable[0], this.addresses.amm)];
545
+ case 5:
546
+ _y = _c.apply(void 0, [_d.sent()]);
547
+ yBN = toBN(_y, this.collateral_token.decimals);
548
+ pAvgBN = maxBorrowableBN[0].div(yBN);
549
+ _d.label = 6;
550
+ case 6:
551
+ maxLeverageCollateralBN = maxBorrowableBN.map(function (mb) { return mb.div(pAvgBN); });
552
+ _maxLeverageCollateral = maxLeverageCollateralBN.map(function (mlc) { return fromBN(mlc, _this.collateral_token.decimals); });
553
+ _d.label = 7;
554
+ case 7:
555
+ i++;
556
+ return [3 /*break*/, 3];
557
+ case 8:
558
+ userEffectiveCollateralBN = BN(userCollateral).plus(BN(userBorrowed).div(pAvgBN));
559
+ res = {};
560
+ for (N = this.minBands; N <= this.maxBands; N++) {
561
+ j = N - this.minBands;
562
+ res[N] = {
563
+ maxDebt: formatNumber(maxBorrowableBN[j].toString(), this.borrowed_token.decimals),
564
+ maxTotalCollateral: formatNumber(maxLeverageCollateralBN[j].plus(userEffectiveCollateralBN).toString(), this.collateral_token.decimals),
565
+ userCollateral: formatNumber(userCollateral, this.collateral_token.decimals),
566
+ collateralFromUserBorrowed: formatNumber(BN(userBorrowed).div(pAvgBN).toString(), this.collateral_token.decimals),
567
+ collateralFromMaxDebt: formatNumber(maxLeverageCollateralBN[j].toString(), this.collateral_token.decimals),
568
+ maxLeverage: maxLeverageCollateralBN[j].plus(userEffectiveCollateralBN).div(userEffectiveCollateralBN).toString(),
569
+ avgPrice: pAvgBN.toString(),
570
+ };
571
+ }
572
+ return [2 /*return*/, res];
573
+ }
574
+ });
575
+ }); }, {
576
+ promise: true,
577
+ maxAge: 60 * 1000, // 1m
578
+ });
579
+ this._setSwapDataToCache = function (inputCoinAddress, outputCoinAddress, _amount, slippage) { return __awaiter(_this, void 0, void 0, function () {
580
+ var swapData, key;
581
+ return __generator(this, function (_a) {
582
+ switch (_a.label) {
583
+ case 0: return [4 /*yield*/, _getQuoteOdos(inputCoinAddress, outputCoinAddress, _amount, this.addresses.amm, true, slippage)];
584
+ case 1:
585
+ swapData = _a.sent();
586
+ _a.label = 2;
587
+ case 2:
588
+ if (!(swapData.pathId == null)) return [3 /*break*/, 4];
589
+ return [4 /*yield*/, _getQuoteOdos(inputCoinAddress, outputCoinAddress, _amount, this.addresses.amm, true, slippage)];
590
+ case 3:
591
+ swapData = _a.sent();
592
+ return [3 /*break*/, 2];
593
+ case 4:
594
+ key = "".concat(inputCoinAddress, "-").concat(_amount);
595
+ this.swapDataCache[key] = __assign(__assign({}, swapData), { slippage: slippage });
596
+ return [2 /*return*/];
597
+ }
598
+ });
599
+ }); };
600
+ this._getSwapDataFromCache = function (inputCoinAddress, _amount) {
601
+ var key = "".concat(inputCoinAddress, "-").concat(_amount);
602
+ if (!(key in _this.swapDataCache))
603
+ throw Error("You must call corresponding `expected` method first " +
604
+ "(leverage.createLoanExpectedCollateral, leverage.borrowMoreExpectedCollateral or leverage.repayExpectedBorrowed)");
605
+ return _this.swapDataCache[key];
606
+ };
607
+ this._leverageExpectedCollateral = function (userCollateral, userBorrowed, debt, user) { return __awaiter(_this, void 0, void 0, function () {
608
+ var _userCollateral, _debt, _userBorrowed, _additionalCollateral, _collateralFromDebt, _collateralFromUserBorrowed, _stateCollateral, _a, _collateral, _borrowed, _totalCollateral, _futureStateCollateral, avgPrice;
609
+ return __generator(this, function (_c) {
610
+ switch (_c.label) {
611
+ case 0:
612
+ _userCollateral = parseUnits(userCollateral, this.collateral_token.decimals);
613
+ _debt = parseUnits(debt, this.borrowed_token.decimals);
614
+ _userBorrowed = parseUnits(userBorrowed, this.borrowed_token.decimals);
615
+ _additionalCollateral = BigInt(this._getSwapDataFromCache(this.addresses.borrowed_token, _debt + _userBorrowed).outAmounts[0]);
616
+ _collateralFromDebt = _debt * BigInt(Math.pow(10, 18)) / (_debt + _userBorrowed) * _additionalCollateral / BigInt(Math.pow(10, 18));
617
+ _collateralFromUserBorrowed = _additionalCollateral - _collateralFromDebt;
618
+ _stateCollateral = BigInt(0);
619
+ if (!user) return [3 /*break*/, 2];
620
+ return [4 /*yield*/, this._userState(user)];
621
+ case 1:
622
+ _a = _c.sent(), _collateral = _a._collateral, _borrowed = _a._borrowed;
623
+ if (_borrowed > BigInt(0))
624
+ throw Error("User ".concat(user, " is already in liquidation mode"));
625
+ _stateCollateral = _collateral;
626
+ _c.label = 2;
627
+ case 2:
628
+ _totalCollateral = _userCollateral + _additionalCollateral;
629
+ _futureStateCollateral = _stateCollateral + _totalCollateral;
630
+ avgPrice = toBN(_debt + _userBorrowed, this.borrowed_token.decimals).div(toBN(_additionalCollateral, this.collateral_token.decimals)).toString();
631
+ return [2 /*return*/, { _futureStateCollateral: _futureStateCollateral, _totalCollateral: _totalCollateral, _userCollateral: _userCollateral, _collateralFromUserBorrowed: _collateralFromUserBorrowed, _collateralFromDebt: _collateralFromDebt, avgPrice: avgPrice }];
632
+ }
633
+ });
634
+ }); };
635
+ this._leverageCalcN1 = memoize(function (userCollateral, userBorrowed, debt, range, user) { return __awaiter(_this, void 0, void 0, function () {
636
+ var _stateDebt, _a, _debt_1, _borrowed, _N, _futureStateCollateral, _debt;
637
+ return __generator(this, function (_c) {
638
+ switch (_c.label) {
639
+ case 0:
640
+ if (range > 0)
641
+ this._checkRange(range);
642
+ _stateDebt = BigInt(0);
643
+ if (!user) return [3 /*break*/, 2];
644
+ return [4 /*yield*/, this._userState(user)];
645
+ case 1:
646
+ _a = _c.sent(), _debt_1 = _a._debt, _borrowed = _a._borrowed, _N = _a._N;
647
+ if (_borrowed > BigInt(0))
648
+ throw Error("User ".concat(user, " is already in liquidation mode"));
649
+ _stateDebt = _debt_1;
650
+ if (range < 0)
651
+ range = Number(llamalend.formatUnits(_N, 0));
652
+ _c.label = 2;
653
+ case 2: return [4 /*yield*/, this._leverageExpectedCollateral(userCollateral, userBorrowed, debt, user)];
654
+ case 3:
655
+ _futureStateCollateral = (_c.sent())._futureStateCollateral;
656
+ _debt = _stateDebt + parseUnits(debt, this.borrowed_token.decimals);
657
+ return [4 /*yield*/, llamalend.contracts[this.addresses.controller].contract.calculate_debt_n1(_futureStateCollateral, _debt, range, llamalend.constantOptions)];
658
+ case 4: return [2 /*return*/, _c.sent()];
659
+ }
660
+ });
661
+ }); }, {
662
+ promise: true,
663
+ maxAge: 60 * 1000, // 1m
664
+ });
665
+ this._leverageCalcN1AllRanges = memoize(function (userCollateral, userBorrowed, debt, maxN) { return __awaiter(_this, void 0, void 0, function () {
666
+ var _futureStateCollateral, _debt, calls, N;
667
+ return __generator(this, function (_a) {
668
+ switch (_a.label) {
669
+ case 0: return [4 /*yield*/, this._leverageExpectedCollateral(userCollateral, userBorrowed, debt)];
670
+ case 1:
671
+ _futureStateCollateral = (_a.sent())._futureStateCollateral;
672
+ _debt = parseUnits(debt, this.borrowed_token.decimals);
673
+ calls = [];
674
+ for (N = this.minBands; N <= maxN; N++) {
675
+ calls.push(llamalend.contracts[this.addresses.controller].multicallContract.calculate_debt_n1(_futureStateCollateral, _debt, N));
676
+ }
677
+ return [4 /*yield*/, llamalend.multicallProvider.all(calls)];
678
+ case 2: return [2 /*return*/, _a.sent()];
679
+ }
680
+ });
681
+ }); }, {
682
+ promise: true,
683
+ maxAge: 60 * 1000, // 1m
684
+ });
685
+ // ---------------- LEVERAGE REPAY ----------------
686
+ this._leverageRepayExpectedBorrowed = function (stateCollateral, userCollateral, userBorrowed) {
687
+ _this._checkLeverageZap();
688
+ var _stateCollateral = parseUnits(stateCollateral, _this.collateral_token.decimals);
689
+ var _userCollateral = parseUnits(userCollateral, _this.collateral_token.decimals);
690
+ var _borrowedExpected = BigInt(0);
691
+ var _borrowedFromStateCollateral = BigInt(0);
692
+ var _borrowedFromUserCollateral = BigInt(0);
693
+ if (_stateCollateral + _userCollateral > BigInt(0)) {
694
+ _borrowedExpected = BigInt(_this._getSwapDataFromCache(_this.addresses.collateral_token, _stateCollateral + _userCollateral).outAmounts[0]);
695
+ _borrowedFromStateCollateral = _stateCollateral * BigInt(Math.pow(10, 18)) / (_stateCollateral + _userCollateral) * _borrowedExpected / BigInt(Math.pow(10, 18));
696
+ _borrowedFromUserCollateral = _borrowedExpected - _borrowedFromStateCollateral;
697
+ }
698
+ var _totalBorrowed = _borrowedExpected + parseUnits(userBorrowed, _this.borrowed_token.decimals);
699
+ var avgPrice = toBN(_borrowedExpected, _this.borrowed_token.decimals).div(toBN(_stateCollateral + _userCollateral, _this.collateral_token.decimals)).toString();
700
+ return { _totalBorrowed: _totalBorrowed, _borrowedFromStateCollateral: _borrowedFromStateCollateral, _borrowedFromUserCollateral: _borrowedFromUserCollateral, avgPrice: avgPrice };
701
+ };
702
+ this.leverageRepayExpectedBorrowed = function (stateCollateral, userCollateral, userBorrowed, slippage) {
703
+ if (slippage === void 0) { slippage = 0.1; }
704
+ return __awaiter(_this, void 0, void 0, function () {
705
+ var _stateCollateral, _userCollateral, _a, _totalBorrowed, _borrowedFromStateCollateral, _borrowedFromUserCollateral, avgPrice;
706
+ return __generator(this, function (_c) {
707
+ switch (_c.label) {
708
+ case 0:
709
+ this._checkLeverageZap();
710
+ _stateCollateral = parseUnits(stateCollateral, this.collateral_token.decimals);
711
+ _userCollateral = parseUnits(userCollateral, this.collateral_token.decimals);
712
+ if (!(_stateCollateral + _userCollateral > BigInt(0))) return [3 /*break*/, 2];
713
+ return [4 /*yield*/, this._setSwapDataToCache(this.addresses.collateral_token, this.addresses.borrowed_token, _stateCollateral + _userCollateral, slippage)];
714
+ case 1:
715
+ _c.sent();
716
+ _c.label = 2;
717
+ case 2:
718
+ _a = this._leverageRepayExpectedBorrowed(stateCollateral, userCollateral, userBorrowed), _totalBorrowed = _a._totalBorrowed, _borrowedFromStateCollateral = _a._borrowedFromStateCollateral, _borrowedFromUserCollateral = _a._borrowedFromUserCollateral, avgPrice = _a.avgPrice;
719
+ return [2 /*return*/, {
720
+ totalBorrowed: formatUnits(_totalBorrowed, this.borrowed_token.decimals),
721
+ borrowedFromStateCollateral: formatUnits(_borrowedFromStateCollateral, this.borrowed_token.decimals),
722
+ borrowedFromUserCollateral: formatUnits(_borrowedFromUserCollateral, this.borrowed_token.decimals),
723
+ userBorrowed: formatNumber(userBorrowed, this.borrowed_token.decimals),
724
+ avgPrice: avgPrice,
725
+ }];
726
+ }
727
+ });
728
+ });
729
+ };
730
+ this._leverageRepayBands = memoize(function (stateCollateral, userCollateral, userBorrowed, address) { return __awaiter(_this, void 0, void 0, function () {
731
+ var _stateRepayCollateral, _a, _stateCollateral, _stateDebt, _N, _n1, _n2, _repayExpected, e_1;
732
+ return __generator(this, function (_c) {
733
+ switch (_c.label) {
734
+ case 0:
735
+ address = _getAddress(address);
736
+ return [4 /*yield*/, this.leverageRepayIsAvailable(stateCollateral, userCollateral, userBorrowed, address)];
737
+ case 1:
738
+ if (!(_c.sent()))
739
+ return [2 /*return*/, [parseUnits(0, 0), parseUnits(0, 0)]];
740
+ _stateRepayCollateral = parseUnits(stateCollateral, this.collateral_token.decimals);
741
+ return [4 /*yield*/, this._userState(address)];
742
+ case 2:
743
+ _a = _c.sent(), _stateCollateral = _a._collateral, _stateDebt = _a._debt, _N = _a._N;
744
+ if (_stateDebt == BigInt(0))
745
+ throw Error("Loan for ".concat(address, " does not exist"));
746
+ if (_stateCollateral < _stateRepayCollateral)
747
+ throw Error("Can't use more collateral than user's position has (".concat(_stateRepayCollateral, ") > ").concat(_stateCollateral, ")"));
748
+ _n1 = parseUnits(0, 0);
749
+ _n2 = parseUnits(0, 0);
750
+ _repayExpected = this._leverageRepayExpectedBorrowed(stateCollateral, userCollateral, userBorrowed)._totalBorrowed;
751
+ _c.label = 3;
752
+ case 3:
753
+ _c.trys.push([3, 5, , 6]);
754
+ return [4 /*yield*/, llamalend.contracts[this.addresses.controller].contract.calculate_debt_n1(_stateCollateral - _stateRepayCollateral, _stateDebt - _repayExpected, _N)];
755
+ case 4:
756
+ _n1 = _c.sent();
757
+ _n2 = _n1 + (_N - BigInt(1));
758
+ return [3 /*break*/, 6];
759
+ case 5:
760
+ e_1 = _c.sent();
761
+ console.log("Full repayment");
762
+ return [3 /*break*/, 6];
763
+ case 6: return [2 /*return*/, [_n2, _n1]];
764
+ }
765
+ });
766
+ }); }, {
767
+ promise: true,
768
+ maxAge: 5 * 60 * 1000, // 5m
769
+ });
770
+ this.id = id;
771
+ this.name = marketData.name;
772
+ this.addresses = marketData.addresses;
773
+ this.borrowed_token = marketData.borrowed_token;
774
+ this.collateral_token = marketData.collateral_token;
775
+ this.coinDecimals = [this.borrowed_token.decimals, this.collateral_token.decimals];
776
+ this.coinAddresses = [this.borrowed_token.address, this.collateral_token.address];
777
+ this.defaultBands = 10;
778
+ this.minBands = 4;
779
+ this.maxBands = 50;
780
+ this.estimateGas = {
781
+ createLoanApprove: this.createLoanApproveEstimateGas.bind(this),
782
+ createLoan: this.createLoanEstimateGas.bind(this),
783
+ borrowMoreApprove: this.borrowMoreApproveEstimateGas.bind(this),
784
+ borrowMore: this.borrowMoreEstimateGas.bind(this),
785
+ addCollateralApprove: this.addCollateralApproveEstimateGas.bind(this),
786
+ addCollateral: this.addCollateralEstimateGas.bind(this),
787
+ removeCollateral: this.removeCollateralEstimateGas.bind(this),
788
+ repayApprove: this.repayApproveEstimateGas.bind(this),
789
+ repay: this.repayEstimateGas.bind(this),
790
+ fullRepayApprove: this.fullRepayApproveEstimateGas.bind(this),
791
+ fullRepay: this.fullRepayEstimateGas.bind(this),
792
+ swapApprove: this.swapApproveEstimateGas.bind(this),
793
+ swap: this.swapEstimateGas.bind(this),
794
+ liquidateApprove: this.liquidateApproveEstimateGas.bind(this),
795
+ liquidate: this.liquidateEstimateGas.bind(this),
796
+ selfLiquidateApprove: this.selfLiquidateApproveEstimateGas.bind(this),
797
+ selfLiquidate: this.selfLiquidateEstimateGas.bind(this),
798
+ };
799
+ this.stats = {
800
+ parameters: this.statsParameters.bind(this),
801
+ rates: this.statsRates.bind(this),
802
+ futureRates: this.statsFutureRates.bind(this),
803
+ balances: this.statsBalances.bind(this),
804
+ bandsInfo: this.statsBandsInfo.bind(this),
805
+ bandBalances: this.statsBandBalances.bind(this),
806
+ bandsBalances: this.statsBandsBalances.bind(this),
807
+ totalDebt: this.statsTotalDebt.bind(this),
808
+ ammBalances: this.statsAmmBalances.bind(this),
809
+ capAndAvailable: this.statsCapAndAvailable.bind(this),
810
+ };
811
+ this.wallet = {
812
+ balances: this.walletBalances.bind(this),
813
+ };
814
+ this.vault = {
815
+ maxDeposit: this.vaultMaxDeposit.bind(this),
816
+ previewDeposit: this.vaultPreviewDeposit.bind(this),
817
+ depositIsApproved: this.vaultDepositIsApproved.bind(this),
818
+ depositApprove: this.vaultDepositApprove.bind(this),
819
+ deposit: this.vaultDeposit.bind(this),
820
+ maxMint: this.vaultMaxMint.bind(this),
821
+ previewMint: this.vaultPreviewMint.bind(this),
822
+ mintIsApproved: this.vaultMintIsApproved.bind(this),
823
+ mintApprove: this.vaultMintApprove.bind(this),
824
+ mint: this.vaultMint.bind(this),
825
+ maxWithdraw: this.vaultMaxWithdraw.bind(this),
826
+ previewWithdraw: this.vaultPreviewWithdraw.bind(this),
827
+ withdraw: this.vaultWithdraw.bind(this),
828
+ maxRedeem: this.vaultMaxRedeem.bind(this),
829
+ previewRedeem: this.vaultPreviewRedeem.bind(this),
830
+ redeem: this.vaultRedeem.bind(this),
831
+ convertToShares: this.vaultConvertToShares.bind(this),
832
+ convertToAssets: this.vaultConvertToAssets.bind(this),
833
+ stakeIsApproved: this.vaultStakeIsApproved.bind(this),
834
+ stakeApprove: this.vaultStakeApprove.bind(this),
835
+ stake: this.vaultStake.bind(this),
836
+ unstake: this.vaultUnstake.bind(this),
837
+ rewardsOnly: this.vaultRewardsOnly.bind(this),
838
+ totalLiquidity: this.vaultTotalLiquidity.bind(this),
839
+ crvApr: this.vaultCrvApr.bind(this),
840
+ claimableCrv: this.vaultClaimableCrv.bind(this),
841
+ claimCrv: this.vaultClaimCrv.bind(this),
842
+ rewardTokens: this.vaultRewardTokens.bind(this),
843
+ rewardsApr: this.vaultRewardsApr.bind(this),
844
+ claimableRewards: this.vaultClaimableRewards.bind(this),
845
+ claimRewards: this.vaultClaimRewards.bind(this),
846
+ estimateGas: {
847
+ depositApprove: this.vaultDepositApproveEstimateGas.bind(this),
848
+ deposit: this.vaultDepositEstimateGas.bind(this),
849
+ mintApprove: this.vaultMintApproveEstimateGas.bind(this),
850
+ mint: this.vaultMintEstimateGas.bind(this),
851
+ withdraw: this.vaultWithdrawEstimateGas.bind(this),
852
+ redeem: this.vaultRedeemEstimateGas.bind(this),
853
+ stakeApprove: this.vaultStakeApproveEstimateGas.bind(this),
854
+ stake: this.vaultStakeEstimateGas.bind(this),
855
+ unstake: this.vaultUnstakeEstimateGas.bind(this),
856
+ claimCrv: this.vaultClaimCrvEstimateGas.bind(this),
857
+ claimRewards: this.vaultClaimRewardsEstimateGas.bind(this),
858
+ },
859
+ };
860
+ this.leverage = {
861
+ hasLeverage: this.hasLeverage.bind(this),
862
+ maxLeverage: this.maxLeverage.bind(this),
863
+ createLoanMaxRecv: this.leverageCreateLoanMaxRecv.bind(this),
864
+ createLoanMaxRecvAllRanges: this.leverageCreateLoanMaxRecvAllRanges.bind(this),
865
+ createLoanExpectedCollateral: this.leverageCreateLoanExpectedCollateral.bind(this),
866
+ createLoanPriceImpact: this.leverageCreateLoanPriceImpact.bind(this),
867
+ createLoanMaxRange: this.leverageCreateLoanMaxRange.bind(this),
868
+ createLoanBands: this.leverageCreateLoanBands.bind(this),
869
+ createLoanBandsAllRanges: this.leverageCreateLoanBandsAllRanges.bind(this),
870
+ createLoanPrices: this.leverageCreateLoanPrices.bind(this),
871
+ createLoanPricesAllRanges: this.leverageCreateLoanPricesAllRanges.bind(this),
872
+ createLoanHealth: this.leverageCreateLoanHealth.bind(this),
873
+ createLoanIsApproved: this.leverageCreateLoanIsApproved.bind(this),
874
+ createLoanApprove: this.leverageCreateLoanApprove.bind(this),
875
+ createLoanRouteImage: this.leverageCreateLoanRouteImage.bind(this),
876
+ createLoan: this.leverageCreateLoan.bind(this),
877
+ borrowMoreMaxRecv: this.leverageBorrowMoreMaxRecv.bind(this),
878
+ borrowMoreExpectedCollateral: this.leverageBorrowMoreExpectedCollateral.bind(this),
879
+ borrowMorePriceImpact: this.leverageBorrowMorePriceImpact.bind(this),
880
+ borrowMoreBands: this.leverageBorrowMoreBands.bind(this),
881
+ borrowMorePrices: this.leverageBorrowMorePrices.bind(this),
882
+ borrowMoreHealth: this.leverageBorrowMoreHealth.bind(this),
883
+ borrowMoreIsApproved: this.leverageCreateLoanIsApproved.bind(this),
884
+ borrowMoreApprove: this.leverageCreateLoanApprove.bind(this),
885
+ borrowMoreRouteImage: this.leverageBorrowMoreRouteImage.bind(this),
886
+ borrowMore: this.leverageBorrowMore.bind(this),
887
+ repayExpectedBorrowed: this.leverageRepayExpectedBorrowed.bind(this),
888
+ repayPriceImpact: this.leverageRepayPriceImpact.bind(this),
889
+ repayIsFull: this.leverageRepayIsFull.bind(this),
890
+ repayIsAvailable: this.leverageRepayIsAvailable.bind(this),
891
+ repayBands: this.leverageRepayBands.bind(this),
892
+ repayPrices: this.leverageRepayPrices.bind(this),
893
+ repayHealth: this.leverageRepayHealth.bind(this),
894
+ repayIsApproved: this.leverageRepayIsApproved.bind(this),
895
+ repayApprove: this.leverageRepayApprove.bind(this),
896
+ repayRouteImage: this.leverageRepayRouteImage.bind(this),
897
+ repay: this.leverageRepay.bind(this),
898
+ estimateGas: {
899
+ createLoanApprove: this.leverageCreateLoanApproveEstimateGas.bind(this),
900
+ createLoan: this.leverageCreateLoanEstimateGas.bind(this),
901
+ borrowMoreApprove: this.leverageCreateLoanApproveEstimateGas.bind(this),
902
+ borrowMore: this.leverageBorrowMoreEstimateGas.bind(this),
903
+ repayApprove: this.leverageRepayApproveEstimateGas.bind(this),
904
+ repay: this.leverageRepayEstimateGas.bind(this),
905
+ },
906
+ };
907
+ }
908
+ // ---------------- VAULT ----------------
909
+ LendMarketTemplate.prototype.vaultMaxDeposit = function (address) {
910
+ if (address === void 0) { address = ""; }
911
+ return __awaiter(this, void 0, void 0, function () {
912
+ var _amount;
913
+ return __generator(this, function (_a) {
914
+ switch (_a.label) {
915
+ case 0:
916
+ address = _getAddress(address);
917
+ return [4 /*yield*/, llamalend.contracts[this.addresses.borrowed_token].contract.balanceOf(address)];
918
+ case 1:
919
+ _amount = _a.sent();
920
+ return [2 /*return*/, formatUnits(_amount, this.borrowed_token.decimals)];
921
+ }
922
+ });
923
+ });
924
+ };
925
+ LendMarketTemplate.prototype.vaultPreviewDeposit = function (amount) {
926
+ return __awaiter(this, void 0, void 0, function () {
927
+ var _amount, _shares;
928
+ return __generator(this, function (_a) {
929
+ switch (_a.label) {
930
+ case 0:
931
+ _amount = parseUnits(amount, this.borrowed_token.decimals);
932
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.previewDeposit(_amount)];
933
+ case 1:
934
+ _shares = _a.sent();
935
+ return [2 /*return*/, formatUnits(_shares, 18)];
936
+ }
937
+ });
938
+ });
939
+ };
940
+ LendMarketTemplate.prototype.vaultDepositIsApproved = function (borrowed) {
941
+ return __awaiter(this, void 0, void 0, function () {
942
+ return __generator(this, function (_a) {
943
+ switch (_a.label) {
944
+ case 0: return [4 /*yield*/, hasAllowance([this.borrowed_token.address], [borrowed], llamalend.signerAddress, this.addresses.vault)];
945
+ case 1: return [2 /*return*/, _a.sent()];
946
+ }
947
+ });
948
+ });
949
+ };
950
+ LendMarketTemplate.prototype.vaultDepositApproveEstimateGas = function (borrowed) {
951
+ return __awaiter(this, void 0, void 0, function () {
952
+ return __generator(this, function (_a) {
953
+ switch (_a.label) {
954
+ case 0: return [4 /*yield*/, ensureAllowanceEstimateGas([this.borrowed_token.address], [borrowed], this.addresses.vault)];
955
+ case 1: return [2 /*return*/, _a.sent()];
956
+ }
957
+ });
958
+ });
959
+ };
960
+ LendMarketTemplate.prototype.vaultDepositApprove = function (borrowed) {
961
+ return __awaiter(this, void 0, void 0, function () {
962
+ return __generator(this, function (_a) {
963
+ switch (_a.label) {
964
+ case 0: return [4 /*yield*/, ensureAllowance([this.borrowed_token.address], [borrowed], this.addresses.vault)];
965
+ case 1: return [2 /*return*/, _a.sent()];
966
+ }
967
+ });
968
+ });
969
+ };
970
+ LendMarketTemplate.prototype._vaultDeposit = function (amount, estimateGas) {
971
+ if (estimateGas === void 0) { estimateGas = false; }
972
+ return __awaiter(this, void 0, void 0, function () {
973
+ var _amount, gas, gasLimit;
974
+ return __generator(this, function (_a) {
975
+ switch (_a.label) {
976
+ case 0:
977
+ _amount = parseUnits(amount, this.borrowed_token.decimals);
978
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.deposit.estimateGas(_amount, __assign({}, llamalend.constantOptions))];
979
+ case 1:
980
+ gas = _a.sent();
981
+ if (estimateGas)
982
+ return [2 /*return*/, smartNumber(gas)];
983
+ return [4 /*yield*/, llamalend.updateFeeData()];
984
+ case 2:
985
+ _a.sent();
986
+ gasLimit = _mulBy1_3(DIGas(gas));
987
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.deposit(_amount, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
988
+ case 3: return [2 /*return*/, (_a.sent()).hash];
989
+ }
990
+ });
991
+ });
992
+ };
993
+ LendMarketTemplate.prototype.vaultDepositEstimateGas = function (amount) {
994
+ return __awaiter(this, void 0, void 0, function () {
995
+ return __generator(this, function (_a) {
996
+ switch (_a.label) {
997
+ case 0: return [4 /*yield*/, this.vaultDepositIsApproved(amount)];
998
+ case 1:
999
+ if (!(_a.sent()))
1000
+ throw Error("Approval is needed for gas estimation");
1001
+ return [4 /*yield*/, this._vaultDeposit(amount, true)];
1002
+ case 2: return [2 /*return*/, _a.sent()];
1003
+ }
1004
+ });
1005
+ });
1006
+ };
1007
+ LendMarketTemplate.prototype.vaultDeposit = function (amount) {
1008
+ return __awaiter(this, void 0, void 0, function () {
1009
+ return __generator(this, function (_a) {
1010
+ switch (_a.label) {
1011
+ case 0: return [4 /*yield*/, this.vaultDepositApprove(amount)];
1012
+ case 1:
1013
+ _a.sent();
1014
+ return [4 /*yield*/, this._vaultDeposit(amount, false)];
1015
+ case 2: return [2 /*return*/, _a.sent()];
1016
+ }
1017
+ });
1018
+ });
1019
+ };
1020
+ LendMarketTemplate.prototype.vaultMaxMint = function (address) {
1021
+ if (address === void 0) { address = ""; }
1022
+ return __awaiter(this, void 0, void 0, function () {
1023
+ var _assetBalance, _shares;
1024
+ return __generator(this, function (_a) {
1025
+ switch (_a.label) {
1026
+ case 0:
1027
+ address = _getAddress(address);
1028
+ return [4 /*yield*/, llamalend.contracts[this.addresses.borrowed_token].contract.balanceOf(address)];
1029
+ case 1:
1030
+ _assetBalance = _a.sent();
1031
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.convertToShares(_assetBalance)];
1032
+ case 2:
1033
+ _shares = _a.sent();
1034
+ return [2 /*return*/, formatUnits(_shares, 18)];
1035
+ }
1036
+ });
1037
+ });
1038
+ };
1039
+ LendMarketTemplate.prototype.vaultPreviewMint = function (amount) {
1040
+ return __awaiter(this, void 0, void 0, function () {
1041
+ var _amount, _assets;
1042
+ return __generator(this, function (_a) {
1043
+ switch (_a.label) {
1044
+ case 0:
1045
+ _amount = parseUnits(amount, 18);
1046
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.previewMint(_amount)];
1047
+ case 1:
1048
+ _assets = _a.sent();
1049
+ return [2 /*return*/, formatUnits(_assets, this.borrowed_token.decimals)];
1050
+ }
1051
+ });
1052
+ });
1053
+ };
1054
+ LendMarketTemplate.prototype.vaultMintIsApproved = function (borrowed) {
1055
+ return __awaiter(this, void 0, void 0, function () {
1056
+ return __generator(this, function (_a) {
1057
+ switch (_a.label) {
1058
+ case 0: return [4 /*yield*/, hasAllowance([this.borrowed_token.address], [borrowed], llamalend.signerAddress, this.addresses.vault)];
1059
+ case 1: return [2 /*return*/, _a.sent()];
1060
+ }
1061
+ });
1062
+ });
1063
+ };
1064
+ LendMarketTemplate.prototype.vaultMintApproveEstimateGas = function (borrowed) {
1065
+ return __awaiter(this, void 0, void 0, function () {
1066
+ return __generator(this, function (_a) {
1067
+ switch (_a.label) {
1068
+ case 0: return [4 /*yield*/, ensureAllowanceEstimateGas([this.borrowed_token.address], [borrowed], this.addresses.vault)];
1069
+ case 1: return [2 /*return*/, _a.sent()];
1070
+ }
1071
+ });
1072
+ });
1073
+ };
1074
+ LendMarketTemplate.prototype.vaultMintApprove = function (borrowed) {
1075
+ return __awaiter(this, void 0, void 0, function () {
1076
+ return __generator(this, function (_a) {
1077
+ switch (_a.label) {
1078
+ case 0: return [4 /*yield*/, ensureAllowance([this.borrowed_token.address], [borrowed], this.addresses.vault)];
1079
+ case 1: return [2 /*return*/, _a.sent()];
1080
+ }
1081
+ });
1082
+ });
1083
+ };
1084
+ LendMarketTemplate.prototype._vaultMint = function (amount, estimateGas) {
1085
+ if (estimateGas === void 0) { estimateGas = false; }
1086
+ return __awaiter(this, void 0, void 0, function () {
1087
+ var _amount, gas, gasLimit;
1088
+ return __generator(this, function (_a) {
1089
+ switch (_a.label) {
1090
+ case 0:
1091
+ _amount = parseUnits(amount, 18);
1092
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.mint.estimateGas(_amount, __assign({}, llamalend.constantOptions))];
1093
+ case 1:
1094
+ gas = _a.sent();
1095
+ if (estimateGas)
1096
+ return [2 /*return*/, smartNumber(gas)];
1097
+ return [4 /*yield*/, llamalend.updateFeeData()];
1098
+ case 2:
1099
+ _a.sent();
1100
+ gasLimit = _mulBy1_3(DIGas(gas));
1101
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.mint(_amount, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
1102
+ case 3: return [2 /*return*/, (_a.sent()).hash];
1103
+ }
1104
+ });
1105
+ });
1106
+ };
1107
+ LendMarketTemplate.prototype.vaultMintEstimateGas = function (amount) {
1108
+ return __awaiter(this, void 0, void 0, function () {
1109
+ return __generator(this, function (_a) {
1110
+ switch (_a.label) {
1111
+ case 0: return [4 /*yield*/, this.vaultMintIsApproved(amount)];
1112
+ case 1:
1113
+ if (!(_a.sent()))
1114
+ throw Error("Approval is needed for gas estimation");
1115
+ return [4 /*yield*/, this._vaultMint(amount, true)];
1116
+ case 2: return [2 /*return*/, _a.sent()];
1117
+ }
1118
+ });
1119
+ });
1120
+ };
1121
+ LendMarketTemplate.prototype.vaultMint = function (amount) {
1122
+ return __awaiter(this, void 0, void 0, function () {
1123
+ return __generator(this, function (_a) {
1124
+ switch (_a.label) {
1125
+ case 0: return [4 /*yield*/, this.vaultMintApprove(amount)];
1126
+ case 1:
1127
+ _a.sent();
1128
+ return [4 /*yield*/, this._vaultMint(amount, false)];
1129
+ case 2: return [2 /*return*/, _a.sent()];
1130
+ }
1131
+ });
1132
+ });
1133
+ };
1134
+ LendMarketTemplate.prototype.vaultMaxWithdraw = function (address) {
1135
+ if (address === void 0) { address = ""; }
1136
+ return __awaiter(this, void 0, void 0, function () {
1137
+ var _assets;
1138
+ return __generator(this, function (_a) {
1139
+ switch (_a.label) {
1140
+ case 0:
1141
+ address = _getAddress(address);
1142
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.maxWithdraw(address)];
1143
+ case 1:
1144
+ _assets = _a.sent();
1145
+ return [2 /*return*/, formatUnits(_assets, this.borrowed_token.decimals)];
1146
+ }
1147
+ });
1148
+ });
1149
+ };
1150
+ LendMarketTemplate.prototype.vaultPreviewWithdraw = function (amount) {
1151
+ return __awaiter(this, void 0, void 0, function () {
1152
+ var _amount, _shares;
1153
+ return __generator(this, function (_a) {
1154
+ switch (_a.label) {
1155
+ case 0:
1156
+ _amount = parseUnits(amount, this.borrowed_token.decimals);
1157
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.previewWithdraw(_amount)];
1158
+ case 1:
1159
+ _shares = _a.sent();
1160
+ return [2 /*return*/, formatUnits(_shares, 18)];
1161
+ }
1162
+ });
1163
+ });
1164
+ };
1165
+ LendMarketTemplate.prototype._vaultWithdraw = function (amount, estimateGas) {
1166
+ if (estimateGas === void 0) { estimateGas = false; }
1167
+ return __awaiter(this, void 0, void 0, function () {
1168
+ var _amount, gas, gasLimit;
1169
+ return __generator(this, function (_a) {
1170
+ switch (_a.label) {
1171
+ case 0:
1172
+ _amount = parseUnits(amount, this.borrowed_token.decimals);
1173
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.withdraw.estimateGas(_amount, __assign({}, llamalend.constantOptions))];
1174
+ case 1:
1175
+ gas = _a.sent();
1176
+ if (estimateGas)
1177
+ return [2 /*return*/, smartNumber(gas)];
1178
+ return [4 /*yield*/, llamalend.updateFeeData()];
1179
+ case 2:
1180
+ _a.sent();
1181
+ gasLimit = _mulBy1_3(DIGas(gas));
1182
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.withdraw(_amount, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
1183
+ case 3: return [2 /*return*/, (_a.sent()).hash];
1184
+ }
1185
+ });
1186
+ });
1187
+ };
1188
+ LendMarketTemplate.prototype.vaultWithdrawEstimateGas = function (amount) {
1189
+ return __awaiter(this, void 0, void 0, function () {
1190
+ return __generator(this, function (_a) {
1191
+ switch (_a.label) {
1192
+ case 0: return [4 /*yield*/, this._vaultWithdraw(amount, true)];
1193
+ case 1: return [2 /*return*/, _a.sent()];
1194
+ }
1195
+ });
1196
+ });
1197
+ };
1198
+ LendMarketTemplate.prototype.vaultWithdraw = function (amount) {
1199
+ return __awaiter(this, void 0, void 0, function () {
1200
+ return __generator(this, function (_a) {
1201
+ switch (_a.label) {
1202
+ case 0: return [4 /*yield*/, this._vaultWithdraw(amount, false)];
1203
+ case 1: return [2 /*return*/, _a.sent()];
1204
+ }
1205
+ });
1206
+ });
1207
+ };
1208
+ LendMarketTemplate.prototype.vaultMaxRedeem = function (address) {
1209
+ if (address === void 0) { address = ""; }
1210
+ return __awaiter(this, void 0, void 0, function () {
1211
+ var _shares;
1212
+ return __generator(this, function (_a) {
1213
+ switch (_a.label) {
1214
+ case 0:
1215
+ address = _getAddress(address);
1216
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.maxRedeem(address)];
1217
+ case 1:
1218
+ _shares = _a.sent();
1219
+ return [2 /*return*/, formatUnits(_shares, 18)];
1220
+ }
1221
+ });
1222
+ });
1223
+ };
1224
+ LendMarketTemplate.prototype.vaultPreviewRedeem = function (amount) {
1225
+ return __awaiter(this, void 0, void 0, function () {
1226
+ var _amount, _assets;
1227
+ return __generator(this, function (_a) {
1228
+ switch (_a.label) {
1229
+ case 0:
1230
+ _amount = parseUnits(amount, 18);
1231
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.previewRedeem(_amount)];
1232
+ case 1:
1233
+ _assets = _a.sent();
1234
+ return [2 /*return*/, formatUnits(_assets, this.borrowed_token.decimals)];
1235
+ }
1236
+ });
1237
+ });
1238
+ };
1239
+ LendMarketTemplate.prototype._vaultRedeem = function (amount, estimateGas) {
1240
+ if (estimateGas === void 0) { estimateGas = false; }
1241
+ return __awaiter(this, void 0, void 0, function () {
1242
+ var _amount, gas, gasLimit;
1243
+ return __generator(this, function (_a) {
1244
+ switch (_a.label) {
1245
+ case 0:
1246
+ _amount = parseUnits(amount, 18);
1247
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.redeem.estimateGas(_amount, __assign({}, llamalend.constantOptions))];
1248
+ case 1:
1249
+ gas = _a.sent();
1250
+ if (estimateGas)
1251
+ return [2 /*return*/, smartNumber(gas)];
1252
+ return [4 /*yield*/, llamalend.updateFeeData()];
1253
+ case 2:
1254
+ _a.sent();
1255
+ gasLimit = _mulBy1_3(DIGas(gas));
1256
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.redeem(_amount, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
1257
+ case 3: return [2 /*return*/, (_a.sent()).hash];
1258
+ }
1259
+ });
1260
+ });
1261
+ };
1262
+ LendMarketTemplate.prototype.vaultRedeemEstimateGas = function (amount) {
1263
+ return __awaiter(this, void 0, void 0, function () {
1264
+ return __generator(this, function (_a) {
1265
+ switch (_a.label) {
1266
+ case 0: return [4 /*yield*/, this._vaultRedeem(amount, true)];
1267
+ case 1: return [2 /*return*/, _a.sent()];
1268
+ }
1269
+ });
1270
+ });
1271
+ };
1272
+ LendMarketTemplate.prototype.vaultRedeem = function (amount) {
1273
+ return __awaiter(this, void 0, void 0, function () {
1274
+ return __generator(this, function (_a) {
1275
+ switch (_a.label) {
1276
+ case 0: return [4 /*yield*/, this._vaultRedeem(amount, false)];
1277
+ case 1: return [2 /*return*/, _a.sent()];
1278
+ }
1279
+ });
1280
+ });
1281
+ };
1282
+ // ---------------- VAULT UTILS ----------------
1283
+ LendMarketTemplate.prototype.vaultConvertToShares = function (assets) {
1284
+ return __awaiter(this, void 0, void 0, function () {
1285
+ var _assets, _shares;
1286
+ return __generator(this, function (_a) {
1287
+ switch (_a.label) {
1288
+ case 0:
1289
+ _assets = parseUnits(assets, this.borrowed_token.decimals);
1290
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.convertToShares(_assets)];
1291
+ case 1:
1292
+ _shares = _a.sent();
1293
+ return [2 /*return*/, llamalend.formatUnits(_shares)];
1294
+ }
1295
+ });
1296
+ });
1297
+ };
1298
+ LendMarketTemplate.prototype.vaultConvertToAssets = function (shares) {
1299
+ return __awaiter(this, void 0, void 0, function () {
1300
+ var _shares, _assets;
1301
+ return __generator(this, function (_a) {
1302
+ switch (_a.label) {
1303
+ case 0:
1304
+ _shares = parseUnits(shares);
1305
+ return [4 /*yield*/, llamalend.contracts[this.addresses.vault].contract.convertToAssets(_shares)];
1306
+ case 1:
1307
+ _assets = _a.sent();
1308
+ return [2 /*return*/, llamalend.formatUnits(_assets, this.borrowed_token.decimals)];
1309
+ }
1310
+ });
1311
+ });
1312
+ };
1313
+ // ---------------- VAULT STAKING ----------------
1314
+ LendMarketTemplate.prototype.vaultStakeIsApproved = function (vaultShares) {
1315
+ return __awaiter(this, void 0, void 0, function () {
1316
+ return __generator(this, function (_a) {
1317
+ switch (_a.label) {
1318
+ case 0:
1319
+ if (this.addresses.gauge === llamalend.constants.ZERO_ADDRESS) {
1320
+ throw Error("stakeIsApproved method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1321
+ }
1322
+ return [4 /*yield*/, hasAllowance([this.addresses.vault], [vaultShares], llamalend.signerAddress, this.addresses.gauge)];
1323
+ case 1: return [2 /*return*/, _a.sent()];
1324
+ }
1325
+ });
1326
+ });
1327
+ };
1328
+ LendMarketTemplate.prototype.vaultStakeApproveEstimateGas = function (vaultShares) {
1329
+ return __awaiter(this, void 0, void 0, function () {
1330
+ return __generator(this, function (_a) {
1331
+ switch (_a.label) {
1332
+ case 0:
1333
+ if (this.addresses.gauge === llamalend.constants.ZERO_ADDRESS) {
1334
+ throw Error("stakeApproveEstimateGas method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1335
+ }
1336
+ return [4 /*yield*/, ensureAllowanceEstimateGas([this.addresses.vault], [vaultShares], this.addresses.gauge)];
1337
+ case 1: return [2 /*return*/, _a.sent()];
1338
+ }
1339
+ });
1340
+ });
1341
+ };
1342
+ LendMarketTemplate.prototype.vaultStakeApprove = function (vaultShares) {
1343
+ return __awaiter(this, void 0, void 0, function () {
1344
+ return __generator(this, function (_a) {
1345
+ switch (_a.label) {
1346
+ case 0:
1347
+ if (this.addresses.gauge === llamalend.constants.ZERO_ADDRESS) {
1348
+ throw Error("stakeApprove method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1349
+ }
1350
+ return [4 /*yield*/, ensureAllowance([this.addresses.vault], [vaultShares], this.addresses.gauge)];
1351
+ case 1: return [2 /*return*/, _a.sent()];
1352
+ }
1353
+ });
1354
+ });
1355
+ };
1356
+ LendMarketTemplate.prototype.vaultStakeEstimateGas = function (vaultShares) {
1357
+ return __awaiter(this, void 0, void 0, function () {
1358
+ var _vaultShares, _a;
1359
+ return __generator(this, function (_c) {
1360
+ switch (_c.label) {
1361
+ case 0:
1362
+ if (this.addresses.gauge === llamalend.constants.ZERO_ADDRESS) {
1363
+ throw Error("stakeEstimateGas method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1364
+ }
1365
+ _vaultShares = parseUnits(vaultShares);
1366
+ _a = smartNumber;
1367
+ return [4 /*yield*/, llamalend.contracts[this.addresses.gauge].contract.deposit.estimateGas(_vaultShares, llamalend.constantOptions)];
1368
+ case 1: return [2 /*return*/, _a.apply(void 0, [_c.sent()])];
1369
+ }
1370
+ });
1371
+ });
1372
+ };
1373
+ LendMarketTemplate.prototype.vaultStake = function (vaultShares) {
1374
+ return __awaiter(this, void 0, void 0, function () {
1375
+ var _vaultShares, gasLimit, _a, _c;
1376
+ return __generator(this, function (_d) {
1377
+ switch (_d.label) {
1378
+ case 0:
1379
+ if (this.addresses.gauge === llamalend.constants.ZERO_ADDRESS) {
1380
+ throw Error("stake method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1381
+ }
1382
+ _vaultShares = parseUnits(vaultShares);
1383
+ return [4 /*yield*/, _ensureAllowance([this.addresses.vault], [_vaultShares], this.addresses.gauge)];
1384
+ case 1:
1385
+ _d.sent();
1386
+ return [4 /*yield*/, llamalend.updateFeeData()];
1387
+ case 2:
1388
+ _d.sent();
1389
+ _a = _mulBy1_3;
1390
+ _c = DIGas;
1391
+ return [4 /*yield*/, llamalend.contracts[this.addresses.gauge].contract.deposit.estimateGas(_vaultShares, llamalend.constantOptions)];
1392
+ case 3:
1393
+ gasLimit = _a.apply(void 0, [_c.apply(void 0, [_d.sent()])]);
1394
+ return [4 /*yield*/, llamalend.contracts[this.addresses.gauge].contract.deposit(_vaultShares, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
1395
+ case 4: return [2 /*return*/, (_d.sent()).hash];
1396
+ }
1397
+ });
1398
+ });
1399
+ };
1400
+ LendMarketTemplate.prototype.vaultUnstakeEstimateGas = function (vaultShares) {
1401
+ return __awaiter(this, void 0, void 0, function () {
1402
+ var _vaultShares, _a;
1403
+ return __generator(this, function (_c) {
1404
+ switch (_c.label) {
1405
+ case 0:
1406
+ if (this.addresses.gauge === llamalend.constants.ZERO_ADDRESS) {
1407
+ throw Error("unstakeEstimateGas method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1408
+ }
1409
+ _vaultShares = parseUnits(vaultShares);
1410
+ _a = smartNumber;
1411
+ return [4 /*yield*/, llamalend.contracts[this.addresses.gauge].contract.withdraw.estimateGas(_vaultShares, llamalend.constantOptions)];
1412
+ case 1: return [2 /*return*/, _a.apply(void 0, [_c.sent()])];
1413
+ }
1414
+ });
1415
+ });
1416
+ };
1417
+ LendMarketTemplate.prototype.vaultUnstake = function (vaultShares) {
1418
+ return __awaiter(this, void 0, void 0, function () {
1419
+ var _vaultShares, gasLimit, _a, _c;
1420
+ return __generator(this, function (_d) {
1421
+ switch (_d.label) {
1422
+ case 0:
1423
+ if (this.addresses.gauge === llamalend.constants.ZERO_ADDRESS) {
1424
+ throw Error("unstake method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1425
+ }
1426
+ _vaultShares = parseUnits(vaultShares);
1427
+ return [4 /*yield*/, llamalend.updateFeeData()];
1428
+ case 1:
1429
+ _d.sent();
1430
+ _a = _mulBy1_3;
1431
+ _c = DIGas;
1432
+ return [4 /*yield*/, llamalend.contracts[this.addresses.gauge].contract.withdraw.estimateGas(_vaultShares, llamalend.constantOptions)];
1433
+ case 2:
1434
+ gasLimit = _a.apply(void 0, [_c.apply(void 0, [(_d.sent())])]);
1435
+ return [4 /*yield*/, llamalend.contracts[this.addresses.gauge].contract.withdraw(_vaultShares, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
1436
+ case 3: return [2 /*return*/, (_d.sent()).hash];
1437
+ }
1438
+ });
1439
+ });
1440
+ };
1441
+ // ---------------- VAULT STAKING REWARDS ----------------
1442
+ LendMarketTemplate.prototype.vaultRewardsOnly = function () {
1443
+ if (llamalend.chainId === 2222 || llamalend.chainId === 324)
1444
+ return true; // TODO remove this for Kava and ZkSync
1445
+ if (this.addresses.gauge === llamalend.constants.ZERO_ADDRESS)
1446
+ throw Error("".concat(this.name, " doesn't have gauge"));
1447
+ var gaugeContract = llamalend.contracts[this.addresses.gauge].contract;
1448
+ return !('inflation_rate()' in gaugeContract || 'inflation_rate(uint256)' in gaugeContract);
1449
+ };
1450
+ LendMarketTemplate.prototype.vaultTotalLiquidity = function (useAPI) {
1451
+ if (useAPI === void 0) { useAPI = true; }
1452
+ return __awaiter(this, void 0, void 0, function () {
1453
+ var cap, price;
1454
+ return __generator(this, function (_a) {
1455
+ switch (_a.label) {
1456
+ case 0: return [4 /*yield*/, this.statsCapAndAvailable(true, useAPI)];
1457
+ case 1:
1458
+ cap = (_a.sent()).cap;
1459
+ return [4 /*yield*/, _getUsdRate(this.addresses.borrowed_token)];
1460
+ case 2:
1461
+ price = _a.sent();
1462
+ return [2 /*return*/, BN(cap).times(price).toFixed(6)];
1463
+ }
1464
+ });
1465
+ });
1466
+ };
1467
+ LendMarketTemplate.prototype.vaultCrvApr = function (useApi) {
1468
+ if (useApi === void 0) { useApi = true; }
1469
+ return __awaiter(this, void 0, void 0, function () {
1470
+ return __generator(this, function (_a) {
1471
+ switch (_a.label) {
1472
+ case 0:
1473
+ if (this.vaultRewardsOnly())
1474
+ throw Error("".concat(this.name, " has Rewards-Only Gauge. Use stats.rewardsApy instead"));
1475
+ return [4 /*yield*/, this._calcCrvApr()];
1476
+ case 1:
1477
+ // const isDisabledChain = [1313161554].includes(llamalend.chainId); // Disable Aurora
1478
+ // if (useApi && !isDisabledChain) {
1479
+ // const crvAPYs = await _getCrvApyFromApi();
1480
+ // const poolCrvApy = crvAPYs[this.addresses.gauge] ?? [0, 0]; // new pools might be missing
1481
+ // return [poolCrvApy[0], poolCrvApy[1]];
1482
+ // }
1483
+ return [2 /*return*/, _a.sent()];
1484
+ }
1485
+ });
1486
+ });
1487
+ };
1488
+ LendMarketTemplate.prototype.vaultClaimableCrv = function (address) {
1489
+ if (address === void 0) { address = ""; }
1490
+ return __awaiter(this, void 0, void 0, function () {
1491
+ var _a, _c;
1492
+ return __generator(this, function (_d) {
1493
+ switch (_d.label) {
1494
+ case 0:
1495
+ if (this.vaultRewardsOnly())
1496
+ throw Error("".concat(this.name, " has Rewards-Only Gauge. Use claimableRewards instead"));
1497
+ address = address || llamalend.signerAddress;
1498
+ if (!address)
1499
+ throw Error("Need to connect wallet or pass address into args");
1500
+ _c = (_a = llamalend).formatUnits;
1501
+ return [4 /*yield*/, llamalend.contracts[this.addresses.gauge].contract.claimable_tokens(address, llamalend.constantOptions)];
1502
+ case 1: return [2 /*return*/, _c.apply(_a, [_d.sent()])];
1503
+ }
1504
+ });
1505
+ });
1506
+ };
1507
+ LendMarketTemplate.prototype._vaultClaimCrv = function (estimateGas) {
1508
+ return __awaiter(this, void 0, void 0, function () {
1509
+ var contract, gas, gasLimit;
1510
+ return __generator(this, function (_a) {
1511
+ switch (_a.label) {
1512
+ case 0:
1513
+ if (this.vaultRewardsOnly())
1514
+ throw Error("".concat(this.name, " has Rewards-Only Gauge. Use claimRewards instead"));
1515
+ contract = llamalend.contracts[llamalend.constants.ALIASES.minter].contract;
1516
+ return [4 /*yield*/, contract.mint.estimateGas(this.addresses.gauge, llamalend.constantOptions)];
1517
+ case 1:
1518
+ gas = _a.sent();
1519
+ if (estimateGas)
1520
+ return [2 /*return*/, smartNumber(gas)];
1521
+ return [4 /*yield*/, llamalend.updateFeeData()];
1522
+ case 2:
1523
+ _a.sent();
1524
+ gasLimit = _mulBy1_3(DIGas(gas));
1525
+ return [4 /*yield*/, contract.mint(this.addresses.gauge, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
1526
+ case 3: return [2 /*return*/, (_a.sent()).hash];
1527
+ }
1528
+ });
1529
+ });
1530
+ };
1531
+ LendMarketTemplate.prototype.vaultClaimCrvEstimateGas = function () {
1532
+ return __awaiter(this, void 0, void 0, function () {
1533
+ return __generator(this, function (_a) {
1534
+ switch (_a.label) {
1535
+ case 0: return [4 /*yield*/, this._vaultClaimCrv(true)];
1536
+ case 1: return [2 /*return*/, _a.sent()];
1537
+ }
1538
+ });
1539
+ });
1540
+ };
1541
+ LendMarketTemplate.prototype.vaultClaimCrv = function () {
1542
+ return __awaiter(this, void 0, void 0, function () {
1543
+ return __generator(this, function (_a) {
1544
+ switch (_a.label) {
1545
+ case 0: return [4 /*yield*/, this._vaultClaimCrv(false)];
1546
+ case 1: return [2 /*return*/, _a.sent()];
1547
+ }
1548
+ });
1549
+ });
1550
+ };
1551
+ LendMarketTemplate.prototype.vaultClaimableRewards = function (address) {
1552
+ if (address === void 0) { address = ""; }
1553
+ return __awaiter(this, void 0, void 0, function () {
1554
+ var gaugeContract, rewardTokens, rewards, _a, rewardTokens_2, rewardToken, _amount;
1555
+ return __generator(this, function (_c) {
1556
+ switch (_c.label) {
1557
+ case 0:
1558
+ if (this.addresses.gauge === llamalend.constants.ZERO_ADDRESS) {
1559
+ throw Error("claimableRewards method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1560
+ }
1561
+ address = address || llamalend.signerAddress;
1562
+ if (!address)
1563
+ throw Error("Need to connect wallet or pass address into args");
1564
+ gaugeContract = llamalend.contracts[this.addresses.gauge].contract;
1565
+ return [4 /*yield*/, this.vaultRewardTokens()];
1566
+ case 1:
1567
+ rewardTokens = _c.sent();
1568
+ rewards = [];
1569
+ _a = 0, rewardTokens_2 = rewardTokens;
1570
+ _c.label = 2;
1571
+ case 2:
1572
+ if (!(_a < rewardTokens_2.length)) return [3 /*break*/, 5];
1573
+ rewardToken = rewardTokens_2[_a];
1574
+ return [4 /*yield*/, gaugeContract.claimable_reward(address, rewardToken.token, llamalend.constantOptions)];
1575
+ case 3:
1576
+ _amount = _c.sent();
1577
+ rewards.push({
1578
+ token: rewardToken.token,
1579
+ symbol: rewardToken.symbol,
1580
+ amount: llamalend.formatUnits(_amount, rewardToken.decimals),
1581
+ });
1582
+ _c.label = 4;
1583
+ case 4:
1584
+ _a++;
1585
+ return [3 /*break*/, 2];
1586
+ case 5: return [2 /*return*/, rewards];
1587
+ }
1588
+ });
1589
+ });
1590
+ };
1591
+ LendMarketTemplate.prototype._vaultClaimRewards = function (estimateGas) {
1592
+ return __awaiter(this, void 0, void 0, function () {
1593
+ var gaugeContract, gas, gasLimit;
1594
+ return __generator(this, function (_a) {
1595
+ switch (_a.label) {
1596
+ case 0:
1597
+ if (this.addresses.gauge === llamalend.constants.ZERO_ADDRESS) {
1598
+ throw Error("claimRewards method doesn't exist for pool ".concat(this.name, " (id: ").concat(this.name, "). There is no gauge"));
1599
+ }
1600
+ gaugeContract = llamalend.contracts[this.addresses.gauge].contract;
1601
+ if (!("claim_rewards()" in gaugeContract))
1602
+ throw Error("".concat(this.name, " pool doesn't have such method"));
1603
+ return [4 /*yield*/, gaugeContract.claim_rewards.estimateGas(llamalend.constantOptions)];
1604
+ case 1:
1605
+ gas = _a.sent();
1606
+ if (estimateGas)
1607
+ return [2 /*return*/, smartNumber(gas)];
1608
+ return [4 /*yield*/, llamalend.updateFeeData()];
1609
+ case 2:
1610
+ _a.sent();
1611
+ gasLimit = _mulBy1_3(DIGas(gas));
1612
+ return [4 /*yield*/, gaugeContract.claim_rewards(__assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
1613
+ case 3: return [2 /*return*/, (_a.sent()).hash];
1614
+ }
1615
+ });
1616
+ });
1617
+ };
1618
+ LendMarketTemplate.prototype.vaultClaimRewardsEstimateGas = function () {
1619
+ return __awaiter(this, void 0, void 0, function () {
1620
+ return __generator(this, function (_a) {
1621
+ switch (_a.label) {
1622
+ case 0: return [4 /*yield*/, this._vaultClaimRewards(true)];
1623
+ case 1: return [2 /*return*/, _a.sent()];
1624
+ }
1625
+ });
1626
+ });
1627
+ };
1628
+ LendMarketTemplate.prototype.vaultClaimRewards = function () {
1629
+ return __awaiter(this, void 0, void 0, function () {
1630
+ return __generator(this, function (_a) {
1631
+ switch (_a.label) {
1632
+ case 0: return [4 /*yield*/, this._vaultClaimRewards(false)];
1633
+ case 1: return [2 /*return*/, _a.sent()];
1634
+ }
1635
+ });
1636
+ });
1637
+ };
1638
+ LendMarketTemplate.prototype.statsRates = function (isGetter, useAPI) {
1639
+ if (isGetter === void 0) { isGetter = true; }
1640
+ if (useAPI === void 0) { useAPI = false; }
1641
+ return __awaiter(this, void 0, void 0, function () {
1642
+ var response, market, _rate, borrowApr, borrowApy, lendApr, lendApy, debt, cap, debtInAYearBN;
1643
+ var _this = this;
1644
+ return __generator(this, function (_a) {
1645
+ switch (_a.label) {
1646
+ case 0:
1647
+ if (!useAPI) return [3 /*break*/, 2];
1648
+ return [4 /*yield*/, _getMarketsData(llamalend.constants.NETWORK_NAME)];
1649
+ case 1:
1650
+ response = _a.sent();
1651
+ market = response.lendingVaultData.find(function (item) { return item.address.toLowerCase() === _this.addresses.vault.toLowerCase(); });
1652
+ if (market) {
1653
+ return [2 /*return*/, {
1654
+ borrowApr: (market.rates.borrowApr * 100).toString(),
1655
+ lendApr: (market.rates.lendApr * 100).toString(),
1656
+ borrowApy: (market.rates.borrowApy * 100).toString(),
1657
+ lendApy: (market.rates.lendApy * 100).toString(),
1658
+ }];
1659
+ }
1660
+ else {
1661
+ throw new Error('Market not found in API');
1662
+ }
1663
+ return [3 /*break*/, 7];
1664
+ case 2: return [4 /*yield*/, this._getRate(isGetter)];
1665
+ case 3:
1666
+ _rate = _a.sent();
1667
+ borrowApr = toBN(_rate).times(365).times(86400).times(100).toString();
1668
+ borrowApy = String(((Math.pow(2.718281828459, (toBN(_rate).times(365).times(86400)).toNumber())) - 1) * 100);
1669
+ lendApr = "0";
1670
+ lendApy = "0";
1671
+ return [4 /*yield*/, this.statsTotalDebt(isGetter)];
1672
+ case 4:
1673
+ debt = _a.sent();
1674
+ if (!(Number(debt) > 0)) return [3 /*break*/, 6];
1675
+ return [4 /*yield*/, this.statsCapAndAvailable(isGetter)];
1676
+ case 5:
1677
+ cap = (_a.sent()).cap;
1678
+ lendApr = toBN(_rate).times(365).times(86400).times(debt).div(cap).times(100).toString();
1679
+ debtInAYearBN = BN(debt).times(Math.pow(2.718281828459, (toBN(_rate).times(365).times(86400)).toNumber()));
1680
+ lendApy = debtInAYearBN.minus(debt).div(cap).times(100).toString();
1681
+ _a.label = 6;
1682
+ case 6: return [2 /*return*/, { borrowApr: borrowApr, lendApr: lendApr, borrowApy: borrowApy, lendApy: lendApy }];
1683
+ case 7: return [2 /*return*/];
1684
+ }
1685
+ });
1686
+ });
1687
+ };
1688
+ LendMarketTemplate.prototype.statsFutureRates = function (dReserves, dDebt, useAPI) {
1689
+ if (useAPI === void 0) { useAPI = true; }
1690
+ return __awaiter(this, void 0, void 0, function () {
1691
+ var _dReserves, _dDebt, _rate, borrowApr, borrowApy, lendApr, lendApy, debt, _a, cap, _c, debtInAYearBN;
1692
+ return __generator(this, function (_d) {
1693
+ switch (_d.label) {
1694
+ case 0:
1695
+ _dReserves = parseUnits(dReserves, this.borrowed_token.decimals);
1696
+ _dDebt = parseUnits(dDebt, this.borrowed_token.decimals);
1697
+ return [4 /*yield*/, this._getFutureRate(_dReserves, _dDebt)];
1698
+ case 1:
1699
+ _rate = _d.sent();
1700
+ borrowApr = toBN(_rate).times(365).times(86400).times(100).toString();
1701
+ borrowApy = String(((Math.pow(2.718281828459, (toBN(_rate).times(365).times(86400)).toNumber())) - 1) * 100);
1702
+ lendApr = "0";
1703
+ lendApy = "0";
1704
+ _a = Number;
1705
+ return [4 /*yield*/, this.statsTotalDebt()];
1706
+ case 2:
1707
+ debt = _a.apply(void 0, [_d.sent()]) + Number(dDebt);
1708
+ if (!(Number(debt) > 0)) return [3 /*break*/, 4];
1709
+ _c = Number;
1710
+ return [4 /*yield*/, this.statsCapAndAvailable(true, useAPI)];
1711
+ case 3:
1712
+ cap = _c.apply(void 0, [(_d.sent()).cap]) + Number(dReserves);
1713
+ lendApr = toBN(_rate).times(365).times(86400).times(debt).div(cap).times(100).toString();
1714
+ debtInAYearBN = BN(debt).times(Math.pow(2.718281828459, (toBN(_rate).times(365).times(86400)).toNumber()));
1715
+ lendApy = debtInAYearBN.minus(debt).div(cap).times(100).toString();
1716
+ _d.label = 4;
1717
+ case 4: return [2 /*return*/, { borrowApr: borrowApr, lendApr: lendApr, borrowApy: borrowApy, lendApy: lendApy }];
1718
+ }
1719
+ });
1720
+ });
1721
+ };
1722
+ LendMarketTemplate.prototype.statsBalances = function () {
1723
+ return __awaiter(this, void 0, void 0, function () {
1724
+ var borrowedContract, collateralContract, ammContract, calls, _a, _borrowedBalance, _collateralBalance, _borrowedAdminFees, _collateralAdminFees;
1725
+ return __generator(this, function (_c) {
1726
+ switch (_c.label) {
1727
+ case 0:
1728
+ borrowedContract = llamalend.contracts[this.borrowed_token.address].multicallContract;
1729
+ collateralContract = llamalend.contracts[this.collateral_token.address].multicallContract;
1730
+ ammContract = llamalend.contracts[this.addresses.amm].multicallContract;
1731
+ calls = [
1732
+ borrowedContract.balanceOf(this.addresses.amm),
1733
+ collateralContract.balanceOf(this.addresses.amm),
1734
+ ammContract.admin_fees_x(),
1735
+ ammContract.admin_fees_y(),
1736
+ ];
1737
+ return [4 /*yield*/, llamalend.multicallProvider.all(calls)];
1738
+ case 1:
1739
+ _a = _c.sent(), _borrowedBalance = _a[0], _collateralBalance = _a[1], _borrowedAdminFees = _a[2], _collateralAdminFees = _a[3];
1740
+ return [2 /*return*/, [
1741
+ formatUnits(_borrowedBalance - _borrowedAdminFees, this.borrowed_token.decimals),
1742
+ formatUnits(_collateralBalance - _collateralAdminFees, this.collateral_token.decimals),
1743
+ ]];
1744
+ }
1745
+ });
1746
+ });
1747
+ };
1748
+ LendMarketTemplate.prototype.statsBandBalances = function (n) {
1749
+ return __awaiter(this, void 0, void 0, function () {
1750
+ var ammContract, calls, _balances;
1751
+ return __generator(this, function (_a) {
1752
+ switch (_a.label) {
1753
+ case 0:
1754
+ ammContract = llamalend.contracts[this.addresses.amm].multicallContract;
1755
+ calls = [];
1756
+ calls.push(ammContract.bands_x(n), ammContract.bands_y(n));
1757
+ return [4 /*yield*/, llamalend.multicallProvider.all(calls)];
1758
+ case 1:
1759
+ _balances = _a.sent();
1760
+ // bands_x and bands_y always return amounts with 18 decimals
1761
+ return [2 /*return*/, {
1762
+ borrowed: formatNumber(formatUnits(_balances[0]), this.borrowed_token.decimals),
1763
+ collateral: formatNumber(formatUnits(_balances[1]), this.collateral_token.decimals),
1764
+ }];
1765
+ }
1766
+ });
1767
+ });
1768
+ };
1769
+ LendMarketTemplate.prototype.statsBandsBalances = function () {
1770
+ return __awaiter(this, void 0, void 0, function () {
1771
+ var _a, maxBand, minBand, ammContract, calls, i, _bands, bands, i, _i;
1772
+ return __generator(this, function (_c) {
1773
+ switch (_c.label) {
1774
+ case 0: return [4 /*yield*/, this.statsBandsInfo()];
1775
+ case 1:
1776
+ _a = _c.sent(), maxBand = _a.maxBand, minBand = _a.minBand;
1777
+ ammContract = llamalend.contracts[this.addresses.amm].multicallContract;
1778
+ calls = [];
1779
+ for (i = minBand; i <= maxBand; i++) {
1780
+ calls.push(ammContract.bands_x(i), ammContract.bands_y(i));
1781
+ }
1782
+ return [4 /*yield*/, llamalend.multicallProvider.all(calls)];
1783
+ case 2:
1784
+ _bands = _c.sent();
1785
+ bands = {};
1786
+ for (i = minBand; i <= maxBand; i++) {
1787
+ _i = i - minBand;
1788
+ // bands_x and bands_y always return amounts with 18 decimals
1789
+ bands[i] = {
1790
+ borrowed: formatNumber(formatUnits(_bands[2 * _i]), this.borrowed_token.decimals),
1791
+ collateral: formatNumber(formatUnits(_bands[(2 * _i) + 1]), this.collateral_token.decimals),
1792
+ };
1793
+ }
1794
+ return [2 /*return*/, bands];
1795
+ }
1796
+ });
1797
+ });
1798
+ };
1799
+ LendMarketTemplate.prototype.statsTotalDebt = function (isGetter, useAPI) {
1800
+ if (isGetter === void 0) { isGetter = true; }
1801
+ if (useAPI === void 0) { useAPI = true; }
1802
+ return __awaiter(this, void 0, void 0, function () {
1803
+ var response, market, _debt;
1804
+ var _this = this;
1805
+ return __generator(this, function (_a) {
1806
+ switch (_a.label) {
1807
+ case 0:
1808
+ if (!useAPI) return [3 /*break*/, 2];
1809
+ return [4 /*yield*/, _getMarketsData(llamalend.constants.NETWORK_NAME)];
1810
+ case 1:
1811
+ response = _a.sent();
1812
+ market = response.lendingVaultData.find(function (item) { return item.address.toLowerCase() === _this.addresses.vault.toLowerCase(); });
1813
+ if (market) {
1814
+ return [2 /*return*/, market.borrowed.total.toString()];
1815
+ }
1816
+ else {
1817
+ throw new Error('Market not found in API');
1818
+ }
1819
+ return [3 /*break*/, 6];
1820
+ case 2:
1821
+ _debt = void 0;
1822
+ if (!isGetter) return [3 /*break*/, 3];
1823
+ _debt = cacheStats.get(cacheKey(this.addresses.controller, 'total_debt'));
1824
+ return [3 /*break*/, 5];
1825
+ case 3: return [4 /*yield*/, llamalend.contracts[this.addresses.controller].contract.total_debt(llamalend.constantOptions)];
1826
+ case 4:
1827
+ _debt = _a.sent();
1828
+ cacheStats.set(cacheKey(this.addresses.controller, 'total_debt'), _debt);
1829
+ _a.label = 5;
1830
+ case 5: return [2 /*return*/, formatUnits(_debt, this.borrowed_token.decimals)];
1831
+ case 6: return [2 /*return*/];
1832
+ }
1833
+ });
1834
+ });
1835
+ };
1836
+ LendMarketTemplate.prototype.statsCapAndAvailable = function (isGetter, useAPI) {
1837
+ if (isGetter === void 0) { isGetter = true; }
1838
+ if (useAPI === void 0) { useAPI = false; }
1839
+ return __awaiter(this, void 0, void 0, function () {
1840
+ var response, market, vaultContract, borrowedContract, _cap, _available;
1841
+ var _a;
1842
+ var _this = this;
1843
+ return __generator(this, function (_c) {
1844
+ switch (_c.label) {
1845
+ case 0:
1846
+ if (!useAPI) return [3 /*break*/, 2];
1847
+ return [4 /*yield*/, _getMarketsData(llamalend.constants.NETWORK_NAME)];
1848
+ case 1:
1849
+ response = _c.sent();
1850
+ market = response.lendingVaultData.find(function (item) { return item.address.toLowerCase() === _this.addresses.vault.toLowerCase(); });
1851
+ if (market) {
1852
+ return [2 /*return*/, {
1853
+ cap: market.totalSupplied.total.toString(),
1854
+ available: market.availableToBorrow.total.toString(),
1855
+ }];
1856
+ }
1857
+ else {
1858
+ throw new Error('Market not found in API');
1859
+ }
1860
+ return [3 /*break*/, 6];
1861
+ case 2:
1862
+ vaultContract = llamalend.contracts[this.addresses.vault].multicallContract;
1863
+ borrowedContract = llamalend.contracts[this.addresses.borrowed_token].multicallContract;
1864
+ _cap = void 0, _available = void 0;
1865
+ if (!isGetter) return [3 /*break*/, 3];
1866
+ _cap = cacheStats.get(cacheKey(this.addresses.vault, 'totalAssets', this.addresses.controller));
1867
+ _available = cacheStats.get(cacheKey(this.addresses.borrowed_token, 'balanceOf', this.addresses.controller));
1868
+ return [3 /*break*/, 5];
1869
+ case 3: return [4 /*yield*/, llamalend.multicallProvider.all([
1870
+ vaultContract.totalAssets(this.addresses.controller),
1871
+ borrowedContract.balanceOf(this.addresses.controller),
1872
+ ])];
1873
+ case 4:
1874
+ _a = _c.sent(), _cap = _a[0], _available = _a[1];
1875
+ cacheStats.set(cacheKey(this.addresses.vault, 'totalAssets', this.addresses.controller), _cap);
1876
+ cacheStats.set(cacheKey(this.addresses.borrowed_token, 'balanceOf', this.addresses.controller), _available);
1877
+ _c.label = 5;
1878
+ case 5: return [2 /*return*/, {
1879
+ cap: llamalend.formatUnits(_cap, this.borrowed_token.decimals),
1880
+ available: llamalend.formatUnits(_available, this.borrowed_token.decimals),
1881
+ }];
1882
+ case 6: return [2 /*return*/];
1883
+ }
1884
+ });
1885
+ });
1886
+ };
1887
+ LendMarketTemplate.prototype.oraclePriceBand = function () {
1888
+ return __awaiter(this, void 0, void 0, function () {
1889
+ var oraclePriceBN, _a, basePriceBN, _c, A_BN, _d, multiplier, term, compareFunc, band, currentTickPriceBN;
1890
+ return __generator(this, function (_e) {
1891
+ switch (_e.label) {
1892
+ case 0:
1893
+ _a = BN;
1894
+ return [4 /*yield*/, this.oraclePrice()];
1895
+ case 1:
1896
+ oraclePriceBN = _a.apply(void 0, [_e.sent()]);
1897
+ _c = BN;
1898
+ return [4 /*yield*/, this.basePrice()];
1899
+ case 2:
1900
+ basePriceBN = _c.apply(void 0, [_e.sent()]);
1901
+ _d = BN;
1902
+ return [4 /*yield*/, this.A()];
1903
+ case 3:
1904
+ A_BN = _d.apply(void 0, [_e.sent()]);
1905
+ multiplier = oraclePriceBN.lte(basePriceBN) ? A_BN.minus(1).div(A_BN) : A_BN.div(A_BN.minus(1));
1906
+ term = oraclePriceBN.lte(basePriceBN) ? 1 : -1;
1907
+ compareFunc = oraclePriceBN.lte(basePriceBN) ?
1908
+ function (oraclePriceBN, currentTickPriceBN) { return oraclePriceBN.lte(currentTickPriceBN); } :
1909
+ function (oraclePriceBN, currentTickPriceBN) { return oraclePriceBN.gt(currentTickPriceBN); };
1910
+ band = 0;
1911
+ currentTickPriceBN = oraclePriceBN.lte(basePriceBN) ? basePriceBN.times(multiplier) : basePriceBN;
1912
+ while (compareFunc(oraclePriceBN, currentTickPriceBN)) {
1913
+ currentTickPriceBN = currentTickPriceBN.times(multiplier);
1914
+ band += term;
1915
+ }
1916
+ return [2 /*return*/, band];
1917
+ }
1918
+ });
1919
+ });
1920
+ };
1921
+ LendMarketTemplate.prototype.price = function () {
1922
+ return __awaiter(this, void 0, void 0, function () {
1923
+ var _price;
1924
+ return __generator(this, function (_a) {
1925
+ switch (_a.label) {
1926
+ case 0: return [4 /*yield*/, llamalend.contracts[this.addresses.amm].contract.get_p(llamalend.constantOptions)];
1927
+ case 1:
1928
+ _price = _a.sent();
1929
+ return [2 /*return*/, formatUnits(_price)];
1930
+ }
1931
+ });
1932
+ });
1933
+ };
1934
+ LendMarketTemplate.prototype.calcTickPrice = function (n) {
1935
+ return __awaiter(this, void 0, void 0, function () {
1936
+ var basePrice, basePriceBN, A_BN, _a;
1937
+ return __generator(this, function (_c) {
1938
+ switch (_c.label) {
1939
+ case 0: return [4 /*yield*/, this.basePrice()];
1940
+ case 1:
1941
+ basePrice = _c.sent();
1942
+ basePriceBN = BN(basePrice);
1943
+ _a = BN;
1944
+ return [4 /*yield*/, this.A()];
1945
+ case 2:
1946
+ A_BN = _a.apply(void 0, [_c.sent()]);
1947
+ return [2 /*return*/, _cutZeros(basePriceBN.times(A_BN.minus(1).div(A_BN).pow(n)).toFixed(18))];
1948
+ }
1949
+ });
1950
+ });
1951
+ };
1952
+ LendMarketTemplate.prototype.calcBandPrices = function (n) {
1953
+ return __awaiter(this, void 0, void 0, function () {
1954
+ var _a;
1955
+ return __generator(this, function (_c) {
1956
+ switch (_c.label) {
1957
+ case 0: return [4 /*yield*/, this.calcTickPrice(n + 1)];
1958
+ case 1:
1959
+ _a = [_c.sent()];
1960
+ return [4 /*yield*/, this.calcTickPrice(n)];
1961
+ case 2: return [2 /*return*/, _a.concat([_c.sent()])];
1962
+ }
1963
+ });
1964
+ });
1965
+ };
1966
+ LendMarketTemplate.prototype.calcRangePct = function (range) {
1967
+ return __awaiter(this, void 0, void 0, function () {
1968
+ var A_BN, _a, startBN, endBN;
1969
+ return __generator(this, function (_c) {
1970
+ switch (_c.label) {
1971
+ case 0:
1972
+ _a = BN;
1973
+ return [4 /*yield*/, this.A()];
1974
+ case 1:
1975
+ A_BN = _a.apply(void 0, [_c.sent()]);
1976
+ startBN = BN(1);
1977
+ endBN = A_BN.minus(1).div(A_BN).pow(range);
1978
+ return [2 /*return*/, startBN.minus(endBN).times(100).toFixed(6)];
1979
+ }
1980
+ });
1981
+ });
1982
+ };
1983
+ // ---------------- WALLET BALANCES ----------------
1984
+ LendMarketTemplate.prototype.walletBalances = function (address) {
1985
+ if (address === void 0) { address = ""; }
1986
+ return __awaiter(this, void 0, void 0, function () {
1987
+ var _a, collateral, borrowed, vaultShares, _c, collateral, borrowed, vaultShares, gauge;
1988
+ return __generator(this, function (_d) {
1989
+ switch (_d.label) {
1990
+ case 0:
1991
+ if (!(this.addresses.gauge === llamalend.constants.ZERO_ADDRESS)) return [3 /*break*/, 2];
1992
+ return [4 /*yield*/, getBalances([this.collateral_token.address, this.borrowed_token.address, this.addresses.vault], address)];
1993
+ case 1:
1994
+ _a = _d.sent(), collateral = _a[0], borrowed = _a[1], vaultShares = _a[2];
1995
+ return [2 /*return*/, { collateral: collateral, borrowed: borrowed, vaultShares: vaultShares, gauge: "0" }];
1996
+ case 2: return [4 /*yield*/, getBalances([this.collateral_token.address, this.borrowed_token.address, this.addresses.vault, this.addresses.gauge], address)];
1997
+ case 3:
1998
+ _c = _d.sent(), collateral = _c[0], borrowed = _c[1], vaultShares = _c[2], gauge = _c[3];
1999
+ return [2 /*return*/, { collateral: collateral, borrowed: borrowed, vaultShares: vaultShares, gauge: gauge }];
2000
+ }
2001
+ });
2002
+ });
2003
+ };
2004
+ // ---------------- USER POSITION ----------------
2005
+ LendMarketTemplate.prototype.userLoanExists = function (address) {
2006
+ if (address === void 0) { address = ""; }
2007
+ return __awaiter(this, void 0, void 0, function () {
2008
+ return __generator(this, function (_a) {
2009
+ switch (_a.label) {
2010
+ case 0:
2011
+ address = _getAddress(address);
2012
+ return [4 /*yield*/, llamalend.contracts[this.addresses.controller].contract.loan_exists(address, llamalend.constantOptions)];
2013
+ case 1: return [2 /*return*/, _a.sent()];
2014
+ }
2015
+ });
2016
+ });
2017
+ };
2018
+ LendMarketTemplate.prototype.userState = function (address) {
2019
+ if (address === void 0) { address = ""; }
2020
+ return __awaiter(this, void 0, void 0, function () {
2021
+ var _a, _collateral, _borrowed, _debt, _N;
2022
+ return __generator(this, function (_c) {
2023
+ switch (_c.label) {
2024
+ case 0: return [4 /*yield*/, this._userState(address)];
2025
+ case 1:
2026
+ _a = _c.sent(), _collateral = _a._collateral, _borrowed = _a._borrowed, _debt = _a._debt, _N = _a._N;
2027
+ return [2 /*return*/, {
2028
+ collateral: formatUnits(_collateral, this.collateral_token.decimals),
2029
+ borrowed: formatUnits(_borrowed, this.borrowed_token.decimals),
2030
+ debt: formatUnits(_debt, this.borrowed_token.decimals),
2031
+ N: formatUnits(_N, 0),
2032
+ }];
2033
+ }
2034
+ });
2035
+ });
2036
+ };
2037
+ LendMarketTemplate.prototype.userHealth = function (full, address) {
2038
+ if (full === void 0) { full = true; }
2039
+ if (address === void 0) { address = ""; }
2040
+ return __awaiter(this, void 0, void 0, function () {
2041
+ var _health;
2042
+ return __generator(this, function (_a) {
2043
+ switch (_a.label) {
2044
+ case 0:
2045
+ address = _getAddress(address);
2046
+ return [4 /*yield*/, llamalend.contracts[this.addresses.controller].contract.health(address, full, llamalend.constantOptions)];
2047
+ case 1:
2048
+ _health = _a.sent();
2049
+ _health = _health * BigInt(100);
2050
+ return [2 /*return*/, formatUnits(_health)];
2051
+ }
2052
+ });
2053
+ });
2054
+ };
2055
+ LendMarketTemplate.prototype._userBands = function (address) {
2056
+ return __awaiter(this, void 0, void 0, function () {
2057
+ var _bands;
2058
+ return __generator(this, function (_a) {
2059
+ switch (_a.label) {
2060
+ case 0:
2061
+ address = _getAddress(address);
2062
+ return [4 /*yield*/, llamalend.contracts[this.addresses.amm].contract.read_user_tick_numbers(address, llamalend.constantOptions)];
2063
+ case 1:
2064
+ _bands = _a.sent();
2065
+ return [2 /*return*/, Array.from(_bands).reverse()];
2066
+ }
2067
+ });
2068
+ });
2069
+ };
2070
+ LendMarketTemplate.prototype.userBands = function (address) {
2071
+ if (address === void 0) { address = ""; }
2072
+ return __awaiter(this, void 0, void 0, function () {
2073
+ return __generator(this, function (_a) {
2074
+ switch (_a.label) {
2075
+ case 0: return [4 /*yield*/, this._userBands(address)];
2076
+ case 1: return [2 /*return*/, (_a.sent()).map(function (_t) { return Number(_t); })];
2077
+ }
2078
+ });
2079
+ });
2080
+ };
2081
+ LendMarketTemplate.prototype.userRange = function (address) {
2082
+ if (address === void 0) { address = ""; }
2083
+ return __awaiter(this, void 0, void 0, function () {
2084
+ var _a, n2, n1;
2085
+ return __generator(this, function (_c) {
2086
+ switch (_c.label) {
2087
+ case 0: return [4 /*yield*/, this.userBands(address)];
2088
+ case 1:
2089
+ _a = _c.sent(), n2 = _a[0], n1 = _a[1];
2090
+ if (n1 == n2)
2091
+ return [2 /*return*/, 0];
2092
+ return [2 /*return*/, n2 - n1 + 1];
2093
+ }
2094
+ });
2095
+ });
2096
+ };
2097
+ LendMarketTemplate.prototype.userPrices = function (address) {
2098
+ if (address === void 0) { address = ""; }
2099
+ return __awaiter(this, void 0, void 0, function () {
2100
+ var _prices;
2101
+ return __generator(this, function (_a) {
2102
+ switch (_a.label) {
2103
+ case 0:
2104
+ address = _getAddress(address);
2105
+ return [4 /*yield*/, llamalend.contracts[this.addresses.controller].contract.user_prices(address, llamalend.constantOptions)];
2106
+ case 1:
2107
+ _prices = _a.sent();
2108
+ return [2 /*return*/, _prices.map(function (_p) { return formatUnits(_p); }).reverse()];
2109
+ }
2110
+ });
2111
+ });
2112
+ };
2113
+ LendMarketTemplate.prototype.userLoss = function (userAddress) {
2114
+ if (userAddress === void 0) { userAddress = ""; }
2115
+ return __awaiter(this, void 0, void 0, function () {
2116
+ var _a, userCollateral, _current_collateral_estimation, deposited_collateral, current_collateral_estimation, loss, loss_pct;
2117
+ return __generator(this, function (_c) {
2118
+ switch (_c.label) {
2119
+ case 0:
2120
+ userAddress = _getAddress(userAddress);
2121
+ return [4 /*yield*/, Promise.all([
2122
+ _getUserCollateral(llamalend.constants.NETWORK_NAME, this.addresses.controller, userAddress),
2123
+ llamalend.contracts[this.addresses.amm].contract.get_y_up(userAddress),
2124
+ ])];
2125
+ case 1:
2126
+ _a = _c.sent(), userCollateral = _a[0], _current_collateral_estimation = _a[1];
2127
+ deposited_collateral = userCollateral.total_deposit_precise;
2128
+ current_collateral_estimation = llamalend.formatUnits(_current_collateral_estimation, this.collateral_token.decimals);
2129
+ if (BN(deposited_collateral).lte(0)) {
2130
+ return [2 /*return*/, {
2131
+ deposited_collateral: deposited_collateral,
2132
+ current_collateral_estimation: current_collateral_estimation,
2133
+ loss: "0.0",
2134
+ loss_pct: "0.0",
2135
+ }];
2136
+ }
2137
+ loss = BN(deposited_collateral).minus(current_collateral_estimation).toString();
2138
+ loss_pct = BN(loss).div(deposited_collateral).times(100).toString();
2139
+ return [2 /*return*/, {
2140
+ deposited_collateral: deposited_collateral,
2141
+ current_collateral_estimation: current_collateral_estimation,
2142
+ loss: loss,
2143
+ loss_pct: loss_pct,
2144
+ }];
2145
+ }
2146
+ });
2147
+ });
2148
+ };
2149
+ LendMarketTemplate.prototype.userBandsBalances = function (address) {
2150
+ if (address === void 0) { address = ""; }
2151
+ return __awaiter(this, void 0, void 0, function () {
2152
+ var _a, n2, n1, contract, _c, _borrowed, _collateral, res, i;
2153
+ return __generator(this, function (_d) {
2154
+ switch (_d.label) {
2155
+ case 0: return [4 /*yield*/, this.userBands(address)];
2156
+ case 1:
2157
+ _a = _d.sent(), n2 = _a[0], n1 = _a[1];
2158
+ if (n1 == 0 && n2 == 0)
2159
+ return [2 /*return*/, {}];
2160
+ address = _getAddress(address);
2161
+ contract = llamalend.contracts[this.addresses.amm].contract;
2162
+ return [4 /*yield*/, contract.get_xy(address, llamalend.constantOptions)];
2163
+ case 2:
2164
+ _c = _d.sent(), _borrowed = _c[0], _collateral = _c[1];
2165
+ res = {};
2166
+ for (i = n1; i <= n2; i++) {
2167
+ res[i] = {
2168
+ collateral: formatUnits(_collateral[i - n1], this.collateral_token.decimals),
2169
+ borrowed: formatUnits(_borrowed[i - n1], this.borrowed_token.decimals),
2170
+ };
2171
+ }
2172
+ return [2 /*return*/, res];
2173
+ }
2174
+ });
2175
+ });
2176
+ };
2177
+ // ---------------- CREATE LOAN ----------------
2178
+ LendMarketTemplate.prototype._checkRange = function (range) {
2179
+ if (range < this.minBands)
2180
+ throw Error("range must be >= ".concat(this.minBands));
2181
+ if (range > this.maxBands)
2182
+ throw Error("range must be <= ".concat(this.maxBands));
2183
+ };
2184
+ LendMarketTemplate.prototype.createLoanMaxRecv = function (collateral, range) {
2185
+ return __awaiter(this, void 0, void 0, function () {
2186
+ var _collateral, contract, _a;
2187
+ return __generator(this, function (_c) {
2188
+ switch (_c.label) {
2189
+ case 0:
2190
+ this._checkRange(range);
2191
+ _collateral = parseUnits(collateral, this.collateral_token.decimals);
2192
+ contract = llamalend.contracts[this.addresses.controller].contract;
2193
+ _a = formatUnits;
2194
+ return [4 /*yield*/, contract.max_borrowable(_collateral, range, 0, llamalend.constantOptions)];
2195
+ case 1: return [2 /*return*/, _a.apply(void 0, [_c.sent(), this.borrowed_token.decimals])];
2196
+ }
2197
+ });
2198
+ });
2199
+ };
2200
+ LendMarketTemplate.prototype.getMaxRange = function (collateral, debt) {
2201
+ return __awaiter(this, void 0, void 0, function () {
2202
+ var maxRecv, N;
2203
+ return __generator(this, function (_a) {
2204
+ switch (_a.label) {
2205
+ case 0: return [4 /*yield*/, this.createLoanMaxRecvAllRanges(collateral)];
2206
+ case 1:
2207
+ maxRecv = _a.sent();
2208
+ for (N = this.minBands; N <= this.maxBands; N++) {
2209
+ if (BN(debt).gt(BN(maxRecv[N])))
2210
+ return [2 /*return*/, N - 1];
2211
+ }
2212
+ return [2 /*return*/, this.maxBands];
2213
+ }
2214
+ });
2215
+ });
2216
+ };
2217
+ LendMarketTemplate.prototype._calcN1 = function (_collateral, _debt, range) {
2218
+ return __awaiter(this, void 0, void 0, function () {
2219
+ return __generator(this, function (_a) {
2220
+ switch (_a.label) {
2221
+ case 0:
2222
+ this._checkRange(range);
2223
+ return [4 /*yield*/, llamalend.contracts[this.addresses.controller].contract.calculate_debt_n1(_collateral, _debt, range, llamalend.constantOptions)];
2224
+ case 1: return [2 /*return*/, _a.sent()];
2225
+ }
2226
+ });
2227
+ });
2228
+ };
2229
+ LendMarketTemplate.prototype._calcN1AllRanges = function (_collateral, _debt, maxN) {
2230
+ return __awaiter(this, void 0, void 0, function () {
2231
+ var calls, N;
2232
+ return __generator(this, function (_a) {
2233
+ switch (_a.label) {
2234
+ case 0:
2235
+ calls = [];
2236
+ for (N = this.minBands; N <= maxN; N++) {
2237
+ calls.push(llamalend.contracts[this.addresses.controller].multicallContract.calculate_debt_n1(_collateral, _debt, N));
2238
+ }
2239
+ return [4 /*yield*/, llamalend.multicallProvider.all(calls)];
2240
+ case 1: return [2 /*return*/, _a.sent()];
2241
+ }
2242
+ });
2243
+ });
2244
+ };
2245
+ LendMarketTemplate.prototype._getPrices = function (_n2, _n1) {
2246
+ return __awaiter(this, void 0, void 0, function () {
2247
+ var contract;
2248
+ return __generator(this, function (_a) {
2249
+ switch (_a.label) {
2250
+ case 0:
2251
+ contract = llamalend.contracts[this.addresses.amm].multicallContract;
2252
+ return [4 /*yield*/, llamalend.multicallProvider.all([
2253
+ contract.p_oracle_down(_n2),
2254
+ contract.p_oracle_up(_n1),
2255
+ ])];
2256
+ case 1: return [2 /*return*/, (_a.sent()).map(function (_p) { return formatUnits(_p); })];
2257
+ }
2258
+ });
2259
+ });
2260
+ };
2261
+ LendMarketTemplate.prototype._calcPrices = function (_n2, _n1) {
2262
+ return __awaiter(this, void 0, void 0, function () {
2263
+ var _a;
2264
+ return __generator(this, function (_c) {
2265
+ switch (_c.label) {
2266
+ case 0: return [4 /*yield*/, this.calcTickPrice(Number(_n2) + 1)];
2267
+ case 1:
2268
+ _a = [_c.sent()];
2269
+ return [4 /*yield*/, this.calcTickPrice(Number(_n1))];
2270
+ case 2: return [2 /*return*/, _a.concat([_c.sent()])];
2271
+ }
2272
+ });
2273
+ });
2274
+ };
2275
+ LendMarketTemplate.prototype._createLoanBands = function (collateral, debt, range) {
2276
+ return __awaiter(this, void 0, void 0, function () {
2277
+ var _n1, _n2;
2278
+ return __generator(this, function (_a) {
2279
+ switch (_a.label) {
2280
+ case 0: return [4 /*yield*/, this._calcN1(parseUnits(collateral, this.collateral_token.decimals), parseUnits(debt, this.borrowed_token.decimals), range)];
2281
+ case 1:
2282
+ _n1 = _a.sent();
2283
+ _n2 = _n1 + BigInt(range - 1);
2284
+ return [2 /*return*/, [_n2, _n1]];
2285
+ }
2286
+ });
2287
+ });
2288
+ };
2289
+ LendMarketTemplate.prototype._createLoanBandsAllRanges = function (collateral, debt) {
2290
+ return __awaiter(this, void 0, void 0, function () {
2291
+ var maxN, _n1_arr, _n2_arr, N, res, N;
2292
+ return __generator(this, function (_a) {
2293
+ switch (_a.label) {
2294
+ case 0: return [4 /*yield*/, this.getMaxRange(collateral, debt)];
2295
+ case 1:
2296
+ maxN = _a.sent();
2297
+ return [4 /*yield*/, this._calcN1AllRanges(parseUnits(collateral, this.collateral_token.decimals), parseUnits(debt, this.borrowed_token.decimals), maxN)];
2298
+ case 2:
2299
+ _n1_arr = _a.sent();
2300
+ _n2_arr = [];
2301
+ for (N = this.minBands; N <= maxN; N++) {
2302
+ _n2_arr.push(_n1_arr[N - this.minBands] + BigInt(N - 1));
2303
+ }
2304
+ res = {};
2305
+ for (N = this.minBands; N <= maxN; N++) {
2306
+ res[N] = [_n2_arr[N - this.minBands], _n1_arr[N - this.minBands]];
2307
+ }
2308
+ return [2 /*return*/, res];
2309
+ }
2310
+ });
2311
+ });
2312
+ };
2313
+ LendMarketTemplate.prototype.createLoanBands = function (collateral, debt, range) {
2314
+ return __awaiter(this, void 0, void 0, function () {
2315
+ var _a, _n2, _n1;
2316
+ return __generator(this, function (_c) {
2317
+ switch (_c.label) {
2318
+ case 0: return [4 /*yield*/, this._createLoanBands(collateral, debt, range)];
2319
+ case 1:
2320
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
2321
+ return [2 /*return*/, [Number(_n2), Number(_n1)]];
2322
+ }
2323
+ });
2324
+ });
2325
+ };
2326
+ LendMarketTemplate.prototype.createLoanBandsAllRanges = function (collateral, debt) {
2327
+ return __awaiter(this, void 0, void 0, function () {
2328
+ var _bandsAllRanges, bandsAllRanges, N;
2329
+ return __generator(this, function (_a) {
2330
+ switch (_a.label) {
2331
+ case 0: return [4 /*yield*/, this._createLoanBandsAllRanges(collateral, debt)];
2332
+ case 1:
2333
+ _bandsAllRanges = _a.sent();
2334
+ bandsAllRanges = {};
2335
+ for (N = this.minBands; N <= this.maxBands; N++) {
2336
+ if (_bandsAllRanges[N]) {
2337
+ bandsAllRanges[N] = _bandsAllRanges[N].map(Number);
2338
+ }
2339
+ else {
2340
+ bandsAllRanges[N] = null;
2341
+ }
2342
+ }
2343
+ return [2 /*return*/, bandsAllRanges];
2344
+ }
2345
+ });
2346
+ });
2347
+ };
2348
+ LendMarketTemplate.prototype.createLoanPrices = function (collateral, debt, range) {
2349
+ return __awaiter(this, void 0, void 0, function () {
2350
+ var _a, _n2, _n1;
2351
+ return __generator(this, function (_c) {
2352
+ switch (_c.label) {
2353
+ case 0: return [4 /*yield*/, this._createLoanBands(collateral, debt, range)];
2354
+ case 1:
2355
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
2356
+ return [4 /*yield*/, this._getPrices(_n2, _n1)];
2357
+ case 2: return [2 /*return*/, _c.sent()];
2358
+ }
2359
+ });
2360
+ });
2361
+ };
2362
+ LendMarketTemplate.prototype.createLoanPricesAllRanges = function (collateral, debt) {
2363
+ return __awaiter(this, void 0, void 0, function () {
2364
+ var _bandsAllRanges, pricesAllRanges, N, _a, _c;
2365
+ return __generator(this, function (_d) {
2366
+ switch (_d.label) {
2367
+ case 0: return [4 /*yield*/, this._createLoanBandsAllRanges(collateral, debt)];
2368
+ case 1:
2369
+ _bandsAllRanges = _d.sent();
2370
+ pricesAllRanges = {};
2371
+ N = this.minBands;
2372
+ _d.label = 2;
2373
+ case 2:
2374
+ if (!(N <= this.maxBands)) return [3 /*break*/, 6];
2375
+ if (!_bandsAllRanges[N]) return [3 /*break*/, 4];
2376
+ _a = pricesAllRanges;
2377
+ _c = N;
2378
+ return [4 /*yield*/, this._calcPrices.apply(this, _bandsAllRanges[N])];
2379
+ case 3:
2380
+ _a[_c] = _d.sent();
2381
+ return [3 /*break*/, 5];
2382
+ case 4:
2383
+ pricesAllRanges[N] = null;
2384
+ _d.label = 5;
2385
+ case 5:
2386
+ N++;
2387
+ return [3 /*break*/, 2];
2388
+ case 6: return [2 /*return*/, pricesAllRanges];
2389
+ }
2390
+ });
2391
+ });
2392
+ };
2393
+ LendMarketTemplate.prototype.createLoanHealth = function (collateral, debt, range, full) {
2394
+ if (full === void 0) { full = true; }
2395
+ return __awaiter(this, void 0, void 0, function () {
2396
+ var _collateral, _debt, contract, _health;
2397
+ return __generator(this, function (_a) {
2398
+ switch (_a.label) {
2399
+ case 0:
2400
+ _collateral = parseUnits(collateral, this.collateral_token.decimals);
2401
+ _debt = parseUnits(debt, this.borrowed_token.decimals);
2402
+ contract = llamalend.contracts[this.addresses.controller].contract;
2403
+ return [4 /*yield*/, contract.health_calculator(llamalend.constants.ZERO_ADDRESS, _collateral, _debt, full, range, llamalend.constantOptions)];
2404
+ case 1:
2405
+ _health = _a.sent();
2406
+ _health = _health * BigInt(100);
2407
+ return [2 /*return*/, formatUnits(_health)];
2408
+ }
2409
+ });
2410
+ });
2411
+ };
2412
+ LendMarketTemplate.prototype.createLoanIsApproved = function (collateral) {
2413
+ return __awaiter(this, void 0, void 0, function () {
2414
+ return __generator(this, function (_a) {
2415
+ switch (_a.label) {
2416
+ case 0: return [4 /*yield*/, hasAllowance([this.collateral_token.address], [collateral], llamalend.signerAddress, this.addresses.controller)];
2417
+ case 1: return [2 /*return*/, _a.sent()];
2418
+ }
2419
+ });
2420
+ });
2421
+ };
2422
+ LendMarketTemplate.prototype.createLoanApproveEstimateGas = function (collateral) {
2423
+ return __awaiter(this, void 0, void 0, function () {
2424
+ return __generator(this, function (_a) {
2425
+ switch (_a.label) {
2426
+ case 0: return [4 /*yield*/, ensureAllowanceEstimateGas([this.collateral_token.address], [collateral], this.addresses.controller)];
2427
+ case 1: return [2 /*return*/, _a.sent()];
2428
+ }
2429
+ });
2430
+ });
2431
+ };
2432
+ LendMarketTemplate.prototype.createLoanApprove = function (collateral) {
2433
+ return __awaiter(this, void 0, void 0, function () {
2434
+ return __generator(this, function (_a) {
2435
+ switch (_a.label) {
2436
+ case 0: return [4 /*yield*/, ensureAllowance([this.collateral_token.address], [collateral], this.addresses.controller)];
2437
+ case 1: return [2 /*return*/, _a.sent()];
2438
+ }
2439
+ });
2440
+ });
2441
+ };
2442
+ LendMarketTemplate.prototype._createLoan = function (collateral, debt, range, estimateGas) {
2443
+ return __awaiter(this, void 0, void 0, function () {
2444
+ var _collateral, _debt, contract, gas, gasLimit;
2445
+ return __generator(this, function (_a) {
2446
+ switch (_a.label) {
2447
+ case 0: return [4 /*yield*/, this.userLoanExists()];
2448
+ case 1:
2449
+ if (_a.sent())
2450
+ throw Error("Loan already created");
2451
+ this._checkRange(range);
2452
+ _collateral = parseUnits(collateral, this.collateral_token.decimals);
2453
+ _debt = parseUnits(debt, this.borrowed_token.decimals);
2454
+ contract = llamalend.contracts[this.addresses.controller].contract;
2455
+ return [4 /*yield*/, contract.create_loan.estimateGas(_collateral, _debt, range, __assign({}, llamalend.constantOptions))];
2456
+ case 2:
2457
+ gas = _a.sent();
2458
+ if (estimateGas)
2459
+ return [2 /*return*/, smartNumber(gas)];
2460
+ return [4 /*yield*/, llamalend.updateFeeData()];
2461
+ case 3:
2462
+ _a.sent();
2463
+ gasLimit = _mulBy1_3(DIGas(gas));
2464
+ return [4 /*yield*/, contract.create_loan(_collateral, _debt, range, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
2465
+ case 4: return [2 /*return*/, (_a.sent()).hash];
2466
+ }
2467
+ });
2468
+ });
2469
+ };
2470
+ LendMarketTemplate.prototype.createLoanEstimateGas = function (collateral, debt, range) {
2471
+ return __awaiter(this, void 0, void 0, function () {
2472
+ return __generator(this, function (_a) {
2473
+ switch (_a.label) {
2474
+ case 0: return [4 /*yield*/, this.createLoanIsApproved(collateral)];
2475
+ case 1:
2476
+ if (!(_a.sent()))
2477
+ throw Error("Approval is needed for gas estimation");
2478
+ return [4 /*yield*/, this._createLoan(collateral, debt, range, true)];
2479
+ case 2: return [2 /*return*/, _a.sent()];
2480
+ }
2481
+ });
2482
+ });
2483
+ };
2484
+ LendMarketTemplate.prototype.createLoan = function (collateral, debt, range) {
2485
+ return __awaiter(this, void 0, void 0, function () {
2486
+ return __generator(this, function (_a) {
2487
+ switch (_a.label) {
2488
+ case 0: return [4 /*yield*/, this.createLoanApprove(collateral)];
2489
+ case 1:
2490
+ _a.sent();
2491
+ return [4 /*yield*/, this._createLoan(collateral, debt, range, false)];
2492
+ case 2: return [2 /*return*/, _a.sent()];
2493
+ }
2494
+ });
2495
+ });
2496
+ };
2497
+ // ---------------- BORROW MORE ----------------
2498
+ LendMarketTemplate.prototype.borrowMoreMaxRecv = function (collateralAmount) {
2499
+ return __awaiter(this, void 0, void 0, function () {
2500
+ var _a, _currentCollateral, _currentDebt, _N, _collateral, contract, _debt;
2501
+ return __generator(this, function (_c) {
2502
+ switch (_c.label) {
2503
+ case 0: return [4 /*yield*/, this._userState()];
2504
+ case 1:
2505
+ _a = _c.sent(), _currentCollateral = _a._collateral, _currentDebt = _a._debt, _N = _a._N;
2506
+ _collateral = _currentCollateral + parseUnits(collateralAmount, this.collateral_token.decimals);
2507
+ contract = llamalend.contracts[this.addresses.controller].contract;
2508
+ return [4 /*yield*/, contract.max_borrowable(_collateral, _N, _currentDebt, llamalend.constantOptions)];
2509
+ case 2:
2510
+ _debt = _c.sent();
2511
+ return [2 /*return*/, formatUnits(_debt - _currentDebt, this.borrowed_token.decimals)];
2512
+ }
2513
+ });
2514
+ });
2515
+ };
2516
+ LendMarketTemplate.prototype._borrowMoreBands = function (collateral, debt) {
2517
+ return __awaiter(this, void 0, void 0, function () {
2518
+ var _a, _currentCollateral, _currentDebt, _N, _collateral, _debt, _n1, _n2;
2519
+ return __generator(this, function (_c) {
2520
+ switch (_c.label) {
2521
+ case 0: return [4 /*yield*/, this._userState()];
2522
+ case 1:
2523
+ _a = _c.sent(), _currentCollateral = _a._collateral, _currentDebt = _a._debt, _N = _a._N;
2524
+ if (_currentDebt === BigInt(0))
2525
+ throw Error("Loan for ".concat(llamalend.signerAddress, " does not exist"));
2526
+ _collateral = _currentCollateral + parseUnits(collateral, this.collateral_token.decimals);
2527
+ _debt = _currentDebt + parseUnits(debt, this.borrowed_token.decimals);
2528
+ return [4 /*yield*/, this._calcN1(_collateral, _debt, Number(_N))];
2529
+ case 2:
2530
+ _n1 = _c.sent();
2531
+ _n2 = _n1 + _N - BigInt(1);
2532
+ return [2 /*return*/, [_n2, _n1]];
2533
+ }
2534
+ });
2535
+ });
2536
+ };
2537
+ LendMarketTemplate.prototype.borrowMoreBands = function (collateral, debt) {
2538
+ return __awaiter(this, void 0, void 0, function () {
2539
+ var _a, _n2, _n1;
2540
+ return __generator(this, function (_c) {
2541
+ switch (_c.label) {
2542
+ case 0: return [4 /*yield*/, this._borrowMoreBands(collateral, debt)];
2543
+ case 1:
2544
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
2545
+ return [2 /*return*/, [Number(_n2), Number(_n1)]];
2546
+ }
2547
+ });
2548
+ });
2549
+ };
2550
+ LendMarketTemplate.prototype.borrowMorePrices = function (collateral, debt) {
2551
+ return __awaiter(this, void 0, void 0, function () {
2552
+ var _a, _n2, _n1;
2553
+ return __generator(this, function (_c) {
2554
+ switch (_c.label) {
2555
+ case 0: return [4 /*yield*/, this._borrowMoreBands(collateral, debt)];
2556
+ case 1:
2557
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
2558
+ return [4 /*yield*/, this._getPrices(_n2, _n1)];
2559
+ case 2: return [2 /*return*/, _c.sent()];
2560
+ }
2561
+ });
2562
+ });
2563
+ };
2564
+ LendMarketTemplate.prototype.borrowMoreHealth = function (collateral, debt, full, address) {
2565
+ if (full === void 0) { full = true; }
2566
+ if (address === void 0) { address = ""; }
2567
+ return __awaiter(this, void 0, void 0, function () {
2568
+ var _collateral, _debt, contract, _health;
2569
+ return __generator(this, function (_a) {
2570
+ switch (_a.label) {
2571
+ case 0:
2572
+ address = _getAddress(address);
2573
+ _collateral = parseUnits(collateral, this.collateral_token.decimals);
2574
+ _debt = parseUnits(debt, this.borrowed_token.decimals);
2575
+ contract = llamalend.contracts[this.addresses.controller].contract;
2576
+ return [4 /*yield*/, contract.health_calculator(address, _collateral, _debt, full, 0, llamalend.constantOptions)];
2577
+ case 1:
2578
+ _health = _a.sent();
2579
+ _health = _health * BigInt(100);
2580
+ return [2 /*return*/, formatUnits(_health)];
2581
+ }
2582
+ });
2583
+ });
2584
+ };
2585
+ LendMarketTemplate.prototype.borrowMoreIsApproved = function (collateral) {
2586
+ return __awaiter(this, void 0, void 0, function () {
2587
+ return __generator(this, function (_a) {
2588
+ switch (_a.label) {
2589
+ case 0: return [4 /*yield*/, hasAllowance([this.addresses.collateral_token], [collateral], llamalend.signerAddress, this.addresses.controller)];
2590
+ case 1: return [2 /*return*/, _a.sent()];
2591
+ }
2592
+ });
2593
+ });
2594
+ };
2595
+ LendMarketTemplate.prototype.borrowMoreApproveEstimateGas = function (collateral) {
2596
+ return __awaiter(this, void 0, void 0, function () {
2597
+ return __generator(this, function (_a) {
2598
+ switch (_a.label) {
2599
+ case 0: return [4 /*yield*/, ensureAllowanceEstimateGas([this.addresses.collateral_token], [collateral], this.addresses.controller)];
2600
+ case 1: return [2 /*return*/, _a.sent()];
2601
+ }
2602
+ });
2603
+ });
2604
+ };
2605
+ LendMarketTemplate.prototype.borrowMoreApprove = function (collateral) {
2606
+ return __awaiter(this, void 0, void 0, function () {
2607
+ return __generator(this, function (_a) {
2608
+ switch (_a.label) {
2609
+ case 0: return [4 /*yield*/, ensureAllowance([this.addresses.collateral_token], [collateral], this.addresses.controller)];
2610
+ case 1: return [2 /*return*/, _a.sent()];
2611
+ }
2612
+ });
2613
+ });
2614
+ };
2615
+ LendMarketTemplate.prototype._borrowMore = function (collateral, debt, estimateGas) {
2616
+ return __awaiter(this, void 0, void 0, function () {
2617
+ var _a, borrowed, currentDebt, _collateral, _debt, contract, gas, gasLimit;
2618
+ return __generator(this, function (_c) {
2619
+ switch (_c.label) {
2620
+ case 0: return [4 /*yield*/, this.userState()];
2621
+ case 1:
2622
+ _a = _c.sent(), borrowed = _a.borrowed, currentDebt = _a.debt;
2623
+ if (Number(currentDebt) === 0)
2624
+ throw Error("Loan for ".concat(llamalend.signerAddress, " does not exist"));
2625
+ if (Number(borrowed) > 0)
2626
+ throw Error("User ".concat(llamalend.signerAddress, " is already in liquidation mode"));
2627
+ _collateral = parseUnits(collateral, this.collateral_token.decimals);
2628
+ _debt = parseUnits(debt, this.borrowed_token.decimals);
2629
+ contract = llamalend.contracts[this.addresses.controller].contract;
2630
+ return [4 /*yield*/, contract.borrow_more.estimateGas(_collateral, _debt, __assign({}, llamalend.constantOptions))];
2631
+ case 2:
2632
+ gas = _c.sent();
2633
+ if (estimateGas)
2634
+ return [2 /*return*/, smartNumber(gas)];
2635
+ return [4 /*yield*/, llamalend.updateFeeData()];
2636
+ case 3:
2637
+ _c.sent();
2638
+ gasLimit = _mulBy1_3(DIGas(gas));
2639
+ return [4 /*yield*/, contract.borrow_more(_collateral, _debt, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
2640
+ case 4: return [2 /*return*/, (_c.sent()).hash];
2641
+ }
2642
+ });
2643
+ });
2644
+ };
2645
+ LendMarketTemplate.prototype.borrowMoreEstimateGas = function (collateral, debt) {
2646
+ return __awaiter(this, void 0, void 0, function () {
2647
+ return __generator(this, function (_a) {
2648
+ switch (_a.label) {
2649
+ case 0: return [4 /*yield*/, this.borrowMoreIsApproved(collateral)];
2650
+ case 1:
2651
+ if (!(_a.sent()))
2652
+ throw Error("Approval is needed for gas estimation");
2653
+ return [4 /*yield*/, this._borrowMore(collateral, debt, true)];
2654
+ case 2: return [2 /*return*/, _a.sent()];
2655
+ }
2656
+ });
2657
+ });
2658
+ };
2659
+ LendMarketTemplate.prototype.borrowMore = function (collateral, debt) {
2660
+ return __awaiter(this, void 0, void 0, function () {
2661
+ return __generator(this, function (_a) {
2662
+ switch (_a.label) {
2663
+ case 0: return [4 /*yield*/, this.borrowMoreApprove(collateral)];
2664
+ case 1:
2665
+ _a.sent();
2666
+ return [4 /*yield*/, this._borrowMore(collateral, debt, false)];
2667
+ case 2: return [2 /*return*/, _a.sent()];
2668
+ }
2669
+ });
2670
+ });
2671
+ };
2672
+ // ---------------- ADD COLLATERAL ----------------
2673
+ LendMarketTemplate.prototype._addCollateralBands = function (collateral, address) {
2674
+ if (address === void 0) { address = ""; }
2675
+ return __awaiter(this, void 0, void 0, function () {
2676
+ var _a, _currentCollateral, _currentDebt, _N, _collateral, _n1, _n2;
2677
+ return __generator(this, function (_c) {
2678
+ switch (_c.label) {
2679
+ case 0:
2680
+ address = _getAddress(address);
2681
+ return [4 /*yield*/, this._userState(address)];
2682
+ case 1:
2683
+ _a = _c.sent(), _currentCollateral = _a._collateral, _currentDebt = _a._debt, _N = _a._N;
2684
+ if (_currentDebt === BigInt(0))
2685
+ throw Error("Loan for ".concat(address, " does not exist"));
2686
+ _collateral = _currentCollateral + parseUnits(collateral, this.collateral_token.decimals);
2687
+ return [4 /*yield*/, this._calcN1(_collateral, _currentDebt, Number(_N))];
2688
+ case 2:
2689
+ _n1 = _c.sent();
2690
+ _n2 = _n1 + _N - BigInt(1);
2691
+ return [2 /*return*/, [_n2, _n1]];
2692
+ }
2693
+ });
2694
+ });
2695
+ };
2696
+ LendMarketTemplate.prototype.addCollateralBands = function (collateral, address) {
2697
+ if (address === void 0) { address = ""; }
2698
+ return __awaiter(this, void 0, void 0, function () {
2699
+ var _a, _n2, _n1;
2700
+ return __generator(this, function (_c) {
2701
+ switch (_c.label) {
2702
+ case 0: return [4 /*yield*/, this._addCollateralBands(collateral, address)];
2703
+ case 1:
2704
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
2705
+ return [2 /*return*/, [Number(_n2), Number(_n1)]];
2706
+ }
2707
+ });
2708
+ });
2709
+ };
2710
+ LendMarketTemplate.prototype.addCollateralPrices = function (collateral, address) {
2711
+ if (address === void 0) { address = ""; }
2712
+ return __awaiter(this, void 0, void 0, function () {
2713
+ var _a, _n2, _n1;
2714
+ return __generator(this, function (_c) {
2715
+ switch (_c.label) {
2716
+ case 0: return [4 /*yield*/, this._addCollateralBands(collateral, address)];
2717
+ case 1:
2718
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
2719
+ return [4 /*yield*/, this._getPrices(_n2, _n1)];
2720
+ case 2: return [2 /*return*/, _c.sent()];
2721
+ }
2722
+ });
2723
+ });
2724
+ };
2725
+ LendMarketTemplate.prototype.addCollateralHealth = function (collateral, full, address) {
2726
+ if (full === void 0) { full = true; }
2727
+ if (address === void 0) { address = ""; }
2728
+ return __awaiter(this, void 0, void 0, function () {
2729
+ var _collateral, contract, _health;
2730
+ return __generator(this, function (_a) {
2731
+ switch (_a.label) {
2732
+ case 0:
2733
+ address = _getAddress(address);
2734
+ _collateral = parseUnits(collateral, this.collateral_token.decimals);
2735
+ contract = llamalend.contracts[this.addresses.controller].contract;
2736
+ return [4 /*yield*/, contract.health_calculator(address, _collateral, 0, full, 0, llamalend.constantOptions)];
2737
+ case 1:
2738
+ _health = _a.sent();
2739
+ _health = _health * BigInt(100);
2740
+ return [2 /*return*/, formatUnits(_health)];
2741
+ }
2742
+ });
2743
+ });
2744
+ };
2745
+ LendMarketTemplate.prototype.addCollateralIsApproved = function (collateral) {
2746
+ return __awaiter(this, void 0, void 0, function () {
2747
+ return __generator(this, function (_a) {
2748
+ switch (_a.label) {
2749
+ case 0: return [4 /*yield*/, hasAllowance([this.addresses.collateral_token], [collateral], llamalend.signerAddress, this.addresses.controller)];
2750
+ case 1: return [2 /*return*/, _a.sent()];
2751
+ }
2752
+ });
2753
+ });
2754
+ };
2755
+ LendMarketTemplate.prototype.addCollateralApproveEstimateGas = function (collateral) {
2756
+ return __awaiter(this, void 0, void 0, function () {
2757
+ return __generator(this, function (_a) {
2758
+ switch (_a.label) {
2759
+ case 0: return [4 /*yield*/, ensureAllowanceEstimateGas([this.addresses.collateral_token], [collateral], this.addresses.controller)];
2760
+ case 1: return [2 /*return*/, _a.sent()];
2761
+ }
2762
+ });
2763
+ });
2764
+ };
2765
+ LendMarketTemplate.prototype.addCollateralApprove = function (collateral) {
2766
+ return __awaiter(this, void 0, void 0, function () {
2767
+ return __generator(this, function (_a) {
2768
+ switch (_a.label) {
2769
+ case 0: return [4 /*yield*/, ensureAllowance([this.addresses.collateral_token], [collateral], this.addresses.controller)];
2770
+ case 1: return [2 /*return*/, _a.sent()];
2771
+ }
2772
+ });
2773
+ });
2774
+ };
2775
+ LendMarketTemplate.prototype._addCollateral = function (collateral, address, estimateGas) {
2776
+ return __awaiter(this, void 0, void 0, function () {
2777
+ var _a, borrowed, currentDebt, _collateral, contract, gas, gasLimit;
2778
+ return __generator(this, function (_c) {
2779
+ switch (_c.label) {
2780
+ case 0: return [4 /*yield*/, this.userState(address)];
2781
+ case 1:
2782
+ _a = _c.sent(), borrowed = _a.borrowed, currentDebt = _a.debt;
2783
+ if (Number(currentDebt) === 0)
2784
+ throw Error("Loan for ".concat(address, " does not exist"));
2785
+ if (Number(borrowed) > 0)
2786
+ throw Error("User ".concat(address, " is already in liquidation mode"));
2787
+ _collateral = parseUnits(collateral, this.collateral_token.decimals);
2788
+ contract = llamalend.contracts[this.addresses.controller].contract;
2789
+ return [4 /*yield*/, contract.add_collateral.estimateGas(_collateral, address, __assign({}, llamalend.constantOptions))];
2790
+ case 2:
2791
+ gas = _c.sent();
2792
+ if (estimateGas)
2793
+ return [2 /*return*/, smartNumber(gas)];
2794
+ return [4 /*yield*/, llamalend.updateFeeData()];
2795
+ case 3:
2796
+ _c.sent();
2797
+ gasLimit = _mulBy1_3(DIGas(gas));
2798
+ return [4 /*yield*/, contract.add_collateral(_collateral, address, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
2799
+ case 4: return [2 /*return*/, (_c.sent()).hash];
2800
+ }
2801
+ });
2802
+ });
2803
+ };
2804
+ LendMarketTemplate.prototype.addCollateralEstimateGas = function (collateral, address) {
2805
+ if (address === void 0) { address = ""; }
2806
+ return __awaiter(this, void 0, void 0, function () {
2807
+ return __generator(this, function (_a) {
2808
+ switch (_a.label) {
2809
+ case 0:
2810
+ address = _getAddress(address);
2811
+ return [4 /*yield*/, this.addCollateralIsApproved(collateral)];
2812
+ case 1:
2813
+ if (!(_a.sent()))
2814
+ throw Error("Approval is needed for gas estimation");
2815
+ return [4 /*yield*/, this._addCollateral(collateral, address, true)];
2816
+ case 2: return [2 /*return*/, _a.sent()];
2817
+ }
2818
+ });
2819
+ });
2820
+ };
2821
+ LendMarketTemplate.prototype.addCollateral = function (collateral, address) {
2822
+ if (address === void 0) { address = ""; }
2823
+ return __awaiter(this, void 0, void 0, function () {
2824
+ return __generator(this, function (_a) {
2825
+ switch (_a.label) {
2826
+ case 0:
2827
+ address = _getAddress(address);
2828
+ return [4 /*yield*/, this.addCollateralApprove(collateral)];
2829
+ case 1:
2830
+ _a.sent();
2831
+ return [4 /*yield*/, this._addCollateral(collateral, address, false)];
2832
+ case 2: return [2 /*return*/, _a.sent()];
2833
+ }
2834
+ });
2835
+ });
2836
+ };
2837
+ // ---------------- REMOVE COLLATERAL ----------------
2838
+ LendMarketTemplate.prototype.maxRemovable = function () {
2839
+ return __awaiter(this, void 0, void 0, function () {
2840
+ var _a, _currentCollateral, _currentDebt, _N, _requiredCollateral;
2841
+ return __generator(this, function (_c) {
2842
+ switch (_c.label) {
2843
+ case 0: return [4 /*yield*/, this._userState()];
2844
+ case 1:
2845
+ _a = _c.sent(), _currentCollateral = _a._collateral, _currentDebt = _a._debt, _N = _a._N;
2846
+ return [4 /*yield*/, llamalend.contracts[this.addresses.controller].contract.min_collateral(_currentDebt, _N, llamalend.constantOptions)];
2847
+ case 2:
2848
+ _requiredCollateral = _c.sent();
2849
+ return [2 /*return*/, formatUnits(_currentCollateral - _requiredCollateral, this.collateral_token.decimals)];
2850
+ }
2851
+ });
2852
+ });
2853
+ };
2854
+ LendMarketTemplate.prototype._removeCollateralBands = function (collateral) {
2855
+ return __awaiter(this, void 0, void 0, function () {
2856
+ var _a, _currentCollateral, _currentDebt, _N, _collateral, _n1, _n2;
2857
+ return __generator(this, function (_c) {
2858
+ switch (_c.label) {
2859
+ case 0: return [4 /*yield*/, this._userState()];
2860
+ case 1:
2861
+ _a = _c.sent(), _currentCollateral = _a._collateral, _currentDebt = _a._debt, _N = _a._N;
2862
+ if (_currentDebt === BigInt(0))
2863
+ throw Error("Loan for ".concat(llamalend.signerAddress, " does not exist"));
2864
+ _collateral = _currentCollateral - parseUnits(collateral, this.collateral_token.decimals);
2865
+ return [4 /*yield*/, this._calcN1(_collateral, _currentDebt, Number(_N))];
2866
+ case 2:
2867
+ _n1 = _c.sent();
2868
+ _n2 = _n1 + _N - BigInt(1);
2869
+ return [2 /*return*/, [_n2, _n1]];
2870
+ }
2871
+ });
2872
+ });
2873
+ };
2874
+ LendMarketTemplate.prototype.removeCollateralBands = function (collateral) {
2875
+ return __awaiter(this, void 0, void 0, function () {
2876
+ var _a, _n2, _n1;
2877
+ return __generator(this, function (_c) {
2878
+ switch (_c.label) {
2879
+ case 0: return [4 /*yield*/, this._removeCollateralBands(collateral)];
2880
+ case 1:
2881
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
2882
+ return [2 /*return*/, [Number(_n2), Number(_n1)]];
2883
+ }
2884
+ });
2885
+ });
2886
+ };
2887
+ LendMarketTemplate.prototype.removeCollateralPrices = function (collateral) {
2888
+ return __awaiter(this, void 0, void 0, function () {
2889
+ var _a, _n2, _n1;
2890
+ return __generator(this, function (_c) {
2891
+ switch (_c.label) {
2892
+ case 0: return [4 /*yield*/, this._removeCollateralBands(collateral)];
2893
+ case 1:
2894
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
2895
+ return [4 /*yield*/, this._getPrices(_n2, _n1)];
2896
+ case 2: return [2 /*return*/, _c.sent()];
2897
+ }
2898
+ });
2899
+ });
2900
+ };
2901
+ LendMarketTemplate.prototype.removeCollateralHealth = function (collateral, full, address) {
2902
+ if (full === void 0) { full = true; }
2903
+ if (address === void 0) { address = ""; }
2904
+ return __awaiter(this, void 0, void 0, function () {
2905
+ var _collateral, contract, _health;
2906
+ return __generator(this, function (_a) {
2907
+ switch (_a.label) {
2908
+ case 0:
2909
+ address = _getAddress(address);
2910
+ _collateral = parseUnits(collateral, this.collateral_token.decimals) * BigInt(-1);
2911
+ contract = llamalend.contracts[this.addresses.controller].contract;
2912
+ return [4 /*yield*/, contract.health_calculator(address, _collateral, 0, full, 0, llamalend.constantOptions)];
2913
+ case 1:
2914
+ _health = _a.sent();
2915
+ _health = _health * BigInt(100);
2916
+ return [2 /*return*/, formatUnits(_health)];
2917
+ }
2918
+ });
2919
+ });
2920
+ };
2921
+ LendMarketTemplate.prototype._removeCollateral = function (collateral, estimateGas) {
2922
+ return __awaiter(this, void 0, void 0, function () {
2923
+ var _a, borrowed, currentDebt, _collateral, contract, gas, gasLimit;
2924
+ return __generator(this, function (_c) {
2925
+ switch (_c.label) {
2926
+ case 0: return [4 /*yield*/, this.userState()];
2927
+ case 1:
2928
+ _a = _c.sent(), borrowed = _a.borrowed, currentDebt = _a.debt;
2929
+ if (Number(currentDebt) === 0)
2930
+ throw Error("Loan for ".concat(llamalend.signerAddress, " does not exist"));
2931
+ if (Number(borrowed) > 0)
2932
+ throw Error("User ".concat(llamalend.signerAddress, " is already in liquidation mode"));
2933
+ _collateral = parseUnits(collateral, this.collateral_token.decimals);
2934
+ contract = llamalend.contracts[this.addresses.controller].contract;
2935
+ return [4 /*yield*/, contract.remove_collateral.estimateGas(_collateral, llamalend.constantOptions)];
2936
+ case 2:
2937
+ gas = _c.sent();
2938
+ if (estimateGas)
2939
+ return [2 /*return*/, smartNumber(gas)];
2940
+ return [4 /*yield*/, llamalend.updateFeeData()];
2941
+ case 3:
2942
+ _c.sent();
2943
+ gasLimit = _mulBy1_3(DIGas(gas));
2944
+ return [4 /*yield*/, contract.remove_collateral(_collateral, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
2945
+ case 4: return [2 /*return*/, (_c.sent()).hash];
2946
+ }
2947
+ });
2948
+ });
2949
+ };
2950
+ LendMarketTemplate.prototype.removeCollateralEstimateGas = function (collateral) {
2951
+ return __awaiter(this, void 0, void 0, function () {
2952
+ return __generator(this, function (_a) {
2953
+ switch (_a.label) {
2954
+ case 0: return [4 /*yield*/, this._removeCollateral(collateral, true)];
2955
+ case 1: return [2 /*return*/, _a.sent()];
2956
+ }
2957
+ });
2958
+ });
2959
+ };
2960
+ LendMarketTemplate.prototype.removeCollateral = function (collateral) {
2961
+ return __awaiter(this, void 0, void 0, function () {
2962
+ return __generator(this, function (_a) {
2963
+ switch (_a.label) {
2964
+ case 0: return [4 /*yield*/, this._removeCollateral(collateral, false)];
2965
+ case 1: return [2 /*return*/, _a.sent()];
2966
+ }
2967
+ });
2968
+ });
2969
+ };
2970
+ // ---------------- REPAY ----------------
2971
+ LendMarketTemplate.prototype._repayBands = function (debt, address) {
2972
+ return __awaiter(this, void 0, void 0, function () {
2973
+ var _a, _currentCollateral, _borrowed, _currentDebt, _N, _debt, _n1, _n2;
2974
+ return __generator(this, function (_c) {
2975
+ switch (_c.label) {
2976
+ case 0: return [4 /*yield*/, this._userState(address)];
2977
+ case 1:
2978
+ _a = _c.sent(), _currentCollateral = _a._collateral, _borrowed = _a._borrowed, _currentDebt = _a._debt, _N = _a._N;
2979
+ if (_currentDebt === BigInt(0))
2980
+ throw Error("Loan for ".concat(address, " does not exist"));
2981
+ if (!(_borrowed > BigInt(0))) return [3 /*break*/, 3];
2982
+ return [4 /*yield*/, this._userBands(address)];
2983
+ case 2: return [2 /*return*/, _c.sent()];
2984
+ case 3:
2985
+ _debt = _currentDebt - parseUnits(debt, this.borrowed_token.decimals);
2986
+ return [4 /*yield*/, this._calcN1(_currentCollateral, _debt, Number(_N))];
2987
+ case 4:
2988
+ _n1 = _c.sent();
2989
+ _n2 = _n1 + _N - BigInt(1);
2990
+ return [2 /*return*/, [_n2, _n1]];
2991
+ }
2992
+ });
2993
+ });
2994
+ };
2995
+ LendMarketTemplate.prototype.repayBands = function (debt, address) {
2996
+ if (address === void 0) { address = ""; }
2997
+ return __awaiter(this, void 0, void 0, function () {
2998
+ var _a, _n2, _n1;
2999
+ return __generator(this, function (_c) {
3000
+ switch (_c.label) {
3001
+ case 0: return [4 /*yield*/, this._repayBands(debt, address)];
3002
+ case 1:
3003
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
3004
+ return [2 /*return*/, [Number(_n2), Number(_n1)]];
3005
+ }
3006
+ });
3007
+ });
3008
+ };
3009
+ LendMarketTemplate.prototype.repayPrices = function (debt, address) {
3010
+ if (address === void 0) { address = ""; }
3011
+ return __awaiter(this, void 0, void 0, function () {
3012
+ var _a, _n2, _n1;
3013
+ return __generator(this, function (_c) {
3014
+ switch (_c.label) {
3015
+ case 0: return [4 /*yield*/, this._repayBands(debt, address)];
3016
+ case 1:
3017
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
3018
+ return [4 /*yield*/, this._getPrices(_n2, _n1)];
3019
+ case 2: return [2 /*return*/, _c.sent()];
3020
+ }
3021
+ });
3022
+ });
3023
+ };
3024
+ LendMarketTemplate.prototype.repayIsApproved = function (debt) {
3025
+ return __awaiter(this, void 0, void 0, function () {
3026
+ return __generator(this, function (_a) {
3027
+ switch (_a.label) {
3028
+ case 0: return [4 /*yield*/, hasAllowance([this.borrowed_token.address], [debt], llamalend.signerAddress, this.addresses.controller)];
3029
+ case 1: return [2 /*return*/, _a.sent()];
3030
+ }
3031
+ });
3032
+ });
3033
+ };
3034
+ LendMarketTemplate.prototype.repayApproveEstimateGas = function (debt) {
3035
+ return __awaiter(this, void 0, void 0, function () {
3036
+ return __generator(this, function (_a) {
3037
+ switch (_a.label) {
3038
+ case 0: return [4 /*yield*/, ensureAllowanceEstimateGas([this.borrowed_token.address], [debt], this.addresses.controller)];
3039
+ case 1: return [2 /*return*/, _a.sent()];
3040
+ }
3041
+ });
3042
+ });
3043
+ };
3044
+ LendMarketTemplate.prototype.repayApprove = function (debt) {
3045
+ return __awaiter(this, void 0, void 0, function () {
3046
+ return __generator(this, function (_a) {
3047
+ switch (_a.label) {
3048
+ case 0: return [4 /*yield*/, ensureAllowance([this.borrowed_token.address], [debt], this.addresses.controller)];
3049
+ case 1: return [2 /*return*/, _a.sent()];
3050
+ }
3051
+ });
3052
+ });
3053
+ };
3054
+ LendMarketTemplate.prototype.repayHealth = function (debt, full, address) {
3055
+ if (full === void 0) { full = true; }
3056
+ if (address === void 0) { address = ""; }
3057
+ return __awaiter(this, void 0, void 0, function () {
3058
+ var _debt, contract, _health;
3059
+ return __generator(this, function (_a) {
3060
+ switch (_a.label) {
3061
+ case 0:
3062
+ address = _getAddress(address);
3063
+ _debt = parseUnits(debt) * BigInt(-1);
3064
+ contract = llamalend.contracts[this.addresses.controller].contract;
3065
+ return [4 /*yield*/, contract.health_calculator(address, 0, _debt, full, 0, llamalend.constantOptions)];
3066
+ case 1:
3067
+ _health = _a.sent();
3068
+ _health = _health * BigInt(100);
3069
+ return [2 /*return*/, formatUnits(_health)];
3070
+ }
3071
+ });
3072
+ });
3073
+ };
3074
+ LendMarketTemplate.prototype._repay = function (debt, address, estimateGas) {
3075
+ return __awaiter(this, void 0, void 0, function () {
3076
+ var currentDebt, _debt, contract, _a, _, n1, borrowed, n, gas, gasLimit;
3077
+ return __generator(this, function (_c) {
3078
+ switch (_c.label) {
3079
+ case 0:
3080
+ address = _getAddress(address);
3081
+ return [4 /*yield*/, this.userState(address)];
3082
+ case 1:
3083
+ currentDebt = (_c.sent()).debt;
3084
+ if (Number(currentDebt) === 0)
3085
+ throw Error("Loan for ".concat(address, " does not exist"));
3086
+ _debt = parseUnits(debt);
3087
+ contract = llamalend.contracts[this.addresses.controller].contract;
3088
+ return [4 /*yield*/, this.userBands(address)];
3089
+ case 2:
3090
+ _a = _c.sent(), _ = _a[0], n1 = _a[1];
3091
+ return [4 /*yield*/, this.userState(address)];
3092
+ case 3:
3093
+ borrowed = (_c.sent()).borrowed;
3094
+ n = (BN(borrowed).gt(0)) ? MAX_ACTIVE_BAND : n1 - 1;
3095
+ return [4 /*yield*/, contract.repay.estimateGas(_debt, address, n, llamalend.constantOptions)];
3096
+ case 4:
3097
+ gas = _c.sent();
3098
+ if (estimateGas)
3099
+ return [2 /*return*/, smartNumber(gas)];
3100
+ return [4 /*yield*/, llamalend.updateFeeData()];
3101
+ case 5:
3102
+ _c.sent();
3103
+ gasLimit = _mulBy1_3(DIGas(gas));
3104
+ return [4 /*yield*/, contract.repay(_debt, address, n, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
3105
+ case 6: return [2 /*return*/, (_c.sent()).hash];
3106
+ }
3107
+ });
3108
+ });
3109
+ };
3110
+ LendMarketTemplate.prototype.repayEstimateGas = function (debt, address) {
3111
+ if (address === void 0) { address = ""; }
3112
+ return __awaiter(this, void 0, void 0, function () {
3113
+ return __generator(this, function (_a) {
3114
+ switch (_a.label) {
3115
+ case 0: return [4 /*yield*/, this.repayIsApproved(debt)];
3116
+ case 1:
3117
+ if (!(_a.sent()))
3118
+ throw Error("Approval is needed for gas estimation");
3119
+ return [4 /*yield*/, this._repay(debt, address, true)];
3120
+ case 2: return [2 /*return*/, _a.sent()];
3121
+ }
3122
+ });
3123
+ });
3124
+ };
3125
+ LendMarketTemplate.prototype.repay = function (debt, address) {
3126
+ if (address === void 0) { address = ""; }
3127
+ return __awaiter(this, void 0, void 0, function () {
3128
+ return __generator(this, function (_a) {
3129
+ switch (_a.label) {
3130
+ case 0: return [4 /*yield*/, this.repayApprove(debt)];
3131
+ case 1:
3132
+ _a.sent();
3133
+ return [4 /*yield*/, this._repay(debt, address, false)];
3134
+ case 2: return [2 /*return*/, _a.sent()];
3135
+ }
3136
+ });
3137
+ });
3138
+ };
3139
+ // ---------------- FULL REPAY ----------------
3140
+ LendMarketTemplate.prototype._fullRepayAmount = function (address) {
3141
+ if (address === void 0) { address = ""; }
3142
+ return __awaiter(this, void 0, void 0, function () {
3143
+ var debt;
3144
+ return __generator(this, function (_a) {
3145
+ switch (_a.label) {
3146
+ case 0:
3147
+ address = _getAddress(address);
3148
+ return [4 /*yield*/, this.userState(address)];
3149
+ case 1:
3150
+ debt = (_a.sent()).debt;
3151
+ return [2 /*return*/, BN(debt).times(1.0001).toString()];
3152
+ }
3153
+ });
3154
+ });
3155
+ };
3156
+ LendMarketTemplate.prototype.fullRepayIsApproved = function (address) {
3157
+ if (address === void 0) { address = ""; }
3158
+ return __awaiter(this, void 0, void 0, function () {
3159
+ var fullRepayAmount;
3160
+ return __generator(this, function (_a) {
3161
+ switch (_a.label) {
3162
+ case 0:
3163
+ address = _getAddress(address);
3164
+ return [4 /*yield*/, this._fullRepayAmount(address)];
3165
+ case 1:
3166
+ fullRepayAmount = _a.sent();
3167
+ return [4 /*yield*/, this.repayIsApproved(fullRepayAmount)];
3168
+ case 2: return [2 /*return*/, _a.sent()];
3169
+ }
3170
+ });
3171
+ });
3172
+ };
3173
+ LendMarketTemplate.prototype.fullRepayApproveEstimateGas = function (address) {
3174
+ if (address === void 0) { address = ""; }
3175
+ return __awaiter(this, void 0, void 0, function () {
3176
+ var fullRepayAmount;
3177
+ return __generator(this, function (_a) {
3178
+ switch (_a.label) {
3179
+ case 0:
3180
+ address = _getAddress(address);
3181
+ return [4 /*yield*/, this._fullRepayAmount(address)];
3182
+ case 1:
3183
+ fullRepayAmount = _a.sent();
3184
+ return [4 /*yield*/, this.repayApproveEstimateGas(fullRepayAmount)];
3185
+ case 2: return [2 /*return*/, _a.sent()];
3186
+ }
3187
+ });
3188
+ });
3189
+ };
3190
+ LendMarketTemplate.prototype.fullRepayApprove = function (address) {
3191
+ if (address === void 0) { address = ""; }
3192
+ return __awaiter(this, void 0, void 0, function () {
3193
+ var fullRepayAmount;
3194
+ return __generator(this, function (_a) {
3195
+ switch (_a.label) {
3196
+ case 0:
3197
+ address = _getAddress(address);
3198
+ return [4 /*yield*/, this._fullRepayAmount(address)];
3199
+ case 1:
3200
+ fullRepayAmount = _a.sent();
3201
+ return [4 /*yield*/, this.repayApprove(fullRepayAmount)];
3202
+ case 2: return [2 /*return*/, _a.sent()];
3203
+ }
3204
+ });
3205
+ });
3206
+ };
3207
+ LendMarketTemplate.prototype.fullRepayEstimateGas = function (address) {
3208
+ if (address === void 0) { address = ""; }
3209
+ return __awaiter(this, void 0, void 0, function () {
3210
+ var fullRepayAmount;
3211
+ return __generator(this, function (_a) {
3212
+ switch (_a.label) {
3213
+ case 0:
3214
+ address = _getAddress(address);
3215
+ return [4 /*yield*/, this._fullRepayAmount(address)];
3216
+ case 1:
3217
+ fullRepayAmount = _a.sent();
3218
+ return [4 /*yield*/, this.repayIsApproved(fullRepayAmount)];
3219
+ case 2:
3220
+ if (!(_a.sent()))
3221
+ throw Error("Approval is needed for gas estimation");
3222
+ return [4 /*yield*/, this._repay(fullRepayAmount, address, true)];
3223
+ case 3: return [2 /*return*/, _a.sent()];
3224
+ }
3225
+ });
3226
+ });
3227
+ };
3228
+ LendMarketTemplate.prototype.fullRepay = function (address) {
3229
+ if (address === void 0) { address = ""; }
3230
+ return __awaiter(this, void 0, void 0, function () {
3231
+ var fullRepayAmount;
3232
+ return __generator(this, function (_a) {
3233
+ switch (_a.label) {
3234
+ case 0:
3235
+ address = _getAddress(address);
3236
+ return [4 /*yield*/, this._fullRepayAmount(address)];
3237
+ case 1:
3238
+ fullRepayAmount = _a.sent();
3239
+ return [4 /*yield*/, this.repayApprove(fullRepayAmount)];
3240
+ case 2:
3241
+ _a.sent();
3242
+ return [4 /*yield*/, this._repay(fullRepayAmount, address, false)];
3243
+ case 3: return [2 /*return*/, _a.sent()];
3244
+ }
3245
+ });
3246
+ });
3247
+ };
3248
+ // ---------------- SWAP ----------------
3249
+ LendMarketTemplate.prototype.maxSwappable = function (i, j) {
3250
+ return __awaiter(this, void 0, void 0, function () {
3251
+ var inDecimals, contract, _a, _inAmount, _outAmount;
3252
+ return __generator(this, function (_c) {
3253
+ switch (_c.label) {
3254
+ case 0:
3255
+ if (!(i === 0 && j === 1) && !(i === 1 && j === 0))
3256
+ throw Error("Wrong index");
3257
+ inDecimals = this.coinDecimals[i];
3258
+ contract = llamalend.contracts[this.addresses.amm].contract;
3259
+ return [4 /*yield*/, contract.get_dxdy(i, j, MAX_ALLOWANCE, llamalend.constantOptions)];
3260
+ case 1:
3261
+ _a = _c.sent(), _inAmount = _a[0], _outAmount = _a[1];
3262
+ if (_outAmount === BigInt(0))
3263
+ return [2 /*return*/, "0"];
3264
+ return [2 /*return*/, formatUnits(_inAmount, inDecimals)];
3265
+ }
3266
+ });
3267
+ });
3268
+ };
3269
+ LendMarketTemplate.prototype._swapExpected = function (i, j, _amount) {
3270
+ return __awaiter(this, void 0, void 0, function () {
3271
+ return __generator(this, function (_a) {
3272
+ switch (_a.label) {
3273
+ case 0: return [4 /*yield*/, llamalend.contracts[this.addresses.amm].contract.get_dy(i, j, _amount, llamalend.constantOptions)];
3274
+ case 1: return [2 /*return*/, _a.sent()];
3275
+ }
3276
+ });
3277
+ });
3278
+ };
3279
+ LendMarketTemplate.prototype.swapExpected = function (i, j, amount) {
3280
+ return __awaiter(this, void 0, void 0, function () {
3281
+ var _a, inDecimals, outDecimals, _amount, _expected;
3282
+ return __generator(this, function (_c) {
3283
+ switch (_c.label) {
3284
+ case 0:
3285
+ if (!(i === 0 && j === 1) && !(i === 1 && j === 0))
3286
+ throw Error("Wrong index");
3287
+ _a = this.coinDecimals, inDecimals = _a[0], outDecimals = _a[1];
3288
+ _amount = parseUnits(amount, inDecimals);
3289
+ return [4 /*yield*/, this._swapExpected(i, j, _amount)];
3290
+ case 1:
3291
+ _expected = _c.sent();
3292
+ return [2 /*return*/, formatUnits(_expected, outDecimals)];
3293
+ }
3294
+ });
3295
+ });
3296
+ };
3297
+ LendMarketTemplate.prototype.swapRequired = function (i, j, outAmount) {
3298
+ return __awaiter(this, void 0, void 0, function () {
3299
+ var _a, inDecimals, outDecimals, _amount, _expected;
3300
+ return __generator(this, function (_c) {
3301
+ switch (_c.label) {
3302
+ case 0:
3303
+ if (!(i === 0 && j === 1) && !(i === 1 && j === 0))
3304
+ throw Error("Wrong index");
3305
+ _a = this.coinDecimals, inDecimals = _a[0], outDecimals = _a[1];
3306
+ _amount = parseUnits(outAmount, outDecimals);
3307
+ return [4 /*yield*/, llamalend.contracts[this.addresses.amm].contract.get_dx(i, j, _amount, llamalend.constantOptions)];
3308
+ case 1:
3309
+ _expected = _c.sent();
3310
+ return [2 /*return*/, formatUnits(_expected, inDecimals)];
3311
+ }
3312
+ });
3313
+ });
3314
+ };
3315
+ LendMarketTemplate.prototype.swapPriceImpact = function (i, j, amount) {
3316
+ return __awaiter(this, void 0, void 0, function () {
3317
+ var _a, inDecimals, outDecimals, _amount, _output, target, amountIntBN, outputIntBN, k, smallAmountIntBN, _smallAmount, _smallOutput, amountBN, outputBN, smallAmountBN, smallOutputBN, rateBN, smallRateBN, slippageBN;
3318
+ return __generator(this, function (_c) {
3319
+ switch (_c.label) {
3320
+ case 0:
3321
+ if (!(i === 0 && j === 1) && !(i === 1 && j === 0))
3322
+ throw Error("Wrong index");
3323
+ _a = this.coinDecimals, inDecimals = _a[0], outDecimals = _a[1];
3324
+ _amount = parseUnits(amount, inDecimals);
3325
+ return [4 /*yield*/, this._swapExpected(i, j, _amount)];
3326
+ case 1:
3327
+ _output = _c.sent();
3328
+ target = BN(Math.pow(10, 15));
3329
+ amountIntBN = BN(amount).times(Math.pow(10, inDecimals));
3330
+ outputIntBN = toBN(_output, 0);
3331
+ k = BigNumber.min(BigNumber.max(target.div(amountIntBN), target.div(outputIntBN)), 0.2);
3332
+ smallAmountIntBN = BigNumber.min(amountIntBN.times(k), BN(Math.pow(10, inDecimals)));
3333
+ if (smallAmountIntBN.toFixed(0) === '0')
3334
+ return [2 /*return*/, '0'];
3335
+ _smallAmount = fromBN(smallAmountIntBN.div(Math.pow(10, inDecimals)), inDecimals);
3336
+ return [4 /*yield*/, this._swapExpected(i, j, _smallAmount)];
3337
+ case 2:
3338
+ _smallOutput = _c.sent();
3339
+ amountBN = BN(amount);
3340
+ outputBN = toBN(_output, outDecimals);
3341
+ smallAmountBN = toBN(_smallAmount, inDecimals);
3342
+ smallOutputBN = toBN(_smallOutput, outDecimals);
3343
+ rateBN = outputBN.div(amountBN);
3344
+ smallRateBN = smallOutputBN.div(smallAmountBN);
3345
+ if (rateBN.gt(smallRateBN))
3346
+ return [2 /*return*/, "0"];
3347
+ slippageBN = BN(1).minus(rateBN.div(smallRateBN)).times(100);
3348
+ return [2 /*return*/, _cutZeros(slippageBN.toFixed(6))];
3349
+ }
3350
+ });
3351
+ });
3352
+ };
3353
+ LendMarketTemplate.prototype.swapIsApproved = function (i, amount) {
3354
+ return __awaiter(this, void 0, void 0, function () {
3355
+ return __generator(this, function (_a) {
3356
+ switch (_a.label) {
3357
+ case 0:
3358
+ if (i !== 0 && i !== 1)
3359
+ throw Error("Wrong index");
3360
+ return [4 /*yield*/, hasAllowance([this.coinAddresses[i]], [amount], llamalend.signerAddress, this.addresses.amm)];
3361
+ case 1: return [2 /*return*/, _a.sent()];
3362
+ }
3363
+ });
3364
+ });
3365
+ };
3366
+ LendMarketTemplate.prototype.swapApproveEstimateGas = function (i, amount) {
3367
+ return __awaiter(this, void 0, void 0, function () {
3368
+ return __generator(this, function (_a) {
3369
+ switch (_a.label) {
3370
+ case 0:
3371
+ if (i !== 0 && i !== 1)
3372
+ throw Error("Wrong index");
3373
+ return [4 /*yield*/, ensureAllowanceEstimateGas([this.coinAddresses[i]], [amount], this.addresses.amm)];
3374
+ case 1: return [2 /*return*/, _a.sent()];
3375
+ }
3376
+ });
3377
+ });
3378
+ };
3379
+ LendMarketTemplate.prototype.swapApprove = function (i, amount) {
3380
+ return __awaiter(this, void 0, void 0, function () {
3381
+ return __generator(this, function (_a) {
3382
+ switch (_a.label) {
3383
+ case 0:
3384
+ if (i !== 0 && i !== 1)
3385
+ throw Error("Wrong index");
3386
+ return [4 /*yield*/, ensureAllowance([this.coinAddresses[i]], [amount], this.addresses.amm)];
3387
+ case 1: return [2 /*return*/, _a.sent()];
3388
+ }
3389
+ });
3390
+ });
3391
+ };
3392
+ LendMarketTemplate.prototype._swap = function (i, j, amount, slippage, estimateGas) {
3393
+ return __awaiter(this, void 0, void 0, function () {
3394
+ var _a, inDecimals, outDecimals, _amount, _expected, minRecvAmountBN, _minRecvAmount, contract, gas, gasLimit;
3395
+ return __generator(this, function (_c) {
3396
+ switch (_c.label) {
3397
+ case 0:
3398
+ if (!(i === 0 && j === 1) && !(i === 1 && j === 0))
3399
+ throw Error("Wrong index");
3400
+ _a = [this.coinDecimals[i], this.coinDecimals[j]], inDecimals = _a[0], outDecimals = _a[1];
3401
+ _amount = parseUnits(amount, inDecimals);
3402
+ return [4 /*yield*/, this._swapExpected(i, j, _amount)];
3403
+ case 1:
3404
+ _expected = _c.sent();
3405
+ minRecvAmountBN = toBN(_expected, outDecimals).times(100 - slippage).div(100);
3406
+ _minRecvAmount = fromBN(minRecvAmountBN, outDecimals);
3407
+ contract = llamalend.contracts[this.addresses.amm].contract;
3408
+ return [4 /*yield*/, contract.exchange.estimateGas(i, j, _amount, _minRecvAmount, llamalend.constantOptions)];
3409
+ case 2:
3410
+ gas = _c.sent();
3411
+ if (estimateGas)
3412
+ return [2 /*return*/, smartNumber(gas)];
3413
+ return [4 /*yield*/, llamalend.updateFeeData()];
3414
+ case 3:
3415
+ _c.sent();
3416
+ gasLimit = _mulBy1_3(DIGas(gas));
3417
+ return [4 /*yield*/, contract.exchange(i, j, _amount, _minRecvAmount, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
3418
+ case 4: return [2 /*return*/, (_c.sent()).hash];
3419
+ }
3420
+ });
3421
+ });
3422
+ };
3423
+ LendMarketTemplate.prototype.swapEstimateGas = function (i, j, amount, slippage) {
3424
+ if (slippage === void 0) { slippage = 0.1; }
3425
+ return __awaiter(this, void 0, void 0, function () {
3426
+ return __generator(this, function (_a) {
3427
+ switch (_a.label) {
3428
+ case 0: return [4 /*yield*/, this.swapIsApproved(i, amount)];
3429
+ case 1:
3430
+ if (!(_a.sent()))
3431
+ throw Error("Approval is needed for gas estimation");
3432
+ return [4 /*yield*/, this._swap(i, j, amount, slippage, true)];
3433
+ case 2: return [2 /*return*/, _a.sent()];
3434
+ }
3435
+ });
3436
+ });
3437
+ };
3438
+ LendMarketTemplate.prototype.swap = function (i, j, amount, slippage) {
3439
+ if (slippage === void 0) { slippage = 0.1; }
3440
+ return __awaiter(this, void 0, void 0, function () {
3441
+ return __generator(this, function (_a) {
3442
+ switch (_a.label) {
3443
+ case 0: return [4 /*yield*/, this.swapApprove(i, amount)];
3444
+ case 1:
3445
+ _a.sent();
3446
+ return [4 /*yield*/, this._swap(i, j, amount, slippage, false)];
3447
+ case 2: return [2 /*return*/, _a.sent()];
3448
+ }
3449
+ });
3450
+ });
3451
+ };
3452
+ // ---------------- LIQUIDATE ----------------
3453
+ LendMarketTemplate.prototype.tokensToLiquidate = function (address) {
3454
+ if (address === void 0) { address = ""; }
3455
+ return __awaiter(this, void 0, void 0, function () {
3456
+ var _tokens;
3457
+ return __generator(this, function (_a) {
3458
+ switch (_a.label) {
3459
+ case 0:
3460
+ address = _getAddress(address);
3461
+ return [4 /*yield*/, llamalend.contracts[this.addresses.controller].contract.tokens_to_liquidate(address, llamalend.constantOptions)];
3462
+ case 1:
3463
+ _tokens = _a.sent();
3464
+ return [2 /*return*/, formatUnits(_tokens, this.borrowed_token.decimals)];
3465
+ }
3466
+ });
3467
+ });
3468
+ };
3469
+ LendMarketTemplate.prototype.liquidateIsApproved = function (address) {
3470
+ if (address === void 0) { address = ""; }
3471
+ return __awaiter(this, void 0, void 0, function () {
3472
+ var tokensToLiquidate;
3473
+ return __generator(this, function (_a) {
3474
+ switch (_a.label) {
3475
+ case 0: return [4 /*yield*/, this.tokensToLiquidate(address)];
3476
+ case 1:
3477
+ tokensToLiquidate = _a.sent();
3478
+ return [4 /*yield*/, hasAllowance([this.addresses.borrowed_token], [tokensToLiquidate], llamalend.signerAddress, this.addresses.controller)];
3479
+ case 2: return [2 /*return*/, _a.sent()];
3480
+ }
3481
+ });
3482
+ });
3483
+ };
3484
+ LendMarketTemplate.prototype.liquidateApproveEstimateGas = function (address) {
3485
+ if (address === void 0) { address = ""; }
3486
+ return __awaiter(this, void 0, void 0, function () {
3487
+ var tokensToLiquidate;
3488
+ return __generator(this, function (_a) {
3489
+ switch (_a.label) {
3490
+ case 0: return [4 /*yield*/, this.tokensToLiquidate(address)];
3491
+ case 1:
3492
+ tokensToLiquidate = _a.sent();
3493
+ return [4 /*yield*/, ensureAllowanceEstimateGas([this.addresses.borrowed_token], [tokensToLiquidate], this.addresses.controller)];
3494
+ case 2: return [2 /*return*/, _a.sent()];
3495
+ }
3496
+ });
3497
+ });
3498
+ };
3499
+ LendMarketTemplate.prototype.liquidateApprove = function (address) {
3500
+ if (address === void 0) { address = ""; }
3501
+ return __awaiter(this, void 0, void 0, function () {
3502
+ var tokensToLiquidate;
3503
+ return __generator(this, function (_a) {
3504
+ switch (_a.label) {
3505
+ case 0: return [4 /*yield*/, this.tokensToLiquidate(address)];
3506
+ case 1:
3507
+ tokensToLiquidate = _a.sent();
3508
+ return [4 /*yield*/, ensureAllowance([this.addresses.borrowed_token], [tokensToLiquidate], this.addresses.controller)];
3509
+ case 2: return [2 /*return*/, _a.sent()];
3510
+ }
3511
+ });
3512
+ });
3513
+ };
3514
+ LendMarketTemplate.prototype._liquidate = function (address, slippage, estimateGas) {
3515
+ return __awaiter(this, void 0, void 0, function () {
3516
+ var _a, borrowed, currentDebt, minAmountBN, _minAmount, contract, gas, gasLimit;
3517
+ return __generator(this, function (_c) {
3518
+ switch (_c.label) {
3519
+ case 0: return [4 /*yield*/, this.userState(address)];
3520
+ case 1:
3521
+ _a = _c.sent(), borrowed = _a.borrowed, currentDebt = _a.debt;
3522
+ if (slippage <= 0)
3523
+ throw Error("Slippage must be > 0");
3524
+ if (slippage > 100)
3525
+ throw Error("Slippage must be <= 100");
3526
+ if (Number(currentDebt) === 0)
3527
+ throw Error("Loan for ".concat(address, " does not exist"));
3528
+ if (Number(borrowed) === 0)
3529
+ throw Error("User ".concat(address, " is not in liquidation mode"));
3530
+ minAmountBN = BN(borrowed).times(100 - slippage).div(100);
3531
+ _minAmount = fromBN(minAmountBN);
3532
+ contract = llamalend.contracts[this.addresses.controller].contract;
3533
+ return [4 /*yield*/, contract.liquidate.estimateGas(address, _minAmount, llamalend.constantOptions)];
3534
+ case 2:
3535
+ gas = (_c.sent());
3536
+ if (estimateGas)
3537
+ return [2 /*return*/, smartNumber(gas)];
3538
+ return [4 /*yield*/, llamalend.updateFeeData()];
3539
+ case 3:
3540
+ _c.sent();
3541
+ gasLimit = _mulBy1_3(DIGas(gas));
3542
+ return [4 /*yield*/, contract.liquidate(address, _minAmount, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
3543
+ case 4: return [2 /*return*/, (_c.sent()).hash];
3544
+ }
3545
+ });
3546
+ });
3547
+ };
3548
+ LendMarketTemplate.prototype.liquidateEstimateGas = function (address, slippage) {
3549
+ if (slippage === void 0) { slippage = 0.1; }
3550
+ return __awaiter(this, void 0, void 0, function () {
3551
+ return __generator(this, function (_a) {
3552
+ switch (_a.label) {
3553
+ case 0: return [4 /*yield*/, this.liquidateIsApproved(address)];
3554
+ case 1:
3555
+ if (!(_a.sent()))
3556
+ throw Error("Approval is needed for gas estimation");
3557
+ return [4 /*yield*/, this._liquidate(address, slippage, true)];
3558
+ case 2: return [2 /*return*/, _a.sent()];
3559
+ }
3560
+ });
3561
+ });
3562
+ };
3563
+ LendMarketTemplate.prototype.liquidate = function (address, slippage) {
3564
+ if (slippage === void 0) { slippage = 0.1; }
3565
+ return __awaiter(this, void 0, void 0, function () {
3566
+ return __generator(this, function (_a) {
3567
+ switch (_a.label) {
3568
+ case 0: return [4 /*yield*/, this.liquidateApprove(address)];
3569
+ case 1:
3570
+ _a.sent();
3571
+ return [4 /*yield*/, this._liquidate(address, slippage, false)];
3572
+ case 2: return [2 /*return*/, _a.sent()];
3573
+ }
3574
+ });
3575
+ });
3576
+ };
3577
+ // ---------------- SELF-LIQUIDATE ----------------
3578
+ LendMarketTemplate.prototype.selfLiquidateIsApproved = function () {
3579
+ return __awaiter(this, void 0, void 0, function () {
3580
+ return __generator(this, function (_a) {
3581
+ switch (_a.label) {
3582
+ case 0: return [4 /*yield*/, this.liquidateIsApproved()];
3583
+ case 1: return [2 /*return*/, _a.sent()];
3584
+ }
3585
+ });
3586
+ });
3587
+ };
3588
+ LendMarketTemplate.prototype.selfLiquidateApproveEstimateGas = function () {
3589
+ return __awaiter(this, void 0, void 0, function () {
3590
+ return __generator(this, function (_a) {
3591
+ return [2 /*return*/, this.liquidateApproveEstimateGas()];
3592
+ });
3593
+ });
3594
+ };
3595
+ LendMarketTemplate.prototype.selfLiquidateApprove = function () {
3596
+ return __awaiter(this, void 0, void 0, function () {
3597
+ return __generator(this, function (_a) {
3598
+ switch (_a.label) {
3599
+ case 0: return [4 /*yield*/, this.liquidateApprove()];
3600
+ case 1: return [2 /*return*/, _a.sent()];
3601
+ }
3602
+ });
3603
+ });
3604
+ };
3605
+ LendMarketTemplate.prototype.selfLiquidateEstimateGas = function (slippage) {
3606
+ if (slippage === void 0) { slippage = 0.1; }
3607
+ return __awaiter(this, void 0, void 0, function () {
3608
+ return __generator(this, function (_a) {
3609
+ switch (_a.label) {
3610
+ case 0: return [4 /*yield*/, this.selfLiquidateIsApproved()];
3611
+ case 1:
3612
+ if (!(_a.sent()))
3613
+ throw Error("Approval is needed for gas estimation");
3614
+ return [4 /*yield*/, this._liquidate(llamalend.signerAddress, slippage, true)];
3615
+ case 2: return [2 /*return*/, _a.sent()];
3616
+ }
3617
+ });
3618
+ });
3619
+ };
3620
+ LendMarketTemplate.prototype.selfLiquidate = function (slippage) {
3621
+ if (slippage === void 0) { slippage = 0.1; }
3622
+ return __awaiter(this, void 0, void 0, function () {
3623
+ return __generator(this, function (_a) {
3624
+ switch (_a.label) {
3625
+ case 0: return [4 /*yield*/, this.selfLiquidateApprove()];
3626
+ case 1:
3627
+ _a.sent();
3628
+ return [4 /*yield*/, this._liquidate(llamalend.signerAddress, slippage, false)];
3629
+ case 2: return [2 /*return*/, _a.sent()];
3630
+ }
3631
+ });
3632
+ });
3633
+ };
3634
+ LendMarketTemplate.prototype._checkLeverageZap = function () {
3635
+ if (!this.hasLeverage()) {
3636
+ throw Error("This market does not support leverage");
3637
+ }
3638
+ };
3639
+ LendMarketTemplate.prototype._get_k_effective_BN = function (N) {
3640
+ return __awaiter(this, void 0, void 0, function () {
3641
+ var _a, loan_discount, A, A_BN, A_ratio_BN, d_k_effective_BN, S, n;
3642
+ return __generator(this, function (_c) {
3643
+ switch (_c.label) {
3644
+ case 0: return [4 /*yield*/, this.statsParameters()];
3645
+ case 1:
3646
+ _a = _c.sent(), loan_discount = _a.loan_discount, A = _a.A;
3647
+ A_BN = BN(A);
3648
+ A_ratio_BN = A_BN.minus(1).div(A_BN);
3649
+ d_k_effective_BN = BN(100).minus(loan_discount).div(100).times(A_ratio_BN.sqrt()).div(N);
3650
+ S = BN(0);
3651
+ for (n = 0; n < N; n++) {
3652
+ S = S.plus(A_ratio_BN.pow(n));
3653
+ }
3654
+ return [2 /*return*/, d_k_effective_BN.times(S)];
3655
+ }
3656
+ });
3657
+ });
3658
+ };
3659
+ LendMarketTemplate.prototype.maxLeverage = function (N) {
3660
+ return __awaiter(this, void 0, void 0, function () {
3661
+ var k_effective_BN;
3662
+ return __generator(this, function (_a) {
3663
+ switch (_a.label) {
3664
+ case 0: return [4 /*yield*/, this._get_k_effective_BN(N)];
3665
+ case 1:
3666
+ k_effective_BN = _a.sent();
3667
+ return [2 /*return*/, BN(1).div(BN(1).minus(k_effective_BN)).toString()];
3668
+ }
3669
+ });
3670
+ });
3671
+ };
3672
+ LendMarketTemplate.prototype.leverageCreateLoanMaxRecv = function (userCollateral, userBorrowed, range) {
3673
+ return __awaiter(this, void 0, void 0, function () {
3674
+ var _userCollateral, _userBorrowed, oraclePriceBand, pAvgBN, _a, maxBorrowablePrevBN, maxBorrowableBN, _userEffectiveCollateral, _maxLeverageCollateral, contract, i, _maxBorrowable, _maxAdditionalCollateral, _c, userEffectiveCollateralBN, maxLeverageCollateralBN;
3675
+ return __generator(this, function (_d) {
3676
+ switch (_d.label) {
3677
+ case 0:
3678
+ // max_borrowable = userCollateral / (1 / (k_effective * max_p_base) - 1 / p_avg)
3679
+ this._checkLeverageZap();
3680
+ if (range > 0)
3681
+ this._checkRange(range);
3682
+ _userCollateral = parseUnits(userCollateral, this.collateral_token.decimals);
3683
+ _userBorrowed = parseUnits(userBorrowed, this.borrowed_token.decimals);
3684
+ return [4 /*yield*/, this.oraclePriceBand()];
3685
+ case 1:
3686
+ oraclePriceBand = _d.sent();
3687
+ _a = BN;
3688
+ return [4 /*yield*/, this.calcTickPrice(oraclePriceBand)];
3689
+ case 2:
3690
+ pAvgBN = _a.apply(void 0, [_d.sent()]);
3691
+ maxBorrowablePrevBN = BN(0);
3692
+ maxBorrowableBN = BN(0);
3693
+ _userEffectiveCollateral = BigInt(0);
3694
+ _maxLeverageCollateral = BigInt(0);
3695
+ contract = llamalend.contracts[llamalend.constants.ALIASES.leverage_zap].contract;
3696
+ i = 0;
3697
+ _d.label = 3;
3698
+ case 3:
3699
+ if (!(i < 5)) return [3 /*break*/, 7];
3700
+ maxBorrowablePrevBN = maxBorrowableBN;
3701
+ _userEffectiveCollateral = _userCollateral + fromBN(BN(userBorrowed).div(pAvgBN), this.collateral_token.decimals);
3702
+ return [4 /*yield*/, contract.max_borrowable(this.addresses.controller, _userEffectiveCollateral, _maxLeverageCollateral, range, fromBN(pAvgBN))];
3703
+ case 4:
3704
+ _maxBorrowable = _d.sent();
3705
+ _maxBorrowable = _maxBorrowable * BigInt(998) / BigInt(1000);
3706
+ if (_maxBorrowable === BigInt(0))
3707
+ return [3 /*break*/, 7];
3708
+ maxBorrowableBN = toBN(_maxBorrowable, this.borrowed_token.decimals);
3709
+ if (maxBorrowableBN.minus(maxBorrowablePrevBN).abs().div(maxBorrowablePrevBN).lt(0.0005)) {
3710
+ maxBorrowableBN = maxBorrowablePrevBN;
3711
+ return [3 /*break*/, 7];
3712
+ }
3713
+ _c = BigInt;
3714
+ return [4 /*yield*/, _getExpectedOdos(this.addresses.borrowed_token, this.addresses.collateral_token, _maxBorrowable + _userBorrowed, this.addresses.amm)];
3715
+ case 5:
3716
+ _maxAdditionalCollateral = _c.apply(void 0, [_d.sent()]);
3717
+ pAvgBN = maxBorrowableBN.plus(userBorrowed).div(toBN(_maxAdditionalCollateral, this.collateral_token.decimals));
3718
+ _maxLeverageCollateral = _maxAdditionalCollateral - fromBN(BN(userBorrowed).div(pAvgBN), this.collateral_token.decimals);
3719
+ _d.label = 6;
3720
+ case 6:
3721
+ i++;
3722
+ return [3 /*break*/, 3];
3723
+ case 7:
3724
+ userEffectiveCollateralBN = maxBorrowableBN.gt(0) ? toBN(_userEffectiveCollateral, this.collateral_token.decimals) : BN(0);
3725
+ maxLeverageCollateralBN = toBN(_maxLeverageCollateral, this.collateral_token.decimals);
3726
+ return [2 /*return*/, {
3727
+ maxDebt: formatNumber(maxBorrowableBN.toString(), this.borrowed_token.decimals),
3728
+ maxTotalCollateral: formatNumber(maxLeverageCollateralBN.plus(userEffectiveCollateralBN).toString(), this.collateral_token.decimals),
3729
+ userCollateral: formatNumber(userCollateral, this.collateral_token.decimals),
3730
+ collateralFromUserBorrowed: formatNumber(BN(userBorrowed).div(pAvgBN).toString(), this.collateral_token.decimals),
3731
+ collateralFromMaxDebt: formatNumber(maxLeverageCollateralBN.toString(), this.collateral_token.decimals),
3732
+ maxLeverage: maxLeverageCollateralBN.plus(userEffectiveCollateralBN).div(userEffectiveCollateralBN).toString(),
3733
+ avgPrice: pAvgBN.toString(),
3734
+ }];
3735
+ }
3736
+ });
3737
+ });
3738
+ };
3739
+ LendMarketTemplate.prototype.leverageCreateLoanExpectedCollateral = function (userCollateral, userBorrowed, debt, slippage) {
3740
+ if (slippage === void 0) { slippage = 0.1; }
3741
+ return __awaiter(this, void 0, void 0, function () {
3742
+ var _debt, _userBorrowed, _a, _totalCollateral, _userCollateral, _collateralFromUserBorrowed, _collateralFromDebt, avgPrice;
3743
+ return __generator(this, function (_c) {
3744
+ switch (_c.label) {
3745
+ case 0:
3746
+ this._checkLeverageZap();
3747
+ _debt = parseUnits(debt, this.borrowed_token.decimals);
3748
+ _userBorrowed = parseUnits(userBorrowed, this.borrowed_token.decimals);
3749
+ return [4 /*yield*/, this._setSwapDataToCache(this.addresses.borrowed_token, this.addresses.collateral_token, _debt + _userBorrowed, slippage)];
3750
+ case 1:
3751
+ _c.sent();
3752
+ return [4 /*yield*/, this._leverageExpectedCollateral(userCollateral, userBorrowed, debt)];
3753
+ case 2:
3754
+ _a = _c.sent(), _totalCollateral = _a._totalCollateral, _userCollateral = _a._userCollateral, _collateralFromUserBorrowed = _a._collateralFromUserBorrowed, _collateralFromDebt = _a._collateralFromDebt, avgPrice = _a.avgPrice;
3755
+ return [2 /*return*/, {
3756
+ totalCollateral: formatUnits(_totalCollateral, this.collateral_token.decimals),
3757
+ userCollateral: formatUnits(_userCollateral, this.collateral_token.decimals),
3758
+ collateralFromUserBorrowed: formatUnits(_collateralFromUserBorrowed, this.collateral_token.decimals),
3759
+ collateralFromDebt: formatUnits(_collateralFromDebt, this.collateral_token.decimals),
3760
+ leverage: toBN(_collateralFromDebt + _userCollateral + _collateralFromUserBorrowed, this.collateral_token.decimals)
3761
+ .div(toBN(_userCollateral + _collateralFromUserBorrowed, this.collateral_token.decimals)).toString(),
3762
+ avgPrice: avgPrice,
3763
+ }];
3764
+ }
3765
+ });
3766
+ });
3767
+ };
3768
+ LendMarketTemplate.prototype.leverageCreateLoanPriceImpact = function (userBorrowed, debt) {
3769
+ return __awaiter(this, void 0, void 0, function () {
3770
+ var _debt, _userBorrowed;
3771
+ return __generator(this, function (_a) {
3772
+ this._checkLeverageZap();
3773
+ _debt = parseUnits(debt, this.borrowed_token.decimals);
3774
+ _userBorrowed = parseUnits(userBorrowed, this.borrowed_token.decimals);
3775
+ return [2 /*return*/, this._getSwapDataFromCache(this.addresses.borrowed_token, _debt + _userBorrowed).priceImpact.toString()];
3776
+ });
3777
+ });
3778
+ };
3779
+ LendMarketTemplate.prototype.leverageCreateLoanMaxRange = function (userCollateral, userBorrowed, debt) {
3780
+ return __awaiter(this, void 0, void 0, function () {
3781
+ var maxRecv, N;
3782
+ return __generator(this, function (_a) {
3783
+ switch (_a.label) {
3784
+ case 0:
3785
+ this._checkLeverageZap();
3786
+ return [4 /*yield*/, this.leverageCreateLoanMaxRecvAllRanges(userCollateral, userBorrowed)];
3787
+ case 1:
3788
+ maxRecv = _a.sent();
3789
+ for (N = this.minBands; N <= this.maxBands; N++) {
3790
+ if (BN(debt).gt(maxRecv[N].maxDebt))
3791
+ return [2 /*return*/, N - 1];
3792
+ }
3793
+ return [2 /*return*/, this.maxBands];
3794
+ }
3795
+ });
3796
+ });
3797
+ };
3798
+ LendMarketTemplate.prototype._leverageBands = function (userCollateral, userBorrowed, debt, range, user) {
3799
+ return __awaiter(this, void 0, void 0, function () {
3800
+ var _n1, N, _n2;
3801
+ return __generator(this, function (_a) {
3802
+ switch (_a.label) {
3803
+ case 0: return [4 /*yield*/, this._leverageCalcN1(userCollateral, userBorrowed, debt, range, user)];
3804
+ case 1:
3805
+ _n1 = _a.sent();
3806
+ if (!(range < 0)) return [3 /*break*/, 3];
3807
+ return [4 /*yield*/, this.userState(user)];
3808
+ case 2:
3809
+ N = (_a.sent()).N;
3810
+ range = Number(N);
3811
+ _a.label = 3;
3812
+ case 3:
3813
+ _n2 = _n1 + BigInt(range - 1);
3814
+ return [2 /*return*/, [_n2, _n1]];
3815
+ }
3816
+ });
3817
+ });
3818
+ };
3819
+ LendMarketTemplate.prototype._leverageCreateLoanBandsAllRanges = function (userCollateral, userBorrowed, debt) {
3820
+ return __awaiter(this, void 0, void 0, function () {
3821
+ var maxN, _n1_arr, _n2_arr, N, _bands, N;
3822
+ return __generator(this, function (_a) {
3823
+ switch (_a.label) {
3824
+ case 0: return [4 /*yield*/, this.leverageCreateLoanMaxRange(userCollateral, userBorrowed, debt)];
3825
+ case 1:
3826
+ maxN = _a.sent();
3827
+ return [4 /*yield*/, this._leverageCalcN1AllRanges(userCollateral, userBorrowed, debt, maxN)];
3828
+ case 2:
3829
+ _n1_arr = _a.sent();
3830
+ _n2_arr = [];
3831
+ for (N = this.minBands; N <= maxN; N++) {
3832
+ _n2_arr.push(_n1_arr[N - this.minBands] + BigInt(N - 1));
3833
+ }
3834
+ _bands = {};
3835
+ for (N = this.minBands; N <= maxN; N++) {
3836
+ _bands[N] = [_n2_arr[N - this.minBands], _n1_arr[N - this.minBands]];
3837
+ }
3838
+ return [2 /*return*/, _bands];
3839
+ }
3840
+ });
3841
+ });
3842
+ };
3843
+ LendMarketTemplate.prototype.leverageCreateLoanBands = function (userCollateral, userBorrowed, debt, range) {
3844
+ return __awaiter(this, void 0, void 0, function () {
3845
+ var _a, _n2, _n1;
3846
+ return __generator(this, function (_c) {
3847
+ switch (_c.label) {
3848
+ case 0:
3849
+ this._checkLeverageZap();
3850
+ return [4 /*yield*/, this._leverageBands(userCollateral, userBorrowed, debt, range)];
3851
+ case 1:
3852
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
3853
+ return [2 /*return*/, [Number(_n2), Number(_n1)]];
3854
+ }
3855
+ });
3856
+ });
3857
+ };
3858
+ LendMarketTemplate.prototype.leverageCreateLoanBandsAllRanges = function (userCollateral, userBorrowed, debt) {
3859
+ return __awaiter(this, void 0, void 0, function () {
3860
+ var _bands, bands, N;
3861
+ return __generator(this, function (_a) {
3862
+ switch (_a.label) {
3863
+ case 0:
3864
+ this._checkLeverageZap();
3865
+ return [4 /*yield*/, this._leverageCreateLoanBandsAllRanges(userCollateral, userBorrowed, debt)];
3866
+ case 1:
3867
+ _bands = _a.sent();
3868
+ bands = {};
3869
+ for (N = this.minBands; N <= this.maxBands; N++) {
3870
+ if (_bands[N]) {
3871
+ bands[N] = _bands[N].map(Number);
3872
+ }
3873
+ else {
3874
+ bands[N] = null;
3875
+ }
3876
+ }
3877
+ return [2 /*return*/, bands];
3878
+ }
3879
+ });
3880
+ });
3881
+ };
3882
+ LendMarketTemplate.prototype.leverageCreateLoanPrices = function (userCollateral, userBorrowed, debt, range) {
3883
+ return __awaiter(this, void 0, void 0, function () {
3884
+ var _a, _n2, _n1;
3885
+ return __generator(this, function (_c) {
3886
+ switch (_c.label) {
3887
+ case 0:
3888
+ this._checkLeverageZap();
3889
+ return [4 /*yield*/, this._leverageBands(userCollateral, userBorrowed, debt, range)];
3890
+ case 1:
3891
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
3892
+ return [4 /*yield*/, this._getPrices(_n2, _n1)];
3893
+ case 2: return [2 /*return*/, _c.sent()];
3894
+ }
3895
+ });
3896
+ });
3897
+ };
3898
+ LendMarketTemplate.prototype.leverageCreateLoanPricesAllRanges = function (userCollateral, userBorrowed, debt) {
3899
+ return __awaiter(this, void 0, void 0, function () {
3900
+ var _bands, prices, N, _a, _c;
3901
+ return __generator(this, function (_d) {
3902
+ switch (_d.label) {
3903
+ case 0:
3904
+ this._checkLeverageZap();
3905
+ return [4 /*yield*/, this._leverageCreateLoanBandsAllRanges(userCollateral, userBorrowed, debt)];
3906
+ case 1:
3907
+ _bands = _d.sent();
3908
+ prices = {};
3909
+ N = this.minBands;
3910
+ _d.label = 2;
3911
+ case 2:
3912
+ if (!(N <= this.maxBands)) return [3 /*break*/, 6];
3913
+ if (!_bands[N]) return [3 /*break*/, 4];
3914
+ _a = prices;
3915
+ _c = N;
3916
+ return [4 /*yield*/, this._calcPrices.apply(this, _bands[N])];
3917
+ case 3:
3918
+ _a[_c] = _d.sent();
3919
+ return [3 /*break*/, 5];
3920
+ case 4:
3921
+ prices[N] = null;
3922
+ _d.label = 5;
3923
+ case 5:
3924
+ N++;
3925
+ return [3 /*break*/, 2];
3926
+ case 6: return [2 /*return*/, prices];
3927
+ }
3928
+ });
3929
+ });
3930
+ };
3931
+ LendMarketTemplate.prototype._leverageHealth = function (userCollateral, userBorrowed, dDebt, range, full, user) {
3932
+ if (user === void 0) { user = llamalend.constants.ZERO_ADDRESS; }
3933
+ return __awaiter(this, void 0, void 0, function () {
3934
+ var _totalCollateral, _a, _borrowed, _N, _dDebt, contract, _health;
3935
+ return __generator(this, function (_c) {
3936
+ switch (_c.label) {
3937
+ case 0:
3938
+ if (range > 0)
3939
+ this._checkRange(range);
3940
+ return [4 /*yield*/, this._leverageExpectedCollateral(userCollateral, userBorrowed, dDebt, user)];
3941
+ case 1:
3942
+ _totalCollateral = (_c.sent())._totalCollateral;
3943
+ return [4 /*yield*/, this._userState(user)];
3944
+ case 2:
3945
+ _a = _c.sent(), _borrowed = _a._borrowed, _N = _a._N;
3946
+ if (_borrowed > BigInt(0))
3947
+ throw Error("User ".concat(user, " is already in liquidation mode"));
3948
+ if (range < 0)
3949
+ range = Number(llamalend.formatUnits(_N, 0));
3950
+ _dDebt = parseUnits(dDebt, this.borrowed_token.decimals);
3951
+ contract = llamalend.contracts[this.addresses.controller].contract;
3952
+ return [4 /*yield*/, contract.health_calculator(user, _totalCollateral, _dDebt, full, range, llamalend.constantOptions)];
3953
+ case 3:
3954
+ _health = _c.sent();
3955
+ _health = _health * BigInt(100);
3956
+ return [2 /*return*/, formatUnits(_health)];
3957
+ }
3958
+ });
3959
+ });
3960
+ };
3961
+ LendMarketTemplate.prototype.leverageCreateLoanHealth = function (userCollateral, userBorrowed, debt, range, full) {
3962
+ if (full === void 0) { full = true; }
3963
+ return __awaiter(this, void 0, void 0, function () {
3964
+ return __generator(this, function (_a) {
3965
+ switch (_a.label) {
3966
+ case 0:
3967
+ this._checkLeverageZap();
3968
+ return [4 /*yield*/, this._leverageHealth(userCollateral, userBorrowed, debt, range, full)];
3969
+ case 1: return [2 /*return*/, _a.sent()];
3970
+ }
3971
+ });
3972
+ });
3973
+ };
3974
+ LendMarketTemplate.prototype.leverageCreateLoanIsApproved = function (userCollateral, userBorrowed) {
3975
+ return __awaiter(this, void 0, void 0, function () {
3976
+ var collateralAllowance, borrowedAllowance;
3977
+ return __generator(this, function (_a) {
3978
+ switch (_a.label) {
3979
+ case 0:
3980
+ this._checkLeverageZap();
3981
+ return [4 /*yield*/, hasAllowance([this.collateral_token.address], [userCollateral], llamalend.signerAddress, this.addresses.controller)];
3982
+ case 1:
3983
+ collateralAllowance = _a.sent();
3984
+ return [4 /*yield*/, hasAllowance([this.borrowed_token.address], [userBorrowed], llamalend.signerAddress, llamalend.constants.ALIASES.leverage_zap)];
3985
+ case 2:
3986
+ borrowedAllowance = _a.sent();
3987
+ return [2 /*return*/, collateralAllowance && borrowedAllowance];
3988
+ }
3989
+ });
3990
+ });
3991
+ };
3992
+ LendMarketTemplate.prototype.leverageCreateLoanApproveEstimateGas = function (userCollateral, userBorrowed) {
3993
+ return __awaiter(this, void 0, void 0, function () {
3994
+ var collateralGas, borrowedGas;
3995
+ return __generator(this, function (_a) {
3996
+ switch (_a.label) {
3997
+ case 0:
3998
+ this._checkLeverageZap();
3999
+ return [4 /*yield*/, ensureAllowanceEstimateGas([this.collateral_token.address], [userCollateral], this.addresses.controller)];
4000
+ case 1:
4001
+ collateralGas = _a.sent();
4002
+ return [4 /*yield*/, ensureAllowanceEstimateGas([this.borrowed_token.address], [userBorrowed], llamalend.constants.ALIASES.leverage_zap)];
4003
+ case 2:
4004
+ borrowedGas = _a.sent();
4005
+ if (Array.isArray(collateralGas) && Array.isArray(borrowedGas)) {
4006
+ return [2 /*return*/, [collateralGas[0] + borrowedGas[0], collateralGas[1] + borrowedGas[1]]];
4007
+ }
4008
+ else {
4009
+ return [2 /*return*/, collateralGas + borrowedGas];
4010
+ }
4011
+ return [2 /*return*/];
4012
+ }
4013
+ });
4014
+ });
4015
+ };
4016
+ LendMarketTemplate.prototype.leverageCreateLoanApprove = function (userCollateral, userBorrowed) {
4017
+ return __awaiter(this, void 0, void 0, function () {
4018
+ var collateralApproveTx, borrowedApproveTx;
4019
+ return __generator(this, function (_a) {
4020
+ switch (_a.label) {
4021
+ case 0:
4022
+ this._checkLeverageZap();
4023
+ return [4 /*yield*/, ensureAllowance([this.collateral_token.address], [userCollateral], this.addresses.controller)];
4024
+ case 1:
4025
+ collateralApproveTx = _a.sent();
4026
+ return [4 /*yield*/, ensureAllowance([this.borrowed_token.address], [userBorrowed], llamalend.constants.ALIASES.leverage_zap)];
4027
+ case 2:
4028
+ borrowedApproveTx = _a.sent();
4029
+ return [2 /*return*/, __spreadArray(__spreadArray([], collateralApproveTx, true), borrowedApproveTx, true)];
4030
+ }
4031
+ });
4032
+ });
4033
+ };
4034
+ LendMarketTemplate.prototype.leverageCreateLoanRouteImage = function (userBorrowed, debt) {
4035
+ return __awaiter(this, void 0, void 0, function () {
4036
+ var _userBorrowed, _debt;
4037
+ return __generator(this, function (_a) {
4038
+ this._checkLeverageZap();
4039
+ _userBorrowed = parseUnits(userBorrowed, this.borrowed_token.decimals);
4040
+ _debt = parseUnits(debt, this.borrowed_token.decimals);
4041
+ return [2 /*return*/, this._getSwapDataFromCache(this.addresses.borrowed_token, _debt + _userBorrowed).pathVizImage];
4042
+ });
4043
+ });
4044
+ };
4045
+ LendMarketTemplate.prototype._leverageCreateLoan = function (userCollateral, userBorrowed, debt, range, slippage, estimateGas) {
4046
+ return __awaiter(this, void 0, void 0, function () {
4047
+ var _userCollateral, _userBorrowed, _debt, swapData, calldata, contract, gas, gasLimit;
4048
+ return __generator(this, function (_a) {
4049
+ switch (_a.label) {
4050
+ case 0: return [4 /*yield*/, this.userLoanExists()];
4051
+ case 1:
4052
+ if (_a.sent())
4053
+ throw Error("Loan already created");
4054
+ this._checkRange(range);
4055
+ _userCollateral = parseUnits(userCollateral, this.collateral_token.decimals);
4056
+ _userBorrowed = parseUnits(userBorrowed, this.borrowed_token.decimals);
4057
+ _debt = parseUnits(debt, this.borrowed_token.decimals);
4058
+ swapData = this._getSwapDataFromCache(this.addresses.borrowed_token, _debt + _userBorrowed);
4059
+ if (slippage !== swapData.slippage)
4060
+ throw Error("You must call leverage.createLoanExpectedCollateral() with slippage=".concat(slippage, " first"));
4061
+ return [4 /*yield*/, _assembleTxOdos(swapData.pathId)];
4062
+ case 2:
4063
+ calldata = _a.sent();
4064
+ contract = llamalend.contracts[this.addresses.controller].contract;
4065
+ return [4 /*yield*/, contract.create_loan_extended.estimateGas(_userCollateral, _debt, range, llamalend.constants.ALIASES.leverage_zap, [0, parseUnits(this._getMarketId(), 0), _userBorrowed], calldata, __assign({}, llamalend.constantOptions))];
4066
+ case 3:
4067
+ gas = _a.sent();
4068
+ if (estimateGas)
4069
+ return [2 /*return*/, smartNumber(gas)];
4070
+ return [4 /*yield*/, llamalend.updateFeeData()];
4071
+ case 4:
4072
+ _a.sent();
4073
+ gasLimit = _mulBy1_3(DIGas(gas));
4074
+ return [4 /*yield*/, contract.create_loan_extended(_userCollateral, _debt, range, llamalend.constants.ALIASES.leverage_zap, [0, parseUnits(this._getMarketId(), 0), _userBorrowed], calldata, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
4075
+ case 5: return [2 /*return*/, (_a.sent()).hash];
4076
+ }
4077
+ });
4078
+ });
4079
+ };
4080
+ LendMarketTemplate.prototype.leverageCreateLoanEstimateGas = function (userCollateral, userBorrowed, debt, range, slippage) {
4081
+ if (slippage === void 0) { slippage = 0.1; }
4082
+ return __awaiter(this, void 0, void 0, function () {
4083
+ return __generator(this, function (_a) {
4084
+ switch (_a.label) {
4085
+ case 0:
4086
+ this._checkLeverageZap();
4087
+ return [4 /*yield*/, this.leverageCreateLoanIsApproved(userCollateral, userBorrowed)];
4088
+ case 1:
4089
+ if (!(_a.sent()))
4090
+ throw Error("Approval is needed for gas estimation");
4091
+ return [4 /*yield*/, this._leverageCreateLoan(userCollateral, userBorrowed, debt, range, slippage, true)];
4092
+ case 2: return [2 /*return*/, _a.sent()];
4093
+ }
4094
+ });
4095
+ });
4096
+ };
4097
+ LendMarketTemplate.prototype.leverageCreateLoan = function (userCollateral, userBorrowed, debt, range, slippage) {
4098
+ if (slippage === void 0) { slippage = 0.1; }
4099
+ return __awaiter(this, void 0, void 0, function () {
4100
+ return __generator(this, function (_a) {
4101
+ switch (_a.label) {
4102
+ case 0:
4103
+ this._checkLeverageZap();
4104
+ return [4 /*yield*/, this.leverageCreateLoanApprove(userCollateral, userBorrowed)];
4105
+ case 1:
4106
+ _a.sent();
4107
+ return [4 /*yield*/, this._leverageCreateLoan(userCollateral, userBorrowed, debt, range, slippage, false)];
4108
+ case 2: return [2 /*return*/, _a.sent()];
4109
+ }
4110
+ });
4111
+ });
4112
+ };
4113
+ // ---------------- LEVERAGE BORROW MORE ----------------
4114
+ LendMarketTemplate.prototype.leverageBorrowMoreMaxRecv = function (userCollateral, userBorrowed, address) {
4115
+ if (address === void 0) { address = ""; }
4116
+ return __awaiter(this, void 0, void 0, function () {
4117
+ var _a, _stateCollateral, _stateBorrowed, _stateDebt, _N, _userCollateral, controllerContract, _borrowedFromStateCollateral, _userBorrowed, oraclePriceBand, pAvgBN, _c, maxBorrowablePrevBN, maxBorrowableBN, _userEffectiveCollateral, _maxLeverageCollateral, contract, i, _maxBorrowable_1, _maxAdditionalCollateral, _d, _maxTotalCollateral, _maxBorrowable;
4118
+ return __generator(this, function (_e) {
4119
+ switch (_e.label) {
4120
+ case 0:
4121
+ // max_borrowable = userCollateral / (1 / (k_effective * max_p_base) - 1 / p_avg)
4122
+ this._checkLeverageZap();
4123
+ address = _getAddress(address);
4124
+ return [4 /*yield*/, this._userState(address)];
4125
+ case 1:
4126
+ _a = _e.sent(), _stateCollateral = _a._collateral, _stateBorrowed = _a._borrowed, _stateDebt = _a._debt, _N = _a._N;
4127
+ if (_stateBorrowed > BigInt(0))
4128
+ throw Error("User ".concat(address, " is already in liquidation mode"));
4129
+ _userCollateral = parseUnits(userCollateral, this.collateral_token.decimals);
4130
+ controllerContract = llamalend.contracts[this.addresses.controller].contract;
4131
+ return [4 /*yield*/, controllerContract.max_borrowable(_stateCollateral, _N, _stateDebt, llamalend.constantOptions)];
4132
+ case 2:
4133
+ _borrowedFromStateCollateral = (_e.sent()) - _stateDebt;
4134
+ _userBorrowed = _borrowedFromStateCollateral + parseUnits(userBorrowed, this.borrowed_token.decimals);
4135
+ userBorrowed = formatUnits(_userBorrowed, this.borrowed_token.decimals);
4136
+ return [4 /*yield*/, this.oraclePriceBand()];
4137
+ case 3:
4138
+ oraclePriceBand = _e.sent();
4139
+ _c = BN;
4140
+ return [4 /*yield*/, this.calcTickPrice(oraclePriceBand)];
4141
+ case 4:
4142
+ pAvgBN = _c.apply(void 0, [_e.sent()]);
4143
+ maxBorrowablePrevBN = BN(0);
4144
+ maxBorrowableBN = BN(0);
4145
+ _userEffectiveCollateral = BigInt(0);
4146
+ _maxLeverageCollateral = BigInt(0);
4147
+ contract = llamalend.contracts[llamalend.constants.ALIASES.leverage_zap].contract;
4148
+ i = 0;
4149
+ _e.label = 5;
4150
+ case 5:
4151
+ if (!(i < 5)) return [3 /*break*/, 9];
4152
+ maxBorrowablePrevBN = maxBorrowableBN;
4153
+ _userEffectiveCollateral = _userCollateral + fromBN(BN(userBorrowed).div(pAvgBN), this.collateral_token.decimals);
4154
+ return [4 /*yield*/, contract.max_borrowable(this.addresses.controller, _userEffectiveCollateral, _maxLeverageCollateral, _N, fromBN(pAvgBN))];
4155
+ case 6:
4156
+ _maxBorrowable_1 = _e.sent();
4157
+ _maxBorrowable_1 = _maxBorrowable_1 * BigInt(998) / BigInt(1000);
4158
+ if (_maxBorrowable_1 === BigInt(0))
4159
+ return [3 /*break*/, 9];
4160
+ maxBorrowableBN = toBN(_maxBorrowable_1, this.borrowed_token.decimals);
4161
+ if (maxBorrowableBN.minus(maxBorrowablePrevBN).abs().div(maxBorrowablePrevBN).lt(0.0005)) {
4162
+ maxBorrowableBN = maxBorrowablePrevBN;
4163
+ return [3 /*break*/, 9];
4164
+ }
4165
+ _d = BigInt;
4166
+ return [4 /*yield*/, _getExpectedOdos(this.addresses.borrowed_token, this.addresses.collateral_token, _maxBorrowable_1 + _userBorrowed, this.addresses.amm)];
4167
+ case 7:
4168
+ _maxAdditionalCollateral = _d.apply(void 0, [_e.sent()]);
4169
+ pAvgBN = maxBorrowableBN.plus(userBorrowed).div(toBN(_maxAdditionalCollateral, this.collateral_token.decimals));
4170
+ _maxLeverageCollateral = _maxAdditionalCollateral - fromBN(BN(userBorrowed).div(pAvgBN), this.collateral_token.decimals);
4171
+ _e.label = 8;
4172
+ case 8:
4173
+ i++;
4174
+ return [3 /*break*/, 5];
4175
+ case 9:
4176
+ if (maxBorrowableBN.eq(0))
4177
+ _userEffectiveCollateral = BigInt(0);
4178
+ _maxTotalCollateral = _userEffectiveCollateral + _maxLeverageCollateral;
4179
+ return [4 /*yield*/, controllerContract.max_borrowable(_stateCollateral + _maxTotalCollateral, _N, _stateDebt, llamalend.constantOptions)];
4180
+ case 10:
4181
+ _maxBorrowable = (_e.sent()) - _stateDebt;
4182
+ _maxBorrowable = _maxBorrowable * BigInt(998) / BigInt(1000);
4183
+ return [2 /*return*/, {
4184
+ maxDebt: formatUnits(_maxBorrowable, this.borrowed_token.decimals),
4185
+ maxTotalCollateral: formatUnits(_maxTotalCollateral, this.collateral_token.decimals),
4186
+ userCollateral: formatNumber(userCollateral, this.collateral_token.decimals),
4187
+ collateralFromUserBorrowed: formatNumber(BN(userBorrowed).div(pAvgBN).toString(), this.collateral_token.decimals),
4188
+ collateralFromMaxDebt: formatUnits(_maxLeverageCollateral, this.collateral_token.decimals),
4189
+ avgPrice: pAvgBN.toString(),
4190
+ }];
4191
+ }
4192
+ });
4193
+ });
4194
+ };
4195
+ LendMarketTemplate.prototype.leverageBorrowMoreExpectedCollateral = function (userCollateral, userBorrowed, dDebt, slippage, address) {
4196
+ if (slippage === void 0) { slippage = 0.1; }
4197
+ if (address === void 0) { address = ""; }
4198
+ return __awaiter(this, void 0, void 0, function () {
4199
+ var _dDebt, _userBorrowed, _a, _totalCollateral, _userCollateral, _collateralFromUserBorrowed, _collateralFromDebt, avgPrice;
4200
+ return __generator(this, function (_c) {
4201
+ switch (_c.label) {
4202
+ case 0:
4203
+ this._checkLeverageZap();
4204
+ address = _getAddress(address);
4205
+ _dDebt = parseUnits(dDebt, this.borrowed_token.decimals);
4206
+ _userBorrowed = parseUnits(userBorrowed, this.borrowed_token.decimals);
4207
+ return [4 /*yield*/, this._setSwapDataToCache(this.addresses.borrowed_token, this.addresses.collateral_token, _dDebt + _userBorrowed, slippage)];
4208
+ case 1:
4209
+ _c.sent();
4210
+ return [4 /*yield*/, this._leverageExpectedCollateral(userCollateral, userBorrowed, dDebt, address)];
4211
+ case 2:
4212
+ _a = _c.sent(), _totalCollateral = _a._totalCollateral, _userCollateral = _a._userCollateral, _collateralFromUserBorrowed = _a._collateralFromUserBorrowed, _collateralFromDebt = _a._collateralFromDebt, avgPrice = _a.avgPrice;
4213
+ return [2 /*return*/, {
4214
+ totalCollateral: formatUnits(_totalCollateral, this.collateral_token.decimals),
4215
+ userCollateral: formatUnits(_userCollateral, this.collateral_token.decimals),
4216
+ collateralFromUserBorrowed: formatUnits(_collateralFromUserBorrowed, this.collateral_token.decimals),
4217
+ collateralFromDebt: formatUnits(_collateralFromDebt, this.collateral_token.decimals),
4218
+ avgPrice: avgPrice,
4219
+ }];
4220
+ }
4221
+ });
4222
+ });
4223
+ };
4224
+ LendMarketTemplate.prototype.leverageBorrowMorePriceImpact = function (userBorrowed, dDebt) {
4225
+ return __awaiter(this, void 0, void 0, function () {
4226
+ var _dDebt, _userBorrowed;
4227
+ return __generator(this, function (_a) {
4228
+ this._checkLeverageZap();
4229
+ _dDebt = parseUnits(dDebt, this.borrowed_token.decimals);
4230
+ _userBorrowed = parseUnits(userBorrowed, this.borrowed_token.decimals);
4231
+ return [2 /*return*/, this._getSwapDataFromCache(this.addresses.borrowed_token, _dDebt + _userBorrowed).priceImpact.toString()];
4232
+ });
4233
+ });
4234
+ };
4235
+ LendMarketTemplate.prototype.leverageBorrowMoreBands = function (userCollateral, userBorrowed, dDebt, address) {
4236
+ if (address === void 0) { address = ""; }
4237
+ return __awaiter(this, void 0, void 0, function () {
4238
+ var _a, _n2, _n1;
4239
+ return __generator(this, function (_c) {
4240
+ switch (_c.label) {
4241
+ case 0:
4242
+ address = _getAddress(address);
4243
+ this._checkLeverageZap();
4244
+ return [4 /*yield*/, this._leverageBands(userCollateral, userBorrowed, dDebt, -1, address)];
4245
+ case 1:
4246
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
4247
+ return [2 /*return*/, [Number(_n2), Number(_n1)]];
4248
+ }
4249
+ });
4250
+ });
4251
+ };
4252
+ LendMarketTemplate.prototype.leverageBorrowMorePrices = function (userCollateral, userBorrowed, dDebt, address) {
4253
+ if (address === void 0) { address = ""; }
4254
+ return __awaiter(this, void 0, void 0, function () {
4255
+ var _a, _n2, _n1;
4256
+ return __generator(this, function (_c) {
4257
+ switch (_c.label) {
4258
+ case 0:
4259
+ address = _getAddress(address);
4260
+ this._checkLeverageZap();
4261
+ return [4 /*yield*/, this._leverageBands(userCollateral, userBorrowed, dDebt, -1, address)];
4262
+ case 1:
4263
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
4264
+ return [4 /*yield*/, this._getPrices(_n2, _n1)];
4265
+ case 2: return [2 /*return*/, _c.sent()];
4266
+ }
4267
+ });
4268
+ });
4269
+ };
4270
+ LendMarketTemplate.prototype.leverageBorrowMoreHealth = function (userCollateral, userBorrowed, dDebt, full, address) {
4271
+ if (full === void 0) { full = true; }
4272
+ if (address === void 0) { address = ""; }
4273
+ return __awaiter(this, void 0, void 0, function () {
4274
+ return __generator(this, function (_a) {
4275
+ switch (_a.label) {
4276
+ case 0:
4277
+ this._checkLeverageZap();
4278
+ address = _getAddress(address);
4279
+ return [4 /*yield*/, this._leverageHealth(userCollateral, userBorrowed, dDebt, -1, full, address)];
4280
+ case 1: return [2 /*return*/, _a.sent()];
4281
+ }
4282
+ });
4283
+ });
4284
+ };
4285
+ LendMarketTemplate.prototype.leverageBorrowMoreRouteImage = function (userBorrowed, debt) {
4286
+ return __awaiter(this, void 0, void 0, function () {
4287
+ var _userBorrowed, _debt;
4288
+ return __generator(this, function (_a) {
4289
+ this._checkLeverageZap();
4290
+ _userBorrowed = parseUnits(userBorrowed, this.borrowed_token.decimals);
4291
+ _debt = parseUnits(debt, this.borrowed_token.decimals);
4292
+ return [2 /*return*/, this._getSwapDataFromCache(this.addresses.borrowed_token, _debt + _userBorrowed).pathVizImage];
4293
+ });
4294
+ });
4295
+ };
4296
+ LendMarketTemplate.prototype._leverageBorrowMore = function (userCollateral, userBorrowed, debt, slippage, estimateGas) {
4297
+ return __awaiter(this, void 0, void 0, function () {
4298
+ var _userCollateral, _userBorrowed, _debt, swapData, calldata, contract, gas, gasLimit;
4299
+ return __generator(this, function (_a) {
4300
+ switch (_a.label) {
4301
+ case 0: return [4 /*yield*/, this.userLoanExists()];
4302
+ case 1:
4303
+ if (!(_a.sent()))
4304
+ throw Error("Loan does not exist");
4305
+ _userCollateral = parseUnits(userCollateral, this.collateral_token.decimals);
4306
+ _userBorrowed = parseUnits(userBorrowed, this.borrowed_token.decimals);
4307
+ _debt = parseUnits(debt, this.borrowed_token.decimals);
4308
+ swapData = this._getSwapDataFromCache(this.addresses.borrowed_token, _debt + _userBorrowed);
4309
+ if (slippage !== swapData.slippage)
4310
+ throw Error("You must call leverage.borrowMoreExpectedCollateral() with slippage=".concat(slippage, " first"));
4311
+ return [4 /*yield*/, _assembleTxOdos(swapData.pathId)];
4312
+ case 2:
4313
+ calldata = _a.sent();
4314
+ contract = llamalend.contracts[this.addresses.controller].contract;
4315
+ return [4 /*yield*/, contract.borrow_more_extended.estimateGas(_userCollateral, _debt, llamalend.constants.ALIASES.leverage_zap, [0, parseUnits(this._getMarketId(), 0), _userBorrowed], calldata, __assign({}, llamalend.constantOptions))];
4316
+ case 3:
4317
+ gas = _a.sent();
4318
+ if (estimateGas)
4319
+ return [2 /*return*/, smartNumber(gas)];
4320
+ return [4 /*yield*/, llamalend.updateFeeData()];
4321
+ case 4:
4322
+ _a.sent();
4323
+ gasLimit = _mulBy1_3(DIGas(gas));
4324
+ return [4 /*yield*/, contract.borrow_more_extended(_userCollateral, _debt, llamalend.constants.ALIASES.leverage_zap, [0, parseUnits(this._getMarketId(), 0), _userBorrowed], calldata, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
4325
+ case 5: return [2 /*return*/, (_a.sent()).hash];
4326
+ }
4327
+ });
4328
+ });
4329
+ };
4330
+ LendMarketTemplate.prototype.leverageBorrowMoreEstimateGas = function (userCollateral, userBorrowed, debt, slippage) {
4331
+ if (slippage === void 0) { slippage = 0.1; }
4332
+ return __awaiter(this, void 0, void 0, function () {
4333
+ return __generator(this, function (_a) {
4334
+ switch (_a.label) {
4335
+ case 0:
4336
+ this._checkLeverageZap();
4337
+ return [4 /*yield*/, this.leverageCreateLoanIsApproved(userCollateral, userBorrowed)];
4338
+ case 1:
4339
+ if (!(_a.sent()))
4340
+ throw Error("Approval is needed for gas estimation");
4341
+ return [4 /*yield*/, this._leverageBorrowMore(userCollateral, userBorrowed, debt, slippage, true)];
4342
+ case 2: return [2 /*return*/, _a.sent()];
4343
+ }
4344
+ });
4345
+ });
4346
+ };
4347
+ LendMarketTemplate.prototype.leverageBorrowMore = function (userCollateral, userBorrowed, debt, slippage) {
4348
+ if (slippage === void 0) { slippage = 0.1; }
4349
+ return __awaiter(this, void 0, void 0, function () {
4350
+ return __generator(this, function (_a) {
4351
+ switch (_a.label) {
4352
+ case 0:
4353
+ this._checkLeverageZap();
4354
+ return [4 /*yield*/, this.leverageCreateLoanApprove(userCollateral, userBorrowed)];
4355
+ case 1:
4356
+ _a.sent();
4357
+ return [4 /*yield*/, this._leverageBorrowMore(userCollateral, userBorrowed, debt, slippage, false)];
4358
+ case 2: return [2 /*return*/, _a.sent()];
4359
+ }
4360
+ });
4361
+ });
4362
+ };
4363
+ LendMarketTemplate.prototype.leverageRepayPriceImpact = function (stateCollateral, userCollateral) {
4364
+ return __awaiter(this, void 0, void 0, function () {
4365
+ var _stateCollateral, _userCollateral;
4366
+ return __generator(this, function (_a) {
4367
+ this._checkLeverageZap();
4368
+ _stateCollateral = parseUnits(stateCollateral, this.collateral_token.decimals);
4369
+ _userCollateral = parseUnits(userCollateral, this.collateral_token.decimals);
4370
+ if (_stateCollateral + _userCollateral > BigInt(0)) {
4371
+ return [2 /*return*/, this._getSwapDataFromCache(this.addresses.collateral_token, _stateCollateral + _userCollateral).priceImpact.toString()];
4372
+ }
4373
+ else {
4374
+ return [2 /*return*/, "0.0"];
4375
+ }
4376
+ return [2 /*return*/];
4377
+ });
4378
+ });
4379
+ };
4380
+ LendMarketTemplate.prototype.leverageRepayIsFull = function (stateCollateral, userCollateral, userBorrowed, address) {
4381
+ if (address === void 0) { address = ""; }
4382
+ return __awaiter(this, void 0, void 0, function () {
4383
+ var _a, _stateBorrowed, _debt, _totalBorrowed;
4384
+ return __generator(this, function (_c) {
4385
+ switch (_c.label) {
4386
+ case 0:
4387
+ this._checkLeverageZap();
4388
+ address = _getAddress(address);
4389
+ return [4 /*yield*/, this._userState(address)];
4390
+ case 1:
4391
+ _a = _c.sent(), _stateBorrowed = _a._borrowed, _debt = _a._debt;
4392
+ _totalBorrowed = this._leverageRepayExpectedBorrowed(stateCollateral, userCollateral, userBorrowed)._totalBorrowed;
4393
+ return [2 /*return*/, _stateBorrowed + _totalBorrowed > _debt];
4394
+ }
4395
+ });
4396
+ });
4397
+ };
4398
+ LendMarketTemplate.prototype.leverageRepayIsAvailable = function (stateCollateral, userCollateral, userBorrowed, address) {
4399
+ if (address === void 0) { address = ""; }
4400
+ return __awaiter(this, void 0, void 0, function () {
4401
+ var _a, collateral, borrowed, debt;
4402
+ return __generator(this, function (_c) {
4403
+ switch (_c.label) {
4404
+ case 0:
4405
+ // 0. const { collateral, stablecoin, debt } = await this.userState(address);
4406
+ // 1. maxCollateral for deleverage is collateral from line above.
4407
+ // 2. If user is underwater (stablecoin > 0), only full repayment is available:
4408
+ // await this.deleverageRepayStablecoins(deleverageCollateral) + stablecoin > debt
4409
+ this._checkLeverageZap();
4410
+ address = _getAddress(address);
4411
+ return [4 /*yield*/, this.userState(address)];
4412
+ case 1:
4413
+ _a = _c.sent(), collateral = _a.collateral, borrowed = _a.borrowed, debt = _a.debt;
4414
+ // Loan does not exist
4415
+ if (BN(debt).eq(0))
4416
+ return [2 /*return*/, false];
4417
+ // Can't spend more than user has
4418
+ if (BN(stateCollateral).gt(collateral))
4419
+ return [2 /*return*/, false];
4420
+ if (!BN(borrowed).gt(0)) return [3 /*break*/, 3];
4421
+ return [4 /*yield*/, this.leverageRepayIsFull(stateCollateral, userCollateral, userBorrowed, address)];
4422
+ case 2: return [2 /*return*/, _c.sent()];
4423
+ case 3: return [2 /*return*/, true];
4424
+ }
4425
+ });
4426
+ });
4427
+ };
4428
+ LendMarketTemplate.prototype.leverageRepayBands = function (stateCollateral, userCollateral, userBorrowed, address) {
4429
+ if (address === void 0) { address = ""; }
4430
+ return __awaiter(this, void 0, void 0, function () {
4431
+ var _a, _n2, _n1;
4432
+ return __generator(this, function (_c) {
4433
+ switch (_c.label) {
4434
+ case 0:
4435
+ this._checkLeverageZap();
4436
+ return [4 /*yield*/, this._leverageRepayBands(stateCollateral, userCollateral, userBorrowed, address)];
4437
+ case 1:
4438
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
4439
+ return [2 /*return*/, [Number(_n2), Number(_n1)]];
4440
+ }
4441
+ });
4442
+ });
4443
+ };
4444
+ LendMarketTemplate.prototype.leverageRepayPrices = function (stateCollateral, userCollateral, userBorrowed, address) {
4445
+ if (address === void 0) { address = ""; }
4446
+ return __awaiter(this, void 0, void 0, function () {
4447
+ var _a, _n2, _n1;
4448
+ return __generator(this, function (_c) {
4449
+ switch (_c.label) {
4450
+ case 0:
4451
+ this._checkLeverageZap();
4452
+ return [4 /*yield*/, this._leverageRepayBands(stateCollateral, userCollateral, userBorrowed, address)];
4453
+ case 1:
4454
+ _a = _c.sent(), _n2 = _a[0], _n1 = _a[1];
4455
+ return [4 /*yield*/, this._getPrices(_n2, _n1)];
4456
+ case 2: return [2 /*return*/, _c.sent()];
4457
+ }
4458
+ });
4459
+ });
4460
+ };
4461
+ LendMarketTemplate.prototype.leverageRepayHealth = function (stateCollateral, userCollateral, userBorrowed, full, address) {
4462
+ if (full === void 0) { full = true; }
4463
+ if (address === void 0) { address = ""; }
4464
+ return __awaiter(this, void 0, void 0, function () {
4465
+ var _a, _stateBorrowed, _debt, _N, _totalBorrowed, _dCollateral, _dDebt, contract, _health;
4466
+ return __generator(this, function (_c) {
4467
+ switch (_c.label) {
4468
+ case 0:
4469
+ this._checkLeverageZap();
4470
+ address = _getAddress(address);
4471
+ return [4 /*yield*/, this._userState(address)];
4472
+ case 1:
4473
+ _a = _c.sent(), _stateBorrowed = _a._borrowed, _debt = _a._debt, _N = _a._N;
4474
+ if (_stateBorrowed > BigInt(0))
4475
+ return [2 /*return*/, "0.0"];
4476
+ return [4 /*yield*/, this.leverageRepayIsAvailable(stateCollateral, userCollateral, userBorrowed, address)];
4477
+ case 2:
4478
+ if (!(_c.sent()))
4479
+ return [2 /*return*/, "0.0"];
4480
+ _totalBorrowed = this._leverageRepayExpectedBorrowed(stateCollateral, userCollateral, userBorrowed)._totalBorrowed;
4481
+ _dCollateral = parseUnits(stateCollateral, this.collateral_token.decimals) * BigInt(-1);
4482
+ _dDebt = _totalBorrowed * BigInt(-1);
4483
+ if (_debt + _dDebt <= BigInt(0))
4484
+ return [2 /*return*/, "0.0"];
4485
+ contract = llamalend.contracts[this.addresses.controller].contract;
4486
+ return [4 /*yield*/, contract.health_calculator(address, _dCollateral, _dDebt, full, _N, llamalend.constantOptions)];
4487
+ case 3:
4488
+ _health = _c.sent();
4489
+ _health = _health * BigInt(100);
4490
+ return [2 /*return*/, llamalend.formatUnits(_health)];
4491
+ }
4492
+ });
4493
+ });
4494
+ };
4495
+ LendMarketTemplate.prototype.leverageRepayIsApproved = function (userCollateral, userBorrowed) {
4496
+ return __awaiter(this, void 0, void 0, function () {
4497
+ return __generator(this, function (_a) {
4498
+ switch (_a.label) {
4499
+ case 0:
4500
+ this._checkLeverageZap();
4501
+ return [4 /*yield*/, hasAllowance([this.collateral_token.address, this.borrowed_token.address], [userCollateral, userBorrowed], llamalend.signerAddress, llamalend.constants.ALIASES.leverage_zap)];
4502
+ case 1: return [2 /*return*/, _a.sent()];
4503
+ }
4504
+ });
4505
+ });
4506
+ };
4507
+ LendMarketTemplate.prototype.leverageRepayApproveEstimateGas = function (userCollateral, userBorrowed) {
4508
+ return __awaiter(this, void 0, void 0, function () {
4509
+ return __generator(this, function (_a) {
4510
+ switch (_a.label) {
4511
+ case 0:
4512
+ this._checkLeverageZap();
4513
+ return [4 /*yield*/, ensureAllowanceEstimateGas([this.collateral_token.address, this.borrowed_token.address], [userCollateral, userBorrowed], llamalend.constants.ALIASES.leverage_zap)];
4514
+ case 1: return [2 /*return*/, _a.sent()];
4515
+ }
4516
+ });
4517
+ });
4518
+ };
4519
+ LendMarketTemplate.prototype.leverageRepayApprove = function (userCollateral, userBorrowed) {
4520
+ return __awaiter(this, void 0, void 0, function () {
4521
+ return __generator(this, function (_a) {
4522
+ switch (_a.label) {
4523
+ case 0:
4524
+ this._checkLeverageZap();
4525
+ return [4 /*yield*/, ensureAllowance([this.collateral_token.address, this.borrowed_token.address], [userCollateral, userBorrowed], llamalend.constants.ALIASES.leverage_zap)];
4526
+ case 1: return [2 /*return*/, _a.sent()];
4527
+ }
4528
+ });
4529
+ });
4530
+ };
4531
+ LendMarketTemplate.prototype.leverageRepayRouteImage = function (stateCollateral, userCollateral) {
4532
+ return __awaiter(this, void 0, void 0, function () {
4533
+ var _stateCollateral, _userCollateral;
4534
+ return __generator(this, function (_a) {
4535
+ this._checkLeverageZap();
4536
+ _stateCollateral = parseUnits(stateCollateral, this.collateral_token.decimals);
4537
+ _userCollateral = parseUnits(userCollateral, this.collateral_token.decimals);
4538
+ return [2 /*return*/, this._getSwapDataFromCache(this.addresses.collateral_token, _stateCollateral + _userCollateral).pathVizImage];
4539
+ });
4540
+ });
4541
+ };
4542
+ LendMarketTemplate.prototype._leverageRepay = function (stateCollateral, userCollateral, userBorrowed, slippage, estimateGas) {
4543
+ return __awaiter(this, void 0, void 0, function () {
4544
+ var _stateCollateral, _userCollateral, _userBorrowed, calldata, swapData, contract, gas, gasLimit;
4545
+ return __generator(this, function (_a) {
4546
+ switch (_a.label) {
4547
+ case 0: return [4 /*yield*/, this.userLoanExists()];
4548
+ case 1:
4549
+ if (!(_a.sent()))
4550
+ throw Error("Loan does not exist");
4551
+ _stateCollateral = parseUnits(stateCollateral, this.collateral_token.decimals);
4552
+ _userCollateral = parseUnits(userCollateral, this.collateral_token.decimals);
4553
+ _userBorrowed = parseUnits(userBorrowed, this.borrowed_token.decimals);
4554
+ calldata = "0x";
4555
+ if (!(_stateCollateral + _userCollateral > BigInt(0))) return [3 /*break*/, 3];
4556
+ swapData = this._getSwapDataFromCache(this.addresses.collateral_token, _stateCollateral + _userCollateral);
4557
+ if (slippage !== swapData.slippage)
4558
+ throw Error("You must call leverage.repayExpectedBorrowed() with slippage=".concat(slippage, " first"));
4559
+ return [4 /*yield*/, _assembleTxOdos(swapData.pathId)];
4560
+ case 2:
4561
+ calldata = _a.sent();
4562
+ _a.label = 3;
4563
+ case 3:
4564
+ console.log('params', [0, parseUnits(this._getMarketId(), 0), _userCollateral, _userBorrowed], calldata);
4565
+ contract = llamalend.contracts[this.addresses.controller].contract;
4566
+ return [4 /*yield*/, contract.repay_extended.estimateGas(llamalend.constants.ALIASES.leverage_zap, [0, parseUnits(this._getMarketId(), 0), _userCollateral, _userBorrowed], calldata)];
4567
+ case 4:
4568
+ gas = _a.sent();
4569
+ if (estimateGas)
4570
+ return [2 /*return*/, smartNumber(gas)];
4571
+ return [4 /*yield*/, llamalend.updateFeeData()];
4572
+ case 5:
4573
+ _a.sent();
4574
+ gasLimit = _mulBy1_3(DIGas(gas));
4575
+ return [4 /*yield*/, contract.repay_extended(llamalend.constants.ALIASES.leverage_zap, [0, parseUnits(this._getMarketId(), 0), _userCollateral, _userBorrowed], calldata, __assign(__assign({}, llamalend.options), { gasLimit: gasLimit }))];
4576
+ case 6: return [2 /*return*/, (_a.sent()).hash];
4577
+ }
4578
+ });
4579
+ });
4580
+ };
4581
+ LendMarketTemplate.prototype.leverageRepayEstimateGas = function (stateCollateral, userCollateral, userBorrowed, slippage) {
4582
+ if (slippage === void 0) { slippage = 0.1; }
4583
+ return __awaiter(this, void 0, void 0, function () {
4584
+ return __generator(this, function (_a) {
4585
+ switch (_a.label) {
4586
+ case 0:
4587
+ this._checkLeverageZap();
4588
+ return [4 /*yield*/, this.leverageRepayIsApproved(userCollateral, userBorrowed)];
4589
+ case 1:
4590
+ if (!(_a.sent()))
4591
+ throw Error("Approval is needed for gas estimation");
4592
+ return [4 /*yield*/, this._leverageRepay(stateCollateral, userCollateral, userBorrowed, slippage, true)];
4593
+ case 2: return [2 /*return*/, _a.sent()];
4594
+ }
4595
+ });
4596
+ });
4597
+ };
4598
+ LendMarketTemplate.prototype.leverageRepay = function (stateCollateral, userCollateral, userBorrowed, slippage) {
4599
+ if (slippage === void 0) { slippage = 0.1; }
4600
+ return __awaiter(this, void 0, void 0, function () {
4601
+ return __generator(this, function (_a) {
4602
+ switch (_a.label) {
4603
+ case 0:
4604
+ this._checkLeverageZap();
4605
+ return [4 /*yield*/, this.leverageRepayApprove(userCollateral, userBorrowed)];
4606
+ case 1:
4607
+ _a.sent();
4608
+ return [4 /*yield*/, this._leverageRepay(stateCollateral, userCollateral, userBorrowed, slippage, false)];
4609
+ case 2: return [2 /*return*/, _a.sent()];
4610
+ }
4611
+ });
4612
+ });
4613
+ };
4614
+ LendMarketTemplate.prototype.currentLeverage = function (userAddress) {
4615
+ if (userAddress === void 0) { userAddress = ''; }
4616
+ return __awaiter(this, void 0, void 0, function () {
4617
+ var _a, userCollateral, _current_collateral_estimation, total_deposit_from_user, current_collateral_estimation;
4618
+ return __generator(this, function (_c) {
4619
+ switch (_c.label) {
4620
+ case 0:
4621
+ userAddress = _getAddress(userAddress);
4622
+ return [4 /*yield*/, Promise.all([
4623
+ _getUserCollateral(llamalend.constants.NETWORK_NAME, this.addresses.controller, userAddress),
4624
+ llamalend.contracts[this.addresses.amm].contract.get_y_up(userAddress),
4625
+ ])];
4626
+ case 1:
4627
+ _a = _c.sent(), userCollateral = _a[0], _current_collateral_estimation = _a[1];
4628
+ total_deposit_from_user = userCollateral.total_deposit_from_user;
4629
+ current_collateral_estimation = llamalend.formatUnits(_current_collateral_estimation, this.collateral_token.decimals);
4630
+ return [2 /*return*/, BN(current_collateral_estimation).div(total_deposit_from_user).toString()];
4631
+ }
4632
+ });
4633
+ });
4634
+ };
4635
+ LendMarketTemplate.prototype.currentPnL = function (userAddress) {
4636
+ if (userAddress === void 0) { userAddress = ''; }
4637
+ return __awaiter(this, void 0, void 0, function () {
4638
+ var calls, _a, currentCollateralEstimation, userState, oraclePrice, debt, userCollateral, totalDepositUsdValue, currentCollateralEstimationFormatted, oraclePriceFormatted, debtFormatted, currentPosition, percentage;
4639
+ return __generator(this, function (_c) {
4640
+ switch (_c.label) {
4641
+ case 0:
4642
+ userAddress = _getAddress(userAddress);
4643
+ calls = [
4644
+ llamalend.contracts[this.addresses.amm].multicallContract.get_y_up(userAddress),
4645
+ llamalend.contracts[this.addresses.controller].multicallContract.user_state(userAddress, llamalend.constantOptions),
4646
+ llamalend.contracts[this.addresses.amm].multicallContract.price_oracle(userAddress),
4647
+ ];
4648
+ return [4 /*yield*/, llamalend.multicallProvider.all(calls)];
4649
+ case 1:
4650
+ _a = _c.sent(), currentCollateralEstimation = _a[0], userState = _a[1], oraclePrice = _a[2];
4651
+ if (!(currentCollateralEstimation || userState || oraclePrice)) {
4652
+ throw new Error('Multicall error');
4653
+ }
4654
+ debt = userState[2];
4655
+ return [4 /*yield*/, _getUserCollateral(llamalend.constants.NETWORK_NAME, this.addresses.controller, userAddress)];
4656
+ case 2:
4657
+ userCollateral = _c.sent();
4658
+ totalDepositUsdValue = userCollateral.total_deposit_usd_value;
4659
+ currentCollateralEstimationFormatted = llamalend.formatUnits(currentCollateralEstimation, this.collateral_token.decimals);
4660
+ oraclePriceFormatted = llamalend.formatUnits(oraclePrice, 18);
4661
+ debtFormatted = llamalend.formatUnits(debt, 18);
4662
+ currentPosition = BN(currentCollateralEstimationFormatted)
4663
+ .times(oraclePriceFormatted)
4664
+ .minus(debtFormatted)
4665
+ .toFixed(this.collateral_token.decimals);
4666
+ percentage = BN(currentPosition)
4667
+ .div(totalDepositUsdValue)
4668
+ .minus(1)
4669
+ .times(100)
4670
+ .toString();
4671
+ return [2 /*return*/, {
4672
+ currentPosition: currentPosition,
4673
+ deposited: totalDepositUsdValue.toString(),
4674
+ percentage: percentage,
4675
+ }];
4676
+ }
4677
+ });
4678
+ });
4679
+ };
4680
+ return LendMarketTemplate;
4681
+ }());
4682
+ export { LendMarketTemplate };