@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
@@ -0,0 +1,132 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_abi_310_generated = require("../../../abi/310/generated.js");
3
+ const require_sdk_constants_address_provider = require("../../constants/address-provider.js");
4
+ const require_sdk_constants_versions = require("../../constants/versions.js");
5
+ require("../../constants/index.js");
6
+ const require_sdk_base_SDKConstruct = require("../../base/SDKConstruct.js");
7
+ require("../../base/index.js");
8
+ const require_sdk_accounts_bots_abi = require("./abi.js");
9
+ const require_sdk_accounts_bots_PeripheryCompressorV310Contract = require("./PeripheryCompressorV310Contract.js");
10
+ //#region src/sdk/accounts/bots/AccountBotsService.ts
11
+ /**
12
+ * Bots of credit accounts.
13
+ *
14
+ * Reads which bots are connected to an account and with which permissions,
15
+ * and builds the transactions that connect or disconnect one.
16
+ **/
17
+ var AccountBotsService = class extends require_sdk_base_SDKConstruct.SDKConstruct {
18
+ /**
19
+ * Reads the bots connected to each of the given credit accounts.
20
+ *
21
+ * All reads go out as a single multicall, split into three groups: the
22
+ * periphery compressor's view of each account, the status of the legacy
23
+ * migration bot on each account, and the status of every bot in
24
+ * `additionalBots` on every account.
25
+ *
26
+ * @param accountsToCheck - Accounts to read, with their credit managers.
27
+ * @param legacyMigrationBot - Legacy migration bot to check, if any.
28
+ * @param additionalBots - Bots to check on every account.
29
+ **/
30
+ async getConnectedBots(accountsToCheck, legacyMigrationBot, additionalBots) {
31
+ const compressor = this.#compressor;
32
+ const compressorCalls = accountsToCheck.map(({ creditManager, creditAccount }) => {
33
+ const { configurator } = this.sdk.marketRegister.findByCreditManager(creditManager);
34
+ return compressor.connectedBotsCall(configurator.address, creditAccount);
35
+ });
36
+ const migrationCalls = legacyMigrationBot ? accountsToCheck.map((account) => this.#botStatusCall(account, legacyMigrationBot)) : [];
37
+ const additionalCalls = accountsToCheck.flatMap((account) => additionalBots.map((bot) => this.#botStatusCall(account, bot)));
38
+ const responses = await this.client.multicall({
39
+ contracts: [
40
+ ...compressorCalls,
41
+ ...migrationCalls,
42
+ ...additionalCalls
43
+ ],
44
+ allowFailure: true,
45
+ batchSize: 0
46
+ });
47
+ const migrationStart = compressorCalls.length;
48
+ const additionalStart = migrationStart + migrationCalls.length;
49
+ return {
50
+ legacy: responses.slice(0, migrationStart),
51
+ legacyMigration: this.#migrationBotStatuses(legacyMigrationBot, accountsToCheck.length, responses.slice(migrationStart, additionalStart)),
52
+ additionalBots: this.#botStatusesPerAccount(accountsToCheck.length, additionalBots.length, responses.slice(additionalStart))
53
+ };
54
+ }
55
+ /**
56
+ * Connects or disconnects a bot, and updates prices when the bot is set on a
57
+ * credit account.
58
+ *
59
+ * @param props - {@link SetBotProps}
60
+ * @returns Everything needed to execute the operation. Setting a bot on a
61
+ * credit manager only yields calls, since it is not a standalone transaction.
62
+ **/
63
+ async setBot({ botAddress, permissions: defaultPermissions, targetContract }) {
64
+ const cm = this.sdk.marketRegister.findCreditManager(targetContract.creditManager);
65
+ const permissions = defaultPermissions !== null ? defaultPermissions : await this.client.readContract({
66
+ address: botAddress,
67
+ abi: require_sdk_accounts_bots_abi.iBotAbi,
68
+ functionName: "requiredPermissions"
69
+ });
70
+ const addBotCall = cm.creditFacade.prepareSetBotPermissions(botAddress, permissions);
71
+ if (targetContract.type !== "creditAccount") return {
72
+ calls: [addBotCall],
73
+ creditFacade: cm.creditFacade
74
+ };
75
+ const calls = await this.sdk.accounts.prependPriceUpdates(targetContract.creditManager, [addBotCall], targetContract);
76
+ return {
77
+ tx: cm.multicallTx(targetContract.creditAccount, calls),
78
+ calls,
79
+ creditFacade: cm.creditFacade
80
+ };
81
+ }
82
+ /**
83
+ * Descriptor of a `getBotStatus` call on the bot list of an account's
84
+ * credit facade.
85
+ **/
86
+ #botStatusCall({ creditManager, creditAccount }, bot) {
87
+ const { creditFacade } = this.sdk.marketRegister.findCreditManager(creditManager);
88
+ return {
89
+ abi: require_abi_310_generated.iBotListV310Abi,
90
+ address: creditFacade.botList,
91
+ functionName: "getBotStatus",
92
+ args: [bot, creditAccount]
93
+ };
94
+ }
95
+ /**
96
+ * Regroups the flat `additionalBots` responses into one entry per account,
97
+ * keeping the order the bots were requested in.
98
+ **/
99
+ #botStatusesPerAccount(accounts, botsPerAccount, responses) {
100
+ this.#checkLength(responses, accounts * botsPerAccount, "bots");
101
+ const perAccount = [];
102
+ for (let i = 0; i < accounts; i++) perAccount.push({ result: responses.slice(i * botsPerAccount, (i + 1) * botsPerAccount) });
103
+ return perAccount;
104
+ }
105
+ /**
106
+ * Migration bot statuses, or `undefined` when no migration bot was queried.
107
+ **/
108
+ #migrationBotStatuses(bot, accounts, responses) {
109
+ if (!bot) return;
110
+ this.#checkLength(responses, accounts, "migration bots");
111
+ return {
112
+ result: responses,
113
+ botAddress: bot
114
+ };
115
+ }
116
+ #checkLength(responses, expected, what) {
117
+ if (responses.length !== expected) this.logger?.error(`result length mismatch for ${what}: got ${responses.length}, expected ${expected}`);
118
+ }
119
+ /**
120
+ * Periphery compressor of the current chain.
121
+ *
122
+ * Resolved on every access, because the address provider is only populated
123
+ * once the SDK is attached or hydrated; the contracts register acts as the
124
+ * cache.
125
+ **/
126
+ get #compressor() {
127
+ const [address] = this.sdk.addressProvider.mustGetLatest(require_sdk_constants_address_provider.AP_PERIPHERY_COMPRESSOR, require_sdk_constants_versions.VERSION_RANGE_310);
128
+ return this.sdk.getContract(address) ?? new require_sdk_accounts_bots_PeripheryCompressorV310Contract.PeripheryCompressorV310Contract(this.sdk, address);
129
+ }
130
+ };
131
+ //#endregion
132
+ exports.AccountBotsService = AccountBotsService;
@@ -0,0 +1,31 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_sdk_base_BaseContract = require("../../base/BaseContract.js");
3
+ require("../../base/index.js");
4
+ //#region src/sdk/accounts/bots/PeripheryCompressorV310Contract.ts
5
+ const abi = require("../../../abi/compressors/peripheryCompressor.js").peripheryCompressorAbi;
6
+ var PeripheryCompressorV310Contract = class extends require_sdk_base_BaseContract.BaseContract {
7
+ constructor(sdk, address) {
8
+ super(sdk, {
9
+ addr: address,
10
+ name: "PeripheryCompressorV310",
11
+ abi,
12
+ version: 310
13
+ });
14
+ }
15
+ /**
16
+ * Descriptor of a `getConnectedBots` call on this compressor.
17
+ *
18
+ * @param marketConfigurator - Configurator that governs the account's market.
19
+ * @param creditAccount - Credit account to list the connected bots of.
20
+ **/
21
+ connectedBotsCall(marketConfigurator, creditAccount) {
22
+ return {
23
+ abi,
24
+ address: this.address,
25
+ functionName: "getConnectedBots",
26
+ args: [marketConfigurator, creditAccount]
27
+ };
28
+ }
29
+ };
30
+ //#endregion
31
+ exports.PeripheryCompressorV310Contract = PeripheryCompressorV310Contract;
@@ -0,0 +1,19 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/sdk/accounts/bots/abi.ts
3
+ /**
4
+ * Minimal bot interface: the permissions a bot needs to operate on a credit
5
+ * account, which the SDK reads when the caller does not specify them.
6
+ **/
7
+ const iBotAbi = [{
8
+ type: "function",
9
+ name: "requiredPermissions",
10
+ inputs: [],
11
+ outputs: [{
12
+ name: "",
13
+ type: "uint192",
14
+ internalType: "uint192"
15
+ }],
16
+ stateMutability: "view"
17
+ }];
18
+ //#endregion
19
+ exports.iBotAbi = iBotAbi;
@@ -0,0 +1,6 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_sdk_accounts_bots_PeripheryCompressorV310Contract = require("./PeripheryCompressorV310Contract.js");
3
+ const require_sdk_accounts_bots_AccountBotsService = require("./AccountBotsService.js");
4
+ require("./types.js");
5
+ exports.AccountBotsService = require_sdk_accounts_bots_AccountBotsService.AccountBotsService;
6
+ exports.PeripheryCompressorV310Contract = require_sdk_accounts_bots_PeripheryCompressorV310Contract.PeripheryCompressorV310Contract;
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
@@ -0,0 +1,280 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_sdk_utils_AddressMap = require("../../utils/AddressMap.js");
3
+ const require_sdk_utils_AddressSet = require("../../utils/AddressSet.js");
4
+ const require_sdk_constants_address_provider = require("../../constants/address-provider.js");
5
+ const require_sdk_constants_addresses = require("../../constants/addresses.js");
6
+ const require_sdk_constants_math = require("../../constants/math.js");
7
+ const require_sdk_constants_versions = require("../../constants/versions.js");
8
+ require("../../constants/index.js");
9
+ const require_sdk_utils_hex = require("../../utils/hex.js");
10
+ require("../../utils/index.js");
11
+ const require_sdk_base_SDKConstruct = require("../../base/SDKConstruct.js");
12
+ require("../../base/index.js");
13
+ const require_abi_rwa_iRWAFactory = require("../../../abi/rwa/iRWAFactory.js");
14
+ const require_sdk_market_math = require("../../market/math.js");
15
+ const require_sdk_market_credit_dominantCollateral = require("../../market/credit/dominantCollateral.js");
16
+ const require_sdk_utils_viem_simulateWithPriceUpdates = require("../../utils/viem/simulateWithPriceUpdates.js");
17
+ require("../../utils/viem/index.js");
18
+ require("../../market/index.js");
19
+ const require_sdk_accounts_credit_account_compressor_CreditAccountCompressorV310Contract = require("./CreditAccountCompressorV310Contract.js");
20
+ //#region src/sdk/accounts/credit-account-compressor/CreditAccountCompressor.ts
21
+ /**
22
+ * Reads credit accounts of the current chain.
23
+ *
24
+ * Stitches the credit account compressor together with the RWA factories (for
25
+ * accounts owned via an investor EOA) and with the withdrawal compressor (for
26
+ * assets that are on their way out of an account), and describes the result
27
+ * either as raw account data or as {@link StrategyPosition}s.
28
+ *
29
+ * TODO: create and deploy new compressor contract onchain to avoid all this stitching
30
+ **/
31
+ var CreditAccountCompressor = class extends require_sdk_base_SDKConstruct.SDKConstruct {
32
+ /**
33
+ * Reads data of a single credit account.
34
+ *
35
+ * When the compressor cannot value the account with current prices, the read
36
+ * is retried with price feed updates applied.
37
+ *
38
+ * @param account - Credit account address.
39
+ * @param blockNumber - Block to read at, defaults to the latest block.
40
+ * @returns Account data, or `undefined` if the account does not exist.
41
+ **/
42
+ async getCreditAccountData(account, blockNumber) {
43
+ const contract = this.#contract;
44
+ const raw = await contract.getCreditAccountData(account, blockNumber);
45
+ if (!raw) return;
46
+ const marketSuite = this.sdk.marketRegister.findByCreditManager(raw.creditManager);
47
+ const factory = marketSuite.rwaFactory;
48
+ let ca;
49
+ let investor;
50
+ if (raw.success) {
51
+ ca = raw;
52
+ investor = await factory?.getInvestor(raw.creditAccount, false);
53
+ } else {
54
+ const { txs: priceUpdateTxs } = await marketSuite.priceOracle.priceUpdateTxsForAccount(raw);
55
+ [ca, investor] = await require_sdk_utils_viem_simulateWithPriceUpdates.simulateWithPriceUpdates(this.client, {
56
+ priceUpdates: priceUpdateTxs,
57
+ contracts: [contract.dataCall(account), ...factory ? [{
58
+ abi: require_abi_rwa_iRWAFactory.iRWAFactoryAbi,
59
+ address: factory.address,
60
+ functionName: "getInvestor",
61
+ args: [raw.creditAccount]
62
+ }] : []],
63
+ blockNumber,
64
+ gas: this.sdk.gasLimit
65
+ });
66
+ }
67
+ return {
68
+ ...ca,
69
+ investor
70
+ };
71
+ }
72
+ /**
73
+ * Reads all credit accounts matching the options, sorted by health factor
74
+ * ascending.
75
+ *
76
+ * @param options - {@link GetCreditAccountsOptions}
77
+ * @param blockNumber - Block to read at, defaults to the latest block.
78
+ **/
79
+ async getCreditAccounts(options, blockNumber) {
80
+ const { creditManager, includeZeroDebt = false, maxHealthFactor = require_sdk_constants_math.MAX_UINT256, minHealthFactor = 0n, owner = require_sdk_constants_addresses.ADDRESS_0X0, ignoreReservePrices = false } = options ?? {};
81
+ const target = creditManager ?? {
82
+ configurators: this.#marketConfigurators,
83
+ creditManagers: [],
84
+ pools: [],
85
+ underlying: "0x0000000000000000000000000000000000000000"
86
+ };
87
+ const { txs: priceUpdateTxs } = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(ignoreReservePrices ? { main: true } : void 0);
88
+ return (await this.#contract.getCreditAccounts(target, {
89
+ owner,
90
+ includeZeroDebt,
91
+ minHealthFactor,
92
+ maxHealthFactor
93
+ }, {
94
+ blockNumber,
95
+ priceUpdateTxs
96
+ })).sort((a, b) => Number(a.healthFactor - b.healthFactor));
97
+ }
98
+ /**
99
+ * Reads all credit accounts of a borrower, sorted by health factor
100
+ * ascending.
101
+ *
102
+ * Covers accounts the borrower owns directly and RWA accounts they own as an
103
+ * investor, which are owned on-chain by an RWA factory.
104
+ *
105
+ * @param borrower - Wallet address.
106
+ * @param options - {@link GetCreditAccountsOptions}
107
+ * @param blockNumber - Block to read at, defaults to the latest block.
108
+ **/
109
+ async getBorrowerCreditAccounts(borrower, options, blockNumber) {
110
+ const { creditManager, includeZeroDebt = false, maxHealthFactor = require_sdk_constants_math.MAX_UINT256, minHealthFactor = 0n, ignoreReservePrices = false } = options ?? {};
111
+ const { txs: priceUpdateTxs } = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(ignoreReservePrices ? { main: true } : void 0);
112
+ const rwaAccountAddresses = (await this.sdk.rwa.getInvestorData(borrower)).flatMap((d) => d.creditAccounts.map((ca) => ca.creditAccount));
113
+ const cmFilter = creditManager ? {
114
+ configurators: [],
115
+ creditManagers: [creditManager],
116
+ pools: [],
117
+ underlying: require_sdk_constants_addresses.ADDRESS_0X0
118
+ } : {
119
+ configurators: this.#marketConfigurators,
120
+ creditManagers: [],
121
+ pools: [],
122
+ underlying: require_sdk_constants_addresses.ADDRESS_0X0
123
+ };
124
+ const permissiveFilter = {
125
+ owner: borrower,
126
+ includeZeroDebt: true,
127
+ minHealthFactor: 0n,
128
+ maxHealthFactor: require_sdk_constants_math.MAX_UINT256,
129
+ reverting: false
130
+ };
131
+ const contract = this.#contract;
132
+ const rwaContracts = rwaAccountAddresses.map((account) => contract.dataCall(account));
133
+ const getCreditAccountsContracts = [false, true].map((reverting) => contract.accountsCall([
134
+ cmFilter,
135
+ {
136
+ ...permissiveFilter,
137
+ reverting
138
+ },
139
+ 0n
140
+ ]));
141
+ const allContracts = [...rwaContracts, ...getCreditAccountsContracts];
142
+ const results = await require_sdk_utils_viem_simulateWithPriceUpdates.simulateWithPriceUpdates(this.client, {
143
+ priceUpdates: priceUpdateTxs,
144
+ contracts: allContracts,
145
+ blockNumber,
146
+ gas: this.sdk.gasLimit
147
+ });
148
+ const rwaResults = results.slice(0, rwaAccountAddresses.length);
149
+ const normalResults = results.slice(rwaAccountAddresses.length);
150
+ const seen = new require_sdk_utils_AddressSet.AddressSet();
151
+ const allCAs = [];
152
+ for (const ca of rwaResults) if (!seen.has(ca.creditAccount)) {
153
+ seen.add(ca.creditAccount);
154
+ allCAs.push({
155
+ ...ca,
156
+ investor: borrower
157
+ });
158
+ }
159
+ for (const [accounts] of normalResults) for (const ca of accounts) if (!seen.has(ca.creditAccount)) {
160
+ seen.add(ca.creditAccount);
161
+ allCAs.push({
162
+ ...ca,
163
+ investor: void 0
164
+ });
165
+ }
166
+ const filtered = allCAs.filter((ca) => {
167
+ if (!includeZeroDebt && ca.debt === 0n) return false;
168
+ if (ca.healthFactor < minHealthFactor) return false;
169
+ if (ca.healthFactor > maxHealthFactor) return false;
170
+ if (creditManager && !require_sdk_utils_hex.hexEq(ca.creditManager, creditManager)) return false;
171
+ return true;
172
+ });
173
+ this.logger?.debug(`loaded ${allCAs.length} borrower credit accounts (${rwaResults.length} RWA, ${filtered.length} after filter)`);
174
+ return filtered.sort((a, b) => Number(a.healthFactor - b.healthFactor));
175
+ }
176
+ /**
177
+ * Describes all credit accounts of a wallet as strategy positions.
178
+ *
179
+ * @param props - {@link ListStrategyPositionsProps}
180
+ **/
181
+ async listPositions(props) {
182
+ const { owner, includeZeroDebt } = props;
183
+ const [accounts] = await Promise.all([this.getBorrowerCreditAccounts(owner, { includeZeroDebt }), this.sdk.withdrawalCompressor?.loadWithdrawableAssets()]);
184
+ const describable = accounts.filter((ca) => {
185
+ if (!ca.success) this.logger?.warn(`cannot describe position of ${this.labelAddress(ca.creditAccount)}: collateral computation failed`);
186
+ return ca.success;
187
+ });
188
+ const withdrawals = await Promise.all(describable.map((ca) => this.#accountWithdrawals(ca)));
189
+ return describable.map((ca, i) => this.#toStrategyPosition(ca, withdrawals[i] ?? new require_sdk_utils_AddressMap.AddressMap()));
190
+ }
191
+ /**
192
+ * Builds one strategy position from an account snapshot.
193
+ *
194
+ * @param withdrawals - Delayed withdrawals of the account, keyed by the
195
+ * phantom token that represents them on it.
196
+ **/
197
+ #toStrategyPosition(ca, withdrawals) {
198
+ const suite = this.sdk.marketRegister.findCreditManager(ca.creditManager);
199
+ const { market } = suite;
200
+ const { priceOracle } = market;
201
+ const { pool } = market.pool;
202
+ const token = this.sdk.tokensMeta.mustGetToken(market.unwrappedUnderlying);
203
+ const totalDebtValue = ca.debt + ca.accruedInterest + ca.accruedFees;
204
+ const collateral = require_sdk_market_credit_dominantCollateral.dominantCollateral(ca, market);
205
+ return {
206
+ kind: "strategy",
207
+ chainId: this.sdk.chainId,
208
+ creditManager: ca.creditManager,
209
+ creditAccount: ca.creditAccount,
210
+ name: collateral ? suite.strategyName(collateral) : token.symbol,
211
+ targetCollateral: collateral ? this.sdk.tokensMeta.mustGetToken(collateral) : null,
212
+ leverage: require_sdk_market_math.positionLeverage(totalDebtValue, ca.totalValue),
213
+ borrowApy: require_sdk_market_math.borrowApyBps(pool.baseInterestRate, suite.creditManager.feeInterest),
214
+ totalDebt: {
215
+ token,
216
+ value: totalDebtValue,
217
+ valueUsd: require_sdk_market_math.usdToNumber(ca.totalDebtUSD)
218
+ },
219
+ totalValue: {
220
+ token,
221
+ value: ca.totalValue,
222
+ valueUsd: require_sdk_market_math.usdToNumber(ca.totalValueUSD)
223
+ },
224
+ healthFactor: require_sdk_market_math.healthFactorBps(ca.healthFactor),
225
+ collaterals: ca.tokens.flatMap((t) => {
226
+ if ((t.mask & ca.enabledTokensMask) === 0n || t.balance <= 10n) return [];
227
+ return [{
228
+ collateral: priceOracle.toTokenAmount(t.token, t.balance),
229
+ quota: priceOracle.toTokenAmount(market.underlying, t.quota),
230
+ withdrawals: withdrawals.get(t.token) ?? []
231
+ }];
232
+ })
233
+ };
234
+ }
235
+ /**
236
+ * Delayed withdrawals of one account, keyed by the phantom token that
237
+ * represents them on it, so that each collateral row can pick up its own.
238
+ **/
239
+ async #accountWithdrawals(ca) {
240
+ const compressor = this.sdk.withdrawalCompressor;
241
+ const byPhantomToken = new require_sdk_utils_AddressMap.AddressMap(void 0, "accountWithdrawals");
242
+ const holdsPhantomToken = ca.tokens.some((t) => t.balance > 10n && compressor?.getWithdrawalSourceToken(t.token) !== void 0);
243
+ if (!compressor || !holdsPhantomToken) return byPhantomToken;
244
+ const { priceOracle } = this.sdk.marketRegister.findByCreditManager(ca.creditManager);
245
+ const { claimable, pending } = await compressor.getCurrentWithdrawals(ca.creditAccount);
246
+ const add = (w, outputs, claimableAt) => {
247
+ const assets = outputs.map((o) => ({
248
+ isDelayed: true,
249
+ ...priceOracle.toTokenAmount(o.token, o.amount),
250
+ redeemer: w.redeemer,
251
+ claimableAt: claimableAt === void 0 ? void 0 : Number(claimableAt)
252
+ }));
253
+ byPhantomToken.upsert(w.withdrawalPhantomToken, [...byPhantomToken.get(w.withdrawalPhantomToken) ?? [], ...assets]);
254
+ };
255
+ for (const w of claimable) add(w, w.outputs);
256
+ for (const w of pending) add(w, w.expectedOutputs, w.claimableAt);
257
+ return byPhantomToken;
258
+ }
259
+ /**
260
+ * Credit account compressor contract of the current chain.
261
+ *
262
+ * Resolved on every access, because the address provider is only populated
263
+ * once the SDK is attached or hydrated. The contracts register acts as the
264
+ * cache: instances register themselves there on construction, and a
265
+ * re-hydrated SDK with a different compressor address simply misses and
266
+ * builds a new wrapper.
267
+ **/
268
+ get #contract() {
269
+ const [address] = this.sdk.addressProvider.mustGetLatest(require_sdk_constants_address_provider.AP_CREDIT_ACCOUNT_COMPRESSOR, require_sdk_constants_versions.VERSION_RANGE_310);
270
+ return this.sdk.getContract(address) ?? new require_sdk_accounts_credit_account_compressor_CreditAccountCompressorV310Contract.CreditAccountCompressorV310Contract(this.sdk, address);
271
+ }
272
+ /**
273
+ * Addresses of market configurators the SDK is attached to.
274
+ **/
275
+ get #marketConfigurators() {
276
+ return this.sdk.marketRegister.marketConfigurators.map((mc) => mc.address);
277
+ }
278
+ };
279
+ //#endregion
280
+ exports.CreditAccountCompressor = CreditAccountCompressor;
@@ -0,0 +1,141 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_sdk_base_BaseContract = require("../../base/BaseContract.js");
3
+ require("../../base/index.js");
4
+ const require_sdk_utils_viem_simulateWithPriceUpdates = require("../../utils/viem/simulateWithPriceUpdates.js");
5
+ require("../../utils/viem/index.js");
6
+ //#region src/sdk/accounts/credit-account-compressor/CreditAccountCompressorV310Contract.ts
7
+ const abi = require("../../../abi/compressors/creditAccountCompressor.js").creditAccountCompressorAbi;
8
+ /**
9
+ * V3.10 credit account compressor.
10
+ *
11
+ * Wraps the compressor ABI and nothing else: single-account reads, paginated
12
+ * multi-account reads, and call descriptors for callers that need to batch
13
+ * these reads with calls to other contracts.
14
+ **/
15
+ var CreditAccountCompressorV310Contract = class extends require_sdk_base_BaseContract.BaseContract {
16
+ #sdk;
17
+ constructor(sdk, address) {
18
+ super(sdk, {
19
+ addr: address,
20
+ name: "CreditAccountCompressorV310",
21
+ abi,
22
+ version: 310
23
+ });
24
+ this.#sdk = sdk;
25
+ }
26
+ /**
27
+ * Reads data of a single credit account.
28
+ *
29
+ * @param account - Credit account address.
30
+ * @param blockNumber - Block to read at, defaults to the latest block.
31
+ * @returns Account data, or `undefined` if the compressor reverted, which it
32
+ * does when the account does not exist.
33
+ **/
34
+ async getCreditAccountData(account, blockNumber) {
35
+ try {
36
+ return await this.client.readContract({
37
+ abi,
38
+ address: this.address,
39
+ functionName: "getCreditAccountData",
40
+ args: [account],
41
+ blockNumber,
42
+ gas: this.#sdk.gasLimit
43
+ });
44
+ } catch (_e) {
45
+ return;
46
+ }
47
+ }
48
+ /**
49
+ * Reads all credit accounts matching the filters, in the order the
50
+ * compressor returns them.
51
+ *
52
+ * Two compressor quirks are handled here: results are paginated, and the
53
+ * `reverting` account filter is exclusive, so accounts whose collateral
54
+ * computation reverts are only returned by a second pass.
55
+ *
56
+ * @param target - Credit managers to query.
57
+ * @param query - Account-level filters, without `reverting`.
58
+ * @param options - Block, price updates and page size.
59
+ **/
60
+ async getCreditAccounts(target, query, options) {
61
+ const { batchSize, blockNumber, priceUpdateTxs } = options ?? {};
62
+ const allCAs = [];
63
+ let revertingOffset = 0;
64
+ for (const reverting of [false, true]) {
65
+ let offset = 0n;
66
+ revertingOffset = allCAs.length;
67
+ do {
68
+ const [accounts, newOffset] = await this.#getCreditAccounts(batchSize ? [
69
+ target,
70
+ {
71
+ ...query,
72
+ reverting
73
+ },
74
+ offset,
75
+ batchSize
76
+ ] : [
77
+ target,
78
+ {
79
+ ...query,
80
+ reverting
81
+ },
82
+ offset
83
+ ], priceUpdateTxs, blockNumber);
84
+ allCAs.push(...accounts);
85
+ offset = newOffset;
86
+ } while (offset !== 0n);
87
+ }
88
+ this.logger?.debug(`loaded ${allCAs.length} credit accounts (${allCAs.length - revertingOffset} reverting)`);
89
+ return allCAs;
90
+ }
91
+ /**
92
+ * Descriptor of a `getCreditAccountData` call on this compressor.
93
+ **/
94
+ dataCall(account) {
95
+ return {
96
+ abi,
97
+ address: this.address,
98
+ functionName: "getCreditAccountData",
99
+ args: [account]
100
+ };
101
+ }
102
+ /**
103
+ * Descriptor of a `getCreditAccounts` call on this compressor.
104
+ **/
105
+ accountsCall(args) {
106
+ return {
107
+ abi,
108
+ address: this.address,
109
+ functionName: "getCreditAccounts",
110
+ args
111
+ };
112
+ }
113
+ /**
114
+ * One page of `getCreditAccounts`, with price updates applied when the
115
+ * accounts hold tokens with on-demand price feeds.
116
+ **/
117
+ async #getCreditAccounts(args, priceUpdateTxs, blockNumber) {
118
+ let resp;
119
+ if (priceUpdateTxs?.length) [resp] = await require_sdk_utils_viem_simulateWithPriceUpdates.simulateWithPriceUpdates(this.client, {
120
+ priceUpdates: priceUpdateTxs,
121
+ contracts: [this.accountsCall(args)],
122
+ blockNumber,
123
+ gas: this.#sdk.gasLimit
124
+ });
125
+ else resp = await this.client.readContract({
126
+ abi,
127
+ address: this.address,
128
+ functionName: "getCreditAccounts",
129
+ args,
130
+ blockNumber,
131
+ gas: this.#sdk.gasLimit
132
+ });
133
+ this.logger?.debug({
134
+ accounts: resp[0]?.length ?? 0,
135
+ nextOffset: Number(resp[1])
136
+ }, "got credit accounts");
137
+ return resp;
138
+ }
139
+ };
140
+ //#endregion
141
+ exports.CreditAccountCompressorV310Contract = CreditAccountCompressorV310Contract;
@@ -0,0 +1,6 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_sdk_accounts_credit_account_compressor_CreditAccountCompressorV310Contract = require("./CreditAccountCompressorV310Contract.js");
3
+ const require_sdk_accounts_credit_account_compressor_CreditAccountCompressor = require("./CreditAccountCompressor.js");
4
+ require("./types.js");
5
+ exports.CreditAccountCompressor = require_sdk_accounts_credit_account_compressor_CreditAccountCompressor.CreditAccountCompressor;
6
+ exports.CreditAccountCompressorV310Contract = require_sdk_accounts_credit_account_compressor_CreditAccountCompressorV310Contract.CreditAccountCompressorV310Contract;
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
@@ -1,4 +1,10 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_sdk_accounts_bots_PeripheryCompressorV310Contract = require("./bots/PeripheryCompressorV310Contract.js");
3
+ const require_sdk_accounts_bots_AccountBotsService = require("./bots/AccountBotsService.js");
4
+ require("./bots/index.js");
5
+ const require_sdk_accounts_credit_account_compressor_CreditAccountCompressorV310Contract = require("./credit-account-compressor/CreditAccountCompressorV310Contract.js");
6
+ const require_sdk_accounts_credit_account_compressor_CreditAccountCompressor = require("./credit-account-compressor/CreditAccountCompressor.js");
7
+ require("./credit-account-compressor/index.js");
2
8
  const require_sdk_accounts_CreditAccountsServiceV310 = require("./CreditAccountsServiceV310.js");
3
9
  const require_sdk_accounts_intents_operations_claim_delayed_index = require("./intents/operations/claim-delayed/index.js");
4
10
  const require_sdk_accounts_intents_index = require("./intents/index.js");
@@ -20,6 +26,9 @@ const require_sdk_accounts_withdrawal_compressor_WithdrawalCompressorV313Contrac
20
26
  const require_sdk_accounts_withdrawal_compressor_createWithdrawalCompressor = require("./withdrawal-compressor/createWithdrawalCompressor.js");
21
27
  require("./withdrawal-compressor/index.js");
22
28
  exports.AbstractWithdrawalCompressorContract = require_sdk_accounts_withdrawal_compressor_AbstractWithdrawalCompressorContract.AbstractWithdrawalCompressorContract;
29
+ exports.AccountBotsService = require_sdk_accounts_bots_AccountBotsService.AccountBotsService;
30
+ exports.CreditAccountCompressor = require_sdk_accounts_credit_account_compressor_CreditAccountCompressor.CreditAccountCompressor;
31
+ exports.CreditAccountCompressorV310Contract = require_sdk_accounts_credit_account_compressor_CreditAccountCompressorV310Contract.CreditAccountCompressorV310Contract;
23
32
  exports.CreditAccountOperationsService = require_sdk_accounts_intents_index.CreditAccountOperationsService;
24
33
  exports.CreditAccountsServiceV310 = require_sdk_accounts_CreditAccountsServiceV310.CreditAccountsServiceV310;
25
34
  exports.DELAYED_INTENT_TYPES = require_sdk_accounts_withdrawal_compressor_intent_codec.DELAYED_INTENT_TYPES;
@@ -29,6 +38,7 @@ exports.LIQUIDATION_APPROVAL_BUFFER = require_sdk_accounts_liquidations_constant
29
38
  exports.LIQUIDATION_COMPRESSOR_V313_ADDRESS = require_sdk_accounts_liquidations_constants.LIQUIDATION_COMPRESSOR_V313_ADDRESS;
30
39
  exports.LiquidationsService = require_sdk_accounts_liquidations_LiquidationsService.LiquidationsService;
31
40
  exports.MultichainLiquidationsService = require_sdk_accounts_liquidations_MultichainLiquidationsService.MultichainLiquidationsService;
41
+ exports.PeripheryCompressorV310Contract = require_sdk_accounts_bots_PeripheryCompressorV310Contract.PeripheryCompressorV310Contract;
32
42
  exports.RedemptionLoggerV310Contract = require_sdk_accounts_withdrawal_compressor_RedemptionLoggerV310Contract.RedemptionLoggerV310Contract;
33
43
  exports.WithdrawalCompressorV310Contract = require_sdk_accounts_withdrawal_compressor_WithdrawalCompressorV310Contract.WithdrawalCompressorV310Contract;
34
44
  exports.WithdrawalCompressorV311Contract = require_sdk_accounts_withdrawal_compressor_WithdrawalCompressorV311Contract.WithdrawalCompressorV311Contract;