@gearbox-protocol/sdk 16.3.2 → 16.4.0-next.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/dist/cjs/dev/index.js +3 -2
  2. package/dist/cjs/dev/kycUtils.js +18 -35
  3. package/dist/cjs/dev/midasUtils.js +40 -11
  4. package/dist/cjs/dev/securitizeUtils.js +14 -10
  5. package/dist/cjs/dev/withdrawalUtils.js +3 -6
  6. package/dist/cjs/model/errors/index.js +2 -0
  7. package/dist/cjs/model/errors/operation-errors.js +18 -0
  8. package/dist/cjs/model/index.js +2 -0
  9. package/dist/cjs/onchain/accounts/CreditAccountsServiceV310.js +0 -1
  10. package/dist/cjs/onchain/accounts/intents/borrow.js +139 -0
  11. package/dist/cjs/onchain/accounts/intents/collateral-valuation.js +41 -0
  12. package/dist/cjs/onchain/accounts/intents/guards.js +15 -3
  13. package/dist/cjs/onchain/accounts/intents/index.js +107 -20
  14. package/dist/cjs/onchain/accounts/intents/leverage-band.js +2 -12
  15. package/dist/cjs/onchain/accounts/intents/maxBorrow.js +89 -0
  16. package/dist/cjs/onchain/accounts/intents/maxWithdrawCollateral.js +15 -41
  17. package/dist/cjs/onchain/accounts/intents/open-strategy.js +6 -45
  18. package/dist/cjs/onchain/accounts/intents/realize.js +54 -2
  19. package/dist/cjs/onchain/accounts/intents/tail.js +1 -1
  20. package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +1 -0
  21. package/dist/cjs/onchain/accounts/intents/utils/common.js +19 -0
  22. package/dist/cjs/onchain/accounts/intents/utils/credit-account-slice.js +21 -0
  23. package/dist/cjs/onchain/accounts/intents/utils/index.js +2 -0
  24. package/dist/cjs/onchain/accounts/intents/utils/price-impact.js +3 -3
  25. package/dist/cjs/onchain/accounts/intents/withdraw-limits.js +97 -0
  26. package/dist/cjs/onchain/core/createAddressProvider.js +2 -5
  27. package/dist/cjs/onchain/index.js +6 -0
  28. package/dist/cjs/onchain/market/adapters/abi/conctructorAbi.js +1 -1
  29. package/dist/cjs/onchain/market/adapters/contracts/MidasGatewayAdapterContract.js +11 -3
  30. package/dist/cjs/onchain/positions/calcHealthFactor.js +3 -3
  31. package/dist/cjs/onchain/preview/index.js +2 -0
  32. package/dist/cjs/onchain/preview/preview/index.js +2 -0
  33. package/dist/cjs/onchain/preview/preview/midasGreenlistsAccount.js +17 -0
  34. package/dist/cjs/onchain/preview/preview/previewOpenStrategyPosition.js +13 -16
  35. package/dist/cjs/onchain/preview/preview/previewOperation.js +19 -11
  36. package/dist/cjs/onchain/preview/preview/replayMulticall.js +4 -3
  37. package/dist/cjs/onchain/validation/bundles/checkCollateralFunding.js +3 -3
  38. package/dist/cjs/onchain/validation/bundles/checkCreditOperation.js +4 -3
  39. package/dist/cjs/onchain/validation/bundles/checkMidasAccountGreenlist.js +44 -0
  40. package/dist/cjs/onchain/validation/bundles/checkRWAOpening.js +16 -7
  41. package/dist/cjs/onchain/validation/bundles/index.js +2 -0
  42. package/dist/cjs/onchain/validation/checkOperation.js +0 -1
  43. package/dist/cjs/onchain/validation/checks/checkReservePriceLimited.js +30 -0
  44. package/dist/cjs/onchain/validation/checks/index.js +2 -0
  45. package/dist/cjs/onchain/validation/index.js +4 -0
  46. package/dist/cjs/sdk/execute/ExecuteApi.js +65 -5
  47. package/dist/cjs/sdk/prepare/PrepareApi.js +89 -14
  48. package/dist/esm/dev/index.js +3 -3
  49. package/dist/esm/dev/kycUtils.js +17 -33
  50. package/dist/esm/dev/midasUtils.js +39 -12
  51. package/dist/esm/dev/securitizeUtils.js +15 -11
  52. package/dist/esm/dev/withdrawalUtils.js +3 -6
  53. package/dist/esm/model/errors/index.js +2 -2
  54. package/dist/esm/model/errors/operation-errors.js +17 -1
  55. package/dist/esm/model/index.js +2 -2
  56. package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +0 -1
  57. package/dist/esm/onchain/accounts/intents/borrow.js +137 -0
  58. package/dist/esm/onchain/accounts/intents/collateral-valuation.js +40 -0
  59. package/dist/esm/onchain/accounts/intents/guards.js +15 -3
  60. package/dist/esm/onchain/accounts/intents/index.js +107 -20
  61. package/dist/esm/onchain/accounts/intents/leverage-band.js +2 -12
  62. package/dist/esm/onchain/accounts/intents/maxBorrow.js +87 -0
  63. package/dist/esm/onchain/accounts/intents/maxWithdrawCollateral.js +15 -41
  64. package/dist/esm/onchain/accounts/intents/open-strategy.js +6 -45
  65. package/dist/esm/onchain/accounts/intents/realize.js +54 -2
  66. package/dist/esm/onchain/accounts/intents/tail.js +1 -1
  67. package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +1 -0
  68. package/dist/esm/onchain/accounts/intents/utils/common.js +19 -1
  69. package/dist/esm/onchain/accounts/intents/utils/credit-account-slice.js +21 -1
  70. package/dist/esm/onchain/accounts/intents/utils/index.js +3 -3
  71. package/dist/esm/onchain/accounts/intents/utils/price-impact.js +3 -3
  72. package/dist/esm/onchain/accounts/intents/withdraw-limits.js +95 -0
  73. package/dist/esm/onchain/core/createAddressProvider.js +2 -5
  74. package/dist/esm/onchain/index.js +4 -1
  75. package/dist/esm/onchain/market/adapters/abi/conctructorAbi.js +1 -1
  76. package/dist/esm/onchain/market/adapters/contracts/MidasGatewayAdapterContract.js +11 -3
  77. package/dist/esm/onchain/positions/calcHealthFactor.js +3 -3
  78. package/dist/esm/onchain/preview/index.js +2 -1
  79. package/dist/esm/onchain/preview/preview/index.js +2 -1
  80. package/dist/esm/onchain/preview/preview/midasGreenlistsAccount.js +16 -0
  81. package/dist/esm/onchain/preview/preview/previewOpenStrategyPosition.js +14 -17
  82. package/dist/esm/onchain/preview/preview/previewOperation.js +19 -11
  83. package/dist/esm/onchain/preview/preview/replayMulticall.js +4 -3
  84. package/dist/esm/onchain/validation/bundles/checkCollateralFunding.js +3 -3
  85. package/dist/esm/onchain/validation/bundles/checkCreditOperation.js +4 -3
  86. package/dist/esm/onchain/validation/bundles/checkMidasAccountGreenlist.js +43 -0
  87. package/dist/esm/onchain/validation/bundles/checkRWAOpening.js +16 -7
  88. package/dist/esm/onchain/validation/bundles/index.js +2 -1
  89. package/dist/esm/onchain/validation/checkOperation.js +0 -1
  90. package/dist/esm/onchain/validation/checks/checkReservePriceLimited.js +29 -0
  91. package/dist/esm/onchain/validation/checks/index.js +2 -1
  92. package/dist/esm/onchain/validation/index.js +3 -1
  93. package/dist/esm/sdk/execute/ExecuteApi.js +65 -5
  94. package/dist/esm/sdk/prepare/PrepareApi.js +89 -14
  95. package/dist/types/dev/index.d.ts +3 -3
  96. package/dist/types/dev/kycUtils.d.ts +1 -5
  97. package/dist/types/dev/midasUtils.d.ts +11 -1
  98. package/dist/types/model/errors/index.d.ts +2 -2
  99. package/dist/types/model/errors/operation-errors.d.ts +54 -1
  100. package/dist/types/model/index.d.ts +3 -3
  101. package/dist/types/model/previews.d.ts +25 -19
  102. package/dist/types/onchain/accounts/index.d.ts +4 -3
  103. package/dist/types/onchain/accounts/intents/borrow.d.ts +141 -0
  104. package/dist/types/onchain/accounts/intents/collateral-valuation.d.ts +42 -0
  105. package/dist/types/onchain/accounts/intents/guards.d.ts +18 -2
  106. package/dist/types/onchain/accounts/intents/index.d.ts +102 -14
  107. package/dist/types/onchain/accounts/intents/maxBorrow.d.ts +54 -0
  108. package/dist/types/onchain/accounts/intents/maxWithdrawCollateral.d.ts +3 -8
  109. package/dist/types/onchain/accounts/intents/open-strategy.d.ts +3 -17
  110. package/dist/types/onchain/accounts/intents/testing/sdk-mock.d.ts +2 -0
  111. package/dist/types/onchain/accounts/intents/tests/open-strategy.fixtures.d.ts +2 -2
  112. package/dist/types/onchain/accounts/intents/types.d.ts +41 -5
  113. package/dist/types/onchain/accounts/intents/utils/common.d.ts +15 -1
  114. package/dist/types/onchain/accounts/intents/utils/credit-account-slice.d.ts +14 -1
  115. package/dist/types/onchain/accounts/intents/utils/index.d.ts +3 -3
  116. package/dist/types/onchain/accounts/intents/withdraw-limits.d.ts +80 -0
  117. package/dist/types/onchain/index.d.ts +8 -4
  118. package/dist/types/onchain/market/adapters/contracts/MidasGatewayAdapterContract.d.ts +8 -2
  119. package/dist/types/onchain/preview/index.d.ts +2 -1
  120. package/dist/types/onchain/preview/preview/index.d.ts +2 -1
  121. package/dist/types/onchain/preview/preview/midasGreenlistsAccount.d.ts +13 -0
  122. package/dist/types/onchain/preview/preview/previewOpenStrategyPosition.d.ts +5 -3
  123. package/dist/types/onchain/preview/preview/replayMulticall.d.ts +8 -7
  124. package/dist/types/onchain/validation/bundles/checkCreditOperation.d.ts +2 -2
  125. package/dist/types/onchain/validation/bundles/checkMidasAccountGreenlist.d.ts +22 -0
  126. package/dist/types/onchain/validation/bundles/checkRWAOpening.d.ts +6 -4
  127. package/dist/types/onchain/validation/bundles/index.d.ts +3 -2
  128. package/dist/types/onchain/validation/checks/checkDebtLimits.d.ts +2 -2
  129. package/dist/types/onchain/validation/checks/checkReservePriceLimited.d.ts +31 -0
  130. package/dist/types/onchain/validation/checks/index.d.ts +2 -1
  131. package/dist/types/onchain/validation/index.d.ts +4 -2
  132. package/dist/types/onchain/validation/raise.d.ts +2 -2
  133. package/dist/types/sdk/execute/index.d.ts +2 -2
  134. package/dist/types/sdk/execute/types.d.ts +48 -6
  135. package/dist/types/sdk/index.d.ts +5 -4
  136. package/dist/types/sdk/prepare/PrepareApi.d.ts +16 -4
  137. package/dist/types/sdk/prepare/index.d.ts +4 -3
  138. package/dist/types/sdk/prepare/types.d.ts +199 -65
  139. package/package.json +1 -1
@@ -204,18 +204,15 @@ async function fulfillMidasRedeemer(anvil, redeemer, logger) {
204
204
  address: MIDAS_VAULT_ADMIN,
205
205
  value: parseEther("100")
206
206
  });
207
- const hash = await anvil.writeContract({
207
+ await anvil.writeContractSync({
208
208
  chain: anvil.chain,
209
209
  address: midasRedemptionVault,
210
210
  account: MIDAS_VAULT_ADMIN,
211
211
  abi: iMidasRedemptionVaultExtAbi,
212
212
  functionName: "safeApproveRequest",
213
- args: [requestId, mTokenRate]
213
+ args: [requestId, mTokenRate],
214
+ throwOnReceiptRevert: true
214
215
  });
215
- if ((await anvil.waitForTransactionReceipt({
216
- hash,
217
- pollingInterval: 100
218
- })).status !== "success") throw new Error(`midas: safeApproveRequest tx ${hash} reverted`);
219
216
  await anvil.stopImpersonatingAccount({ address: MIDAS_VAULT_ADMIN });
220
217
  }
221
218
  /**
@@ -1,7 +1,7 @@
1
1
  import "./base.js";
2
2
  import { creditAccountFrozen, liquidatorNotEligible, notEmergencyLiquidator } from "./liquidation-errors.js";
3
- import { creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, rwaOpenRequirementsNotMet } from "./operation-errors.js";
3
+ import { accountNotMidasGreenlisted, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, 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 { creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, liquidatorNotEligible, malformedTransaction, marketExpired, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, rwaOpenRequirementsNotMet, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress };
7
+ export { accountNotMidasGreenlisted, creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, liquidatorNotEligible, malformedTransaction, marketExpired, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, reservePriceLimited, rwaOpenRequirementsNotMet, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress };
@@ -66,6 +66,14 @@ function insufficientCollateral(args) {
66
66
  ...args
67
67
  };
68
68
  }
69
+ /** {@inheritDoc ReservePriceLimitedError} */
70
+ function reservePriceLimited(args) {
71
+ return {
72
+ code: "reservePriceLimited",
73
+ message: `The reserve price feed values this collateral below what the operation pays out: the account covers its debt at ${args.atMainPrices} on the main feed and only ${args.healthFactor} at the reserve one, below ${args.healthFactorThreshold}.`,
74
+ ...args
75
+ };
76
+ }
69
77
  /** {@inheritDoc ForbiddenTokenError} */
70
78
  function forbiddenToken(token) {
71
79
  return {
@@ -117,5 +125,13 @@ function rwaOpenRequirementsNotMet(args) {
117
125
  ...args
118
126
  };
119
127
  }
128
+ /** {@inheritDoc AccountNotMidasGreenlistedError} */
129
+ function accountNotMidasGreenlisted(args) {
130
+ return {
131
+ code: "accountNotMidasGreenlisted",
132
+ message: `The credit account is not Midas-greenlisted for ${args.token.symbol}.`,
133
+ ...args
134
+ };
135
+ }
120
136
  //#endregion
121
- export { creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, rwaOpenRequirementsNotMet };
137
+ export { accountNotMidasGreenlisted, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, reservePriceLimited, rwaOpenRequirementsNotMet };
@@ -15,7 +15,7 @@ import { ANALYTICS_POSITIONS_DEFAULT_LIMIT, ANALYTICS_POSITIONS_MAX_LIMIT, analy
15
15
  import "./curators.js";
16
16
  import "./delayed-intents.js";
17
17
  import { creditAccountFrozen, liquidatorNotEligible, notEmergencyLiquidator } from "./errors/liquidation-errors.js";
18
- import { creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, rwaOpenRequirementsNotMet } from "./errors/operation-errors.js";
18
+ import { accountNotMidasGreenlisted, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, reservePriceLimited, rwaOpenRequirementsNotMet } from "./errors/operation-errors.js";
19
19
  import { unpriceableTokenError } from "./errors/oracle-errors.js";
20
20
  import { creditAccountNotEmpty, creditAccountNotFound, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, unexpectedFailure, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress } from "./errors/prepare-errors.js";
21
21
  import { malformedTransaction } from "./errors/preview-errors.js";
@@ -32,4 +32,4 @@ import { chainFailedSchema, chainMetadataSchema, chainSucceededSchema, dataSourc
32
32
  import { safeValue, sdkErr, sdkOk } from "./result.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, amountSchema, analyticsChartQueryOptionsSchema, analyticsChartQueryParamsSchema, analyticsChartQuerySchema, 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, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, 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, quotaAssetSchema, quotaCountExceeded, quotaLimitReached, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, 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, 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, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, 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, quotaAssetSchema, quotaCountExceeded, quotaLimitReached, 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 };
@@ -212,7 +212,6 @@ var CreditAccountsServiceV310 = class extends SDKConstruct {
212
212
  }),
213
213
  ...callsAfter ?? []
214
214
  ];
215
- calls = await this.#prependMidasReceiveGreenlist(cm.address, calls);
216
215
  calls = await this.prependPriceUpdates(cm.address, calls);
217
216
  const tx = reopenCreditAccount ? cmSuite.multicallTx(reopenCreditAccount, calls, rwaOptions) : cmSuite.openCreditAccountTx(to, calls, referralCode, rwaOptions);
218
217
  tx.value = ethAmount.toString(10);
@@ -0,0 +1,137 @@
1
+ import { insufficientBalance } from "../../../model/errors/operation-errors.js";
2
+ import { unsupportedCollateralToken } from "../../../model/errors/prepare-errors.js";
3
+ import "../../../model/index.js";
4
+ import { toToken } from "../../validation/helpers/token.js";
5
+ import { IntentPreviewError } from "../../validation/raise.js";
6
+ import "../../validation/index.js";
7
+ import { eq, toTargetDecimals } from "./utils/common.js";
8
+ import { assertCanBorrow, assertCollateralised, assertGrowthAllowed, assertMarketOperable, assertQuotaAvailable } from "./guards.js";
9
+ import { assertDebtLimits } from "./math.js";
10
+ import { unopenedAccountSlice } from "./utils/credit-account-slice.js";
11
+ import { collectPriceImpact } from "./utils/price-impact.js";
12
+ import { getQuotasForUpdate } from "./utils/quotas-for-update.js";
13
+ import { createRouterPaths } from "./utils/router-path.js";
14
+ import "./utils/index.js";
15
+ //#region src/onchain/accounts/intents/borrow.ts
16
+ /**
17
+ * Builds the state a borrow would leave behind.
18
+ *
19
+ * The debt is named rather than derived: a borrow asks for an amount, where an
20
+ * opening asks for a leverage and lets the collateral decide. Everything the
21
+ * loan pays out leaves the account, so the collateral alone backs it — which
22
+ * is what makes the health factor here a straight function of the two amounts.
23
+ *
24
+ * Produces no operation list, as opening never does: the caller hands the
25
+ * numbers and the calls to `sdk.accounts.openCA`, with `withdrawToken` set to
26
+ * the payout.
27
+ */
28
+ async function buildBorrowState(props) {
29
+ const { sdk, creditManager, collateralAmount, borrowAmount, slippage = 0, quotaReserve, creditAccount: existing } = props;
30
+ const suite = sdk.marketRegister.findCreditManager(creditManager);
31
+ const market = sdk.marketRegister.findByCreditManager(creditManager);
32
+ assertMarketOperable(suite);
33
+ const underlying = market.pool.underlying.toLowerCase();
34
+ const collateralToken = props.collateralToken.toLowerCase();
35
+ const borrowToken = props.borrowToken.toLowerCase();
36
+ const convert = (from, to, amount) => market.priceOracle.safeConvert(from, to, amount).value;
37
+ if (eq(collateralToken, borrowToken)) throw new IntentPreviewError(unsupportedCollateralToken(toToken(sdk, collateralToken)), "borrow: the payout token cannot also be the collateral");
38
+ const rwaAsset = sdk.tokensMeta.rwaUnderlyings.get(underlying)?.asset?.toLowerCase();
39
+ const unwrapsPayout = !!rwaAsset && eq(borrowToken, rwaAsset);
40
+ if (rwaAsset && eq(borrowToken, underlying)) throw new IntentPreviewError(unsupportedCollateralToken(toToken(sdk, borrowToken)), `borrow: ${underlying} cannot leave the account, ask for the payout in ${rwaAsset}`);
41
+ if (collateralAmount <= 0n) throw new IntentPreviewError(insufficientBalance(), "borrow: no collateral supplied");
42
+ if (borrowAmount <= 0n) throw new IntentPreviewError(insufficientBalance(), "borrow: nothing to borrow");
43
+ const margin = convert(collateralToken, underlying, collateralAmount);
44
+ if (margin <= 0n) throw new IntentPreviewError(insufficientBalance(), "borrow: collateral is worth nothing in underlying");
45
+ const debt = eq(borrowToken, underlying) ? borrowAmount : unwrapsPayout ? toTargetDecimals(borrowAmount, borrowToken, underlying, sdk) : convert(borrowToken, underlying, borrowAmount);
46
+ assertDebtLimits(sdk, debt, suite.creditFacade, underlying);
47
+ assertCanBorrow(sdk, suite, debt);
48
+ const account = existing ?? unopenedAccountSlice({
49
+ creditManager,
50
+ creditFacade: suite.creditFacade.address,
51
+ underlying
52
+ });
53
+ const leg = eq(borrowToken, underlying) || unwrapsPayout ? void 0 : await createRouterPaths({
54
+ sdk,
55
+ creditAccount: account,
56
+ slippage
57
+ }).swap({
58
+ tokenIn: underlying,
59
+ tokenOut: borrowToken,
60
+ amount: debt,
61
+ keep: eq(collateralToken, underlying) ? collateralAmount : 0n
62
+ });
63
+ const unwrap = unwrapsPayout ? await sdk.accounts.assembleRWAUnwrapCalls(debt, creditManager) : void 0;
64
+ if (unwrapsPayout && !unwrap) throw new Error(`borrow: no unwrap calls found for ${borrowToken}`);
65
+ const assets = [{
66
+ token: collateralToken,
67
+ balance: collateralAmount
68
+ }];
69
+ const quotaIncrease = borrowCollateralQuota({
70
+ sdk,
71
+ creditManager,
72
+ assets,
73
+ quotaReserve
74
+ });
75
+ assertGrowthAllowed({
76
+ sdk,
77
+ suite,
78
+ market,
79
+ before: [],
80
+ after: assets
81
+ });
82
+ assertQuotaAvailable(sdk, market, quotaIncrease);
83
+ const snapshot = {
84
+ creditManager,
85
+ assets,
86
+ quotas: quotaIncrease,
87
+ totalDebt: debt,
88
+ totalValue: margin
89
+ };
90
+ const projection = sdk.positions.projection(snapshot, { availableLiquidityChange: -debt });
91
+ assertCollateralised(projection.safeHealthFactor, true);
92
+ const priced = (token, balance) => market.priceOracle.toTokenAmount(token, balance);
93
+ const payout = unwrapsPayout ? toTargetDecimals(debt, underlying, borrowToken, sdk) : leg ? leg.amount : debt;
94
+ return {
95
+ ...projection,
96
+ currentPrice: sdk.positions.currentPrice(snapshot),
97
+ executionCost: void 0,
98
+ priceImpact: await collectPriceImpact(leg?.probe ? [leg.probe] : [], {
99
+ totalValue: margin,
100
+ netValue: margin - debt,
101
+ toUnderlying: (from, amount) => convert(from, underlying, amount)
102
+ }),
103
+ collateral: priced(collateralToken, collateralAmount),
104
+ borrowed: priced(borrowToken, payout),
105
+ minBorrowed: priced(borrowToken, leg ? leg.minAmount : payout),
106
+ slippage,
107
+ quotaIncrease,
108
+ calls: leg ? [...leg.calls] : unwrap ?? [],
109
+ creditAccount: existing?.creditAccount
110
+ };
111
+ }
112
+ /**
113
+ * Quota a borrow buys for its collateral on an account that holds none yet.
114
+ *
115
+ * Shared with `maxBorrow`, because a quota short of the collateral's weighted
116
+ * value is what caps the loan: the two have to read the same number or the
117
+ * ceiling one offers is one the other refuses.
118
+ *
119
+ * @param props - {@link BorrowCollateralQuotaProps}
120
+ **/
121
+ function borrowCollateralQuota({ sdk, creditManager, assets, quotaReserve }) {
122
+ const suite = sdk.marketRegister.findCreditManager(creditManager);
123
+ const market = sdk.marketRegister.findByCreditManager(creditManager);
124
+ return getQuotasForUpdate({
125
+ assetsBefore: [],
126
+ assetsAfter: assets,
127
+ initialQuotas: [],
128
+ quotaReserve,
129
+ underlyingToken: market.pool.underlying,
130
+ liquidationThresholds: suite.creditManager.liquidationThresholds,
131
+ quotas: market.pool.pqk.quotas,
132
+ maxDebt: suite.creditFacade.maxDebt,
133
+ convert: (from, to, amount) => market.priceOracle.safeConvert(from, to, amount).value
134
+ }).quotaIncrease;
135
+ }
136
+ //#endregion
137
+ export { borrowCollateralQuota, buildBorrowState };
@@ -0,0 +1,40 @@
1
+ import { BigIntMath } from "../../utils/bigint-math.js";
2
+ import { PERCENTAGE_FACTOR } from "../../constants/math.js";
3
+ import "../../utils/index.js";
4
+ import { eq } from "./utils/common.js";
5
+ //#region src/onchain/accounts/intents/collateral-valuation.ts
6
+ /** {@inheritDoc CollateralValuation} */
7
+ function collateralValuation(creditAccount, sdk) {
8
+ const { market, creditManager } = sdk.marketRegister.findCreditManager(creditAccount.creditManager);
9
+ const { priceOracle } = market;
10
+ const { pqk } = market.pool;
11
+ const underlying = market.pool.underlying;
12
+ const masked = creditAccount.enabledTokensMask !== 0n;
13
+ const mainUsd = (token, amount) => {
14
+ try {
15
+ return priceOracle.convertToUSD(token, amount);
16
+ } catch {
17
+ return;
18
+ }
19
+ };
20
+ const lt = (token) => BigInt(creditManager.liquidationThresholds.get(token) ?? 0);
21
+ const checkedUsd = (holding) => eq(holding.token, underlying) ? mainUsd(holding.token, holding.balance) ?? 0n : priceOracle.safeConvertMinUSD(holding.token, holding.balance).value;
22
+ /** A quota is underlying-denominated, and a closed market backs nothing. */
23
+ const quotaValue = (holding) => pqk.hasActiveQuota(holding.token) ? (mainUsd(underlying, holding.quota) ?? 0n) * PERCENTAGE_FACTOR : 0n;
24
+ const weigh = (holding) => {
25
+ const weighted = checkedUsd(holding) * lt(holding.token);
26
+ if (holding.quota === 0n) return weighted;
27
+ return BigIntMath.min(quotaValue(holding), weighted);
28
+ };
29
+ return {
30
+ underlying,
31
+ counts: (holding) => holding.balance > 10n && (!masked || (holding.mask & creditAccount.enabledTokensMask) !== 0n),
32
+ weigh,
33
+ quotaValue,
34
+ mainUsd,
35
+ checkedUsd,
36
+ lt
37
+ };
38
+ }
39
+ //#endregion
40
+ export { collateralValuation };
@@ -6,6 +6,7 @@ import { checkCreditManagerPaused } from "../../validation/checks/checkCreditMan
6
6
  import { checkForbiddenToken } from "../../validation/checks/checkForbiddenToken.js";
7
7
  import { checkMarketExpired } from "../../validation/checks/checkMarketExpired.js";
8
8
  import { checkQuotaLimit } from "../../validation/checks/checkQuotaLimit.js";
9
+ import { checkReservePriceLimited } from "../../validation/checks/checkReservePriceLimited.js";
9
10
  import { raise } from "../../validation/raise.js";
10
11
  import "../../validation/index.js";
11
12
  import { eq } from "./utils/common.js";
@@ -111,13 +112,24 @@ function assertGrowthAllowed(args) {
111
112
  * whose reserve feed the SDK cannot read keeps its main price, so a plan can
112
113
  * still be refused on-chain after passing here.
113
114
  */
114
- function assertCollateralised(healthFactorBps, safePrices) {
115
+ function assertCollateralised(healthFactorBps, safePrices, atSafePrices) {
115
116
  const healthFactorThreshold = MIN_HEALTH_FACTOR_FACADE;
116
- raise(checkCollateralised({
117
+ const errors = checkCollateralised({
117
118
  healthFactor: healthFactorBps,
118
119
  healthFactorThreshold,
119
120
  safePrices
120
- }), `the account would end at a health factor of ${healthFactorBps}, below ${healthFactorThreshold}`);
121
+ });
122
+ if (errors.length === 0) return;
123
+ if (safePrices && atSafePrices) {
124
+ const { atMainPrices, withdrawable } = atSafePrices();
125
+ raise(checkReservePriceLimited({
126
+ healthFactor: healthFactorBps,
127
+ atMainPrices,
128
+ healthFactorThreshold,
129
+ withdrawable
130
+ }), `the account covers its debt at ${atMainPrices} on the main feed and only ${healthFactorBps} at the reserve one, below ${healthFactorThreshold}`);
131
+ }
132
+ raise(errors, `the account would end at a health factor of ${healthFactorBps}, below ${healthFactorThreshold}`);
121
133
  }
122
134
  /**
123
135
  * A quota can only be raised as far as the market still has room for: past the
@@ -7,14 +7,16 @@ import { IntentPreviewError } from "../../validation/raise.js";
7
7
  import "../../validation/index.js";
8
8
  import { isPhantomToken } from "./utils/pick-token.js";
9
9
  import { assertMarketOperable } from "./guards.js";
10
+ import { fetchCreditAccountSlice, toCreditAccountSlice } from "./utils/credit-account-slice.js";
11
+ import { buildBorrowState } from "./borrow.js";
10
12
  import { calcLeverageBand } from "./leverage-band.js";
11
- import { maxProportionalWithdrawal } from "./math.js";
13
+ import { maxBorrow } from "./maxBorrow.js";
12
14
  import { maxWithdrawCollateral } from "./maxWithdrawCollateral.js";
13
- import { fetchCreditAccountSlice, toCreditAccountSlice } from "./utils/credit-account-slice.js";
14
15
  import { buildOpenStrategyState } from "./open-strategy.js";
15
16
  import { planAddCollateral, planAdjustLeverage, planAdjustLeverageDelayed, planDeposit, planRepay, planWithdraw, planWithdrawAsset, planWithdrawDelayed } from "./plan.js";
16
- import { realize } from "./realize.js";
17
17
  import { accountView } from "./view.js";
18
+ import { withdrawLimits } from "./withdraw-limits.js";
19
+ import { realize } from "./realize.js";
18
20
  import { planTail, projectTail } from "./tail.js";
19
21
  //#region src/onchain/accounts/intents/index.ts
20
22
  /**
@@ -50,26 +52,29 @@ var CreditAccountOperationsService = class extends SDKConstruct {
50
52
  }
51
53
  /**
52
54
  * Both ends of what a `WITHDRAW` can take out, in underlying: the largest
53
- * partial withdrawal that keeps leverage and stays inside the facade's
54
- * `debtLimits`, and the net value an exit hands over. They are reported together
55
- * because a withdraw form needs both — the range it may offer, and the one
56
- * amount past it that is allowed — and because the distance between them is
57
- * the account's own, not a constant a caller could assume.
55
+ * partial withdrawal that keeps leverage, and the net value an exit hands
56
+ * over. They are reported together because a withdraw form needs both — the
57
+ * range it may offer, and the one amount past it that is allowed — and
58
+ * because the distance between them is the account's own, not a constant a
59
+ * caller could assume.
58
60
  *
59
- * Takes no target health factor, unlike {@link maxWithdrawCollateral}: a
60
- * proportional withdrawal leaves the factor where it found it, and the
61
- * facade's `minDebt` is what bounds it.
61
+ * Two rules bound the partial end and both are reported: the facade's
62
+ * `debtLimits` as `partial`, and the safe-price collateral check on top of
63
+ * it as `safePartial`. The second is the one to offer — see
64
+ * {@link WithdrawCeilings}.
62
65
  *
63
- * @param props - Account slice and the SDK holding its market
64
- * @returns The two ceilings, see {@link WithdrawCeilings} for the gap between
65
- * them
66
+ * Takes no target health factor, unlike {@link maxWithdrawCollateral}. A
67
+ * proportional withdrawal leaves the factor where it found it, so there is
68
+ * no room to choose: what these answer to is the facade's own threshold,
69
+ * which is also what {@link startIntent} refuses against.
70
+ *
71
+ * @param props - Account slice, the SDK holding its market, and optionally
72
+ * the collateral the withdrawal would be funded from
73
+ * @returns The three limits, see {@link WithdrawCeilings} for the gap
74
+ * between them
66
75
  */
67
76
  maxWithdraw(props) {
68
- const view = accountView(props.creditAccount, props.sdk);
69
- return {
70
- partial: maxProportionalWithdrawal(view, view.debtLimits),
71
- exit: view.collateral > 0n ? view.collateral : 0n
72
- };
77
+ return withdrawLimits(props);
73
78
  }
74
79
  /**
75
80
  * Debt a `REPAY` would have to cover to settle the account, in underlying
@@ -129,6 +134,34 @@ var CreditAccountOperationsService = class extends SDKConstruct {
129
134
  });
130
135
  }
131
136
  /**
137
+ * Largest loan a given collateral supports at `targetHF`, in the payout
138
+ * token's units — the ceiling a borrow form should offer.
139
+ *
140
+ * Reads no account, like {@link leverageBand}: the borrow opens one. The
141
+ * collateral is valued the way the transaction will be judged, at safe
142
+ * prices and under the quota the borrow buys, and the answer is then held to
143
+ * what the market will lend.
144
+ *
145
+ * A ceiling, not a verdict: the facade's `minDebt` is a floor and is not
146
+ * applied here, so collateral too small for this market still answers with
147
+ * what it carries and {@link borrowIntent} is the one that refuses the loan.
148
+ *
149
+ * The default is {@link MIN_HF_LIMITED}, the threshold a form holds an
150
+ * account to.
151
+ *
152
+ * @param props - The manager, the SDK holding its market, the collateral put
153
+ * up, the token to be paid in, and optionally the health factor to land at
154
+ * @returns Amount in the payout token's units; `0n` where no loan of this
155
+ * shape can be funded at any size
156
+ */
157
+ maxBorrow(props) {
158
+ const { targetHF = MIN_HF_LIMITED, ...rest } = props;
159
+ return maxBorrow({
160
+ ...rest,
161
+ targetHF: targetHF + 2n
162
+ });
163
+ }
164
+ /**
132
165
  * Previews the same operation when its source only redeems through its
133
166
  * issuer: a Securitize dsToken, a Mellow share.
134
167
  *
@@ -179,7 +212,10 @@ var CreditAccountOperationsService = class extends SDKConstruct {
179
212
  });
180
213
  return {
181
214
  ...result,
182
- state: tail.state,
215
+ state: {
216
+ ...tail.state,
217
+ executionCost: result.state.executionCost
218
+ },
183
219
  delayed
184
220
  };
185
221
  } catch (e) {
@@ -271,6 +307,26 @@ var CreditAccountOperationsService = class extends SDKConstruct {
271
307
  };
272
308
  }
273
309
  /**
310
+ * Previews opening an account that holds nothing.
311
+ *
312
+ * Nothing is put up, drawn or routed, so there is no state to build and no
313
+ * guard to run beyond the market's own: a paused or expired facade takes no
314
+ * multicall, and an opening is a multicall like any other. Answers the same
315
+ * envelope its two neighbours do so a caller branches on `ok` throughout.
316
+ *
317
+ * @param props - The SDK holding the market, and the manager to open in
318
+ * @returns `{ ok: true }`, or `{ ok: false, error }` when the market takes
319
+ * no transaction right now
320
+ */
321
+ async openEmptyAccountIntent(props) {
322
+ try {
323
+ assertMarketOperable(props.sdk.marketRegister.findCreditManager(props.creditManager));
324
+ return { ok: true };
325
+ } catch (e) {
326
+ return asSDKError(e);
327
+ }
328
+ }
329
+ /**
274
330
  * Previews opening a brand-new leveraged position.
275
331
  *
276
332
  * Sits apart from {@link startIntent} because there is no account yet: nothing
@@ -292,6 +348,37 @@ var CreditAccountOperationsService = class extends SDKConstruct {
292
348
  return asSDKError(e);
293
349
  }
294
350
  }
351
+ /**
352
+ * Previews taking a loan against collateral, on an account this same
353
+ * transaction opens.
354
+ *
355
+ * Sits beside {@link openStrategyIntent} rather than under
356
+ * {@link startIntent} for the same reason: there is no account yet, and the
357
+ * output feeds `sdk.accounts.openCA`. What sets it apart from an opening is
358
+ * where the loan goes — out to the wallet rather than into a position — so
359
+ * the debt is named outright instead of following from a leverage, and the
360
+ * collateral is the only thing the account is left holding.
361
+ *
362
+ * `creditAccount` draws the loan on one the wallet already holds instead of
363
+ * opening another, as an opening takes one.
364
+ *
365
+ * @param props - Credit manager, the collateral the wallet puts up and the
366
+ * payout it asks for
367
+ * @returns Debt, the payout's two branches and the projection the account
368
+ * lands in, or `{ ok: false, error }` when the loan is not viable — a debt
369
+ * outside the facade's limits, collateral that cannot carry it, a payout the
370
+ * router has no path to
371
+ */
372
+ async borrowIntent(props) {
373
+ try {
374
+ return {
375
+ ok: true,
376
+ state: await buildBorrowState(props)
377
+ };
378
+ } catch (e) {
379
+ return asSDKError(e);
380
+ }
381
+ }
295
382
  /** Plan → realise → wrap. Unviable requests become `{ ok: false }`. */
296
383
  async #preview(props, plan) {
297
384
  try {
@@ -1,5 +1,6 @@
1
1
  import { BigIntMath } from "../../utils/bigint-math.js";
2
2
  import { LEVERAGE_DECIMALS } from "../../constants/math.js";
3
+ import { resolveCreditManager } from "./utils/common.js";
3
4
  //#region src/onchain/accounts/intents/leverage-band.ts
4
5
  /**
5
6
  * The leverages this market will actually fund for a position of this size.
@@ -29,7 +30,7 @@ import { LEVERAGE_DECIMALS } from "../../constants/math.js";
29
30
  * ```
30
31
  **/
31
32
  function calcLeverageBand({ sdk, creditManager, collateral, targetHF }) {
32
- const found = resolve(sdk, creditManager);
33
+ const found = resolveCreditManager(sdk, creditManager);
33
34
  if (!found) return;
34
35
  const { suite, market } = found;
35
36
  const target = suite.strategyTargetCollateral;
@@ -54,16 +55,5 @@ function calcLeverageBand({ sdk, creditManager, collateral, targetHF }) {
54
55
  max
55
56
  };
56
57
  }
57
- /** The manager's suite and market, or nothing while they cannot be resolved. */
58
- function resolve(sdk, creditManager) {
59
- try {
60
- return {
61
- suite: sdk.marketRegister.findCreditManager(creditManager),
62
- market: sdk.marketRegister.findByCreditManager(creditManager)
63
- };
64
- } catch {
65
- return;
66
- }
67
- }
68
58
  //#endregion
69
59
  export { calcLeverageBand };
@@ -0,0 +1,87 @@
1
+ import { BigIntMath } from "../../utils/bigint-math.js";
2
+ import "../../constants/math.js";
3
+ import "../../utils/index.js";
4
+ import { eq, resolveCreditManager, toTargetDecimals } from "./utils/common.js";
5
+ import { unopenedAccountSlice } from "./utils/credit-account-slice.js";
6
+ import "./utils/index.js";
7
+ import { borrowCollateralQuota } from "./borrow.js";
8
+ import { collateralValuation } from "./collateral-valuation.js";
9
+ //#region src/onchain/accounts/intents/maxBorrow.ts
10
+ /**
11
+ * Largest loan this collateral supports at `targetHF` — the ceiling a borrow
12
+ * form should offer, in the payout token's units.
13
+ *
14
+ * The inverse of a borrow rather than a search for one: the loan leaves the
15
+ * account entirely, so the collateral is the whole of what backs the debt, and
16
+ * the health factor is one division away from the amount. Solving it the other
17
+ * way round costs a division too, and no iteration.
18
+ *
19
+ * Collateral is valued the way the transaction will be judged — at safe
20
+ * prices, under its liquidation threshold, capped by the quota the borrow
21
+ * buys for it, all of which is {@link collateralValuation}'s business. The ceiling
22
+ * is then held to what the market will actually lend: the pool's free
23
+ * liquidity, the manager's own allowance and the facade's `maxDebt`, whichever
24
+ * binds first.
25
+ *
26
+ * The facade's `minDebt` is deliberately not applied. It is a floor, and a
27
+ * ceiling answered as `0n` because the collateral is too small for this market
28
+ * would tell a form nothing about what it is holding — the number a user needs
29
+ * to see is the one they are short of. Collateral that carries something
30
+ * therefore answers with it, whether or not the market would lend that little;
31
+ * a loan under the floor is refused by `borrow` itself, with `debtOutOfRange`
32
+ * naming both ends.
33
+ *
34
+ * Nothing is fetched or simulated — the account does not exist yet and every
35
+ * input is loaded market state, so a form can call this on each keystroke.
36
+ *
37
+ * @param props - {@link MaxBorrowProps}
38
+ * @returns Amount in the payout token's units; `0n` where no loan of this
39
+ * shape exists at any size — a collateral that backs nothing at safe prices, a
40
+ * market with nothing left to lend, and a manager the SDK does not hold yet
41
+ **/
42
+ function maxBorrow(props) {
43
+ const { sdk, creditManager, collateralAmount, targetHF, quotaReserve } = props;
44
+ const found = resolveCreditManager(sdk, creditManager);
45
+ if (!found) return 0n;
46
+ const { suite, market } = found;
47
+ const { priceOracle } = market;
48
+ const underlying = market.pool.underlying.toLowerCase();
49
+ const collateralToken = props.collateralToken.toLowerCase();
50
+ const borrowToken = props.borrowToken.toLowerCase();
51
+ const rwaAsset = sdk.tokensMeta.rwaUnderlyings.get(underlying)?.asset?.toLowerCase();
52
+ if (eq(collateralToken, borrowToken)) return 0n;
53
+ if (rwaAsset && eq(borrowToken, underlying)) return 0n;
54
+ if (collateralAmount <= 10n || targetHF <= 0n) return 0n;
55
+ const quotas = borrowCollateralQuota({
56
+ sdk,
57
+ creditManager,
58
+ assets: [{
59
+ token: collateralToken,
60
+ balance: collateralAmount
61
+ }],
62
+ quotaReserve
63
+ });
64
+ const holding = {
65
+ token: collateralToken,
66
+ balance: collateralAmount,
67
+ quota: quotas.find((q) => eq(q.token, collateralToken))?.balance ?? 0n,
68
+ mask: 0n,
69
+ success: true
70
+ };
71
+ const valuation = collateralValuation({
72
+ ...unopenedAccountSlice({
73
+ creditManager,
74
+ creditFacade: suite.creditFacade.address,
75
+ underlying
76
+ }),
77
+ tokens: [holding]
78
+ }, sdk);
79
+ const weighted = valuation.checkedUsd(holding) * valuation.lt(collateralToken);
80
+ const backed = quotas.some((q) => eq(q.token, collateralToken)) ? BigIntMath.min(valuation.quotaValue(holding), weighted) : weighted;
81
+ if (backed <= 0n) return 0n;
82
+ const ceiling = BigIntMath.min(priceOracle.safeConvertFromUSD(underlying, backed / targetHF).value, suite.maxBorrowAmount().amount.value);
83
+ const unwrapsPayout = !!rwaAsset && eq(borrowToken, rwaAsset);
84
+ return eq(borrowToken, underlying) ? ceiling : unwrapsPayout ? toTargetDecimals(ceiling, underlying, borrowToken, sdk) : priceOracle.safeConvert(underlying, borrowToken, ceiling).value;
85
+ }
86
+ //#endregion
87
+ export { maxBorrow };