@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,536 @@
1
+ import { MarketUtils as BlueMarketUtils, MathLib, UnsupportedMarketIrmError, } from "@morpho-org/blue-sdk";
2
+ import { fetchMarket as fetchBlueMarket } from "@morpho-org/blue-sdk-viem";
3
+ import { MarketParams, MarketUtils, Payload, PriceRatifierV1, RateRatifierV1, } from "@morpho-org/midnight-sdk";
4
+ import { _try, deepFreeze } from "@morpho-org/morpho-ts";
5
+ import { parseMidnightCancelAndMake } from "../../actions/midnight/cancelAndMake.js";
6
+ import { createChainCheck, } from "../../actions/requirements/chainCheck.js";
7
+ import { validateMidnightDeadline } from "../../entities/midnight/deadline.js";
8
+ import { validateMidnightMakerOfferCallbacks, validateMidnightMakerOfferStates, } from "../../entities/midnight/publication.js";
9
+ import { getMidnightBlueBuyCallbackAddress, getMidnightBlueBuyCallbackData, } from "../../helpers/callback.js";
10
+ import { encodeMidnightMarketId, wrapMidnightEncoding, } from "../../helpers/encodeMidnightCalldata.js";
11
+ import { validateChainId } from "../../helpers/index.js";
12
+ import { resolveTransactionMetadata } from "../../helpers/metadata.js";
13
+ import { parseNonnegative } from "../../helpers/parse.js";
14
+ import { parseMidnightAccount, parseMidnightNativeFunding, parseMidnightPositiveAmount, } from "../../helpers/parseMidnight.js";
15
+ import { parseMidnightMakerBinding, parseMidnightMakerFundingBinding, parseMidnightMakerIntent, parseMidnightMakerTree, validateMidnightMakerCancellations, } from "../../helpers/parseMidnightMaker.js";
16
+ import { validateMidnightAddress } from "../../helpers/validateMidnightAccount.js";
17
+ import { validateMidnightCollateralSupplies } from "../../helpers/validateMidnightCollateralSupplies.js";
18
+ import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
19
+ import { validateMidnightBytes32 } from "../../helpers/validateMidnightPublication.js";
20
+ import { validateOfferSides } from "../../helpers/validateOfferSides.js";
21
+ import { validatePositiveInput } from "../../helpers/validatePositiveInput.js";
22
+ import { EmptyBlueParkingMarketError, EmptyMidnightCollateralSuppliesError, ExpiredDeadlineError, InvalidBigIntInputError, MarketIdMismatchError, ZeroBlueParkingSharesError, } from "../../types/index.js";
23
+ import { getPlanObject, validatePlanField } from "../validation.js";
24
+ import { validateCollateralIndexTypes } from "./market.js";
25
+ import { fetchMidnightMakerOfferStatesBeforeDeadline } from "./publicationState.js";
26
+ const offersParams = Symbol();
27
+ const preparedMake = Symbol();
28
+ /**
29
+ * Validates the complete raw publication request before state reads, with the same checks in the
30
+ * same order as the entity maker flows, from a plain viem client.
31
+ * @param params - Maker account, offer tree and optional mempool validation settings.
32
+ * @param context - Plain viem client and the chain the offers are published on.
33
+ * @returns The frozen request that {@link getOffersDataInternal} reads state for.
34
+ * @throws {ChainIdMismatchError} when the client declares another chain than `context.chainId`.
35
+ * @throws {MidnightZeroAccountError} when `accountAddress` is the zero address.
36
+ * @throws {MidnightCalldataEncodingError} when `accountAddress` is malformed.
37
+ * @throws {MidnightOfferMakerMismatchError} when an offer names another maker.
38
+ * @throws {MidnightOfferRatifierMismatchError} when an offer names another ratifier than the tree's.
39
+ * @internal
40
+ */
41
+ export const parseGetOffersDataParams = (params, { client, chainId }) => {
42
+ validateChainId(client.chain?.id, chainId);
43
+ const accountAddress = parseMidnightAccount("accountAddress", params.accountAddress);
44
+ const tree = parseMidnightMakerTree({
45
+ offers: params.offers,
46
+ accountAddress,
47
+ });
48
+ const { ratifier, ratifierType } = parseMidnightMakerBinding({
49
+ tree,
50
+ chainId,
51
+ accountAddress,
52
+ });
53
+ return Object.freeze({
54
+ tree,
55
+ accountAddress,
56
+ ratifier,
57
+ ratifierType,
58
+ validation: params.validation,
59
+ [offersParams]: true,
60
+ });
61
+ };
62
+ /**
63
+ * Reads publication state only from the complete constructed request, using a plain viem client.
64
+ * Pass the caller's `chainCheck` to share one `eth_chainId` read per invocation. With a
65
+ * `bundleDeadline`, the block is pinned first and the deadline is checked against its timestamp
66
+ * before any contract read, and again against the validated state's timestamp after the offer checks.
67
+ * `validateFunding` receives the pinned block number and timestamp and runs after the pinned
68
+ * offer-state checks and before the optional mempool API call.
69
+ * A `rejectAfterPinnedChecks` error is thrown after the pinned offer-state and deadline checks,
70
+ * so no funding check, API call, ratification or encoding runs.
71
+ * @param params - Request built by {@link parseGetOffersDataParams}.
72
+ * @param context - Plain viem client, chain, market-creation clock, optional chain check, bundle deadline, funding check and post-pinned-check error.
73
+ * @returns Offer groups, tree, ratifier and encoded payload ready for publication.
74
+ * @throws {ChainIdMismatchError} when the client's RPC reports another chain.
75
+ * @throws {ExpiredDeadlineError} when `bundleDeadline` is at or before the pinned block timestamp while every offer is live,
76
+ * or `rejectAfterPinnedChecks` is set and the pinned checks pass.
77
+ * @throws {viem.BaseError} when a publication-state read fails.
78
+ * @internal
79
+ */
80
+ export const getOffersDataInternal = async (params, { client, chainId, marketCreationTime = "expiry", chainCheck = createChainCheck(client, chainId), bundleDeadline, validateFunding, rejectAfterPinnedChecks, }) => {
81
+ const { tree, accountAddress, ratifier, ratifierType } = params;
82
+ const { states, now, blockNumber } = await fetchMidnightMakerOfferStatesBeforeDeadline({ client, chainId, tree, bundleDeadline }, chainCheck);
83
+ validateMidnightMakerOfferStates({ tree, states, now, marketCreationTime });
84
+ if (bundleDeadline !== undefined && bundleDeadline <= now) {
85
+ throw new ExpiredDeadlineError(bundleDeadline, now);
86
+ }
87
+ if (rejectAfterPinnedChecks !== undefined) {
88
+ throw rejectAfterPinnedChecks;
89
+ }
90
+ // Funding state is checked before the optional mempool API call.
91
+ await validateFunding?.(blockNumber, now);
92
+ const groups = [];
93
+ const seenGroups = new Set();
94
+ for (const offer of tree.offers) {
95
+ const key = offer.group.toLowerCase();
96
+ if (!seenGroups.has(key)) {
97
+ seenGroups.add(key);
98
+ groups.push(offer.group);
99
+ }
100
+ }
101
+ if (params.validation !== false) {
102
+ await tree.mempoolValidate({ ...params.validation, chainId });
103
+ }
104
+ const items = tree.type === "priceV1"
105
+ ? PriceRatifierV1.ratify({ tree })
106
+ : RateRatifierV1.ratify({ tree });
107
+ return {
108
+ accountAddress,
109
+ groups,
110
+ tree,
111
+ ratifierType,
112
+ ratifier,
113
+ payload: await Payload.encode(items),
114
+ };
115
+ };
116
+ /**
117
+ * Copies caller cancellations after rejecting a non-array value or a non-object entry, holes
118
+ * included, with a typed error; an untyped JavaScript `null` is treated as omitted.
119
+ * @internal
120
+ */
121
+ function copyMakerCancellations(cancellations) {
122
+ validatePlanField(cancellations ?? [], {
123
+ path: "$.cancellations",
124
+ type: "array",
125
+ });
126
+ // Array.from visits holes too, so a sparse entry reaches the object check.
127
+ return Array.from(cancellations ?? [], (cancellation, index) => {
128
+ getPlanObject(cancellation, `$.cancellations[${index}]`);
129
+ return { group: cancellation.group, maxConsumed: cancellation.maxConsumed };
130
+ });
131
+ }
132
+ async function parseMakeParams({ params, operation, }, context) {
133
+ const { client, chainId, chainCheck, rejectAfterPinnedChecks } = context;
134
+ validateChainId(client.chain?.id, chainId);
135
+ const accountAddress = parseMidnightAccount("accountAddress", params.accountAddress);
136
+ // Preserve account and local expiry precedence before constructing the tree.
137
+ validateMidnightDeadline(params.deadline, params.now);
138
+ const lend = operation === "makeLend" || operation === "makeRepay";
139
+ const intent = parseMidnightMakerIntent({
140
+ offers: params.offers,
141
+ accountAddress,
142
+ side: lend ? "lend" : "borrow",
143
+ reduceOnly: operation === "makeRepay" || operation === "makeWithdraw",
144
+ });
145
+ const metadata = resolveTransactionMetadata(context.metadata, params.now);
146
+ let loanToken;
147
+ let approvalAmount = 0n;
148
+ if (operation === "makeLend" || operation === "makeRepay") {
149
+ loanToken = params.loanToken;
150
+ // Address and amounts precede opening-side and callback checks for lenders.
151
+ validateMidnightAddress("loanToken", loanToken);
152
+ if (typeof params.loanAssets !== "bigint") {
153
+ throw new InvalidBigIntInputError("loanAssets", params.loanAssets);
154
+ }
155
+ // Validation only; funding positivity precedes the reserved amount and opening side.
156
+ validatePositiveInput("loanAssets", params.loanAssets);
157
+ const reservedLoanAssets = params.reservedLoanAssets ?? 0n;
158
+ if (typeof reservedLoanAssets !== "bigint") {
159
+ throw new InvalidBigIntInputError("reservedLoanAssets", reservedLoanAssets);
160
+ }
161
+ approvalAmount =
162
+ params.loanAssets +
163
+ parseNonnegative("reservedLoanAssets", reservedLoanAssets);
164
+ }
165
+ if (!intent.reduceOnly) {
166
+ validateOfferSides(intent.tree.offers, lend);
167
+ }
168
+ validateMidnightMakerOfferCallbacks(intent.tree.offers);
169
+ const cancellations = copyMakerCancellations(params.cancellations);
170
+ validateMidnightMakerCancellations({ cancellations, tree: intent.tree });
171
+ const offersContext = { client, chainId };
172
+ const data = await getOffersDataInternal(parseGetOffersDataParams({ ...params, offers: intent.tree }, offersContext), {
173
+ ...offersContext,
174
+ chainCheck,
175
+ bundleDeadline: params.deadline,
176
+ rejectAfterPinnedChecks,
177
+ });
178
+ if (loanToken != null) {
179
+ // Funding relationships deliberately follow pinned publication state and API validation.
180
+ parseMidnightMakerFundingBinding({ tree: data.tree, loanToken });
181
+ }
182
+ const action = parseMidnightCancelAndMake({
183
+ chainId,
184
+ cancellations,
185
+ deadline: params.deadline,
186
+ metadata,
187
+ publication: {
188
+ ratifier: data.ratifier,
189
+ root: data.tree.root,
190
+ groups: data.groups,
191
+ payload: data.payload,
192
+ },
193
+ });
194
+ return Object.freeze({ action, data, loanToken, approvalAmount });
195
+ }
196
+ /**
197
+ * Constructs the complete lend publication and its loan-token allowance amount from raw params for
198
+ * a TransactionPlan, with the entity `makeLend` checks in the same order, except that malformed
199
+ * cancellations are rejected before any state read.
200
+ * @param params - Maker account, lend-side offer tree, loan token and assets, cancellations and deadline.
201
+ * @param context - Plain viem client, chain, analytics metadata and optional chain check.
202
+ * @returns The parsed bundle action, its publication data, the loan token and the approval amount.
203
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports, another chain.
204
+ * @throws {ExpiredDeadlineError} when `deadline` is at or before `now` or the pinned block timestamp.
205
+ * @throws {InvalidBigIntInputError} when `loanAssets` or `reservedLoanAssets` is not a bigint.
206
+ * @throws {NonPositiveInputError} when `loanAssets` is not positive.
207
+ * @throws {MidnightOfferSideMismatchError} when an offer is not lend-side.
208
+ * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
209
+ * @throws {DuplicateMidnightGroupCancellationError} when a group is cancelled more than once.
210
+ * @throws {MidnightReplacementGroupCancelledError} when a cancelled group is in the new tree.
211
+ * @throws {MidnightOfferMarketLoanTokenMismatchError} when an offer market lends another token.
212
+ * @throws {viem.BaseError} when a publication-state read fails.
213
+ * @internal
214
+ */
215
+ export const parseMakeLendParams = (params, context) => parseMakeParams({ params, operation: "makeLend" }, context).then((parsed) => Object.freeze({ ...parsed, [preparedMake]: "makeLend" }));
216
+ /**
217
+ * Constructs the complete reduce-only repayment publication and its loan-token allowance amount
218
+ * from raw params for a TransactionPlan, with the entity `makeRepay` checks in the same order,
219
+ * except that malformed cancellations are rejected before any state read.
220
+ * @param params - Maker account, reduce-only lend-side offer tree, loan token and assets, cancellations and deadline.
221
+ * @param context - Plain viem client, chain, analytics metadata and optional chain check.
222
+ * @returns The parsed bundle action, its publication data, the loan token and the approval amount.
223
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports, another chain.
224
+ * @throws {ExpiredDeadlineError} when `deadline` is at or before `now` or the pinned block timestamp.
225
+ * @throws {NonPositiveInputError} when `loanAssets` is not positive.
226
+ * @throws {MidnightOfferNotReduceOnlyError} when an offer is not reduce-only.
227
+ * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
228
+ * @throws {DuplicateMidnightGroupCancellationError} when a group is cancelled more than once.
229
+ * @throws {MidnightReplacementGroupCancelledError} when a cancelled group is in the new tree.
230
+ * @throws {MidnightOfferMarketLoanTokenMismatchError} when an offer market lends another token.
231
+ * @throws {viem.BaseError} when a publication-state read fails.
232
+ * @internal
233
+ */
234
+ export const parseMakeRepayParams = (params, context) => parseMakeParams({ params, operation: "makeRepay" }, context).then((parsed) => Object.freeze({ ...parsed, [preparedMake]: "makeRepay" }));
235
+ /**
236
+ * Constructs the complete borrow publication from raw params for a TransactionPlan, with the
237
+ * entity `makeBorrow` checks in the same order, except that malformed cancellations are rejected
238
+ * before any state read.
239
+ * @param params - Maker account, borrow-side offer tree, cancellations, deadline and validation.
240
+ * @param context - Plain viem client, chain, analytics metadata and optional chain check.
241
+ * @returns The parsed bundle action and the publication data it encodes.
242
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports, another chain.
243
+ * @throws {ExpiredDeadlineError} when `deadline` is at or before `now` or the pinned block timestamp.
244
+ * @throws {MidnightOfferSideMismatchError} when an offer is not borrow-side.
245
+ * @throws {InvalidTransactionPlanError} when a supplied non-null `cancellations` is not an array or has a non-object entry.
246
+ * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
247
+ * @throws {DuplicateMidnightGroupCancellationError} when a group is cancelled more than once.
248
+ * @throws {MidnightReplacementGroupCancelledError} when a cancelled group is in the new tree.
249
+ * @throws {viem.BaseError} when a publication-state read fails.
250
+ * @internal
251
+ */
252
+ export const parseMakeBorrowParams = (params, context) => parseMakeParams({ params, operation: "makeBorrow" }, context).then((parsed) => Object.freeze({ ...parsed, [preparedMake]: "makeBorrow" }));
253
+ /**
254
+ * Constructs the complete reduce-only credit-exit publication from raw params for a
255
+ * TransactionPlan, with the entity `makeWithdraw` checks in the same order, except that malformed
256
+ * cancellations are rejected before any state read.
257
+ * @param params - Maker account, reduce-only borrow-side offer tree, cancellations and deadline.
258
+ * @param context - Plain viem client, chain, analytics metadata and optional chain check.
259
+ * @returns The parsed bundle action and the publication data it encodes.
260
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports, another chain.
261
+ * @throws {ExpiredDeadlineError} when `deadline` is at or before `now` or the pinned block timestamp.
262
+ * @throws {MidnightOfferNotReduceOnlyError} when an offer is not reduce-only.
263
+ * @throws {InvalidTransactionPlanError} when a supplied non-null `cancellations` is not an array or
264
+ * has a non-object entry.
265
+ * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
266
+ * @throws {DuplicateMidnightGroupCancellationError} when a group is cancelled more than once.
267
+ * @throws {MidnightReplacementGroupCancelledError} when a cancelled group is in the new tree.
268
+ * @throws {viem.BaseError} when a publication-state read fails.
269
+ * @internal
270
+ */
271
+ export const parseMakeWithdrawParams = (params, context) => parseMakeParams({ params, operation: "makeWithdraw" }, context).then((parsed) => Object.freeze({ ...parsed, [preparedMake]: "makeWithdraw" }));
272
+ const validateCollateralAssetsTypes = (supplies) => {
273
+ for (const [index, { assets }] of supplies.entries()) {
274
+ if (typeof assets !== "bigint") {
275
+ throw new InvalidBigIntInputError(`collateral.supplies[${index}].assets`, assets);
276
+ }
277
+ }
278
+ };
279
+ /**
280
+ * Validates a collateral supply request without state and resolves the token each supply pulls,
281
+ * with the same checks in the same order as `validateMidnightCancelAndMakePublication`.
282
+ *
283
+ * @param params - Collateral market and supplies, and the chain the bundle runs on.
284
+ * @returns The token and amount pulled by each supply, in input order.
285
+ * @throws {EmptyMidnightCollateralSuppliesError} when collateral supplies are empty.
286
+ * @throws {UnsupportedChainIdError} when the chain is absent from the registry.
287
+ * @throws {ChainIdMismatchError} when the collateral market targets another chain.
288
+ * @throws {MidnightMarketAddressMismatchError} when its Midnight deployment differs.
289
+ * @throws {MidnightCalldataEncodingError} when the collateral market address is malformed.
290
+ * @throws {NonPositiveInputError} when a collateral supply is not positive.
291
+ * @throws {InputExceedsMaxError} when a supply or per-index total exceeds uint128.
292
+ * @throws {UnknownCollateralIndexError} when a supply index is not configured.
293
+ */
294
+ const parseMidnightCollateralPulls = ({ collateral, chainId, }) => {
295
+ if (collateral.supplies.length === 0) {
296
+ throw new EmptyMidnightCollateralSuppliesError();
297
+ }
298
+ validateMidnightMarket({ market: collateral.market, chainId });
299
+ // Validation only; checks supply entries and their per-index totals.
300
+ validateMidnightCollateralSupplies({
301
+ market: collateral.market,
302
+ field: "collateral.supplies",
303
+ supplies: collateral.supplies,
304
+ });
305
+ return collateral.supplies.map(({ collateralIndex, assets }) => ({
306
+ token: MarketUtils.getCollateralByIndex(collateral.market, collateralIndex)
307
+ .token,
308
+ assets,
309
+ }));
310
+ };
311
+ /**
312
+ * Constructs the complete collateral-funded borrow publication from raw params for a
313
+ * TransactionPlan, with the entity `supplyCollateralMakeBorrow` checks, except that the market,
314
+ * collateral and native funding checks run before any state read.
315
+ * @param params - Maker account, borrow-side offer tree, collateral supplies, native amount, cancellations and deadline.
316
+ * @param context - Plain viem client, chain, analytics metadata, optional chain check and post-pinned-check error.
317
+ * @returns The parsed bundle action, its publication data and the frozen collateral it supplies.
318
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports, another chain.
319
+ * @throws {ExpiredDeadlineError} when `deadline` is at or before `now` or the pinned block timestamp,
320
+ * or `rejectAfterPinnedChecks` is set and the pinned checks pass.
321
+ * @throws {MidnightOfferSideMismatchError} when an offer is not borrow-side.
322
+ * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
323
+ * @throws {DuplicateMidnightGroupCancellationError} when a group is cancelled more than once.
324
+ * @throws {MidnightReplacementGroupCancelledError} when a cancelled group is in the new tree.
325
+ * @throws {MarketIdMismatchError} when an offer targets another market than the collateral market.
326
+ * @throws {EmptyMidnightCollateralSuppliesError} when collateral supplies are empty.
327
+ * @throws {InvalidBigIntInputError} when a supply index or amount is not a bigint.
328
+ * @throws {UnknownCollateralIndexError} when a supply index is not configured.
329
+ * @throws {viem.BaseError} when a publication-state read fails.
330
+ * @internal
331
+ */
332
+ export const parseSupplyCollateralMakeBorrowParams = async (params, context) => {
333
+ const { client, chainId, chainCheck, rejectAfterPinnedChecks } = context;
334
+ const metadata = resolveTransactionMetadata(context.metadata, params.now);
335
+ validateChainId(client.chain?.id, chainId);
336
+ const accountAddress = parseMidnightAccount("accountAddress", params.accountAddress);
337
+ // Preserve local expiry before market/tree construction.
338
+ validateMidnightDeadline(params.deadline, params.now);
339
+ const market = params.collateral.market instanceof MarketParams
340
+ ? params.collateral.market
341
+ : MarketParams.from(params.collateral.market);
342
+ const tree = parseMidnightMakerTree({
343
+ offers: params.offers,
344
+ accountAddress,
345
+ });
346
+ // Borrow-side and callback guards precede reduce-only guards on this funded boundary.
347
+ validateOfferSides(tree.offers, false);
348
+ validateMidnightMakerOfferCallbacks(tree.offers);
349
+ const intent = parseMidnightMakerIntent({
350
+ offers: tree,
351
+ accountAddress,
352
+ side: "borrow",
353
+ reduceOnly: false,
354
+ });
355
+ const cancellations = copyMakerCancellations(params.cancellations);
356
+ validateMidnightMakerCancellations({ cancellations, tree: intent.tree });
357
+ const offersContext = { client, chainId };
358
+ // Offer bindings keep their place before the collateral market comparison.
359
+ const offersRequest = parseGetOffersDataParams({ ...params, offers: intent.tree }, offersContext);
360
+ // Market, collateral and native funding need no state, so they precede every network read.
361
+ const marketId = encodeMidnightMarketId(market);
362
+ for (const offer of intent.tree.offers) {
363
+ const offerMarketId = encodeMidnightMarketId(offer.market);
364
+ if (offerMarketId.toLowerCase() !== marketId.toLowerCase()) {
365
+ throw new MarketIdMismatchError(offerMarketId, marketId);
366
+ }
367
+ }
368
+ validateCollateralIndexTypes("collateral.supplies", params.collateral.supplies);
369
+ validateCollateralAssetsTypes(params.collateral.supplies);
370
+ const pulls = parseMidnightCollateralPulls({
371
+ collateral: { market, supplies: params.collateral.supplies },
372
+ chainId,
373
+ });
374
+ // The bundle uses this copy, so changes to the request during the reads cannot reach it.
375
+ const collateral = deepFreeze({
376
+ market: MarketUtils.toStruct(market),
377
+ supplies: params.collateral.supplies.map(({ collateralIndex, assets }) => ({
378
+ collateralIndex,
379
+ assets,
380
+ })),
381
+ });
382
+ const { nativeAmount } = params;
383
+ // Validation only; the bundle action resolves the same pulls and native coverage again.
384
+ parseMidnightNativeFunding({ chainId, nativeAmount, pulls });
385
+ const data = await getOffersDataInternal(offersRequest, {
386
+ ...offersContext,
387
+ marketCreationTime: "now",
388
+ chainCheck,
389
+ bundleDeadline: params.deadline,
390
+ rejectAfterPinnedChecks,
391
+ });
392
+ const action = parseMidnightCancelAndMake({
393
+ chainId,
394
+ nativeAmount,
395
+ cancellations,
396
+ deadline: params.deadline,
397
+ metadata,
398
+ publication: {
399
+ ratifier: data.ratifier,
400
+ root: data.tree.root,
401
+ groups: data.groups,
402
+ payload: data.payload,
403
+ collateral,
404
+ },
405
+ });
406
+ return Object.freeze({
407
+ action,
408
+ data,
409
+ collateral,
410
+ [preparedMake]: "supplyCollateralMakeBorrow",
411
+ });
412
+ };
413
+ /**
414
+ * Constructs the complete Blue-funded lend publication from raw params for a TransactionPlan. The
415
+ * input, tree, cancellation, deadline and binding checks run before the chain check, the
416
+ * publication-state reads and the Blue market read; payload encoding, which also checks market
417
+ * maturity, runs after them. The Blue market is read at the block the publication-state reads are pinned to,
418
+ * after their checks and before the optional mempool API call.
419
+ * @param params - Maker account, lend-side offer tree, Blue market, assets to park, callback salt, cancellations and deadline.
420
+ * @param context - Plain viem client, chain, analytics metadata, optional chain check and post-pinned-check error.
421
+ * @returns The parsed bundle action, its publication data, the loan token, the approval amount and the frozen Blue supply.
422
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports, another chain.
423
+ * @throws {InvalidMidnightHexInputError} when `callbackSalt` is not 32-byte hex.
424
+ * @throws {InvalidBigIntInputError} when `assetsToPark` or `blueMarket.lltv` is not a bigint.
425
+ * @throws {NonPositiveInputError} when `assetsToPark` is not positive.
426
+ * @throws {MidnightOfferSideMismatchError} when an offer is not lend-side.
427
+ * @throws {ExpiredDeadlineError} when `deadline` is at or before `now` or the pinned block timestamp,
428
+ * or `rejectAfterPinnedChecks` is set and the pinned offer checks pass, before the Blue market read.
429
+ * @throws {EmptyBlueParkingMarketError} when the Blue market has no supply shares at the pinned block.
430
+ * @throws {ZeroBlueParkingSharesError} when `assetsToPark` buys zero Blue supply shares.
431
+ * @throws {viem.BaseError} when a publication-state or Blue market read fails.
432
+ * @internal
433
+ */
434
+ export const parseSupplyBlueMakeLendParams = async (params, context) => {
435
+ const { client, chainId } = context;
436
+ const suppliedNow = params.now;
437
+ const metadata = resolveTransactionMetadata(context.metadata, suppliedNow);
438
+ validateChainId(client.chain?.id, chainId);
439
+ const accountAddress = parseMidnightAccount("accountAddress", params.accountAddress);
440
+ // Preserve salt and amount error context before constructing the tree.
441
+ validateMidnightBytes32("callbackSalt", params.callbackSalt);
442
+ if (typeof params.assetsToPark !== "bigint") {
443
+ throw new InvalidBigIntInputError("assetsToPark", params.assetsToPark);
444
+ }
445
+ const assets = parseMidnightPositiveAmount("assetsToPark", params.assetsToPark);
446
+ const { loanToken, collateralToken, oracle, irm, lltv } = params.blueMarket;
447
+ if (typeof lltv !== "bigint") {
448
+ throw new InvalidBigIntInputError("blueMarket.lltv", lltv);
449
+ }
450
+ const blueSupply = deepFreeze({
451
+ market: { loanToken, collateralToken, oracle, irm, lltv },
452
+ assets,
453
+ callbackSalt: params.callbackSalt,
454
+ });
455
+ const tree = parseMidnightMakerTree({
456
+ offers: params.offers,
457
+ accountAddress,
458
+ });
459
+ // Side errors precede reduce-only errors on this funded boundary.
460
+ validateOfferSides(tree.offers, true);
461
+ const intent = parseMidnightMakerIntent({
462
+ offers: tree,
463
+ accountAddress,
464
+ side: "lend",
465
+ reduceOnly: false,
466
+ });
467
+ const cancellations = copyMakerCancellations(params.cancellations);
468
+ validateMidnightMakerCancellations({ cancellations, tree: intent.tree });
469
+ validateMidnightDeadline(params.deadline, suppliedNow);
470
+ const { callbackSalt, market: blueMarket, assets: assetsToPark } = blueSupply;
471
+ const callbackData = wrapMidnightEncoding("blueMarket", () => getMidnightBlueBuyCallbackData(blueMarket));
472
+ const blueMarketId = BlueMarketUtils.getMarketId(blueMarket);
473
+ const callback = getMidnightBlueBuyCallbackAddress({
474
+ chainId,
475
+ owner: accountAddress,
476
+ salt: callbackSalt,
477
+ });
478
+ parseMidnightMakerFundingBinding({
479
+ tree: intent.tree,
480
+ loanToken: blueMarket.loanToken,
481
+ callback: { address: callback, data: callbackData },
482
+ });
483
+ // Validation only; the bundle action resolves the same native coverage again.
484
+ parseMidnightNativeFunding({
485
+ chainId,
486
+ nativeAmount: params.nativeAmount,
487
+ pulls: [{ token: blueMarket.loanToken, assets: assetsToPark }],
488
+ });
489
+ const offersRequest = parseGetOffersDataParams({ ...params, offers: intent.tree }, { client, chainId });
490
+ const chainCheck = context.chainCheck ?? createChainCheck(client, chainId);
491
+ await chainCheck();
492
+ const data = await getOffersDataInternal(offersRequest, {
493
+ client,
494
+ chainId,
495
+ chainCheck,
496
+ bundleDeadline: params.deadline,
497
+ rejectAfterPinnedChecks: context.rejectAfterPinnedChecks,
498
+ validateFunding: async (blockNumber, timestamp) => {
499
+ const fetched = await fetchBlueMarket(blueMarketId, client, {
500
+ blockNumber,
501
+ });
502
+ const market = _try(() => fetched.accrueInterest(MathLib.max(timestamp, fetched.lastUpdate)), UnsupportedMarketIrmError) ?? fetched;
503
+ if (market.totalSupplyShares === 0n) {
504
+ throw new EmptyBlueParkingMarketError({ marketId: blueMarketId });
505
+ }
506
+ if (market.toSupplyShares(assetsToPark, "Down") === 0n) {
507
+ throw new ZeroBlueParkingSharesError({
508
+ marketId: blueMarketId,
509
+ assets: assetsToPark,
510
+ });
511
+ }
512
+ },
513
+ });
514
+ const action = parseMidnightCancelAndMake({
515
+ chainId,
516
+ publication: {
517
+ ratifier: data.ratifier,
518
+ root: data.tree.root,
519
+ groups: data.groups,
520
+ payload: data.payload,
521
+ blueSupply: { market: blueMarket, assets: assetsToPark, callbackSalt },
522
+ },
523
+ nativeAmount: params.nativeAmount,
524
+ cancellations,
525
+ deadline: params.deadline,
526
+ metadata,
527
+ });
528
+ return Object.freeze({
529
+ action,
530
+ data,
531
+ loanToken: blueMarket.loanToken,
532
+ approvalAmount: assetsToPark,
533
+ blueSupply,
534
+ [preparedMake]: "supplyBlueMakeLend",
535
+ });
536
+ };
@@ -0,0 +1,24 @@
1
+ import type { Tree } from "@morpho-org/midnight-sdk";
2
+ import { type Client } from "viem";
3
+ import type { ChainCheck } from "../../actions/requirements/chainCheck.js";
4
+ import { fetchMidnightMakerOfferStatesWithChainCheck } from "../../entities/midnight/publication.js";
5
+ /**
6
+ * Reads maker publication state for a TransactionPlan at a block it pins first, and returns that
7
+ * block so later reads can use it. With a `bundleDeadline`, it rejects the deadline against the
8
+ * pinned block's timestamp before any contract read.
9
+ * @param params - Client, chain, maker tree and optional bundle deadline.
10
+ * @param chainCheck - The invocation's chain check, run before the first read.
11
+ * @returns Per-offer states plus the timestamp and number of the pinned block.
12
+ * @throws {ChainIdMismatchError} when the client's RPC reports another chain.
13
+ * @throws {ExpiredDeadlineError} when `bundleDeadline` is at or before the pinned block timestamp while every offer is live.
14
+ * @throws {viem.BaseError} when block, contract, or oracle-code reads fail.
15
+ * @internal
16
+ */
17
+ export declare function fetchMidnightMakerOfferStatesBeforeDeadline(params: {
18
+ readonly client: Client;
19
+ readonly chainId: number;
20
+ readonly tree: Tree<"priceV1"> | Tree<"rateV1">;
21
+ readonly bundleDeadline?: bigint;
22
+ }, chainCheck: ChainCheck): Promise<Awaited<ReturnType<typeof fetchMidnightMakerOfferStatesWithChainCheck>> & {
23
+ readonly blockNumber: bigint;
24
+ }>;
@@ -0,0 +1,47 @@
1
+ import { numberToHex, } from "viem";
2
+ import { getBlock, getBlockNumber } from "viem/actions";
3
+ import { fetchMidnightMakerOfferStatesWithChainCheck } from "../../entities/midnight/publication.js";
4
+ import { ExpiredDeadlineError } from "../../types/index.js";
5
+ /**
6
+ * Reads maker publication state for a TransactionPlan at a block it pins first, and returns that
7
+ * block so later reads can use it. With a `bundleDeadline`, it rejects the deadline against the
8
+ * pinned block's timestamp before any contract read.
9
+ * @param params - Client, chain, maker tree and optional bundle deadline.
10
+ * @param chainCheck - The invocation's chain check, run before the first read.
11
+ * @returns Per-offer states plus the timestamp and number of the pinned block.
12
+ * @throws {ChainIdMismatchError} when the client's RPC reports another chain.
13
+ * @throws {ExpiredDeadlineError} when `bundleDeadline` is at or before the pinned block timestamp while every offer is live.
14
+ * @throws {viem.BaseError} when block, contract, or oracle-code reads fail.
15
+ * @internal
16
+ */
17
+ export async function fetchMidnightMakerOfferStatesBeforeDeadline(params, chainCheck) {
18
+ const { client, chainId, tree, bundleDeadline } = params;
19
+ await chainCheck();
20
+ const blockNumber = await getBlockNumber(client);
21
+ const pinnedBlock = numberToHex(blockNumber);
22
+ let header;
23
+ const forward = client.request;
24
+ const request = async (args, options) => {
25
+ if (args.method !== "eth_getBlockByNumber" ||
26
+ !Array.isArray(args.params) ||
27
+ args.params[0] !== pinnedBlock) {
28
+ return forward(args, options);
29
+ }
30
+ header ??= { value: await forward(args, options) };
31
+ return header.value;
32
+ };
33
+ const pinnedClient = {
34
+ ...client,
35
+ request: request,
36
+ };
37
+ if (bundleDeadline !== undefined) {
38
+ const { timestamp } = await getBlock(pinnedClient, { blockNumber });
39
+ // Let offer validation keep its typed error when an offer has already expired.
40
+ if (bundleDeadline <= timestamp &&
41
+ tree.offers.every(({ expiry }) => expiry > timestamp)) {
42
+ throw new ExpiredDeadlineError(bundleDeadline, timestamp);
43
+ }
44
+ }
45
+ const { states, now } = await fetchMidnightMakerOfferStatesWithChainCheck({ client: pinnedClient, chainId, tree, blockNumber }, chainCheck);
46
+ return { states, now, blockNumber };
47
+ }