@gearbox-protocol/sdk 18.4.1-aave.8 → 18.4.1-aave.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/cjs/onchain/accounts/index.js +1 -1
  2. package/dist/cjs/onchain/accounts/intents/index.js +33 -0
  3. package/dist/cjs/onchain/accounts/intents/operations.js +21 -0
  4. package/dist/cjs/onchain/accounts/intents/plan.js +55 -0
  5. package/dist/cjs/onchain/accounts/intents/readAaveHoldings.js +56 -0
  6. package/dist/cjs/onchain/accounts/intents/realize.js +64 -1
  7. package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +1 -1
  8. package/dist/cjs/onchain/accounts/intents/utils/ledger.js +8 -0
  9. package/dist/cjs/onchain/index.js +3 -1
  10. package/dist/cjs/onchain/market/adapters/abi/index.js +2 -0
  11. package/dist/cjs/onchain/market/adapters/abi/securitize/iSecuritizeNAVProvider.js +15 -0
  12. package/dist/cjs/onchain/market/adapters/abi/securitize/index.js +2 -0
  13. package/dist/cjs/onchain/market/adapters/contracts/AaveHorizonBridgeAdapterContract.js +21 -0
  14. package/dist/cjs/onchain/market/adapters/contracts/AaveV3PoolAdapterContract.js +14 -0
  15. package/dist/cjs/onchain/market/adapters/contracts/SecuritizeRedemptionGatewayAdapterContract.js +42 -5
  16. package/dist/cjs/onchain/market/adapters/index.js +2 -0
  17. package/dist/cjs/onchain/market/index.js +2 -0
  18. package/dist/cjs/onchain/positions/MultichainPositionsService.js +15 -0
  19. package/dist/cjs/onchain/positions/PositionsService.js +31 -0
  20. package/dist/cjs/onchain/positions/readAavePosition.js +152 -0
  21. package/dist/cjs/onchain/preview/preview/previewOperation.js +8 -5
  22. package/dist/cjs/sdk/positions/PositionsNamespace.js +6 -0
  23. package/dist/cjs/sdk/prepare/PrepareApi.js +43 -0
  24. package/dist/esm/dev/AccountOpener.js +1 -1
  25. package/dist/esm/dev/withdrawalUtils.js +1 -1
  26. package/dist/esm/history/trace/extractTransfers.js +1 -1
  27. package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +2 -2
  28. package/dist/esm/onchain/accounts/index.js +1 -1
  29. package/dist/esm/onchain/accounts/intents/index.js +34 -1
  30. package/dist/esm/onchain/accounts/intents/operations.js +20 -1
  31. package/dist/esm/onchain/accounts/intents/plan.js +56 -2
  32. package/dist/esm/onchain/accounts/intents/readAaveHoldings.js +55 -0
  33. package/dist/esm/onchain/accounts/intents/realize.js +65 -2
  34. package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +1 -1
  35. package/dist/esm/onchain/accounts/intents/utils/ledger.js +8 -0
  36. package/dist/esm/onchain/accounts/liquidations/LiquidationsService.js +1 -1
  37. package/dist/esm/onchain/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +1 -1
  38. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.js +1 -1
  39. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.js +1 -1
  40. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.js +1 -1
  41. package/dist/esm/onchain/base/TokensMeta.js +3 -3
  42. package/dist/esm/onchain/core/createAddressProvider.js +1 -1
  43. package/dist/esm/onchain/index.js +3 -2
  44. package/dist/esm/onchain/market/adapters/abi/index.js +2 -1
  45. package/dist/esm/onchain/market/adapters/abi/securitize/iSecuritizeNAVProvider.js +14 -0
  46. package/dist/esm/onchain/market/adapters/abi/securitize/index.js +2 -1
  47. package/dist/esm/onchain/market/adapters/contracts/AaveHorizonBridgeAdapterContract.js +21 -0
  48. package/dist/esm/onchain/market/adapters/contracts/AaveV3PoolAdapterContract.js +14 -0
  49. package/dist/esm/onchain/market/adapters/contracts/AccountMigratorAdapterContract.js +1 -1
  50. package/dist/esm/onchain/market/adapters/contracts/ERC4626AdapterContract.js +1 -1
  51. package/dist/esm/onchain/market/adapters/contracts/SecuritizeRedemptionGatewayAdapterContract.js +43 -6
  52. package/dist/esm/onchain/market/adapters/index.js +2 -1
  53. package/dist/esm/onchain/market/credit/CreditFacadeV310BaseContract.js +1 -1
  54. package/dist/esm/onchain/market/index.js +2 -1
  55. package/dist/esm/onchain/market/pool/PoolV310Contract.js +1 -1
  56. package/dist/esm/onchain/market/rwa/createDegenNFT.js +1 -1
  57. package/dist/esm/onchain/market/zapper/IETHZapperContract.js +1 -1
  58. package/dist/esm/onchain/market/zapper/ZapperContract.js +1 -1
  59. package/dist/esm/onchain/positions/MultichainPositionsService.js +15 -0
  60. package/dist/esm/onchain/positions/PositionsService.js +31 -0
  61. package/dist/esm/onchain/positions/readAavePosition.js +151 -0
  62. package/dist/esm/onchain/preview/preview/previewOperation.js +8 -5
  63. package/dist/esm/onchain/preview/preview/previewPoolPositionOperation.js +2 -2
  64. package/dist/esm/onchain/utils/viem/simulateWithPriceUpdates.js +1 -1
  65. package/dist/esm/sdk/positions/PositionsNamespace.js +6 -0
  66. package/dist/esm/sdk/prepare/PrepareApi.js +43 -0
  67. package/dist/types/model/aave.d.ts +39 -0
  68. package/dist/types/model/index.d.ts +4 -4
  69. package/dist/types/model/opportunities.d.ts +1 -1
  70. package/dist/types/onchain/accounts/index.d.ts +2 -2
  71. package/dist/types/onchain/accounts/intents/index.d.ts +21 -3
  72. package/dist/types/onchain/accounts/intents/operations.d.ts +38 -1
  73. package/dist/types/onchain/accounts/intents/plan.d.ts +27 -1
  74. package/dist/types/onchain/accounts/intents/readAaveHoldings.d.ts +16 -0
  75. package/dist/types/onchain/accounts/intents/types.d.ts +42 -0
  76. package/dist/types/onchain/index.d.ts +4 -3
  77. package/dist/types/onchain/market/adapters/abi/index.d.ts +2 -1
  78. package/dist/types/onchain/market/adapters/abi/securitize/iSecuritizeNAVProvider.d.ts +13 -0
  79. package/dist/types/onchain/market/adapters/abi/securitize/index.d.ts +2 -1
  80. package/dist/types/onchain/market/adapters/contracts/AaveHorizonBridgeAdapterContract.d.ts +7 -0
  81. package/dist/types/onchain/market/adapters/contracts/AaveV3PoolAdapterContract.d.ts +5 -0
  82. package/dist/types/onchain/market/adapters/contracts/SecuritizeRedemptionGatewayAdapterContract.d.ts +19 -4
  83. package/dist/types/onchain/market/adapters/index.d.ts +2 -1
  84. package/dist/types/onchain/market/index.d.ts +2 -1
  85. package/dist/types/onchain/positions/MultichainPositionsService.d.ts +7 -1
  86. package/dist/types/onchain/positions/PositionsService.d.ts +16 -2
  87. package/dist/types/onchain/positions/index.d.ts +2 -2
  88. package/dist/types/onchain/positions/readAavePosition.d.ts +22 -0
  89. package/dist/types/onchain/positions/types.d.ts +25 -0
  90. package/dist/types/sdk/index.d.ts +2 -2
  91. package/dist/types/sdk/positions/PositionsNamespace.d.ts +6 -1
  92. package/dist/types/sdk/positions/types.d.ts +9 -1
  93. package/dist/types/sdk/prepare/PrepareApi.d.ts +5 -1
  94. package/dist/types/sdk/prepare/index.d.ts +2 -2
  95. package/dist/types/sdk/prepare/types.d.ts +42 -0
  96. package/package.json +1 -1
@@ -15,6 +15,7 @@ const require_onchain_positions_calcBorrowRate = require("./calcBorrowRate.js");
15
15
  const require_onchain_positions_calcHealthFactor = require("./calcHealthFactor.js");
16
16
  const require_onchain_positions_calcLiquidationPrice = require("./calcLiquidationPrice.js");
17
17
  const require_onchain_positions_calcTimeToLiquidationMs = require("./calcTimeToLiquidationMs.js");
18
+ const require_onchain_positions_readAavePosition = require("./readAavePosition.js");
18
19
  const require_onchain_positions_types = require("./types.js");
19
20
  //#region src/onchain/positions/PositionsService.ts
20
21
  /**
@@ -68,6 +69,36 @@ var PositionsService = class extends require_onchain_base_SDKConstruct.SDKConstr
68
69
  return accounts.map((ca, i) => this.#toStrategyPosition(ca, withdrawals[i] ?? new require_onchain_utils_AddressMap.AddressMap()));
69
70
  }
70
71
  /**
72
+ * Describes the Aave Horizon positions of a wallet, see
73
+ * {@link readAavePosition}. Accounts are found as
74
+ * {@link listStrategyPositions} finds them, zero-debt ones included: an
75
+ * account whose position moved to Aave carries no debt.
76
+ *
77
+ * One Aave pool holds one position per owner, however many of the owner's
78
+ * accounts moved into it, so each is reported once. Its `creditAccount` is
79
+ * one the exit can run through — with no debt and no quota, as
80
+ * `prepare.closeAavePosition` requires — where the owner has one, and any
81
+ * of the accounts otherwise.
82
+ **/
83
+ async listAavePositions(props) {
84
+ const { wallet, blockNumber } = props;
85
+ const accounts = await this.sdk.accounts.getBorrowerCreditAccounts(wallet, { includeZeroDebt: true }, blockNumber);
86
+ const positions = await Promise.all(accounts.map((ca) => require_onchain_positions_readAavePosition.readAavePosition(this.sdk, ca, blockNumber)));
87
+ const byOwner = /* @__PURE__ */ new Map();
88
+ positions.forEach((position, i) => {
89
+ const ca = accounts[i];
90
+ if (!position || !ca) return;
91
+ const key = `${position.pool}:${ca.investor ?? ca.owner}`.toLowerCase();
92
+ const exitable = ca.debt + ca.accruedInterest + ca.accruedFees === 0n && ca.tokens.every((t) => t.quota === 0n);
93
+ const known = byOwner.get(key);
94
+ if (!known || exitable && !known.exitable) byOwner.set(key, {
95
+ position,
96
+ exitable
97
+ });
98
+ });
99
+ return [...byOwner.values()].map((p) => p.position);
100
+ }
101
+ /**
71
102
  * Returns delayed withdrawals of a strategy position
72
103
  **/
73
104
  async getCurrentWithdrawals(props) {
@@ -0,0 +1,152 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_onchain_constants_math = require("../constants/math.js");
3
+ const require_onchain_market_adapters_abi_aave_iAaveOracle = require("../market/adapters/abi/aave/iAaveOracle.js");
4
+ const require_onchain_market_adapters_abi_aave_iAaveV3Pool = require("../market/adapters/abi/aave/iAaveV3Pool.js");
5
+ const require_onchain_market_adapters_abi_aave_iPoolAddressesProvider = require("../market/adapters/abi/aave/iPoolAddressesProvider.js");
6
+ require("../market/adapters/abi/aave/index.js");
7
+ const require_onchain_market_adapters_contracts_AaveHorizonBridgeAdapterContract = require("../market/adapters/contracts/AaveHorizonBridgeAdapterContract.js");
8
+ const require_onchain_market_adapters_contracts_AaveV3PoolAdapterContract = require("../market/adapters/contracts/AaveV3PoolAdapterContract.js");
9
+ const require_onchain_market_math = require("../market/math.js");
10
+ const require_onchain_market_strategyName = require("../market/strategyName.js");
11
+ const require_onchain_positions_calcTimeToLiquidationMs = require("./calcTimeToLiquidationMs.js");
12
+ let viem = require("viem");
13
+ //#region src/onchain/positions/readAavePosition.ts
14
+ /**
15
+ * The Aave Horizon position of a credit account's owner — the investor of an
16
+ * RWA account — on the pool the account's credit manager moves positions to,
17
+ * reported beside that account.
18
+ *
19
+ * The pool and its RWAs come from the credit manager's Aave pool adapter, kept
20
+ * to those whose aToken a Horizon bridge adapter of the same credit manager
21
+ * takes against the underlying (the asset an RWA underlying wraps). Values are
22
+ * at the Aave oracle's prices, the ones Aave liquidates at.
23
+ *
24
+ * `undefined` when the credit manager has no such adapters, or the owner
25
+ * neither supplies any of those RWAs nor owes anything on the pool.
26
+ **/
27
+ async function readAavePosition(sdk, ca, blockNumber) {
28
+ const suite = sdk.marketRegister.findCreditManager(ca.creditManager);
29
+ const market = sdk.marketRegister.findByCreditManager(ca.creditManager);
30
+ const underlying = market.unwrappedUnderlying;
31
+ const adapters = suite.creditManager.adapters.values();
32
+ const poolAdapter = adapters.find((p) => p instanceof require_onchain_market_adapters_contracts_AaveV3PoolAdapterContract.AaveV3PoolAdapterContract);
33
+ const bridgeAdapter = adapters.find((b) => b instanceof require_onchain_market_adapters_contracts_AaveHorizonBridgeAdapterContract.AaveHorizonBridgeAdapterContract && b.isDebtTokenAllowed(underlying));
34
+ if (!poolAdapter || !bridgeAdapter) return;
35
+ const pool = poolAdapter.targetContract;
36
+ const owner = ca.investor ?? ca.owner;
37
+ const assets = poolAdapter.allowedAssets.filter((a) => !market.isUnderlyingLike(a));
38
+ const [[account, provider], [debtReserve, ...reserves]] = await Promise.all([sdk.client.multicall({
39
+ contracts: [{
40
+ address: pool,
41
+ abi: require_onchain_market_adapters_abi_aave_iAaveV3Pool.iAaveV3PoolAbi,
42
+ functionName: "getUserAccountData",
43
+ args: [owner]
44
+ }, {
45
+ address: pool,
46
+ abi: require_onchain_market_adapters_abi_aave_iAaveV3Pool.iAaveV3PoolAbi,
47
+ functionName: "ADDRESSES_PROVIDER"
48
+ }],
49
+ allowFailure: false,
50
+ batchSize: 0,
51
+ blockNumber
52
+ }), sdk.client.multicall({
53
+ contracts: [underlying, ...assets].map((asset) => ({
54
+ address: pool,
55
+ abi: require_onchain_market_adapters_abi_aave_iAaveV3Pool.iAaveV3PoolAbi,
56
+ functionName: "getReserveData",
57
+ args: [asset]
58
+ })),
59
+ allowFailure: false,
60
+ batchSize: 0,
61
+ blockNumber
62
+ })]);
63
+ if (!debtReserve) return;
64
+ const listed = assets.flatMap((token, i) => {
65
+ const reserve = reserves[i];
66
+ return reserve && bridgeAdapter.isATokenAllowed(reserve.aTokenAddress) ? [{
67
+ token,
68
+ reserve
69
+ }] : [];
70
+ });
71
+ if (!listed.length) return;
72
+ const [oracle, [owed = 0n, ...supplied]] = await Promise.all([sdk.client.readContract({
73
+ address: provider,
74
+ abi: require_onchain_market_adapters_abi_aave_iPoolAddressesProvider.iPoolAddressesProviderAbi,
75
+ functionName: "getPriceOracle",
76
+ blockNumber
77
+ }), sdk.client.multicall({
78
+ contracts: [debtReserve.variableDebtTokenAddress, ...listed.map((l) => l.reserve.aTokenAddress)].map((token) => ({
79
+ address: token,
80
+ abi: viem.erc20Abi,
81
+ functionName: "balanceOf",
82
+ args: [owner]
83
+ })),
84
+ allowFailure: false,
85
+ batchSize: 0,
86
+ blockNumber
87
+ })]);
88
+ const held = listed.flatMap(({ token, reserve }, i) => {
89
+ const balance = supplied[i] ?? 0n;
90
+ return balance > 10n ? [{
91
+ token,
92
+ reserve,
93
+ balance
94
+ }] : [];
95
+ });
96
+ if (!held.length && owed === 0n) return;
97
+ const [underlyingPrice, ...prices] = await sdk.client.readContract({
98
+ address: oracle,
99
+ abi: require_onchain_market_adapters_abi_aave_iAaveOracle.iAaveOracleAbi,
100
+ functionName: "getAssetsPrices",
101
+ args: [[underlying, ...held.map((h) => h.token)]],
102
+ blockNumber
103
+ });
104
+ const scale = (configuration) => 10n ** (configuration >> 48n & 255n);
105
+ const underlyingScale = scale(debtReserve.configuration.data);
106
+ let totalValue = 0n;
107
+ held.forEach(({ reserve, balance }, i) => {
108
+ totalValue += balance * (prices[i] ?? 0n) * underlyingScale / (scale(reserve.configuration.data) * underlyingPrice);
109
+ });
110
+ const debtBase = account[1];
111
+ const currentLiquidationThreshold = account[3];
112
+ const healthFactor = require_onchain_market_math.healthFactorBps(account[5]);
113
+ const rate = Number(debtReserve.currentVariableBorrowRate * require_onchain_constants_math.PERCENTAGE_FACTOR / require_onchain_constants_math.RAY);
114
+ const sole = held.length === 1 ? held[0] : void 0;
115
+ let liquidationPrice = null;
116
+ if (sole && currentLiquidationThreshold > 0n) liquidationPrice = debtBase * require_onchain_constants_math.PERCENTAGE_FACTOR * scale(sole.reserve.configuration.data) * require_onchain_constants_math.PRICE_DECIMALS / (sole.balance * currentLiquidationThreshold * underlyingPrice);
117
+ const { priceOracle } = market;
118
+ const collaterals = held.map(({ token, balance }) => ({
119
+ collateral: priceOracle.toTokenAmount(token, balance),
120
+ quota: priceOracle.toTokenAmount(market.underlying, 0n),
121
+ withdrawals: []
122
+ }));
123
+ const targetCollateral = sole ? sdk.tokensMeta.mustGetToken(sole.token) : suite.accountTargetCollateral(ca.creditAccount);
124
+ return {
125
+ kind: "aave",
126
+ chainId: sdk.chainId,
127
+ creditManager: ca.creditManager,
128
+ creditAccount: ca.creditAccount,
129
+ underlyingToken: suite.underlyingToken,
130
+ name: targetCollateral ? require_onchain_market_strategyName.strategyName(targetCollateral, suite.underlyingToken) : suite.underlyingToken.symbol,
131
+ curator: market.curator,
132
+ targetCollateral,
133
+ leverage: require_onchain_market_math.calcPositionLeverage(totalValue, owed),
134
+ borrowApy: rate,
135
+ totalDebt: market.toUnderlyingAmount(owed),
136
+ totalValue: market.toUnderlyingAmount(totalValue),
137
+ healthFactor,
138
+ borrowRate: {
139
+ total: totalValue > 0n ? Number(BigInt(rate) * owed / totalValue) : 0,
140
+ totalOnDebt: rate,
141
+ base: rate,
142
+ quotas: []
143
+ },
144
+ timeToLiquidation: require_onchain_positions_calcTimeToLiquidationMs.calcTimeToLiquidationMs(healthFactor, BigInt(rate)),
145
+ liquidationPrice,
146
+ collaterals,
147
+ pool,
148
+ bridge: bridgeAdapter.bridge
149
+ };
150
+ }
151
+ //#endregion
152
+ exports.readAavePosition = readAavePosition;
@@ -85,10 +85,16 @@ async function resolveCreditAccount(sdk, address, options, data) {
85
85
  * best-effort preview of the state after the withdrawal is claimed.
86
86
  *
87
87
  * A reopening is reported as `OpenCreditAccount` and never as a delayed
88
- * withdrawal: an opening requests no redemption.
88
+ * withdrawal: an opening requests no redemption. A multicall that borrows on
89
+ * an empty account and does request one — the exit from Aave Horizon, which
90
+ * borrows to bring the position back and redeems it at once — is a delayed
91
+ * operation instead.
89
92
  */
90
93
  async function previewMulticallOperation(sdk, input, operation, replay, blockNumber) {
91
- if (replay.before.totalDebt === 0n && replay.before.quotas.toAssets(0n).length === 0 && replay.after.account.totalDebt > 0n) return require_onchain_preview_preview_previewOpenStrategyPosition.previewOpenStrategyPosition(sdk, input, operation, replay);
94
+ const detected = require_onchain_preview_preview_detectDelayedOperation.detectDelayedOperation(sdk, operation.multicall);
95
+ if (!detected.ok) return detected;
96
+ const delayed = detected.data;
97
+ if (!delayed && replay.before.totalDebt === 0n && replay.before.quotas.toAssets(0n).length === 0 && replay.after.account.totalDebt > 0n) return require_onchain_preview_preview_previewOpenStrategyPosition.previewOpenStrategyPosition(sdk, input, operation, replay);
92
98
  let instantPreview;
93
99
  if (require_onchain_preview_preview_detectCloseOrRepay.isCloseOrRepay(operation.multicall)) {
94
100
  const instant = require_onchain_preview_preview_previewExitOrRepayStrategyPosition.previewExitOrRepayStrategyPosition(sdk, input, operation, false, replay);
@@ -99,9 +105,6 @@ async function previewMulticallOperation(sdk, input, operation, replay, blockNum
99
105
  if (!instant.ok) return instant;
100
106
  instantPreview = instant.data;
101
107
  }
102
- const detected = require_onchain_preview_preview_detectDelayedOperation.detectDelayedOperation(sdk, operation.multicall);
103
- if (!detected.ok) return detected;
104
- const delayed = detected.data;
105
108
  if (!delayed) {
106
109
  const intent = await require_onchain_preview_preview_detectDelayedClaim.resolveDelayedClaimIntent(sdk, operation.multicall, blockNumber);
107
110
  if (!intent.ok) return intent;
@@ -62,6 +62,12 @@ var PositionsNamespace = class extends require_sdk_AbstractNamespace.AbstractNam
62
62
  async getCurrentWithdrawals(props) {
63
63
  return this.onchain.getCurrentWithdrawals(props);
64
64
  }
65
+ /**
66
+ * {@inheritDoc IPositionsOnchainOnly.listAavePositions}
67
+ **/
68
+ async listAavePositions(props) {
69
+ return this.onchain.listAavePositions(props);
70
+ }
65
71
  };
66
72
  //#endregion
67
73
  exports.PositionsNamespace = PositionsNamespace;
@@ -403,6 +403,32 @@ var PrepareApi = class extends require_onchain_base_MultichainConstruct.Multicha
403
403
  });
404
404
  }
405
405
  /**
406
+ * {@inheritDoc IOpportunitiesPrepare.closeAavePosition}
407
+ **/
408
+ async closeAavePosition(position, params) {
409
+ const state = {};
410
+ try {
411
+ const sdk = await this.#chain(position.chainId);
412
+ const at = stateBlock(sdk);
413
+ const data = await sdk.accounts.getCreditAccountData(position.creditAccount);
414
+ if (!data) return refused(require_model_errors_prepare_errors.creditAccountNotFound(position.creditAccount), state);
415
+ const creditAccount = require_onchain_accounts_intents_utils_credit_account_slice.toCreditAccountSlice(data);
416
+ if (creditAccount.totalDebt > 0n || creditAccount.tokens.some((t) => t.quota > 0n)) return refused(require_model_errors_prepare_errors.creditAccountNotEmpty(position.creditAccount), state);
417
+ return delayedStarted(await service(sdk).closeAavePositionIntent({
418
+ creditAccount,
419
+ sdk,
420
+ token: params.token,
421
+ to: params.to,
422
+ owner: data.investor ?? data.owner,
423
+ slippage: params.slippage,
424
+ quotaReserve: params.quotaReserve,
425
+ draft: state
426
+ }), at);
427
+ } catch (e) {
428
+ return refused(require_model_errors_prepare_errors.unexpectedFailure(e), state);
429
+ }
430
+ }
431
+ /**
406
432
  * {@inheritDoc IOpportunitiesPrepare.adjustLeverage}
407
433
  **/
408
434
  async adjustLeverage(position, params) {
@@ -790,6 +816,23 @@ function finalized(result, at) {
790
816
  }
791
817
  /**
792
818
  * {@inheritDoc planned}
819
+ *
820
+ * A request carries one thing an instant operation does not: what it recorded
821
+ * for the tail, and when that tail can run.
822
+ **/
823
+ function delayedStarted(result, at) {
824
+ if (!result.ok) return methodError(result);
825
+ const { operations, state, calls, delayed } = result;
826
+ return require_model_result.sdkOk({
827
+ operations,
828
+ state,
829
+ calls,
830
+ delayed,
831
+ ...at
832
+ });
833
+ }
834
+ /**
835
+ * {@inheritDoc planned}
793
836
  **/
794
837
  function opened(result, at) {
795
838
  return result.ok ? require_model_result.sdkOk({
@@ -1,5 +1,5 @@
1
- import { ierc20Abi } from "../abi/iERC20.js";
2
1
  import { iCreditFacadeV310Abi } from "../abi/310/generated.js";
2
+ import { ierc20Abi } from "../abi/iERC20.js";
3
3
  import { AddressMap } from "../onchain/utils/AddressMap.js";
4
4
  import { AddressSet } from "../onchain/utils/AddressSet.js";
5
5
  import { AssetsMap } from "../onchain/utils/AssetsMap.js";
@@ -1,6 +1,6 @@
1
- import { iWithdrawalCompressorV313Abi } from "../abi/IWithdrawalCompressorV313.js";
2
1
  import { getNetworkType } from "../onchain/chain/chains.js";
3
2
  import { getWithdrawalCompressorAddress } from "../onchain/accounts/withdrawal-compressor/addresses.js";
3
+ import { iWithdrawalCompressorV313Abi } from "../abi/IWithdrawalCompressorV313.js";
4
4
  import "../onchain/index.js";
5
5
  import { iMidasDataFeedAbi, iMidasRedemptionVaultAbi, midasGatewayAbi, midasRedeemerAbi, midasRedemptionVaultPhantomTokenAbi, securitizeRedeemerAbi, securitizeRedemptionGatewayAbi, securitizeRedemptionPhantomTokenAbi } from "./withdrawalAbi.js";
6
6
  import { erc20Abi, hexToString, parseAbi, parseEther } from "viem";
@@ -1,5 +1,5 @@
1
- import { ierc20Abi } from "../../abi/iERC20.js";
2
1
  import { iCreditFacadeV310Abi } from "../../abi/310/generated.js";
2
+ import { ierc20Abi } from "../../abi/iERC20.js";
3
3
  import { AddressMap } from "../../onchain/utils/AddressMap.js";
4
4
  import "../../onchain/index.js";
5
5
  import { UnexpectedFacadeEventOrderError } from "./errors.js";
@@ -1,5 +1,3 @@
1
- import { iBaseRewardPoolAbi } from "../../abi/iBaseRewardPool.js";
2
- import { ierc4626AdapterAbi } from "../../abi/ierc4626Adapter.js";
3
1
  import { AP_REWARDS_COMPRESSOR } from "../constants/address-provider.js";
4
2
  import { ADDRESS_0X0 } from "../constants/addresses.js";
5
3
  import { MAX_UINT256 } from "../constants/math.js";
@@ -10,6 +8,8 @@ import "../base/index.js";
10
8
  import { AccountBotsService } from "./bots/AccountBotsService.js";
11
9
  import "./bots/index.js";
12
10
  import { rewardsCompressorAbi } from "../../abi/compressors/rewardsCompressor.js";
11
+ import { iBaseRewardPoolAbi } from "../../abi/iBaseRewardPool.js";
12
+ import { ierc4626AdapterAbi } from "../../abi/ierc4626Adapter.js";
13
13
  import { expectedBalanceDeltas } from "../market/credit/expectedBalanceDeltas.js";
14
14
  import "../market/index.js";
15
15
  import { CreditAccountCompressor } from "./credit-account-compressor/CreditAccountCompressor.js";
@@ -8,6 +8,7 @@ import { CreditAccountsServiceV310 } from "./CreditAccountsServiceV310.js";
8
8
  import { isPhantomToken } from "./intents/utils/pick-token.js";
9
9
  import { fetchCreditAccountSlice, toCreditAccountSlice } from "./intents/utils/credit-account-slice.js";
10
10
  import { DIRECT_TRANSFERS_QUOTA, calcDefaultQuota, calcQuotaUpdate, calcRecommendedQuota, maxAmountForQuota, roundUpQuota } from "./quota-utils.js";
11
+ import { DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, decodeDelayedIntent, encodeDelayedIntent } from "./withdrawal-compressor/intent-codec.js";
11
12
  import { CreditAccountOperationsService } from "./intents/index.js";
12
13
  import { LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS } from "./liquidations/constants.js";
13
14
  import { optimalPartialLiquidation, partialLiquidationParams } from "./liquidations/partialLiquidation.js";
@@ -15,7 +16,6 @@ import { LiquidationsService } from "./liquidations/LiquidationsService.js";
15
16
  import { MultichainLiquidationsService } from "./liquidations/MultichainLiquidationsService.js";
16
17
  import "./liquidations/index.js";
17
18
  import "./types.js";
18
- import { DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, decodeDelayedIntent, encodeDelayedIntent } from "./withdrawal-compressor/intent-codec.js";
19
19
  import { AbstractWithdrawalCompressorContract, iCreditAccountAbi, toClaimableWithdrawal, toPendingWithdrawal, toRequestableWithdrawal } from "./withdrawal-compressor/AbstractWithdrawalCompressorContract.js";
20
20
  import { getWithdrawalCompressorAddress } from "./withdrawal-compressor/addresses.js";
21
21
  import { RedemptionLoggerV310Contract } from "./withdrawal-compressor/RedemptionLoggerV310Contract.js";
@@ -17,7 +17,8 @@ import { maxBorrow } from "./maxBorrow.js";
17
17
  import { maxBorrowAndWithdraw } from "./maxBorrowAndWithdraw.js";
18
18
  import { maxWithdrawCollateral } from "./maxWithdrawCollateral.js";
19
19
  import { buildOpenStrategyState } from "./open-strategy.js";
20
- import { planAddCollateral, planAdjustLeverage, planAdjustLeverageDelayed, planBorrowAndWithdraw, planDeposit, planMoveToAave, planRepay, planUpdateQuota, planWithdraw, planWithdrawAsset, planWithdrawDelayed } from "./plan.js";
20
+ import { planAddCollateral, planAdjustLeverage, planAdjustLeverageDelayed, planBorrowAndWithdraw, planCloseAavePosition, planDeposit, planMoveToAave, planRepay, planUpdateQuota, planWithdraw, planWithdrawAsset, planWithdrawDelayed } from "./plan.js";
21
+ import { readAaveHoldings } from "./readAaveHoldings.js";
21
22
  import { withdrawLimits } from "./withdraw-limits.js";
22
23
  import { realize } from "./realize.js";
23
24
  import { planTail, projectTail } from "./tail.js";
@@ -239,6 +240,7 @@ var CreditAccountOperationsService = class extends SDKConstruct {
239
240
  switch (intent.type) {
240
241
  case "ADJUST_LEVERAGE": return planAdjustLeverageDelayed(intent, view);
241
242
  case "WITHDRAW": return planWithdrawDelayed(intent, view);
243
+ case "CLOSE_AAVE_POSITION": return planCloseAavePosition(intent, view);
242
244
  default: throw new Error(`${intent.type} - cannot be delayed`);
243
245
  }
244
246
  }, limits);
@@ -273,6 +275,37 @@ var CreditAccountOperationsService = class extends SDKConstruct {
273
275
  }
274
276
  }
275
277
  /**
278
+ * Previews leaving `owner`'s Aave Horizon position in `token` in one
279
+ * transaction, see {@link CloseAavePositionIntent}.
280
+ *
281
+ * What the owner holds and owes on Aave is read here, at the block the SDK
282
+ * stands at; the rest is {@link startDelayedIntent}, tail included.
283
+ *
284
+ * @param props - Account slice, quota reserve and slippage, the RWA, the
285
+ * wallet the exit pays, and the owner the bridge resolves for the account:
286
+ * the investor of an RWA factory account, the borrower otherwise
287
+ * @returns The request transaction, the state the exit ends in and what it
288
+ * recorded for the tail, or `{ ok: false, error }`
289
+ */
290
+ async closeAavePositionIntent(props) {
291
+ const { token, to, owner, ...rest } = props;
292
+ let holdings;
293
+ try {
294
+ holdings = await readAaveHoldings(rest.sdk, rest.creditAccount.creditManager, owner, token);
295
+ } catch (e) {
296
+ return asRefused(e, rest.draft ?? {});
297
+ }
298
+ return this.startDelayedIntent({
299
+ ...rest,
300
+ intent: {
301
+ type: "CLOSE_AAVE_POSITION",
302
+ token,
303
+ to,
304
+ holdings
305
+ }
306
+ });
307
+ }
308
+ /**
276
309
  * Previews a delayable intent both ways at once: settled by the router now,
277
310
  * and started as a redemption that finishes days later.
278
311
  *
@@ -153,6 +153,25 @@ function buildAaveOpenPositionOperation(input) {
153
153
  calls: [input.adapter.openPositionDiffCall(input.aToken, input.debtToken, 0n, input.borrowAmount)]
154
154
  };
155
155
  }
156
+ function buildAaveClosePositionOperation(input) {
157
+ return {
158
+ type: "aaveClosePosition",
159
+ aToken: input.aToken,
160
+ aTokenAmount: input.aTokenAmount,
161
+ debtToken: input.debtToken,
162
+ repayAmount: input.repayAmount,
163
+ calls: [input.adapter.closePositionCall(input.aToken, input.debtToken, input.repayAmount, input.aTokenAmount)]
164
+ };
165
+ }
166
+ function buildAaveWithdrawOperation(input) {
167
+ return {
168
+ type: "aaveWithdraw",
169
+ token: input.token,
170
+ aToken: input.aToken,
171
+ amount: input.amount,
172
+ calls: [input.adapter.withdrawDiffCall(input.token, 0n)]
173
+ };
174
+ }
156
175
  /**
157
176
  * What a request or a claim puts on the account right away, as opposed to what
158
177
  * only the phantom token represents.
@@ -168,4 +187,4 @@ function instantOutput(outputs, token) {
168
187
  }
169
188
  }
170
189
  //#endregion
171
- export { buildAaveOpenPositionOperation, buildAaveSupplyOperation, buildAddCollateralOperation, buildClaimDelayedWithdrawalOperation, buildCloseSwapOperation, buildDecreaseDebtOperation, buildIncreaseDebtOperation, buildQuotaUpdateOperation, buildStartDelayedWithdrawalOperation, buildSwapOperation, buildUnwrapRwaCollateralOperation, buildWithdrawCollateralOperation, buildWrapRwaCollateralOperation, instantOutput };
190
+ export { buildAaveClosePositionOperation, buildAaveOpenPositionOperation, buildAaveSupplyOperation, buildAaveWithdrawOperation, buildAddCollateralOperation, buildClaimDelayedWithdrawalOperation, buildCloseSwapOperation, buildDecreaseDebtOperation, buildIncreaseDebtOperation, buildQuotaUpdateOperation, buildStartDelayedWithdrawalOperation, buildSwapOperation, buildUnwrapRwaCollateralOperation, buildWithdrawCollateralOperation, buildWrapRwaCollateralOperation, instantOutput };
@@ -1,4 +1,4 @@
1
- import { MAX_UINT256, PERCENTAGE_FACTOR, isZeroBalance } from "../../constants/math.js";
1
+ import { MAX_UINT256, PERCENTAGE_FACTOR, RAY, SECONDS_PER_YEAR, isZeroBalance } from "../../constants/math.js";
2
2
  import "../../constants/index.js";
3
3
  import { debtOutOfRange, insufficientBalance, leverageOutOfRange } from "../../../model/errors/operation-errors.js";
4
4
  import { noDelayedRoute, unsupportedCollateralToken } from "../../../model/errors/prepare-errors.js";
@@ -147,6 +147,53 @@ function planMoveToAave(intent, view) {
147
147
  ];
148
148
  }
149
149
  /**
150
+ * The owner's Aave position comes back and leaves: the account borrows what
151
+ * the owner owes on Aave, the bridge repays it and returns the aTokens, the
152
+ * pool turns them back into the RWA, and the RWA is requested for redemption
153
+ * with an exit recorded for the tail — all in one transaction.
154
+ *
155
+ * The repayment is the debt plus {@link CLOSE_AAVE_WINDOW} of interest at the
156
+ * current rate, see {@link CloseAavePositionIntent}.
157
+ */
158
+ function planCloseAavePosition(intent, view) {
159
+ const { token, holdings } = intent;
160
+ const U = view.underlying;
161
+ if (eq(token, U) || isZeroBalance(holdings.supplied)) throw new IntentPreviewError(unsupportedCollateralToken(toToken(view.sdk, token)), `closeAavePosition: the owner holds no aToken of ${token} on Aave`);
162
+ if (holdings.owed <= 0n) throw new IntentPreviewError(debtOutOfRange({
163
+ requested: toTokenAmount(view.sdk, U, 0n),
164
+ minDebt: toTokenAmount(view.sdk, U, view.debtLimits.minDebt),
165
+ maxDebt: toTokenAmount(view.sdk, U, view.debtLimits.maxDebt)
166
+ }), "closeAavePosition: the owner owes nothing on Aave");
167
+ const repay = holdings.owed + ceilDiv(holdings.owed * holdings.borrowRate * CLOSE_AAVE_WINDOW, RAY * BigInt(SECONDS_PER_YEAR));
168
+ let borrowed = toTargetDecimals(repay, holdings.debtToken, U, view.sdk);
169
+ if (toTargetDecimals(borrowed, U, holdings.debtToken, view.sdk) < repay) borrowed += 1n;
170
+ assertDebtLimits(view.sdk, view.debt + borrowed, view.debtLimits, U, view.limits);
171
+ return [
172
+ borrow(borrowed),
173
+ ...eq(holdings.debtToken, U) ? [] : [convert(U, holdings.debtToken, borrowed)],
174
+ {
175
+ kind: "aaveClosePosition",
176
+ token,
177
+ repay,
178
+ aTokenAmount: holdings.supplied
179
+ },
180
+ {
181
+ kind: "aaveWithdraw",
182
+ token
183
+ },
184
+ {
185
+ kind: "request",
186
+ token,
187
+ amount: view.balanceOf(token) + holdings.supplied,
188
+ reserve: 0n,
189
+ record: {
190
+ type: "CLOSE_ACCOUNT",
191
+ to: intent.to
192
+ }
193
+ }
194
+ ];
195
+ }
196
+ /**
150
197
  * One token's quota changes; no balance moves and debt is untouched.
151
198
  *
152
199
  * Only a token the account holds can be quoted here, and only on an account
@@ -449,6 +496,13 @@ const clearQuotas = () => ({ kind: "clearQuotas" });
449
496
  */
450
497
  const SETTLE_MARGIN = 10n;
451
498
  const withMargin = (debt) => debt + debt * SETTLE_MARGIN / PERCENTAGE_FACTOR;
499
+ /**
500
+ * Seconds of Aave interest a closing repays on top of the debt it read: the
501
+ * bridge keeps whatever Aave does not take, so this is paid for, unlike
502
+ * {@link SETTLE_MARGIN}, and an hour costs a fraction of a basis point.
503
+ */
504
+ const CLOSE_AAVE_WINDOW = 3600n;
505
+ const ceilDiv = (a, b) => (a + b - 1n) / b;
452
506
  /** The amount that asks for all of it, whatever "all" turns out to be. */
453
507
  const everything = (amount) => amount >= MAX_UINT256;
454
508
  const min = (a, b) => a < b ? a : b;
@@ -488,4 +542,4 @@ function assertPositive(amount, flow) {
488
542
  if (amount <= 0n) throw new IntentPreviewError(insufficientBalance(), `${flow}: amount must be positive`);
489
543
  }
490
544
  //#endregion
491
- export { RAISED, planAddCollateral, planAdjustLeverage, planAdjustLeverageDelayed, planBorrowAndWithdraw, planDeposit, planFinishClaimOnly, planFinishCloseAccount, planFinishDecreaseLeverage, planFinishWithdraw, planMoveToAave, planRepay, planUpdateQuota, planWithdraw, planWithdrawAsset, planWithdrawDelayed };
545
+ export { RAISED, planAddCollateral, planAdjustLeverage, planAdjustLeverageDelayed, planBorrowAndWithdraw, planCloseAavePosition, planDeposit, planFinishClaimOnly, planFinishCloseAccount, planFinishDecreaseLeverage, planFinishWithdraw, planMoveToAave, planRepay, planUpdateQuota, planWithdraw, planWithdrawAsset, planWithdrawDelayed };
@@ -0,0 +1,55 @@
1
+ import { iAaveV3PoolAbi } from "../../market/adapters/abi/aave/iAaveV3Pool.js";
2
+ import "../../market/adapters/abi/aave/index.js";
3
+ import { AaveV3PoolAdapterContract } from "../../market/adapters/contracts/AaveV3PoolAdapterContract.js";
4
+ import { unsupportedCollateralToken } from "../../../model/errors/prepare-errors.js";
5
+ import "../../../model/index.js";
6
+ import { toToken } from "../../validation/helpers/token.js";
7
+ import { IntentPreviewError } from "../../validation/raise.js";
8
+ import { erc20Abi } from "viem";
9
+ //#region src/onchain/accounts/intents/readAaveHoldings.ts
10
+ /**
11
+ * What `owner` holds and owes on the Aave pool the credit manager supplies
12
+ * `token` to: its aTokens of `token`, and its variable debt in the asset the
13
+ * Horizon bridge lends there — the underlying, or the asset an RWA underlying
14
+ * wraps.
15
+ *
16
+ * Refused with `unsupportedCollateralToken` when no Aave pool adapter of the
17
+ * credit manager lists `token`.
18
+ */
19
+ async function readAaveHoldings(sdk, creditManager, owner, token) {
20
+ const suite = sdk.marketRegister.findCreditManager(creditManager);
21
+ const adapter = suite.creditManager.adapters.values().find((a) => a instanceof AaveV3PoolAdapterContract && a.isAssetAllowed(token));
22
+ if (!adapter) throw new IntentPreviewError(unsupportedCollateralToken(toToken(sdk, token)), `readAaveHoldings: no Aave pool adapter lists ${token}`);
23
+ const underlying = suite.underlying;
24
+ const debtToken = sdk.tokensMeta.rwaUnderlyings.get(underlying)?.asset ?? underlying;
25
+ const [aToken, reserve] = await Promise.all([adapter.aToken(token), sdk.client.readContract({
26
+ address: adapter.pool,
27
+ abi: iAaveV3PoolAbi,
28
+ functionName: "getReserveData",
29
+ args: [debtToken]
30
+ })]);
31
+ const [supplied, owed] = await sdk.client.multicall({
32
+ contracts: [{
33
+ address: aToken,
34
+ abi: erc20Abi,
35
+ functionName: "balanceOf",
36
+ args: [owner]
37
+ }, {
38
+ address: reserve.variableDebtTokenAddress,
39
+ abi: erc20Abi,
40
+ functionName: "balanceOf",
41
+ args: [owner]
42
+ }],
43
+ allowFailure: false,
44
+ batchSize: 0
45
+ });
46
+ return {
47
+ aToken,
48
+ debtToken,
49
+ supplied,
50
+ owed,
51
+ borrowRate: reserve.currentVariableBorrowRate
52
+ };
53
+ }
54
+ //#endregion
55
+ export { readAaveHoldings };