@gearbox-protocol/sdk 3.0.0-vfour.3 → 3.0.0-vfour.4

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.
@@ -1,266 +1,16 @@
1
1
  'use strict';
2
2
 
3
- var sdkGov = require('@gearbox-protocol/sdk-gov');
4
3
  var viem = require('viem');
4
+ var sdkGov = require('@gearbox-protocol/sdk-gov');
5
5
  var utils = require('viem/utils');
6
+ var actions = require('viem/actions');
6
7
  var chains$1 = require('viem/chains');
7
8
  var eventemitter3 = require('eventemitter3');
8
9
  var evmConnector = require('@redstone-finance/evm-connector');
9
10
  var redstoneProtocol = require('redstone-protocol');
10
11
  var aura = require('@gearbox-protocol/sdk-gov/lib/tokens/aura');
11
12
 
12
- // src/base/AddressLabeller.ts
13
-
14
- // src/constants/addresses.ts
15
- var ADDRESS_0X0 = "0x0000000000000000000000000000000000000000";
16
- var NOT_DEPLOYED = "0xNOT DEPLOYED";
17
-
18
- // src/constants/address-provider.ts
19
- var NO_VERSION = 0;
20
- var AP_ACL = "ACL";
21
- var AP_CONTRACTS_REGISTER = "CONTRACTS_REGISTER";
22
- var AP_PRICE_ORACLE = "PRICE_ORACLE";
23
- var AP_ACCOUNT_FACTORY = "ACCOUNT_FACTORY";
24
- var AP_DATA_COMPRESSOR = "DATA_COMPRESSOR";
25
- var AP_MARKET_COMPRESSOR = "MARKET_COMPRESSOR";
26
- var AP_CREDIT_ACCOUNT_COMPRESSOR = "CREDIT_ACCOUNT_COMPRESSOR";
27
- var AP_TREASURY = "TREASURY";
28
- var AP_GEAR_TOKEN = "GEAR_TOKEN";
29
- var AP_WETH_TOKEN = "WETH_TOKEN";
30
- var AP_WETH_GATEWAY = "WETH_GATEWAY";
31
- var AP_ROUTER = "ROUTER";
32
- var AP_BOT_LIST = "BOT_LIST";
33
- var AP_GEAR_STAKING = "GEAR_STAKING";
34
- var AP_ZAPPER_REGISTER = "ZAPPER_REGISTER";
35
- var AP_CONTROLLER_TIMELOCK = "CONTROLLER_TIMELOCK";
36
- var AP_DEGEN_NFT = "DEGEN_NFT";
37
- var AP_ZERO_PRICE_FEED = "ZERO_PRICE_FEED";
38
- var AP_DEGEN_DISTRIBUTOR = "DEGEN_DISTRIBUTOR";
39
- var AP_MULTI_PAUSE = "MULTI_PAUSE";
40
- var AP_INFLATION_ATTACK_BLOCKER = "INFLATION_ATTACK_BLOCKER";
41
- var AP_INSOLVENCY_CHECKER = "INSOLVENCY_CHECKER";
42
- var AP_PARTIAL_LIQUIDATION_BOT = "PARTIAL_LIQUIDATION_BOT";
43
- var AP_DELEVERAGE_BOT_PEGGED = "DELEVERAGE_BOT_PEGGED";
44
- var AP_DELEVERAGE_BOT_LV = "DELEVERAGE_BOT_LV";
45
- var AP_DELEVERAGE_BOT_HV = "DELEVERAGE_BOT_HV";
46
- var ADDRESS_PROVIDER = {
47
- Mainnet: "0x9ea7b04Da02a5373317D745c1571c84aaD03321D",
48
- Arbitrum: "0x7d04eCdb892Ae074f03B5D0aBA03796F90F3F2af",
49
- Optimism: "0x3761ca4BFAcFCFFc1B8034e69F19116dD6756726",
50
- Base: NOT_DEPLOYED
51
- };
52
- var AddressMap = class {
53
- #map;
54
- #frozen = false;
55
- constructor(entries) {
56
- this.#map = /* @__PURE__ */ new Map();
57
- if (entries) {
58
- for (const [address, value] of entries) {
59
- const key = address.toLowerCase();
60
- if (!viem.isAddress(key)) {
61
- throw new Error(`value "${address}" is not an address`);
62
- }
63
- this.#map.set(key, value);
64
- }
65
- }
66
- }
67
- /**
68
- * Adds or updates value
69
- * @param address
70
- * @param value
71
- */
72
- upsert(address, value) {
73
- if (this.#frozen) {
74
- throw new Error(`AddressMap is frozen`);
75
- }
76
- const key = address.toLowerCase();
77
- if (!viem.isAddress(key)) {
78
- throw new Error(`value "${address}" is not an address`);
79
- }
80
- this.#map.set(key, value);
81
- }
82
- /**
83
- * Adds value, throws if this address is already used
84
- * @param address
85
- * @param value
86
- */
87
- insert(address, value) {
88
- if (this.#frozen) {
89
- throw new Error(`AddressMap is frozen`);
90
- }
91
- const key = address.toLowerCase();
92
- if (!viem.isAddress(key)) {
93
- throw new Error(`value "${address}" is not an address`);
94
- }
95
- if (this.#map.has(key)) {
96
- throw new Error(`address ${address} already exists`);
97
- }
98
- this.#map.set(key, value);
99
- }
100
- /**
101
- * Checks if address is present in map
102
- * @param address
103
- * @returns
104
- */
105
- has(address) {
106
- const key = address.toLowerCase();
107
- if (!viem.isAddress(key)) {
108
- throw new Error(`value "${address}" is not an address`);
109
- }
110
- return this.#map.has(key);
111
- }
112
- /**
113
- * Returns value, or undefined if the address is not in map
114
- * @param address
115
- * @returns
116
- */
117
- get(address) {
118
- const key = address.toLowerCase();
119
- if (!viem.isAddress(key)) {
120
- throw new Error(`value "${address}" is not an address`);
121
- }
122
- return this.#map.get(key);
123
- }
124
- /**
125
- * Gets address from map, throws if not found
126
- * @param address
127
- * @returns
128
- */
129
- mustGet(address) {
130
- const v = this.get(address);
131
- if (!v) {
132
- throw new Error(`address ${address} not found in map`);
133
- }
134
- return v;
135
- }
136
- entries() {
137
- return this.#map.entries();
138
- }
139
- values() {
140
- return this.#map.values();
141
- }
142
- asRecord() {
143
- return Object.fromEntries(this.#map.entries());
144
- }
145
- freeze() {
146
- this.#frozen = true;
147
- }
148
- };
149
- function bytes32ToString(bytes) {
150
- return viem.bytesToString(viem.toBytes(bytes)).replaceAll("\0", "");
151
- }
152
-
153
- // src/utils/childLogger.ts
154
- function childLogger(module, logger) {
155
- return logger?.child?.({ module }) ?? logger;
156
- }
157
-
158
- // src/utils/json.ts
159
- function replacer(_key, value) {
160
- if (typeof value === "bigint") {
161
- return {
162
- __type: "bigint",
163
- __value: value.toString()
164
- };
165
- } else {
166
- return value;
167
- }
168
- }
169
- function reviver(_key, value) {
170
- if (value && value.__type === "bigint") {
171
- return BigInt(value.__value);
172
- }
173
- return value;
174
- }
175
- var json_stringify = (obj, space = 2) => {
176
- return JSON.stringify(obj, replacer, space);
177
- };
178
- var json_parse = (s) => {
179
- return JSON.parse(s, reviver);
180
- };
181
-
182
- // src/utils/createRawTx.ts
183
- function createRawTx(to, parameters, description) {
184
- const { args } = parameters;
185
- const fname = parameters.functionName;
186
- const { abi: abi2, functionName } = (() => {
187
- if (parameters.abi.length === 1 && parameters.functionName?.startsWith("0x"))
188
- return parameters;
189
- return viem.prepareEncodeFunctionData(parameters);
190
- })();
191
- const abiItem = abi2[0];
192
- const signature = functionName;
193
- const data = "inputs" in abiItem && abiItem.inputs ? viem.encodeAbiParameters(abiItem.inputs, args ?? []) : void 0;
194
- const functionEncodedData = viem.concatHex([signature, data ?? "0x"]);
195
- const inputs = "inputs" in abiItem && abiItem.inputs ? [...abiItem.inputs] : [];
196
- const payable = "payble" in abiItem ? abiItem.payble === true : false;
197
- const contractInputsValues = {};
198
- if (inputs.length > 0 && args && args.length !== 0) {
199
- args.forEach((arg, i) => {
200
- const methodName = inputs[i].name;
201
- let stringifiedArg = arg instanceof BigInt ? arg.toString() : arg;
202
- contractInputsValues[methodName] = Array.isArray(stringifiedArg) ? json_stringify(stringifiedArg) : stringifiedArg;
203
- });
204
- }
205
- return {
206
- to,
207
- value: "0",
208
- contractMethod: {
209
- inputs,
210
- name: fname,
211
- payable
212
- },
213
- signature: utils.formatAbiItem(abiItem),
214
- callData: functionEncodedData,
215
- contractInputsValues,
216
- description
217
- };
218
- }
219
-
220
- // src/base/AddressLabeller.ts
221
- var AddressLabeller = class {
222
- #labels = new AddressMap();
223
- set(address, label) {
224
- if (address === NOT_DEPLOYED) {
225
- return;
226
- }
227
- if (typeof label === "string") {
228
- this.#labels.upsert(address, label);
229
- } else {
230
- this.#labels.upsert(address, label(this.#labels.get(address)));
231
- }
232
- }
233
- get(address) {
234
- const label = this.#labels.get(address);
235
- return label ? `${address} [${label}]` : address;
236
- }
237
- get all() {
238
- return this.#labels.asRecord();
239
- }
240
- };
241
- function initLegacyLabels(labeller, network) {
242
- Object.entries(sdkGov.tokenDataByNetwork[network]).forEach(([label, address]) => {
243
- labeller.set(address, label);
244
- });
245
- Object.entries(sdkGov.tickerTokensByNetwork[network]).forEach(([label, address]) => {
246
- labeller.set(address, label);
247
- });
248
- Object.entries(sdkGov.contractsByNetwork[network]).forEach(([label, address]) => {
249
- labeller.set(address, label);
250
- });
251
- const multisigs = [
252
- { safe: sdkGov.MULTISIG, label: "Multisig" },
253
- { safe: sdkGov.ROUTER_MULTISIG_ADDRESS, label: "RouterMultisig" },
254
- { safe: sdkGov.VETO_ADMIN, label: "VetoAdmin" },
255
- { safe: sdkGov.TREASURY, label: "Treasury" }
256
- ];
257
- multisigs.forEach(({ safe, label }) => {
258
- labeller.set(safe[network], label);
259
- });
260
- sdkGov.emergencyLiquidators.forEach((address) => {
261
- labeller.set(address, "EmergencyLiquidator");
262
- });
263
- }
13
+ // src/accounts/CreditAccountsService.ts
264
14
 
265
15
  // src/abi/compressors.ts
266
16
  var iAddressProviderV3_1Abi = [
@@ -423,9 +173,438 @@ var iAddressProviderV3_1Abi = [
423
173
  { name: "addr", internalType: "address", type: "address" },
424
174
  { name: "saveVersion", internalType: "bool", type: "bool" }
425
175
  ],
426
- name: "setAddress",
427
- outputs: [],
428
- stateMutability: "nonpayable"
176
+ name: "setAddress",
177
+ outputs: [],
178
+ stateMutability: "nonpayable"
179
+ },
180
+ {
181
+ type: "function",
182
+ inputs: [],
183
+ name: "version",
184
+ outputs: [{ name: "", internalType: "uint256", type: "uint256" }],
185
+ stateMutability: "view"
186
+ },
187
+ {
188
+ type: "event",
189
+ anonymous: false,
190
+ inputs: [
191
+ {
192
+ name: "marketConfigurator",
193
+ internalType: "address",
194
+ type: "address",
195
+ indexed: true
196
+ }
197
+ ],
198
+ name: "AddMarketConfigurator"
199
+ },
200
+ {
201
+ type: "event",
202
+ anonymous: false,
203
+ inputs: [
204
+ {
205
+ name: "marketConfigurator",
206
+ internalType: "address",
207
+ type: "address",
208
+ indexed: true
209
+ }
210
+ ],
211
+ name: "RemoveMarketConfigurator"
212
+ },
213
+ {
214
+ type: "event",
215
+ anonymous: false,
216
+ inputs: [
217
+ { name: "key", internalType: "string", type: "string", indexed: false },
218
+ {
219
+ name: "value",
220
+ internalType: "address",
221
+ type: "address",
222
+ indexed: true
223
+ },
224
+ {
225
+ name: "version",
226
+ internalType: "uint256",
227
+ type: "uint256",
228
+ indexed: false
229
+ }
230
+ ],
231
+ name: "SetAddress"
232
+ }
233
+ ];
234
+ var iCreditAccountCompressorAbi = [
235
+ {
236
+ type: "function",
237
+ inputs: [],
238
+ name: "contractType",
239
+ outputs: [{ name: "", internalType: "bytes32", type: "bytes32" }],
240
+ stateMutability: "view"
241
+ },
242
+ {
243
+ type: "function",
244
+ inputs: [
245
+ { name: "creditManager", internalType: "address", type: "address" },
246
+ {
247
+ name: "caFilter",
248
+ internalType: "struct CreditAccountFilter",
249
+ type: "tuple",
250
+ components: [
251
+ { name: "owner", internalType: "address", type: "address" },
252
+ { name: "includeZeroDebt", internalType: "bool", type: "bool" },
253
+ { name: "minHealthFactor", internalType: "uint16", type: "uint16" },
254
+ { name: "maxHealthFactor", internalType: "uint16", type: "uint16" },
255
+ { name: "reverting", internalType: "bool", type: "bool" }
256
+ ]
257
+ }
258
+ ],
259
+ name: "countCreditAccounts",
260
+ outputs: [{ name: "", internalType: "uint256", type: "uint256" }],
261
+ stateMutability: "view"
262
+ },
263
+ {
264
+ type: "function",
265
+ inputs: [
266
+ {
267
+ name: "cmFilter",
268
+ internalType: "struct MarketFilter",
269
+ type: "tuple",
270
+ components: [
271
+ { name: "curators", internalType: "address[]", type: "address[]" },
272
+ { name: "pools", internalType: "address[]", type: "address[]" },
273
+ { name: "underlying", internalType: "address", type: "address" }
274
+ ]
275
+ },
276
+ {
277
+ name: "caFilter",
278
+ internalType: "struct CreditAccountFilter",
279
+ type: "tuple",
280
+ components: [
281
+ { name: "owner", internalType: "address", type: "address" },
282
+ { name: "includeZeroDebt", internalType: "bool", type: "bool" },
283
+ { name: "minHealthFactor", internalType: "uint16", type: "uint16" },
284
+ { name: "maxHealthFactor", internalType: "uint16", type: "uint16" },
285
+ { name: "reverting", internalType: "bool", type: "bool" }
286
+ ]
287
+ }
288
+ ],
289
+ name: "countCreditAccounts",
290
+ outputs: [{ name: "", internalType: "uint256", type: "uint256" }],
291
+ stateMutability: "view"
292
+ },
293
+ {
294
+ type: "function",
295
+ inputs: [
296
+ { name: "creditAccount", internalType: "address", type: "address" }
297
+ ],
298
+ name: "getCreditAccountData",
299
+ outputs: [
300
+ {
301
+ name: "",
302
+ internalType: "struct CreditAccountData",
303
+ type: "tuple",
304
+ components: [
305
+ { name: "creditAccount", internalType: "address", type: "address" },
306
+ { name: "creditManager", internalType: "address", type: "address" },
307
+ { name: "creditFacade", internalType: "address", type: "address" },
308
+ { name: "underlying", internalType: "address", type: "address" },
309
+ { name: "owner", internalType: "address", type: "address" },
310
+ {
311
+ name: "enabledTokensMask",
312
+ internalType: "uint256",
313
+ type: "uint256"
314
+ },
315
+ { name: "debt", internalType: "uint256", type: "uint256" },
316
+ { name: "accruedInterest", internalType: "uint256", type: "uint256" },
317
+ { name: "accruedFees", internalType: "uint256", type: "uint256" },
318
+ { name: "totalDebtUSD", internalType: "uint256", type: "uint256" },
319
+ { name: "totalValueUSD", internalType: "uint256", type: "uint256" },
320
+ { name: "twvUSD", internalType: "uint256", type: "uint256" },
321
+ { name: "totalValue", internalType: "uint256", type: "uint256" },
322
+ { name: "healthFactor", internalType: "uint16", type: "uint16" },
323
+ { name: "success", internalType: "bool", type: "bool" },
324
+ {
325
+ name: "tokens",
326
+ internalType: "struct TokenInfo[]",
327
+ type: "tuple[]",
328
+ components: [
329
+ { name: "token", internalType: "address", type: "address" },
330
+ { name: "mask", internalType: "uint256", type: "uint256" },
331
+ { name: "balance", internalType: "uint256", type: "uint256" },
332
+ { name: "quota", internalType: "uint256", type: "uint256" },
333
+ { name: "success", internalType: "bool", type: "bool" }
334
+ ]
335
+ }
336
+ ]
337
+ }
338
+ ],
339
+ stateMutability: "view"
340
+ },
341
+ {
342
+ type: "function",
343
+ inputs: [
344
+ {
345
+ name: "cmFilter",
346
+ internalType: "struct MarketFilter",
347
+ type: "tuple",
348
+ components: [
349
+ { name: "curators", internalType: "address[]", type: "address[]" },
350
+ { name: "pools", internalType: "address[]", type: "address[]" },
351
+ { name: "underlying", internalType: "address", type: "address" }
352
+ ]
353
+ },
354
+ {
355
+ name: "caFilter",
356
+ internalType: "struct CreditAccountFilter",
357
+ type: "tuple",
358
+ components: [
359
+ { name: "owner", internalType: "address", type: "address" },
360
+ { name: "includeZeroDebt", internalType: "bool", type: "bool" },
361
+ { name: "minHealthFactor", internalType: "uint16", type: "uint16" },
362
+ { name: "maxHealthFactor", internalType: "uint16", type: "uint16" },
363
+ { name: "reverting", internalType: "bool", type: "bool" }
364
+ ]
365
+ },
366
+ { name: "offset", internalType: "uint256", type: "uint256" }
367
+ ],
368
+ name: "getCreditAccounts",
369
+ outputs: [
370
+ {
371
+ name: "data",
372
+ internalType: "struct CreditAccountData[]",
373
+ type: "tuple[]",
374
+ components: [
375
+ { name: "creditAccount", internalType: "address", type: "address" },
376
+ { name: "creditManager", internalType: "address", type: "address" },
377
+ { name: "creditFacade", internalType: "address", type: "address" },
378
+ { name: "underlying", internalType: "address", type: "address" },
379
+ { name: "owner", internalType: "address", type: "address" },
380
+ {
381
+ name: "enabledTokensMask",
382
+ internalType: "uint256",
383
+ type: "uint256"
384
+ },
385
+ { name: "debt", internalType: "uint256", type: "uint256" },
386
+ { name: "accruedInterest", internalType: "uint256", type: "uint256" },
387
+ { name: "accruedFees", internalType: "uint256", type: "uint256" },
388
+ { name: "totalDebtUSD", internalType: "uint256", type: "uint256" },
389
+ { name: "totalValueUSD", internalType: "uint256", type: "uint256" },
390
+ { name: "twvUSD", internalType: "uint256", type: "uint256" },
391
+ { name: "totalValue", internalType: "uint256", type: "uint256" },
392
+ { name: "healthFactor", internalType: "uint16", type: "uint16" },
393
+ { name: "success", internalType: "bool", type: "bool" },
394
+ {
395
+ name: "tokens",
396
+ internalType: "struct TokenInfo[]",
397
+ type: "tuple[]",
398
+ components: [
399
+ { name: "token", internalType: "address", type: "address" },
400
+ { name: "mask", internalType: "uint256", type: "uint256" },
401
+ { name: "balance", internalType: "uint256", type: "uint256" },
402
+ { name: "quota", internalType: "uint256", type: "uint256" },
403
+ { name: "success", internalType: "bool", type: "bool" }
404
+ ]
405
+ }
406
+ ]
407
+ },
408
+ { name: "nextOffset", internalType: "uint256", type: "uint256" }
409
+ ],
410
+ stateMutability: "view"
411
+ },
412
+ {
413
+ type: "function",
414
+ inputs: [
415
+ { name: "creditManager", internalType: "address", type: "address" },
416
+ {
417
+ name: "caFilter",
418
+ internalType: "struct CreditAccountFilter",
419
+ type: "tuple",
420
+ components: [
421
+ { name: "owner", internalType: "address", type: "address" },
422
+ { name: "includeZeroDebt", internalType: "bool", type: "bool" },
423
+ { name: "minHealthFactor", internalType: "uint16", type: "uint16" },
424
+ { name: "maxHealthFactor", internalType: "uint16", type: "uint16" },
425
+ { name: "reverting", internalType: "bool", type: "bool" }
426
+ ]
427
+ },
428
+ { name: "offset", internalType: "uint256", type: "uint256" }
429
+ ],
430
+ name: "getCreditAccounts",
431
+ outputs: [
432
+ {
433
+ name: "data",
434
+ internalType: "struct CreditAccountData[]",
435
+ type: "tuple[]",
436
+ components: [
437
+ { name: "creditAccount", internalType: "address", type: "address" },
438
+ { name: "creditManager", internalType: "address", type: "address" },
439
+ { name: "creditFacade", internalType: "address", type: "address" },
440
+ { name: "underlying", internalType: "address", type: "address" },
441
+ { name: "owner", internalType: "address", type: "address" },
442
+ {
443
+ name: "enabledTokensMask",
444
+ internalType: "uint256",
445
+ type: "uint256"
446
+ },
447
+ { name: "debt", internalType: "uint256", type: "uint256" },
448
+ { name: "accruedInterest", internalType: "uint256", type: "uint256" },
449
+ { name: "accruedFees", internalType: "uint256", type: "uint256" },
450
+ { name: "totalDebtUSD", internalType: "uint256", type: "uint256" },
451
+ { name: "totalValueUSD", internalType: "uint256", type: "uint256" },
452
+ { name: "twvUSD", internalType: "uint256", type: "uint256" },
453
+ { name: "totalValue", internalType: "uint256", type: "uint256" },
454
+ { name: "healthFactor", internalType: "uint16", type: "uint16" },
455
+ { name: "success", internalType: "bool", type: "bool" },
456
+ {
457
+ name: "tokens",
458
+ internalType: "struct TokenInfo[]",
459
+ type: "tuple[]",
460
+ components: [
461
+ { name: "token", internalType: "address", type: "address" },
462
+ { name: "mask", internalType: "uint256", type: "uint256" },
463
+ { name: "balance", internalType: "uint256", type: "uint256" },
464
+ { name: "quota", internalType: "uint256", type: "uint256" },
465
+ { name: "success", internalType: "bool", type: "bool" }
466
+ ]
467
+ }
468
+ ]
469
+ },
470
+ { name: "nextOffset", internalType: "uint256", type: "uint256" }
471
+ ],
472
+ stateMutability: "view"
473
+ },
474
+ {
475
+ type: "function",
476
+ inputs: [
477
+ { name: "creditManager", internalType: "address", type: "address" },
478
+ {
479
+ name: "caFilter",
480
+ internalType: "struct CreditAccountFilter",
481
+ type: "tuple",
482
+ components: [
483
+ { name: "owner", internalType: "address", type: "address" },
484
+ { name: "includeZeroDebt", internalType: "bool", type: "bool" },
485
+ { name: "minHealthFactor", internalType: "uint16", type: "uint16" },
486
+ { name: "maxHealthFactor", internalType: "uint16", type: "uint16" },
487
+ { name: "reverting", internalType: "bool", type: "bool" }
488
+ ]
489
+ },
490
+ { name: "offset", internalType: "uint256", type: "uint256" },
491
+ { name: "limit", internalType: "uint256", type: "uint256" }
492
+ ],
493
+ name: "getCreditAccounts",
494
+ outputs: [
495
+ {
496
+ name: "data",
497
+ internalType: "struct CreditAccountData[]",
498
+ type: "tuple[]",
499
+ components: [
500
+ { name: "creditAccount", internalType: "address", type: "address" },
501
+ { name: "creditManager", internalType: "address", type: "address" },
502
+ { name: "creditFacade", internalType: "address", type: "address" },
503
+ { name: "underlying", internalType: "address", type: "address" },
504
+ { name: "owner", internalType: "address", type: "address" },
505
+ {
506
+ name: "enabledTokensMask",
507
+ internalType: "uint256",
508
+ type: "uint256"
509
+ },
510
+ { name: "debt", internalType: "uint256", type: "uint256" },
511
+ { name: "accruedInterest", internalType: "uint256", type: "uint256" },
512
+ { name: "accruedFees", internalType: "uint256", type: "uint256" },
513
+ { name: "totalDebtUSD", internalType: "uint256", type: "uint256" },
514
+ { name: "totalValueUSD", internalType: "uint256", type: "uint256" },
515
+ { name: "twvUSD", internalType: "uint256", type: "uint256" },
516
+ { name: "totalValue", internalType: "uint256", type: "uint256" },
517
+ { name: "healthFactor", internalType: "uint16", type: "uint16" },
518
+ { name: "success", internalType: "bool", type: "bool" },
519
+ {
520
+ name: "tokens",
521
+ internalType: "struct TokenInfo[]",
522
+ type: "tuple[]",
523
+ components: [
524
+ { name: "token", internalType: "address", type: "address" },
525
+ { name: "mask", internalType: "uint256", type: "uint256" },
526
+ { name: "balance", internalType: "uint256", type: "uint256" },
527
+ { name: "quota", internalType: "uint256", type: "uint256" },
528
+ { name: "success", internalType: "bool", type: "bool" }
529
+ ]
530
+ }
531
+ ]
532
+ },
533
+ { name: "nextOffset", internalType: "uint256", type: "uint256" }
534
+ ],
535
+ stateMutability: "view"
536
+ },
537
+ {
538
+ type: "function",
539
+ inputs: [
540
+ {
541
+ name: "cmFilter",
542
+ internalType: "struct MarketFilter",
543
+ type: "tuple",
544
+ components: [
545
+ { name: "curators", internalType: "address[]", type: "address[]" },
546
+ { name: "pools", internalType: "address[]", type: "address[]" },
547
+ { name: "underlying", internalType: "address", type: "address" }
548
+ ]
549
+ },
550
+ {
551
+ name: "caFilter",
552
+ internalType: "struct CreditAccountFilter",
553
+ type: "tuple",
554
+ components: [
555
+ { name: "owner", internalType: "address", type: "address" },
556
+ { name: "includeZeroDebt", internalType: "bool", type: "bool" },
557
+ { name: "minHealthFactor", internalType: "uint16", type: "uint16" },
558
+ { name: "maxHealthFactor", internalType: "uint16", type: "uint16" },
559
+ { name: "reverting", internalType: "bool", type: "bool" }
560
+ ]
561
+ },
562
+ { name: "offset", internalType: "uint256", type: "uint256" },
563
+ { name: "limit", internalType: "uint256", type: "uint256" }
564
+ ],
565
+ name: "getCreditAccounts",
566
+ outputs: [
567
+ {
568
+ name: "data",
569
+ internalType: "struct CreditAccountData[]",
570
+ type: "tuple[]",
571
+ components: [
572
+ { name: "creditAccount", internalType: "address", type: "address" },
573
+ { name: "creditManager", internalType: "address", type: "address" },
574
+ { name: "creditFacade", internalType: "address", type: "address" },
575
+ { name: "underlying", internalType: "address", type: "address" },
576
+ { name: "owner", internalType: "address", type: "address" },
577
+ {
578
+ name: "enabledTokensMask",
579
+ internalType: "uint256",
580
+ type: "uint256"
581
+ },
582
+ { name: "debt", internalType: "uint256", type: "uint256" },
583
+ { name: "accruedInterest", internalType: "uint256", type: "uint256" },
584
+ { name: "accruedFees", internalType: "uint256", type: "uint256" },
585
+ { name: "totalDebtUSD", internalType: "uint256", type: "uint256" },
586
+ { name: "totalValueUSD", internalType: "uint256", type: "uint256" },
587
+ { name: "twvUSD", internalType: "uint256", type: "uint256" },
588
+ { name: "totalValue", internalType: "uint256", type: "uint256" },
589
+ { name: "healthFactor", internalType: "uint16", type: "uint16" },
590
+ { name: "success", internalType: "bool", type: "bool" },
591
+ {
592
+ name: "tokens",
593
+ internalType: "struct TokenInfo[]",
594
+ type: "tuple[]",
595
+ components: [
596
+ { name: "token", internalType: "address", type: "address" },
597
+ { name: "mask", internalType: "uint256", type: "uint256" },
598
+ { name: "balance", internalType: "uint256", type: "uint256" },
599
+ { name: "quota", internalType: "uint256", type: "uint256" },
600
+ { name: "success", internalType: "bool", type: "bool" }
601
+ ]
602
+ }
603
+ ]
604
+ },
605
+ { name: "nextOffset", internalType: "uint256", type: "uint256" }
606
+ ],
607
+ stateMutability: "view"
429
608
  },
430
609
  {
431
610
  type: "function",
@@ -433,52 +612,6 @@ var iAddressProviderV3_1Abi = [
433
612
  name: "version",
434
613
  outputs: [{ name: "", internalType: "uint256", type: "uint256" }],
435
614
  stateMutability: "view"
436
- },
437
- {
438
- type: "event",
439
- anonymous: false,
440
- inputs: [
441
- {
442
- name: "marketConfigurator",
443
- internalType: "address",
444
- type: "address",
445
- indexed: true
446
- }
447
- ],
448
- name: "AddMarketConfigurator"
449
- },
450
- {
451
- type: "event",
452
- anonymous: false,
453
- inputs: [
454
- {
455
- name: "marketConfigurator",
456
- internalType: "address",
457
- type: "address",
458
- indexed: true
459
- }
460
- ],
461
- name: "RemoveMarketConfigurator"
462
- },
463
- {
464
- type: "event",
465
- anonymous: false,
466
- inputs: [
467
- { name: "key", internalType: "string", type: "string", indexed: false },
468
- {
469
- name: "value",
470
- internalType: "address",
471
- type: "address",
472
- indexed: true
473
- },
474
- {
475
- name: "version",
476
- internalType: "uint256",
477
- type: "uint256",
478
- indexed: false
479
- }
480
- ],
481
- name: "SetAddress"
482
615
  }
483
616
  ];
484
617
  var iMarketCompressorAbi = [
@@ -12275,7 +12408,262 @@ var routerV3Abi = [
12275
12408
  inputs: [{ name: "", internalType: "address", type: "address" }],
12276
12409
  name: "UnsupportedRouterComponent"
12277
12410
  }
12278
- ];
12411
+ ];
12412
+
12413
+ // src/constants/addresses.ts
12414
+ var ADDRESS_0X0 = "0x0000000000000000000000000000000000000000";
12415
+ var NOT_DEPLOYED = "0xNOT DEPLOYED";
12416
+
12417
+ // src/constants/address-provider.ts
12418
+ var NO_VERSION = 0;
12419
+ var AP_ACL = "ACL";
12420
+ var AP_CONTRACTS_REGISTER = "CONTRACTS_REGISTER";
12421
+ var AP_PRICE_ORACLE = "PRICE_ORACLE";
12422
+ var AP_ACCOUNT_FACTORY = "ACCOUNT_FACTORY";
12423
+ var AP_DATA_COMPRESSOR = "DATA_COMPRESSOR";
12424
+ var AP_MARKET_COMPRESSOR = "MARKET_COMPRESSOR";
12425
+ var AP_CREDIT_ACCOUNT_COMPRESSOR = "CREDIT_ACCOUNT_COMPRESSOR";
12426
+ var AP_TREASURY = "TREASURY";
12427
+ var AP_GEAR_TOKEN = "GEAR_TOKEN";
12428
+ var AP_WETH_TOKEN = "WETH_TOKEN";
12429
+ var AP_WETH_GATEWAY = "WETH_GATEWAY";
12430
+ var AP_ROUTER = "ROUTER";
12431
+ var AP_BOT_LIST = "BOT_LIST";
12432
+ var AP_GEAR_STAKING = "GEAR_STAKING";
12433
+ var AP_ZAPPER_REGISTER = "ZAPPER_REGISTER";
12434
+ var AP_CONTROLLER_TIMELOCK = "CONTROLLER_TIMELOCK";
12435
+ var AP_DEGEN_NFT = "DEGEN_NFT";
12436
+ var AP_ZERO_PRICE_FEED = "ZERO_PRICE_FEED";
12437
+ var AP_DEGEN_DISTRIBUTOR = "DEGEN_DISTRIBUTOR";
12438
+ var AP_MULTI_PAUSE = "MULTI_PAUSE";
12439
+ var AP_INFLATION_ATTACK_BLOCKER = "INFLATION_ATTACK_BLOCKER";
12440
+ var AP_INSOLVENCY_CHECKER = "INSOLVENCY_CHECKER";
12441
+ var AP_PARTIAL_LIQUIDATION_BOT = "PARTIAL_LIQUIDATION_BOT";
12442
+ var AP_DELEVERAGE_BOT_PEGGED = "DELEVERAGE_BOT_PEGGED";
12443
+ var AP_DELEVERAGE_BOT_LV = "DELEVERAGE_BOT_LV";
12444
+ var AP_DELEVERAGE_BOT_HV = "DELEVERAGE_BOT_HV";
12445
+ var ADDRESS_PROVIDER = {
12446
+ Mainnet: "0x9ea7b04Da02a5373317D745c1571c84aaD03321D",
12447
+ Arbitrum: "0x7d04eCdb892Ae074f03B5D0aBA03796F90F3F2af",
12448
+ Optimism: "0x3761ca4BFAcFCFFc1B8034e69F19116dD6756726",
12449
+ Base: NOT_DEPLOYED
12450
+ };
12451
+
12452
+ // src/constants/math.ts
12453
+ var MIN_INT96 = -39614081257132168796771975168n;
12454
+ var MAX_UINT256 = 115792089237316195423570985008687907853269984665640564039457584007913129639935n;
12455
+ var AddressMap = class {
12456
+ #map;
12457
+ #frozen = false;
12458
+ constructor(entries) {
12459
+ this.#map = /* @__PURE__ */ new Map();
12460
+ if (entries) {
12461
+ for (const [address, value] of entries) {
12462
+ const key = address.toLowerCase();
12463
+ if (!viem.isAddress(key)) {
12464
+ throw new Error(`value "${address}" is not an address`);
12465
+ }
12466
+ this.#map.set(key, value);
12467
+ }
12468
+ }
12469
+ }
12470
+ /**
12471
+ * Adds or updates value
12472
+ * @param address
12473
+ * @param value
12474
+ */
12475
+ upsert(address, value) {
12476
+ if (this.#frozen) {
12477
+ throw new Error(`AddressMap is frozen`);
12478
+ }
12479
+ const key = address.toLowerCase();
12480
+ if (!viem.isAddress(key)) {
12481
+ throw new Error(`value "${address}" is not an address`);
12482
+ }
12483
+ this.#map.set(key, value);
12484
+ }
12485
+ /**
12486
+ * Adds value, throws if this address is already used
12487
+ * @param address
12488
+ * @param value
12489
+ */
12490
+ insert(address, value) {
12491
+ if (this.#frozen) {
12492
+ throw new Error(`AddressMap is frozen`);
12493
+ }
12494
+ const key = address.toLowerCase();
12495
+ if (!viem.isAddress(key)) {
12496
+ throw new Error(`value "${address}" is not an address`);
12497
+ }
12498
+ if (this.#map.has(key)) {
12499
+ throw new Error(`address ${address} already exists`);
12500
+ }
12501
+ this.#map.set(key, value);
12502
+ }
12503
+ /**
12504
+ * Checks if address is present in map
12505
+ * @param address
12506
+ * @returns
12507
+ */
12508
+ has(address) {
12509
+ const key = address.toLowerCase();
12510
+ if (!viem.isAddress(key)) {
12511
+ throw new Error(`value "${address}" is not an address`);
12512
+ }
12513
+ return this.#map.has(key);
12514
+ }
12515
+ /**
12516
+ * Returns value, or undefined if the address is not in map
12517
+ * @param address
12518
+ * @returns
12519
+ */
12520
+ get(address) {
12521
+ const key = address.toLowerCase();
12522
+ if (!viem.isAddress(key)) {
12523
+ throw new Error(`value "${address}" is not an address`);
12524
+ }
12525
+ return this.#map.get(key);
12526
+ }
12527
+ /**
12528
+ * Gets address from map, throws if not found
12529
+ * @param address
12530
+ * @returns
12531
+ */
12532
+ mustGet(address) {
12533
+ const v = this.get(address);
12534
+ if (!v) {
12535
+ throw new Error(`address ${address} not found in map`);
12536
+ }
12537
+ return v;
12538
+ }
12539
+ entries() {
12540
+ return this.#map.entries();
12541
+ }
12542
+ values() {
12543
+ return this.#map.values();
12544
+ }
12545
+ asRecord() {
12546
+ return Object.fromEntries(this.#map.entries());
12547
+ }
12548
+ freeze() {
12549
+ this.#frozen = true;
12550
+ }
12551
+ };
12552
+ function bytes32ToString(bytes) {
12553
+ return viem.bytesToString(viem.toBytes(bytes)).replaceAll("\0", "");
12554
+ }
12555
+
12556
+ // src/utils/childLogger.ts
12557
+ function childLogger(module, logger) {
12558
+ return logger?.child?.({ module }) ?? logger;
12559
+ }
12560
+
12561
+ // src/utils/json.ts
12562
+ function replacer(_key, value) {
12563
+ if (typeof value === "bigint") {
12564
+ return {
12565
+ __type: "bigint",
12566
+ __value: value.toString()
12567
+ };
12568
+ } else {
12569
+ return value;
12570
+ }
12571
+ }
12572
+ function reviver(_key, value) {
12573
+ if (value && value.__type === "bigint") {
12574
+ return BigInt(value.__value);
12575
+ }
12576
+ return value;
12577
+ }
12578
+ var json_stringify = (obj, space = 2) => {
12579
+ return JSON.stringify(obj, replacer, space);
12580
+ };
12581
+ var json_parse = (s) => {
12582
+ return JSON.parse(s, reviver);
12583
+ };
12584
+
12585
+ // src/utils/createRawTx.ts
12586
+ function createRawTx(to, parameters, description) {
12587
+ const { args } = parameters;
12588
+ const fname = parameters.functionName;
12589
+ const { abi: abi2, functionName } = (() => {
12590
+ if (parameters.abi.length === 1 && parameters.functionName?.startsWith("0x"))
12591
+ return parameters;
12592
+ return viem.prepareEncodeFunctionData(parameters);
12593
+ })();
12594
+ const abiItem = abi2[0];
12595
+ const signature = functionName;
12596
+ const data = "inputs" in abiItem && abiItem.inputs ? viem.encodeAbiParameters(abiItem.inputs, args ?? []) : void 0;
12597
+ const functionEncodedData = viem.concatHex([signature, data ?? "0x"]);
12598
+ const inputs = "inputs" in abiItem && abiItem.inputs ? [...abiItem.inputs] : [];
12599
+ const payable = "payble" in abiItem ? abiItem.payble === true : false;
12600
+ const contractInputsValues = {};
12601
+ if (inputs.length > 0 && args && args.length !== 0) {
12602
+ args.forEach((arg, i) => {
12603
+ const methodName = inputs[i].name;
12604
+ let stringifiedArg = arg instanceof BigInt ? arg.toString() : arg;
12605
+ contractInputsValues[methodName] = Array.isArray(stringifiedArg) ? json_stringify(stringifiedArg) : stringifiedArg;
12606
+ });
12607
+ }
12608
+ return {
12609
+ to,
12610
+ value: "0",
12611
+ contractMethod: {
12612
+ inputs,
12613
+ name: fname,
12614
+ payable
12615
+ },
12616
+ signature: utils.formatAbiItem(abiItem),
12617
+ callData: functionEncodedData,
12618
+ contractInputsValues,
12619
+ description
12620
+ };
12621
+ }
12622
+
12623
+ // src/base/AddressLabeller.ts
12624
+ var AddressLabeller = class {
12625
+ #labels = new AddressMap();
12626
+ set(address, label) {
12627
+ if (address === NOT_DEPLOYED) {
12628
+ return;
12629
+ }
12630
+ if (typeof label === "string") {
12631
+ this.#labels.upsert(address, label);
12632
+ } else {
12633
+ this.#labels.upsert(address, label(this.#labels.get(address)));
12634
+ }
12635
+ }
12636
+ get(address) {
12637
+ const label = this.#labels.get(address);
12638
+ return label ? `${address} [${label}]` : address;
12639
+ }
12640
+ get all() {
12641
+ return this.#labels.asRecord();
12642
+ }
12643
+ };
12644
+ function initLegacyLabels(labeller, network) {
12645
+ Object.entries(sdkGov.tokenDataByNetwork[network]).forEach(([label, address]) => {
12646
+ labeller.set(address, label);
12647
+ });
12648
+ Object.entries(sdkGov.tickerTokensByNetwork[network]).forEach(([label, address]) => {
12649
+ labeller.set(address, label);
12650
+ });
12651
+ Object.entries(sdkGov.contractsByNetwork[network]).forEach(([label, address]) => {
12652
+ labeller.set(address, label);
12653
+ });
12654
+ const multisigs = [
12655
+ { safe: sdkGov.MULTISIG, label: "Multisig" },
12656
+ { safe: sdkGov.ROUTER_MULTISIG_ADDRESS, label: "RouterMultisig" },
12657
+ { safe: sdkGov.VETO_ADMIN, label: "VetoAdmin" },
12658
+ { safe: sdkGov.TREASURY, label: "Treasury" }
12659
+ ];
12660
+ multisigs.forEach(({ safe, label }) => {
12661
+ labeller.set(safe[network], label);
12662
+ });
12663
+ sdkGov.emergencyLiquidators.forEach((address) => {
12664
+ labeller.set(address, "EmergencyLiquidator");
12665
+ });
12666
+ }
12279
12667
 
12280
12668
  // src/base/SDKConstruct.ts
12281
12669
  var SDKConstruct = class {
@@ -12425,6 +12813,502 @@ var VotingContractStatus = /* @__PURE__ */ ((VotingContractStatus2) => {
12425
12813
  VotingContractStatus2[VotingContractStatus2["UNVOTE_ONLY"] = 2] = "UNVOTE_ONLY";
12426
12814
  return VotingContractStatus2;
12427
12815
  })(VotingContractStatus || {});
12816
+ async function detectNetwork(client) {
12817
+ for (const chain of sdkGov.supportedChains) {
12818
+ try {
12819
+ await client.readContract({
12820
+ abi: ierc20MetadataAbi,
12821
+ address: sdkGov.tokenDataByNetwork[chain].USDC,
12822
+ functionName: "symbol"
12823
+ });
12824
+ return chain;
12825
+ } catch {
12826
+ }
12827
+ }
12828
+ throw new Error("Unsupported network");
12829
+ }
12830
+
12831
+ // src/utils/viem/createAnvilClient.ts
12832
+ function createAnvilClient({
12833
+ chain,
12834
+ transport
12835
+ }) {
12836
+ return viem.createTestClient(
12837
+ {
12838
+ chain,
12839
+ mode: "anvil",
12840
+ transport,
12841
+ cacheTime: 0
12842
+ }
12843
+ ).extend(viem.publicActions).extend(viem.walletActions).extend((client) => ({
12844
+ isAnvil: () => isAnvil(client),
12845
+ detectNetwork: () => detectNetwork(client)
12846
+ }));
12847
+ }
12848
+ async function isAnvil(client) {
12849
+ try {
12850
+ const resp = await client.request({
12851
+ method: "anvil_nodeInfo",
12852
+ params: []
12853
+ });
12854
+ return !!resp.currentBlockNumber;
12855
+ } catch {
12856
+ return false;
12857
+ }
12858
+ }
12859
+ async function simulateMulticall(client, parameters) {
12860
+ const {
12861
+ allowFailure = true,
12862
+ batchSize: batchSize_,
12863
+ blockNumber,
12864
+ blockTag,
12865
+ multicallAddress: multicallAddress_,
12866
+ stateOverride,
12867
+ gas
12868
+ } = parameters;
12869
+ const contracts = parameters.contracts;
12870
+ const batchSize = batchSize_ ?? (typeof client.batch?.multicall === "object" && client.batch.multicall.batchSize || 1024);
12871
+ let multicallAddress = multicallAddress_;
12872
+ if (!multicallAddress) {
12873
+ if (!client.chain)
12874
+ throw new Error(
12875
+ "client chain not configured. multicallAddress is required."
12876
+ );
12877
+ multicallAddress = viem.getChainContractAddress({
12878
+ blockNumber,
12879
+ chain: client.chain,
12880
+ contract: "multicall3"
12881
+ });
12882
+ }
12883
+ const chunkedCalls = [[]];
12884
+ let currentChunk = 0;
12885
+ let currentChunkSize = 0;
12886
+ for (const contract of contracts) {
12887
+ const { abi: abi2, address, args, functionName } = contract;
12888
+ try {
12889
+ const callData = viem.encodeFunctionData({ abi: abi2, args, functionName });
12890
+ currentChunkSize += (callData.length - 2) / 2;
12891
+ if (
12892
+ // Check if batching is enabled.
12893
+ batchSize > 0 && // Check if the current size of the batch exceeds the size limit.
12894
+ currentChunkSize > batchSize && // Check if the current chunk is not already empty.
12895
+ chunkedCalls[currentChunk].length > 0
12896
+ ) {
12897
+ currentChunk++;
12898
+ currentChunkSize = (callData.length - 2) / 2;
12899
+ chunkedCalls[currentChunk] = [];
12900
+ }
12901
+ chunkedCalls[currentChunk] = [
12902
+ ...chunkedCalls[currentChunk],
12903
+ {
12904
+ allowFailure: true,
12905
+ callData,
12906
+ target: address
12907
+ }
12908
+ ];
12909
+ } catch (err) {
12910
+ const error = viem.getContractError(err, {
12911
+ abi: abi2,
12912
+ address,
12913
+ args,
12914
+ docsPath: "/docs/contract/multicall",
12915
+ functionName
12916
+ });
12917
+ if (!allowFailure) throw error;
12918
+ chunkedCalls[currentChunk] = [
12919
+ ...chunkedCalls[currentChunk],
12920
+ {
12921
+ allowFailure: true,
12922
+ callData: "0x",
12923
+ target: address
12924
+ }
12925
+ ];
12926
+ }
12927
+ }
12928
+ const aggregate3Results = await Promise.allSettled(
12929
+ chunkedCalls.map(
12930
+ (calls) => utils.getAction(
12931
+ client,
12932
+ actions.simulateContract,
12933
+ "simulateContract"
12934
+ )({
12935
+ abi: viem.multicall3Abi,
12936
+ address: multicallAddress,
12937
+ args: [calls],
12938
+ blockNumber,
12939
+ blockTag,
12940
+ // does not infer well that either blockNumber or blockTag must be present
12941
+ functionName: "aggregate3",
12942
+ stateOverride,
12943
+ gas
12944
+ })
12945
+ )
12946
+ );
12947
+ const results = [];
12948
+ for (let i = 0; i < aggregate3Results.length; i++) {
12949
+ const result = aggregate3Results[i];
12950
+ if (result.status === "rejected") {
12951
+ if (!allowFailure) {
12952
+ throw result.reason;
12953
+ }
12954
+ for (const _i of chunkedCalls[i]) {
12955
+ results.push({
12956
+ status: "failure",
12957
+ error: result.reason,
12958
+ result: void 0
12959
+ });
12960
+ }
12961
+ continue;
12962
+ }
12963
+ const aggregate3Result = result.value.result;
12964
+ for (let j = 0; j < aggregate3Result.length; j++) {
12965
+ const { returnData, success } = aggregate3Result[j];
12966
+ const { callData } = chunkedCalls[i][j];
12967
+ const { abi: abi2, address, functionName, args } = contracts[results.length];
12968
+ try {
12969
+ if (callData === "0x") throw new viem.AbiDecodingZeroDataError();
12970
+ if (!success) throw new viem.RawContractError({ data: returnData });
12971
+ const result2 = viem.decodeFunctionResult({
12972
+ abi: abi2,
12973
+ args,
12974
+ data: returnData,
12975
+ functionName
12976
+ });
12977
+ results.push(allowFailure ? { result: result2, status: "success" } : result2);
12978
+ } catch (err) {
12979
+ const error = viem.getContractError(err, {
12980
+ abi: abi2,
12981
+ address,
12982
+ args,
12983
+ docsPath: "/docs/contract/multicall",
12984
+ functionName
12985
+ });
12986
+ if (!allowFailure) throw error;
12987
+ results.push({ error, result: void 0, status: "failure" });
12988
+ }
12989
+ }
12990
+ }
12991
+ if (results.length !== contracts.length)
12992
+ throw new viem.BaseError("multicall results mismatch");
12993
+ return results;
12994
+ }
12995
+
12996
+ // src/accounts/CreditAccountsService.ts
12997
+ var CreditAccountsService = class extends SDKConstruct {
12998
+ #compressor;
12999
+ #wallet;
13000
+ constructor(sdk, wallet) {
13001
+ super(sdk);
13002
+ this.#compressor = sdk.addressProvider.getLatestVersion(
13003
+ AP_CREDIT_ACCOUNT_COMPRESSOR
13004
+ );
13005
+ this.#wallet = wallet;
13006
+ }
13007
+ /**
13008
+ * Returns single credit account data, or undefined if it's not found
13009
+ * Performs all necessary price feed updates under the hood
13010
+ * @param account
13011
+ * @returns
13012
+ */
13013
+ async getCreditAccountData(account) {
13014
+ let raw;
13015
+ try {
13016
+ raw = await this.provider.publicClient.readContract({
13017
+ abi: iCreditAccountCompressorAbi,
13018
+ address: this.#compressor,
13019
+ functionName: "getCreditAccountData",
13020
+ args: [account]
13021
+ });
13022
+ } catch (e) {
13023
+ return void 0;
13024
+ }
13025
+ if (raw.success) {
13026
+ return raw;
13027
+ }
13028
+ const { txs: priceUpdateTxs, timestamp: _ } = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs();
13029
+ const resp = await simulateMulticall(this.#wallet, {
13030
+ contracts: [
13031
+ ...priceUpdateTxs.map(rawTxToMulticallPriceUpdate),
13032
+ {
13033
+ abi: iCreditAccountCompressorAbi,
13034
+ address: this.#compressor,
13035
+ functionName: "getCreditAccountData",
13036
+ args: [account]
13037
+ }
13038
+ ],
13039
+ allowFailure: false,
13040
+ gas: 550000000n,
13041
+ batchSize: 0
13042
+ // we cannot have price updates and compressor request in different batches
13043
+ });
13044
+ const cad = resp.pop();
13045
+ return cad;
13046
+ }
13047
+ /**
13048
+ * Methods to get all credit accounts with some optional filtering
13049
+ * Performs all necessary price feed updates under the hood
13050
+ *
13051
+ * TODO: do we want to expose pagination?
13052
+ * TODO: do we want to expose "reverting"?
13053
+ * TODO: do we want to expose MarketFilter in any way? If so, we need to check that the MarketFilter is compatibled with attached markets?
13054
+ * @param args
13055
+ * @returns
13056
+ */
13057
+ async getCreditAccounts(args) {
13058
+ const {
13059
+ creditManager,
13060
+ includeZeroDebt = false,
13061
+ maxHealthFactor = 65535,
13062
+ // TODO: this will change to bigint
13063
+ minHealthFactor = 0,
13064
+ owner = ADDRESS_0X0
13065
+ } = args ?? {};
13066
+ const arg0 = creditManager ?? {
13067
+ curators: [],
13068
+ pools: this.pools,
13069
+ underlying: ADDRESS_0X0
13070
+ };
13071
+ const caFilter = {
13072
+ owner,
13073
+ includeZeroDebt,
13074
+ minHealthFactor,
13075
+ maxHealthFactor
13076
+ };
13077
+ const { txs: priceUpdateTxs, timestamp: _ } = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs();
13078
+ const allCAs = [];
13079
+ for (const reverting of [false, true]) {
13080
+ let offset = 0n;
13081
+ do {
13082
+ const [accounts, newOffset] = await this.#getCreditAccounts({
13083
+ priceUpdateTxs,
13084
+ args: [arg0, { ...caFilter, reverting }, offset]
13085
+ });
13086
+ allCAs.push(...accounts);
13087
+ offset = newOffset;
13088
+ } while (offset !== 0n);
13089
+ }
13090
+ return allCAs;
13091
+ }
13092
+ /**
13093
+ * Generates transaction to liquidate credit account
13094
+ * @param account
13095
+ * @param to Address to transfer underlying left after liquidation
13096
+ * @param slippage
13097
+ * @returns
13098
+ */
13099
+ async fullyLiquidate(account, to, slippage = 50n) {
13100
+ const cm = this.sdk.marketRegister.findCreditManager(account.creditManager);
13101
+ const market = this.sdk.marketRegister.findByCreditManager(
13102
+ account.creditManager
13103
+ );
13104
+ const preview = await this.sdk.router.findBestClosePath(
13105
+ account,
13106
+ cm.creditManager,
13107
+ slippage
13108
+ );
13109
+ const priceUpdates = await this.#getUpdateForAccounts(account);
13110
+ const priceUpdateCalls = market.priceOracle.onDemandPriceUpdates(
13111
+ cm.creditFacade.address,
13112
+ priceUpdates
13113
+ );
13114
+ return cm.creditFacade.createRawTx({
13115
+ functionName: "liquidateCreditAccount",
13116
+ args: [
13117
+ account.creditAccount,
13118
+ to,
13119
+ [...priceUpdateCalls, ...preview.calls]
13120
+ ]
13121
+ });
13122
+ }
13123
+ /**
13124
+ * Closes credit account or sets debt to zero (but keep account)
13125
+ * @param operation
13126
+ * @param ca
13127
+ * @param assetsToKeep Tokens to withdraw from credit account
13128
+ * @param to Address to withdraw underlying to
13129
+ * @param slippage
13130
+ * @returns
13131
+ */
13132
+ async closeCreditAccount(operation, ca, assetsToKeep, to, slippage = 50n) {
13133
+ const cm = this.sdk.marketRegister.findCreditManager(ca.creditManager);
13134
+ const calls = await this.#prepareCloseCreditAccount(
13135
+ ca,
13136
+ cm,
13137
+ assetsToKeep,
13138
+ to,
13139
+ slippage
13140
+ );
13141
+ return cm.creditFacade.createRawTx({
13142
+ functionName: operation === "close" ? "closeCreditAccount" : "multicall",
13143
+ args: [ca.creditAccount, calls]
13144
+ });
13145
+ }
13146
+ /**
13147
+ * Internal wrapper for CreditAccountCompressor.getCreditAccounts + price updates wrapped into multicall
13148
+ * @param param0
13149
+ * @returns
13150
+ */
13151
+ async #getCreditAccounts({
13152
+ args,
13153
+ priceUpdateTxs
13154
+ }) {
13155
+ if (priceUpdateTxs?.length) {
13156
+ const resp = await simulateMulticall(this.#wallet, {
13157
+ contracts: [
13158
+ ...priceUpdateTxs.map(rawTxToMulticallPriceUpdate),
13159
+ {
13160
+ abi: iCreditAccountCompressorAbi,
13161
+ address: this.#compressor,
13162
+ functionName: "getCreditAccounts",
13163
+ args
13164
+ }
13165
+ ],
13166
+ allowFailure: false,
13167
+ gas: 550000000n,
13168
+ batchSize: 0
13169
+ // we cannot have price updates and compressor request in different batches
13170
+ });
13171
+ const getCreditAccountsResp = resp.pop();
13172
+ return getCreditAccountsResp;
13173
+ }
13174
+ return this.provider.publicClient.readContract({
13175
+ abi: iCreditAccountCompressorAbi,
13176
+ address: this.#compressor,
13177
+ functionName: "getCreditAccounts",
13178
+ args
13179
+ });
13180
+ }
13181
+ /**
13182
+ * Returns raw txs that are needed to update all price feeds so that all credit accounts (possibly from different markets) compute
13183
+ * @param accounts
13184
+ * @returns
13185
+ */
13186
+ async #getUpdateForAccounts(...accounts) {
13187
+ const tokensByPool = /* @__PURE__ */ new Map();
13188
+ const oracleByPool = /* @__PURE__ */ new Map();
13189
+ for (const acc of accounts) {
13190
+ const market = this.sdk.marketRegister.findByCreditManager(
13191
+ acc.creditManager
13192
+ );
13193
+ const pool = market.state.pool.pool.address;
13194
+ oracleByPool.set(pool, market.priceOracle);
13195
+ for (const t of acc.tokens) {
13196
+ if (t.balance > 10n) {
13197
+ const tokens = tokensByPool.get(pool) ?? /* @__PURE__ */ new Set();
13198
+ tokens.add(t.token);
13199
+ tokensByPool.set(pool, tokens);
13200
+ }
13201
+ }
13202
+ }
13203
+ const priceFeeds = [];
13204
+ for (const [pool, priceFeedFactory] of oracleByPool.entries()) {
13205
+ const tokens = Array.from(tokensByPool.get(pool) ?? []);
13206
+ priceFeeds.push(...priceFeedFactory.priceFeedsForTokens(tokens));
13207
+ }
13208
+ return this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(priceFeeds);
13209
+ }
13210
+ async #prepareCloseCreditAccount(ca, cm, assetsToKeep, to, slippage = 50n) {
13211
+ const market = this.sdk.marketRegister.findByCreditManager(
13212
+ ca.creditManager
13213
+ );
13214
+ const closePath = await this.sdk.router.findBestClosePath(
13215
+ ca,
13216
+ cm.creditManager,
13217
+ slippage
13218
+ );
13219
+ const priceUpdates = await this.#getUpdateForAccounts(ca);
13220
+ const priceUpdateCalls = market.priceOracle.onDemandPriceUpdates(
13221
+ cm.creditFacade.address,
13222
+ priceUpdates
13223
+ );
13224
+ return [
13225
+ ...priceUpdateCalls,
13226
+ ...closePath.calls,
13227
+ ...this.#prepareDisableQuotas(ca),
13228
+ ...this.#prepareDecreaseDebt(ca),
13229
+ ...this.#prepareDisableTokens(ca),
13230
+ ...assetsToKeep.map(
13231
+ (t) => this.#prepareWithdrawToken(ca, t, MAX_UINT256, to)
13232
+ )
13233
+ ];
13234
+ }
13235
+ #prepareDisableQuotas(ca) {
13236
+ const calls = [];
13237
+ for (const { token, quota } of ca.tokens) {
13238
+ if (quota > 0n) {
13239
+ calls.push({
13240
+ target: ca.creditFacade,
13241
+ callData: viem.encodeFunctionData({
13242
+ abi: iCreditFacadeV3MulticallAbi,
13243
+ functionName: "updateQuota",
13244
+ args: [token, MIN_INT96, 0n]
13245
+ })
13246
+ });
13247
+ }
13248
+ }
13249
+ return calls;
13250
+ }
13251
+ #prepareDecreaseDebt(ca) {
13252
+ if (ca.totalDebtUSD > 0n) {
13253
+ return [
13254
+ {
13255
+ target: ca.creditFacade,
13256
+ callData: viem.encodeFunctionData({
13257
+ abi: iCreditFacadeV3MulticallAbi,
13258
+ functionName: "decreaseDebt",
13259
+ args: [MAX_UINT256]
13260
+ })
13261
+ }
13262
+ ];
13263
+ }
13264
+ return [];
13265
+ }
13266
+ #prepareDisableTokens(ca) {
13267
+ const calls = [];
13268
+ for (const t of ca.tokens) {
13269
+ if (t.token !== ca.underlying && (t.mask & ca.enabledTokensMask) !== 0n && t.quota === 0n) {
13270
+ calls.push({
13271
+ target: ca.creditFacade,
13272
+ callData: viem.encodeFunctionData({
13273
+ abi: iCreditFacadeV3MulticallAbi,
13274
+ functionName: "disableToken",
13275
+ args: [t.token]
13276
+ })
13277
+ });
13278
+ }
13279
+ }
13280
+ return calls;
13281
+ }
13282
+ #prepareWithdrawToken(ca, token, amount, to) {
13283
+ return {
13284
+ target: ca.creditFacade,
13285
+ callData: viem.encodeFunctionData({
13286
+ abi: iCreditFacadeV3MulticallAbi,
13287
+ functionName: "withdrawCollateral",
13288
+ args: [token, amount, to]
13289
+ })
13290
+ };
13291
+ }
13292
+ /**
13293
+ * Returns addresses of pools of attached markets
13294
+ */
13295
+ get pools() {
13296
+ return this.sdk.marketRegister.poolState.map((p) => p.pool.address);
13297
+ }
13298
+ };
13299
+ function rawTxToMulticallPriceUpdate(tx) {
13300
+ const { to, callData } = tx;
13301
+ const { args, functionName } = viem.decodeFunctionData({
13302
+ abi: iUpdatablePriceFeedAbi,
13303
+ data: callData
13304
+ });
13305
+ return {
13306
+ abi: iUpdatablePriceFeedAbi,
13307
+ address: to,
13308
+ functionName,
13309
+ args
13310
+ };
13311
+ }
12428
13312
  var SUPPORTED_CHAINS = [
12429
13313
  "Mainnet",
12430
13314
  "Arbitrum",
@@ -12792,7 +13676,7 @@ var CreditFacadeContract = class extends BaseContract {
12792
13676
  // src/market/CreditManagerContract.ts
12793
13677
  var CreditManagerContract = class extends BaseContract {
12794
13678
  state;
12795
- constructor(sdk, { creditManager, creditFacade }, pool) {
13679
+ constructor(sdk, { creditManager, creditFacade, adapters }, pool) {
12796
13680
  super(sdk, {
12797
13681
  ...creditManager.baseParams,
12798
13682
  name: `CreditManagerV3(${creditManager.name})`,
@@ -12817,14 +13701,9 @@ var CreditManagerContract = class extends BaseContract {
12817
13701
  feeLiquidationExpired: creditManager.feeLiquidationExpired,
12818
13702
  liquidationDiscountExpired: creditManager.liquidationDiscountExpired,
12819
13703
  quotedTokensMask: 0n,
12820
- contractsToAdapters: {},
12821
- // cmd.adapters.reduce(
12822
- // (acc, adapter) => {
12823
- // acc[adapter.targetContract as Address] = adapter.adapter as Address;
12824
- // return acc;
12825
- // },
12826
- // {} as Record<Address, Address>,
12827
- // ),
13704
+ contractsToAdapters: Object.fromEntries(
13705
+ adapters.map((a) => [a.targetContract, a.baseParams.addr])
13706
+ ),
12828
13707
  creditAccounts: [],
12829
13708
  // [...result[5].result!],
12830
13709
  name: creditManager.name
@@ -14459,49 +15338,6 @@ function compareRouterResults(a, b) {
14459
15338
  function assetsMap(assets) {
14460
15339
  return new AddressMap(assets.map(({ token, balance }) => [token, balance]));
14461
15340
  }
14462
- async function detectNetwork(client) {
14463
- for (const chain of sdkGov.supportedChains) {
14464
- try {
14465
- await client.readContract({
14466
- abi: ierc20MetadataAbi,
14467
- address: sdkGov.tokenDataByNetwork[chain].USDC,
14468
- functionName: "symbol"
14469
- });
14470
- return chain;
14471
- } catch {
14472
- }
14473
- }
14474
- throw new Error("Unsupported network");
14475
- }
14476
-
14477
- // src/utils/viem/createAnvilClient.ts
14478
- function createAnvilClient({
14479
- chain,
14480
- transport
14481
- }) {
14482
- return viem.createTestClient(
14483
- {
14484
- chain,
14485
- mode: "anvil",
14486
- transport,
14487
- cacheTime: 0
14488
- }
14489
- ).extend(viem.publicActions).extend(viem.walletActions).extend((client) => ({
14490
- isAnvil: () => isAnvil(client),
14491
- detectNetwork: () => detectNetwork(client)
14492
- }));
14493
- }
14494
- async function isAnvil(client) {
14495
- try {
14496
- const resp = await client.request({
14497
- method: "anvil_nodeInfo",
14498
- params: []
14499
- });
14500
- return !!resp.currentBlockNumber;
14501
- } catch {
14502
- return false;
14503
- }
14504
- }
14505
15341
 
14506
15342
  // src/GearboxSDK.ts
14507
15343
  var GearboxSDK = class _GearboxSDK extends eventemitter3.EventEmitter {
@@ -15123,6 +15959,7 @@ exports.BotListContract = BotListContract;
15123
15959
  exports.BoundedPriceFeedContract = BoundedPriceFeedContract;
15124
15960
  exports.ChainlinkPriceFeedContract = ChainlinkPriceFeedContract;
15125
15961
  exports.CompositePriceFeedContract = CompositePriceFeedContract;
15962
+ exports.CreditAccountsService = CreditAccountsService;
15126
15963
  exports.CreditConfiguratorContract = CreditConfiguratorContract;
15127
15964
  exports.CreditFacadeContract = CreditFacadeContract;
15128
15965
  exports.CreditFactory = CreditFactory;
@@ -15135,6 +15972,8 @@ exports.GaugeContract = GaugeContract;
15135
15972
  exports.GearStakingContract = GearStakingContract;
15136
15973
  exports.GearboxSDK = GearboxSDK;
15137
15974
  exports.LinearModelContract = LinearModelContract;
15975
+ exports.MAX_UINT256 = MAX_UINT256;
15976
+ exports.MIN_INT96 = MIN_INT96;
15138
15977
  exports.MarketFactory = MarketFactory;
15139
15978
  exports.MarketRegister = MarketRegister;
15140
15979
  exports.MellowLRTPriceFeedContract = MellowLRTPriceFeedContract;