@gearbox-protocol/sdk 14.12.0-next.74 → 14.12.0-next.76

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 (79) hide show
  1. package/dist/cjs/plugins/accounts-counter/AccountsCounterPlugin.js +1 -1
  2. package/dist/cjs/sdk/accounts/CreditAccountsServiceV310.js +85 -584
  3. package/dist/cjs/sdk/accounts/bots/AccountBotsService.js +132 -0
  4. package/dist/cjs/sdk/accounts/bots/PeripheryCompressorV310Contract.js +31 -0
  5. package/dist/cjs/sdk/accounts/bots/abi.js +19 -0
  6. package/dist/cjs/sdk/accounts/bots/index.js +6 -0
  7. package/dist/cjs/sdk/accounts/bots/types.js +1 -0
  8. package/dist/cjs/sdk/accounts/credit-account-compressor/CreditAccountCompressor.js +280 -0
  9. package/dist/cjs/sdk/accounts/credit-account-compressor/CreditAccountCompressorV310Contract.js +141 -0
  10. package/dist/cjs/sdk/accounts/credit-account-compressor/index.js +6 -0
  11. package/dist/cjs/sdk/accounts/credit-account-compressor/types.js +1 -0
  12. package/dist/cjs/sdk/accounts/index.js +10 -0
  13. package/dist/cjs/sdk/index.js +8 -0
  14. package/dist/cjs/sdk/market/ZapperRegister.js +1 -1
  15. package/dist/cjs/sdk/market/credit/CreditSuite.js +31 -0
  16. package/dist/cjs/sdk/market/oracle/PriceOracleBaseContract.js +41 -1
  17. package/dist/cjs/sdk/market/oracle/PriceOracleV310Contract.js +0 -23
  18. package/dist/cjs/sdk/market/pricefeeds/PriceFeedsRegister.js +1 -1
  19. package/dist/esm/plugins/accounts-counter/AccountsCounterPlugin.js +1 -1
  20. package/dist/esm/sdk/accounts/CreditAccountsServiceV310.js +87 -586
  21. package/dist/esm/sdk/accounts/bots/AccountBotsService.js +131 -0
  22. package/dist/esm/sdk/accounts/bots/PeripheryCompressorV310Contract.js +31 -0
  23. package/dist/esm/sdk/accounts/bots/abi.js +18 -0
  24. package/dist/esm/sdk/accounts/bots/index.js +4 -0
  25. package/dist/esm/sdk/accounts/bots/types.js +1 -0
  26. package/dist/esm/sdk/accounts/credit-account-compressor/CreditAccountCompressor.js +279 -0
  27. package/dist/esm/sdk/accounts/credit-account-compressor/CreditAccountCompressorV310Contract.js +141 -0
  28. package/dist/esm/sdk/accounts/credit-account-compressor/index.js +4 -0
  29. package/dist/esm/sdk/accounts/credit-account-compressor/types.js +1 -0
  30. package/dist/esm/sdk/accounts/index.js +7 -1
  31. package/dist/esm/sdk/index.js +5 -1
  32. package/dist/esm/sdk/market/ZapperRegister.js +1 -1
  33. package/dist/esm/sdk/market/credit/CreditSuite.js +31 -0
  34. package/dist/esm/sdk/market/oracle/PriceOracleBaseContract.js +41 -1
  35. package/dist/esm/sdk/market/oracle/PriceOracleV310Contract.js +0 -23
  36. package/dist/esm/sdk/market/pricefeeds/PriceFeedsRegister.js +1 -1
  37. package/dist/types/new-sdk/AbstractNamespace.d.ts +2 -2
  38. package/dist/types/new-sdk/opportunities/OpportunitiesNamespace.d.ts +1 -1
  39. package/dist/types/new-sdk/positions/PositionsNamespace.d.ts +1 -1
  40. package/dist/types/plugins/accounts/AccountsPlugin.d.ts +1 -1
  41. package/dist/types/sdk/accounts/CreditAccountsServiceV310.d.ts +17 -58
  42. package/dist/types/sdk/accounts/bots/AccountBotsService.d.ts +38 -0
  43. package/dist/types/sdk/accounts/bots/PeripheryCompressorV310Contract.d.ts +236 -0
  44. package/dist/types/sdk/accounts/bots/abi.d.ts +18 -0
  45. package/dist/types/sdk/accounts/bots/index.d.ts +4 -0
  46. package/dist/types/sdk/accounts/bots/types.d.ts +143 -0
  47. package/dist/types/sdk/accounts/credit-account-compressor/CreditAccountCompressor.d.ts +60 -0
  48. package/dist/types/sdk/accounts/credit-account-compressor/CreditAccountCompressorV310Contract.d.ts +879 -0
  49. package/dist/types/sdk/accounts/credit-account-compressor/index.d.ts +4 -0
  50. package/dist/types/sdk/accounts/credit-account-compressor/types.d.ts +164 -0
  51. package/dist/types/sdk/accounts/index.d.ts +11 -3
  52. package/dist/types/sdk/accounts/liquidations/MultichainLiquidationsService.d.ts +2 -2
  53. package/dist/types/sdk/accounts/liquidations/types.d.ts +1 -1
  54. package/dist/types/sdk/accounts/types.d.ts +13 -194
  55. package/dist/types/sdk/base/TokensMeta.d.ts +1 -1
  56. package/dist/types/sdk/base/index.d.ts +2 -2
  57. package/dist/types/sdk/base/types.d.ts +6 -1
  58. package/dist/types/sdk/index.d.ts +11 -5
  59. package/dist/types/sdk/market/MarketConfiguratorContract.d.ts +1 -1
  60. package/dist/types/sdk/market/MarketSuite.d.ts +1 -1
  61. package/dist/types/sdk/market/credit/CreditManagerV310Contract.d.ts +1 -1
  62. package/dist/types/sdk/market/credit/CreditSuite.d.ts +26 -1
  63. package/dist/types/sdk/market/credit/types.d.ts +1 -1
  64. package/dist/types/sdk/market/index.d.ts +2 -2
  65. package/dist/types/sdk/market/oracle/PriceOracleBaseContract.d.ts +16 -5
  66. package/dist/types/sdk/market/oracle/PriceOracleV310Contract.d.ts +0 -11
  67. package/dist/types/sdk/market/oracle/index.d.ts +2 -2
  68. package/dist/types/sdk/market/oracle/types.d.ts +31 -15
  69. package/dist/types/sdk/market/pool/LinearInterestRateModelContract.d.ts +1 -1
  70. package/dist/types/sdk/market/pool/PoolQuotaKeeperV310Contract.d.ts +1 -1
  71. package/dist/types/sdk/market/pool/PoolSuite.d.ts +1 -1
  72. package/dist/types/sdk/market/pool/PoolV310Contract.d.ts +1 -1
  73. package/dist/types/sdk/market/pool/types.d.ts +1 -1
  74. package/dist/types/sdk/market/pricefeeds/AbstractPriceFeed.d.ts +1 -1
  75. package/dist/types/sdk/market/pricefeeds/types.d.ts +1 -1
  76. package/dist/types/sdk/opportunities/MultichainOpportunitiesService.d.ts +2 -2
  77. package/dist/types/sdk/pools/types.d.ts +1 -1
  78. package/dist/types/sdk/positions/MultichainPositionsService.d.ts +2 -2
  79. package/package.json +1 -1
@@ -1,29 +1,19 @@
1
1
  import { iBaseRewardPoolAbi } from "../../abi/iBaseRewardPool.js";
2
2
  import { ierc4626AdapterAbi } from "../../abi/ierc4626Adapter.js";
3
- import { iBotListV310Abi } from "../../abi/310/generated.js";
4
- import { creditAccountCompressorAbi } from "../../abi/compressors/creditAccountCompressor.js";
5
- import { peripheryCompressorAbi } from "../../abi/compressors/peripheryCompressor.js";
6
- import { rewardsCompressorAbi } from "../../abi/compressors/rewardsCompressor.js";
7
- import { iRWAFactoryAbi } from "../../abi/rwa/iRWAFactory.js";
8
- import { AddressMap } from "../utils/AddressMap.js";
9
- import { AddressSet } from "../utils/AddressSet.js";
10
- import { AP_CREDIT_ACCOUNT_COMPRESSOR, AP_PERIPHERY_COMPRESSOR, AP_REWARDS_COMPRESSOR } from "../constants/address-provider.js";
3
+ import { AP_REWARDS_COMPRESSOR } from "../constants/address-provider.js";
11
4
  import { ADDRESS_0X0 } from "../constants/addresses.js";
12
5
  import { MAX_UINT256 } from "../constants/math.js";
13
6
  import { VERSION_RANGE_310 } from "../constants/versions.js";
14
7
  import "../constants/index.js";
15
- import { hexEq } from "../utils/hex.js";
16
- import "../utils/index.js";
17
8
  import { SDKConstruct } from "../base/SDKConstruct.js";
18
9
  import "../base/index.js";
19
- import { borrowApyBps, healthFactorBps, positionLeverage, usdToNumber } from "../market/math.js";
20
- import { dominantCollateral } from "../market/credit/dominantCollateral.js";
21
- import { simulateWithPriceUpdates } from "../utils/viem/simulateWithPriceUpdates.js";
22
- import "../utils/viem/index.js";
23
- import { getRawPriceUpdates } from "../market/pricefeeds/getRawPriceUpdates.js";
24
- import "../market/index.js";
10
+ import { AccountBotsService } from "./bots/AccountBotsService.js";
11
+ import "./bots/index.js";
12
+ import { rewardsCompressorAbi } from "../../abi/compressors/rewardsCompressor.js";
13
+ import { CreditAccountCompressor } from "./credit-account-compressor/CreditAccountCompressor.js";
14
+ import "./credit-account-compressor/index.js";
25
15
  import { extractPriceUpdates, extractQuotaTokens, mergePriceUpdates } from "./multicall-utils.js";
26
- import { encodeFunctionData, getContract } from "viem";
16
+ import { encodeFunctionData } from "viem";
27
17
  //#region src/sdk/accounts/CreditAccountsServiceV310.ts
28
18
  /**
29
19
  * Service for querying and operating on Gearbox credit accounts.
@@ -36,268 +26,38 @@ import { encodeFunctionData, getContract } from "viem";
36
26
  **/
37
27
  var CreditAccountsServiceV310 = class extends SDKConstruct {
38
28
  #compressor;
39
- #batchSize;
40
- constructor(sdk, options) {
29
+ /**
30
+ * {@inheritDoc ICreditAccountsService.bots}
31
+ **/
32
+ bots;
33
+ constructor(sdk) {
41
34
  super(sdk);
42
- this.#batchSize = options?.batchSize;
43
- }
44
- setBatchSize(batchSize) {
45
- this.#batchSize = batchSize;
35
+ this.#compressor = new CreditAccountCompressor(sdk);
36
+ this.bots = new AccountBotsService(sdk);
46
37
  }
47
38
  /**
48
39
  * {@inheritDoc ICreditAccountsService.getCreditAccountData}
49
40
  **/
50
41
  async getCreditAccountData(account, blockNumber) {
51
- let raw;
52
- try {
53
- raw = await this.client.readContract({
54
- abi: creditAccountCompressorAbi,
55
- address: this.compressor,
56
- functionName: "getCreditAccountData",
57
- args: [account],
58
- blockNumber,
59
- gas: this.sdk.gasLimit
60
- });
61
- } catch (_e) {
62
- return;
63
- }
64
- const factory = this.sdk.marketRegister.findByCreditManager(raw.creditManager).rwaFactory;
65
- let ca;
66
- let investor;
67
- if (raw.success) {
68
- ca = raw;
69
- investor = await factory?.getInvestor(raw.creditAccount, false);
70
- } else {
71
- const { txs: priceUpdateTxs } = await this.#getUpdateForAccount(raw);
72
- [ca, investor] = await simulateWithPriceUpdates(this.client, {
73
- priceUpdates: priceUpdateTxs,
74
- contracts: [{
75
- abi: creditAccountCompressorAbi,
76
- address: this.compressor,
77
- functionName: "getCreditAccountData",
78
- args: [account]
79
- }, ...factory ? [{
80
- abi: iRWAFactoryAbi,
81
- address: factory.address,
82
- functionName: "getInvestor",
83
- args: [raw.creditAccount]
84
- }] : []],
85
- blockNumber,
86
- gas: this.sdk.gasLimit
87
- });
88
- }
89
- return {
90
- ...ca,
91
- investor
92
- };
42
+ return this.#compressor.getCreditAccountData(account, blockNumber);
93
43
  }
94
44
  /**
95
45
  * {@inheritDoc ICreditAccountsService.getCreditAccounts}
96
46
  **/
97
47
  async getCreditAccounts(options, blockNumber) {
98
- const { creditManager, includeZeroDebt = false, maxHealthFactor = MAX_UINT256, minHealthFactor = 0n, owner = ADDRESS_0X0, ignoreReservePrices = false } = options ?? {};
99
- const arg0 = creditManager ?? {
100
- configurators: this.marketConfigurators,
101
- creditManagers: [],
102
- pools: [],
103
- underlying: "0x0000000000000000000000000000000000000000"
104
- };
105
- const caFilter = {
106
- owner,
107
- includeZeroDebt,
108
- minHealthFactor,
109
- maxHealthFactor,
110
- reverting: false
111
- };
112
- const { txs: priceUpdateTxs } = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(ignoreReservePrices ? { main: true } : void 0);
113
- const allCAs = [];
114
- let revertingOffset = 0;
115
- for (const reverting of [false, true]) {
116
- let offset = 0n;
117
- revertingOffset = allCAs.length;
118
- do {
119
- const [accounts, newOffset] = await this.#getCreditAccounts(this.#batchSize ? [
120
- arg0,
121
- {
122
- ...caFilter,
123
- reverting
124
- },
125
- offset,
126
- BigInt(this.#batchSize)
127
- ] : [
128
- arg0,
129
- {
130
- ...caFilter,
131
- reverting
132
- },
133
- offset
134
- ], priceUpdateTxs, blockNumber);
135
- allCAs.push(...accounts);
136
- offset = newOffset;
137
- } while (offset !== 0n);
138
- }
139
- this.logger?.debug(`loaded ${allCAs.length} credit accounts (${allCAs.length - revertingOffset} reverting)`);
140
- return allCAs.sort((a, b) => Number(a.healthFactor - b.healthFactor));
48
+ return this.#compressor.getCreditAccounts(options, blockNumber);
141
49
  }
142
50
  /**
143
51
  * {@inheritDoc ICreditAccountsService.getBorrowerCreditAccounts}
144
52
  **/
145
53
  async getBorrowerCreditAccounts(borrower, options, blockNumber) {
146
- const { creditManager, includeZeroDebt = false, maxHealthFactor = MAX_UINT256, minHealthFactor = 0n, ignoreReservePrices = false } = options ?? {};
147
- const { txs: priceUpdateTxs } = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(ignoreReservePrices ? { main: true } : void 0);
148
- const rwaAccountAddresses = (await this.sdk.rwa.getInvestorData(borrower)).flatMap((d) => d.creditAccounts.map((ca) => ca.creditAccount));
149
- const cmFilter = creditManager ? {
150
- configurators: [],
151
- creditManagers: [creditManager],
152
- pools: [],
153
- underlying: ADDRESS_0X0
154
- } : {
155
- configurators: this.marketConfigurators,
156
- creditManagers: [],
157
- pools: [],
158
- underlying: ADDRESS_0X0
159
- };
160
- const permissiveFilter = {
161
- owner: borrower,
162
- includeZeroDebt: true,
163
- minHealthFactor: 0n,
164
- maxHealthFactor: MAX_UINT256,
165
- reverting: false
166
- };
167
- const rwaContracts = rwaAccountAddresses.map((account) => ({
168
- abi: creditAccountCompressorAbi,
169
- address: this.compressor,
170
- functionName: "getCreditAccountData",
171
- args: [account]
172
- }));
173
- const getCreditAccountsContracts = [false, true].map((reverting) => ({
174
- abi: creditAccountCompressorAbi,
175
- address: this.compressor,
176
- functionName: "getCreditAccounts",
177
- args: [
178
- cmFilter,
179
- {
180
- ...permissiveFilter,
181
- reverting
182
- },
183
- 0n
184
- ]
185
- }));
186
- const allContracts = [...rwaContracts, ...getCreditAccountsContracts];
187
- const results = await simulateWithPriceUpdates(this.client, {
188
- priceUpdates: priceUpdateTxs,
189
- contracts: allContracts,
190
- blockNumber,
191
- gas: this.sdk.gasLimit
192
- });
193
- const rwaResults = results.slice(0, rwaAccountAddresses.length);
194
- const normalResults = results.slice(rwaAccountAddresses.length);
195
- const seen = new AddressSet();
196
- const allCAs = [];
197
- for (const ca of rwaResults) if (!seen.has(ca.creditAccount)) {
198
- seen.add(ca.creditAccount);
199
- allCAs.push({
200
- ...ca,
201
- investor: borrower
202
- });
203
- }
204
- for (const [accounts] of normalResults) for (const ca of accounts) if (!seen.has(ca.creditAccount)) {
205
- seen.add(ca.creditAccount);
206
- allCAs.push({
207
- ...ca,
208
- investor: void 0
209
- });
210
- }
211
- const filtered = allCAs.filter((ca) => {
212
- if (!includeZeroDebt && ca.debt === 0n) return false;
213
- if (ca.healthFactor < minHealthFactor) return false;
214
- if (ca.healthFactor > maxHealthFactor) return false;
215
- if (creditManager && !hexEq(ca.creditManager, creditManager)) return false;
216
- return true;
217
- });
218
- this.logger?.debug(`loaded ${allCAs.length} borrower credit accounts (${rwaResults.length} RWA, ${filtered.length} after filter)`);
219
- return filtered.sort((a, b) => Number(a.healthFactor - b.healthFactor));
54
+ return this.#compressor.getBorrowerCreditAccounts(borrower, options, blockNumber);
220
55
  }
221
56
  /**
222
57
  * {@inheritDoc ICreditAccountsService.listPositions}
223
58
  **/
224
59
  async listPositions(props) {
225
- const { owner, includeZeroDebt } = props;
226
- const [accounts] = await Promise.all([this.getBorrowerCreditAccounts(owner, { includeZeroDebt }), this.sdk.withdrawalCompressor?.loadWithdrawableAssets()]);
227
- const describable = accounts.filter((ca) => {
228
- if (!ca.success) this.logger?.warn(`cannot describe position of ${this.labelAddress(ca.creditAccount)}: collateral computation failed`);
229
- return ca.success;
230
- });
231
- const withdrawals = await Promise.all(describable.map((ca) => this.#accountWithdrawals(ca)));
232
- return describable.map((ca, i) => this.#strategyPosition(ca, withdrawals[i] ?? new AddressMap()));
233
- }
234
- /**
235
- * Builds one strategy position from an account snapshot.
236
- *
237
- * @param withdrawals - Delayed withdrawals of the account, keyed by the
238
- * phantom token that represents them on it.
239
- **/
240
- #strategyPosition(ca, withdrawals) {
241
- const suite = this.sdk.marketRegister.findCreditManager(ca.creditManager);
242
- const { market } = suite;
243
- const { priceOracle } = market;
244
- const { pool } = market.pool;
245
- const token = this.sdk.tokensMeta.mustGetToken(market.unwrappedUnderlying);
246
- const totalDebtValue = ca.debt + ca.accruedInterest + ca.accruedFees;
247
- const collateral = dominantCollateral(ca, market);
248
- return {
249
- kind: "strategy",
250
- chainId: this.sdk.chainId,
251
- creditManager: ca.creditManager,
252
- creditAccount: ca.creditAccount,
253
- name: collateral ? suite.strategyName(collateral) : token.symbol,
254
- targetCollateral: collateral ? this.sdk.tokensMeta.mustGetToken(collateral) : null,
255
- leverage: positionLeverage(totalDebtValue, ca.totalValue),
256
- borrowApy: borrowApyBps(pool.baseInterestRate, suite.creditManager.feeInterest),
257
- totalDebt: {
258
- token,
259
- value: totalDebtValue,
260
- valueUsd: usdToNumber(ca.totalDebtUSD)
261
- },
262
- totalValue: {
263
- token,
264
- value: ca.totalValue,
265
- valueUsd: usdToNumber(ca.totalValueUSD)
266
- },
267
- healthFactor: healthFactorBps(ca.healthFactor),
268
- collaterals: ca.tokens.flatMap((t) => {
269
- if ((t.mask & ca.enabledTokensMask) === 0n || t.balance <= 10n) return [];
270
- return [{
271
- collateral: priceOracle.toTokenAmount(t.token, t.balance),
272
- quota: priceOracle.toTokenAmount(market.underlying, t.quota),
273
- withdrawals: withdrawals.get(t.token) ?? []
274
- }];
275
- })
276
- };
277
- }
278
- /**
279
- * Delayed withdrawals of one account, keyed by the phantom token that
280
- * represents them on it, so that each collateral row can pick up its own.
281
- **/
282
- async #accountWithdrawals(ca) {
283
- const compressor = this.sdk.withdrawalCompressor;
284
- const byPhantomToken = new AddressMap(void 0, "accountWithdrawals");
285
- const holdsPhantomToken = ca.tokens.some((t) => t.balance > 10n && compressor?.getWithdrawalSourceToken(t.token) !== void 0);
286
- if (!compressor || !holdsPhantomToken) return byPhantomToken;
287
- const { priceOracle } = this.sdk.marketRegister.findByCreditManager(ca.creditManager);
288
- const { claimable, pending } = await compressor.getCurrentWithdrawals(ca.creditAccount);
289
- const add = (w, outputs, claimableAt) => {
290
- const assets = outputs.map((o) => ({
291
- isDelayed: true,
292
- ...priceOracle.toTokenAmount(o.token, o.amount),
293
- redeemer: w.redeemer,
294
- claimableAt: claimableAt === void 0 ? void 0 : Number(claimableAt)
295
- }));
296
- byPhantomToken.upsert(w.withdrawalPhantomToken, [...byPhantomToken.get(w.withdrawalPhantomToken) ?? [], ...assets]);
297
- };
298
- for (const w of claimable) add(w, w.outputs);
299
- for (const w of pending) add(w, w.expectedOutputs, w.claimableAt);
300
- return byPhantomToken;
60
+ return this.#compressor.listPositions(props);
301
61
  }
302
62
  /**
303
63
  * {@inheritDoc ICreditAccountsService.getRewards}
@@ -337,76 +97,6 @@ var CreditAccountsServiceV310 = class extends SDKConstruct {
337
97
  return Object.values(r);
338
98
  }
339
99
  /**
340
- * {@inheritDoc ICreditAccountsService.getConnectedBots}
341
- **/
342
- async getConnectedBots(accountsToCheck, legacyMigrationBot, additionalBots) {
343
- const allResp = await this.client.multicall({
344
- contracts: [
345
- ...accountsToCheck.map((o) => {
346
- const pool = this.sdk.marketRegister.findByCreditManager(o.creditManager);
347
- return {
348
- abi: peripheryCompressorAbi,
349
- address: this.peripheryCompressor,
350
- functionName: "getConnectedBots",
351
- args: [pool.configurator.address, o.creditAccount]
352
- };
353
- }),
354
- ...legacyMigrationBot ? accountsToCheck.map((ca) => {
355
- const cm = this.sdk.marketRegister.findCreditManager(ca.creditManager);
356
- return {
357
- abi: iBotListV310Abi,
358
- address: cm.creditFacade.botList,
359
- functionName: "getBotStatus",
360
- args: [legacyMigrationBot, ca.creditAccount]
361
- };
362
- }) : [],
363
- ...accountsToCheck.flatMap((ca) => {
364
- const cm = this.sdk.marketRegister.findCreditManager(ca.creditManager);
365
- return additionalBots.map((bot) => {
366
- return {
367
- abi: iBotListV310Abi,
368
- address: cm.creditFacade.botList,
369
- functionName: "getBotStatus",
370
- args: [bot, ca.creditAccount]
371
- };
372
- });
373
- })
374
- ],
375
- allowFailure: true,
376
- batchSize: 0
377
- });
378
- const legacyStart = 0;
379
- const legacyEnd = accountsToCheck.length;
380
- const legacy = allResp.slice(legacyStart, legacyEnd);
381
- const migrationStart = legacyEnd;
382
- const migrationEnd = legacyMigrationBot ? migrationStart + accountsToCheck.length : migrationStart;
383
- const migrationResp = allResp.slice(migrationStart, migrationEnd);
384
- const additionalStart = migrationEnd;
385
- const additionalResp = allResp.slice(additionalStart);
386
- return {
387
- legacy,
388
- additionalBots: this.#getActiveBots(accountsToCheck, additionalBots, additionalResp),
389
- legacyMigration: this.#getActiveMigrationBots(accountsToCheck, legacyMigrationBot, migrationResp)
390
- };
391
- }
392
- #getActiveBots(accountsToCheck, bots, result) {
393
- if (result.length !== bots.length * accountsToCheck.length) console.error("result length mismatch", result.length, bots.length * accountsToCheck.length);
394
- return accountsToCheck.reduce((acc, _, index) => {
395
- const r = result.slice(index * bots.length, (index + 1) * bots.length);
396
- acc.push({ result: r });
397
- return acc;
398
- }, []);
399
- }
400
- #getActiveMigrationBots(accountsToCheck, bot, result) {
401
- if (bot) {
402
- if (result.length !== accountsToCheck.length) console.error("result length mismatch for migration bots", result.length, accountsToCheck.length);
403
- return {
404
- result,
405
- botAddress: bot
406
- };
407
- }
408
- }
409
- /**
410
100
  * {@inheritDoc ICreditAccountsService.fullyLiquidate}
411
101
  **/
412
102
  async fullyLiquidate(props) {
@@ -419,7 +109,7 @@ var CreditAccountsServiceV310 = class extends SDKConstruct {
419
109
  keepAssets,
420
110
  debtOnly
421
111
  });
422
- const calls = await this.#prependPriceUpdates(account.creditManager, routerCloseResult.calls, account, { ignoreReservePrices });
112
+ const calls = await this.prependPriceUpdates(account.creditManager, routerCloseResult.calls, account, { ignoreReservePrices });
423
113
  let lossPolicyData;
424
114
  if (applyLossPolicy) {
425
115
  lossPolicyData = await this.sdk.marketRegister.findByCreditManager(account.creditManager).lossPolicy.getLiquidationData(account.creditAccount);
@@ -533,15 +223,13 @@ var CreditAccountsServiceV310 = class extends SDKConstruct {
533
223
  async getApprovalAddress(options) {
534
224
  const { creditManager } = options;
535
225
  const suite = this.sdk.marketRegister.findCreditManager(creditManager);
536
- const factory = this.sdk.marketRegister.findByPool(suite.pool).rwaFactory;
537
- if (factory) return factory.getApprovalAddress(options);
538
- return suite.creditManager.address;
226
+ return suite.rwaFactory ? suite.rwaFactory.getApprovalAddress(options) : suite.creditManager.address;
539
227
  }
540
228
  /**
541
229
  * {@inheritDoc ICreditAccountsService.getOpenAccountRequirements}
542
230
  */
543
231
  async getOpenAccountRequirements(borrower, creditManager, props) {
544
- const { rwaFactory } = this.sdk.marketRegister.findByCreditManager(creditManager);
232
+ const { rwaFactory } = this.sdk.marketRegister.findCreditManager(creditManager);
545
233
  if (!rwaFactory) return;
546
234
  return rwaFactory.getOpenAccountRequirements(borrower, props);
547
235
  }
@@ -567,170 +255,80 @@ var CreditAccountsServiceV310 = class extends SDKConstruct {
567
255
  }),
568
256
  ...callsAfter ?? []
569
257
  ];
570
- const calls = await this.#prependPriceUpdates(cm.address, operationCalls);
571
- let tx;
572
- if (reopenCreditAccount) tx = await this.#multicallTx(cmSuite, reopenCreditAccount, calls);
573
- else tx = await this.#openCreditAccountTx(cmSuite, to, calls, referralCode, rwaOptions);
258
+ const calls = await this.prependPriceUpdates(cm.address, operationCalls);
259
+ const tx = reopenCreditAccount ? cmSuite.multicallTx(reopenCreditAccount, calls) : cmSuite.openCreditAccountTx(to, calls, referralCode, rwaOptions);
574
260
  tx.value = ethAmount.toString(10);
575
261
  return tx;
576
262
  }
577
263
  /**
578
- * Internal wrapper for CreditAccountCompressor.getCreditAccounts + price updates wrapped into multicall
579
- * @param args
580
- * @param priceUpdateTxs
581
- * @param blockNumber
582
- * @returns
583
- */
584
- async #getCreditAccounts(args, priceUpdateTxs, blockNumber) {
585
- let resp;
586
- if (priceUpdateTxs?.length) [resp] = await simulateWithPriceUpdates(this.client, {
587
- priceUpdates: priceUpdateTxs,
588
- contracts: [{
589
- abi: creditAccountCompressorAbi,
590
- address: this.compressor,
591
- functionName: "getCreditAccounts",
592
- args
593
- }],
594
- blockNumber,
595
- gas: this.sdk.gasLimit
596
- });
597
- else resp = await this.client.readContract({
598
- abi: creditAccountCompressorAbi,
599
- address: this.compressor,
600
- functionName: "getCreditAccounts",
601
- args,
602
- blockNumber,
603
- gas: this.sdk.gasLimit
604
- });
605
- this.logger?.debug({
606
- accounts: resp[0]?.length ?? 0,
607
- nextOffset: Number(resp[1])
608
- }, "got credit accounts");
609
- return resp;
610
- }
611
- /**
612
- * Returns multicall entries to redeem (unwrap) RWA ERC-4626 vault shares into underlying for the given credit manager.
613
- * Used when withdrawing debt from a RWA market: redeems adapter vault shares so the underlying can be withdrawn.
614
- * Only applies when the credit manager's underlying is RWA-gated and has an ERC-4626 adapter configured.
615
- * @param amount - Number of vault shares (adapter tokens) to redeem
264
+ * Encodes one ERC-4626 adapter call for an RWA market's underlying vault.
265
+ *
266
+ * @param functionName - Adapter function to call
267
+ * @param amount - Amount passed to the adapter, in the units the function expects
616
268
  * @param creditManager - Credit manager address
617
- * @returns Array of MultiCall to pass to credit facade multicall, or undefined if underlying is not RWA or no adapter is configured
269
+ * @returns Array of MultiCall to pass to credit facade multicall, or undefined
270
+ * if the underlying is not RWA-gated or no adapter is configured for it
618
271
  */
619
- async assembleRWAUnwrapCalls(amount, creditManager) {
272
+ #rwaVaultCalls(functionName, amount, creditManager) {
620
273
  const suite = this.sdk.marketRegister.findCreditManager(creditManager);
621
274
  const meta = this.sdk.tokensMeta.mustGet(suite.underlying);
622
275
  if (!this.sdk.tokensMeta.isRWAUnderlying(meta)) return;
623
- const adapterAddress = suite.creditManager.adapters.get(meta.addr)?.address;
624
- if (!adapterAddress) return;
625
- return [{
626
- target: adapterAddress,
627
- callData: encodeFunctionData({
276
+ const target = suite.creditManager.adapters.get(meta.addr)?.address;
277
+ if (!target) return;
278
+ let callData;
279
+ switch (functionName) {
280
+ case "deposit":
281
+ callData = encodeFunctionData({
282
+ abi: ierc4626AdapterAbi,
283
+ functionName,
284
+ args: [amount, ADDRESS_0X0]
285
+ });
286
+ break;
287
+ case "redeem":
288
+ callData = encodeFunctionData({
289
+ abi: ierc4626AdapterAbi,
290
+ functionName,
291
+ args: [
292
+ amount,
293
+ ADDRESS_0X0,
294
+ ADDRESS_0X0
295
+ ]
296
+ });
297
+ break;
298
+ default: callData = encodeFunctionData({
628
299
  abi: ierc4626AdapterAbi,
629
- functionName: "redeem",
630
- args: [
631
- amount,
632
- ADDRESS_0X0,
633
- ADDRESS_0X0
634
- ]
635
- })
300
+ functionName,
301
+ args: [amount]
302
+ });
303
+ }
304
+ return [{
305
+ target,
306
+ callData
636
307
  }];
637
308
  }
638
309
  /**
639
- * Returns multicall entries to deposit (wrap) underlying into RWA ERC-4626 vault shares for the given credit manager.
640
- * Used when adding debt on a RWA market: deposits underlying into the adapter vault so shares are minted on the account.
641
- * Only applies when the credit manager's underlying is RWA-gated and has an ERC-4626 adapter configured.
642
- * @param amount - Amount of underlying assets to deposit into the vault (in underlying decimals)
643
- * @param creditManager - Credit manager address
644
- * @returns Array of MultiCall to pass to credit facade multicall, or undefined if underlying is not RWA or no adapter is configured
310
+ * {@inheritDoc ICreditAccountsService.assembleRWAUnwrapCalls}
645
311
  */
646
- async assembleRWAWrapCalls(amount, creditManager) {
647
- const suite = this.sdk.marketRegister.findCreditManager(creditManager);
648
- const meta = this.sdk.tokensMeta.mustGet(suite.underlying);
649
- if (!this.sdk.tokensMeta.isRWAUnderlying(meta)) return;
650
- const adapterAddress = suite.creditManager.adapters.get(meta.addr)?.address;
651
- if (!adapterAddress) return;
652
- return [{
653
- target: adapterAddress,
654
- callData: encodeFunctionData({
655
- abi: ierc4626AdapterAbi,
656
- functionName: "deposit",
657
- args: [amount, ADDRESS_0X0]
658
- })
659
- }];
312
+ async assembleRWAUnwrapCalls(amount, creditManager) {
313
+ return this.#rwaVaultCalls("redeem", amount, creditManager);
660
314
  }
661
315
  /**
662
- * Returns multicall entries to call redeemDiff on the RWA ERC-4626 adapter for the given credit manager.
663
- * Redeems the leftover vault shares (e.g. after repaying debt) so the account does not hold excess RWA vault tokens.
664
- * Only applies when the credit manager's underlying is RWA-gated and has an ERC-4626 adapter configured.
665
- * @param amount - Leftover vault share amount to redeem (in adapter/vault decimals)
666
- * @param creditManager - Credit manager address
667
- * @returns Array of MultiCall to pass to credit facade multicall, or undefined if underlying is not RWA or no adapter is configured
316
+ * {@inheritDoc ICreditAccountsService.assembleRWAWrapCalls}
668
317
  */
669
- async assembleRedeemDiffCalls(amount, creditManager) {
670
- const suite = this.sdk.marketRegister.findCreditManager(creditManager);
671
- const meta = this.sdk.tokensMeta.mustGet(suite.underlying);
672
- if (!this.sdk.tokensMeta.isRWAUnderlying(meta)) return;
673
- const adapterAddress = suite.creditManager.adapters.get(meta.addr)?.address;
674
- if (!adapterAddress) return;
675
- return [{
676
- target: adapterAddress,
677
- callData: encodeFunctionData({
678
- abi: ierc4626AdapterAbi,
679
- functionName: "redeemDiff",
680
- args: [amount]
681
- })
682
- }];
318
+ async assembleRWAWrapCalls(amount, creditManager) {
319
+ return this.#rwaVaultCalls("deposit", amount, creditManager);
683
320
  }
684
321
  /**
685
- * Returns multicall entries to call depositDiff on the RWA ERC-4626 adapter for the given credit manager.
686
- * Deposits the leftover underlying (e.g. after decreasing debt) into the vault so the account does not hold excess underlying.
687
- * Only applies when the credit manager's underlying is RWA-gated and has an ERC-4626 adapter configured.
688
- * @param amount - Leftover underlying amount to deposit into the vault (in underlying decimals)
689
- * @param creditManager - Credit manager address
690
- * @returns Array of MultiCall to pass to credit facade multicall, or undefined if underlying is not RWA or no adapter is configured
322
+ * {@inheritDoc ICreditAccountsService.assembleRedeemDiffCalls}
691
323
  */
692
- async assembleDepositDiffCalls(amount, creditManager) {
693
- const suite = this.sdk.marketRegister.findCreditManager(creditManager);
694
- const meta = this.sdk.tokensMeta.mustGet(suite.underlying);
695
- if (!this.sdk.tokensMeta.isRWAUnderlying(meta)) return;
696
- const adapterAddress = suite.creditManager.adapters.get(meta.addr)?.address;
697
- if (!adapterAddress) return;
698
- return [{
699
- target: adapterAddress,
700
- callData: encodeFunctionData({
701
- abi: ierc4626AdapterAbi,
702
- functionName: "depositDiff",
703
- args: [amount]
704
- })
705
- }];
324
+ async assembleRedeemDiffCalls(amount, creditManager) {
325
+ return this.#rwaVaultCalls("redeemDiff", amount, creditManager);
706
326
  }
707
327
  /**
708
- * {@inheritDoc ICreditAccountsService.setBot}
328
+ * {@inheritDoc ICreditAccountsService.assembleDepositDiffCalls}
709
329
  */
710
- async setBot({ botAddress, permissions: defaultPermissions, targetContract }) {
711
- const cm = this.sdk.marketRegister.findCreditManager(targetContract.creditManager);
712
- const permissions = defaultPermissions !== null ? defaultPermissions : await getContract({
713
- address: botAddress,
714
- client: this.sdk.client,
715
- abi: [{
716
- type: "function",
717
- name: "requiredPermissions",
718
- inputs: [],
719
- outputs: [{
720
- name: "",
721
- type: "uint192",
722
- internalType: "uint192"
723
- }],
724
- stateMutability: "view"
725
- }]
726
- }).read.requiredPermissions();
727
- const addBotCall = cm.creditFacade.prepareSetBotPermissions(botAddress, permissions);
728
- const calls = targetContract.type === "creditAccount" ? await this.#prependPriceUpdates(targetContract.creditManager, [addBotCall], targetContract) : [addBotCall];
729
- return {
730
- tx: targetContract.type === "creditAccount" ? await this.#multicallTx(cm, targetContract.creditAccount, calls) : void 0,
731
- calls,
732
- creditFacade: cm.creditFacade
733
- };
330
+ async assembleDepositDiffCalls(amount, creditManager) {
331
+ return this.#rwaVaultCalls("depositDiff", amount, creditManager);
734
332
  }
735
333
  /**
736
334
  * {@inheritDoc ICreditAccountsService.assembleRepayCreditAccountCalls}
@@ -771,88 +369,34 @@ var CreditAccountsServiceV310 = class extends SDKConstruct {
771
369
  minQuota,
772
370
  averageQuota
773
371
  })];
774
- const calls = await this.#prependPriceUpdates(ca.creditManager, operationCalls, ca);
775
- return await this.#multicallTx(cm, ca.creditAccount, calls);
372
+ const calls = await this.prependPriceUpdates(ca.creditManager, operationCalls, ca);
373
+ return cm.multicallTx(ca.creditAccount, calls);
776
374
  }
777
375
  /**
778
376
  * Returns raw txs that are needed to update all price feeds so that all credit accounts (possibly from different markets) compute
779
377
  * {@inheritDoc ICreditAccountsService.getOnDemandPriceUpdates}
780
378
  **/
781
379
  async getOnDemandPriceUpdates(account, ignoreReservePrices) {
782
- const { creditManager, creditAccount } = account;
783
- const cm = this.sdk.marketRegister.findCreditManager(creditManager);
784
- const update = await this.#getUpdateForAccount(account, ignoreReservePrices);
785
- this.logger?.debug({
786
- account: creditAccount,
787
- manager: cm.name
788
- }, `getting on demand price updates from ${update.txs.length} txs`);
789
- return getRawPriceUpdates(update);
380
+ const { priceOracle } = this.sdk.marketRegister.findByCreditManager(account.creditManager);
381
+ return priceOracle.priceUpdatesForAccount(account, { reserve: !ignoreReservePrices });
790
382
  }
791
383
  /**
792
- * Analyzes a multicall array and prepends necessary on-demand price feed updates.
793
- *
794
- * Deduplicates existing `onDemandPriceUpdates` calls
795
- *
796
- * @param creditManager - Address of the credit manager
797
- * @param calls - The multicall array to prepend price updates to
798
- * @param ca - Credit account slice, undefined when opening a new account
799
- * @param options - Optional settings for price update generation
800
- * @returns A new array with a single consolidated price update call prepended,
801
- * followed by the non-price-update calls in their original order
384
+ * {@inheritDoc ICreditAccountsService.prependPriceUpdates}
802
385
  */
803
- async #prependPriceUpdates(creditManager, calls, ca, options) {
804
- const market = this.sdk.marketRegister.findByCreditManager(creditManager);
386
+ async prependPriceUpdates(creditManager, calls, creditAccount, options) {
387
+ const { priceOracle } = this.sdk.marketRegister.findByCreditManager(creditManager);
805
388
  const suite = this.sdk.marketRegister.findCreditManager(creditManager);
806
- const cm = suite.creditManager;
807
389
  const { priceUpdates: existingUpdates, remainingCalls } = extractPriceUpdates(calls);
808
- const tokens = new AddressSet([cm.underlying, ...extractQuotaTokens(calls)]);
809
- if (ca) for (const t of ca.tokens) {
810
- const isEnabled = (t.mask & ca.enabledTokensMask) !== 0n;
811
- if (t.balance > 10n && isEnabled) tokens.add(t.token);
812
- }
813
- const ignoreReservePrices = options?.ignoreReservePrices;
814
- const priceFeeds = market.priceOracle.priceFeedsForTokens(Array.from(tokens), {
815
- main: true,
816
- reserve: !ignoreReservePrices
817
- });
818
- const tStr = tokens.map((t) => this.labelAddress(t)).join(", ");
819
- const remark = ignoreReservePrices ? " main" : "";
820
- this.logger?.debug({
821
- account: ca?.creditAccount,
822
- manager: cm.name
823
- }, `prependPriceUpdates for ${tStr} from ${priceFeeds.length}${remark} price feeds`);
824
- const generatedUpdates = await this.sdk.priceFeeds.generatePriceFeedsUpdates(priceFeeds);
390
+ const extraTokens = extractQuotaTokens(calls).asArray();
391
+ const opts = {
392
+ reserve: !options?.ignoreReservePrices,
393
+ extraTokens
394
+ };
395
+ const generatedUpdates = creditAccount ? await priceOracle.priceUpdatesForAccount(creditAccount, opts) : await priceOracle.priceUpdatesForTokens([suite.creditManager.underlying, ...extraTokens], opts);
825
396
  const merged = mergePriceUpdates(existingUpdates, generatedUpdates);
826
397
  if (merged.length === 0) return remainingCalls;
827
398
  return [suite.creditFacade.prepareOnDemandPriceUpdates(merged), ...remainingCalls];
828
399
  }
829
- async #getUpdateForAccount(account, ignoreReservePrices) {
830
- const { creditManager, creditAccount, enabledTokensMask } = account;
831
- const market = this.sdk.marketRegister.findByCreditManager(creditManager);
832
- const cm = this.sdk.marketRegister.findCreditManager(creditManager).creditManager;
833
- const tokens = new AddressSet([cm.underlying]);
834
- for (const t of account.tokens) {
835
- const isEnabled = (t.mask & enabledTokensMask) !== 0n;
836
- if (t.balance > 10n && isEnabled) tokens.add(t.token);
837
- }
838
- const priceFeeds = market.priceOracle.priceFeedsForTokens(Array.from(tokens), {
839
- main: true,
840
- reserve: !ignoreReservePrices
841
- });
842
- const tStr = tokens.map((t) => this.labelAddress(t)).join(", ");
843
- const remark = ignoreReservePrices ? " main" : "";
844
- this.logger?.debug({
845
- account: creditAccount,
846
- manager: cm.name
847
- }, `generating price feed updates for ${tStr} from ${priceFeeds.length}${remark} price feeds`);
848
- return this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(priceFeeds);
849
- }
850
- /**
851
- * {@inheritDoc ICreditAccountsService.prependPriceUpdates}
852
- */
853
- async prependPriceUpdates(creditManager, calls, creditAccount, options) {
854
- return this.#prependPriceUpdates(creditManager, calls, creditAccount, options);
855
- }
856
400
  /**
857
401
  * {@inheritDoc ICreditAccountsService.assembleCaOperations}
858
402
  */
@@ -898,8 +442,8 @@ var CreditAccountsServiceV310 = class extends SDKConstruct {
898
442
  */
899
443
  async executeCaUpdate(creditAccount, calls, options) {
900
444
  const cm = this.sdk.marketRegister.findCreditManager(creditAccount.creditManager);
901
- const callsWithPrices = await this.#prependPriceUpdates(creditAccount.creditManager, calls, creditAccount, { ignoreReservePrices: options?.ignoreReservePrices });
902
- const tx = await this.#multicallTx(cm, creditAccount.creditAccount, callsWithPrices);
445
+ const callsWithPrices = await this.prependPriceUpdates(creditAccount.creditManager, calls, creditAccount, { ignoreReservePrices: options?.ignoreReservePrices });
446
+ const tx = cm.multicallTx(creditAccount.creditAccount, callsWithPrices);
903
447
  if (options?.ethAmount && options.ethAmount > 0n) tx.value = options.ethAmount.toString(10);
904
448
  return tx;
905
449
  }
@@ -933,52 +477,9 @@ var CreditAccountsServiceV310 = class extends SDKConstruct {
933
477
  prepareAddCollateral(creditFacade, assets, permits) {
934
478
  return this.sdk.marketRegister.findCreditFacade(creditFacade).prepareAddCollateral(assets, permits);
935
479
  }
936
- /**
937
- * Returns addresses of market configurators
938
- */
939
- get marketConfigurators() {
940
- return this.sdk.marketRegister.marketConfigurators.map((mc) => mc.address);
941
- }
942
480
  get rewardCompressor() {
943
481
  return this.sdk.addressProvider.mustGetLatest(AP_REWARDS_COMPRESSOR, VERSION_RANGE_310)[0];
944
482
  }
945
- get peripheryCompressor() {
946
- return this.sdk.addressProvider.mustGetLatest(AP_PERIPHERY_COMPRESSOR, VERSION_RANGE_310)[0];
947
- }
948
- get compressor() {
949
- if (!this.#compressor) {
950
- [this.#compressor] = this.sdk.addressProvider.mustGetLatest(AP_CREDIT_ACCOUNT_COMPRESSOR, VERSION_RANGE_310);
951
- this.logger?.debug(`credit account compressor address: ${this.#compressor}`);
952
- }
953
- return this.#compressor;
954
- }
955
- /**
956
- * Wrapper that selects between credit facade and RWA factory
957
- * @param suite
958
- * @param to
959
- * @param calls
960
- * @param referralCode
961
- * @param rwaOptions
962
- * @returns
963
- */
964
- async #openCreditAccountTx(suite, to, calls, referralCode, rwaOptions) {
965
- const factory = this.sdk.marketRegister.findByPool(suite.pool).rwaFactory;
966
- if (factory) return factory.openCreditAccount(suite.creditManager.address, calls, rwaOptions);
967
- return suite.creditFacade.openCreditAccount(to, calls, referralCode ?? 0n);
968
- }
969
- /**
970
- * Wrapper that selects between credit facade and RWA factory
971
- * @param suite
972
- * @param creditAccount
973
- * @param calls
974
- * @param rwaOptions
975
- * @returns
976
- */
977
- async #multicallTx(suite, creditAccount, calls, rwaOptions) {
978
- const factory = this.sdk.marketRegister.findByCreditManager(suite.creditManager.address).rwaFactory;
979
- if (factory) return factory.multicall(creditAccount, calls, rwaOptions);
980
- return suite.creditFacade.multicall(creditAccount, calls);
981
- }
982
483
  /**
983
484
  * Withdrawal compressor of the current chain.
984
485
  * @throws If no withdrawal compressor is supported on the current chain.