@morpho-org/morpho-sdk 10.3.1 → 10.4.0

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 (188) hide show
  1. package/README.md +169 -5
  2. package/lib/cjs/actions/midnight/redeem.d.ts +20 -3
  3. package/lib/cjs/actions/midnight/redeem.js +58 -1
  4. package/lib/cjs/actions/midnight/supplyCollateralWithNative.d.ts +24 -1
  5. package/lib/cjs/actions/midnight/supplyCollateralWithNative.js +41 -0
  6. package/lib/cjs/actions/midnight/withdrawCollateral.d.ts +16 -2
  7. package/lib/cjs/actions/midnight/withdrawCollateral.js +26 -1
  8. package/lib/cjs/helpers/callback.d.ts +3 -2
  9. package/lib/cjs/helpers/callback.js +4 -20
  10. package/lib/cjs/helpers/computeMidnightPostWithdrawalCollateral.d.ts +17 -0
  11. package/lib/cjs/helpers/computeMidnightPostWithdrawalCollateral.js +30 -0
  12. package/lib/cjs/helpers/parseMidnightMaker.d.ts +21 -0
  13. package/lib/cjs/helpers/parseMidnightMaker.js +41 -1
  14. package/lib/cjs/helpers/validate.d.ts +49 -1
  15. package/lib/cjs/helpers/validate.js +87 -1
  16. package/lib/cjs/helpers/validateMidnightPublication.d.ts +10 -0
  17. package/lib/cjs/helpers/validateMidnightPublication.js +18 -1
  18. package/lib/cjs/helpers/validateMidnightTakeableOfferFields.d.ts +28 -0
  19. package/lib/cjs/helpers/validateMidnightTakeableOfferFields.js +85 -0
  20. package/lib/cjs/index.d.ts +2 -2
  21. package/lib/cjs/index.js +23 -1
  22. package/lib/cjs/midnight/utils.d.ts +1 -1
  23. package/lib/cjs/midnight/utils.js +2 -1
  24. package/lib/cjs/transactionPlan/blue/withdrawBuyCallback.d.ts +101 -0
  25. package/lib/cjs/transactionPlan/blue/withdrawBuyCallback.js +264 -0
  26. package/lib/cjs/transactionPlan/error.d.ts +27 -0
  27. package/lib/cjs/transactionPlan/error.js +30 -1
  28. package/lib/cjs/transactionPlan/index.d.ts +40 -1
  29. package/lib/cjs/transactionPlan/index.js +46 -5
  30. package/lib/cjs/transactionPlan/midnight/authorization.d.ts +15 -0
  31. package/lib/cjs/transactionPlan/midnight/authorization.js +45 -0
  32. package/lib/cjs/transactionPlan/midnight/cancelOffers.d.ts +80 -0
  33. package/lib/cjs/transactionPlan/midnight/cancelOffers.js +125 -0
  34. package/lib/cjs/transactionPlan/midnight/makeBorrow.d.ts +104 -0
  35. package/lib/cjs/transactionPlan/midnight/makeBorrow.js +126 -0
  36. package/lib/cjs/transactionPlan/midnight/makeLend.d.ts +140 -0
  37. package/lib/cjs/transactionPlan/midnight/makeLend.js +176 -0
  38. package/lib/cjs/transactionPlan/midnight/makeRepay.d.ts +118 -0
  39. package/lib/cjs/transactionPlan/midnight/makeRepay.js +118 -0
  40. package/lib/cjs/transactionPlan/midnight/makeWithdraw.d.ts +104 -0
  41. package/lib/cjs/transactionPlan/midnight/makeWithdraw.js +126 -0
  42. package/lib/cjs/transactionPlan/midnight/makerPublication.d.ts +55 -0
  43. package/lib/cjs/transactionPlan/midnight/makerPublication.js +315 -0
  44. package/lib/cjs/transactionPlan/midnight/market.d.ts +49 -0
  45. package/lib/cjs/transactionPlan/midnight/market.js +120 -0
  46. package/lib/cjs/transactionPlan/midnight/prepare.d.ts +244 -0
  47. package/lib/cjs/transactionPlan/midnight/prepare.js +547 -0
  48. package/lib/cjs/transactionPlan/midnight/publicationState.d.ts +24 -0
  49. package/lib/cjs/transactionPlan/midnight/publicationState.js +50 -0
  50. package/lib/cjs/transactionPlan/midnight/redeem.d.ts +102 -0
  51. package/lib/cjs/transactionPlan/midnight/redeem.js +170 -0
  52. package/lib/cjs/transactionPlan/midnight/reduceOnlySellFeasibility.d.ts +25 -0
  53. package/lib/cjs/transactionPlan/midnight/reduceOnlySellFeasibility.js +51 -0
  54. package/lib/cjs/transactionPlan/midnight/repayWithdrawCollateral.d.ts +162 -0
  55. package/lib/cjs/transactionPlan/midnight/repayWithdrawCollateral.js +328 -0
  56. package/lib/cjs/transactionPlan/midnight/supplyBlueMakeLend.d.ts +155 -0
  57. package/lib/cjs/transactionPlan/midnight/supplyBlueMakeLend.js +199 -0
  58. package/lib/cjs/transactionPlan/midnight/supplyCollateral.d.ts +96 -0
  59. package/lib/cjs/transactionPlan/midnight/supplyCollateral.js +190 -0
  60. package/lib/cjs/transactionPlan/midnight/supplyCollateralBatch.d.ts +112 -0
  61. package/lib/cjs/transactionPlan/midnight/supplyCollateralBatch.js +221 -0
  62. package/lib/cjs/transactionPlan/midnight/supplyCollateralMakeBorrow.d.ts +129 -0
  63. package/lib/cjs/transactionPlan/midnight/supplyCollateralMakeBorrow.js +179 -0
  64. package/lib/cjs/transactionPlan/midnight/supplyCollateralWithNative.d.ts +115 -0
  65. package/lib/cjs/transactionPlan/midnight/supplyCollateralWithNative.js +259 -0
  66. package/lib/cjs/transactionPlan/midnight/takeBorrow.d.ts +304 -0
  67. package/lib/cjs/transactionPlan/midnight/takeBorrow.js +545 -0
  68. package/lib/cjs/transactionPlan/midnight/takeLend.d.ts +99 -0
  69. package/lib/cjs/transactionPlan/midnight/takeLend.js +263 -0
  70. package/lib/cjs/transactionPlan/midnight/takeRepayWithdrawCollateral.d.ts +175 -0
  71. package/lib/cjs/transactionPlan/midnight/takeRepayWithdrawCollateral.js +440 -0
  72. package/lib/cjs/transactionPlan/midnight/takeWithdraw.d.ts +139 -0
  73. package/lib/cjs/transactionPlan/midnight/takeWithdraw.js +240 -0
  74. package/lib/cjs/transactionPlan/midnight/validation.d.ts +22 -0
  75. package/lib/cjs/transactionPlan/midnight/validation.js +158 -0
  76. package/lib/cjs/transactionPlan/midnight/withdrawCollateral.d.ts +130 -0
  77. package/lib/cjs/transactionPlan/midnight/withdrawCollateral.js +228 -0
  78. package/lib/cjs/transactionPlan/midnight/withdrawCollateralBatch.d.ts +142 -0
  79. package/lib/cjs/transactionPlan/midnight/withdrawCollateralBatch.js +232 -0
  80. package/lib/cjs/transactionPlan/plan.d.ts +48 -14
  81. package/lib/cjs/transactionPlan/plan.js +103 -18
  82. package/lib/cjs/transactionPlan/requirements.d.ts +7 -4
  83. package/lib/cjs/transactionPlan/requirements.js +2 -2
  84. package/lib/cjs/transactionPlan/serde.d.ts +13 -2
  85. package/lib/cjs/transactionPlan/serde.js +68 -21
  86. package/lib/cjs/transactionPlan/types.d.ts +147 -0
  87. package/lib/cjs/transactionPlan/validateActions.d.ts +3 -1
  88. package/lib/cjs/transactionPlan/validateActions.js +31 -3
  89. package/lib/cjs/transactionPlan/validation.d.ts +1 -1
  90. package/lib/cjs/transactionPlan/validation.js +37 -1
  91. package/lib/cjs/types/error.d.ts +2 -0
  92. package/lib/cjs/types/error.js +2 -0
  93. package/lib/cjs/version.d.ts +1 -1
  94. package/lib/cjs/version.js +1 -1
  95. package/lib/esm/actions/midnight/redeem.d.ts +20 -3
  96. package/lib/esm/actions/midnight/redeem.js +56 -0
  97. package/lib/esm/actions/midnight/supplyCollateralWithNative.d.ts +24 -1
  98. package/lib/esm/actions/midnight/supplyCollateralWithNative.js +40 -0
  99. package/lib/esm/actions/midnight/withdrawCollateral.d.ts +16 -2
  100. package/lib/esm/actions/midnight/withdrawCollateral.js +25 -1
  101. package/lib/esm/helpers/callback.d.ts +3 -2
  102. package/lib/esm/helpers/callback.js +5 -21
  103. package/lib/esm/helpers/computeMidnightPostWithdrawalCollateral.d.ts +17 -0
  104. package/lib/esm/helpers/computeMidnightPostWithdrawalCollateral.js +27 -0
  105. package/lib/esm/helpers/parseMidnightMaker.d.ts +21 -0
  106. package/lib/esm/helpers/parseMidnightMaker.js +40 -1
  107. package/lib/esm/helpers/validate.d.ts +49 -1
  108. package/lib/esm/helpers/validate.js +84 -1
  109. package/lib/esm/helpers/validateMidnightPublication.d.ts +10 -0
  110. package/lib/esm/helpers/validateMidnightPublication.js +16 -0
  111. package/lib/esm/helpers/validateMidnightTakeableOfferFields.d.ts +28 -0
  112. package/lib/esm/helpers/validateMidnightTakeableOfferFields.js +81 -0
  113. package/lib/esm/index.d.ts +2 -2
  114. package/lib/esm/index.js +1 -1
  115. package/lib/esm/midnight/utils.d.ts +1 -1
  116. package/lib/esm/midnight/utils.js +1 -1
  117. package/lib/esm/transactionPlan/blue/withdrawBuyCallback.d.ts +101 -0
  118. package/lib/esm/transactionPlan/blue/withdrawBuyCallback.js +259 -0
  119. package/lib/esm/transactionPlan/error.d.ts +27 -0
  120. package/lib/esm/transactionPlan/error.js +28 -0
  121. package/lib/esm/transactionPlan/index.d.ts +40 -1
  122. package/lib/esm/transactionPlan/index.js +20 -1
  123. package/lib/esm/transactionPlan/midnight/authorization.d.ts +15 -0
  124. package/lib/esm/transactionPlan/midnight/authorization.js +40 -0
  125. package/lib/esm/transactionPlan/midnight/cancelOffers.d.ts +80 -0
  126. package/lib/esm/transactionPlan/midnight/cancelOffers.js +120 -0
  127. package/lib/esm/transactionPlan/midnight/makeBorrow.d.ts +104 -0
  128. package/lib/esm/transactionPlan/midnight/makeBorrow.js +123 -0
  129. package/lib/esm/transactionPlan/midnight/makeLend.d.ts +140 -0
  130. package/lib/esm/transactionPlan/midnight/makeLend.js +172 -0
  131. package/lib/esm/transactionPlan/midnight/makeRepay.d.ts +118 -0
  132. package/lib/esm/transactionPlan/midnight/makeRepay.js +115 -0
  133. package/lib/esm/transactionPlan/midnight/makeWithdraw.d.ts +104 -0
  134. package/lib/esm/transactionPlan/midnight/makeWithdraw.js +123 -0
  135. package/lib/esm/transactionPlan/midnight/makerPublication.d.ts +55 -0
  136. package/lib/esm/transactionPlan/midnight/makerPublication.js +310 -0
  137. package/lib/esm/transactionPlan/midnight/market.d.ts +49 -0
  138. package/lib/esm/transactionPlan/midnight/market.js +112 -0
  139. package/lib/esm/transactionPlan/midnight/prepare.d.ts +244 -0
  140. package/lib/esm/transactionPlan/midnight/prepare.js +536 -0
  141. package/lib/esm/transactionPlan/midnight/publicationState.d.ts +24 -0
  142. package/lib/esm/transactionPlan/midnight/publicationState.js +47 -0
  143. package/lib/esm/transactionPlan/midnight/redeem.d.ts +102 -0
  144. package/lib/esm/transactionPlan/midnight/redeem.js +165 -0
  145. package/lib/esm/transactionPlan/midnight/reduceOnlySellFeasibility.d.ts +25 -0
  146. package/lib/esm/transactionPlan/midnight/reduceOnlySellFeasibility.js +47 -0
  147. package/lib/esm/transactionPlan/midnight/repayWithdrawCollateral.d.ts +162 -0
  148. package/lib/esm/transactionPlan/midnight/repayWithdrawCollateral.js +323 -0
  149. package/lib/esm/transactionPlan/midnight/supplyBlueMakeLend.d.ts +155 -0
  150. package/lib/esm/transactionPlan/midnight/supplyBlueMakeLend.js +196 -0
  151. package/lib/esm/transactionPlan/midnight/supplyCollateral.d.ts +96 -0
  152. package/lib/esm/transactionPlan/midnight/supplyCollateral.js +185 -0
  153. package/lib/esm/transactionPlan/midnight/supplyCollateralBatch.d.ts +112 -0
  154. package/lib/esm/transactionPlan/midnight/supplyCollateralBatch.js +216 -0
  155. package/lib/esm/transactionPlan/midnight/supplyCollateralMakeBorrow.d.ts +129 -0
  156. package/lib/esm/transactionPlan/midnight/supplyCollateralMakeBorrow.js +176 -0
  157. package/lib/esm/transactionPlan/midnight/supplyCollateralWithNative.d.ts +115 -0
  158. package/lib/esm/transactionPlan/midnight/supplyCollateralWithNative.js +254 -0
  159. package/lib/esm/transactionPlan/midnight/takeBorrow.d.ts +304 -0
  160. package/lib/esm/transactionPlan/midnight/takeBorrow.js +539 -0
  161. package/lib/esm/transactionPlan/midnight/takeLend.d.ts +99 -0
  162. package/lib/esm/transactionPlan/midnight/takeLend.js +258 -0
  163. package/lib/esm/transactionPlan/midnight/takeRepayWithdrawCollateral.d.ts +175 -0
  164. package/lib/esm/transactionPlan/midnight/takeRepayWithdrawCollateral.js +435 -0
  165. package/lib/esm/transactionPlan/midnight/takeWithdraw.d.ts +139 -0
  166. package/lib/esm/transactionPlan/midnight/takeWithdraw.js +236 -0
  167. package/lib/esm/transactionPlan/midnight/validation.d.ts +22 -0
  168. package/lib/esm/transactionPlan/midnight/validation.js +151 -0
  169. package/lib/esm/transactionPlan/midnight/withdrawCollateral.d.ts +130 -0
  170. package/lib/esm/transactionPlan/midnight/withdrawCollateral.js +223 -0
  171. package/lib/esm/transactionPlan/midnight/withdrawCollateralBatch.d.ts +142 -0
  172. package/lib/esm/transactionPlan/midnight/withdrawCollateralBatch.js +227 -0
  173. package/lib/esm/transactionPlan/plan.d.ts +48 -14
  174. package/lib/esm/transactionPlan/plan.js +99 -14
  175. package/lib/esm/transactionPlan/requirements.d.ts +7 -4
  176. package/lib/esm/transactionPlan/requirements.js +2 -2
  177. package/lib/esm/transactionPlan/serde.d.ts +13 -2
  178. package/lib/esm/transactionPlan/serde.js +49 -2
  179. package/lib/esm/transactionPlan/types.d.ts +147 -0
  180. package/lib/esm/transactionPlan/validateActions.d.ts +3 -1
  181. package/lib/esm/transactionPlan/validateActions.js +31 -3
  182. package/lib/esm/transactionPlan/validation.d.ts +1 -1
  183. package/lib/esm/transactionPlan/validation.js +38 -2
  184. package/lib/esm/types/error.d.ts +2 -0
  185. package/lib/esm/types/error.js +2 -0
  186. package/lib/esm/version.d.ts +1 -1
  187. package/lib/esm/version.js +1 -1
  188. package/package.json +2 -2
@@ -0,0 +1,539 @@
1
+ import { MathLib } from "@morpho-org/blue-sdk";
2
+ import { AccrualPosition } from "@morpho-org/midnight-sdk";
3
+ import { deepFreeze, getChainAddress, Time } from "@morpho-org/morpho-ts";
4
+ import { midnightSupplyCollateralTakeBorrow, parseMidnightSupplyCollateralTakeBorrow, } from "../../actions/midnight/supplyCollateralTakeBorrow.js";
5
+ import { midnightTakeBorrow, parseMidnightTakeBorrow, } from "../../actions/midnight/takeBorrow.js";
6
+ import { createChainCheck } from "../../actions/requirements/chainCheck.js";
7
+ import { parseMidnightApprovalRequirements } from "../../actions/requirements/midnight/getMidnightApprovalRequirements.js";
8
+ import { assertRegistryTargetsHaveCode } from "../../entities/requirements/assertContractCode.js";
9
+ import { MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS } from "../../helpers/constant.js";
10
+ import { validateMidnightPositionBinding } from "../../helpers/parseMidnight.js";
11
+ import { validateMidnightBorrowHealth, validateReferenceTime, } from "../../helpers/validate.js";
12
+ import { validateMidnightTakeableOfferFields } from "../../helpers/validateMidnightTakeableOfferFields.js";
13
+ import { validateMidnightTakeFeasibility } from "../../helpers/validateMidnightTakeFeasibility.js";
14
+ import { MidnightTakeDeadlineTooFarError } from "../../types/error.js";
15
+ import { InvalidTransactionPlanError } from "../error.js";
16
+ import { resolveIntent } from "../intent.js";
17
+ import { getTokenRequirements } from "../requirements.js";
18
+ import { getPlanObject, validatePlanFields } from "../validation.js";
19
+ import { prepareMidnightBundleAuthorization } from "./authorization.js";
20
+ import { storedFills, storedMarketTuple, validateCollateralIndexTypes, validateStoredCollateralOrder, } from "./market.js";
21
+ import { invalidSellTargetType, validateMidnightSellPlanAction, validateMidnightTargetAmountTypes, } from "./validation.js";
22
+ /**
23
+ * Prepares a MidnightBundlesV2 borrow for the submitting account, using existing
24
+ * credit first and then filling lend offers under the given target and referral fee.
25
+ * Validates inputs with the same parse-once constructor, position binding, buffered health
26
+ * check and fill feasibility check as the entity `takeBorrow`, then reads the registry
27
+ * targets' bytecode and the bundle authorization. Feasibility uses the position's credit
28
+ * accrued to the reference timestamp against `marketData`, the same snapshot that caps
29
+ * withdrawable credit. On an assets target, offers that would revert the
30
+ * whole bundle are dropped from the stored fills. Like the entity check, fill feasibility counts
31
+ * units at par and does not price discounted bids after settlement fees, so a plan can pass
32
+ * preparation and still revert onchain; the onchain bounds keep funds safe. Simulate before sending.
33
+ * @param client - Viem client used to verify chain, deployments and authorization.
34
+ * @param params - Account, market and position snapshots, collateral prices, fills and intent.
35
+ * @param params.chainId - Chain containing the market and MidnightBundlesV2.
36
+ * @param params.account - Non-zero borrower that sends the plan and owns any new debt.
37
+ * @param params.marketData - Hydrated market snapshot used for fill feasibility and collateral capacity.
38
+ * @param params.positionData - Borrower's position snapshot for the same market.
39
+ * @param params.collateralPrices - Oracle prices indexed by market collateral, scaled by `ORACLE_PRICE_SCALE`.
40
+ * @param params.takeableOffers - ABI-ready lend offers from the caller's quote, in fill order.
41
+ * @param params.target.type - `"assets"` to receive loan assets, or `"units"` to sell exact units.
42
+ * @param params.target.assets - Exact loan assets paid to the receiver on an assets target; any referral fee is sold on top.
43
+ * @param params.target.maxUnits - Unit cap on an assets target; also bounds the buffered health check.
44
+ * @param params.target.units - Exact units to sell on a units target.
45
+ * @param params.target.minSellerAssets - Loan-asset floor on a units target, checked against the
46
+ * proceeds after any referral fee.
47
+ * @param params.receiver - Optional recipient of the loan assets; defaults to `account`.
48
+ * @param params.referralFee.bps - Optional referral fee in integer basis points, at most 10%.
49
+ * @param params.referralFee.recipient - Recipient required for a positive referral fee.
50
+ * @param params.now - Reference Unix timestamp in seconds; omitting it uses the device clock (an untyped JavaScript `null` does too).
51
+ * @param params.expiresAt - Onchain deadline in Unix seconds; defaults to, and may not exceed, one hour after `now`.
52
+ * @param params.calldataOrigin - Optional attribution bytes appended to each built transaction.
53
+ * @returns A frozen plan with a standalone authorization step if needed and no signature requests.
54
+ * @throws {InvalidBigIntInputError} If a supplied non-null `now`, or a target amount, is not a bigint;
55
+ * checked before any request.
56
+ * @throws {ZeroAccountError} If `account` is the zero address.
57
+ * @throws {NonIntegerInputError} If `expiresAt` or `referralFee.bps` is not a safe integer.
58
+ * @throws {NonPositiveInputError} If `expiresAt`, the target amount, `maxUnits` or
59
+ * `minSellerAssets` is not positive.
60
+ * @throws {ExpiredDeadlineError} If expiry is at or before the reference timestamp.
61
+ * @throws {NegativeInputError} If `referralFee.bps` or an offer cap is negative.
62
+ * @throws {InputExceedsMaxError} If `referralFee.bps` exceeds 1,000 (10%), or a target amount or
63
+ * offer cap exceeds uint128.
64
+ * @throws {InvalidCalldataOriginError} If `calldataOrigin` is empty, malformed or has an odd number of hex digits.
65
+ * @throws {MidnightTakeDeadlineTooFarError} If expiry is more than one hour away.
66
+ * @throws {InvalidTransactionPlanError} If `account` is malformed or the target type is neither assets nor units.
67
+ * @throws {ChainIdMismatchError} If the client, transport or market is on a different chain.
68
+ * @throws {MidnightMarketAddressMismatchError} If the market targets another Midnight deployment.
69
+ * @throws {EmptyMidnightTakeableOffersError} If no offers are supplied.
70
+ * @throws {MidnightOfferSideMismatchError} If an offer is not a lend offer.
71
+ * @throws {MidnightTakeableOfferMarketMismatchError} If an offer trades another market.
72
+ * @throws {MidnightCalldataEncodingError} If an offer field cannot be ABI-encoded.
73
+ * @throws {MidnightZeroReceiverError} If the receiver is the zero address.
74
+ * @throws {MidnightContractReceiverError} If the receiver, or the referral fee recipient of a
75
+ * positive fee, is a Midnight protocol or market token contract.
76
+ * @throws {UnboundedMidnightTakeInputError} If `target.units` or `target.maxUnits` is `maxUint256`.
77
+ * @throws {ReferralFeeRecipientMissingError} If a positive referral fee has no recipient.
78
+ * @throws {UnsupportedChainIdError} If the chain is absent from the address registry.
79
+ * @throws {UnknownAddressError} If the chain has no `midnightBundlesV2` deployment.
80
+ * @throws {MarketIdMismatchError} If the position belongs to another market.
81
+ * @throws {AccrualPositionUserMismatchError} If the position is not owned by the account.
82
+ * @throws {BorrowExceedsSafeLtvError} If the debt bound exceeds buffered collateral capacity.
83
+ * @throws {MissingMarketPriceError} If any held collateral has no supplied price.
84
+ * @throws {InvalidMidnightPositionLossFactorError} If `marketData`'s loss factor is below the position's
85
+ * last loss factor; fetch the market and position at the same block.
86
+ * @throws {InvalidMidnightPositionAccrualStateError} If the position's credit and fee snapshot cannot be accrued.
87
+ * @throws {MidnightTakeableOffersNotFillableError} If the supplied offers cannot be used.
88
+ * @throws {MidnightTakeTargetUnreachableError} If the supplied target and bounds cannot be met.
89
+ * @throws {MissingContractCodeError} If either registered Midnight target has no deployed code.
90
+ * @throws {viem.BaseError} If an `eth_chainId` request or the authorization read fails.
91
+ * @example
92
+ * ```ts
93
+ * import { buildTransactions, prepareMidnightTakeBorrow, type TransactionPlan } from "@morpho-org/morpho-sdk";
94
+ * import { fetchMidnightAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
95
+ * import { MidnightApi } from "@morpho-org/morpho-sdk/midnight-api";
96
+ * import { type Address, type Hash, createPublicClient, http, parseAbi } from "viem";
97
+ * import { base } from "viem/chains";
98
+ *
99
+ * async function prepareBorrow(account: Address, marketId: Hash) {
100
+ * const client = createPublicClient({ chain: base, transport: http() });
101
+ * const block = await client.getBlock();
102
+ * const positionData = await fetchMidnightAccrualPosition(client, {
103
+ * marketId,
104
+ * user: account,
105
+ * blockNumber: block.number,
106
+ * });
107
+ * const marketData = positionData.market;
108
+ * const collateralPrices = await Promise.all(
109
+ * marketData.params.collateralParams.map(({ oracle }) =>
110
+ * client.readContract({
111
+ * address: oracle,
112
+ * abi: parseAbi(["function price() view returns (uint256)"]),
113
+ * functionName: "price",
114
+ * blockNumber: block.number,
115
+ * }),
116
+ * ),
117
+ * );
118
+ * const assets = 1_000_000n;
119
+ * const maxUnits = 1_100_000n;
120
+ * // Quote the unit ceiling: fees come out of the proceeds, so fills sized to the net
121
+ * // assets could not deliver them.
122
+ * const quote = await new MidnightApi().fetchBookQuote({
123
+ * marketId,
124
+ * side: "bids",
125
+ * units: maxUnits,
126
+ * taker: account,
127
+ * });
128
+ * const plan: TransactionPlan = await prepareMidnightTakeBorrow(client, {
129
+ * chainId: base.id,
130
+ * account,
131
+ * marketData,
132
+ * positionData,
133
+ * collateralPrices,
134
+ * now: block.timestamp,
135
+ * target: { type: "assets", assets, maxUnits },
136
+ * takeableOffers: quote.data.takeableOffers,
137
+ * });
138
+ * // Simulate, then send in order from plan.account on plan.chainId.
139
+ * return buildTransactions(plan);
140
+ * }
141
+ * ```
142
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
143
+ */
144
+ export async function prepareMidnightTakeBorrow(client, params) {
145
+ return prepareBorrow(client, { params });
146
+ }
147
+ /**
148
+ * Prepares an atomic collateral supply and fixed-rate borrow on MidnightBundlesV2.
149
+ * Validates inputs with the same parse-once constructor, position binding, buffered health
150
+ * check and fill feasibility check as the entity `supplyCollateralTakeBorrow`. Pass the
151
+ * position before the supply: the health check adds the supplied collateral to it, and
152
+ * repeated collateral indexes are summed. Native ETH may fund wrapped-native collateral, but
153
+ * the ERC-20 allowance must cover the full pull. Approvals and authorization are separate
154
+ * steps, so they can remain even if the bundled transaction fails.
155
+ * @param client - Viem client used to verify chain, deployments, allowances and authorization.
156
+ * @param params - Account, market and pre-supply position snapshots, collateral prices,
157
+ * collateral supplies, optional native funding, fills and intent.
158
+ * @param params.chainId - Chain containing the market and MidnightBundlesV2.
159
+ * @param params.account - Non-zero borrower that supplies the collateral, sends the plan and owns any new debt.
160
+ * @param params.marketData - Hydrated market snapshot used for fill feasibility and collateral capacity.
161
+ * @param params.positionData - Borrower's position snapshot for the same market, taken before the supply.
162
+ * @param params.collateralPrices - Oracle prices indexed by market collateral, scaled by `ORACLE_PRICE_SCALE`.
163
+ * @param params.collateralSupplies - Positive collateral supplies; each `collateralIndex` indexes
164
+ * `marketData.params.collateralParams`, `assets` is in that token's base units, and repeated indexes are summed.
165
+ * @param params.nativeAmount - Optional native ETH in wei for wrapped-native collateral, capped by its pull.
166
+ * @param params.takeableOffers - ABI-ready lend offers from the caller's quote, in fill order.
167
+ * @param params.target.type - `"assets"` to receive loan assets, or `"units"` to sell exact units.
168
+ * @param params.target.assets - Exact loan assets paid to the receiver on an assets target; any referral fee is sold on top.
169
+ * @param params.target.maxUnits - Unit cap on an assets target; also bounds the buffered health check.
170
+ * @param params.target.units - Exact units to sell on a units target.
171
+ * @param params.target.minSellerAssets - Loan-asset floor on a units target, checked against the
172
+ * proceeds after any referral fee.
173
+ * @param params.receiver - Optional recipient of the loan assets; defaults to `account`.
174
+ * @param params.referralFee.bps - Optional referral fee in integer basis points, at most 10%.
175
+ * @param params.referralFee.recipient - Recipient required for a positive referral fee.
176
+ * @param params.now - Reference Unix timestamp in seconds; defaults to the device clock.
177
+ * @param params.expiresAt - Onchain deadline in Unix seconds; defaults to, and may not exceed, one hour after `now`.
178
+ * @param params.calldataOrigin - Optional attribution bytes appended to each built transaction.
179
+ * @returns A frozen plan with any necessary approvals and authorization, without signature requests.
180
+ * @throws {InvalidBigIntInputError} If a supplied non-null `now`, a target amount or a collateral index
181
+ * is not a bigint; checked before any request.
182
+ * @throws {ZeroAccountError} If `account` is the zero address.
183
+ * @throws {NonIntegerInputError} If `expiresAt` or `referralFee.bps` is not a safe integer.
184
+ * @throws {NonPositiveInputError} If `expiresAt`, a supply amount, the target amount,
185
+ * `maxUnits` or `minSellerAssets` is not positive.
186
+ * @throws {ExpiredDeadlineError} If expiry is at or before the reference timestamp.
187
+ * @throws {NegativeInputError} If `referralFee.bps`, an offer cap or `nativeAmount` is negative.
188
+ * @throws {InputExceedsMaxError} If `referralFee.bps` exceeds 1,000 (10%), a supply amount, per-index
189
+ * sum, target amount or offer cap exceeds uint128, or `nativeAmount` exceeds the wrapped-native pull.
190
+ * @throws {InvalidCalldataOriginError} If `calldataOrigin` is empty, malformed or has an odd number of hex digits.
191
+ * @throws {MidnightTakeDeadlineTooFarError} If expiry is more than one hour away.
192
+ * @throws {InvalidTransactionPlanError} If `account` is malformed, `collateralSupplies` is not an
193
+ * array of objects, or the target type is neither assets nor units.
194
+ * @throws {ChainIdMismatchError} If the client, transport or market is on a different chain.
195
+ * @throws {MidnightMarketAddressMismatchError} If the market targets another Midnight deployment.
196
+ * @throws {EmptyMidnightCollateralSuppliesError} If no collateral is supplied.
197
+ * @throws {UnknownCollateralIndexError} If a supply names an unconfigured collateral index.
198
+ * @throws {EmptyMidnightTakeableOffersError} If no offers are supplied.
199
+ * @throws {MidnightOfferSideMismatchError} If an offer is not a lend offer.
200
+ * @throws {MidnightTakeableOfferMarketMismatchError} If an offer trades another market.
201
+ * @throws {MidnightCalldataEncodingError} If an offer field cannot be ABI-encoded.
202
+ * @throws {MidnightZeroReceiverError} If the receiver is the zero address.
203
+ * @throws {MidnightContractReceiverError} If the receiver, or the referral fee recipient of a
204
+ * positive fee, is a Midnight protocol or market token contract.
205
+ * @throws {UnboundedMidnightTakeInputError} If `target.units` or `target.maxUnits` is `maxUint256`.
206
+ * @throws {ReferralFeeRecipientMissingError} If a positive referral fee has no recipient.
207
+ * @throws {MidnightTakeTargetUnreachableError} If the supplied target and bounds cannot be met.
208
+ * @throws {InvalidMidnightNativeAmountTypeError} If `nativeAmount` is not a bigint.
209
+ * @throws {ChainWNativeMissingError} If native funding is used on a chain without wrapped native.
210
+ * @throws {NativeAmountOnNonWNativeAssetError} If native funding is used without a wrapped-native supply.
211
+ * @throws {UnsupportedChainIdError} If the chain is absent from the address registry.
212
+ * @throws {UnknownAddressError} If the chain has no `midnightBundlesV2` deployment.
213
+ * @throws {MarketIdMismatchError} If the position belongs to another market.
214
+ * @throws {AccrualPositionUserMismatchError} If the position is not owned by the account.
215
+ * @throws {BorrowExceedsSafeLtvError} If the debt bound exceeds the post-supply buffered capacity.
216
+ * @throws {MissingMarketPriceError} If any held collateral has no supplied price.
217
+ * @throws {InvalidMidnightPositionLossFactorError} If `marketData`'s loss factor is below the position's
218
+ * last loss factor; fetch the market and position at the same block.
219
+ * @throws {InvalidMidnightPositionAccrualStateError} If the position's credit and fee snapshot cannot be accrued.
220
+ * @throws {MidnightTakeableOffersNotFillableError} If the supplied offers cannot be used.
221
+ * @throws {MissingContractCodeError} If either registered Midnight target has no deployed code.
222
+ * @throws {viem.BaseError} If an `eth_chainId` request, an allowance read or the authorization read fails.
223
+ * @example
224
+ * ```ts
225
+ * import {
226
+ * buildTransactions,
227
+ * prepareMidnightSupplyCollateralTakeBorrow,
228
+ * type TransactionPlan,
229
+ * } from "@morpho-org/morpho-sdk";
230
+ * import { fetchMidnightAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
231
+ * import { MidnightApi } from "@morpho-org/morpho-sdk/midnight-api";
232
+ * import { type Address, type Hash, createPublicClient, http, parseAbi } from "viem";
233
+ * import { base } from "viem/chains";
234
+ *
235
+ * async function prepareSupplyAndBorrow(account: Address, marketId: Hash, collateralAssets: bigint) {
236
+ * const client = createPublicClient({ chain: base, transport: http() });
237
+ * const block = await client.getBlock();
238
+ * // Read the position before the supply; the health check adds the supplied collateral.
239
+ * const positionData = await fetchMidnightAccrualPosition(client, {
240
+ * marketId,
241
+ * user: account,
242
+ * blockNumber: block.number,
243
+ * });
244
+ * const marketData = positionData.market;
245
+ * const collateralPrices = await Promise.all(
246
+ * marketData.params.collateralParams.map(({ oracle }) =>
247
+ * client.readContract({
248
+ * address: oracle,
249
+ * abi: parseAbi(["function price() view returns (uint256)"]),
250
+ * functionName: "price",
251
+ * blockNumber: block.number,
252
+ * }),
253
+ * ),
254
+ * );
255
+ * const assets = 1_000_000n;
256
+ * const maxUnits = 1_100_000n;
257
+ * // Quote the unit ceiling: fees come out of the proceeds.
258
+ * const quote = await new MidnightApi().fetchBookQuote({
259
+ * marketId,
260
+ * side: "bids",
261
+ * units: maxUnits,
262
+ * taker: account,
263
+ * });
264
+ * const plan: TransactionPlan = await prepareMidnightSupplyCollateralTakeBorrow(client, {
265
+ * chainId: base.id,
266
+ * account,
267
+ * marketData,
268
+ * positionData,
269
+ * collateralPrices,
270
+ * now: block.timestamp,
271
+ * collateralSupplies: [{ collateralIndex: 0n, assets: collateralAssets }],
272
+ * target: { type: "assets", assets, maxUnits },
273
+ * takeableOffers: quote.data.takeableOffers,
274
+ * });
275
+ * // Simulate, then send in order from plan.account on plan.chainId.
276
+ * return buildTransactions(plan);
277
+ * }
278
+ * ```
279
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
280
+ */
281
+ export async function prepareMidnightSupplyCollateralTakeBorrow(client, params) {
282
+ return prepareBorrow(client, {
283
+ params,
284
+ supply: {
285
+ collateralSupplies: params.collateralSupplies,
286
+ nativeAmount: params.nativeAmount,
287
+ },
288
+ });
289
+ }
290
+ const supplyActionId = "midnightSupplyCollateralTakeBorrow";
291
+ const sellTargetAmounts = {
292
+ assets: ["assets", "maxUnits"],
293
+ units: ["units", "minSellerAssets"],
294
+ };
295
+ function parseFundedBorrow(borrow, supply) {
296
+ // Throws typed errors before reading entries when a JS caller passes a malformed list.
297
+ validateStoredSuppliesArray(supply.collateralSupplies, "$.collateralSupplies");
298
+ for (const [index, entry] of supply.collateralSupplies.entries()) {
299
+ getPlanObject(entry, `$.collateralSupplies[${index}]`);
300
+ }
301
+ validateCollateralIndexTypes("collateralSupplies", supply.collateralSupplies);
302
+ return parseMidnightSupplyCollateralTakeBorrow({ ...borrow, ...supply });
303
+ }
304
+ async function prepareBorrow(client, { params, supply, }) {
305
+ const { chainId, account, marketData, positionData, collateralPrices, target, } = params;
306
+ const now = params.now ?? Time.timestamp();
307
+ // Reject a non-bigint clock so the window sum below cannot throw a generic TypeError.
308
+ validateReferenceTime(now);
309
+ const maxDeadline = now + MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS;
310
+ const intent = resolveIntent({ ...params, expiresAt: params.expiresAt ?? Number(maxDeadline) }, now);
311
+ if (intent.deadline > maxDeadline) {
312
+ throw new MidnightTakeDeadlineTooFarError({
313
+ deadline: intent.deadline,
314
+ maxDeadline,
315
+ });
316
+ }
317
+ if (target.type !== "assets" && target.type !== "units") {
318
+ throw invalidSellTargetType("$.target");
319
+ }
320
+ validateMidnightTargetAmountTypes(target, sellTargetAmounts[target.type]);
321
+ const borrow = {
322
+ chainId,
323
+ market: marketData.params,
324
+ target,
325
+ receiver: params.receiver ?? account,
326
+ takeableOffers: params.takeableOffers,
327
+ deadline: intent.deadline,
328
+ referralFeePct: intent.referralFeePct,
329
+ referralFeeRecipient: intent.referralFeeRecipient,
330
+ };
331
+ const funded = supply && parseFundedBorrow(borrow, supply);
332
+ const parsed = funded ?? parseMidnightTakeBorrow(borrow);
333
+ validateMidnightTakeableOfferFields(parsed.takeableOffers);
334
+ const bundle = getChainAddress(chainId, "midnightBundlesV2");
335
+ validateMidnightPositionBinding({
336
+ positionData,
337
+ accountAddress: account,
338
+ marketData,
339
+ });
340
+ const collateral = funded
341
+ ? Array.from({ length: parsed.market.collateralParams.length }, (_, index) => positionData.collateral[index] ?? 0n)
342
+ : [...positionData.collateral];
343
+ const pulls = new Map();
344
+ for (const { collateralIndex, token, assets } of funded?.collateralSupplies ??
345
+ []) {
346
+ const index = Number(collateralIndex);
347
+ collateral[index] = (collateral[index] ?? 0n) + assets;
348
+ pulls.set(token, (pulls.get(token) ?? 0n) + assets);
349
+ }
350
+ validateMidnightBorrowHealth({
351
+ market: marketData,
352
+ collateral,
353
+ collateralPrices,
354
+ debt: positionData.debt,
355
+ borrowUnits: parsed.target.type === "units"
356
+ ? parsed.target.units
357
+ : parsed.target.maxUnits,
358
+ });
359
+ const { credit } = new AccrualPosition(positionData, marketData).accrueInterest(MathLib.max(now, positionData.lastAccrual));
360
+ const takeableOffers = validateMidnightTakeFeasibility({
361
+ side: "sell",
362
+ takeableOffers: parsed.takeableOffers,
363
+ accountAddress: account,
364
+ marketData,
365
+ now,
366
+ deadline: parsed.deadline,
367
+ referralFeePct: parsed.referralFeePct,
368
+ fallbackUnits: MathLib.min(credit, marketData.withdrawable),
369
+ credit,
370
+ target: parsed.target,
371
+ increasesDebt: true,
372
+ });
373
+ const requirement = { chainId, account, bundle, pulls };
374
+ const [approvals, authorization] = await prepareBorrowRequirements(client, requirement);
375
+ const inputs = {
376
+ chainId,
377
+ account,
378
+ market: parsed.market,
379
+ target: parsed.target,
380
+ receiver: parsed.receiver,
381
+ takeableOffers,
382
+ deadline: parsed.deadline,
383
+ referralFeePct: parsed.referralFeePct,
384
+ referralFeeRecipient: parsed.referralFeeRecipient,
385
+ };
386
+ return deepFreeze({
387
+ version: 2,
388
+ chainId,
389
+ account,
390
+ expiresAt: intent.expiresAt,
391
+ ...(intent.calldataOrigin && { calldataOrigin: intent.calldataOrigin }),
392
+ steps: [
393
+ ...approvals,
394
+ ...(authorization === undefined ? [] : [authorization]),
395
+ funded
396
+ ? {
397
+ id: supplyActionId,
398
+ label: "Supply collateral and borrow on Midnight",
399
+ action: {
400
+ type: supplyActionId,
401
+ inputs: {
402
+ ...inputs,
403
+ collateralSupplies: funded.collateralSupplies.map(({ collateralIndex, assets }) => ({
404
+ collateralIndex,
405
+ assets,
406
+ })),
407
+ ...(supply?.nativeAmount !== undefined && {
408
+ nativeAssets: supply.nativeAmount,
409
+ }),
410
+ },
411
+ },
412
+ }
413
+ : {
414
+ id: "midnightTakeBorrow",
415
+ label: "Borrow on Midnight",
416
+ action: { type: "midnightTakeBorrow", inputs },
417
+ },
418
+ ],
419
+ signatureRequests: [],
420
+ });
421
+ }
422
+ async function prepareBorrowRequirements(client, requirement) {
423
+ const { chainId, account, bundle } = requirement;
424
+ const chainCheck = createChainCheck(client, chainId);
425
+ await chainCheck();
426
+ // Check deployments before an authorization read can fail decoding empty data.
427
+ await assertRegistryTargetsHaveCode(client, chainId, [
428
+ { role: "midnightBundlesV2", address: bundle },
429
+ { role: "midnight", address: getChainAddress(chainId, "midnight") },
430
+ ], chainCheck);
431
+ return Promise.all([
432
+ prepareCollateralApprovals(client, requirement),
433
+ prepareMidnightBundleAuthorization(client, { chainId, account }),
434
+ ]);
435
+ }
436
+ async function prepareCollateralApprovals(client, { chainId, account, bundle, pulls, }) {
437
+ const requirements = await Promise.all([...pulls].map(([token, amount], tokenIndex) => {
438
+ // Validation only; the entity checks the same per-token bound in getRequirements().
439
+ parseMidnightApprovalRequirements({
440
+ viemClient: client,
441
+ chainId,
442
+ token,
443
+ owner: account,
444
+ spender: bundle,
445
+ amount,
446
+ });
447
+ return getTokenRequirements(client, {
448
+ chainId,
449
+ owner: account,
450
+ token,
451
+ spender: bundle,
452
+ amount,
453
+ approvalId: (index) => `${supplyActionId}:approval:${tokenIndex}:${index}`,
454
+ });
455
+ }));
456
+ return requirements.flatMap(({ approvals }) => approvals);
457
+ }
458
+ function storedBorrowParams({ chainId, market, target, receiver, takeableOffers, deadline, referralFeePct, referralFeeRecipient, }) {
459
+ if (target.type !== "assets" && target.type !== "units") {
460
+ throw invalidSellTargetType("$.inputs.target");
461
+ }
462
+ return {
463
+ chainId,
464
+ market: storedMarketTuple(market),
465
+ target,
466
+ receiver,
467
+ takeableOffers: storedFills(takeableOffers),
468
+ deadline,
469
+ referralFeePct,
470
+ referralFeeRecipient,
471
+ };
472
+ }
473
+ function storedSupplyBorrowParams({ inputs }) {
474
+ return {
475
+ ...storedBorrowParams(inputs),
476
+ collateralSupplies: inputs.collateralSupplies.map(({ collateralIndex, assets }) => ({ collateralIndex, assets })),
477
+ nativeAmount: inputs.nativeAssets,
478
+ };
479
+ }
480
+ /** @internal Encodes the prepared borrow from persisted inputs without state reads. */
481
+ export function buildMidnightTakeBorrow(action) {
482
+ if (action.type !== supplyActionId) {
483
+ return midnightTakeBorrow(storedBorrowParams(action.inputs));
484
+ }
485
+ validateStoredCollateralOrder(action.inputs.market.collateralParams, "$.inputs.market.collateralParams");
486
+ validateStoredSuppliesArray(action.inputs.collateralSupplies, "$.inputs.collateralSupplies");
487
+ for (const [index, supply] of action.inputs.collateralSupplies.entries()) {
488
+ getPlanObject(supply, `$.inputs.collateralSupplies[${index}]`);
489
+ }
490
+ const { type } = getPlanObject(action.inputs.target, "$.inputs.target");
491
+ if (type !== "assets" && type !== "units") {
492
+ throw invalidSellTargetType("$.inputs.target");
493
+ }
494
+ return midnightSupplyCollateralTakeBorrow(storedSupplyBorrowParams(action));
495
+ }
496
+ function validateStoredSuppliesArray(value, path) {
497
+ if (!Array.isArray(value)) {
498
+ throw new InvalidTransactionPlanError({
499
+ path,
500
+ reason: "expected an array",
501
+ });
502
+ }
503
+ }
504
+ /**
505
+ * @internal Validates a stored collateral supply and borrow recipe: the sell shape, the
506
+ * collateral order, the supply and native funding fields, then the action's clock-free parse
507
+ * checks on the stored inputs.
508
+ */
509
+ export function validateMidnightSupplyCollateralTakeBorrowPlanAction(action, path) {
510
+ validateMidnightSellPlanAction(action, path);
511
+ const inputsPath = `${path}.inputs`;
512
+ const inputs = getPlanObject(action.inputs, inputsPath);
513
+ validateStoredCollateralOrder(inputs.market.collateralParams, `${inputsPath}.market.collateralParams`);
514
+ const suppliesPath = `${inputsPath}.collateralSupplies`;
515
+ validateStoredSuppliesArray(inputs.collateralSupplies, suppliesPath);
516
+ for (const [index, supply] of inputs.collateralSupplies.entries()) {
517
+ const supplyPath = `${suppliesPath}[${index}]`;
518
+ validatePlanFields(getPlanObject(supply, supplyPath), {
519
+ path: supplyPath,
520
+ fields: { collateralIndex: "uint256 bigint", assets: "uint128 bigint" },
521
+ });
522
+ }
523
+ if (inputs.nativeAssets !== undefined) {
524
+ validatePlanFields(inputs, {
525
+ path: inputsPath,
526
+ fields: { nativeAssets: "uint256 bigint" },
527
+ });
528
+ }
529
+ try {
530
+ parseMidnightSupplyCollateralTakeBorrow(storedSupplyBorrowParams(action));
531
+ }
532
+ catch (cause) {
533
+ throw new InvalidTransactionPlanError({
534
+ path: inputsPath,
535
+ reason: "expected a valid Midnight collateral supply and borrow",
536
+ cause,
537
+ });
538
+ }
539
+ }
@@ -0,0 +1,99 @@
1
+ import type { Market } from "@morpho-org/midnight-sdk";
2
+ import type { Client } from "viem";
3
+ import { type MidnightTakeLendParams } from "../../actions/midnight/takeLend.js";
4
+ import { type IntentParams } from "../intent.js";
5
+ import type { Action, TransactionPlan } from "../types.js";
6
+ /**
7
+ * Inputs for preparing a fixed-rate lend from caller-selected borrow offers.
8
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
9
+ */
10
+ export interface MidnightTakeLendPlanParams extends Omit<IntentParams, "supportSignature" | "deployless">, Pick<MidnightTakeLendParams, "target" | "takeableOffers" | "nativeAmount" | "maxContinuousFee"> {
11
+ /** Hydrated market snapshot used for validation and fill feasibility. */
12
+ readonly marketData: Market;
13
+ /** Reference timestamp in seconds; defaults to the device clock. */
14
+ readonly now?: bigint;
15
+ /** Unix seconds; defaults to one hour after the reference timestamp. */
16
+ readonly expiresAt?: number;
17
+ }
18
+ /**
19
+ * Prepares an ordered plan to lend through MidnightBundlesV2. Validates inputs with the same
20
+ * parse-once constructor and fill feasibility check as the entity `takeLend`, then reads the
21
+ * registry targets' bytecode, allowance, and authorization. It does not read live fill availability.
22
+ * On an assets target, an offer is dropped from the stored fills only when its price would revert
23
+ * the bundle at every time up to the deadline; one that is invalid for part of that window stays, so
24
+ * simulate before sending.
25
+ * Even with native input, the bundle needs allowance for the full loan-token pull.
26
+ * @param client - Viem client connected to the intent chain for prerequisite reads.
27
+ * @param params - Sender, market snapshot, ABI-ready fills, target bounds, funding and expiry.
28
+ * @param params.now - Optional reference timestamp in Unix seconds; omitting it uses the device clock (an untyped JavaScript `null` does too).
29
+ * @returns A frozen plan with any approval and authorization steps before the lend.
30
+ * @throws {InvalidBigIntInputError} If a supplied non-null `now`, `maxContinuousFee` or a target amount
31
+ * is not a bigint.
32
+ * @throws {ZeroAccountError} If `account` is the zero address.
33
+ * @throws {NonIntegerInputError} If `expiresAt` or `referralFee.bps` is not a safe integer.
34
+ * @throws {NonPositiveInputError} If `expiresAt`, the target amount, `minUnits` or
35
+ * `maxBuyerAssets` is not positive.
36
+ * @throws {ExpiredDeadlineError} If expiry is at or before the reference timestamp.
37
+ * @throws {NegativeInputError} If `referralFee.bps`, an offer cap, `maxContinuousFee` or
38
+ * `nativeAmount` is negative.
39
+ * @throws {InputExceedsMaxError} If `referralFee.bps` exceeds 1,000 (10%), a target amount or offer
40
+ * cap exceeds uint128, `maxContinuousFee` exceeds uint256, or `nativeAmount` exceeds the pull.
41
+ * @throws {InvalidCalldataOriginError} If `calldataOrigin` is empty, malformed or has an odd number of hex digits.
42
+ * @throws {MidnightTakeDeadlineTooFarError} If expiry is more than one hour away.
43
+ * @throws {InvalidTransactionPlanError} If `account` is malformed or the target type is neither assets nor units.
44
+ * @throws {ChainIdMismatchError} If the client, transport or market is on a different chain.
45
+ * @throws {UnsupportedChainIdError} If the chain is absent from the address registry.
46
+ * @throws {UnknownAddressError} If the chain has no `midnightBundlesV2` deployment.
47
+ * @throws {MidnightMarketAddressMismatchError} If the market targets another Midnight deployment.
48
+ * @throws {EmptyMidnightTakeableOffersError} If no offers are supplied.
49
+ * @throws {MidnightOfferSideMismatchError} If an offer is not borrow-side.
50
+ * @throws {MidnightTakeableOfferMarketMismatchError} If an offer trades a different market.
51
+ * @throws {MidnightTakeableOfferZeroSellerReceiverError} If an offer routes seller proceeds to the zero address.
52
+ * @throws {UnboundedMidnightTakeInputError} If `target.units` or `target.maxBuyerAssets` is `maxUint256`.
53
+ * @throws {ReferralFeeRecipientMissingError} If a positive referral fee has no recipient.
54
+ * @throws {MidnightContractReceiverError} If the referral fee recipient is a Midnight protocol or market token contract.
55
+ * @throws {InvalidMidnightNativeAmountTypeError} If `nativeAmount` is not a bigint.
56
+ * @throws {MidnightCalldataEncodingError} If an offer field, including a `maxUnits` or
57
+ * `maxAssets` cap that is not a bigint, cannot be ABI-encoded.
58
+ * @throws {ChainWNativeMissingError} If wNative is not configured for the chain.
59
+ * @throws {NativeAmountOnNonWNativeAssetError} If positive native input is used with another loan token.
60
+ * @throws {MidnightContinuousFeeAboveMaxError} If `maxContinuousFee` is below the market's continuous fee.
61
+ * @throws {MidnightTakeableOffersNotFillableError} If every offer is expired, not yet started,
62
+ * self-made, capped below the market fee or otherwise dead.
63
+ * @throws {MidnightTakeTargetUnreachableError} If the live offers cannot meet the target and its bounds.
64
+ * @throws {MissingContractCodeError} If either registered Midnight target has no deployed code.
65
+ * @throws {viem.BaseError} If an `eth_chainId` request or prerequisite read fails.
66
+ * @example
67
+ * ```ts
68
+ * import { buildTransactions, prepareMidnightTakeLend } from "@morpho-org/morpho-sdk";
69
+ * import { fetchMidnightMarket } from "@morpho-org/morpho-sdk/fetch";
70
+ * import { MidnightApi } from "@morpho-org/morpho-sdk/midnight-api";
71
+ * import { type Address, createPublicClient, type Hex, http, maxUint256 } from "viem";
72
+ * import { base } from "viem/chains";
73
+ *
74
+ * export async function takeLendTransactions(marketId: Hex, account: Address) {
75
+ * const client = createPublicClient({ chain: base, transport: http() });
76
+ * const marketData = await fetchMidnightMarket(client, { marketId });
77
+ * const quote = await new MidnightApi().fetchBookQuote({
78
+ * marketId, side: "asks", units: 1_000_000n, taker: account,
79
+ * });
80
+ * const plan = await prepareMidnightTakeLend(client, {
81
+ * chainId: base.id, account, marketData, takeableOffers: quote.data.takeableOffers,
82
+ * target: { type: "units", units: 1_000_000n, maxBuyerAssets: 990_000n },
83
+ * maxContinuousFee: maxUint256,
84
+ * });
85
+ * // Simulate, then send in order from plan.account on plan.chainId.
86
+ * return buildTransactions(plan);
87
+ * }
88
+ * ```
89
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
90
+ */
91
+ export declare function prepareMidnightTakeLend(client: Client, params: MidnightTakeLendPlanParams): Promise<TransactionPlan>;
92
+ type TakeLendAction = Extract<Action, {
93
+ type: "midnightTakeLend";
94
+ }>;
95
+ /** @internal Encodes the prepared lend from persisted inputs without state reads. */
96
+ export declare function buildMidnightTakeLend({ inputs: { chainId, market, target, takeableOffers, maxContinuousFee, deadline, referralFeePct, referralFeeRecipient, nativeAssets, }, }: TakeLendAction): Readonly<import("../../index.js").Transaction<import("../../index.js").MidnightTakeLendAction>>;
97
+ /** @internal Validates the restored recipe shape without encoding or fetching offers. */
98
+ export declare function validateMidnightTakeLendPlanAction(action: Record<string, unknown>, path: string): void;
99
+ export {};