@gearbox-protocol/sdk 18.4.1-aave.1 → 18.4.1-aave.11

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 (165) hide show
  1. package/dist/cjs/abi/rwa/iSecuritizeRWAFactory.js +15 -0
  2. package/dist/cjs/model/errors/index.js +1 -0
  3. package/dist/cjs/model/errors/operation-errors.js +9 -0
  4. package/dist/cjs/model/index.js +1 -0
  5. package/dist/cjs/onchain/accounts/bots/AccountBotsService.js +29 -0
  6. package/dist/cjs/onchain/accounts/bots/PeripheryCompressorV310Contract.js +2 -1
  7. package/dist/cjs/onchain/accounts/index.js +1 -1
  8. package/dist/cjs/onchain/accounts/intents/index.js +33 -1
  9. package/dist/cjs/onchain/accounts/intents/operations.js +13 -13
  10. package/dist/cjs/onchain/accounts/intents/plan.js +45 -23
  11. package/dist/cjs/onchain/accounts/intents/readAaveHoldings.js +56 -0
  12. package/dist/cjs/onchain/accounts/intents/realize.js +61 -23
  13. package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +1 -1
  14. package/dist/cjs/onchain/accounts/intents/utils/ledger.js +6 -6
  15. package/dist/cjs/onchain/chain/chains.js +1 -0
  16. package/dist/cjs/onchain/index.js +13 -1
  17. package/dist/cjs/onchain/market/ZapperRegister.js +1 -1
  18. package/dist/cjs/onchain/market/adapters/abi/aave/iAaveOracle.js +20 -0
  19. package/dist/cjs/onchain/market/adapters/abi/aave/iAaveV3Pool.js +166 -0
  20. package/dist/cjs/onchain/market/adapters/abi/aave/iPoolAddressesProvider.js +11 -0
  21. package/dist/cjs/onchain/market/adapters/abi/aave/iVariableDebtToken.js +17 -0
  22. package/dist/cjs/onchain/market/adapters/abi/aave/index.js +6 -0
  23. package/dist/cjs/onchain/market/adapters/abi/adapters/iAaveHorizonBridgeAdapter.js +27 -0
  24. package/dist/cjs/onchain/market/adapters/abi/index.js +8 -0
  25. package/dist/cjs/onchain/market/adapters/abi/securitize/iSecuritizeNAVProvider.js +15 -0
  26. package/dist/cjs/onchain/market/adapters/abi/securitize/index.js +2 -0
  27. package/dist/cjs/onchain/market/adapters/contracts/AaveHorizonBridgeAdapterContract.js +100 -12
  28. package/dist/cjs/onchain/market/adapters/contracts/AaveV3PoolAdapterContract.js +19 -11
  29. package/dist/cjs/onchain/market/adapters/contracts/SecuritizeRedemptionGatewayAdapterContract.js +42 -5
  30. package/dist/cjs/onchain/market/adapters/index.js +8 -0
  31. package/dist/cjs/onchain/market/index.js +8 -0
  32. package/dist/cjs/onchain/market/rwa/securitize/SecuritizeRWAFactory.js +9 -0
  33. package/dist/cjs/onchain/positions/MultichainPositionsService.js +15 -0
  34. package/dist/cjs/onchain/positions/PositionsService.js +31 -0
  35. package/dist/cjs/onchain/positions/aaveMoveCalls.js +45 -0
  36. package/dist/cjs/onchain/positions/projectAavePosition.js +164 -26
  37. package/dist/cjs/onchain/positions/readAavePosition.js +152 -0
  38. package/dist/cjs/onchain/preview/index.js +2 -0
  39. package/dist/cjs/onchain/preview/preview/aaveBridgeBorrows.js +24 -0
  40. package/dist/cjs/onchain/preview/preview/aaveMoveStart.js +27 -0
  41. package/dist/cjs/onchain/preview/preview/index.js +2 -0
  42. package/dist/cjs/onchain/preview/preview/previewAdjustStrategyPosition.js +3 -0
  43. package/dist/cjs/onchain/preview/preview/previewExitOrRepayStrategyPosition.js +5 -2
  44. package/dist/cjs/onchain/preview/preview/previewOpenStrategyPosition.js +4 -1
  45. package/dist/cjs/onchain/preview/preview/previewOperation.js +31 -8
  46. package/dist/cjs/onchain/validation/bundles/checkAaveDelegation.js +54 -0
  47. package/dist/cjs/onchain/validation/bundles/checkCreditOperation.js +36 -11
  48. package/dist/cjs/onchain/validation/bundles/index.js +2 -0
  49. package/dist/cjs/onchain/validation/checkOperation.js +16 -4
  50. package/dist/cjs/onchain/validation/index.js +2 -0
  51. package/dist/cjs/sdk/execute/ExecuteApi.js +1 -0
  52. package/dist/cjs/sdk/positions/PositionsNamespace.js +6 -0
  53. package/dist/cjs/sdk/prepare/PrepareApi.js +68 -9
  54. package/dist/cjs/sdk/preview/PreviewNamespace.js +11 -2
  55. package/dist/esm/abi/rwa/iSecuritizeRWAFactory.js +15 -0
  56. package/dist/esm/model/errors/index.js +2 -2
  57. package/dist/esm/model/errors/operation-errors.js +9 -1
  58. package/dist/esm/model/index.js +2 -2
  59. package/dist/esm/onchain/accounts/bots/AccountBotsService.js +29 -0
  60. package/dist/esm/onchain/accounts/bots/PeripheryCompressorV310Contract.js +1 -1
  61. package/dist/esm/onchain/accounts/index.js +1 -1
  62. package/dist/esm/onchain/accounts/intents/index.js +34 -2
  63. package/dist/esm/onchain/accounts/intents/operations.js +12 -12
  64. package/dist/esm/onchain/accounts/intents/plan.js +46 -24
  65. package/dist/esm/onchain/accounts/intents/readAaveHoldings.js +55 -0
  66. package/dist/esm/onchain/accounts/intents/realize.js +62 -24
  67. package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +1 -1
  68. package/dist/esm/onchain/accounts/intents/utils/ledger.js +6 -6
  69. package/dist/esm/onchain/chain/chains.js +1 -0
  70. package/dist/esm/onchain/index.js +8 -2
  71. package/dist/esm/onchain/market/ZapperRegister.js +1 -1
  72. package/dist/esm/onchain/market/adapters/abi/aave/iAaveOracle.js +19 -0
  73. package/dist/esm/onchain/market/adapters/abi/aave/iAaveV3Pool.js +166 -0
  74. package/dist/esm/onchain/market/adapters/abi/aave/iPoolAddressesProvider.js +10 -0
  75. package/dist/esm/onchain/market/adapters/abi/aave/iVariableDebtToken.js +16 -0
  76. package/dist/esm/onchain/market/adapters/abi/aave/index.js +4 -1
  77. package/dist/esm/onchain/market/adapters/abi/adapters/iAaveHorizonBridgeAdapter.js +27 -0
  78. package/dist/esm/onchain/market/adapters/abi/index.js +5 -1
  79. package/dist/esm/onchain/market/adapters/abi/securitize/iSecuritizeNAVProvider.js +14 -0
  80. package/dist/esm/onchain/market/adapters/abi/securitize/index.js +2 -1
  81. package/dist/esm/onchain/market/adapters/contracts/AaveHorizonBridgeAdapterContract.js +101 -13
  82. package/dist/esm/onchain/market/adapters/contracts/AaveV3PoolAdapterContract.js +20 -12
  83. package/dist/esm/onchain/market/adapters/contracts/SecuritizeRedemptionGatewayAdapterContract.js +43 -6
  84. package/dist/esm/onchain/market/adapters/index.js +5 -1
  85. package/dist/esm/onchain/market/index.js +5 -1
  86. package/dist/esm/onchain/market/rwa/securitize/SecuritizeRWAFactory.js +9 -0
  87. package/dist/esm/onchain/positions/MultichainPositionsService.js +15 -0
  88. package/dist/esm/onchain/positions/PositionsService.js +31 -0
  89. package/dist/esm/onchain/positions/aaveMoveCalls.js +44 -0
  90. package/dist/esm/onchain/positions/projectAavePosition.js +165 -27
  91. package/dist/esm/onchain/positions/readAavePosition.js +151 -0
  92. package/dist/esm/onchain/preview/index.js +2 -1
  93. package/dist/esm/onchain/preview/preview/aaveBridgeBorrows.js +23 -0
  94. package/dist/esm/onchain/preview/preview/aaveMoveStart.js +26 -0
  95. package/dist/esm/onchain/preview/preview/index.js +2 -1
  96. package/dist/esm/onchain/preview/preview/previewAdjustStrategyPosition.js +3 -0
  97. package/dist/esm/onchain/preview/preview/previewExitOrRepayStrategyPosition.js +5 -2
  98. package/dist/esm/onchain/preview/preview/previewOpenStrategyPosition.js +4 -1
  99. package/dist/esm/onchain/preview/preview/previewOperation.js +31 -8
  100. package/dist/esm/onchain/validation/bundles/checkAaveDelegation.js +53 -0
  101. package/dist/esm/onchain/validation/bundles/checkCreditOperation.js +36 -11
  102. package/dist/esm/onchain/validation/bundles/index.js +2 -1
  103. package/dist/esm/onchain/validation/checkOperation.js +16 -4
  104. package/dist/esm/onchain/validation/index.js +2 -1
  105. package/dist/esm/sdk/execute/ExecuteApi.js +1 -0
  106. package/dist/esm/sdk/positions/PositionsNamespace.js +6 -0
  107. package/dist/esm/sdk/prepare/PrepareApi.js +69 -10
  108. package/dist/esm/sdk/preview/PreviewNamespace.js +11 -2
  109. package/dist/types/abi/rwa/iSecuritizeRWAFactory.d.ts +14 -0
  110. package/dist/types/model/aave.d.ts +60 -3
  111. package/dist/types/model/errors/index.d.ts +2 -2
  112. package/dist/types/model/errors/operation-errors.d.ts +19 -0
  113. package/dist/types/model/index.d.ts +5 -5
  114. package/dist/types/model/opportunities.d.ts +1 -1
  115. package/dist/types/model/previews.d.ts +18 -2
  116. package/dist/types/onchain/accounts/bots/AccountBotsService.d.ts +11 -1
  117. package/dist/types/onchain/accounts/bots/index.d.ts +2 -2
  118. package/dist/types/onchain/accounts/bots/types.d.ts +7 -1
  119. package/dist/types/onchain/accounts/index.d.ts +3 -3
  120. package/dist/types/onchain/accounts/intents/index.d.ts +21 -3
  121. package/dist/types/onchain/accounts/intents/operations.d.ts +27 -23
  122. package/dist/types/onchain/accounts/intents/plan.d.ts +23 -19
  123. package/dist/types/onchain/accounts/intents/readAaveHoldings.d.ts +16 -0
  124. package/dist/types/onchain/accounts/intents/types.d.ts +37 -14
  125. package/dist/types/onchain/index.d.ts +10 -4
  126. package/dist/types/onchain/market/adapters/abi/aave/iAaveOracle.d.ts +22 -0
  127. package/dist/types/onchain/market/adapters/abi/aave/iAaveV3Pool.d.ts +139 -0
  128. package/dist/types/onchain/market/adapters/abi/aave/iPoolAddressesProvider.d.ts +11 -0
  129. package/dist/types/onchain/market/adapters/abi/aave/iVariableDebtToken.d.ts +17 -0
  130. package/dist/types/onchain/market/adapters/abi/aave/index.d.ts +4 -1
  131. package/dist/types/onchain/market/adapters/abi/adapters/iAaveHorizonBridgeAdapter.d.ts +21 -0
  132. package/dist/types/onchain/market/adapters/abi/index.d.ts +5 -1
  133. package/dist/types/onchain/market/adapters/abi/securitize/iSecuritizeNAVProvider.d.ts +13 -0
  134. package/dist/types/onchain/market/adapters/abi/securitize/index.d.ts +2 -1
  135. package/dist/types/onchain/market/adapters/contracts/AaveHorizonBridgeAdapterContract.d.ts +59 -10
  136. package/dist/types/onchain/market/adapters/contracts/AaveV3PoolAdapterContract.d.ts +147 -4
  137. package/dist/types/onchain/market/adapters/contracts/SecuritizeRedemptionGatewayAdapterContract.d.ts +19 -4
  138. package/dist/types/onchain/market/adapters/index.d.ts +5 -1
  139. package/dist/types/onchain/market/index.d.ts +5 -1
  140. package/dist/types/onchain/market/rwa/securitize/SecuritizeRWAFactory.d.ts +20 -0
  141. package/dist/types/onchain/market/rwa/types.d.ts +6 -0
  142. package/dist/types/onchain/positions/MultichainPositionsService.d.ts +7 -1
  143. package/dist/types/onchain/positions/PositionsService.d.ts +16 -2
  144. package/dist/types/onchain/positions/aaveMoveCalls.d.ts +30 -0
  145. package/dist/types/onchain/positions/index.d.ts +2 -2
  146. package/dist/types/onchain/positions/projectAavePosition.d.ts +34 -4
  147. package/dist/types/onchain/positions/readAavePosition.d.ts +22 -0
  148. package/dist/types/onchain/positions/types.d.ts +25 -0
  149. package/dist/types/onchain/preview/index.d.ts +2 -1
  150. package/dist/types/onchain/preview/preview/aaveBridgeBorrows.d.ts +15 -0
  151. package/dist/types/onchain/preview/preview/aaveMoveStart.d.ts +18 -0
  152. package/dist/types/onchain/preview/preview/index.d.ts +2 -1
  153. package/dist/types/onchain/validation/bundles/checkAaveDelegation.d.ts +21 -0
  154. package/dist/types/onchain/validation/bundles/checkCreditOperation.d.ts +2 -2
  155. package/dist/types/onchain/validation/bundles/index.d.ts +2 -1
  156. package/dist/types/onchain/validation/index.d.ts +2 -1
  157. package/dist/types/sdk/execute/types.d.ts +7 -5
  158. package/dist/types/sdk/index.d.ts +2 -2
  159. package/dist/types/sdk/positions/PositionsNamespace.d.ts +6 -1
  160. package/dist/types/sdk/positions/types.d.ts +9 -1
  161. package/dist/types/sdk/prepare/PrepareApi.d.ts +4 -4
  162. package/dist/types/sdk/prepare/index.d.ts +2 -2
  163. package/dist/types/sdk/prepare/types.d.ts +88 -28
  164. package/dist/types/sdk/preview/types.d.ts +4 -2
  165. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import "./base.js";
2
2
  import { creditAccountFrozen, liquidatorNotEligible, notEmergencyLiquidator, partialLiquidationImpossible } from "./liquidation-errors.js";
3
- import { accountNotMidasGreenlisted, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaAboveMax, quotaCountExceeded, quotaInactive, quotaLimitReached, quotaUnchanged, reservePriceLimited, rwaOpenRequirementsNotMet } from "./operation-errors.js";
3
+ import { accountNotMidasGreenlisted, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientBorrowAllowance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaAboveMax, quotaCountExceeded, quotaInactive, quotaLimitReached, quotaUnchanged, reservePriceLimited, rwaOpenRequirementsNotMet } from "./operation-errors.js";
4
4
  import { unpriceableTokenError } from "./oracle-errors.js";
5
5
  import { creditAccountNotEmpty, creditAccountNotFound, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, unexpectedFailure, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress } from "./prepare-errors.js";
6
6
  import { malformedTransaction } from "./preview-errors.js";
7
- export { accountNotMidasGreenlisted, creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, liquidatorNotEligible, malformedTransaction, marketExpired, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, partialLiquidationImpossible, poolPaused, poolSunset, quotaAboveMax, quotaCountExceeded, quotaInactive, quotaLimitReached, quotaUnchanged, reservePriceLimited, rwaOpenRequirementsNotMet, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress };
7
+ export { accountNotMidasGreenlisted, creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientBorrowAllowance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, liquidatorNotEligible, malformedTransaction, marketExpired, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, partialLiquidationImpossible, poolPaused, poolSunset, quotaAboveMax, quotaCountExceeded, quotaInactive, quotaLimitReached, quotaUnchanged, reservePriceLimited, rwaOpenRequirementsNotMet, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress };
@@ -141,6 +141,14 @@ function insufficientAllowance(args) {
141
141
  ...args
142
142
  };
143
143
  }
144
+ /** {@inheritDoc InsufficientBorrowAllowanceError} */
145
+ function insufficientBorrowAllowance(args) {
146
+ return {
147
+ code: "insufficientBorrowAllowance",
148
+ message: `${args.required.value} of ${args.required.token.symbol} borrowing must be delegated to ${args.spender} on ${args.debtToken}, ${args.allowed.value} is.`,
149
+ ...args
150
+ };
151
+ }
144
152
  /** {@inheritDoc RWAOpenRequirementsError} */
145
153
  function rwaOpenRequirementsNotMet(args) {
146
154
  return {
@@ -158,4 +166,4 @@ function accountNotMidasGreenlisted(args) {
158
166
  };
159
167
  }
160
168
  //#endregion
161
- export { accountNotMidasGreenlisted, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaAboveMax, quotaCountExceeded, quotaInactive, quotaLimitReached, quotaUnchanged, reservePriceLimited, rwaOpenRequirementsNotMet };
169
+ export { accountNotMidasGreenlisted, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientBorrowAllowance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaAboveMax, quotaCountExceeded, quotaInactive, quotaLimitReached, quotaUnchanged, reservePriceLimited, rwaOpenRequirementsNotMet };
@@ -16,7 +16,7 @@ import { ANALYTICS_POSITIONS_DEFAULT_LIMIT, ANALYTICS_POSITIONS_MAX_LIMIT, analy
16
16
  import "./curators.js";
17
17
  import "./delayed-intents.js";
18
18
  import { creditAccountFrozen, liquidatorNotEligible, notEmergencyLiquidator, partialLiquidationImpossible } from "./errors/liquidation-errors.js";
19
- import { accountNotMidasGreenlisted, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaAboveMax, quotaCountExceeded, quotaInactive, quotaLimitReached, quotaUnchanged, reservePriceLimited, rwaOpenRequirementsNotMet } from "./errors/operation-errors.js";
19
+ import { accountNotMidasGreenlisted, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientBorrowAllowance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaAboveMax, quotaCountExceeded, quotaInactive, quotaLimitReached, quotaUnchanged, reservePriceLimited, rwaOpenRequirementsNotMet } from "./errors/operation-errors.js";
20
20
  import { unpriceableTokenError } from "./errors/oracle-errors.js";
21
21
  import { creditAccountNotEmpty, creditAccountNotFound, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, unexpectedFailure, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress } from "./errors/prepare-errors.js";
22
22
  import { malformedTransaction } from "./errors/preview-errors.js";
@@ -32,4 +32,4 @@ import { safeValue, sdkErr, sdkOk } from "./result.js";
32
32
  import "./rewards.js";
33
33
  import "./withdrawals.js";
34
34
  import { positionClaimableWithdrawalSchema, positionPendingWithdrawalSchema, positionWithdrawalsSchema, withdrawalOutputAmountSchema } from "./withdrawals.schema.js";
35
- export { ANALYTICS_POSITIONS_DEFAULT_LIMIT, ANALYTICS_POSITIONS_MAX_LIMIT, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, FILTER_ALL, KYC_REGISTRATION_LINKS, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PROTOCOL_CHART_METRICS, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_PROTOCOLS, SECURITIZE_REGISTER_VAULT_TYPES, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, accountNotMidasGreenlisted, amountSchema, analyticsChartQueryOptionsSchema, analyticsChartQueryParamsSchema, analyticsChartQuerySchema, analyticsContractOptionSchema, analyticsContractRefSchema, analyticsCuratorOptionSchema, analyticsPositionFilterOptionsQuerySchema, analyticsPositionFilterOptionsSchema, analyticsPositionListOptionsSchema, analyticsPositionListQueryParamsSchema, analyticsPositionListQuerySchema, analyticsPositionPageSchema, analyticsPositionSchema, analyticsPositionSortFieldSchema, analyticsSortDirectionSchema, apyBreakdownSchema, asEstimated, assetTypeSchema, backendPreferred, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, compareTagOf, creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, curatorNameSchema, curatorSchema, dataSourceSchema, debtOutOfRange, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, forbiddenToken, instantReceivedAssetSchema, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, isFilterSet, kycRequirementSchema, leverageOutOfRange, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, liquidatorNotEligible, malformedTransaction, marketExpired, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, partialLiquidationImpossible, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPaused, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, poolSunset, positionClaimableWithdrawalSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionPendingWithdrawalSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionWithdrawalsSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, protocolChartMetricSchema, quotaAboveMax, quotaAssetSchema, quotaCountExceeded, quotaInactive, quotaLimitReached, quotaUnchanged, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, reservePriceLimited, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, rwaOpenRequirementsNotMet, rwaProtocolSchema, safeValue, sdkErr, sdkOk, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress, withdrawalOutputAmountSchema };
35
+ export { ANALYTICS_POSITIONS_DEFAULT_LIMIT, ANALYTICS_POSITIONS_MAX_LIMIT, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, FILTER_ALL, KYC_REGISTRATION_LINKS, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PROTOCOL_CHART_METRICS, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_PROTOCOLS, SECURITIZE_REGISTER_VAULT_TYPES, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, accountNotMidasGreenlisted, amountSchema, analyticsChartQueryOptionsSchema, analyticsChartQueryParamsSchema, analyticsChartQuerySchema, analyticsContractOptionSchema, analyticsContractRefSchema, analyticsCuratorOptionSchema, analyticsPositionFilterOptionsQuerySchema, analyticsPositionFilterOptionsSchema, analyticsPositionListOptionsSchema, analyticsPositionListQueryParamsSchema, analyticsPositionListQuerySchema, analyticsPositionPageSchema, analyticsPositionSchema, analyticsPositionSortFieldSchema, analyticsSortDirectionSchema, apyBreakdownSchema, asEstimated, assetTypeSchema, backendPreferred, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, compareTagOf, creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, curatorNameSchema, curatorSchema, dataSourceSchema, debtOutOfRange, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, forbiddenToken, instantReceivedAssetSchema, insufficientAllowance, insufficientBalance, insufficientBorrowAllowance, insufficientCollateral, insufficientPoolLiquidity, isFilterSet, kycRequirementSchema, leverageOutOfRange, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, liquidatorNotEligible, malformedTransaction, marketExpired, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, partialLiquidationImpossible, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPaused, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, poolSunset, positionClaimableWithdrawalSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionPendingWithdrawalSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionWithdrawalsSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, protocolChartMetricSchema, quotaAboveMax, quotaAssetSchema, quotaCountExceeded, quotaInactive, quotaLimitReached, quotaUnchanged, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, reservePriceLimited, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, rwaOpenRequirementsNotMet, rwaProtocolSchema, safeValue, sdkErr, sdkOk, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress, withdrawalOutputAmountSchema };
@@ -1,7 +1,10 @@
1
1
  import { iBotListV310Abi } from "../../../abi/310/generated.js";
2
+ import { peripheryCompressorAbi } from "../../../abi/compressors/peripheryCompressor.js";
3
+ import { AddressMap } from "../../utils/AddressMap.js";
2
4
  import { AP_PERIPHERY_COMPRESSOR } from "../../constants/address-provider.js";
3
5
  import { VERSION_RANGE_310 } from "../../constants/versions.js";
4
6
  import "../../constants/index.js";
7
+ import "../../utils/index.js";
5
8
  import { SDKConstruct } from "../../base/SDKConstruct.js";
6
9
  import "../../base/index.js";
7
10
  import { iBotAbi } from "./abi.js";
@@ -14,6 +17,32 @@ import { PeripheryCompressorV310Contract } from "./PeripheryCompressorV310Contra
14
17
  * and builds the transactions that connect or disconnect one.
15
18
  **/
16
19
  var AccountBotsService = class extends SDKConstruct {
20
+ #marketBots = new AddressMap(void 0, "marketBots");
21
+ /**
22
+ * The bots a market configurator lists among its periphery contracts.
23
+ *
24
+ * Read once per configurator and kept for the service's lifetime: the list
25
+ * changes only when the curator adds or removes a bot. A failed read is not
26
+ * kept, so the next call tries again.
27
+ *
28
+ * @param marketConfigurator - Configurator to list the bots of.
29
+ **/
30
+ getMarketBots(marketConfigurator) {
31
+ let bots = this.#marketBots.get(marketConfigurator);
32
+ if (!bots) {
33
+ bots = this.client.readContract({
34
+ address: this.#compressor.address,
35
+ abi: peripheryCompressorAbi,
36
+ functionName: "getBots",
37
+ args: [marketConfigurator]
38
+ }).catch((e) => {
39
+ this.#marketBots.delete(marketConfigurator);
40
+ throw e;
41
+ });
42
+ this.#marketBots.upsert(marketConfigurator, bots);
43
+ }
44
+ return bots;
45
+ }
17
46
  /**
18
47
  * Reads the bots connected to each of the given credit accounts.
19
48
  *
@@ -1,6 +1,6 @@
1
+ import { peripheryCompressorAbi } from "../../../abi/compressors/peripheryCompressor.js";
1
2
  import { BaseContract } from "../../base/BaseContract.js";
2
3
  import "../../base/index.js";
3
- import { peripheryCompressorAbi } from "../../../abi/compressors/peripheryCompressor.js";
4
4
  //#region src/onchain/accounts/bots/PeripheryCompressorV310Contract.ts
5
5
  const abi = peripheryCompressorAbi;
6
6
  var PeripheryCompressorV310Contract = class extends BaseContract {
@@ -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, 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";
@@ -65,7 +66,6 @@ var CreditAccountOperationsService = class extends SDKConstruct {
65
66
  case "ADJUST_LEVERAGE": return planAdjustLeverage(intent, view);
66
67
  case "DEPOSIT": return planDeposit(intent, view);
67
68
  case "REPAY": return planRepay(intent, view);
68
- case "MOVE_TO_AAVE": return planMoveToAave(intent, view);
69
69
  case "WITHDRAW": return planWithdraw(intent, view);
70
70
  case "UPDATE_QUOTA": return planUpdateQuota(intent, view);
71
71
  default: throw new Error(`${intent.type} - not implemented`);
@@ -239,6 +239,7 @@ var CreditAccountOperationsService = class extends SDKConstruct {
239
239
  switch (intent.type) {
240
240
  case "ADJUST_LEVERAGE": return planAdjustLeverageDelayed(intent, view);
241
241
  case "WITHDRAW": return planWithdrawDelayed(intent, view);
242
+ case "CLOSE_AAVE_POSITION": return planCloseAavePosition(intent, view);
242
243
  default: throw new Error(`${intent.type} - cannot be delayed`);
243
244
  }
244
245
  }, limits);
@@ -273,6 +274,37 @@ var CreditAccountOperationsService = class extends SDKConstruct {
273
274
  }
274
275
  }
275
276
  /**
277
+ * Previews leaving `owner`'s Aave Horizon position in `token` in one
278
+ * transaction, see {@link CloseAavePositionIntent}.
279
+ *
280
+ * What the owner holds and owes on Aave is read here, at the block the SDK
281
+ * stands at; the rest is {@link startDelayedIntent}, tail included.
282
+ *
283
+ * @param props - Account slice, quota reserve and slippage, the RWA, the
284
+ * wallet the exit pays, and the owner the bridge resolves for the account:
285
+ * the investor of an RWA factory account, the borrower otherwise
286
+ * @returns The request transaction, the state the exit ends in and what it
287
+ * recorded for the tail, or `{ ok: false, error }`
288
+ */
289
+ async closeAavePositionIntent(props) {
290
+ const { token, to, owner, ...rest } = props;
291
+ let holdings;
292
+ try {
293
+ holdings = await readAaveHoldings(rest.sdk, rest.creditAccount.creditManager, owner, token);
294
+ } catch (e) {
295
+ return asRefused(e, rest.draft ?? {});
296
+ }
297
+ return this.startDelayedIntent({
298
+ ...rest,
299
+ intent: {
300
+ type: "CLOSE_AAVE_POSITION",
301
+ token,
302
+ to,
303
+ holdings
304
+ }
305
+ });
306
+ }
307
+ /**
276
308
  * Previews a delayable intent both ways at once: settled by the router now,
277
309
  * and started as a redemption that finishes days later.
278
310
  *
@@ -134,23 +134,23 @@ function buildClaimDelayedWithdrawalOperation(input) {
134
134
  })
135
135
  };
136
136
  }
137
- function buildAaveSupplyOperation(input) {
137
+ function buildAaveClosePositionOperation(input) {
138
138
  return {
139
- type: "aaveSupply",
140
- token: input.token,
139
+ type: "aaveClosePosition",
141
140
  aToken: input.aToken,
142
- amount: input.amount,
143
- calls: [input.adapter.supplyCall(input.token, input.amount)]
141
+ aTokenAmount: input.aTokenAmount,
142
+ debtToken: input.debtToken,
143
+ repayAmount: input.repayAmount,
144
+ calls: [input.adapter.closePositionCall(input.aToken, input.debtToken, input.repayAmount, input.aTokenAmount)]
144
145
  };
145
146
  }
146
- function buildAaveOpenPositionOperation(input) {
147
+ function buildAaveWithdrawOperation(input) {
147
148
  return {
148
- type: "aaveOpenPosition",
149
+ type: "aaveWithdraw",
150
+ token: input.token,
149
151
  aToken: input.aToken,
150
- aTokenAmount: input.aTokenAmount,
151
- debtToken: input.debtToken,
152
- borrowAmount: input.borrowAmount,
153
- calls: [input.adapter.openPositionCall(input.aToken, input.debtToken, input.aTokenAmount, input.borrowAmount)]
152
+ amount: input.amount,
153
+ calls: [input.adapter.withdrawDiffCall(input.token, 0n)]
154
154
  };
155
155
  }
156
156
  /**
@@ -168,4 +168,4 @@ function instantOutput(outputs, token) {
168
168
  }
169
169
  }
170
170
  //#endregion
171
- export { buildAaveOpenPositionOperation, buildAaveSupplyOperation, buildAddCollateralOperation, buildClaimDelayedWithdrawalOperation, buildCloseSwapOperation, buildDecreaseDebtOperation, buildIncreaseDebtOperation, buildQuotaUpdateOperation, buildStartDelayedWithdrawalOperation, buildSwapOperation, buildUnwrapRwaCollateralOperation, buildWithdrawCollateralOperation, buildWrapRwaCollateralOperation, instantOutput };
171
+ export { buildAaveClosePositionOperation, 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";
@@ -104,35 +104,50 @@ function planRepay(intent, view) {
104
104
  ];
105
105
  }
106
106
  /**
107
- * The position leaves for Aave Horizon: the RWA is supplied to the Aave pool,
108
- * its aTokens go to the owner with a loan against them, and that loan settles
109
- * the account's own.
107
+ * The owner's Aave position comes back and leaves: the account borrows what
108
+ * the owner owes on Aave, the bridge repays it and returns the aTokens, the
109
+ * pool turns them back into the RWA, and the RWA is requested for redemption
110
+ * with an exit recorded for the tail — all in one transaction.
110
111
  *
111
- * Aave lends the debt plus the {@link SETTLE_MARGIN} headroom, since the facade
112
- * is told to repay everything outstanding by the time the transaction lands;
113
- * what it does not take stays on the account.
112
+ * The repayment is the debt plus {@link CLOSE_AAVE_WINDOW} of interest at the
113
+ * current rate, see {@link CloseAavePositionIntent}.
114
114
  */
115
- function planMoveToAave(intent, view) {
116
- const amount = view.balanceOf(intent.token);
117
- if (eq(intent.token, view.underlying) || isZeroBalance(amount)) throw new IntentPreviewError(unsupportedCollateralToken(toToken(view.sdk, intent.token)), `moveToAave: ${intent.token} is the underlying or not held by the account`);
118
- if (view.debt <= 0n) throw new IntentPreviewError(debtOutOfRange({
119
- requested: toTokenAmount(view.sdk, view.underlying, view.debt),
120
- minDebt: toTokenAmount(view.sdk, view.underlying, view.debtLimits.minDebt),
121
- maxDebt: toTokenAmount(view.sdk, view.underlying, view.debtLimits.maxDebt)
122
- }), "moveToAave: the account owes nothing");
115
+ function planCloseAavePosition(intent, view) {
116
+ const { token, holdings } = intent;
117
+ const U = view.underlying;
118
+ 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`);
119
+ if (holdings.owed <= 0n) throw new IntentPreviewError(debtOutOfRange({
120
+ requested: toTokenAmount(view.sdk, U, 0n),
121
+ minDebt: toTokenAmount(view.sdk, U, view.debtLimits.minDebt),
122
+ maxDebt: toTokenAmount(view.sdk, U, view.debtLimits.maxDebt)
123
+ }), "closeAavePosition: the owner owes nothing on Aave");
124
+ const repay = holdings.owed + ceilDiv(holdings.owed * holdings.borrowRate * CLOSE_AAVE_WINDOW, RAY * BigInt(SECONDS_PER_YEAR));
125
+ let borrowed = toTargetDecimals(repay, holdings.debtToken, U, view.sdk);
126
+ if (toTargetDecimals(borrowed, U, holdings.debtToken, view.sdk) < repay) borrowed += 1n;
127
+ assertDebtLimits(view.sdk, view.debt + borrowed, view.debtLimits, U, view.limits);
123
128
  return [
129
+ borrow(borrowed),
130
+ ...eq(holdings.debtToken, U) ? [] : [convert(U, holdings.debtToken, borrowed)],
124
131
  {
125
- kind: "aaveSupply",
126
- token: intent.token,
127
- amount
132
+ kind: "aaveClosePosition",
133
+ token,
134
+ repay,
135
+ aTokenAmount: holdings.supplied
128
136
  },
129
137
  {
130
- kind: "aaveOpenPosition",
131
- token: intent.token,
132
- borrow: withMargin(view.debt)
138
+ kind: "aaveWithdraw",
139
+ token
133
140
  },
134
- clearQuotas(),
135
- repay(view.debt)
141
+ {
142
+ kind: "request",
143
+ token,
144
+ amount: view.balanceOf(token) + holdings.supplied,
145
+ reserve: 0n,
146
+ record: {
147
+ type: "CLOSE_ACCOUNT",
148
+ to: intent.to
149
+ }
150
+ }
136
151
  ];
137
152
  }
138
153
  /**
@@ -438,6 +453,13 @@ const clearQuotas = () => ({ kind: "clearQuotas" });
438
453
  */
439
454
  const SETTLE_MARGIN = 10n;
440
455
  const withMargin = (debt) => debt + debt * SETTLE_MARGIN / PERCENTAGE_FACTOR;
456
+ /**
457
+ * Seconds of Aave interest a closing repays on top of the debt it read: the
458
+ * bridge keeps whatever Aave does not take, so this is paid for, unlike
459
+ * {@link SETTLE_MARGIN}, and an hour costs a fraction of a basis point.
460
+ */
461
+ const CLOSE_AAVE_WINDOW = 3600n;
462
+ const ceilDiv = (a, b) => (a + b - 1n) / b;
441
463
  /** The amount that asks for all of it, whatever "all" turns out to be. */
442
464
  const everything = (amount) => amount >= MAX_UINT256;
443
465
  const min = (a, b) => a < b ? a : b;
@@ -477,4 +499,4 @@ function assertPositive(amount, flow) {
477
499
  if (amount <= 0n) throw new IntentPreviewError(insufficientBalance(), `${flow}: amount must be positive`);
478
500
  }
479
501
  //#endregion
480
- export { RAISED, planAddCollateral, planAdjustLeverage, planAdjustLeverageDelayed, planBorrowAndWithdraw, planDeposit, planFinishClaimOnly, planFinishCloseAccount, planFinishDecreaseLeverage, planFinishWithdraw, planMoveToAave, planRepay, planUpdateQuota, planWithdraw, planWithdrawAsset, planWithdrawDelayed };
502
+ export { RAISED, planAddCollateral, planAdjustLeverage, planAdjustLeverageDelayed, planBorrowAndWithdraw, planCloseAavePosition, planDeposit, planFinishClaimOnly, planFinishCloseAccount, planFinishDecreaseLeverage, planFinishWithdraw, 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 };
@@ -2,6 +2,7 @@ import { getDirectTransferToken } from "../../chain/chains.js";
2
2
  import { PERCENTAGE_FACTOR_1KK } from "../../constants/math.js";
3
3
  import { AaveHorizonBridgeAdapterContract } from "../../market/adapters/contracts/AaveHorizonBridgeAdapterContract.js";
4
4
  import { AaveV3PoolAdapterContract } from "../../market/adapters/contracts/AaveV3PoolAdapterContract.js";
5
+ import { SecuritizeRedemptionGatewayAdapterContract } from "../../market/adapters/contracts/SecuritizeRedemptionGatewayAdapterContract.js";
5
6
  import { insufficientBalance } from "../../../model/errors/operation-errors.js";
6
7
  import { multipleDelayedWithdrawals, noDelayedRoute, unsupportedCollateralToken, withdrawalInProgress } from "../../../model/errors/prepare-errors.js";
7
8
  import "../../../model/index.js";
@@ -14,7 +15,8 @@ import { OperationLedger } from "./utils/ledger.js";
14
15
  import { collectPriceImpact } from "./utils/price-impact.js";
15
16
  import { clearedQuotas, getQuotasForUpdate, quotasAfterUpdate, withDirectTransferQuota } from "./utils/quotas-for-update.js";
16
17
  import { createRouterPaths } from "./utils/router-path.js";
17
- import { buildAaveOpenPositionOperation, buildAaveSupplyOperation, buildAddCollateralOperation, buildClaimDelayedWithdrawalOperation, buildCloseSwapOperation, buildDecreaseDebtOperation, buildIncreaseDebtOperation, buildQuotaUpdateOperation, buildStartDelayedWithdrawalOperation, buildSwapOperation, buildUnwrapRwaCollateralOperation, buildWithdrawCollateralOperation, buildWrapRwaCollateralOperation, instantOutput } from "./operations.js";
18
+ import { encodeDelayedIntent } from "../withdrawal-compressor/intent-codec.js";
19
+ import { buildAaveClosePositionOperation, buildAaveWithdrawOperation, buildAddCollateralOperation, buildClaimDelayedWithdrawalOperation, buildCloseSwapOperation, buildDecreaseDebtOperation, buildIncreaseDebtOperation, buildQuotaUpdateOperation, buildStartDelayedWithdrawalOperation, buildSwapOperation, buildUnwrapRwaCollateralOperation, buildWithdrawCollateralOperation, buildWrapRwaCollateralOperation, instantOutput } from "./operations.js";
18
20
  import { resolveQuotaUpdate } from "./resolveQuotaUpdate.js";
19
21
  import { withdrawLimits } from "./withdraw-limits.js";
20
22
  //#region src/onchain/accounts/intents/realize.ts
@@ -287,12 +289,19 @@ async function realize(steps, props) {
287
289
  if (ledger.balanceOf(asset.withdrawalPhantomToken) > 0n) throw new IntentPreviewError(withdrawalInProgress(toTokenAmount(sdk, asset.withdrawalPhantomToken, ledger.balanceOf(asset.withdrawalPhantomToken))), `request: ${asset.withdrawalPhantomToken} already holds a pending withdrawal`);
288
290
  assertHolds(step.token, step.amount + step.reserve, "request");
289
291
  if (step.record.type !== "CLOSE_ACCOUNT") directTransfer ??= getDirectTransferToken(step.token, sdk.networkType);
290
- const preview = await sdk.accounts.previewDelayedWithdrawal({
292
+ const preview = (creditAccount.tokens.find((t) => eq(t.token, step.token))?.balance ?? 0n) >= step.amount ? await sdk.accounts.previewDelayedWithdrawal({
291
293
  creditAccount: creditAccount.creditAccount,
292
294
  token: step.token,
293
295
  amount: step.amount,
294
296
  withdrawalPhantomToken: asset.withdrawalPhantomToken,
295
297
  intent: step.record
298
+ }) : await arrivingRedemption({
299
+ sdk,
300
+ suite,
301
+ asset,
302
+ amount: step.amount,
303
+ leftover: ledger.balanceOf(step.token) - step.amount,
304
+ record: step.record
296
305
  });
297
306
  push(buildStartDelayedWithdrawalOperation({
298
307
  preview,
@@ -329,8 +338,9 @@ async function realize(steps, props) {
329
338
  break;
330
339
  case "sweep": {
331
340
  withdrawsCollateral = true;
341
+ const swept = (token) => !step.token || eq(token, step.token) || rwaAsset !== void 0 && eq(step.token, underlying) && eq(token, rwaAsset);
332
342
  const wrapped = ledger.balanceOf(underlying);
333
- if (rwaAsset && wrapped > 0n) push(await buildUnwrapRwaCollateralOperation({
343
+ if (rwaAsset && wrapped > 0n && swept(underlying)) push(await buildUnwrapRwaCollateralOperation({
334
344
  tokenIn: underlying,
335
345
  all: true,
336
346
  amountIn: wrapped,
@@ -340,6 +350,7 @@ async function realize(steps, props) {
340
350
  sdk
341
351
  }));
342
352
  for (const { token, balance } of ledger.snapshot().assets) {
353
+ if (!swept(token)) continue;
343
354
  const withdrawal = buildWithdrawCollateralOperation({
344
355
  token,
345
356
  amount: balance,
@@ -355,33 +366,36 @@ async function realize(steps, props) {
355
366
  }
356
367
  break;
357
368
  }
358
- case "aaveSupply": {
359
- assertHolds(step.token, step.amount, "aaveSupply");
360
- const adapter = aavePoolAdapter(sdk, suite, step.token);
361
- push(buildAaveSupplyOperation({
362
- adapter,
363
- token: step.token,
364
- aToken: await adapter.aToken(step.token),
365
- amount: step.amount
366
- }));
367
- break;
368
- }
369
- case "aaveOpenPosition": {
369
+ case "aaveClosePosition": {
370
370
  const aToken = await aavePoolAdapter(sdk, suite, step.token).aToken(step.token);
371
- const aTokenAmount = ledger.balanceOf(aToken);
372
- assertHolds(aToken, aTokenAmount, "aaveOpenPosition");
373
- push(buildAaveOpenPositionOperation({
371
+ const debtToken = rwaAsset ?? underlying;
372
+ assertHolds(debtToken, step.repay, "aaveClosePosition");
373
+ push(buildAaveClosePositionOperation({
374
374
  adapter: aaveBridgeAdapter(sdk, suite, step.token, {
375
375
  aToken,
376
- debtToken: underlying
376
+ debtToken
377
377
  }),
378
378
  aToken,
379
- aTokenAmount,
380
- debtToken: underlying,
381
- borrowAmount: step.borrow
379
+ aTokenAmount: step.aTokenAmount,
380
+ debtToken,
381
+ repayAmount: step.repay
382
382
  }));
383
383
  break;
384
384
  }
385
+ case "aaveWithdraw": {
386
+ const adapter = aavePoolAdapter(sdk, suite, step.token);
387
+ const aToken = await adapter.aToken(step.token);
388
+ const amount = ledger.balanceOf(aToken);
389
+ assertHolds(aToken, amount, "aaveWithdraw");
390
+ push(buildAaveWithdrawOperation({
391
+ adapter,
392
+ token: step.token,
393
+ aToken,
394
+ amount
395
+ }));
396
+ raised = amount;
397
+ break;
398
+ }
385
399
  }
386
400
  const floor = ledger.snapshot();
387
401
  const { assets, debt } = floor;
@@ -504,10 +518,34 @@ async function delayedConfig(sdk, creditAccount, token) {
504
518
  if (assets.length > 1) throw new IntentPreviewError(multipleDelayedWithdrawals(toToken(sdk, token), assets.length), `request: ${token} has ${assets.length} delayed withdrawal configs`);
505
519
  return assets[0];
506
520
  }
521
+ /**
522
+ * The request for a redemption of a balance an earlier call of the same
523
+ * multicall brings in. The withdrawal compressor caps what it quotes at the
524
+ * balance the account holds before the transaction, so the request is built
525
+ * here instead: a diff call that names no amount, its phantom valued the way
526
+ * the gateway values it. Only a Securitize redemption gateway redeems that
527
+ * way; any other redemption is refused with `noDelayedRoute`.
528
+ */
529
+ async function arrivingRedemption(input) {
530
+ const { sdk, suite, asset, amount } = input;
531
+ const adapter = suite.creditManager.adapters.values().find((a) => a instanceof SecuritizeRedemptionGatewayAdapterContract && eq(a.dsToken, asset.token) && eq(a.redemptionPhantomToken, asset.withdrawalPhantomToken));
532
+ if (!adapter) throw new IntentPreviewError(noDelayedRoute(toToken(sdk, asset.token)), `request: ${asset.token} arrives in this transaction, and only a Securitize gateway redeems it without a quote`);
533
+ return {
534
+ token: asset.token,
535
+ amountIn: amount,
536
+ outputs: [{
537
+ token: asset.withdrawalPhantomToken,
538
+ isDelayed: true,
539
+ amount: await adapter.redemptionValue(amount)
540
+ }],
541
+ requestCalls: [adapter.redeemDiffCall(input.leftover, encodeDelayedIntent(input.record))],
542
+ claimableAt: sdk.timestamp + asset.withdrawalLength
543
+ };
544
+ }
507
545
  /** The credit manager's Aave pool adapter that lists `token`. */
508
546
  function aavePoolAdapter(sdk, suite, token) {
509
547
  const adapter = suite.creditManager.adapters.values().find((a) => a instanceof AaveV3PoolAdapterContract && a.isAssetAllowed(token));
510
- if (!adapter) throw new IntentPreviewError(unsupportedCollateralToken(toToken(sdk, token)), `aaveSupply: no Aave pool adapter lists ${token}`);
548
+ if (!adapter) throw new IntentPreviewError(unsupportedCollateralToken(toToken(sdk, token)), `aave: no Aave pool adapter lists ${token}`);
511
549
  return adapter;
512
550
  }
513
551
  /**
@@ -516,7 +554,7 @@ function aavePoolAdapter(sdk, suite, token) {
516
554
  */
517
555
  function aaveBridgeAdapter(sdk, suite, token, pair) {
518
556
  const adapter = suite.creditManager.adapters.values().find((a) => a instanceof AaveHorizonBridgeAdapterContract && a.isATokenAllowed(pair.aToken) && a.isDebtTokenAllowed(pair.debtToken));
519
- if (!adapter) throw new IntentPreviewError(unsupportedCollateralToken(toToken(sdk, token)), `aaveOpenPosition: no Horizon bridge adapter takes ${pair.aToken} against ${pair.debtToken}`);
557
+ if (!adapter) throw new IntentPreviewError(unsupportedCollateralToken(toToken(sdk, token)), `aaveClosePosition: no Horizon bridge adapter takes ${pair.aToken} against ${pair.debtToken}`);
520
558
  return adapter;
521
559
  }
522
560
  const callsOf = (operations) => operations.flatMap((op) => op.calls);
@@ -326,7 +326,7 @@ function buildMockSdk(args) {
326
326
  chainId: 1,
327
327
  networkType: "Mainnet",
328
328
  currentBlock: 1n,
329
- timestamp: args.timestamp ?? 0,
329
+ timestamp: BigInt(args.timestamp ?? 0),
330
330
  withdrawalCompressor,
331
331
  tokensMeta: {
332
332
  get: (token) => ({
@@ -80,13 +80,13 @@ var OperationLedger = class {
80
80
  this.#add(op.withdrawalPhantomToken, -op.withdrawalTokenSpent);
81
81
  for (const out of op.outputs) this.#add(out.token, out.amount);
82
82
  break;
83
- case "aaveSupply":
84
- this.#add(op.token, -op.amount);
85
- this.#add(op.aToken, op.amount);
83
+ case "aaveClosePosition":
84
+ this.#add(op.debtToken, -op.repayAmount);
85
+ this.#add(op.aToken, op.aTokenAmount);
86
86
  break;
87
- case "aaveOpenPosition":
88
- this.#add(op.aToken, -op.aTokenAmount);
89
- this.#add(op.debtToken, op.borrowAmount);
87
+ case "aaveWithdraw":
88
+ this.#add(op.aToken, -op.amount);
89
+ this.#add(op.token, op.amount);
90
90
  }
91
91
  return this;
92
92
  }
@@ -127,6 +127,7 @@ const chains = {
127
127
  symbol: "USDC"
128
128
  },
129
129
  tokenPrettyNames: AddressMap.fromRecord({
130
+ "0x225e61a55b6ef8cc2ae94e85d0a95f9e2cd96a88": "VBILL → RLUSD",
130
131
  "0xab7d50fc2486a1ac06516e2ece9dadc95ba8cd20": "wstETH redemption from cp0xLRT",
131
132
  "0x6252467c2fefb61cb55180282943139baeea36c5": "wstETH redemption from rstETH",
132
133
  "0xd412ca00d177eba2843348f9c50dd17bfce32c40": "wstETH redemption from pzETH",