@gearbox-protocol/sdk 14.12.0-next.73 → 14.12.0-next.75
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/dev/AccountOpener.js +2 -5
- package/dist/cjs/plugins/accounts-counter/AccountsCounterPlugin.js +1 -1
- package/dist/cjs/sdk/accounts/CreditAccountsServiceV310.js +118 -974
- package/dist/cjs/sdk/accounts/credit-account-compressor/CreditAccountCompressor.js +280 -0
- package/dist/cjs/sdk/accounts/credit-account-compressor/CreditAccountCompressorV310Contract.js +141 -0
- package/dist/cjs/sdk/accounts/credit-account-compressor/index.js +6 -0
- package/dist/cjs/sdk/accounts/credit-account-compressor/types.js +1 -0
- package/dist/cjs/sdk/accounts/index.js +5 -4
- package/dist/cjs/sdk/accounts/intents/operations/unwrap-rwa-collateral/index.js +1 -1
- package/dist/cjs/sdk/accounts/intents/operations/wrap-rwa-collateral/index.js +1 -1
- package/dist/cjs/sdk/accounts/intents/testing/sdk-mock.js +2 -2
- package/dist/cjs/sdk/accounts/liquidations/LiquidationsService.js +3 -3
- package/dist/cjs/sdk/accounts/liquidations/constants.js +0 -2
- package/dist/cjs/sdk/accounts/liquidations/index.js +0 -2
- package/dist/cjs/sdk/constants/index.js +1 -0
- package/dist/cjs/sdk/constants/math.js +5 -0
- package/dist/cjs/sdk/index.js +12 -4
- package/dist/cjs/sdk/market/MarketRegister.js +10 -0
- package/dist/cjs/sdk/market/credit/CreditFacadeV310Contract.js +181 -0
- package/dist/cjs/sdk/market/credit/CreditSuite.js +107 -1
- package/dist/cjs/sdk/{accounts → market/credit}/dominantCollateral.js +18 -4
- package/dist/cjs/sdk/market/credit/index.js +3 -0
- package/dist/cjs/sdk/market/index.js +3 -0
- package/dist/cjs/sdk/market/math.js +59 -0
- package/dist/cjs/sdk/market/oracle/PriceOracleBaseContract.js +41 -1
- package/dist/cjs/sdk/market/oracle/PriceOracleV310Contract.js +0 -30
- package/dist/cjs/sdk/market/pricefeeds/PriceFeedsRegister.js +1 -1
- package/dist/cjs/sdk/opportunities/index.js +4 -0
- package/dist/esm/dev/AccountOpener.js +2 -5
- package/dist/esm/plugins/accounts-counter/AccountsCounterPlugin.js +1 -1
- package/dist/esm/sdk/accounts/CreditAccountsServiceV310.js +121 -977
- package/dist/esm/sdk/accounts/credit-account-compressor/CreditAccountCompressor.js +279 -0
- package/dist/esm/sdk/accounts/credit-account-compressor/CreditAccountCompressorV310Contract.js +141 -0
- package/dist/esm/sdk/accounts/credit-account-compressor/index.js +4 -0
- package/dist/esm/sdk/accounts/credit-account-compressor/types.js +1 -0
- package/dist/esm/sdk/accounts/index.js +4 -3
- package/dist/esm/sdk/accounts/intents/operations/unwrap-rwa-collateral/index.js +1 -1
- package/dist/esm/sdk/accounts/intents/operations/wrap-rwa-collateral/index.js +1 -1
- package/dist/esm/sdk/accounts/intents/testing/sdk-mock.js +2 -2
- package/dist/esm/sdk/accounts/liquidations/LiquidationsService.js +2 -2
- package/dist/esm/sdk/accounts/liquidations/constants.js +1 -2
- package/dist/esm/sdk/accounts/liquidations/index.js +1 -2
- package/dist/esm/sdk/constants/index.js +2 -2
- package/dist/esm/sdk/constants/math.js +5 -1
- package/dist/esm/sdk/index.js +6 -5
- package/dist/esm/sdk/market/MarketRegister.js +10 -0
- package/dist/esm/sdk/market/credit/CreditFacadeV310Contract.js +181 -0
- package/dist/esm/sdk/market/credit/CreditSuite.js +108 -2
- package/dist/esm/sdk/{accounts → market/credit}/dominantCollateral.js +18 -5
- package/dist/esm/sdk/market/credit/index.js +2 -1
- package/dist/esm/sdk/market/index.js +2 -1
- package/dist/esm/sdk/market/math.js +56 -1
- package/dist/esm/sdk/market/oracle/PriceOracleBaseContract.js +41 -1
- package/dist/esm/sdk/market/oracle/PriceOracleV310Contract.js +1 -31
- package/dist/esm/sdk/market/pricefeeds/PriceFeedsRegister.js +1 -1
- package/dist/esm/sdk/opportunities/index.js +2 -2
- package/dist/types/plugins/accounts/AccountsPlugin.d.ts +1 -1
- package/dist/types/sdk/OnchainSDK.d.ts +1 -1
- package/dist/types/sdk/accounts/CreditAccountsServiceV310.d.ts +23 -124
- package/dist/types/sdk/accounts/credit-account-compressor/CreditAccountCompressor.d.ts +60 -0
- package/dist/types/sdk/accounts/credit-account-compressor/CreditAccountCompressorV310Contract.d.ts +879 -0
- package/dist/types/sdk/accounts/credit-account-compressor/index.d.ts +4 -0
- package/dist/types/sdk/accounts/credit-account-compressor/types.d.ts +164 -0
- package/dist/types/sdk/accounts/index.d.ts +7 -5
- package/dist/types/sdk/accounts/liquidations/constants.d.ts +1 -2
- package/dist/types/sdk/accounts/liquidations/index.d.ts +1 -2
- package/dist/types/sdk/accounts/types.d.ts +46 -457
- package/dist/types/sdk/base/index.d.ts +2 -2
- package/dist/types/sdk/base/types.d.ts +6 -1
- package/dist/types/sdk/constants/index.d.ts +2 -2
- package/dist/types/sdk/constants/math.d.ts +5 -1
- package/dist/types/sdk/index.d.ts +16 -14
- package/dist/types/sdk/market/MarketRegister.d.ts +7 -0
- package/dist/types/sdk/market/credit/CreditFacadeV310Contract.d.ts +47 -2
- package/dist/types/sdk/market/credit/CreditSuite.d.ts +24 -2
- package/dist/types/sdk/{accounts → market/credit}/dominantCollateral.d.ts +13 -6
- package/dist/types/sdk/market/credit/index.d.ts +3 -2
- package/dist/types/sdk/market/credit/types.d.ts +112 -2
- package/dist/types/sdk/market/index.d.ts +4 -3
- package/dist/types/sdk/market/math.d.ts +60 -1
- package/dist/types/sdk/market/oracle/PriceOracleBaseContract.d.ts +15 -4
- package/dist/types/sdk/market/oracle/PriceOracleV310Contract.d.ts +0 -10
- package/dist/types/sdk/market/oracle/index.d.ts +2 -2
- package/dist/types/sdk/market/oracle/types.d.ts +30 -14
- package/dist/types/sdk/market/rwa/securitize/SecuritizeRWAFactory.d.ts +1 -1
- package/dist/types/sdk/market/rwa/types.d.ts +1 -1
- package/dist/types/sdk/opportunities/index.d.ts +2 -2
- package/package.json +1 -1
- package/dist/cjs/sdk/accounts/constants.js +0 -12
- package/dist/esm/sdk/accounts/constants.js +0 -11
- package/dist/types/sdk/accounts/constants.d.ts +0 -11
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { AddressMap } from "../../utils/AddressMap.js";
|
|
2
|
+
import { AddressSet } from "../../utils/AddressSet.js";
|
|
3
|
+
import { AP_CREDIT_ACCOUNT_COMPRESSOR } from "../../constants/address-provider.js";
|
|
4
|
+
import { ADDRESS_0X0 } from "../../constants/addresses.js";
|
|
5
|
+
import { MAX_UINT256 } from "../../constants/math.js";
|
|
6
|
+
import { VERSION_RANGE_310 } from "../../constants/versions.js";
|
|
7
|
+
import "../../constants/index.js";
|
|
8
|
+
import { hexEq } from "../../utils/hex.js";
|
|
9
|
+
import "../../utils/index.js";
|
|
10
|
+
import { SDKConstruct } from "../../base/SDKConstruct.js";
|
|
11
|
+
import "../../base/index.js";
|
|
12
|
+
import { iRWAFactoryAbi } from "../../../abi/rwa/iRWAFactory.js";
|
|
13
|
+
import { borrowApyBps, healthFactorBps, positionLeverage, usdToNumber } from "../../market/math.js";
|
|
14
|
+
import { dominantCollateral } from "../../market/credit/dominantCollateral.js";
|
|
15
|
+
import { simulateWithPriceUpdates } from "../../utils/viem/simulateWithPriceUpdates.js";
|
|
16
|
+
import "../../utils/viem/index.js";
|
|
17
|
+
import "../../market/index.js";
|
|
18
|
+
import { CreditAccountCompressorV310Contract } from "./CreditAccountCompressorV310Contract.js";
|
|
19
|
+
//#region src/sdk/accounts/credit-account-compressor/CreditAccountCompressor.ts
|
|
20
|
+
/**
|
|
21
|
+
* Reads credit accounts of the current chain.
|
|
22
|
+
*
|
|
23
|
+
* Stitches the credit account compressor together with the RWA factories (for
|
|
24
|
+
* accounts owned via an investor EOA) and with the withdrawal compressor (for
|
|
25
|
+
* assets that are on their way out of an account), and describes the result
|
|
26
|
+
* either as raw account data or as {@link StrategyPosition}s.
|
|
27
|
+
*
|
|
28
|
+
* TODO: create and deploy new compressor contract onchain to avoid all this stitching
|
|
29
|
+
**/
|
|
30
|
+
var CreditAccountCompressor = class extends SDKConstruct {
|
|
31
|
+
/**
|
|
32
|
+
* Reads data of a single credit account.
|
|
33
|
+
*
|
|
34
|
+
* When the compressor cannot value the account with current prices, the read
|
|
35
|
+
* is retried with price feed updates applied.
|
|
36
|
+
*
|
|
37
|
+
* @param account - Credit account address.
|
|
38
|
+
* @param blockNumber - Block to read at, defaults to the latest block.
|
|
39
|
+
* @returns Account data, or `undefined` if the account does not exist.
|
|
40
|
+
**/
|
|
41
|
+
async getCreditAccountData(account, blockNumber) {
|
|
42
|
+
const contract = this.#contract;
|
|
43
|
+
const raw = await contract.getCreditAccountData(account, blockNumber);
|
|
44
|
+
if (!raw) return;
|
|
45
|
+
const marketSuite = this.sdk.marketRegister.findByCreditManager(raw.creditManager);
|
|
46
|
+
const factory = marketSuite.rwaFactory;
|
|
47
|
+
let ca;
|
|
48
|
+
let investor;
|
|
49
|
+
if (raw.success) {
|
|
50
|
+
ca = raw;
|
|
51
|
+
investor = await factory?.getInvestor(raw.creditAccount, false);
|
|
52
|
+
} else {
|
|
53
|
+
const { txs: priceUpdateTxs } = await marketSuite.priceOracle.priceUpdateTxsForAccount(raw);
|
|
54
|
+
[ca, investor] = await simulateWithPriceUpdates(this.client, {
|
|
55
|
+
priceUpdates: priceUpdateTxs,
|
|
56
|
+
contracts: [contract.dataCall(account), ...factory ? [{
|
|
57
|
+
abi: iRWAFactoryAbi,
|
|
58
|
+
address: factory.address,
|
|
59
|
+
functionName: "getInvestor",
|
|
60
|
+
args: [raw.creditAccount]
|
|
61
|
+
}] : []],
|
|
62
|
+
blockNumber,
|
|
63
|
+
gas: this.sdk.gasLimit
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
...ca,
|
|
68
|
+
investor
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Reads all credit accounts matching the options, sorted by health factor
|
|
73
|
+
* ascending.
|
|
74
|
+
*
|
|
75
|
+
* @param options - {@link GetCreditAccountsOptions}
|
|
76
|
+
* @param blockNumber - Block to read at, defaults to the latest block.
|
|
77
|
+
**/
|
|
78
|
+
async getCreditAccounts(options, blockNumber) {
|
|
79
|
+
const { creditManager, includeZeroDebt = false, maxHealthFactor = MAX_UINT256, minHealthFactor = 0n, owner = ADDRESS_0X0, ignoreReservePrices = false } = options ?? {};
|
|
80
|
+
const target = creditManager ?? {
|
|
81
|
+
configurators: this.#marketConfigurators,
|
|
82
|
+
creditManagers: [],
|
|
83
|
+
pools: [],
|
|
84
|
+
underlying: "0x0000000000000000000000000000000000000000"
|
|
85
|
+
};
|
|
86
|
+
const { txs: priceUpdateTxs } = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(ignoreReservePrices ? { main: true } : void 0);
|
|
87
|
+
return (await this.#contract.getCreditAccounts(target, {
|
|
88
|
+
owner,
|
|
89
|
+
includeZeroDebt,
|
|
90
|
+
minHealthFactor,
|
|
91
|
+
maxHealthFactor
|
|
92
|
+
}, {
|
|
93
|
+
blockNumber,
|
|
94
|
+
priceUpdateTxs
|
|
95
|
+
})).sort((a, b) => Number(a.healthFactor - b.healthFactor));
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Reads all credit accounts of a borrower, sorted by health factor
|
|
99
|
+
* ascending.
|
|
100
|
+
*
|
|
101
|
+
* Covers accounts the borrower owns directly and RWA accounts they own as an
|
|
102
|
+
* investor, which are owned on-chain by an RWA factory.
|
|
103
|
+
*
|
|
104
|
+
* @param borrower - Wallet address.
|
|
105
|
+
* @param options - {@link GetCreditAccountsOptions}
|
|
106
|
+
* @param blockNumber - Block to read at, defaults to the latest block.
|
|
107
|
+
**/
|
|
108
|
+
async getBorrowerCreditAccounts(borrower, options, blockNumber) {
|
|
109
|
+
const { creditManager, includeZeroDebt = false, maxHealthFactor = MAX_UINT256, minHealthFactor = 0n, ignoreReservePrices = false } = options ?? {};
|
|
110
|
+
const { txs: priceUpdateTxs } = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(ignoreReservePrices ? { main: true } : void 0);
|
|
111
|
+
const rwaAccountAddresses = (await this.sdk.rwa.getInvestorData(borrower)).flatMap((d) => d.creditAccounts.map((ca) => ca.creditAccount));
|
|
112
|
+
const cmFilter = creditManager ? {
|
|
113
|
+
configurators: [],
|
|
114
|
+
creditManagers: [creditManager],
|
|
115
|
+
pools: [],
|
|
116
|
+
underlying: ADDRESS_0X0
|
|
117
|
+
} : {
|
|
118
|
+
configurators: this.#marketConfigurators,
|
|
119
|
+
creditManagers: [],
|
|
120
|
+
pools: [],
|
|
121
|
+
underlying: ADDRESS_0X0
|
|
122
|
+
};
|
|
123
|
+
const permissiveFilter = {
|
|
124
|
+
owner: borrower,
|
|
125
|
+
includeZeroDebt: true,
|
|
126
|
+
minHealthFactor: 0n,
|
|
127
|
+
maxHealthFactor: MAX_UINT256,
|
|
128
|
+
reverting: false
|
|
129
|
+
};
|
|
130
|
+
const contract = this.#contract;
|
|
131
|
+
const rwaContracts = rwaAccountAddresses.map((account) => contract.dataCall(account));
|
|
132
|
+
const getCreditAccountsContracts = [false, true].map((reverting) => contract.accountsCall([
|
|
133
|
+
cmFilter,
|
|
134
|
+
{
|
|
135
|
+
...permissiveFilter,
|
|
136
|
+
reverting
|
|
137
|
+
},
|
|
138
|
+
0n
|
|
139
|
+
]));
|
|
140
|
+
const allContracts = [...rwaContracts, ...getCreditAccountsContracts];
|
|
141
|
+
const results = await simulateWithPriceUpdates(this.client, {
|
|
142
|
+
priceUpdates: priceUpdateTxs,
|
|
143
|
+
contracts: allContracts,
|
|
144
|
+
blockNumber,
|
|
145
|
+
gas: this.sdk.gasLimit
|
|
146
|
+
});
|
|
147
|
+
const rwaResults = results.slice(0, rwaAccountAddresses.length);
|
|
148
|
+
const normalResults = results.slice(rwaAccountAddresses.length);
|
|
149
|
+
const seen = new AddressSet();
|
|
150
|
+
const allCAs = [];
|
|
151
|
+
for (const ca of rwaResults) if (!seen.has(ca.creditAccount)) {
|
|
152
|
+
seen.add(ca.creditAccount);
|
|
153
|
+
allCAs.push({
|
|
154
|
+
...ca,
|
|
155
|
+
investor: borrower
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
for (const [accounts] of normalResults) for (const ca of accounts) if (!seen.has(ca.creditAccount)) {
|
|
159
|
+
seen.add(ca.creditAccount);
|
|
160
|
+
allCAs.push({
|
|
161
|
+
...ca,
|
|
162
|
+
investor: void 0
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
const filtered = allCAs.filter((ca) => {
|
|
166
|
+
if (!includeZeroDebt && ca.debt === 0n) return false;
|
|
167
|
+
if (ca.healthFactor < minHealthFactor) return false;
|
|
168
|
+
if (ca.healthFactor > maxHealthFactor) return false;
|
|
169
|
+
if (creditManager && !hexEq(ca.creditManager, creditManager)) return false;
|
|
170
|
+
return true;
|
|
171
|
+
});
|
|
172
|
+
this.logger?.debug(`loaded ${allCAs.length} borrower credit accounts (${rwaResults.length} RWA, ${filtered.length} after filter)`);
|
|
173
|
+
return filtered.sort((a, b) => Number(a.healthFactor - b.healthFactor));
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Describes all credit accounts of a wallet as strategy positions.
|
|
177
|
+
*
|
|
178
|
+
* @param props - {@link ListStrategyPositionsProps}
|
|
179
|
+
**/
|
|
180
|
+
async listPositions(props) {
|
|
181
|
+
const { owner, includeZeroDebt } = props;
|
|
182
|
+
const [accounts] = await Promise.all([this.getBorrowerCreditAccounts(owner, { includeZeroDebt }), this.sdk.withdrawalCompressor?.loadWithdrawableAssets()]);
|
|
183
|
+
const describable = accounts.filter((ca) => {
|
|
184
|
+
if (!ca.success) this.logger?.warn(`cannot describe position of ${this.labelAddress(ca.creditAccount)}: collateral computation failed`);
|
|
185
|
+
return ca.success;
|
|
186
|
+
});
|
|
187
|
+
const withdrawals = await Promise.all(describable.map((ca) => this.#accountWithdrawals(ca)));
|
|
188
|
+
return describable.map((ca, i) => this.#toStrategyPosition(ca, withdrawals[i] ?? new AddressMap()));
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Builds one strategy position from an account snapshot.
|
|
192
|
+
*
|
|
193
|
+
* @param withdrawals - Delayed withdrawals of the account, keyed by the
|
|
194
|
+
* phantom token that represents them on it.
|
|
195
|
+
**/
|
|
196
|
+
#toStrategyPosition(ca, withdrawals) {
|
|
197
|
+
const suite = this.sdk.marketRegister.findCreditManager(ca.creditManager);
|
|
198
|
+
const { market } = suite;
|
|
199
|
+
const { priceOracle } = market;
|
|
200
|
+
const { pool } = market.pool;
|
|
201
|
+
const token = this.sdk.tokensMeta.mustGetToken(market.unwrappedUnderlying);
|
|
202
|
+
const totalDebtValue = ca.debt + ca.accruedInterest + ca.accruedFees;
|
|
203
|
+
const collateral = dominantCollateral(ca, market);
|
|
204
|
+
return {
|
|
205
|
+
kind: "strategy",
|
|
206
|
+
chainId: this.sdk.chainId,
|
|
207
|
+
creditManager: ca.creditManager,
|
|
208
|
+
creditAccount: ca.creditAccount,
|
|
209
|
+
name: collateral ? suite.strategyName(collateral) : token.symbol,
|
|
210
|
+
targetCollateral: collateral ? this.sdk.tokensMeta.mustGetToken(collateral) : null,
|
|
211
|
+
leverage: positionLeverage(totalDebtValue, ca.totalValue),
|
|
212
|
+
borrowApy: borrowApyBps(pool.baseInterestRate, suite.creditManager.feeInterest),
|
|
213
|
+
totalDebt: {
|
|
214
|
+
token,
|
|
215
|
+
value: totalDebtValue,
|
|
216
|
+
valueUsd: usdToNumber(ca.totalDebtUSD)
|
|
217
|
+
},
|
|
218
|
+
totalValue: {
|
|
219
|
+
token,
|
|
220
|
+
value: ca.totalValue,
|
|
221
|
+
valueUsd: usdToNumber(ca.totalValueUSD)
|
|
222
|
+
},
|
|
223
|
+
healthFactor: healthFactorBps(ca.healthFactor),
|
|
224
|
+
collaterals: ca.tokens.flatMap((t) => {
|
|
225
|
+
if ((t.mask & ca.enabledTokensMask) === 0n || t.balance <= 10n) return [];
|
|
226
|
+
return [{
|
|
227
|
+
collateral: priceOracle.toTokenAmount(t.token, t.balance),
|
|
228
|
+
quota: priceOracle.toTokenAmount(market.underlying, t.quota),
|
|
229
|
+
withdrawals: withdrawals.get(t.token) ?? []
|
|
230
|
+
}];
|
|
231
|
+
})
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Delayed withdrawals of one account, keyed by the phantom token that
|
|
236
|
+
* represents them on it, so that each collateral row can pick up its own.
|
|
237
|
+
**/
|
|
238
|
+
async #accountWithdrawals(ca) {
|
|
239
|
+
const compressor = this.sdk.withdrawalCompressor;
|
|
240
|
+
const byPhantomToken = new AddressMap(void 0, "accountWithdrawals");
|
|
241
|
+
const holdsPhantomToken = ca.tokens.some((t) => t.balance > 10n && compressor?.getWithdrawalSourceToken(t.token) !== void 0);
|
|
242
|
+
if (!compressor || !holdsPhantomToken) return byPhantomToken;
|
|
243
|
+
const { priceOracle } = this.sdk.marketRegister.findByCreditManager(ca.creditManager);
|
|
244
|
+
const { claimable, pending } = await compressor.getCurrentWithdrawals(ca.creditAccount);
|
|
245
|
+
const add = (w, outputs, claimableAt) => {
|
|
246
|
+
const assets = outputs.map((o) => ({
|
|
247
|
+
isDelayed: true,
|
|
248
|
+
...priceOracle.toTokenAmount(o.token, o.amount),
|
|
249
|
+
redeemer: w.redeemer,
|
|
250
|
+
claimableAt: claimableAt === void 0 ? void 0 : Number(claimableAt)
|
|
251
|
+
}));
|
|
252
|
+
byPhantomToken.upsert(w.withdrawalPhantomToken, [...byPhantomToken.get(w.withdrawalPhantomToken) ?? [], ...assets]);
|
|
253
|
+
};
|
|
254
|
+
for (const w of claimable) add(w, w.outputs);
|
|
255
|
+
for (const w of pending) add(w, w.expectedOutputs, w.claimableAt);
|
|
256
|
+
return byPhantomToken;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Credit account compressor contract of the current chain.
|
|
260
|
+
*
|
|
261
|
+
* Resolved on every access, because the address provider is only populated
|
|
262
|
+
* once the SDK is attached or hydrated. The contracts register acts as the
|
|
263
|
+
* cache: instances register themselves there on construction, and a
|
|
264
|
+
* re-hydrated SDK with a different compressor address simply misses and
|
|
265
|
+
* builds a new wrapper.
|
|
266
|
+
**/
|
|
267
|
+
get #contract() {
|
|
268
|
+
const [address] = this.sdk.addressProvider.mustGetLatest(AP_CREDIT_ACCOUNT_COMPRESSOR, VERSION_RANGE_310);
|
|
269
|
+
return this.sdk.getContract(address) ?? new CreditAccountCompressorV310Contract(this.sdk, address);
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Addresses of market configurators the SDK is attached to.
|
|
273
|
+
**/
|
|
274
|
+
get #marketConfigurators() {
|
|
275
|
+
return this.sdk.marketRegister.marketConfigurators.map((mc) => mc.address);
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
//#endregion
|
|
279
|
+
export { CreditAccountCompressor };
|
package/dist/esm/sdk/accounts/credit-account-compressor/CreditAccountCompressorV310Contract.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { BaseContract } from "../../base/BaseContract.js";
|
|
2
|
+
import "../../base/index.js";
|
|
3
|
+
import { simulateWithPriceUpdates } from "../../utils/viem/simulateWithPriceUpdates.js";
|
|
4
|
+
import "../../utils/viem/index.js";
|
|
5
|
+
import { creditAccountCompressorAbi } from "../../../abi/compressors/creditAccountCompressor.js";
|
|
6
|
+
//#region src/sdk/accounts/credit-account-compressor/CreditAccountCompressorV310Contract.ts
|
|
7
|
+
const abi = 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 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 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
|
+
export { CreditAccountCompressorV310Contract };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { CreditAccountCompressorV310Contract } from "./credit-account-compressor/CreditAccountCompressorV310Contract.js";
|
|
2
|
+
import { CreditAccountCompressor } from "./credit-account-compressor/CreditAccountCompressor.js";
|
|
3
|
+
import "./credit-account-compressor/index.js";
|
|
3
4
|
import { CreditAccountsServiceV310 } from "./CreditAccountsServiceV310.js";
|
|
4
5
|
import { primaryInstantOutput } from "./intents/operations/claim-delayed/index.js";
|
|
5
6
|
import { CreditAccountOperationsService } from "./intents/index.js";
|
|
@@ -20,4 +21,4 @@ import { toWithdrawalStatus } from "./withdrawal-compressor/types.js";
|
|
|
20
21
|
import { WithdrawalCompressorV313Contract } from "./withdrawal-compressor/WithdrawalCompressorV313Contract.js";
|
|
21
22
|
import { createWithdrawalCompressor } from "./withdrawal-compressor/createWithdrawalCompressor.js";
|
|
22
23
|
import "./withdrawal-compressor/index.js";
|
|
23
|
-
export { AbstractWithdrawalCompressorContract, CreditAccountOperationsService, CreditAccountsServiceV310, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION,
|
|
24
|
+
export { AbstractWithdrawalCompressorContract, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountsServiceV310, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, InvalidDelayedIntentError, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, LiquidationsService, MultichainLiquidationsService, RedemptionLoggerV310Contract, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, createRedemptionLogger, createWithdrawalCompressor, decodeDelayedIntent, encodeDelayedIntent, getWithdrawalCompressorAddress, iCreditAccountAbi, primaryInstantOutput, toClaimableWithdrawal, toPendingWithdrawal, toRequestableWithdrawal, toWithdrawalStatus };
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
/** One-to-one swap op (withdraw resume conversion legs). */
|
|
3
3
|
async function buildUnwrapRwaCollateralOperation(input, option) {
|
|
4
4
|
if (option.kind === "onchain") {
|
|
5
|
-
const calls = await input.sdk.accounts.
|
|
5
|
+
const calls = await input.sdk.accounts.assembleRWAUnwrapCalls(input.amountIn, input.creditAccount.creditManager);
|
|
6
6
|
if (!calls) throw new Error("unwrapRwaCollateral: no wrap calls found");
|
|
7
7
|
return {
|
|
8
8
|
type: "unwrapRwaCollateral",
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
/** One-to-one wrap op (decrease-leverage resume repay from rwa.asset). */
|
|
3
3
|
async function buildWrapRwaCollateralOperation(input, option) {
|
|
4
4
|
if (option.kind === "onchain") {
|
|
5
|
-
const calls = await input.sdk.accounts.
|
|
5
|
+
const calls = await input.sdk.accounts.assembleRWAWrapCalls(input.amountIn, input.creditAccount.creditManager);
|
|
6
6
|
if (!calls) throw new Error("wrapRwaCollateral: no wrap calls found");
|
|
7
7
|
return {
|
|
8
8
|
type: "wrapRwaCollateral",
|
|
@@ -163,8 +163,8 @@ function buildMockSdk(args) {
|
|
|
163
163
|
prepareUpdateQuotas: vi.fn(() => [CA_OP_CALLS.changeQuota]),
|
|
164
164
|
assembleClaimDelayedCalls: vi.fn(({ claimableNow }) => [...claimableNow.claimCalls]),
|
|
165
165
|
assembleCloseCreditAccountCalls: vi.fn(async () => [MOCK_CLOSE_CALL]),
|
|
166
|
-
|
|
167
|
-
|
|
166
|
+
assembleRWAWrapCalls: vi.fn(async () => [MOCK_RWA_WRAP_CALL]),
|
|
167
|
+
assembleRWAUnwrapCalls: vi.fn(async () => [MOCK_RWA_UNWRAP_CALL])
|
|
168
168
|
}
|
|
169
169
|
};
|
|
170
170
|
}
|
|
@@ -9,6 +9,7 @@ import "../../utils/index.js";
|
|
|
9
9
|
import { SDKConstruct } from "../../base/SDKConstruct.js";
|
|
10
10
|
import "../../base/index.js";
|
|
11
11
|
import { usdToNumber } from "../../market/math.js";
|
|
12
|
+
import { dominantCollateral } from "../../market/credit/dominantCollateral.js";
|
|
12
13
|
import { matchesLiquidatableAccountFilter } from "../../../model/liquidations.js";
|
|
13
14
|
import "../../../model/index.js";
|
|
14
15
|
import { RWA_LIQUIDATOR_MIDAS } from "../../market/rwa/midas/constants.js";
|
|
@@ -17,8 +18,7 @@ import "../../market/rwa/midas/index.js";
|
|
|
17
18
|
import { RWA_LIQUIDATOR_SECURITIZE } from "../../market/rwa/securitize/constants.js";
|
|
18
19
|
import { SecuritizeLiquidatorContract } from "../../market/rwa/securitize/SecuritizeLiquidatorContract.js";
|
|
19
20
|
import "../../market/rwa/securitize/index.js";
|
|
20
|
-
import "
|
|
21
|
-
import { dominantCollateral } from "../dominantCollateral.js";
|
|
21
|
+
import "../../market/index.js";
|
|
22
22
|
import { LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS } from "./constants.js";
|
|
23
23
|
//#region src/sdk/accounts/liquidations/LiquidationsService.ts
|
|
24
24
|
/**
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { DUST_THRESHOLD } from "../constants.js";
|
|
2
1
|
//#region src/sdk/accounts/liquidations/constants.ts
|
|
3
2
|
const LIQUIDATION_COMPRESSOR_V313_ADDRESS = "0xB70C4500a0afF02107eB983a348F22492fB6dC94";
|
|
4
3
|
/**
|
|
@@ -8,4 +7,4 @@ const LIQUIDATION_COMPRESSOR_V313_ADDRESS = "0xB70C4500a0afF02107eB983a348F22492
|
|
|
8
7
|
**/
|
|
9
8
|
const LIQUIDATION_APPROVAL_BUFFER = 50n;
|
|
10
9
|
//#endregion
|
|
11
|
-
export {
|
|
10
|
+
export { LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS };
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { DUST_THRESHOLD } from "../constants.js";
|
|
2
1
|
import { LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS } from "./constants.js";
|
|
3
2
|
import { LiquidationsService } from "./LiquidationsService.js";
|
|
4
3
|
import { MultichainLiquidationsService } from "./MultichainLiquidationsService.js";
|
|
5
4
|
import "./types.js";
|
|
6
|
-
export {
|
|
5
|
+
export { LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, LiquidationsService, MultichainLiquidationsService };
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, NO_VERSION } from "./address-provider.js";
|
|
2
2
|
import { ADDRESS_0X0, MULTICALL_ADDRESS, NATIVE_ADDRESS, NOT_DEPLOYED } from "./addresses.js";
|
|
3
3
|
import { BotPermissions, botPermissionsToString } from "./bot-permissions.js";
|
|
4
|
-
import { LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, WAD, WAD_DECIMALS_POW, halfRAY } from "./math.js";
|
|
4
|
+
import { DUST_THRESHOLD, LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, WAD, WAD_DECIMALS_POW, halfRAY } from "./math.js";
|
|
5
5
|
import { BLOCKS_PER_WEEK_BY_NETWORK, RAMP_DURATION_BY_NETWORK } from "./networks.js";
|
|
6
6
|
import { PERIPHERY_CONTRACTS } from "./periphery.js";
|
|
7
7
|
import { VERSION_RANGE_310, isV310, isVersionRange } from "./versions.js";
|
|
8
|
-
export { ADDRESS_0X0, ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, BLOCKS_PER_WEEK_BY_NETWORK, BotPermissions, LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, MULTICALL_ADDRESS, NATIVE_ADDRESS, NOT_DEPLOYED, NO_VERSION, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PERIPHERY_CONTRACTS, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, VERSION_RANGE_310, WAD, WAD_DECIMALS_POW, botPermissionsToString, halfRAY, isV310, isVersionRange };
|
|
8
|
+
export { ADDRESS_0X0, ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, BLOCKS_PER_WEEK_BY_NETWORK, BotPermissions, DUST_THRESHOLD, LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, MULTICALL_ADDRESS, NATIVE_ADDRESS, NOT_DEPLOYED, NO_VERSION, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PERIPHERY_CONTRACTS, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, VERSION_RANGE_310, WAD, WAD_DECIMALS_POW, botPermissionsToString, halfRAY, isV310, isVersionRange };
|
|
@@ -16,5 +16,9 @@ const PERCENTAGE_FACTOR = 10000n;
|
|
|
16
16
|
const PERCENTAGE_FACTOR_1KK = PERCENTAGE_FACTOR * PERCENTAGE_DECIMALS;
|
|
17
17
|
const LEVERAGE_DECIMALS = 100n;
|
|
18
18
|
const SLIPPAGE_DECIMALS = 100n;
|
|
19
|
+
/**
|
|
20
|
+
* Token balances at or below this threshold are treated as dust and ignored.
|
|
21
|
+
**/
|
|
22
|
+
const DUST_THRESHOLD = 10n;
|
|
19
23
|
//#endregion
|
|
20
|
-
export { LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, WAD, WAD_DECIMALS_POW, halfRAY };
|
|
24
|
+
export { DUST_THRESHOLD, LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, WAD, WAD_DECIMALS_POW, halfRAY };
|
package/dist/esm/sdk/index.js
CHANGED
|
@@ -15,7 +15,7 @@ import { etherscanApiUrl, etherscanUrl } from "./utils/etherscan.js";
|
|
|
15
15
|
import { ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, NO_VERSION } from "./constants/address-provider.js";
|
|
16
16
|
import { ADDRESS_0X0, MULTICALL_ADDRESS, NATIVE_ADDRESS, NOT_DEPLOYED } from "./constants/addresses.js";
|
|
17
17
|
import { BotPermissions, botPermissionsToString } from "./constants/bot-permissions.js";
|
|
18
|
-
import { LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, WAD, WAD_DECIMALS_POW, halfRAY } from "./constants/math.js";
|
|
18
|
+
import { DUST_THRESHOLD, LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, WAD, WAD_DECIMALS_POW, halfRAY } from "./constants/math.js";
|
|
19
19
|
import { BLOCKS_PER_WEEK_BY_NETWORK, RAMP_DURATION_BY_NETWORK } from "./constants/networks.js";
|
|
20
20
|
import { PERIPHERY_CONTRACTS } from "./constants/periphery.js";
|
|
21
21
|
import { VERSION_RANGE_310, isV310, isVersionRange } from "./constants/versions.js";
|
|
@@ -47,8 +47,9 @@ import { createAdapter } from "./market/adapters/createAdapter.js";
|
|
|
47
47
|
import { CreditConfiguratorV310Contract } from "./market/credit/CreditConfiguratorV310Contract.js";
|
|
48
48
|
import { CreditFacadeV310BaseContract, creditFacadeV310Abi as abi } from "./market/credit/CreditFacadeV310BaseContract.js";
|
|
49
49
|
import { CreditFacadeV310Contract } from "./market/credit/CreditFacadeV310Contract.js";
|
|
50
|
-
import { additionalBorrowApyBps, borrowApyBps, healthFactorBps, maxLeverage, positionLeverage, rayToBps, usdToNumber, utilizationBps } from "./market/math.js";
|
|
50
|
+
import { PARTIAL_LIQUIDATION_BUFFER_BPS, additionalBorrowApyBps, borrowApyBps, healthFactorBps, maxLeverage, minSeizedAmount, optimalHFForPartialLiquidation, optimalRepaidAmount, positionLeverage, rayToBps, usdToNumber, utilizationBps } from "./market/math.js";
|
|
51
51
|
import { CreditManagerV310Contract } from "./market/credit/CreditManagerV310Contract.js";
|
|
52
|
+
import { dominantCollateral, mustGetDominantCollateral } from "./market/credit/dominantCollateral.js";
|
|
52
53
|
import { CreditSuite } from "./market/credit/CreditSuite.js";
|
|
53
54
|
import { simulateMulticall } from "./utils/viem/simulateMulticall.js";
|
|
54
55
|
import { SimulateWithPriceUpdatesError, getSimulateWithPriceUpdatesError, simulateWithPriceUpdates } from "./utils/viem/simulateWithPriceUpdates.js";
|
|
@@ -102,8 +103,8 @@ import { SecuritizeRWAFactory } from "./market/rwa/securitize/SecuritizeRWAFacto
|
|
|
102
103
|
import { RWARegistry } from "./market/rwa/RWARegistry.js";
|
|
103
104
|
import { RWA_FACTORY_TYPES, isRWAFactory } from "./market/rwa/types.js";
|
|
104
105
|
import "./market/index.js";
|
|
105
|
-
import {
|
|
106
|
-
import {
|
|
106
|
+
import { CreditAccountCompressorV310Contract } from "./accounts/credit-account-compressor/CreditAccountCompressorV310Contract.js";
|
|
107
|
+
import { CreditAccountCompressor } from "./accounts/credit-account-compressor/CreditAccountCompressor.js";
|
|
107
108
|
import { CreditAccountsServiceV310 } from "./accounts/CreditAccountsServiceV310.js";
|
|
108
109
|
import { primaryInstantOutput } from "./accounts/intents/operations/claim-delayed/index.js";
|
|
109
110
|
import { CreditAccountOperationsService } from "./accounts/intents/index.js";
|
|
@@ -144,4 +145,4 @@ import { OnchainSDK, STATE_VERSION } from "./OnchainSDK.js";
|
|
|
144
145
|
import { MultichainSDK } from "./MultichainSDK.js";
|
|
145
146
|
import { attachOptionsSchema, onchainSDKOptionsSchema } from "./options.js";
|
|
146
147
|
import "./types/index.js";
|
|
147
|
-
export { ADDRESS_0X0, ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, AbstractLPPriceFeedContract, AbstractPriceFeedContract, AbstractWithdrawalCompressorContract, AddressMap, AddressProviderV310Contract, AddressSet, AssetsMap, BLOCKS_PER_WEEK_BY_NETWORK, BalancerStablePriceFeedContract, BalancerWeightedPriceFeedContract, BaseContract, BasePlugin, BigIntMath, BotPermissions, BoundedPriceFeedContract, ChainContractsRegister, ChainNotConfiguredError, CompositePriceFeedContract, Construct, ContractParseError, CreditAccountOperationsService, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, DUST_THRESHOLD, Erc4626PriceFeedContract, ExternalPriceFeedContract, GaugeContract, IERC20ZapperContract, IETHZapperContract, InvalidDelayedIntentError, LEVERAGE_DECIMALS, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, LinearInterestRateModelContract, LiquidationsService, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, MULTICALL_ADDRESS, MarketRegister, MarketSuite, MellowLRTPriceFeedContract, MidasLiquidatorContract, MissingSerializedParamsError, MultichainConstruct, MultichainLiquidationsService, MultichainOpportunitiesService, MultichainPositionsService, MultichainSDK, NATIVE_ADDRESS, NOT_DEPLOYED, NO_VERSION, NetworkType, OnchainSDK, OpportunitiesService, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PERIPHERY_CONTRACTS, PHANTOM_TOKEN_CONTRACT_TYPES, PHANTOM_TOKEN_MIDAS_REDEMPTION, PHANTOM_TOKEN_SECURITIZE_REDEMPTION, PRICE_DECIMALS, PRICE_DECIMALS_POW, PartialPriceFeedInitError, PendleTWAPPTPriceFeed, PlaceholderAdapterContract, PlaceholderContract, PluginStateVersionError, PoolService, PoolSuite, PoolV310Contract, PositionsService, PriceFeedRef, PriceFeedRegister, PriceOracleV310Contract, PythPriceFeed, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, RWARegistry, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_LIQUIDATOR_MIDAS, RWA_LIQUIDATOR_SECURITIZE, RWA_ON_DEMAND_LP_MONOPOLIZED, RWA_UNDERLYING_DEFAULT, RWA_UNDERLYING_ON_DEMAND, RedemptionLoggerV310Contract, RedstonePriceFeedContract, RouterV310Contract, SDKConstruct, SECONDS_PER_YEAR, SECURITIZE_REGISTER_VAULT_TYPES, SLIPPAGE_DECIMALS, STATE_VERSION, SUPPORTED_NETWORKS, SdkAlreadyAttachedError, SdkChainMismatchError, SdkMissingChainStateError, SdkNotAttachedError, SdkStateVersionMismatchError, SdkSyncFailedError, SecuritizeLiquidatorContract, SecuritizeRWAFactory, SimulateWithPriceUpdatesError, SimulationError, TokensMeta, TypedObjectUtils, UnsupportedZapperFunctionError, VERSION_RANGE_310, VotingContractStatus, WAD, WAD_DECIMALS_POW, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, WstETHPriceFeedContract, YearnPriceFeedContract, ZapperContract, ZeroPriceFeedContract, ZodAddress, ZodHex, additionalBorrowApyBps, assetsMap, attachOptionsSchema, borrowApyBps, botPermissionsToString, bytes32ToString, chains, childLogger, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, decodeDelayedIntent, detectNetwork, dominantCollateral, encodeDelayedIntent, estimateRawTxGas, etherscanApiUrl, etherscanUrl, executeDelegatedMulticalls, fetchPythPayloads, fetchRedstonePayloads, filterDust, filterDustUSD, findCuratorMarketConfigurator, fmtBinaryMask, formatBN, formatBNvalue, formatDuration, formatLeverage, formatNumberToString_, formatPercentage, formatTimestamp, functionArgsToMap, functionArgsToRecord, generateCastTraceCall, getAssetType, getCastTraceArgs, getChain, getCuratorName, getFunctionSignature, getNetworkType, getRawPriceUpdates, getSimulateWithPriceUpdatesError, getWithdrawalCompressorAddress, halfRAY, healthFactorBps, hexEq, hydrateAddressProvider, iCreditAccountAbi, isDust, isLPPriceFeed, isPublicNetwork, isRWAFactory, isRWAToken, isSunsetPool, isSunsetStrategy, isSupportedNetwork, isUpdatablePriceFeed, isV310, isVersionRange, json_parse, json_stringify, maxLeverage, numberWithCommas, onchainSDKOptionsSchema, percentFmt, positionLeverage, primaryInstantOutput, rayToBps, rayToNumber, retry, sendRawTx, shortAddress, shortHash, simulateCall, simulateMulticall, simulateWithPriceUpdates, toAddress, toBN, toBigInt, toClaimableWithdrawal, toPendingWithdrawal, toRequestableWithdrawal, toSignificant, toWithdrawalStatus, usdToNumber, utilizationBps, watchBlocksAsync };
|
|
148
|
+
export { ADDRESS_0X0, ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, AbstractLPPriceFeedContract, AbstractPriceFeedContract, AbstractWithdrawalCompressorContract, AddressMap, AddressProviderV310Contract, AddressSet, AssetsMap, BLOCKS_PER_WEEK_BY_NETWORK, BalancerStablePriceFeedContract, BalancerWeightedPriceFeedContract, BaseContract, BasePlugin, BigIntMath, BotPermissions, BoundedPriceFeedContract, ChainContractsRegister, ChainNotConfiguredError, CompositePriceFeedContract, Construct, ContractParseError, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, DUST_THRESHOLD, Erc4626PriceFeedContract, ExternalPriceFeedContract, GaugeContract, IERC20ZapperContract, IETHZapperContract, InvalidDelayedIntentError, LEVERAGE_DECIMALS, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, LinearInterestRateModelContract, LiquidationsService, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, MULTICALL_ADDRESS, MarketRegister, MarketSuite, MellowLRTPriceFeedContract, MidasLiquidatorContract, MissingSerializedParamsError, MultichainConstruct, MultichainLiquidationsService, MultichainOpportunitiesService, MultichainPositionsService, MultichainSDK, NATIVE_ADDRESS, NOT_DEPLOYED, NO_VERSION, NetworkType, OnchainSDK, OpportunitiesService, PARTIAL_LIQUIDATION_BUFFER_BPS, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PERIPHERY_CONTRACTS, PHANTOM_TOKEN_CONTRACT_TYPES, PHANTOM_TOKEN_MIDAS_REDEMPTION, PHANTOM_TOKEN_SECURITIZE_REDEMPTION, PRICE_DECIMALS, PRICE_DECIMALS_POW, PartialPriceFeedInitError, PendleTWAPPTPriceFeed, PlaceholderAdapterContract, PlaceholderContract, PluginStateVersionError, PoolService, PoolSuite, PoolV310Contract, PositionsService, PriceFeedRef, PriceFeedRegister, PriceOracleV310Contract, PythPriceFeed, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, RWARegistry, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_LIQUIDATOR_MIDAS, RWA_LIQUIDATOR_SECURITIZE, RWA_ON_DEMAND_LP_MONOPOLIZED, RWA_UNDERLYING_DEFAULT, RWA_UNDERLYING_ON_DEMAND, RedemptionLoggerV310Contract, RedstonePriceFeedContract, RouterV310Contract, SDKConstruct, SECONDS_PER_YEAR, SECURITIZE_REGISTER_VAULT_TYPES, SLIPPAGE_DECIMALS, STATE_VERSION, SUPPORTED_NETWORKS, SdkAlreadyAttachedError, SdkChainMismatchError, SdkMissingChainStateError, SdkNotAttachedError, SdkStateVersionMismatchError, SdkSyncFailedError, SecuritizeLiquidatorContract, SecuritizeRWAFactory, SimulateWithPriceUpdatesError, SimulationError, TokensMeta, TypedObjectUtils, UnsupportedZapperFunctionError, VERSION_RANGE_310, VotingContractStatus, WAD, WAD_DECIMALS_POW, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, WstETHPriceFeedContract, YearnPriceFeedContract, ZapperContract, ZeroPriceFeedContract, ZodAddress, ZodHex, additionalBorrowApyBps, assetsMap, attachOptionsSchema, borrowApyBps, botPermissionsToString, bytes32ToString, chains, childLogger, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, decodeDelayedIntent, detectNetwork, dominantCollateral, encodeDelayedIntent, estimateRawTxGas, etherscanApiUrl, etherscanUrl, executeDelegatedMulticalls, fetchPythPayloads, fetchRedstonePayloads, filterDust, filterDustUSD, findCuratorMarketConfigurator, fmtBinaryMask, formatBN, formatBNvalue, formatDuration, formatLeverage, formatNumberToString_, formatPercentage, formatTimestamp, functionArgsToMap, functionArgsToRecord, generateCastTraceCall, getAssetType, getCastTraceArgs, getChain, getCuratorName, getFunctionSignature, getNetworkType, getRawPriceUpdates, getSimulateWithPriceUpdatesError, getWithdrawalCompressorAddress, halfRAY, healthFactorBps, hexEq, hydrateAddressProvider, iCreditAccountAbi, isDust, isLPPriceFeed, isPublicNetwork, isRWAFactory, isRWAToken, isSunsetPool, isSunsetStrategy, isSupportedNetwork, isUpdatablePriceFeed, isV310, isVersionRange, json_parse, json_stringify, maxLeverage, minSeizedAmount, mustGetDominantCollateral, numberWithCommas, onchainSDKOptionsSchema, optimalHFForPartialLiquidation, optimalRepaidAmount, percentFmt, positionLeverage, primaryInstantOutput, rayToBps, rayToNumber, retry, sendRawTx, shortAddress, shortHash, simulateCall, simulateMulticall, simulateWithPriceUpdates, toAddress, toBN, toBigInt, toClaimableWithdrawal, toPendingWithdrawal, toRequestableWithdrawal, toSignificant, toWithdrawalStatus, usdToNumber, utilizationBps, watchBlocksAsync };
|
|
@@ -11,6 +11,7 @@ import "../utils/viem/index.js";
|
|
|
11
11
|
import { MarketConfiguratorContract } from "./MarketConfiguratorContract.js";
|
|
12
12
|
import { MarketSuite } from "./MarketSuite.js";
|
|
13
13
|
import { ZapperRegister } from "./ZapperRegister.js";
|
|
14
|
+
import { isAddressEqual } from "viem";
|
|
14
15
|
//#region src/sdk/market/MarketRegister.ts
|
|
15
16
|
/**
|
|
16
17
|
* Central registry of all Gearbox markets on the current chain.
|
|
@@ -179,6 +180,15 @@ var MarketRegister = class extends ZapperRegister {
|
|
|
179
180
|
throw new Error(`cannot find credit manager ${creditManager}`);
|
|
180
181
|
}
|
|
181
182
|
/**
|
|
183
|
+
* Finds a credit facade by its on-chain address.
|
|
184
|
+
* @param creditFacade - Credit facade contract address.
|
|
185
|
+
* @throws If no loaded market contains the given credit facade.
|
|
186
|
+
**/
|
|
187
|
+
findCreditFacade(creditFacade) {
|
|
188
|
+
for (const cm of this.creditManagers) if (isAddressEqual(cm.creditFacade.address, creditFacade)) return cm.creditFacade;
|
|
189
|
+
throw new Error(`cannot find credit facade ${creditFacade}`);
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
182
192
|
* Finds the market that contains the given credit manager.
|
|
183
193
|
* @param creditManager - Credit manager contract address.
|
|
184
194
|
* @throws If no loaded market contains the given credit manager.
|