@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,55 @@
1
+ import { type Client, type Hex } from "viem";
2
+ import { type ParsedMidnightCancelAndMake } from "../../actions/midnight/cancelAndMake.js";
3
+ import type { GetOffersDataParams, MakeOffersParams, OffersData } from "../../entities/midnight/types.js";
4
+ import { type IntentParams } from "../intent.js";
5
+ import type { Action } from "../types.js";
6
+ import type { MakerParamsContext } from "./prepare.js";
7
+ type MakerPublicationAction = Extract<Action, {
8
+ type: "midnightMakeBorrow" | "midnightMakeLend" | "midnightMakeRepay" | "midnightMakeWithdraw" | "midnightSupplyCollateralMakeBorrow" | "midnightSupplyBlueMakeLend";
9
+ }>;
10
+ type CollateralFunding = Pick<Extract<Action, {
11
+ type: "midnightSupplyCollateralMakeBorrow";
12
+ }>["inputs"], "collateral" | "nativeAssets">;
13
+ type BlueFunding = Pick<Extract<Action, {
14
+ type: "midnightSupplyBlueMakeLend";
15
+ }>["inputs"], "blueSupply" | "nativeAssets">;
16
+ type MidnightMakerPublicationInputs = Omit<MakerPublicationAction["inputs"], keyof CollateralFunding | keyof BlueFunding>;
17
+ /**
18
+ * Inputs shared by every resting Midnight maker publication plan.
19
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
20
+ */
21
+ export interface MidnightMakerPublicationPlanParams extends Pick<IntentParams, "chainId" | "account" | "calldataOrigin">, Pick<GetOffersDataParams, "offers" | "validation"> {
22
+ /** Optional groups to cancel atomically with publication; must not overlap the new tree. */
23
+ readonly cancellations?: MakerPublicationAction["inputs"]["cancellations"];
24
+ /** Unix seconds, strictly before every offer expiry. Defaults to the earlier of now + 2 hours and the earliest offer expiry minus one second. */
25
+ readonly expiresAt?: number;
26
+ /** Reference time in Unix seconds for plan expiry; defaults to the device clock. */
27
+ readonly now?: bigint;
28
+ }
29
+ /**
30
+ * @internal Resolves the plan intent and offer-capped deadline, then runs the operation's maker
31
+ * parse constructor with a chain check that also checks bundle, Midnight and ratifier code once,
32
+ * right before the first publication-state read, plus any operation-specific `codeRoles`. The
33
+ * constructor also rejects a deadline at or before the pinned block timestamp while every offer
34
+ * is live.
35
+ */
36
+ export declare function prepareMidnightMakerPublication<Parsed extends {
37
+ readonly action: ParsedMidnightCancelAndMake;
38
+ readonly data: OffersData;
39
+ }>(client: Client, { params, parse, codeRoles, }: {
40
+ readonly params: MidnightMakerPublicationPlanParams;
41
+ readonly codeRoles?: readonly ("blue" | "midnightBlueBuyCallbackFactory")[];
42
+ readonly parse: (raw: MakeOffersParams, context: MakerParamsContext) => Promise<Parsed>;
43
+ }): Promise<{
44
+ readonly parsed: Parsed;
45
+ readonly inputs: MidnightMakerPublicationInputs;
46
+ readonly calldataOrigin: Hex | undefined;
47
+ }>;
48
+ /** @internal Encodes a maker recipe's publication, cancellations and optional collateral or Blue funding. */
49
+ export declare function buildMidnightMakerPublication(action: MakerPublicationAction): Readonly<import("../../index.js").Transaction<import("../../index.js").MidnightCancelAndMakeAction>>;
50
+ /**
51
+ * @internal Checks stored publication shape and ABI bounds, not the authenticity of offer bytes.
52
+ * Every maker publication type shares this recipe, so the action type is not bound to the payload.
53
+ */
54
+ export declare function validateMidnightMakerPublicationPlanAction(action: Record<string, unknown>, path: string): void;
55
+ export {};
@@ -0,0 +1,310 @@
1
+ import { getChainAddress, MathLib, Time } from "@morpho-org/morpho-ts";
2
+ import { isAddressEqual } from "viem";
3
+ import { parseMidnightCancelAndMake, } from "../../actions/midnight/cancelAndMake.js";
4
+ import { encodeMidnightCancelAndMake } from "../../actions/midnight/encode.js";
5
+ import { createChainCheck, } from "../../actions/requirements/chainCheck.js";
6
+ import { assertRegistryTargetsHaveCode } from "../../entities/requirements/assertContractCode.js";
7
+ import { parseMidnightMakerTree } from "../../helpers/parseMidnightMaker.js";
8
+ import { validateReferenceTime } from "../../helpers/validate.js";
9
+ import { validateMidnightAccount } from "../../helpers/validateMidnightAccount.js";
10
+ import { ExpiredDeadlineError, InputExceedsMaxError, UnsupportedMidnightAuthorizationTargetError, } from "../../types/error.js";
11
+ import { InvalidTransactionPlanError } from "../error.js";
12
+ import { resolveIntent } from "../intent.js";
13
+ import { getPlanObject, validatePlanField, validatePlanFields, } from "../validation.js";
14
+ import { validateSignaturelessMidnightAction } from "./authorization.js";
15
+ import { storedMarketTuple, validateStoredCollateralOrder } from "./market.js";
16
+ import { validateStoredMidnightMarket } from "./validation.js";
17
+ const publicationKinds = {
18
+ midnightMakeBorrow: "borrow",
19
+ midnightMakeLend: "lend",
20
+ midnightMakeRepay: "repay",
21
+ midnightMakeWithdraw: "withdraw",
22
+ midnightSupplyCollateralMakeBorrow: "collateral-backed borrow",
23
+ midnightSupplyBlueMakeLend: "Blue-backed lend",
24
+ };
25
+ const ratifierRoles = {
26
+ priceV1: "priceRatifierV1",
27
+ rateV1: "rateRatifierV1",
28
+ };
29
+ /**
30
+ * @internal Resolves the plan intent and offer-capped deadline, then runs the operation's maker
31
+ * parse constructor with a chain check that also checks bundle, Midnight and ratifier code once,
32
+ * right before the first publication-state read, plus any operation-specific `codeRoles`. The
33
+ * constructor also rejects a deadline at or before the pinned block timestamp while every offer
34
+ * is live.
35
+ */
36
+ export async function prepareMidnightMakerPublication(client, { params, parse, codeRoles = [], }) {
37
+ const { chainId, account } = params;
38
+ const now = params.now ?? Time.timestamp();
39
+ validateReferenceTime(now);
40
+ const intent = resolveIntent({
41
+ account,
42
+ chainId,
43
+ expiresAt: params.expiresAt,
44
+ calldataOrigin: params.calldataOrigin,
45
+ }, now);
46
+ const tree = parseMidnightMakerTree({
47
+ offers: params.offers,
48
+ accountAddress: account,
49
+ });
50
+ // Conservative SDK cutoff: the core still fills an offer at its expiry second.
51
+ const offerDeadline = tree.offers.reduce((earliest, offer) => MathLib.min(earliest, offer.expiry - 1n), intent.deadline);
52
+ // An offer expired at the reference time is reported by the pinned offer-state check, as in the entity.
53
+ const offerExpired = offerDeadline < now;
54
+ const deadline = offerExpired ? intent.deadline : offerDeadline;
55
+ if (params.expiresAt !== undefined && deadline < intent.deadline) {
56
+ throw new InputExceedsMaxError({
57
+ field: "expiresAt",
58
+ value: intent.deadline,
59
+ max: deadline,
60
+ });
61
+ }
62
+ const chainCheck = createChainCheck(client, chainId);
63
+ let preflightPassed = false;
64
+ const checkChainAndCode = async () => {
65
+ if (preflightPassed) {
66
+ return;
67
+ }
68
+ await chainCheck();
69
+ await assertRegistryTargetsHaveCode(client, chainId, [
70
+ "midnightBundlesV2",
71
+ "midnight",
72
+ ratifierRoles[tree.type],
73
+ ...codeRoles,
74
+ ].map((role) => ({ role, address: getChainAddress(chainId, role) })), chainCheck);
75
+ preflightPassed = true;
76
+ };
77
+ const parsed = await parse({
78
+ accountAddress: account,
79
+ offers: tree,
80
+ cancellations: params.cancellations,
81
+ deadline,
82
+ now,
83
+ validation: params.validation,
84
+ }, {
85
+ client,
86
+ chainId,
87
+ chainCheck: checkChainAndCode,
88
+ // No plan can be returned for an expired offer, so stop once the pinned check passes.
89
+ ...(offerExpired && {
90
+ rejectAfterPinnedChecks: new ExpiredDeadlineError(offerDeadline, now),
91
+ }),
92
+ });
93
+ const { action, data } = parsed;
94
+ return {
95
+ parsed,
96
+ inputs: {
97
+ chainId,
98
+ account,
99
+ deadline: action.deadline,
100
+ cancellations: action.cancellations.map(({ group, maxConsumed }) => ({
101
+ group,
102
+ maxConsumed,
103
+ })),
104
+ root: data.tree.root,
105
+ ratifierType: data.ratifierType,
106
+ ratifier: data.ratifier,
107
+ groups: [...data.groups],
108
+ payload: data.payload,
109
+ },
110
+ calldataOrigin: intent.calldataOrigin,
111
+ };
112
+ }
113
+ function parseStoredMidnightMakerPublication({ type, inputs, }) {
114
+ const { chainId, account, deadline, ratifierType, ratifier, root, groups, payload, } = inputs;
115
+ validateMidnightAccount("accountAddress", account);
116
+ if (ratifierType !== "priceV1" && ratifierType !== "rateV1") {
117
+ throw new InvalidTransactionPlanError({
118
+ path: "inputs.ratifierType",
119
+ reason: "expected priceV1 or rateV1",
120
+ });
121
+ }
122
+ const registered = getChainAddress(chainId, ratifierRoles[ratifierType]);
123
+ if (!isAddressEqual(ratifier, registered)) {
124
+ throw new UnsupportedMidnightAuthorizationTargetError({
125
+ authorized: ratifier,
126
+ chainId,
127
+ supportedTargets: [registered],
128
+ });
129
+ }
130
+ const cancellations = inputs.cancellations.map(({ group, maxConsumed }) => ({
131
+ group,
132
+ maxConsumed,
133
+ }));
134
+ const publication = { ratifier, root, groups, payload };
135
+ if (type === "midnightSupplyCollateralMakeBorrow") {
136
+ const { collateral } = inputs;
137
+ if (collateral == null) {
138
+ throw missingFunding("collateral");
139
+ }
140
+ return parseMidnightCancelAndMake({
141
+ chainId,
142
+ deadline,
143
+ nativeAmount: inputs.nativeAssets,
144
+ cancellations,
145
+ publication: {
146
+ ...publication,
147
+ collateral: {
148
+ market: storedMarketTuple(collateral.market),
149
+ supplies: collateral.supplies.map(({ collateralIndex, assets }) => ({
150
+ collateralIndex,
151
+ assets,
152
+ })),
153
+ },
154
+ },
155
+ });
156
+ }
157
+ if (type === "midnightSupplyBlueMakeLend") {
158
+ const { blueSupply } = inputs;
159
+ if (blueSupply == null) {
160
+ throw missingFunding("blueSupply");
161
+ }
162
+ const { loanToken, collateralToken, oracle, irm, lltv } = blueSupply.market;
163
+ return parseMidnightCancelAndMake({
164
+ chainId,
165
+ deadline,
166
+ nativeAmount: inputs.nativeAssets,
167
+ cancellations,
168
+ publication: {
169
+ ...publication,
170
+ blueSupply: {
171
+ market: { loanToken, collateralToken, oracle, irm, lltv },
172
+ assets: blueSupply.assets,
173
+ callbackSalt: blueSupply.callbackSalt,
174
+ },
175
+ },
176
+ });
177
+ }
178
+ return parseMidnightCancelAndMake({
179
+ chainId,
180
+ deadline,
181
+ cancellations,
182
+ publication,
183
+ });
184
+ }
185
+ function missingFunding(field) {
186
+ return new InvalidTransactionPlanError({
187
+ path: `inputs.${field}`,
188
+ reason: "expected funding for the maker publication",
189
+ });
190
+ }
191
+ /** @internal Encodes a maker recipe's publication, cancellations and optional collateral or Blue funding. */
192
+ export function buildMidnightMakerPublication(action) {
193
+ if (action.type === "midnightSupplyCollateralMakeBorrow" &&
194
+ action.inputs.collateral != null) {
195
+ validateStoredCollateralOrder(action.inputs.collateral.market.collateralParams, "$.inputs.collateral.market.collateralParams");
196
+ }
197
+ return encodeMidnightCancelAndMake(parseStoredMidnightMakerPublication(action));
198
+ }
199
+ /**
200
+ * @internal Checks stored publication shape and ABI bounds, not the authenticity of offer bytes.
201
+ * Every maker publication type shares this recipe, so the action type is not bound to the payload.
202
+ */
203
+ export function validateMidnightMakerPublicationPlanAction(action, path) {
204
+ validateSignaturelessMidnightAction(action, path);
205
+ const inputPath = `${path}.inputs`;
206
+ const inputs = getPlanObject(action.inputs, inputPath);
207
+ validatePlanFields(inputs, {
208
+ path: inputPath,
209
+ fields: {
210
+ ratifier: "address",
211
+ root: "bytes32",
212
+ groups: "array",
213
+ payload: "hex",
214
+ cancellations: "array",
215
+ deadline: "uint256 bigint",
216
+ },
217
+ });
218
+ if (inputs.ratifierType !== "priceV1" && inputs.ratifierType !== "rateV1") {
219
+ throw new InvalidTransactionPlanError({
220
+ path: `${inputPath}.ratifierType`,
221
+ reason: "expected priceV1 or rateV1",
222
+ });
223
+ }
224
+ for (const [index, group] of inputs.groups.entries()) {
225
+ validatePlanField(group, {
226
+ path: `${inputPath}.groups[${index}]`,
227
+ type: "bytes32",
228
+ });
229
+ }
230
+ for (const [index, value] of inputs.cancellations.entries()) {
231
+ const cancellationPath = `${inputPath}.cancellations[${index}]`;
232
+ validatePlanFields(getPlanObject(value, cancellationPath), {
233
+ path: cancellationPath,
234
+ fields: { group: "bytes32", maxConsumed: "uint128 bigint" },
235
+ });
236
+ }
237
+ const publication = action;
238
+ // Validate only the persisted funding values that feed the parse constructor.
239
+ if (publication.type === "midnightSupplyCollateralMakeBorrow") {
240
+ validateStoredCollateralFunding(inputs, inputPath);
241
+ }
242
+ if (publication.type === "midnightSupplyBlueMakeLend") {
243
+ validateStoredBlueFunding(inputs, inputPath);
244
+ }
245
+ try {
246
+ // Reuse the action's clock-free parse checks; do not reconstruct the tree.
247
+ parseStoredMidnightMakerPublication(publication);
248
+ }
249
+ catch (cause) {
250
+ throw new InvalidTransactionPlanError({
251
+ path: inputPath,
252
+ reason: `expected a valid Midnight ${publicationKinds[publication.type]} publication`,
253
+ cause,
254
+ });
255
+ }
256
+ }
257
+ function validateStoredNativeAssets(inputs, inputPath) {
258
+ if (inputs.nativeAssets !== undefined) {
259
+ validatePlanField(inputs.nativeAssets, {
260
+ path: `${inputPath}.nativeAssets`,
261
+ type: "uint256 bigint",
262
+ });
263
+ }
264
+ }
265
+ function validateStoredBlueFunding(inputs, inputPath) {
266
+ validateStoredNativeAssets(inputs, inputPath);
267
+ const path = `${inputPath}.blueSupply`;
268
+ const supply = getPlanObject(inputs.blueSupply, path);
269
+ validatePlanFields(supply, {
270
+ path,
271
+ fields: { assets: "uint128 bigint", callbackSalt: "bytes32" },
272
+ });
273
+ const marketPath = `${path}.market`;
274
+ validatePlanFields(getPlanObject(supply.market, marketPath), {
275
+ path: marketPath,
276
+ fields: {
277
+ loanToken: "address",
278
+ collateralToken: "address",
279
+ oracle: "address",
280
+ irm: "address",
281
+ lltv: "uint256 bigint",
282
+ },
283
+ });
284
+ }
285
+ function validateStoredCollateralFunding(inputs, inputPath) {
286
+ validateStoredNativeAssets(inputs, inputPath);
287
+ const path = `${inputPath}.collateral`;
288
+ const collateral = getPlanObject(inputs.collateral, path);
289
+ const marketPath = `${path}.market`;
290
+ // Validate the market tuple before checking the order of its indexed tokens.
291
+ validateStoredMidnightMarket(collateral.market, {
292
+ path: marketPath,
293
+ chainId: inputs.chainId,
294
+ });
295
+ const { market } = collateral;
296
+ validateStoredCollateralOrder(market.collateralParams, `${marketPath}.collateralParams`);
297
+ if (!Array.isArray(collateral.supplies)) {
298
+ throw new InvalidTransactionPlanError({
299
+ path: `${path}.supplies`,
300
+ reason: "expected an array",
301
+ });
302
+ }
303
+ for (const [index, supply] of collateral.supplies.entries()) {
304
+ const supplyPath = `${path}.supplies[${index}]`;
305
+ validatePlanFields(getPlanObject(supply, supplyPath), {
306
+ path: supplyPath,
307
+ fields: { collateralIndex: "uint256 bigint", assets: "uint128 bigint" },
308
+ });
309
+ }
310
+ }
@@ -0,0 +1,49 @@
1
+ import { type OfferStruct } from "@morpho-org/midnight-sdk";
2
+ import type { MidnightTakeableOffer } from "../../actions/midnight/types.js";
3
+ import type { MidnightCollateralTransfer } from "../../types/index.js";
4
+ /** @internal Projects a stored market and its collaterals onto the fields consumed by Midnight. */
5
+ export declare function storedMarketTuple({ chainId, midnight, loanToken, collateralParams, maturity, rcfThreshold, enterGate, liquidatorGate, }: OfferStruct["market"]): OfferStruct["market"];
6
+ /**
7
+ * @internal Rejects collateral that is not in strictly ascending token order. Midnight sorts the
8
+ * market's collateral, so a stored `collateralIndex` names the token it shows only in that order.
9
+ */
10
+ export declare function validateStoredCollateralOrder(collateralParams: OfferStruct["market"]["collateralParams"], path: string): void;
11
+ /** @internal Projects quote fills onto the fields consumed by Midnight. */
12
+ export declare function storedFills(takeableOffers: readonly MidnightTakeableOffer[]): {
13
+ units: bigint;
14
+ offer: {
15
+ market: import("@morpho-org/midnight-sdk").MarketParams;
16
+ buy: boolean;
17
+ maker: `0x${string}`;
18
+ start: bigint;
19
+ expiry: bigint;
20
+ tick: bigint;
21
+ group: `0x${string}`;
22
+ callback: `0x${string}`;
23
+ callbackData: `0x${string}`;
24
+ receiverIfMakerIsSeller: `0x${string}`;
25
+ ratifier: `0x${string}`;
26
+ reduceOnly: boolean;
27
+ maxUnits: bigint;
28
+ maxAssets: bigint;
29
+ continuousFeeCap: bigint;
30
+ };
31
+ ratifierData: `0x${string}`;
32
+ }[];
33
+ /**
34
+ * Rejects a supplied collateral price that is not a bigint before the health check converts it.
35
+ * Missing entries stay allowed: only the health check knows which prices it needs. @internal
36
+ */
37
+ export declare function validateCollateralPriceTypes(prices: readonly bigint[]): void;
38
+ /**
39
+ * @internal Rejects a collateral index that is not a bigint. Midnight's index lookup accepts a
40
+ * number, but a stored plan must hold a bigint to be restored.
41
+ */
42
+ export declare function validateCollateralIndexTypes(field: string, entries: readonly {
43
+ readonly collateralIndex: bigint;
44
+ }[]): void;
45
+ /**
46
+ * @internal Rejects collateral transfer inputs a parse constructor cannot read with a typed error:
47
+ * a list that is not an array, an entry that is not an object, or a non-bigint index or amount.
48
+ */
49
+ export declare function validateCollateralTransferInputs(field: string, entries: readonly MidnightCollateralTransfer[]): void;
@@ -0,0 +1,112 @@
1
+ import { MarketUtils } from "@morpho-org/midnight-sdk";
2
+ import { InvalidBigIntInputError } from "../../types/error.js";
3
+ import { InvalidTransactionPlanError } from "../error.js";
4
+ import { getPlanObject } from "../validation.js";
5
+ /** @internal Projects a stored market and its collaterals onto the fields consumed by Midnight. */
6
+ export function storedMarketTuple({ chainId, midnight, loanToken, collateralParams, maturity, rcfThreshold, enterGate, liquidatorGate, }) {
7
+ return {
8
+ chainId,
9
+ midnight,
10
+ loanToken,
11
+ collateralParams: collateralParams.map(({ token, lltv, liquidationCursor, oracle }) => ({
12
+ token,
13
+ lltv,
14
+ liquidationCursor,
15
+ oracle,
16
+ })),
17
+ maturity,
18
+ rcfThreshold,
19
+ enterGate,
20
+ liquidatorGate,
21
+ };
22
+ }
23
+ /**
24
+ * @internal Rejects collateral that is not in strictly ascending token order. Midnight sorts the
25
+ * market's collateral, so a stored `collateralIndex` names the token it shows only in that order.
26
+ */
27
+ export function validateStoredCollateralOrder(collateralParams, path) {
28
+ for (const [index, collateral] of collateralParams.entries()) {
29
+ const previous = collateralParams[index - 1];
30
+ if (previous &&
31
+ MarketUtils.compareCollateralTokens(previous, collateral) >= 0) {
32
+ throw new InvalidTransactionPlanError({
33
+ path,
34
+ reason: "expected collateral tokens in strictly ascending address order",
35
+ });
36
+ }
37
+ }
38
+ }
39
+ /** @internal Projects quote fills onto the fields consumed by Midnight. */
40
+ export function storedFills(takeableOffers) {
41
+ return takeableOffers.map(({ units, offer, ratifierData }) => ({
42
+ units,
43
+ offer: {
44
+ market: storedMarketTuple(offer.market),
45
+ buy: offer.buy,
46
+ maker: offer.maker,
47
+ start: offer.start,
48
+ expiry: offer.expiry,
49
+ tick: offer.tick,
50
+ group: offer.group,
51
+ callback: offer.callback,
52
+ callbackData: offer.callbackData,
53
+ receiverIfMakerIsSeller: offer.receiverIfMakerIsSeller,
54
+ ratifier: offer.ratifier,
55
+ reduceOnly: offer.reduceOnly,
56
+ maxUnits: offer.maxUnits,
57
+ maxAssets: offer.maxAssets,
58
+ continuousFeeCap: offer.continuousFeeCap,
59
+ },
60
+ ratifierData,
61
+ }));
62
+ }
63
+ /**
64
+ * Rejects a supplied collateral price that is not a bigint before the health check converts it.
65
+ * Missing entries stay allowed: only the health check knows which prices it needs. @internal
66
+ */
67
+ export function validateCollateralPriceTypes(prices) {
68
+ if (!Array.isArray(prices)) {
69
+ throw new InvalidTransactionPlanError({
70
+ path: "$.collateralPrices",
71
+ reason: "expected an array",
72
+ });
73
+ }
74
+ for (const [index, price] of prices.entries()) {
75
+ if (price !== undefined && typeof price !== "bigint") {
76
+ throw new InvalidBigIntInputError(`collateralPrices[${index}]`, price);
77
+ }
78
+ }
79
+ }
80
+ /**
81
+ * @internal Rejects a collateral index that is not a bigint. Midnight's index lookup accepts a
82
+ * number, but a stored plan must hold a bigint to be restored.
83
+ */
84
+ export function validateCollateralIndexTypes(field, entries) {
85
+ for (const [index, { collateralIndex }] of entries.entries()) {
86
+ if (typeof collateralIndex !== "bigint") {
87
+ throw new InvalidBigIntInputError(`${field}[${index}].collateralIndex`, collateralIndex);
88
+ }
89
+ }
90
+ }
91
+ /**
92
+ * @internal Rejects collateral transfer inputs a parse constructor cannot read with a typed error:
93
+ * a list that is not an array, an entry that is not an object, or a non-bigint index or amount.
94
+ */
95
+ export function validateCollateralTransferInputs(field, entries) {
96
+ if (!Array.isArray(entries)) {
97
+ throw new InvalidTransactionPlanError({
98
+ path: `$.${field}`,
99
+ reason: "expected an array",
100
+ });
101
+ }
102
+ for (const [index, entry] of entries.entries()) {
103
+ // Validation only; a hole or null entry would otherwise throw a native TypeError.
104
+ getPlanObject(entry, `$.${field}[${index}]`);
105
+ }
106
+ validateCollateralIndexTypes(field, entries);
107
+ for (const [index, { assets }] of entries.entries()) {
108
+ if (typeof assets !== "bigint") {
109
+ throw new InvalidBigIntInputError(`${field}[${index}].assets`, assets);
110
+ }
111
+ }
112
+ }