@gearbox-protocol/sdk 18.4.0 → 18.4.1-aave.10
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/abi/rwa/iSecuritizeRWAFactory.js +15 -0
- package/dist/cjs/model/errors/index.js +1 -0
- package/dist/cjs/model/errors/operation-errors.js +9 -0
- package/dist/cjs/model/index.js +2 -4
- package/dist/cjs/offchain/GearboxAPI.js +0 -7
- package/dist/cjs/offchain/index.js +0 -3
- package/dist/cjs/onchain/accounts/bots/AccountBotsService.js +29 -0
- package/dist/cjs/onchain/accounts/bots/PeripheryCompressorV310Contract.js +2 -1
- package/dist/cjs/onchain/accounts/index.js +1 -1
- package/dist/cjs/onchain/accounts/intents/index.js +33 -0
- package/dist/cjs/onchain/accounts/intents/operations.js +21 -0
- package/dist/cjs/onchain/accounts/intents/plan.js +55 -0
- package/dist/cjs/onchain/accounts/intents/readAaveHoldings.js +56 -0
- package/dist/cjs/onchain/accounts/intents/realize.js +84 -2
- package/dist/cjs/onchain/accounts/intents/testing/market.js +1 -0
- package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +3 -2
- package/dist/cjs/onchain/accounts/intents/utils/ledger.js +8 -0
- package/dist/cjs/onchain/chain/chains.js +4 -0
- package/dist/cjs/onchain/index.js +25 -1
- package/dist/cjs/onchain/market/ZapperRegister.js +1 -1
- package/dist/cjs/onchain/market/adapters/abi/aave/iAaveHorizonBridge.js +94 -0
- package/dist/cjs/onchain/market/adapters/abi/aave/iAaveOracle.js +20 -0
- package/dist/cjs/onchain/market/adapters/abi/aave/iAaveV3Pool.js +278 -0
- package/dist/cjs/onchain/market/adapters/abi/aave/iPoolAddressesProvider.js +11 -0
- package/dist/cjs/onchain/market/adapters/abi/aave/iVariableDebtToken.js +17 -0
- package/dist/cjs/onchain/market/adapters/abi/aave/index.js +11 -0
- package/dist/cjs/onchain/market/adapters/abi/actionAbi.js +1 -0
- package/dist/cjs/onchain/market/adapters/abi/adapters/iAaveHorizonBridgeAdapter.js +224 -0
- package/dist/cjs/onchain/market/adapters/abi/adapters/iAaveV3PoolAdapter.js +177 -0
- package/dist/cjs/onchain/market/adapters/abi/adapters/index.js +4 -0
- package/dist/cjs/onchain/market/adapters/abi/conctructorAbi.js +2 -0
- package/dist/cjs/onchain/market/adapters/abi/index.js +17 -0
- package/dist/cjs/onchain/market/adapters/abi/securitize/iSecuritizeNAVProvider.js +15 -0
- package/dist/cjs/onchain/market/adapters/abi/securitize/index.js +2 -0
- package/dist/cjs/onchain/market/adapters/contracts/AaveHorizonBridgeAdapterContract.js +218 -0
- package/dist/cjs/onchain/market/adapters/contracts/AaveV3PoolAdapterContract.js +213 -0
- package/dist/cjs/onchain/market/adapters/contracts/AbstractAdapter.js +8 -0
- package/dist/cjs/onchain/market/adapters/contracts/SecuritizeRedemptionGatewayAdapterContract.js +42 -5
- package/dist/cjs/onchain/market/adapters/contracts/index.js +4 -0
- package/dist/cjs/onchain/market/adapters/createAdapter.js +4 -0
- package/dist/cjs/onchain/market/adapters/index.js +20 -0
- package/dist/cjs/onchain/market/adapters/types.js +2 -0
- package/dist/cjs/onchain/market/index.js +20 -0
- package/dist/cjs/onchain/market/rwa/securitize/SecuritizeRWAFactory.js +9 -0
- package/dist/cjs/onchain/positions/MultichainPositionsService.js +15 -0
- package/dist/cjs/onchain/positions/PositionsService.js +31 -0
- package/dist/cjs/onchain/positions/aaveMoveCalls.js +45 -0
- package/dist/cjs/onchain/positions/projectAavePosition.js +178 -0
- package/dist/cjs/onchain/positions/readAavePosition.js +152 -0
- package/dist/cjs/onchain/preview/index.js +2 -0
- package/dist/cjs/onchain/preview/preview/aaveBridgeBorrows.js +24 -0
- package/dist/cjs/onchain/preview/preview/aaveMoveStart.js +27 -0
- package/dist/cjs/onchain/preview/preview/index.js +2 -0
- package/dist/cjs/onchain/preview/preview/loadAdapterReplayState.js +17 -0
- package/dist/cjs/onchain/preview/preview/previewAdjustStrategyPosition.js +3 -0
- package/dist/cjs/onchain/preview/preview/previewExitOrRepayStrategyPosition.js +5 -2
- package/dist/cjs/onchain/preview/preview/previewOpenStrategyPosition.js +4 -1
- package/dist/cjs/onchain/preview/preview/previewOperation.js +33 -8
- package/dist/cjs/onchain/validation/bundles/checkAaveDelegation.js +54 -0
- package/dist/cjs/onchain/validation/bundles/checkCreditOperation.js +36 -11
- package/dist/cjs/onchain/validation/bundles/index.js +2 -0
- package/dist/cjs/onchain/validation/checkOperation.js +16 -4
- package/dist/cjs/onchain/validation/index.js +2 -0
- package/dist/cjs/sdk/GearboxSDK.js +0 -9
- package/dist/cjs/sdk/execute/ExecuteApi.js +1 -0
- package/dist/cjs/sdk/positions/PositionsNamespace.js +6 -0
- package/dist/cjs/sdk/prepare/PrepareApi.js +98 -0
- package/dist/cjs/sdk/preview/PreviewNamespace.js +42 -0
- package/dist/esm/abi/rwa/iSecuritizeRWAFactory.js +15 -0
- package/dist/esm/model/errors/index.js +2 -2
- package/dist/esm/model/errors/operation-errors.js +9 -1
- package/dist/esm/model/index.js +3 -4
- package/dist/esm/offchain/GearboxAPI.js +0 -7
- package/dist/esm/offchain/index.js +1 -3
- package/dist/esm/onchain/accounts/bots/AccountBotsService.js +29 -0
- package/dist/esm/onchain/accounts/bots/PeripheryCompressorV310Contract.js +1 -1
- package/dist/esm/onchain/accounts/index.js +1 -1
- package/dist/esm/onchain/accounts/intents/index.js +34 -1
- package/dist/esm/onchain/accounts/intents/operations.js +20 -1
- package/dist/esm/onchain/accounts/intents/plan.js +56 -2
- package/dist/esm/onchain/accounts/intents/readAaveHoldings.js +55 -0
- package/dist/esm/onchain/accounts/intents/realize.js +86 -4
- package/dist/esm/onchain/accounts/intents/testing/market.js +1 -0
- package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +3 -2
- package/dist/esm/onchain/accounts/intents/utils/ledger.js +8 -0
- package/dist/esm/onchain/chain/chains.js +4 -0
- package/dist/esm/onchain/index.js +14 -2
- package/dist/esm/onchain/market/ZapperRegister.js +1 -1
- package/dist/esm/onchain/market/adapters/abi/aave/iAaveHorizonBridge.js +93 -0
- package/dist/esm/onchain/market/adapters/abi/aave/iAaveOracle.js +19 -0
- package/dist/esm/onchain/market/adapters/abi/aave/iAaveV3Pool.js +277 -0
- package/dist/esm/onchain/market/adapters/abi/aave/iPoolAddressesProvider.js +10 -0
- package/dist/esm/onchain/market/adapters/abi/aave/iVariableDebtToken.js +16 -0
- package/dist/esm/onchain/market/adapters/abi/aave/index.js +6 -0
- package/dist/esm/onchain/market/adapters/abi/actionAbi.js +1 -0
- package/dist/esm/onchain/market/adapters/abi/adapters/iAaveHorizonBridgeAdapter.js +223 -0
- package/dist/esm/onchain/market/adapters/abi/adapters/iAaveV3PoolAdapter.js +176 -0
- package/dist/esm/onchain/market/adapters/abi/adapters/index.js +3 -1
- package/dist/esm/onchain/market/adapters/abi/conctructorAbi.js +2 -0
- package/dist/esm/onchain/market/adapters/abi/index.js +10 -1
- package/dist/esm/onchain/market/adapters/abi/securitize/iSecuritizeNAVProvider.js +14 -0
- package/dist/esm/onchain/market/adapters/abi/securitize/index.js +2 -1
- package/dist/esm/onchain/market/adapters/contracts/AaveHorizonBridgeAdapterContract.js +217 -0
- package/dist/esm/onchain/market/adapters/contracts/AaveV3PoolAdapterContract.js +212 -0
- package/dist/esm/onchain/market/adapters/contracts/AbstractAdapter.js +8 -0
- package/dist/esm/onchain/market/adapters/contracts/SecuritizeRedemptionGatewayAdapterContract.js +43 -6
- package/dist/esm/onchain/market/adapters/contracts/index.js +3 -1
- package/dist/esm/onchain/market/adapters/createAdapter.js +4 -0
- package/dist/esm/onchain/market/adapters/index.js +11 -1
- package/dist/esm/onchain/market/adapters/types.js +2 -0
- package/dist/esm/onchain/market/index.js +11 -1
- package/dist/esm/onchain/market/rwa/securitize/SecuritizeRWAFactory.js +9 -0
- package/dist/esm/onchain/positions/MultichainPositionsService.js +15 -0
- package/dist/esm/onchain/positions/PositionsService.js +31 -0
- package/dist/esm/onchain/positions/aaveMoveCalls.js +44 -0
- package/dist/esm/onchain/positions/projectAavePosition.js +177 -0
- package/dist/esm/onchain/positions/readAavePosition.js +151 -0
- package/dist/esm/onchain/preview/index.js +2 -1
- package/dist/esm/onchain/preview/preview/aaveBridgeBorrows.js +23 -0
- package/dist/esm/onchain/preview/preview/aaveMoveStart.js +26 -0
- package/dist/esm/onchain/preview/preview/index.js +2 -1
- package/dist/esm/onchain/preview/preview/loadAdapterReplayState.js +16 -0
- package/dist/esm/onchain/preview/preview/previewAdjustStrategyPosition.js +3 -0
- package/dist/esm/onchain/preview/preview/previewExitOrRepayStrategyPosition.js +5 -2
- package/dist/esm/onchain/preview/preview/previewOpenStrategyPosition.js +4 -1
- package/dist/esm/onchain/preview/preview/previewOperation.js +33 -8
- package/dist/esm/onchain/validation/bundles/checkAaveDelegation.js +53 -0
- package/dist/esm/onchain/validation/bundles/checkCreditOperation.js +36 -11
- package/dist/esm/onchain/validation/bundles/index.js +2 -1
- package/dist/esm/onchain/validation/checkOperation.js +16 -4
- package/dist/esm/onchain/validation/index.js +2 -1
- package/dist/esm/sdk/GearboxSDK.js +0 -9
- package/dist/esm/sdk/execute/ExecuteApi.js +1 -0
- package/dist/esm/sdk/positions/PositionsNamespace.js +6 -0
- package/dist/esm/sdk/prepare/PrepareApi.js +99 -1
- package/dist/esm/sdk/preview/PreviewNamespace.js +42 -0
- package/dist/types/abi/rwa/iSecuritizeRWAFactory.d.ts +14 -0
- package/dist/types/model/aave.d.ts +89 -0
- package/dist/types/model/analytics.d.ts +2 -2
- package/dist/types/model/errors/index.d.ts +2 -2
- package/dist/types/model/errors/operation-errors.d.ts +19 -0
- package/dist/types/model/index.d.ts +6 -7
- package/dist/types/model/positions.d.ts +1 -1
- package/dist/types/model/previews.d.ts +31 -0
- package/dist/types/offchain/AbstractOffchainNamespace.d.ts +1 -1
- package/dist/types/offchain/GearboxAPI.d.ts +0 -6
- package/dist/types/offchain/analytics/OffchainAnalytics.d.ts +1 -1
- package/dist/types/offchain/analytics/types.d.ts +1 -1
- package/dist/types/offchain/index.d.ts +1 -3
- package/dist/types/offchain/opportunities/OffchainOpportunities.d.ts +1 -1
- package/dist/types/offchain/opportunities/types.d.ts +1 -1
- package/dist/types/offchain/positions/OffchainPositions.d.ts +1 -1
- package/dist/types/offchain/positions/types.d.ts +1 -1
- package/dist/types/onchain/accounts/bots/AccountBotsService.d.ts +11 -1
- package/dist/types/onchain/accounts/bots/index.d.ts +2 -2
- package/dist/types/onchain/accounts/bots/types.d.ts +7 -1
- package/dist/types/onchain/accounts/index.d.ts +3 -3
- package/dist/types/onchain/accounts/intents/index.d.ts +21 -3
- package/dist/types/onchain/accounts/intents/operations.d.ts +41 -1
- package/dist/types/onchain/accounts/intents/plan.d.ts +32 -3
- package/dist/types/onchain/accounts/intents/readAaveHoldings.d.ts +16 -0
- package/dist/types/onchain/accounts/intents/testing/market.d.ts +4 -0
- package/dist/types/onchain/accounts/intents/testing/sdk-mock.d.ts +4 -0
- package/dist/types/onchain/accounts/intents/types.d.ts +42 -0
- package/dist/types/onchain/index.d.ts +16 -4
- package/dist/types/onchain/market/adapters/abi/aave/iAaveHorizonBridge.d.ts +83 -0
- package/dist/types/onchain/market/adapters/abi/aave/iAaveOracle.d.ts +22 -0
- package/dist/types/onchain/market/adapters/abi/aave/iAaveV3Pool.d.ts +229 -0
- package/dist/types/onchain/market/adapters/abi/aave/iPoolAddressesProvider.d.ts +11 -0
- package/dist/types/onchain/market/adapters/abi/aave/iVariableDebtToken.d.ts +17 -0
- package/dist/types/onchain/market/adapters/abi/aave/index.d.ts +6 -0
- package/dist/types/onchain/market/adapters/abi/adapters/iAaveHorizonBridgeAdapter.d.ts +207 -0
- package/dist/types/onchain/market/adapters/abi/adapters/iAaveV3PoolAdapter.d.ts +172 -0
- package/dist/types/onchain/market/adapters/abi/adapters/index.d.ts +3 -1
- package/dist/types/onchain/market/adapters/abi/index.d.ts +10 -1
- package/dist/types/onchain/market/adapters/abi/securitize/iSecuritizeNAVProvider.d.ts +13 -0
- package/dist/types/onchain/market/adapters/abi/securitize/index.d.ts +2 -1
- package/dist/types/onchain/market/adapters/contracts/AaveHorizonBridgeAdapterContract.d.ts +361 -0
- package/dist/types/onchain/market/adapters/contracts/AaveV3PoolAdapterContract.d.ts +455 -0
- package/dist/types/onchain/market/adapters/contracts/AbstractAdapter.d.ts +8 -0
- package/dist/types/onchain/market/adapters/contracts/SecuritizeRedemptionGatewayAdapterContract.d.ts +19 -4
- package/dist/types/onchain/market/adapters/contracts/index.d.ts +3 -1
- package/dist/types/onchain/market/adapters/index.d.ts +11 -1
- package/dist/types/onchain/market/adapters/types.d.ts +3 -1
- package/dist/types/onchain/market/index.d.ts +11 -1
- package/dist/types/onchain/market/rwa/securitize/SecuritizeRWAFactory.d.ts +20 -0
- package/dist/types/onchain/market/rwa/types.d.ts +6 -0
- package/dist/types/onchain/positions/MultichainPositionsService.d.ts +7 -1
- package/dist/types/onchain/positions/PositionsService.d.ts +16 -2
- package/dist/types/onchain/positions/aaveMoveCalls.d.ts +30 -0
- package/dist/types/onchain/positions/index.d.ts +2 -2
- package/dist/types/onchain/positions/projectAavePosition.d.ts +46 -0
- package/dist/types/onchain/positions/readAavePosition.d.ts +22 -0
- package/dist/types/onchain/positions/types.d.ts +25 -0
- package/dist/types/onchain/preview/index.d.ts +2 -1
- package/dist/types/onchain/preview/preview/aaveBridgeBorrows.d.ts +15 -0
- package/dist/types/onchain/preview/preview/aaveMoveStart.d.ts +18 -0
- package/dist/types/onchain/preview/preview/index.d.ts +2 -1
- package/dist/types/onchain/preview/preview/loadAdapterReplayState.d.ts +13 -0
- package/dist/types/onchain/validation/bundles/checkAaveDelegation.d.ts +21 -0
- package/dist/types/onchain/validation/bundles/checkCreditOperation.d.ts +2 -2
- package/dist/types/onchain/validation/bundles/index.d.ts +2 -1
- package/dist/types/onchain/validation/index.d.ts +2 -1
- package/dist/types/sdk/GearboxSDK.d.ts +1 -8
- package/dist/types/sdk/analytics/AnalyticsNamespace.d.ts +1 -1
- package/dist/types/sdk/analytics/types.d.ts +1 -1
- package/dist/types/sdk/execute/types.d.ts +7 -5
- package/dist/types/sdk/index.d.ts +3 -3
- package/dist/types/sdk/opportunities/OpportunitiesNamespace.d.ts +1 -1
- package/dist/types/sdk/opportunities/types.d.ts +1 -1
- package/dist/types/sdk/positions/PositionsNamespace.d.ts +7 -2
- package/dist/types/sdk/positions/types.d.ts +10 -2
- package/dist/types/sdk/prepare/PrepareApi.d.ts +11 -3
- package/dist/types/sdk/prepare/index.d.ts +2 -2
- package/dist/types/sdk/prepare/types.d.ts +116 -1
- package/dist/types/sdk/preview/PreviewNamespace.d.ts +5 -1
- package/dist/types/sdk/preview/types.d.ts +12 -1
- package/dist/types/sdk/types.d.ts +0 -20
- package/package.json +1 -1
- package/dist/cjs/model/notices.schema.js +0 -25
- package/dist/cjs/offchain/notices/OffchainNotices.js +0 -27
- package/dist/cjs/offchain/notices/index.js +0 -3
- package/dist/esm/model/notices.schema.js +0 -23
- package/dist/esm/offchain/notices/OffchainNotices.js +0 -26
- package/dist/esm/offchain/notices/index.js +0 -1
- package/dist/types/model/notices.d.ts +0 -28
- package/dist/types/model/notices.schema.d.ts +0 -22
- package/dist/types/offchain/notices/OffchainNotices.d.ts +0 -18
- package/dist/types/offchain/notices/index.d.ts +0 -2
- /package/dist/cjs/model/{notices.js → aave.js} +0 -0
- /package/dist/esm/model/{notices.js → aave.js} +0 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { MAX_UINT16, PERCENTAGE_FACTOR, PRICE_DECIMALS, RAY, SECONDS_PER_YEAR } from "../constants/math.js";
|
|
2
|
+
import { iAaveOracleAbi } from "../market/adapters/abi/aave/iAaveOracle.js";
|
|
3
|
+
import { iAaveV3PoolAbi } from "../market/adapters/abi/aave/iAaveV3Pool.js";
|
|
4
|
+
import { iPoolAddressesProviderAbi } from "../market/adapters/abi/aave/iPoolAddressesProvider.js";
|
|
5
|
+
import "../market/adapters/abi/aave/index.js";
|
|
6
|
+
import { AaveHorizonBridgeAdapterContract } from "../market/adapters/contracts/AaveHorizonBridgeAdapterContract.js";
|
|
7
|
+
import { AaveV3PoolAdapterContract } from "../market/adapters/contracts/AaveV3PoolAdapterContract.js";
|
|
8
|
+
import { calcPositionLeverage } from "../market/math.js";
|
|
9
|
+
import { isAddressEqual } from "viem";
|
|
10
|
+
//#region src/onchain/positions/projectAavePosition.ts
|
|
11
|
+
/**
|
|
12
|
+
* Where an opening lands once it has moved to Aave Horizon, from the snapshot
|
|
13
|
+
* of the credit account it is built in.
|
|
14
|
+
*
|
|
15
|
+
* The move supplies the account's RWA to the pool and borrows the Gearbox
|
|
16
|
+
* debt against it on the owner's behalf, so the Aave side is read off
|
|
17
|
+
* the pool for `owner`: the reserve's LTV and liquidation threshold (its eMode
|
|
18
|
+
* category's, where the owner is in one that lists it), the Aave oracle's
|
|
19
|
+
* prices, the variable borrow rate of the underlying, and whatever the owner
|
|
20
|
+
* already holds and owes there. `healthFactor` and `liquidationPrice` are of
|
|
21
|
+
* that whole position; the values describe this opening alone.
|
|
22
|
+
*
|
|
23
|
+
* The RWA is either on the account already, and the position is on Aave at
|
|
24
|
+
* once (the opening moves it in its own transaction), or still being minted
|
|
25
|
+
* and moved by the finalizer bot once it settles: then the
|
|
26
|
+
* account holds the withdrawal phantom token of a delayed operation the
|
|
27
|
+
* withdrawal compressor lists for the credit manager, the mint takes that
|
|
28
|
+
* operation's `withdrawalLength` and is assumed to come out one for one, and
|
|
29
|
+
* the Gearbox debt accrues interest at the credit manager's rate meanwhile.
|
|
30
|
+
*
|
|
31
|
+
* `undefined` when the credit manager cannot move the account to Aave: no
|
|
32
|
+
* pool adapter lists an asset of the account or the RWA it is being minted
|
|
33
|
+
* into, or no bridge adapter takes its aToken against the underlying.
|
|
34
|
+
**/
|
|
35
|
+
async function projectAavePosition(sdk, snapshot, owner) {
|
|
36
|
+
const suite = sdk.marketRegister.findCreditManager(snapshot.creditManager);
|
|
37
|
+
const market = sdk.marketRegister.findByCreditManager(snapshot.creditManager);
|
|
38
|
+
const underlying = market.unwrappedUnderlying;
|
|
39
|
+
const adapters = suite.creditManager.adapters.values();
|
|
40
|
+
const poolAdapters = adapters.filter((p) => p instanceof AaveV3PoolAdapterContract);
|
|
41
|
+
const compressor = sdk.withdrawalCompressor;
|
|
42
|
+
const delayed = compressor?.state ? compressor.getWithdrawableAssets(snapshot.creditManager) : [];
|
|
43
|
+
let collateral;
|
|
44
|
+
let mintDuration = 0;
|
|
45
|
+
let poolAdapter;
|
|
46
|
+
for (const a of snapshot.assets) {
|
|
47
|
+
if (a.balance <= 10n || isAddressEqual(a.token, underlying)) continue;
|
|
48
|
+
const mint = delayed.find((d) => isAddressEqual(d.withdrawalPhantomToken, a.token));
|
|
49
|
+
const token = mint ? mint.underlying : a.token;
|
|
50
|
+
poolAdapter = poolAdapters.find((p) => p.isAssetAllowed(token));
|
|
51
|
+
if (poolAdapter) {
|
|
52
|
+
collateral = {
|
|
53
|
+
token,
|
|
54
|
+
balance: a.balance
|
|
55
|
+
};
|
|
56
|
+
mintDuration = mint ? Number(mint.withdrawalLength) : 0;
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (!collateral || !poolAdapter) return;
|
|
61
|
+
const pool = poolAdapter.targetContract;
|
|
62
|
+
const [rwaReserve, debtReserve, account, eMode, provider] = await sdk.client.multicall({
|
|
63
|
+
contracts: [
|
|
64
|
+
{
|
|
65
|
+
address: pool,
|
|
66
|
+
abi: iAaveV3PoolAbi,
|
|
67
|
+
functionName: "getReserveData",
|
|
68
|
+
args: [collateral.token]
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
address: pool,
|
|
72
|
+
abi: iAaveV3PoolAbi,
|
|
73
|
+
functionName: "getReserveData",
|
|
74
|
+
args: [underlying]
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
address: pool,
|
|
78
|
+
abi: iAaveV3PoolAbi,
|
|
79
|
+
functionName: "getUserAccountData",
|
|
80
|
+
args: [owner]
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
address: pool,
|
|
84
|
+
abi: iAaveV3PoolAbi,
|
|
85
|
+
functionName: "getUserEMode",
|
|
86
|
+
args: [owner]
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
address: pool,
|
|
90
|
+
abi: iAaveV3PoolAbi,
|
|
91
|
+
functionName: "ADDRESSES_PROVIDER"
|
|
92
|
+
}
|
|
93
|
+
],
|
|
94
|
+
allowFailure: false,
|
|
95
|
+
batchSize: 0
|
|
96
|
+
});
|
|
97
|
+
const bridgeAdapter = adapters.find((b) => b instanceof AaveHorizonBridgeAdapterContract && b.isATokenAllowed(rwaReserve.aTokenAddress) && b.isDebtTokenAllowed(underlying));
|
|
98
|
+
if (!bridgeAdapter) return;
|
|
99
|
+
const oracle = await sdk.client.readContract({
|
|
100
|
+
address: provider,
|
|
101
|
+
abi: iPoolAddressesProviderAbi,
|
|
102
|
+
functionName: "getPriceOracle"
|
|
103
|
+
});
|
|
104
|
+
const [[rwaPrice, underlyingPrice], categoryParams] = await Promise.all([sdk.client.readContract({
|
|
105
|
+
address: oracle,
|
|
106
|
+
abi: iAaveOracleAbi,
|
|
107
|
+
functionName: "getAssetsPrices",
|
|
108
|
+
args: [[collateral.token, underlying]]
|
|
109
|
+
}), eMode > 0n ? sdk.client.multicall({
|
|
110
|
+
contracts: [{
|
|
111
|
+
address: pool,
|
|
112
|
+
abi: iAaveV3PoolAbi,
|
|
113
|
+
functionName: "getEModeCategoryCollateralConfig",
|
|
114
|
+
args: [Number(eMode)]
|
|
115
|
+
}, {
|
|
116
|
+
address: pool,
|
|
117
|
+
abi: iAaveV3PoolAbi,
|
|
118
|
+
functionName: "getEModeCategoryCollateralBitmap",
|
|
119
|
+
args: [Number(eMode)]
|
|
120
|
+
}],
|
|
121
|
+
allowFailure: false,
|
|
122
|
+
batchSize: 0
|
|
123
|
+
}) : void 0]);
|
|
124
|
+
const rwaConfig = rwaReserve.configuration.data;
|
|
125
|
+
let ltv = rwaConfig & 65535n;
|
|
126
|
+
let liquidationThreshold = rwaConfig >> 16n & 65535n;
|
|
127
|
+
const [category, bitmap] = categoryParams ?? [];
|
|
128
|
+
if (category && bitmap && bitmap >> BigInt(rwaReserve.id) & 1n) {
|
|
129
|
+
ltv = BigInt(category.ltv);
|
|
130
|
+
liquidationThreshold = BigInt(category.liquidationThreshold);
|
|
131
|
+
}
|
|
132
|
+
const rwaScale = 10n ** (rwaConfig >> 48n & 255n);
|
|
133
|
+
const underlyingScale = 10n ** (debtReserve.configuration.data >> 48n & 255n);
|
|
134
|
+
const collateralBase = account[0];
|
|
135
|
+
const debtBase = account[1];
|
|
136
|
+
const currentLiquidationThreshold = account[3];
|
|
137
|
+
const currentLtv = account[4];
|
|
138
|
+
const gearboxPool = { availableLiquidityChange: -snapshot.totalDebt };
|
|
139
|
+
const gearboxRate = sdk.positions.metrics(snapshot, gearboxPool).borrowRate.totalOnDebt;
|
|
140
|
+
const interest = snapshot.totalDebt * BigInt(gearboxRate) * BigInt(mintDuration) / (PERCENTAGE_FACTOR * BigInt(SECONDS_PER_YEAR));
|
|
141
|
+
const totalDebt = snapshot.totalDebt + interest;
|
|
142
|
+
const suppliedBase = collateral.balance * rwaPrice / rwaScale;
|
|
143
|
+
const owedBase = debtBase + ceilDiv(totalDebt * underlyingPrice, underlyingScale);
|
|
144
|
+
const weightedLiquidation = collateralBase * currentLiquidationThreshold + suppliedBase * liquidationThreshold;
|
|
145
|
+
const borrowableBase = (collateralBase * currentLtv + suppliedBase * ltv) / PERCENTAGE_FACTOR;
|
|
146
|
+
const totalValue = collateral.balance * rwaPrice * underlyingScale / (rwaScale * underlyingPrice);
|
|
147
|
+
const rate = Number(debtReserve.currentVariableBorrowRate * PERCENTAGE_FACTOR / RAY);
|
|
148
|
+
const uncovered = owedBase * PERCENTAGE_FACTOR - collateralBase * currentLiquidationThreshold;
|
|
149
|
+
const liquidationPrice = liquidationThreshold === 0n ? null : uncovered <= 0n ? 0n : uncovered * rwaScale * PRICE_DECIMALS / (collateral.balance * liquidationThreshold * underlyingPrice);
|
|
150
|
+
return {
|
|
151
|
+
aave: {
|
|
152
|
+
totalValue: market.toUnderlyingAmount(totalValue),
|
|
153
|
+
totalDebt: market.toUnderlyingAmount(totalDebt),
|
|
154
|
+
netValue: market.toUnderlyingAmount(totalValue - totalDebt),
|
|
155
|
+
assets: [market.priceOracle.toTokenAmount(collateral.token, collateral.balance)],
|
|
156
|
+
healthFactor: Number(owedBase > 0n ? weightedLiquidation / owedBase : MAX_UINT16),
|
|
157
|
+
liquidationPrice,
|
|
158
|
+
borrowRate: {
|
|
159
|
+
total: totalValue > 0n ? Number(BigInt(rate) * totalDebt / totalValue) : 0,
|
|
160
|
+
totalOnDebt: rate,
|
|
161
|
+
base: rate,
|
|
162
|
+
quotas: []
|
|
163
|
+
},
|
|
164
|
+
leverage: calcPositionLeverage(totalValue, totalDebt),
|
|
165
|
+
mintPeriodInterest: market.toUnderlyingAmount(interest),
|
|
166
|
+
mintDuration,
|
|
167
|
+
estLiveAt: Number(sdk.timestamp) + mintDuration,
|
|
168
|
+
bridge: bridgeAdapter.bridge
|
|
169
|
+
},
|
|
170
|
+
maxDebt: borrowableBase > debtBase ? (borrowableBase - debtBase) * underlyingScale / underlyingPrice : 0n
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
function ceilDiv(a, b) {
|
|
174
|
+
return (a + b - 1n) / b;
|
|
175
|
+
}
|
|
176
|
+
//#endregion
|
|
177
|
+
export { projectAavePosition };
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { PERCENTAGE_FACTOR, PRICE_DECIMALS, RAY } from "../constants/math.js";
|
|
2
|
+
import { iAaveOracleAbi } from "../market/adapters/abi/aave/iAaveOracle.js";
|
|
3
|
+
import { iAaveV3PoolAbi } from "../market/adapters/abi/aave/iAaveV3Pool.js";
|
|
4
|
+
import { iPoolAddressesProviderAbi } from "../market/adapters/abi/aave/iPoolAddressesProvider.js";
|
|
5
|
+
import "../market/adapters/abi/aave/index.js";
|
|
6
|
+
import { AaveHorizonBridgeAdapterContract } from "../market/adapters/contracts/AaveHorizonBridgeAdapterContract.js";
|
|
7
|
+
import { AaveV3PoolAdapterContract } from "../market/adapters/contracts/AaveV3PoolAdapterContract.js";
|
|
8
|
+
import { calcPositionLeverage, healthFactorBps } from "../market/math.js";
|
|
9
|
+
import { strategyName } from "../market/strategyName.js";
|
|
10
|
+
import { calcTimeToLiquidationMs } from "./calcTimeToLiquidationMs.js";
|
|
11
|
+
import { erc20Abi } from "viem";
|
|
12
|
+
//#region src/onchain/positions/readAavePosition.ts
|
|
13
|
+
/**
|
|
14
|
+
* The Aave Horizon position of a credit account's owner — the investor of an
|
|
15
|
+
* RWA account — on the pool the account's credit manager moves positions to,
|
|
16
|
+
* reported beside that account.
|
|
17
|
+
*
|
|
18
|
+
* The pool and its RWAs come from the credit manager's Aave pool adapter, kept
|
|
19
|
+
* to those whose aToken a Horizon bridge adapter of the same credit manager
|
|
20
|
+
* takes against the underlying (the asset an RWA underlying wraps). Values are
|
|
21
|
+
* at the Aave oracle's prices, the ones Aave liquidates at.
|
|
22
|
+
*
|
|
23
|
+
* `undefined` when the credit manager has no such adapters, or the owner
|
|
24
|
+
* neither supplies any of those RWAs nor owes anything on the pool.
|
|
25
|
+
**/
|
|
26
|
+
async function readAavePosition(sdk, ca, blockNumber) {
|
|
27
|
+
const suite = sdk.marketRegister.findCreditManager(ca.creditManager);
|
|
28
|
+
const market = sdk.marketRegister.findByCreditManager(ca.creditManager);
|
|
29
|
+
const underlying = market.unwrappedUnderlying;
|
|
30
|
+
const adapters = suite.creditManager.adapters.values();
|
|
31
|
+
const poolAdapter = adapters.find((p) => p instanceof AaveV3PoolAdapterContract);
|
|
32
|
+
const bridgeAdapter = adapters.find((b) => b instanceof AaveHorizonBridgeAdapterContract && b.isDebtTokenAllowed(underlying));
|
|
33
|
+
if (!poolAdapter || !bridgeAdapter) return;
|
|
34
|
+
const pool = poolAdapter.targetContract;
|
|
35
|
+
const owner = ca.investor ?? ca.owner;
|
|
36
|
+
const assets = poolAdapter.allowedAssets.filter((a) => !market.isUnderlyingLike(a));
|
|
37
|
+
const [[account, provider], [debtReserve, ...reserves]] = await Promise.all([sdk.client.multicall({
|
|
38
|
+
contracts: [{
|
|
39
|
+
address: pool,
|
|
40
|
+
abi: iAaveV3PoolAbi,
|
|
41
|
+
functionName: "getUserAccountData",
|
|
42
|
+
args: [owner]
|
|
43
|
+
}, {
|
|
44
|
+
address: pool,
|
|
45
|
+
abi: iAaveV3PoolAbi,
|
|
46
|
+
functionName: "ADDRESSES_PROVIDER"
|
|
47
|
+
}],
|
|
48
|
+
allowFailure: false,
|
|
49
|
+
batchSize: 0,
|
|
50
|
+
blockNumber
|
|
51
|
+
}), sdk.client.multicall({
|
|
52
|
+
contracts: [underlying, ...assets].map((asset) => ({
|
|
53
|
+
address: pool,
|
|
54
|
+
abi: iAaveV3PoolAbi,
|
|
55
|
+
functionName: "getReserveData",
|
|
56
|
+
args: [asset]
|
|
57
|
+
})),
|
|
58
|
+
allowFailure: false,
|
|
59
|
+
batchSize: 0,
|
|
60
|
+
blockNumber
|
|
61
|
+
})]);
|
|
62
|
+
if (!debtReserve) return;
|
|
63
|
+
const listed = assets.flatMap((token, i) => {
|
|
64
|
+
const reserve = reserves[i];
|
|
65
|
+
return reserve && bridgeAdapter.isATokenAllowed(reserve.aTokenAddress) ? [{
|
|
66
|
+
token,
|
|
67
|
+
reserve
|
|
68
|
+
}] : [];
|
|
69
|
+
});
|
|
70
|
+
if (!listed.length) return;
|
|
71
|
+
const [oracle, [owed = 0n, ...supplied]] = await Promise.all([sdk.client.readContract({
|
|
72
|
+
address: provider,
|
|
73
|
+
abi: iPoolAddressesProviderAbi,
|
|
74
|
+
functionName: "getPriceOracle",
|
|
75
|
+
blockNumber
|
|
76
|
+
}), sdk.client.multicall({
|
|
77
|
+
contracts: [debtReserve.variableDebtTokenAddress, ...listed.map((l) => l.reserve.aTokenAddress)].map((token) => ({
|
|
78
|
+
address: token,
|
|
79
|
+
abi: erc20Abi,
|
|
80
|
+
functionName: "balanceOf",
|
|
81
|
+
args: [owner]
|
|
82
|
+
})),
|
|
83
|
+
allowFailure: false,
|
|
84
|
+
batchSize: 0,
|
|
85
|
+
blockNumber
|
|
86
|
+
})]);
|
|
87
|
+
const held = listed.flatMap(({ token, reserve }, i) => {
|
|
88
|
+
const balance = supplied[i] ?? 0n;
|
|
89
|
+
return balance > 10n ? [{
|
|
90
|
+
token,
|
|
91
|
+
reserve,
|
|
92
|
+
balance
|
|
93
|
+
}] : [];
|
|
94
|
+
});
|
|
95
|
+
if (!held.length && owed === 0n) return;
|
|
96
|
+
const [underlyingPrice, ...prices] = await sdk.client.readContract({
|
|
97
|
+
address: oracle,
|
|
98
|
+
abi: iAaveOracleAbi,
|
|
99
|
+
functionName: "getAssetsPrices",
|
|
100
|
+
args: [[underlying, ...held.map((h) => h.token)]],
|
|
101
|
+
blockNumber
|
|
102
|
+
});
|
|
103
|
+
const scale = (configuration) => 10n ** (configuration >> 48n & 255n);
|
|
104
|
+
const underlyingScale = scale(debtReserve.configuration.data);
|
|
105
|
+
let totalValue = 0n;
|
|
106
|
+
held.forEach(({ reserve, balance }, i) => {
|
|
107
|
+
totalValue += balance * (prices[i] ?? 0n) * underlyingScale / (scale(reserve.configuration.data) * underlyingPrice);
|
|
108
|
+
});
|
|
109
|
+
const debtBase = account[1];
|
|
110
|
+
const currentLiquidationThreshold = account[3];
|
|
111
|
+
const healthFactor = healthFactorBps(account[5]);
|
|
112
|
+
const rate = Number(debtReserve.currentVariableBorrowRate * PERCENTAGE_FACTOR / RAY);
|
|
113
|
+
const sole = held.length === 1 ? held[0] : void 0;
|
|
114
|
+
let liquidationPrice = null;
|
|
115
|
+
if (sole && currentLiquidationThreshold > 0n) liquidationPrice = debtBase * PERCENTAGE_FACTOR * scale(sole.reserve.configuration.data) * PRICE_DECIMALS / (sole.balance * currentLiquidationThreshold * underlyingPrice);
|
|
116
|
+
const { priceOracle } = market;
|
|
117
|
+
const collaterals = held.map(({ token, balance }) => ({
|
|
118
|
+
collateral: priceOracle.toTokenAmount(token, balance),
|
|
119
|
+
quota: priceOracle.toTokenAmount(market.underlying, 0n),
|
|
120
|
+
withdrawals: []
|
|
121
|
+
}));
|
|
122
|
+
const targetCollateral = sole ? sdk.tokensMeta.mustGetToken(sole.token) : suite.accountTargetCollateral(ca.creditAccount);
|
|
123
|
+
return {
|
|
124
|
+
kind: "aave",
|
|
125
|
+
chainId: sdk.chainId,
|
|
126
|
+
creditManager: ca.creditManager,
|
|
127
|
+
creditAccount: ca.creditAccount,
|
|
128
|
+
underlyingToken: suite.underlyingToken,
|
|
129
|
+
name: targetCollateral ? strategyName(targetCollateral, suite.underlyingToken) : suite.underlyingToken.symbol,
|
|
130
|
+
curator: market.curator,
|
|
131
|
+
targetCollateral,
|
|
132
|
+
leverage: calcPositionLeverage(totalValue, owed),
|
|
133
|
+
borrowApy: rate,
|
|
134
|
+
totalDebt: market.toUnderlyingAmount(owed),
|
|
135
|
+
totalValue: market.toUnderlyingAmount(totalValue),
|
|
136
|
+
healthFactor,
|
|
137
|
+
borrowRate: {
|
|
138
|
+
total: totalValue > 0n ? Number(BigInt(rate) * owed / totalValue) : 0,
|
|
139
|
+
totalOnDebt: rate,
|
|
140
|
+
base: rate,
|
|
141
|
+
quotas: []
|
|
142
|
+
},
|
|
143
|
+
timeToLiquidation: calcTimeToLiquidationMs(healthFactor, BigInt(rate)),
|
|
144
|
+
liquidationPrice,
|
|
145
|
+
collaterals,
|
|
146
|
+
pool,
|
|
147
|
+
bridge: bridgeAdapter.bridge
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
//#endregion
|
|
151
|
+
export { readAavePosition };
|
|
@@ -5,6 +5,7 @@ import { parseRWAFactoryOperationCalldata } from "./parse/parseRWAFactoryOperati
|
|
|
5
5
|
import { parseOperationCalldata } from "./parse/parseOperationCalldata.js";
|
|
6
6
|
import { isPoolOperation, isRWAOperation } from "./parse/types.js";
|
|
7
7
|
import "./parse/index.js";
|
|
8
|
+
import { aaveBridgeBorrows } from "./preview/aaveBridgeBorrows.js";
|
|
8
9
|
import { buildDelayedStrategyPositionOperationPreview } from "./preview/buildDelayedStrategyPositionOperationPreview.js";
|
|
9
10
|
import { CreditAccountState } from "./preview/CreditAccountState.js";
|
|
10
11
|
import { classifyCloseOrRepay, isCloseOrRepay } from "./preview/detectCloseOrRepay.js";
|
|
@@ -18,4 +19,4 @@ import { makeReplayState, replayInnerOperations } from "./preview/replayInnerOpe
|
|
|
18
19
|
import { replayMulticall } from "./preview/replayMulticall.js";
|
|
19
20
|
import { previewOperation } from "./preview/previewOperation.js";
|
|
20
21
|
import "./preview/index.js";
|
|
21
|
-
export { CreditAccountState, buildDelayedStrategyPositionOperationPreview, classifyCloseOrRepay, classifyInnerOperations, detectDelayedClaim, detectDelayedOperation, estimateClaimableAt, isCloseOrRepay, isPoolOperation, isRWAOperation, makeReplayState, midasGreenlistsAccount, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parseRWAFactoryOperationCalldata, previewAdjustStrategyPosition, previewExitOrRepayStrategyPosition, previewOperation, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
|
|
22
|
+
export { CreditAccountState, aaveBridgeBorrows, buildDelayedStrategyPositionOperationPreview, classifyCloseOrRepay, classifyInnerOperations, detectDelayedClaim, detectDelayedOperation, estimateClaimableAt, isCloseOrRepay, isPoolOperation, isRWAOperation, makeReplayState, midasGreenlistsAccount, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parseRWAFactoryOperationCalldata, previewAdjustStrategyPosition, previewExitOrRepayStrategyPosition, previewOperation, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { AaveHorizonBridgeAdapterContract } from "../../market/adapters/contracts/AaveHorizonBridgeAdapterContract.js";
|
|
2
|
+
//#region src/onchain/preview/preview/aaveBridgeBorrows.ts
|
|
3
|
+
/**
|
|
4
|
+
* The loans the multicall's Horizon bridge calls take as the account owner,
|
|
5
|
+
* at the amounts the calldata names.
|
|
6
|
+
*/
|
|
7
|
+
function aaveBridgeBorrows(sdk, creditManager, multicall) {
|
|
8
|
+
const { priceOracle } = sdk.marketRegister.findByCreditManager(creditManager);
|
|
9
|
+
const borrows = [];
|
|
10
|
+
for (const op of multicall) {
|
|
11
|
+
if (op.operation !== "Execute") continue;
|
|
12
|
+
const adapter = sdk.getContract(op.adapter);
|
|
13
|
+
if (!(adapter instanceof AaveHorizonBridgeAdapterContract)) continue;
|
|
14
|
+
const borrow = adapter.parseBorrow(op.calldata);
|
|
15
|
+
if (borrow) borrows.push({
|
|
16
|
+
bridge: adapter.bridge,
|
|
17
|
+
amount: priceOracle.toTokenAmount(borrow.debtToken, borrow.amount)
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
return borrows;
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
23
|
+
export { aaveBridgeBorrows };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { AaveHorizonBridgeAdapterContract } from "../../market/adapters/contracts/AaveHorizonBridgeAdapterContract.js";
|
|
2
|
+
import { AaveV3PoolAdapterContract } from "../../market/adapters/contracts/AaveV3PoolAdapterContract.js";
|
|
3
|
+
//#region src/onchain/preview/preview/aaveMoveStart.ts
|
|
4
|
+
/**
|
|
5
|
+
* Index at which an opening that moves to Aave Horizon in its own multicall
|
|
6
|
+
* starts the move: the first Aave pool adapter call after the debt is drawn,
|
|
7
|
+
* followed by a Horizon bridge borrow. `undefined` for a multicall that does
|
|
8
|
+
* not move a position to Aave.
|
|
9
|
+
*
|
|
10
|
+
* The calls before it build the credit account an opening preview describes;
|
|
11
|
+
* the rest supply its collateral to Aave and repay its debt with the loan
|
|
12
|
+
* Aave takes in the owner's name.
|
|
13
|
+
*/
|
|
14
|
+
function aaveMoveStart(sdk, multicall) {
|
|
15
|
+
const borrowed = multicall.findIndex((op) => op.operation === "IncreaseBorrowedAmount");
|
|
16
|
+
if (borrowed < 0) return;
|
|
17
|
+
const start = multicall.findIndex((op, i) => i > borrowed && op.operation === "Execute" && sdk.getContract(op.adapter) instanceof AaveV3PoolAdapterContract);
|
|
18
|
+
if (start < 0) return;
|
|
19
|
+
return multicall.slice(start + 1).some((op) => {
|
|
20
|
+
if (op.operation !== "Execute") return false;
|
|
21
|
+
const adapter = sdk.getContract(op.adapter);
|
|
22
|
+
return adapter instanceof AaveHorizonBridgeAdapterContract && adapter.parseBorrow(op.calldata) !== void 0;
|
|
23
|
+
}) ? start : void 0;
|
|
24
|
+
}
|
|
25
|
+
//#endregion
|
|
26
|
+
export { aaveMoveStart };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { aaveBridgeBorrows } from "./aaveBridgeBorrows.js";
|
|
1
2
|
import { buildDelayedStrategyPositionOperationPreview } from "./buildDelayedStrategyPositionOperationPreview.js";
|
|
2
3
|
import { CreditAccountState } from "./CreditAccountState.js";
|
|
3
4
|
import { classifyCloseOrRepay, isCloseOrRepay } from "./detectCloseOrRepay.js";
|
|
@@ -10,4 +11,4 @@ import { previewExitOrRepayStrategyPosition } from "./previewExitOrRepayStrategy
|
|
|
10
11
|
import { makeReplayState, replayInnerOperations } from "./replayInnerOperations.js";
|
|
11
12
|
import { replayMulticall } from "./replayMulticall.js";
|
|
12
13
|
import { previewOperation } from "./previewOperation.js";
|
|
13
|
-
export { CreditAccountState, buildDelayedStrategyPositionOperationPreview, classifyCloseOrRepay, detectDelayedClaim, detectDelayedOperation, estimateClaimableAt, isCloseOrRepay, makeReplayState, midasGreenlistsAccount, previewAdjustStrategyPosition, previewExitOrRepayStrategyPosition, previewOperation, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
|
|
14
|
+
export { CreditAccountState, aaveBridgeBorrows, buildDelayedStrategyPositionOperationPreview, classifyCloseOrRepay, detectDelayedClaim, detectDelayedOperation, estimateClaimableAt, isCloseOrRepay, makeReplayState, midasGreenlistsAccount, previewAdjustStrategyPosition, previewExitOrRepayStrategyPosition, previewOperation, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { AbstractAdapterContract } from "../../market/adapters/contracts/AbstractAdapter.js";
|
|
2
|
+
//#region src/onchain/preview/preview/loadAdapterReplayState.ts
|
|
3
|
+
/**
|
|
4
|
+
* Has every adapter called in `multicall` read what it needs to replay its
|
|
5
|
+
* call, see {@link AbstractAdapterContract.loadReplayState}. Runs before
|
|
6
|
+
* {@link replayInnerOperations}, which cannot wait on the chain.
|
|
7
|
+
*/
|
|
8
|
+
async function loadAdapterReplayState(sdk, multicall) {
|
|
9
|
+
await Promise.all(multicall.map((op) => {
|
|
10
|
+
if (op.operation !== "Execute") return;
|
|
11
|
+
const adapter = sdk.getContract(op.adapter);
|
|
12
|
+
return adapter instanceof AbstractAdapterContract ? adapter.loadReplayState(op.calldata) : void 0;
|
|
13
|
+
}));
|
|
14
|
+
}
|
|
15
|
+
//#endregion
|
|
16
|
+
export { loadAdapterReplayState };
|
|
@@ -3,6 +3,7 @@ import { DUST_THRESHOLD } from "../../constants/math.js";
|
|
|
3
3
|
import { asEstimated } from "../../../model/previews.js";
|
|
4
4
|
import { sdkOk } from "../../../model/result.js";
|
|
5
5
|
import "../../../model/index.js";
|
|
6
|
+
import { aaveBridgeBorrows } from "./aaveBridgeBorrows.js";
|
|
6
7
|
import { unwrapNativeCollateral } from "./unwrapNativeCollateral.js";
|
|
7
8
|
//#region src/onchain/preview/preview/previewAdjustStrategyPosition.ts
|
|
8
9
|
/**
|
|
@@ -23,6 +24,7 @@ function previewAdjustStrategyPosition(sdk, input, operation, replay) {
|
|
|
23
24
|
const assetsChange = account.balances.difference(before.balances).toAssets(DUST_THRESHOLD);
|
|
24
25
|
const priced = oracle.safeConvertAssets(account.balances.toAssets(), market.underlying);
|
|
25
26
|
const snap = account.toSnapshot(priced.value);
|
|
27
|
+
const aaveBorrows = aaveBridgeBorrows(sdk, operation.creditManager, operation.multicall);
|
|
26
28
|
return sdkOk({
|
|
27
29
|
operation: "AdjustCreditAccount",
|
|
28
30
|
...asEstimated(sdk.positions.projection(snap, { availableLiquidityChange: before.totalDebt - account.totalDebt })),
|
|
@@ -37,6 +39,7 @@ function previewAdjustStrategyPosition(sdk, input, operation, replay) {
|
|
|
37
39
|
...oracle.toAmount(market.underlying, q.balance)
|
|
38
40
|
})),
|
|
39
41
|
assetsChange: assetsChange.map((a) => oracle.toTokenAmount(a.token, a.balance)),
|
|
42
|
+
...aaveBorrows.length > 0 ? { aaveBorrows } : {},
|
|
40
43
|
warning: priced.error
|
|
41
44
|
});
|
|
42
45
|
}
|
|
@@ -3,6 +3,7 @@ import "../../constants/math.js";
|
|
|
3
3
|
import { asEstimated } from "../../../model/previews.js";
|
|
4
4
|
import { sdkOk } from "../../../model/result.js";
|
|
5
5
|
import "../../../model/index.js";
|
|
6
|
+
import { aaveBridgeBorrows } from "./aaveBridgeBorrows.js";
|
|
6
7
|
import { classifyCloseOrRepay } from "./detectCloseOrRepay.js";
|
|
7
8
|
import { unwrapNativeCollateral } from "./unwrapNativeCollateral.js";
|
|
8
9
|
//#region src/onchain/preview/preview/previewExitOrRepayStrategyPosition.ts
|
|
@@ -11,7 +12,8 @@ function previewExitOrRepayStrategyPosition(sdk, input, operation, permanent, re
|
|
|
11
12
|
const exitTokens = [market.underlying];
|
|
12
13
|
const meta = sdk.tokensMeta.get(market.underlying);
|
|
13
14
|
if (meta && sdk.tokensMeta.isRWAUnderlying(meta)) exitTokens.push(meta.asset);
|
|
14
|
-
|
|
15
|
+
const aaveBorrows = aaveBridgeBorrows(sdk, operation.creditManager, operation.multicall);
|
|
16
|
+
return (aaveBorrows.length > 0 ? "repay" : classifyCloseOrRepay(operation.multicall, exitTokens)) === "close" ? sdkOk(previewCloseCreditAccount(sdk, operation, permanent, replay)) : previewRepayCreditAccount(sdk, input, operation, permanent, replay, aaveBorrows);
|
|
15
17
|
}
|
|
16
18
|
/**
|
|
17
19
|
* Previews a credit account closure: all collateral is swapped into
|
|
@@ -45,7 +47,7 @@ function previewCloseCreditAccount(sdk, operation, permanent, replay) {
|
|
|
45
47
|
* from the wallet when needed) and collateral is returned to the user
|
|
46
48
|
* in-kind.
|
|
47
49
|
*/
|
|
48
|
-
function previewRepayCreditAccount(sdk, input, operation, permanent, replay) {
|
|
50
|
+
function previewRepayCreditAccount(sdk, input, operation, permanent, replay, aaveBorrows) {
|
|
49
51
|
const { value = 0n } = input;
|
|
50
52
|
const market = sdk.marketRegister.findByCreditManager(operation.creditManager);
|
|
51
53
|
const { before, after } = replay;
|
|
@@ -65,6 +67,7 @@ function previewRepayCreditAccount(sdk, input, operation, permanent, replay) {
|
|
|
65
67
|
collateralAdded: collateralAdded.map((a) => market.priceOracle.toTokenAmount(a.token, a.balance)),
|
|
66
68
|
debtRepaid: market.toUnderlyingAmount(before.totalDebt - account.totalDebt),
|
|
67
69
|
collateralWithdrawn: after.collateralWithdrawn.toAssets().map((a) => market.priceOracle.toTokenAmount(a.token, a.balance)),
|
|
70
|
+
...aaveBorrows.length > 0 ? { aaveBorrows } : {},
|
|
68
71
|
warning: priced.error
|
|
69
72
|
});
|
|
70
73
|
}
|
|
@@ -2,6 +2,7 @@ import { AP_WETH_TOKEN } from "../../constants/address-provider.js";
|
|
|
2
2
|
import { asEstimated } from "../../../model/previews.js";
|
|
3
3
|
import { sdkOk } from "../../../model/result.js";
|
|
4
4
|
import "../../../model/index.js";
|
|
5
|
+
import { aaveBridgeBorrows } from "./aaveBridgeBorrows.js";
|
|
5
6
|
import { midasGreenlistsAccount } from "./midasGreenlistsAccount.js";
|
|
6
7
|
import { unwrapNativeCollateral } from "./unwrapNativeCollateral.js";
|
|
7
8
|
//#region src/onchain/preview/preview/previewOpenStrategyPosition.ts
|
|
@@ -23,6 +24,7 @@ function previewOpenStrategyPosition(sdk, input, operation, replay) {
|
|
|
23
24
|
const collateral = unwrapped.data;
|
|
24
25
|
const snap = account.toSnapshot(netValue + account.totalDebt);
|
|
25
26
|
const targetAsset = inferTargetAsset(operation.multicall, account.balances);
|
|
27
|
+
const aaveBorrows = aaveBridgeBorrows(sdk, operation.creditManager, operation.multicall);
|
|
26
28
|
const projection = {
|
|
27
29
|
...asEstimated(sdk.positions.projection(snap, { availableLiquidityChange: -account.totalDebt })),
|
|
28
30
|
targetCollateral: targetAsset ? oracle.toTokenAmount(targetAsset.token, targetAsset.balance) : void 0,
|
|
@@ -35,7 +37,8 @@ function previewOpenStrategyPosition(sdk, input, operation, replay) {
|
|
|
35
37
|
operation: "OpenCreditAccount",
|
|
36
38
|
...operation.operation === "MultiCall" || operation.operation === "BotMulticall" || operation.operation === "RWAMulticall" ? { creditAccount: operation.creditAccount } : {},
|
|
37
39
|
..."args" in operation ? { rwaArgs: operation.args } : {},
|
|
38
|
-
midasGreenlistsAccount: midasGreenlistsAccount(sdk, operation.multicall)
|
|
40
|
+
midasGreenlistsAccount: midasGreenlistsAccount(sdk, operation.multicall),
|
|
41
|
+
...aaveBorrows.length > 0 ? { aaveBorrows } : {}
|
|
39
42
|
});
|
|
40
43
|
}
|
|
41
44
|
/**
|
|
@@ -11,6 +11,8 @@ import { detectDelayedOperation } from "./detectDelayedOperation.js";
|
|
|
11
11
|
import { estimateClaimableAt } from "./estimateClaimableAt.js";
|
|
12
12
|
import { previewAdjustStrategyPosition } from "./previewAdjustStrategyPosition.js";
|
|
13
13
|
import { previewExitOrRepayStrategyPosition } from "./previewExitOrRepayStrategyPosition.js";
|
|
14
|
+
import { aaveMoveStart } from "./aaveMoveStart.js";
|
|
15
|
+
import { loadAdapterReplayState } from "./loadAdapterReplayState.js";
|
|
14
16
|
import { previewOpenStrategyPosition } from "./previewOpenStrategyPosition.js";
|
|
15
17
|
import { previewPoolPositionOperation } from "./previewPoolPositionOperation.js";
|
|
16
18
|
import { replayMulticall } from "./replayMulticall.js";
|
|
@@ -33,8 +35,9 @@ async function previewOperation(sdk, input, options, creditAccount) {
|
|
|
33
35
|
if (!parsed.ok) return parsed;
|
|
34
36
|
const operation = parsed.data;
|
|
35
37
|
if (isPoolOperation(operation)) return previewPoolPositionOperation(sdk, operation, options);
|
|
38
|
+
if ("multicall" in operation) await loadAdapterReplayState(sdk, operation.multicall);
|
|
36
39
|
if (operation.operation === "OpenCreditAccount" || operation.operation === "RWAOpenCreditAccount") {
|
|
37
|
-
const replayed = replayMulticall(sdk, operation);
|
|
40
|
+
const replayed = replayMulticall(sdk, beforeAaveMove(sdk, operation));
|
|
38
41
|
if (!replayed.ok) return replayed;
|
|
39
42
|
return previewOpenStrategyPosition(sdk, input, operation, replayed.data);
|
|
40
43
|
}
|
|
@@ -55,7 +58,7 @@ async function previewOperation(sdk, input, options, creditAccount) {
|
|
|
55
58
|
if (!resolved.ok) return resolved;
|
|
56
59
|
const replayed = replayMulticall(sdk, operation, resolved.data);
|
|
57
60
|
if (!replayed.ok) return replayed;
|
|
58
|
-
return previewMulticallOperation(sdk, input, operation, replayed.data, options?.blockNumber);
|
|
61
|
+
return previewMulticallOperation(sdk, input, operation, replayed.data, options?.blockNumber, resolved.data);
|
|
59
62
|
}
|
|
60
63
|
return sdkErr({
|
|
61
64
|
code: "unsupportedOperation",
|
|
@@ -64,6 +67,18 @@ async function previewOperation(sdk, input, options, creditAccount) {
|
|
|
64
67
|
});
|
|
65
68
|
}
|
|
66
69
|
/**
|
|
70
|
+
* The operation cut where its move to Aave Horizon begins, see
|
|
71
|
+
* {@link aaveMoveStart}: an opening preview describes the account before it
|
|
72
|
+
* moves. The operation itself when it does not move.
|
|
73
|
+
*/
|
|
74
|
+
function beforeAaveMove(sdk, operation) {
|
|
75
|
+
const start = aaveMoveStart(sdk, operation.multicall);
|
|
76
|
+
return start === void 0 ? operation : {
|
|
77
|
+
...operation,
|
|
78
|
+
multicall: operation.multicall.slice(0, start)
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
67
82
|
* Resolves the pre-state of the credit account an operation targets: uses the
|
|
68
83
|
* injected state when present, otherwise fetches it from the credit account
|
|
69
84
|
* compressor.
|
|
@@ -82,10 +97,23 @@ async function resolveCreditAccount(sdk, address, options, data) {
|
|
|
82
97
|
* best-effort preview of the state after the withdrawal is claimed.
|
|
83
98
|
*
|
|
84
99
|
* A reopening is reported as `OpenCreditAccount` and never as a delayed
|
|
85
|
-
* withdrawal: an opening requests no redemption.
|
|
100
|
+
* withdrawal: an opening requests no redemption. A multicall that borrows on
|
|
101
|
+
* an empty account and does request one — the exit from Aave Horizon, which
|
|
102
|
+
* borrows to bring the position back and redeems it at once — is a delayed
|
|
103
|
+
* operation instead. A reopening that moves to Aave in the same multicall
|
|
104
|
+
* ends owing nothing, and is told apart by the move itself.
|
|
86
105
|
*/
|
|
87
|
-
async function previewMulticallOperation(sdk, input, operation, replay, blockNumber) {
|
|
88
|
-
|
|
106
|
+
async function previewMulticallOperation(sdk, input, operation, replay, blockNumber, creditAccount) {
|
|
107
|
+
const detected = detectDelayedOperation(sdk, operation.multicall);
|
|
108
|
+
if (!detected.ok) return detected;
|
|
109
|
+
const delayed = detected.data;
|
|
110
|
+
const startsEmpty = !delayed && replay.before.totalDebt === 0n && replay.before.quotas.toAssets(0n).length === 0;
|
|
111
|
+
if (startsEmpty && aaveMoveStart(sdk, operation.multicall) !== void 0) {
|
|
112
|
+
const halfway = replayMulticall(sdk, beforeAaveMove(sdk, operation), creditAccount);
|
|
113
|
+
if (!halfway.ok) return halfway;
|
|
114
|
+
return previewOpenStrategyPosition(sdk, input, operation, halfway.data);
|
|
115
|
+
}
|
|
116
|
+
if (startsEmpty && replay.after.account.totalDebt > 0n) return previewOpenStrategyPosition(sdk, input, operation, replay);
|
|
89
117
|
let instantPreview;
|
|
90
118
|
if (isCloseOrRepay(operation.multicall)) {
|
|
91
119
|
const instant = previewExitOrRepayStrategyPosition(sdk, input, operation, false, replay);
|
|
@@ -96,9 +124,6 @@ async function previewMulticallOperation(sdk, input, operation, replay, blockNum
|
|
|
96
124
|
if (!instant.ok) return instant;
|
|
97
125
|
instantPreview = instant.data;
|
|
98
126
|
}
|
|
99
|
-
const detected = detectDelayedOperation(sdk, operation.multicall);
|
|
100
|
-
if (!detected.ok) return detected;
|
|
101
|
-
const delayed = detected.data;
|
|
102
127
|
if (!delayed) {
|
|
103
128
|
const intent = await resolveDelayedClaimIntent(sdk, operation.multicall, blockNumber);
|
|
104
129
|
if (!intent.ok) return intent;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { iAaveHorizonBridgeAbi } from "../../market/adapters/abi/aave/iAaveHorizonBridge.js";
|
|
2
|
+
import { iAaveV3PoolAbi } from "../../market/adapters/abi/aave/iAaveV3Pool.js";
|
|
3
|
+
import { iVariableDebtTokenAbi } from "../../market/adapters/abi/aave/iVariableDebtToken.js";
|
|
4
|
+
import "../../market/adapters/abi/aave/index.js";
|
|
5
|
+
import { insufficientBorrowAllowance } from "../../../model/errors/operation-errors.js";
|
|
6
|
+
import { unexpectedFailure } from "../../../model/errors/prepare-errors.js";
|
|
7
|
+
import "../../../model/index.js";
|
|
8
|
+
import { toTokenAmount } from "../helpers/token.js";
|
|
9
|
+
import "../helpers/index.js";
|
|
10
|
+
//#region src/onchain/validation/bundles/checkAaveDelegation.ts
|
|
11
|
+
/**
|
|
12
|
+
* `owner` has delegated the bridge at least the borrowed amount on the
|
|
13
|
+
* variable debt token of the borrowed token, in the pool the bridge borrows
|
|
14
|
+
* from.
|
|
15
|
+
*/
|
|
16
|
+
async function checkAaveDelegation(input) {
|
|
17
|
+
const { sdk, owner, borrow, blockNumber } = input;
|
|
18
|
+
const { bridge, amount } = borrow;
|
|
19
|
+
const token = amount.token.address;
|
|
20
|
+
try {
|
|
21
|
+
const pool = await sdk.client.readContract({
|
|
22
|
+
address: bridge,
|
|
23
|
+
abi: iAaveHorizonBridgeAbi,
|
|
24
|
+
functionName: "pool",
|
|
25
|
+
blockNumber
|
|
26
|
+
});
|
|
27
|
+
const { variableDebtTokenAddress } = await sdk.client.readContract({
|
|
28
|
+
address: pool,
|
|
29
|
+
abi: iAaveV3PoolAbi,
|
|
30
|
+
functionName: "getReserveData",
|
|
31
|
+
args: [token],
|
|
32
|
+
blockNumber
|
|
33
|
+
});
|
|
34
|
+
const allowed = await sdk.client.readContract({
|
|
35
|
+
address: variableDebtTokenAddress,
|
|
36
|
+
abi: iVariableDebtTokenAbi,
|
|
37
|
+
functionName: "borrowAllowance",
|
|
38
|
+
args: [owner, bridge],
|
|
39
|
+
blockNumber
|
|
40
|
+
});
|
|
41
|
+
return allowed >= amount.value ? [] : [insufficientBorrowAllowance({
|
|
42
|
+
owner,
|
|
43
|
+
spender: bridge,
|
|
44
|
+
debtToken: variableDebtTokenAddress,
|
|
45
|
+
required: amount,
|
|
46
|
+
allowed: toTokenAmount(sdk, token, allowed)
|
|
47
|
+
})];
|
|
48
|
+
} catch (cause) {
|
|
49
|
+
return [unexpectedFailure(cause, `read the ${amount.token.symbol} borrow delegation`)];
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
export { checkAaveDelegation };
|