@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,101 @@
1
+ import { type MarketId } from "@morpho-org/blue-sdk";
2
+ import { type Address, type Client } from "viem";
3
+ import { type BlueWithdrawBuyCallbackAction, type ReferenceTimestampParams, type Transaction } from "../../types/index.js";
4
+ import { type IntentParams } from "../intent.js";
5
+ import type { Action, TransactionPlan } from "../types.js";
6
+ import { type BlueMarketSnapshot, type BluePositionSnapshot } from "./prepare.js";
7
+ /**
8
+ * Caller intent and caller-fetched snapshots for withdrawing a BlueBuyCallback's whole supply
9
+ * position to its owner. The position belongs to `callbackAddress`, not to `account`.
10
+ * @example
11
+ * ```ts
12
+ * import type { BlueWithdrawBuyCallbackPlanParams } from "@morpho-org/morpho-sdk";
13
+ * import type { Address } from "viem";
14
+ * declare const callbackAddress: Address;
15
+ * const withdrawal = { callbackAddress, expiresAt: 1_900_000_000 } satisfies Pick<
16
+ * BlueWithdrawBuyCallbackPlanParams,
17
+ * "callbackAddress" | "expiresAt"
18
+ * >;
19
+ * ```
20
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
21
+ */
22
+ export interface BlueWithdrawBuyCallbackPlanParams extends Pick<IntentParams, "chainId" | "account" | "expiresAt" | "calldataOrigin">, ReferenceTimestampParams {
23
+ readonly marketId: MarketId;
24
+ readonly marketData: BlueMarketSnapshot;
25
+ /** BlueBuyCallback whose supply position is withdrawn; `account` must be its owner. */
26
+ readonly callbackAddress: Address;
27
+ /** Caller-fetched position of `callbackAddress`; every supply share in it is withdrawn. */
28
+ readonly positionData: BluePositionSnapshot;
29
+ }
30
+ /**
31
+ * Prepares a direct Morpho Blue withdrawal of a BlueBuyCallback's whole supply position to its owner.
32
+ * The call is `withdraw(marketParams, 0, shares, callbackAddress, account)` on Morpho Blue, not
33
+ * BlueBundlesV1: the callback authorizes its owner on Blue at construction, so the plan has no
34
+ * approval, authorization step or signature request. Preparation reads the chain and rejects a
35
+ * callback the registered factory did not create, another owner, or a revoked Blue authorization.
36
+ * The plan carries no referral fee, and `expiresAt` is plan metadata, not an onchain deadline.
37
+ * @param client - Viem client on the requested chain.
38
+ * @param params.chainId - Chain containing Morpho Blue and the registered `midnightBlueBuyCallbackFactory`.
39
+ * @param params.account - Non-zero callback owner that sends the transaction and receives the loan assets.
40
+ * @param params.marketId - Market ID matching both snapshots and the market tuple.
41
+ * @param params.marketData.chainId - Chain on which the market snapshot was fetched; must equal `chainId`.
42
+ * @param params.marketData.market - Caller-fetched `Market` snapshot used to fix the market tuple; its state must equal the position snapshot's market. Never stored in the plan.
43
+ * @param params.callbackAddress - BlueBuyCallback whose supply position is withdrawn.
44
+ * @param params.positionData.chainId - Position snapshot's chain; must equal `chainId`.
45
+ * @param params.positionData.position - Caller-fetched `AccrualPosition` of `callbackAddress` on `marketId`; all its supply shares are withdrawn and their assets must not exceed that market's liquidity.
46
+ * @param params.now - Optional reference timestamp in seconds, normally the latest block timestamp; defaults to the device clock.
47
+ * @param params.expiresAt - Optional Unix expiry in safe-integer seconds, later than `now`; defaults to `now + 2h`. Plan metadata only.
48
+ * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to the withdrawal calldata; omitted by default.
49
+ * @returns A deep-frozen, data-only `{ version, chainId, account, expiresAt, steps, signatureRequests, calldataOrigin? }` plan with one `blueWithdrawBuyCallback` step and no signature requests.
50
+ * @throws {BlueSnapshotChainMismatchError} when a market or position snapshot's chain differs from `chainId`.
51
+ * @throws {MarketIdMismatchError} when a snapshot's ID differs from `marketId` or does not hash from its market tuple.
52
+ * @throws {BlueSnapshotStateMismatchError} when the market snapshot's state differs from the position snapshot's market.
53
+ * @throws {MissingAccrualPositionError} when no position snapshot is provided.
54
+ * @throws {AccrualPositionUserMismatchError} when the position belongs to another address than `callbackAddress`.
55
+ * @throws {ZeroAccountError} when `account` is the zero address.
56
+ * @throws {InvalidTransactionPlanError} when `account` or `callbackAddress` is not a checksum-valid address, or `calldataOrigin` exceeds 1 MiB.
57
+ * @throws {NonIntegerInputError} when `expiresAt` is not a safe integer.
58
+ * @throws {NonPositiveInputError} when `expiresAt` is not positive.
59
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before `now`.
60
+ * @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty, malformed or has an odd number of hex digits.
61
+ * @throws {EmptyBlueSupplyPositionError} when the callback holds no supply shares.
62
+ * @throws {InsufficientBlueLiquidityError} when the position's supply assets exceed the snapshot market's liquidity.
63
+ * @throws {InputExceedsMaxError} when the supply shares exceed `uint256`.
64
+ * @throws {UnsupportedChainIdError} when `chainId` is absent from the registry.
65
+ * @throws {UnknownAddressError} when Morpho Blue or `midnightBlueBuyCallbackFactory` is not registered on `chainId`.
66
+ * @throws {ChainIdMismatchError} when the client declares another chain (checked before any snapshot) or its transport serves one.
67
+ * @throws {MissingContractCodeError} when Morpho Blue or the factory has no deployed code.
68
+ * @throws {NotBlueBuyCallbackError} when the factory did not create `callbackAddress`.
69
+ * @throws {BlueBuyCallbackOwnerMismatchError} when the callback's `OWNER()` is not `account`.
70
+ * @throws {BlueBuyCallbackUnauthorizedError} when Morpho Blue does not authorize `account` for the callback.
71
+ * @throws {viem.BaseError} when a chain, bytecode, factory, owner or authorization read fails.
72
+ * @example
73
+ * ```ts
74
+ * import { markets } from "@morpho-org/morpho-test";
75
+ * import { buildTransactions, prepareBlueWithdrawBuyCallback } from "@morpho-org/morpho-sdk";
76
+ * import { fetchBlueAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
77
+ * import { createPublicClient, type Address, http } from "viem";
78
+ * import { mainnet } from "viem/chains";
79
+ *
80
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
81
+ * declare const account: Address; // Owner of the BlueBuyCallback.
82
+ * declare const callbackAddress: Address; // BlueBuyCallback created by the registered factory.
83
+ * const position = await fetchBlueAccrualPosition(callbackAddress, markets[mainnet.id].usdc_wbtc.id, client);
84
+ * const plan = await prepareBlueWithdrawBuyCallback(client, {
85
+ * chainId: mainnet.id, account, callbackAddress, marketId: position.market.id,
86
+ * marketData: { chainId: mainnet.id, market: position.market },
87
+ * positionData: { chainId: mainnet.id, position },
88
+ * now: (await client.getBlock()).timestamp,
89
+ * });
90
+ * const [transaction] = buildTransactions(plan);
91
+ * // Submit transaction from account; it calls Morpho Blue directly.
92
+ * ```
93
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
94
+ */
95
+ export declare function prepareBlueWithdrawBuyCallback(client: Client, params: BlueWithdrawBuyCallbackPlanParams): Promise<TransactionPlan>;
96
+ /** @internal Encodes the stored callback withdrawal through the same action as the entity handle. */
97
+ export declare function buildBlueWithdrawBuyCallback(action: Extract<Action, {
98
+ type: "blueWithdrawBuyCallback";
99
+ }>): Readonly<Transaction<BlueWithdrawBuyCallbackAction>>;
100
+ /** @internal Validates the stored callback withdrawal's structural inputs. */
101
+ export declare function validateBlueWithdrawBuyCallbackPlanAction(action: Record<string, unknown>, path: string): void;
@@ -0,0 +1,259 @@
1
+ import { MarketUtils } from "@morpho-org/blue-sdk";
2
+ import { deepFreeze, getChainAddress, isHexEqual, Time, } from "@morpho-org/morpho-ts";
3
+ import { isAddressEqual } from "viem";
4
+ import { getBytecode, readContract } from "viem/actions";
5
+ import { blueAbi, midnightBlueBuyCallbackAbi, midnightBlueBuyCallbackFactoryAbi, } from "../../abis.js";
6
+ import { parseBlueWithdrawBuyCallback } from "../../actions/blue/withdrawBuyCallback.internal.js";
7
+ import { blueWithdrawBuyCallback } from "../../actions/blue/withdrawBuyCallback.js";
8
+ import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
+ import { validateChainId } from "../../helpers/index.js";
10
+ import { validateMarketParamsId } from "../../helpers/validate.js";
11
+ import { AccrualPositionUserMismatchError, BlueBuyCallbackOwnerMismatchError, BlueBuyCallbackUnauthorizedError, EmptyBlueSupplyPositionError, InsufficientBlueLiquidityError, MarketIdMismatchError, MissingAccrualPositionError, MissingContractCodeError, NotBlueBuyCallbackError, } from "../../types/index.js";
12
+ import { BlueSnapshotChainMismatchError, BlueSnapshotStateMismatchError, } from "../error.js";
13
+ import { resolveIntent } from "../intent.js";
14
+ import { getPlanObject, validatePlanField, validatePlanFields, } from "../validation.js";
15
+ import { validateBlueMarketSnapshot, } from "./prepare.js";
16
+ const MARKET_STATE_FIELDS = [
17
+ "totalSupplyAssets",
18
+ "totalSupplyShares",
19
+ "totalBorrowAssets",
20
+ "totalBorrowShares",
21
+ "lastUpdate",
22
+ "fee",
23
+ "price",
24
+ "rateAtTarget",
25
+ ];
26
+ /**
27
+ * Prepares a direct Morpho Blue withdrawal of a BlueBuyCallback's whole supply position to its owner.
28
+ * The call is `withdraw(marketParams, 0, shares, callbackAddress, account)` on Morpho Blue, not
29
+ * BlueBundlesV1: the callback authorizes its owner on Blue at construction, so the plan has no
30
+ * approval, authorization step or signature request. Preparation reads the chain and rejects a
31
+ * callback the registered factory did not create, another owner, or a revoked Blue authorization.
32
+ * The plan carries no referral fee, and `expiresAt` is plan metadata, not an onchain deadline.
33
+ * @param client - Viem client on the requested chain.
34
+ * @param params.chainId - Chain containing Morpho Blue and the registered `midnightBlueBuyCallbackFactory`.
35
+ * @param params.account - Non-zero callback owner that sends the transaction and receives the loan assets.
36
+ * @param params.marketId - Market ID matching both snapshots and the market tuple.
37
+ * @param params.marketData.chainId - Chain on which the market snapshot was fetched; must equal `chainId`.
38
+ * @param params.marketData.market - Caller-fetched `Market` snapshot used to fix the market tuple; its state must equal the position snapshot's market. Never stored in the plan.
39
+ * @param params.callbackAddress - BlueBuyCallback whose supply position is withdrawn.
40
+ * @param params.positionData.chainId - Position snapshot's chain; must equal `chainId`.
41
+ * @param params.positionData.position - Caller-fetched `AccrualPosition` of `callbackAddress` on `marketId`; all its supply shares are withdrawn and their assets must not exceed that market's liquidity.
42
+ * @param params.now - Optional reference timestamp in seconds, normally the latest block timestamp; defaults to the device clock.
43
+ * @param params.expiresAt - Optional Unix expiry in safe-integer seconds, later than `now`; defaults to `now + 2h`. Plan metadata only.
44
+ * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to the withdrawal calldata; omitted by default.
45
+ * @returns A deep-frozen, data-only `{ version, chainId, account, expiresAt, steps, signatureRequests, calldataOrigin? }` plan with one `blueWithdrawBuyCallback` step and no signature requests.
46
+ * @throws {BlueSnapshotChainMismatchError} when a market or position snapshot's chain differs from `chainId`.
47
+ * @throws {MarketIdMismatchError} when a snapshot's ID differs from `marketId` or does not hash from its market tuple.
48
+ * @throws {BlueSnapshotStateMismatchError} when the market snapshot's state differs from the position snapshot's market.
49
+ * @throws {MissingAccrualPositionError} when no position snapshot is provided.
50
+ * @throws {AccrualPositionUserMismatchError} when the position belongs to another address than `callbackAddress`.
51
+ * @throws {ZeroAccountError} when `account` is the zero address.
52
+ * @throws {InvalidTransactionPlanError} when `account` or `callbackAddress` is not a checksum-valid address, or `calldataOrigin` exceeds 1 MiB.
53
+ * @throws {NonIntegerInputError} when `expiresAt` is not a safe integer.
54
+ * @throws {NonPositiveInputError} when `expiresAt` is not positive.
55
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before `now`.
56
+ * @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty, malformed or has an odd number of hex digits.
57
+ * @throws {EmptyBlueSupplyPositionError} when the callback holds no supply shares.
58
+ * @throws {InsufficientBlueLiquidityError} when the position's supply assets exceed the snapshot market's liquidity.
59
+ * @throws {InputExceedsMaxError} when the supply shares exceed `uint256`.
60
+ * @throws {UnsupportedChainIdError} when `chainId` is absent from the registry.
61
+ * @throws {UnknownAddressError} when Morpho Blue or `midnightBlueBuyCallbackFactory` is not registered on `chainId`.
62
+ * @throws {ChainIdMismatchError} when the client declares another chain (checked before any snapshot) or its transport serves one.
63
+ * @throws {MissingContractCodeError} when Morpho Blue or the factory has no deployed code.
64
+ * @throws {NotBlueBuyCallbackError} when the factory did not create `callbackAddress`.
65
+ * @throws {BlueBuyCallbackOwnerMismatchError} when the callback's `OWNER()` is not `account`.
66
+ * @throws {BlueBuyCallbackUnauthorizedError} when Morpho Blue does not authorize `account` for the callback.
67
+ * @throws {viem.BaseError} when a chain, bytecode, factory, owner or authorization read fails.
68
+ * @example
69
+ * ```ts
70
+ * import { markets } from "@morpho-org/morpho-test";
71
+ * import { buildTransactions, prepareBlueWithdrawBuyCallback } from "@morpho-org/morpho-sdk";
72
+ * import { fetchBlueAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
73
+ * import { createPublicClient, type Address, http } from "viem";
74
+ * import { mainnet } from "viem/chains";
75
+ *
76
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
77
+ * declare const account: Address; // Owner of the BlueBuyCallback.
78
+ * declare const callbackAddress: Address; // BlueBuyCallback created by the registered factory.
79
+ * const position = await fetchBlueAccrualPosition(callbackAddress, markets[mainnet.id].usdc_wbtc.id, client);
80
+ * const plan = await prepareBlueWithdrawBuyCallback(client, {
81
+ * chainId: mainnet.id, account, callbackAddress, marketId: position.market.id,
82
+ * marketData: { chainId: mainnet.id, market: position.market },
83
+ * positionData: { chainId: mainnet.id, position },
84
+ * now: (await client.getBlock()).timestamp,
85
+ * });
86
+ * const [transaction] = buildTransactions(plan);
87
+ * // Submit transaction from account; it calls Morpho Blue directly.
88
+ * ```
89
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
90
+ */
91
+ export async function prepareBlueWithdrawBuyCallback(client, params) {
92
+ const { chainId, account, callbackAddress, marketId, marketData } = params;
93
+ const snapshot = params.positionData;
94
+ // Reject a client declaring another chain first, as the entity does.
95
+ validateChainId(client.chain?.id, chainId);
96
+ validatePlanField(callbackAddress, {
97
+ path: "$.callbackAddress",
98
+ type: "address",
99
+ });
100
+ // Reject mismatched snapshots before deriving the withdrawal or reading chain state.
101
+ validateBlueMarketSnapshot(marketData, { chainId, marketId });
102
+ if (snapshot == null) {
103
+ throw new MissingAccrualPositionError(marketId);
104
+ }
105
+ if (snapshot.chainId !== chainId) {
106
+ throw new BlueSnapshotChainMismatchError(snapshot.chainId, chainId);
107
+ }
108
+ const { position } = snapshot;
109
+ if (!isHexEqual(position.marketId, marketId)) {
110
+ throw new MarketIdMismatchError(position.marketId, marketId);
111
+ }
112
+ if (!isHexEqual(position.market.id, marketId)) {
113
+ throw new MarketIdMismatchError(position.market.id, marketId);
114
+ }
115
+ validateMarketParamsId(position.market.params);
116
+ if (!isAddressEqual(position.user, callbackAddress)) {
117
+ throw new AccrualPositionUserMismatchError(position.user, callbackAddress);
118
+ }
119
+ // Bind the withdrawal to one market state: the position's market bounds the liquidity check.
120
+ for (const field of MARKET_STATE_FIELDS) {
121
+ if (position.market[field] !== marketData.market[field]) {
122
+ throw new BlueSnapshotStateMismatchError({
123
+ field,
124
+ positionValue: position.market[field],
125
+ marketValue: marketData.market[field],
126
+ });
127
+ }
128
+ }
129
+ const intent = resolveIntent(params, params.now ?? Time.timestamp());
130
+ const market = marketData.market.id;
131
+ const shares = position.supplyShares;
132
+ if (shares === 0n) {
133
+ throw new EmptyBlueSupplyPositionError({ market, user: callbackAddress });
134
+ }
135
+ const assets = position.supplyAssets;
136
+ const liquidity = position.market.liquidity;
137
+ if (assets > liquidity) {
138
+ throw new InsufficientBlueLiquidityError({ market, assets, liquidity });
139
+ }
140
+ const { loanToken, collateralToken, oracle, irm, lltv } = marketData.market.params;
141
+ // Validate shares, the market tuple and the Blue registration before any RPC read.
142
+ parseBlueWithdrawBuyCallback({
143
+ market: { chainId, marketParams: marketData.market.params },
144
+ args: { callbackAddress, userAddress: account, shares },
145
+ });
146
+ const blue = getChainAddress(chainId, "blue");
147
+ const factory = getChainAddress(chainId, "midnightBlueBuyCallbackFactory");
148
+ await validateClientChainId(client, chainId);
149
+ const targets = [
150
+ { role: "blue", address: blue },
151
+ { role: "midnightBlueBuyCallbackFactory", address: factory },
152
+ ];
153
+ // Start every read, then consume them in target order so a stalled or failed
154
+ // later read cannot hide Blue's missing code, as `assertRegistryTargetsHaveCode` does.
155
+ const reads = targets.map(({ address }) => {
156
+ const read = getBytecode(client, { address });
157
+ read.catch(() => undefined);
158
+ return read;
159
+ });
160
+ for (const [index, { role, address }] of targets.entries()) {
161
+ const bytecode = await reads[index];
162
+ if (bytecode === undefined || bytecode === "0x") {
163
+ throw new MissingContractCodeError(address, chainId, role);
164
+ }
165
+ }
166
+ // Check the factory first: OWNER() on an arbitrary address can revert or lie.
167
+ const isBlueBuyCallback = await readContract(client, {
168
+ address: factory,
169
+ abi: midnightBlueBuyCallbackFactoryAbi,
170
+ functionName: "isBlueBuyCallback",
171
+ args: [callbackAddress],
172
+ });
173
+ if (!isBlueBuyCallback) {
174
+ throw new NotBlueBuyCallbackError(callbackAddress);
175
+ }
176
+ const [owner, isAuthorized] = await Promise.all([
177
+ readContract(client, {
178
+ address: callbackAddress,
179
+ abi: midnightBlueBuyCallbackAbi,
180
+ functionName: "OWNER",
181
+ }),
182
+ readContract(client, {
183
+ address: blue,
184
+ abi: blueAbi,
185
+ functionName: "isAuthorized",
186
+ args: [callbackAddress, account],
187
+ }),
188
+ ]);
189
+ if (!isAddressEqual(owner, account)) {
190
+ throw new BlueBuyCallbackOwnerMismatchError({
191
+ callback: callbackAddress,
192
+ owner,
193
+ userAddress: account,
194
+ });
195
+ }
196
+ if (!isAuthorized) {
197
+ throw new BlueBuyCallbackUnauthorizedError({
198
+ callback: callbackAddress,
199
+ userAddress: account,
200
+ });
201
+ }
202
+ return deepFreeze({
203
+ version: 2,
204
+ chainId,
205
+ account,
206
+ expiresAt: intent.expiresAt,
207
+ ...(intent.calldataOrigin && { calldataOrigin: intent.calldataOrigin }),
208
+ steps: [
209
+ {
210
+ id: "blueWithdrawBuyCallback",
211
+ label: "Withdraw BlueBuyCallback supply from Blue",
212
+ action: {
213
+ type: "blueWithdrawBuyCallback",
214
+ inputs: {
215
+ chainId,
216
+ account,
217
+ marketParams: { loanToken, collateralToken, oracle, irm, lltv },
218
+ callbackAddress,
219
+ shares,
220
+ },
221
+ },
222
+ },
223
+ ],
224
+ signatureRequests: [],
225
+ });
226
+ }
227
+ /** @internal Encodes the stored callback withdrawal through the same action as the entity handle. */
228
+ export function buildBlueWithdrawBuyCallback(action) {
229
+ const { chainId, account, marketParams, callbackAddress, shares } = action.inputs;
230
+ return blueWithdrawBuyCallback({
231
+ market: {
232
+ chainId,
233
+ marketParams: {
234
+ ...marketParams,
235
+ id: MarketUtils.getMarketId(marketParams),
236
+ liquidationIncentiveFactor: MarketUtils.getLiquidationIncentiveFactor(marketParams),
237
+ },
238
+ },
239
+ args: { callbackAddress, userAddress: account, shares },
240
+ });
241
+ }
242
+ /** @internal Validates the stored callback withdrawal's structural inputs. */
243
+ export function validateBlueWithdrawBuyCallbackPlanAction(action, path) {
244
+ const inputs = getPlanObject(action.inputs, `${path}.inputs`);
245
+ validatePlanFields(inputs, {
246
+ path: `${path}.inputs`,
247
+ fields: { callbackAddress: "address", shares: "uint256 bigint" },
248
+ });
249
+ validatePlanFields(getPlanObject(inputs.marketParams, `${path}.inputs.marketParams`), {
250
+ path: `${path}.inputs.marketParams`,
251
+ fields: {
252
+ loanToken: "address",
253
+ collateralToken: "address",
254
+ oracle: "address",
255
+ irm: "address",
256
+ lltv: "uint256 bigint",
257
+ },
258
+ });
259
+ }
@@ -195,3 +195,30 @@ export declare class NonIntegerInputError extends Error {
195
195
  */
196
196
  constructor(field: string, value: number);
197
197
  }
198
+ /**
199
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
200
+ * A reduce-only Midnight withdrawal needs more credit units than the position's accrued credit
201
+ * holds, so no quote or market liquidity can reach the target.
202
+ */
203
+ export declare class MidnightTakeCreditInsufficientError extends Error {
204
+ /** Position credit accrued to the reference timestamp. */
205
+ readonly credit: bigint;
206
+ /** Credit units the target needs. */
207
+ readonly requiredUnits: bigint;
208
+ /**
209
+ * @param params - Accrued credit, the units the target needs and optional underlying error.
210
+ * @param params.credit - Position credit accrued to the reference timestamp.
211
+ * @param params.requiredUnits - Credit units the target needs.
212
+ * @param params.cause - Offer-shortfall error that the credit shortfall replaces.
213
+ * @example
214
+ * ```ts
215
+ * import { MidnightTakeCreditInsufficientError } from "@morpho-org/morpho-sdk";
216
+ * const error = new MidnightTakeCreditInsufficientError({ credit: 40n, requiredUnits: 50n });
217
+ * ```
218
+ */
219
+ constructor({ credit, requiredUnits, cause, }: {
220
+ readonly credit: bigint;
221
+ readonly requiredUnits: bigint;
222
+ readonly cause?: unknown;
223
+ });
224
+ }
@@ -232,3 +232,31 @@ export class NonIntegerInputError extends Error {
232
232
  this.name = "NonIntegerInputError";
233
233
  }
234
234
  }
235
+ /**
236
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
237
+ * A reduce-only Midnight withdrawal needs more credit units than the position's accrued credit
238
+ * holds, so no quote or market liquidity can reach the target.
239
+ */
240
+ export class MidnightTakeCreditInsufficientError extends Error {
241
+ /** Position credit accrued to the reference timestamp. */
242
+ credit;
243
+ /** Credit units the target needs. */
244
+ requiredUnits;
245
+ /**
246
+ * @param params - Accrued credit, the units the target needs and optional underlying error.
247
+ * @param params.credit - Position credit accrued to the reference timestamp.
248
+ * @param params.requiredUnits - Credit units the target needs.
249
+ * @param params.cause - Offer-shortfall error that the credit shortfall replaces.
250
+ * @example
251
+ * ```ts
252
+ * import { MidnightTakeCreditInsufficientError } from "@morpho-org/morpho-sdk";
253
+ * const error = new MidnightTakeCreditInsufficientError({ credit: 40n, requiredUnits: 50n });
254
+ * ```
255
+ */
256
+ constructor({ credit, requiredUnits, cause, }) {
257
+ super(`Midnight position credit "${credit}" is below the "${requiredUnits}" units the target needs. Lower the target to at most the position's credit.`, { cause });
258
+ this.credit = credit;
259
+ this.requiredUnits = requiredUnits;
260
+ this.name = "MidnightTakeCreditInsufficientError";
261
+ }
262
+ }
@@ -16,10 +16,49 @@ export type { BlueSupplyCollateralBorrowPlanParams } from "./blue/supplyCollater
16
16
  export { prepareBlueSupplyCollateralBorrow } from "./blue/supplyCollateralBorrow.js";
17
17
  export type { BlueWithdrawPlanParams } from "./blue/withdraw.js";
18
18
  export { prepareBlueWithdraw } from "./blue/withdraw.js";
19
+ export type { BlueWithdrawBuyCallbackPlanParams } from "./blue/withdrawBuyCallback.js";
20
+ export { prepareBlueWithdrawBuyCallback } from "./blue/withdrawBuyCallback.js";
19
21
  export type { BlueWithdrawCollateralPlanParams } from "./blue/withdrawCollateral.js";
20
22
  export { prepareBlueWithdrawCollateral } from "./blue/withdrawCollateral.js";
21
- export { BlueSnapshotChainMismatchError, BlueSnapshotStateMismatchError, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, NonIntegerInputError, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, ZeroAccountError, } from "./error.js";
23
+ export { BlueSnapshotChainMismatchError, BlueSnapshotStateMismatchError, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, MidnightTakeCreditInsufficientError, NonIntegerInputError, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, ZeroAccountError, } from "./error.js";
22
24
  export type { Funding, IntentParams, ReferralFee, } from "./intent.js";
25
+ export type { MidnightCancelOffersPlanParams } from "./midnight/cancelOffers.js";
26
+ export { prepareMidnightCancelOffers } from "./midnight/cancelOffers.js";
27
+ export type { MidnightMakeBorrowPlanParams } from "./midnight/makeBorrow.js";
28
+ export { prepareMidnightMakeBorrow } from "./midnight/makeBorrow.js";
29
+ export type { MidnightMakeLendPlanParams } from "./midnight/makeLend.js";
30
+ export { prepareMidnightMakeLend } from "./midnight/makeLend.js";
31
+ export type { MidnightMakeRepayPlanParams } from "./midnight/makeRepay.js";
32
+ export { prepareMidnightMakeRepay } from "./midnight/makeRepay.js";
33
+ export type { MidnightMakerPublicationPlanParams } from "./midnight/makerPublication.js";
34
+ export type { MidnightMakeWithdrawPlanParams } from "./midnight/makeWithdraw.js";
35
+ export { prepareMidnightMakeWithdraw } from "./midnight/makeWithdraw.js";
36
+ export type { MidnightRedeemPlanParams } from "./midnight/redeem.js";
37
+ export { prepareMidnightRedeem } from "./midnight/redeem.js";
38
+ export type { MidnightRepayWithdrawCollateralPlanParams } from "./midnight/repayWithdrawCollateral.js";
39
+ export { prepareMidnightRepayWithdrawCollateral } from "./midnight/repayWithdrawCollateral.js";
40
+ export type { MidnightSupplyBlueMakeLendPlanParams } from "./midnight/supplyBlueMakeLend.js";
41
+ export { prepareMidnightSupplyBlueMakeLend } from "./midnight/supplyBlueMakeLend.js";
42
+ export type { MidnightSupplyCollateralPlanParams } from "./midnight/supplyCollateral.js";
43
+ export { prepareMidnightSupplyCollateral } from "./midnight/supplyCollateral.js";
44
+ export type { MidnightSupplyCollateralBatchPlanParams } from "./midnight/supplyCollateralBatch.js";
45
+ export { prepareMidnightSupplyCollateralBatch } from "./midnight/supplyCollateralBatch.js";
46
+ export type { MidnightSupplyCollateralMakeBorrowPlanParams } from "./midnight/supplyCollateralMakeBorrow.js";
47
+ export { prepareMidnightSupplyCollateralMakeBorrow } from "./midnight/supplyCollateralMakeBorrow.js";
48
+ export type { MidnightSupplyCollateralWithNativePlanParams } from "./midnight/supplyCollateralWithNative.js";
49
+ export { prepareMidnightSupplyCollateralWithNative } from "./midnight/supplyCollateralWithNative.js";
50
+ export type { MidnightSupplyCollateralTakeBorrowPlanParams, MidnightTakeBorrowPlanParams, } from "./midnight/takeBorrow.js";
51
+ export { prepareMidnightSupplyCollateralTakeBorrow, prepareMidnightTakeBorrow, } from "./midnight/takeBorrow.js";
52
+ export type { MidnightTakeLendPlanParams } from "./midnight/takeLend.js";
53
+ export { prepareMidnightTakeLend } from "./midnight/takeLend.js";
54
+ export type { MidnightTakeRepayWithdrawCollateralPlanParams } from "./midnight/takeRepayWithdrawCollateral.js";
55
+ export { prepareMidnightTakeRepayWithdrawCollateral } from "./midnight/takeRepayWithdrawCollateral.js";
56
+ export type { MidnightTakeWithdrawPlanParams } from "./midnight/takeWithdraw.js";
57
+ export { prepareMidnightTakeWithdraw } from "./midnight/takeWithdraw.js";
58
+ export type { MidnightWithdrawCollateralPlanParams } from "./midnight/withdrawCollateral.js";
59
+ export { prepareMidnightWithdrawCollateral } from "./midnight/withdrawCollateral.js";
60
+ export type { MidnightWithdrawCollateralBatchPlanParams } from "./midnight/withdrawCollateralBatch.js";
61
+ export { prepareMidnightWithdrawCollateralBatch } from "./midnight/withdrawCollateralBatch.js";
23
62
  export { applySignatures, buildTransaction, buildTransactions, getPendingSignatureRequests, } from "./plan.js";
24
63
  export { parseTransactionPlan, serializeTransactionPlan } from "./serde.js";
25
64
  export type { Action, SignatureRequest, Step, TransactionPlan, } from "./types.js";
@@ -7,8 +7,27 @@ export { prepareBlueSupply } from "./blue/supply.js";
7
7
  export { prepareBlueSupplyCollateral } from "./blue/supplyCollateral.js";
8
8
  export { prepareBlueSupplyCollateralBorrow } from "./blue/supplyCollateralBorrow.js";
9
9
  export { prepareBlueWithdraw } from "./blue/withdraw.js";
10
+ export { prepareBlueWithdrawBuyCallback } from "./blue/withdrawBuyCallback.js";
10
11
  export { prepareBlueWithdrawCollateral } from "./blue/withdrawCollateral.js";
11
- export { BlueSnapshotChainMismatchError, BlueSnapshotStateMismatchError, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, NonIntegerInputError, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, ZeroAccountError, } from "./error.js";
12
+ export { BlueSnapshotChainMismatchError, BlueSnapshotStateMismatchError, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, MidnightTakeCreditInsufficientError, NonIntegerInputError, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, ZeroAccountError, } from "./error.js";
13
+ export { prepareMidnightCancelOffers } from "./midnight/cancelOffers.js";
14
+ export { prepareMidnightMakeBorrow } from "./midnight/makeBorrow.js";
15
+ export { prepareMidnightMakeLend } from "./midnight/makeLend.js";
16
+ export { prepareMidnightMakeRepay } from "./midnight/makeRepay.js";
17
+ export { prepareMidnightMakeWithdraw } from "./midnight/makeWithdraw.js";
18
+ export { prepareMidnightRedeem } from "./midnight/redeem.js";
19
+ export { prepareMidnightRepayWithdrawCollateral } from "./midnight/repayWithdrawCollateral.js";
20
+ export { prepareMidnightSupplyBlueMakeLend } from "./midnight/supplyBlueMakeLend.js";
21
+ export { prepareMidnightSupplyCollateral } from "./midnight/supplyCollateral.js";
22
+ export { prepareMidnightSupplyCollateralBatch } from "./midnight/supplyCollateralBatch.js";
23
+ export { prepareMidnightSupplyCollateralMakeBorrow } from "./midnight/supplyCollateralMakeBorrow.js";
24
+ export { prepareMidnightSupplyCollateralWithNative } from "./midnight/supplyCollateralWithNative.js";
25
+ export { prepareMidnightSupplyCollateralTakeBorrow, prepareMidnightTakeBorrow, } from "./midnight/takeBorrow.js";
26
+ export { prepareMidnightTakeLend } from "./midnight/takeLend.js";
27
+ export { prepareMidnightTakeRepayWithdrawCollateral } from "./midnight/takeRepayWithdrawCollateral.js";
28
+ export { prepareMidnightTakeWithdraw } from "./midnight/takeWithdraw.js";
29
+ export { prepareMidnightWithdrawCollateral } from "./midnight/withdrawCollateral.js";
30
+ export { prepareMidnightWithdrawCollateralBatch } from "./midnight/withdrawCollateralBatch.js";
12
31
  export { applySignatures, buildTransaction, buildTransactions, getPendingSignatureRequests, } from "./plan.js";
13
32
  export { parseTransactionPlan, serializeTransactionPlan } from "./serde.js";
14
33
  export { prepareVaultV1Deposit } from "./vaultv1/deposit.js";
@@ -0,0 +1,15 @@
1
+ import type { Address, Client } from "viem";
2
+ import type { Action, Step } from "../types.js";
3
+ type Authorization = Extract<Action, {
4
+ type: "midnightAuthorization";
5
+ }>;
6
+ /** @internal Resolves the ordinary registry bundle grant after the RPC chain has been checked. */
7
+ export declare function prepareMidnightBundleAuthorization(client: Client, inputs: {
8
+ readonly chainId: number;
9
+ readonly account: Address;
10
+ }): Promise<Step<Authorization> | undefined>;
11
+ /** @internal Derives the authorization target from the chain, not from a stored operator. */
12
+ export declare function buildMidnightAuthorization({ inputs }: Authorization): Readonly<import("../../index.js").Transaction<import("../../index.js").MidnightAuthorizationAction>>;
13
+ /** @internal Midnight steps never use signature requests. */
14
+ export declare function validateSignaturelessMidnightAction(action: Record<string, unknown>, path: string): void;
15
+ export {};
@@ -0,0 +1,40 @@
1
+ import { midnightAbi } from "@morpho-org/midnight-sdk";
2
+ import { getChainAddress } from "@morpho-org/morpho-ts";
3
+ import { readContract } from "viem/actions";
4
+ import { midnightSetIsAuthorized } from "../../actions/midnight/authorization.js";
5
+ import { InvalidTransactionPlanError } from "../error.js";
6
+ /** @internal Resolves the ordinary registry bundle grant after the RPC chain has been checked. */
7
+ export async function prepareMidnightBundleAuthorization(client, inputs) {
8
+ const { chainId, account } = inputs;
9
+ const isAuthorized = await readContract(client, {
10
+ address: getChainAddress(chainId, "midnight"),
11
+ abi: midnightAbi,
12
+ functionName: "isAuthorized",
13
+ args: [account, getChainAddress(chainId, "midnightBundlesV2")],
14
+ });
15
+ if (isAuthorized) {
16
+ return undefined;
17
+ }
18
+ return {
19
+ id: "midnightAuthorization",
20
+ label: "Authorize Midnight bundle",
21
+ action: { type: "midnightAuthorization", inputs },
22
+ };
23
+ }
24
+ /** @internal Derives the authorization target from the chain, not from a stored operator. */
25
+ export function buildMidnightAuthorization({ inputs }) {
26
+ return midnightSetIsAuthorized({
27
+ chainId: inputs.chainId,
28
+ onBehalf: inputs.account,
29
+ authorized: getChainAddress(inputs.chainId, "midnightBundlesV2"),
30
+ });
31
+ }
32
+ /** @internal Midnight steps never use signature requests. */
33
+ export function validateSignaturelessMidnightAction(action, path) {
34
+ if ("signatureRequestIds" in action) {
35
+ throw new InvalidTransactionPlanError({
36
+ path: `${path}.signatureRequestIds`,
37
+ reason: "Midnight steps do not consume signatures",
38
+ });
39
+ }
40
+ }
@@ -0,0 +1,80 @@
1
+ import type { Client, Hex } from "viem";
2
+ import type { MidnightCancelOffersAction, ReferenceTimestampParams, Transaction } from "../../types/index.js";
3
+ import { type IntentParams } from "../intent.js";
4
+ import type { Action, TransactionPlan } from "../types.js";
5
+ /**
6
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
7
+ * Offer groups to cancel in full for `account` through a direct Midnight call.
8
+ * No authorization, approval or signature is needed.
9
+ * @example
10
+ * ```ts
11
+ * import type { MidnightCancelOffersPlanParams } from "@morpho-org/morpho-sdk";
12
+ * import type { Address, Hex } from "viem";
13
+ *
14
+ * declare const maker: Address;
15
+ * declare const group: Hex;
16
+ * const params: MidnightCancelOffersPlanParams = { chainId: 8453, account: maker, groups: [group] };
17
+ * ```
18
+ */
19
+ export interface MidnightCancelOffersPlanParams extends Pick<IntentParams, "chainId" | "account" | "expiresAt" | "calldataOrigin">, ReferenceTimestampParams {
20
+ /** Nonempty list of distinct 32-byte offer groups, cancelled in list order. */
21
+ readonly groups: readonly Hex[];
22
+ }
23
+ /**
24
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
25
+ * Prepares a full cancellation of `account`'s offer groups as one direct Midnight transaction.
26
+ * One group builds a bare `setConsumed(group, maxUint128, account)`; two or more build one Midnight
27
+ * core `multicall` of those calls, which cancels every group or none. The transaction never targets
28
+ * MidnightBundlesV2, so it builds on every chain with a Midnight deployment. `account`, or an
29
+ * operator it authorized on Midnight, must send it. Validates the groups with the same parse
30
+ * constructor as the entity `cancelOffers`, in the same order. Expiry is plan metadata, not an
31
+ * onchain deadline.
32
+ * @param client - Client used to validate the chain and Midnight core code, not retained by the plan.
33
+ * @param params.chainId - Chain containing the Midnight deployment.
34
+ * @param params.account - Non-zero maker whose groups are cancelled.
35
+ * @param params.groups - Nonempty list of distinct 32-byte offer groups.
36
+ * @param params.now - Reference Unix timestamp in seconds; omitting it uses the device clock (an untyped JavaScript `null` does too).
37
+ * @param params.expiresAt - Expiry in Unix seconds, later than `now`; defaults to `now + 2h`.
38
+ * @param params.calldataOrigin - Optional non-empty hex bytes appended to the built transaction.
39
+ * @returns A deep-frozen plan with one `midnightCancelOffers` step and no signature requests.
40
+ * @throws {InvalidBigIntInputError} when a supplied non-null `now` is not a bigint.
41
+ * @throws {ZeroAccountError} when `account` is the zero address.
42
+ * @throws {InvalidTransactionPlanError} when `account` is malformed or `calldataOrigin` exceeds 1 MiB.
43
+ * @throws {NonIntegerInputError} when `expiresAt` is not a safe integer.
44
+ * @throws {NonPositiveInputError} when `expiresAt` is not positive.
45
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before the reference time.
46
+ * @throws {InvalidCalldataOriginError} when attribution bytes are empty or malformed.
47
+ * @throws {EmptyMidnightGroupCancellationsError} when `groups` is empty.
48
+ * @throws {InvalidMidnightHexInputError} when a group is not 32-byte hex.
49
+ * @throws {DuplicateMidnightGroupCancellationError} when a group appears more than once.
50
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
51
+ * @throws {UnknownAddressError} when the chain has no `midnight` deployment.
52
+ * @throws {ChainIdMismatchError} when the client declares or serves another chain.
53
+ * @throws {MissingContractCodeError} when the registered Midnight core has no deployed code.
54
+ * @throws {viem.BaseError} when the RPC chain ID or bytecode read fails.
55
+ * @example
56
+ * ```ts
57
+ * import { buildTransactions, prepareMidnightCancelOffers } from "@morpho-org/morpho-sdk";
58
+ * import { createPublicClient, http, type Address, type Hex } from "viem";
59
+ * import { base } from "viem/chains";
60
+ *
61
+ * declare const maker: Address;
62
+ * declare const group: Hex;
63
+ * const client = createPublicClient({ chain: base, transport: http() });
64
+ * const plan = await prepareMidnightCancelOffers(client, {
65
+ * chainId: base.id,
66
+ * account: maker,
67
+ * groups: [group],
68
+ * now: (await client.getBlock()).timestamp,
69
+ * });
70
+ * // One transaction: setConsumed(group, maxUint128, maker) on Midnight.
71
+ * const [tx] = buildTransactions(plan);
72
+ * ```
73
+ */
74
+ export declare function prepareMidnightCancelOffers(client: Client, params: MidnightCancelOffersPlanParams): Promise<TransactionPlan>;
75
+ /** @internal Validates the stored cancellation's plain input shape. */
76
+ export declare function validateMidnightCancelOffersPlanAction(action: Record<string, unknown>, path: string): void;
77
+ /** @internal Encodes the stored cancellation through the same action as `cancelOffers`. */
78
+ export declare function buildMidnightCancelOffers(action: Extract<Action, {
79
+ type: "midnightCancelOffers";
80
+ }>): Readonly<Transaction<MidnightCancelOffersAction>>;