@morpho-org/morpho-sdk 10.4.0 → 10.5.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 (193) hide show
  1. package/lib/cjs/actions/blue/common.js +12 -3
  2. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +16 -11
  3. package/lib/cjs/actions/midnight/takeBorrow.js +14 -8
  4. package/lib/cjs/actions/midnight/takeLend.js +15 -9
  5. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +19 -13
  6. package/lib/cjs/actions/midnight/takeWithdraw.js +14 -8
  7. package/lib/cjs/constants.d.ts +1 -1
  8. package/lib/cjs/constants.js +3 -2
  9. package/lib/cjs/entities/midnight/midnight.d.ts +106 -103
  10. package/lib/cjs/entities/midnight/midnight.js +120 -101
  11. package/lib/cjs/entities/vaultV1/vaultV1.js +0 -1
  12. package/lib/cjs/entities/vaultV2/vaultV2.js +0 -1
  13. package/lib/cjs/helpers/constant.d.ts +7 -0
  14. package/lib/cjs/helpers/constant.js +8 -1
  15. package/lib/cjs/helpers/index.d.ts +1 -1
  16. package/lib/cjs/helpers/index.js +2 -1
  17. package/lib/cjs/helpers/validate.d.ts +25 -1
  18. package/lib/cjs/helpers/validate.js +25 -1
  19. package/lib/cjs/transactionPlan/assemble.d.ts +24 -0
  20. package/lib/cjs/transactionPlan/assemble.js +25 -0
  21. package/lib/cjs/transactionPlan/blue/borrow.js +14 -64
  22. package/lib/cjs/transactionPlan/blue/refinance.js +9 -11
  23. package/lib/cjs/transactionPlan/blue/repay.js +10 -24
  24. package/lib/cjs/transactionPlan/blue/repayWithdrawCollateral.js +49 -45
  25. package/lib/cjs/transactionPlan/blue/stored.d.ts +26 -0
  26. package/lib/cjs/transactionPlan/blue/stored.js +87 -0
  27. package/lib/cjs/transactionPlan/blue/supply.js +7 -22
  28. package/lib/cjs/transactionPlan/blue/supplyCollateral.d.ts +1 -1
  29. package/lib/cjs/transactionPlan/blue/supplyCollateral.js +10 -15
  30. package/lib/cjs/transactionPlan/blue/supplyCollateralBorrow.js +14 -64
  31. package/lib/cjs/transactionPlan/blue/withdraw.d.ts +2 -3
  32. package/lib/cjs/transactionPlan/blue/withdraw.js +67 -79
  33. package/lib/cjs/transactionPlan/blue/withdrawCollateral.d.ts +2 -3
  34. package/lib/cjs/transactionPlan/blue/withdrawCollateral.js +31 -30
  35. package/lib/cjs/transactionPlan/deposit.js +4 -7
  36. package/lib/cjs/transactionPlan/intent.d.ts +1 -1
  37. package/lib/cjs/transactionPlan/midnight/makeBorrow.d.ts +1 -1
  38. package/lib/cjs/transactionPlan/midnight/makeBorrow.js +1 -1
  39. package/lib/cjs/transactionPlan/midnight/makeLend.d.ts +1 -1
  40. package/lib/cjs/transactionPlan/midnight/makeLend.js +1 -1
  41. package/lib/cjs/transactionPlan/midnight/makeRepay.d.ts +1 -1
  42. package/lib/cjs/transactionPlan/midnight/makeRepay.js +1 -1
  43. package/lib/cjs/transactionPlan/midnight/repayWithdrawCollateral.d.ts +1 -1
  44. package/lib/cjs/transactionPlan/midnight/repayWithdrawCollateral.js +1 -1
  45. package/lib/cjs/transactionPlan/midnight/supplyBlueMakeLend.d.ts +1 -1
  46. package/lib/cjs/transactionPlan/midnight/supplyBlueMakeLend.js +1 -1
  47. package/lib/cjs/transactionPlan/midnight/supplyCollateral.d.ts +1 -1
  48. package/lib/cjs/transactionPlan/midnight/supplyCollateral.js +1 -1
  49. package/lib/cjs/transactionPlan/midnight/supplyCollateralBatch.d.ts +1 -1
  50. package/lib/cjs/transactionPlan/midnight/supplyCollateralBatch.js +1 -1
  51. package/lib/cjs/transactionPlan/midnight/supplyCollateralMakeBorrow.d.ts +1 -1
  52. package/lib/cjs/transactionPlan/midnight/supplyCollateralMakeBorrow.js +1 -1
  53. package/lib/cjs/transactionPlan/midnight/supplyCollateralWithNative.d.ts +1 -1
  54. package/lib/cjs/transactionPlan/midnight/supplyCollateralWithNative.js +1 -1
  55. package/lib/cjs/transactionPlan/midnight/takeBorrow.d.ts +6 -2
  56. package/lib/cjs/transactionPlan/midnight/takeBorrow.js +10 -4
  57. package/lib/cjs/transactionPlan/midnight/takeRepayWithdrawCollateral.d.ts +1 -1
  58. package/lib/cjs/transactionPlan/midnight/takeRepayWithdrawCollateral.js +1 -1
  59. package/lib/cjs/transactionPlan/midnight/takeWithdraw.d.ts +1 -1
  60. package/lib/cjs/transactionPlan/midnight/takeWithdraw.js +1 -1
  61. package/lib/cjs/transactionPlan/permit.d.ts +15 -2
  62. package/lib/cjs/transactionPlan/permit.js +26 -68
  63. package/lib/cjs/transactionPlan/plan.d.ts +51 -1
  64. package/lib/cjs/transactionPlan/plan.js +56 -13
  65. package/lib/cjs/transactionPlan/redeem.js +4 -7
  66. package/lib/cjs/transactionPlan/types.d.ts +4 -3
  67. package/lib/cjs/transactionPlan/vaultBinding.d.ts +29 -0
  68. package/lib/cjs/transactionPlan/vaultBinding.js +69 -0
  69. package/lib/cjs/transactionPlan/vaultRequirements.d.ts +20 -0
  70. package/lib/cjs/transactionPlan/vaultRequirements.js +37 -0
  71. package/lib/cjs/transactionPlan/vaultv1/deposit.d.ts +1 -1
  72. package/lib/cjs/transactionPlan/vaultv1/deposit.js +2 -13
  73. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.d.ts +2 -2
  74. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.js +10 -41
  75. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.d.ts +1 -1
  76. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.js +6 -18
  77. package/lib/cjs/transactionPlan/vaultv1/redeem.js +1 -12
  78. package/lib/cjs/transactionPlan/vaultv1/withdraw.d.ts +1 -1
  79. package/lib/cjs/transactionPlan/vaultv1/withdraw.js +2 -13
  80. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +1 -1
  81. package/lib/cjs/transactionPlan/vaultv2/deposit.js +2 -13
  82. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.d.ts +1 -1
  83. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.js +4 -7
  84. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.d.ts +2 -2
  85. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.js +12 -42
  86. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.d.ts +2 -2
  87. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.js +10 -41
  88. package/lib/cjs/transactionPlan/vaultv2/redeem.d.ts +1 -1
  89. package/lib/cjs/transactionPlan/vaultv2/redeem.js +2 -13
  90. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +1 -1
  91. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +2 -13
  92. package/lib/cjs/transactionPlan/withdraw.js +4 -7
  93. package/lib/cjs/types/error.d.ts +27 -1
  94. package/lib/cjs/types/error.js +32 -3
  95. package/lib/cjs/version.d.ts +1 -1
  96. package/lib/cjs/version.js +1 -1
  97. package/lib/esm/actions/blue/common.js +13 -4
  98. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +16 -11
  99. package/lib/esm/actions/midnight/takeBorrow.js +14 -8
  100. package/lib/esm/actions/midnight/takeLend.js +15 -9
  101. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +19 -13
  102. package/lib/esm/actions/midnight/takeWithdraw.js +14 -8
  103. package/lib/esm/constants.d.ts +1 -1
  104. package/lib/esm/constants.js +1 -1
  105. package/lib/esm/entities/midnight/midnight.d.ts +106 -103
  106. package/lib/esm/entities/midnight/midnight.js +120 -101
  107. package/lib/esm/entities/vaultV1/vaultV1.js +0 -1
  108. package/lib/esm/entities/vaultV2/vaultV2.js +0 -1
  109. package/lib/esm/helpers/constant.d.ts +7 -0
  110. package/lib/esm/helpers/constant.js +7 -0
  111. package/lib/esm/helpers/index.d.ts +1 -1
  112. package/lib/esm/helpers/index.js +1 -1
  113. package/lib/esm/helpers/validate.d.ts +25 -1
  114. package/lib/esm/helpers/validate.js +25 -2
  115. package/lib/esm/transactionPlan/assemble.d.ts +24 -0
  116. package/lib/esm/transactionPlan/assemble.js +21 -0
  117. package/lib/esm/transactionPlan/blue/borrow.js +15 -65
  118. package/lib/esm/transactionPlan/blue/refinance.js +10 -12
  119. package/lib/esm/transactionPlan/blue/repay.js +11 -25
  120. package/lib/esm/transactionPlan/blue/repayWithdrawCollateral.js +50 -46
  121. package/lib/esm/transactionPlan/blue/stored.d.ts +26 -0
  122. package/lib/esm/transactionPlan/blue/stored.js +80 -0
  123. package/lib/esm/transactionPlan/blue/supply.js +7 -22
  124. package/lib/esm/transactionPlan/blue/supplyCollateral.d.ts +1 -1
  125. package/lib/esm/transactionPlan/blue/supplyCollateral.js +10 -15
  126. package/lib/esm/transactionPlan/blue/supplyCollateralBorrow.js +15 -65
  127. package/lib/esm/transactionPlan/blue/withdraw.d.ts +2 -3
  128. package/lib/esm/transactionPlan/blue/withdraw.js +70 -82
  129. package/lib/esm/transactionPlan/blue/withdrawCollateral.d.ts +2 -3
  130. package/lib/esm/transactionPlan/blue/withdrawCollateral.js +32 -31
  131. package/lib/esm/transactionPlan/deposit.js +5 -8
  132. package/lib/esm/transactionPlan/intent.d.ts +1 -1
  133. package/lib/esm/transactionPlan/midnight/makeBorrow.d.ts +1 -1
  134. package/lib/esm/transactionPlan/midnight/makeBorrow.js +1 -1
  135. package/lib/esm/transactionPlan/midnight/makeLend.d.ts +1 -1
  136. package/lib/esm/transactionPlan/midnight/makeLend.js +1 -1
  137. package/lib/esm/transactionPlan/midnight/makeRepay.d.ts +1 -1
  138. package/lib/esm/transactionPlan/midnight/makeRepay.js +1 -1
  139. package/lib/esm/transactionPlan/midnight/repayWithdrawCollateral.d.ts +1 -1
  140. package/lib/esm/transactionPlan/midnight/repayWithdrawCollateral.js +1 -1
  141. package/lib/esm/transactionPlan/midnight/supplyBlueMakeLend.d.ts +1 -1
  142. package/lib/esm/transactionPlan/midnight/supplyBlueMakeLend.js +1 -1
  143. package/lib/esm/transactionPlan/midnight/supplyCollateral.d.ts +1 -1
  144. package/lib/esm/transactionPlan/midnight/supplyCollateral.js +1 -1
  145. package/lib/esm/transactionPlan/midnight/supplyCollateralBatch.d.ts +1 -1
  146. package/lib/esm/transactionPlan/midnight/supplyCollateralBatch.js +1 -1
  147. package/lib/esm/transactionPlan/midnight/supplyCollateralMakeBorrow.d.ts +1 -1
  148. package/lib/esm/transactionPlan/midnight/supplyCollateralMakeBorrow.js +1 -1
  149. package/lib/esm/transactionPlan/midnight/supplyCollateralWithNative.d.ts +1 -1
  150. package/lib/esm/transactionPlan/midnight/supplyCollateralWithNative.js +1 -1
  151. package/lib/esm/transactionPlan/midnight/takeBorrow.d.ts +6 -2
  152. package/lib/esm/transactionPlan/midnight/takeBorrow.js +11 -5
  153. package/lib/esm/transactionPlan/midnight/takeRepayWithdrawCollateral.d.ts +1 -1
  154. package/lib/esm/transactionPlan/midnight/takeRepayWithdrawCollateral.js +1 -1
  155. package/lib/esm/transactionPlan/midnight/takeWithdraw.d.ts +1 -1
  156. package/lib/esm/transactionPlan/midnight/takeWithdraw.js +1 -1
  157. package/lib/esm/transactionPlan/permit.d.ts +15 -2
  158. package/lib/esm/transactionPlan/permit.js +25 -68
  159. package/lib/esm/transactionPlan/plan.d.ts +51 -1
  160. package/lib/esm/transactionPlan/plan.js +55 -13
  161. package/lib/esm/transactionPlan/redeem.js +5 -8
  162. package/lib/esm/transactionPlan/types.d.ts +4 -3
  163. package/lib/esm/transactionPlan/vaultBinding.d.ts +29 -0
  164. package/lib/esm/transactionPlan/vaultBinding.js +65 -0
  165. package/lib/esm/transactionPlan/vaultRequirements.d.ts +20 -0
  166. package/lib/esm/transactionPlan/vaultRequirements.js +34 -0
  167. package/lib/esm/transactionPlan/vaultv1/deposit.d.ts +1 -1
  168. package/lib/esm/transactionPlan/vaultv1/deposit.js +3 -14
  169. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.d.ts +2 -2
  170. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.js +12 -43
  171. package/lib/esm/transactionPlan/vaultv1/migrateToV2.d.ts +1 -1
  172. package/lib/esm/transactionPlan/vaultv1/migrateToV2.js +9 -21
  173. package/lib/esm/transactionPlan/vaultv1/redeem.js +2 -13
  174. package/lib/esm/transactionPlan/vaultv1/withdraw.d.ts +1 -1
  175. package/lib/esm/transactionPlan/vaultv1/withdraw.js +3 -14
  176. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +1 -1
  177. package/lib/esm/transactionPlan/vaultv2/deposit.js +3 -14
  178. package/lib/esm/transactionPlan/vaultv2/forceRedeem.d.ts +1 -1
  179. package/lib/esm/transactionPlan/vaultv2/forceRedeem.js +5 -8
  180. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.d.ts +2 -2
  181. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.js +15 -45
  182. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.d.ts +2 -2
  183. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.js +12 -43
  184. package/lib/esm/transactionPlan/vaultv2/redeem.d.ts +1 -1
  185. package/lib/esm/transactionPlan/vaultv2/redeem.js +3 -14
  186. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +1 -1
  187. package/lib/esm/transactionPlan/vaultv2/withdraw.js +3 -14
  188. package/lib/esm/transactionPlan/withdraw.js +5 -8
  189. package/lib/esm/types/error.d.ts +27 -1
  190. package/lib/esm/types/error.js +30 -2
  191. package/lib/esm/version.d.ts +1 -1
  192. package/lib/esm/version.js +1 -1
  193. package/package.json +3 -3
@@ -0,0 +1,24 @@
1
+ import type { Address } from "viem";
2
+ import type { Intent } from "./intent.js";
3
+ import type { TransactionPlan } from "./types.js";
4
+ /**
5
+ * @internal The stored plan header: version, chain, account, expiry, and the calldata origin when
6
+ * the intent has one.
7
+ */
8
+ export declare function planHeader({ chainId, account }: {
9
+ readonly chainId: number;
10
+ readonly account: Address;
11
+ }, { expiresAt, calldataOrigin }: Pick<Intent, "expiresAt" | "calldataOrigin">): {
12
+ readonly version: 2;
13
+ readonly chainId: number;
14
+ readonly account: `0x${string}`;
15
+ readonly expiresAt: number;
16
+ readonly calldataOrigin?: `0x${string}` | undefined;
17
+ };
18
+ /**
19
+ * @internal Deeply freezes a prepared plan. `detach` copies it first, so no object the caller
20
+ * passed in is frozen or shared with the plan.
21
+ */
22
+ export declare function freezePlan(plan: TransactionPlan, { detach }: {
23
+ readonly detach: boolean;
24
+ }): TransactionPlan;
@@ -0,0 +1,21 @@
1
+ import { deepFreeze } from "@morpho-org/morpho-ts";
2
+ /**
3
+ * @internal The stored plan header: version, chain, account, expiry, and the calldata origin when
4
+ * the intent has one.
5
+ */
6
+ export function planHeader({ chainId, account }, { expiresAt, calldataOrigin }) {
7
+ return {
8
+ version: 2,
9
+ chainId,
10
+ account,
11
+ expiresAt,
12
+ ...(calldataOrigin && { calldataOrigin }),
13
+ };
14
+ }
15
+ /**
16
+ * @internal Deeply freezes a prepared plan. `detach` copies it first, so no object the caller
17
+ * passed in is frozen or shared with the plan.
18
+ */
19
+ export function freezePlan(plan, { detach }) {
20
+ return deepFreeze(detach ? structuredClone(plan) : plan);
21
+ }
@@ -1,12 +1,14 @@
1
- import { deepFreeze, MathLib, Time } from "@morpho-org/morpho-ts";
1
+ import { MathLib, Time } from "@morpho-org/morpho-ts";
2
2
  import { blueBorrow } from "../../actions/blue/borrow.js";
3
3
  import { normalizeBundlesCommonParams } from "../../actions/bundles/common.js";
4
4
  import { getBlueBundlesV1QuoteTimestamp } from "../../helpers/getBlueBundlesV1QuoteTimestamp.js";
5
5
  import { DEFAULT_LLTV_BUFFER } from "../../helpers/index.js";
6
6
  import { validatePositionHealth } from "../../helpers/validate.js";
7
+ import { freezePlan, planHeader } from "../assemble.js";
7
8
  import { IncompleteTransactionPlanError, InvalidTransactionPlanError, } from "../error.js";
8
9
  import { getPlanObject, validatePlanField, validatePlanFields, } from "../validation.js";
9
10
  import { prepareBlue, } from "./prepare.js";
11
+ import { BUNDLES_COMMON_FIELDS, signatureRoles, validateStoredBlueMarket, validateStoredReallocations, } from "./stored.js";
10
12
  /**
11
13
  * Prepares a BlueBundlesV1 borrow against existing collateral. No token allowance is needed.
12
14
  * Health uses the expiry, floored at max(now, lastUpdate), like the entity handle.
@@ -118,12 +120,8 @@ export async function prepareBlueBorrow(client, { chainId, account, marketId, ma
118
120
  reason: "expected prepared borrow inputs",
119
121
  });
120
122
  }
121
- return deepFreeze(structuredClone({
122
- version: 2,
123
- account: inputs.account,
124
- chainId: inputs.chainId,
125
- expiresAt: intent.expiresAt,
126
- ...(intent.calldataOrigin && { calldataOrigin: intent.calldataOrigin }),
123
+ return freezePlan({
124
+ ...planHeader({ chainId: inputs.chainId, account: inputs.account }, intent),
127
125
  steps: [
128
126
  ...steps,
129
127
  {
@@ -135,14 +133,14 @@ export async function prepareBlueBorrow(client, { chainId, account, marketId, ma
135
133
  ...inputs,
136
134
  authorizationNonce: signatureRequests.find((request) => request.id === morphoAuthorizationRequestId)?.args.nonce ?? 0n,
137
135
  },
138
- signatureRequestIds: morphoAuthorizationRequestId
139
- ? { morphoAuthorization: morphoAuthorizationRequestId }
140
- : {},
136
+ signatureRequestIds: signatureRoles({
137
+ morphoAuthorization: morphoAuthorizationRequestId,
138
+ }),
141
139
  },
142
140
  },
143
141
  ],
144
142
  signatureRequests,
145
- }));
143
+ }, { detach: true });
146
144
  }
147
145
  /** @internal Encodes a prepared borrow without state reads or signing. */
148
146
  export function buildBlueBorrow(action, requests) {
@@ -185,26 +183,6 @@ export function buildBlueBorrow(action, requests) {
185
183
  },
186
184
  });
187
185
  }
188
- function validateMarket(value, path) {
189
- const market = getPlanObject(value, path);
190
- validatePlanFields(market, {
191
- path,
192
- fields: {
193
- id: "hex",
194
- loanToken: "address",
195
- collateralToken: "address",
196
- oracle: "address",
197
- irm: "address",
198
- lltv: "uint256 bigint",
199
- },
200
- });
201
- if (typeof market.id !== "string" || market.id.length !== 66) {
202
- throw new InvalidTransactionPlanError({
203
- path: `${path}.id`,
204
- reason: "expected a 32-byte market ID",
205
- });
206
- }
207
- }
208
186
  /** @internal Validates the stored borrow recipe, including each allocator input. */
209
187
  export function validateBorrowPlanAction(action, path) {
210
188
  const inputs = getPlanObject(action.inputs, `${path}.inputs`);
@@ -215,47 +193,19 @@ export function validateBorrowPlanAction(action, path) {
215
193
  borrowAssets: "uint256 bigint",
216
194
  authorizationNonce: "uint256 bigint",
217
195
  maxLtv: "uint256 bigint",
218
- deadline: "uint256 bigint",
219
- referralFeePct: "uint256 bigint",
220
- referralFeeRecipient: "address",
196
+ ...BUNDLES_COMMON_FIELDS,
221
197
  reallocations: "array",
222
198
  },
223
199
  });
224
- validateMarket(inputs.marketParams, `${path}.inputs.marketParams`);
200
+ validateStoredBlueMarket(inputs.marketParams, `${path}.inputs.marketParams`);
225
201
  if (inputs.maxPenalty !== undefined) {
226
202
  validatePlanField(inputs.maxPenalty, {
227
203
  path: `${path}.inputs.maxPenalty`,
228
204
  type: "uint256 bigint",
229
205
  });
230
206
  }
231
- for (const [index, value] of inputs.reallocations.entries()) {
232
- const entryPath = `${path}.inputs.reallocations[${index}]`;
233
- const entry = getPlanObject(value, entryPath);
234
- validatePlanFields(entry, {
235
- path: entryPath,
236
- fields: {
237
- vault: "address",
238
- assets: "uint256 bigint",
239
- penalty: "uint256 bigint",
240
- },
241
- });
242
- validatePlanFields(getPlanObject(entry.to, `${entryPath}.to`), {
243
- path: `${entryPath}.to`,
244
- fields: { adapter: "address" },
245
- });
246
- const from = getPlanObject(entry.from, `${entryPath}.from`);
247
- if (from.type !== "market" && from.type !== "idle") {
248
- throw new InvalidTransactionPlanError({
249
- path: `${entryPath}.from.type`,
250
- reason: "expected market or idle",
251
- });
252
- }
253
- if (from.type === "market") {
254
- validatePlanFields(from, {
255
- path: `${entryPath}.from`,
256
- fields: { adapter: "address" },
257
- });
258
- validateMarket(from.marketParams, `${entryPath}.from.marketParams`);
259
- }
260
- }
207
+ validateStoredReallocations(inputs.reallocations, {
208
+ path: `${path}.inputs.reallocations`,
209
+ marketParams: validateStoredBlueMarket,
210
+ });
261
211
  }
@@ -1,14 +1,16 @@
1
1
  import { MathLib, } from "@morpho-org/blue-sdk";
2
- import { deepFreeze, Time } from "@morpho-org/morpho-ts";
2
+ import { Time } from "@morpho-org/morpho-ts";
3
3
  import { parseBlueAllocations, parseBlueBundlesV1Common, } from "../../actions/blue/common.js";
4
4
  import { blueRefinance } from "../../actions/blue/refinance.js";
5
5
  import { validateBlueRefinanceQuote, validateBlueRefinanceSource, } from "../../actions/blue/refinanceValidation.js";
6
6
  import { DEFAULT_LLTV_BUFFER } from "../../helpers/index.js";
7
7
  import { parseBlueMarket } from "../../helpers/parse.js";
8
+ import { freezePlan, planHeader } from "../assemble.js";
8
9
  import { IncompleteTransactionPlanError, InvalidTransactionPlanError, } from "../error.js";
9
10
  import { getPlanObject, validatePlanField, validatePlanFields, } from "../validation.js";
10
11
  import { prepareBlue, } from "./prepare.js";
11
12
  import { validateBlueRefinanceDestination } from "./refinanceValidation.js";
13
+ import { BUNDLES_COMMON_FIELDS, signatureRoles } from "./stored.js";
12
14
  /**
13
15
  * Prepares a full Blue borrow-position migration. Fetch both market and position snapshots at the
14
16
  * same block and pass that block's timestamp as `now`. Penalties and fees increase destination debt;
@@ -152,20 +154,18 @@ export async function prepareBlueRefinance(client, params) {
152
154
  ...(maxPenalty !== undefined && { maxPenalty }),
153
155
  ...(request && { authorizationNonce: request.args.nonce }),
154
156
  },
155
- signatureRequestIds: request === undefined ? {} : { morphoAuthorization: request.id },
157
+ signatureRequestIds: signatureRoles({
158
+ morphoAuthorization: request?.id,
159
+ }),
156
160
  };
157
- return deepFreeze(structuredClone({
158
- version: 2,
159
- account,
160
- chainId,
161
- expiresAt: intent.expiresAt,
162
- ...(intent.calldataOrigin && { calldataOrigin: intent.calldataOrigin }),
161
+ return freezePlan({
162
+ ...planHeader({ chainId, account }, intent),
163
163
  steps: [
164
164
  ...steps,
165
165
  { id, label: "Refinance Blue borrow position", action },
166
166
  ],
167
167
  signatureRequests,
168
- }));
168
+ }, { detach: true });
169
169
  }
170
170
  function validatePlanMarketParams(value, path) {
171
171
  const params = getPlanObject(value, path);
@@ -241,9 +241,7 @@ export function validateRefinancePlanAction(action, path) {
241
241
  path: `${path}.inputs`,
242
242
  fields: {
243
243
  maxLtv: "uint256 bigint",
244
- deadline: "uint256 bigint",
245
- referralFeePct: "uint256 bigint",
246
- referralFeeRecipient: "address",
244
+ ...BUNDLES_COMMON_FIELDS,
247
245
  reallocations: "array",
248
246
  },
249
247
  });
@@ -1,5 +1,5 @@
1
1
  import { AccrualPosition, MarketParams, } from "@morpho-org/blue-sdk";
2
- import { deepFreeze, Time } from "@morpho-org/morpho-ts";
2
+ import { Time } from "@morpho-org/morpho-ts";
3
3
  import { maxUint256 } from "viem";
4
4
  import { getBlueBundlesV1ReferralFeeAssets } from "../../actions/blue/common.js";
5
5
  import { blueRepay } from "../../actions/blue/repay.js";
@@ -8,10 +8,12 @@ import { parseNativeFunding } from "../../helpers/parse.js";
8
8
  import { quoteBlueRepayFunding } from "../../helpers/quoteBlueRepay.js";
9
9
  import { validateReferralFee } from "../../helpers/validate.js";
10
10
  import { NonPositiveInputError } from "../../types/index.js";
11
+ import { freezePlan, planHeader } from "../assemble.js";
11
12
  import { InvalidTransactionPlanError, TransactionPlanSignatureMismatchError, } from "../error.js";
12
13
  import { getVaultPermit, validateTokenPermitRequest } from "../permit.js";
13
14
  import { getPlanObject, validatePlanFields } from "../validation.js";
14
15
  import { prepareBlue, } from "./prepare.js";
16
+ import { BUNDLES_COMMON_FIELDS, signatureRoles, validateStoredBlueMarketParams, } from "./stored.js";
15
17
  /**
16
18
  * Prepares an asset, share, or full Blue repayment through BlueBundlesV1, never Permit2.
17
19
  * Share quotes accrue the supplied position to expiry, at most two hours from the reference time.
@@ -133,12 +135,8 @@ export async function prepareBlueRepay(client, { chainId, account, marketId, mar
133
135
  reason: "expected resolved repayment inputs",
134
136
  });
135
137
  }
136
- return deepFreeze(structuredClone({
137
- version: 2,
138
- chainId: params.chainId,
139
- account: params.account,
140
- expiresAt: resolvedIntent.expiresAt,
141
- calldataOrigin: resolvedIntent.calldataOrigin,
138
+ return freezePlan({
139
+ ...planHeader({ chainId: params.chainId, account: params.account }, resolvedIntent),
142
140
  steps: [
143
141
  ...steps,
144
142
  {
@@ -147,14 +145,14 @@ export async function prepareBlueRepay(client, { chainId, account, marketId, mar
147
145
  action: {
148
146
  type: "blueRepay",
149
147
  inputs,
150
- signatureRequestIds: signatureRequests.length
151
- ? { tokenPermit: signatureRequests[0]?.id }
152
- : {},
148
+ signatureRequestIds: signatureRoles({
149
+ tokenPermit: signatureRequests[0]?.id,
150
+ }),
153
151
  },
154
152
  },
155
153
  ],
156
154
  signatureRequests,
157
- }));
155
+ }, { detach: true });
158
156
  }
159
157
  /** @internal Checks a repayment permit against the fixed token pull. */
160
158
  export function validateBlueRepayPermit(request, action) {
@@ -197,9 +195,7 @@ export function validateBlueRepayPlanAction(action, path) {
197
195
  repayAssets: "uint256 bigint",
198
196
  repayShares: "uint256 bigint",
199
197
  maxRepayAssets: "uint256 bigint",
200
- deadline: "uint256 bigint",
201
- referralFeePct: "uint256 bigint",
202
- referralFeeRecipient: "address",
198
+ ...BUNDLES_COMMON_FIELDS,
203
199
  },
204
200
  });
205
201
  if (inputs.nativeAssets !== undefined) {
@@ -208,16 +204,6 @@ export function validateBlueRepayPlanAction(action, path) {
208
204
  fields: { nativeAssets: "uint256 bigint" },
209
205
  });
210
206
  }
211
- const market = getPlanObject(inputs.marketParams, `${path}.inputs.marketParams`);
212
- validatePlanFields(market, {
213
- path: `${path}.inputs.marketParams`,
214
- fields: {
215
- loanToken: "address",
216
- collateralToken: "address",
217
- oracle: "address",
218
- irm: "address",
219
- lltv: "uint256 bigint",
220
- },
221
- });
207
+ validateStoredBlueMarketParams(inputs.marketParams, `${path}.inputs.marketParams`);
222
208
  getPlanObject(action.signatureRequestIds, `${path}.signatureRequestIds`);
223
209
  }
@@ -1,5 +1,5 @@
1
1
  import { AccrualPosition, MarketParams, MathLib, } from "@morpho-org/blue-sdk";
2
- import { deepFreeze, Time } from "@morpho-org/morpho-ts";
2
+ import { Time } from "@morpho-org/morpho-ts";
3
3
  import { maxUint256 } from "viem";
4
4
  import { getBlueBundlesV1ReferralFeeAssets, parseBlueBundlesV1Common, } from "../../actions/blue/common.js";
5
5
  import { blueRepayWithdrawCollateral } from "../../actions/blue/repayWithdrawCollateral.js";
@@ -9,11 +9,13 @@ import { DEFAULT_LLTV_BUFFER, validateChainId, validatePositionHealthAfterWithdr
9
9
  import { parseNativeFunding } from "../../helpers/parse.js";
10
10
  import { quoteBlueRepay, quoteBlueRepayFunding, } from "../../helpers/quoteBlueRepay.js";
11
11
  import { MutuallyExclusiveRepayAmountsError, NegativeInputError, NonPositiveInputError, } from "../../types/index.js";
12
+ import { freezePlan, planHeader } from "../assemble.js";
12
13
  import { BlueSnapshotStateMismatchError, IncompleteTransactionPlanError, InvalidTransactionPlanError, TransactionPlanSignatureMismatchError, } from "../error.js";
13
14
  import { getVaultPermit, validateTokenPermitRequest } from "../permit.js";
14
15
  import { getPlanObject, validatePlanFields } from "../validation.js";
15
16
  import { validateMorphoAuthorizationRequest } from "./authorization.js";
16
17
  import { prepareBlue, } from "./prepare.js";
18
+ import { BUNDLES_COMMON_FIELDS, signatureRoles, validateStoredBlueMarketParams, } from "./stored.js";
17
19
  /**
18
20
  * Prepares one BlueBundlesV1 repayment and collateral withdrawal from caller-fetched snapshots.
19
21
  * Withdrawal health uses the expiry floored at max(now, lastUpdate); expiries more than
@@ -73,23 +75,24 @@ import { prepareBlue, } from "./prepare.js";
73
75
  */
74
76
  export async function prepareBlueRepayWithdrawCollateral(client, params) {
75
77
  const id = "blueRepayWithdrawCollateral";
76
- const now = params.now ?? Time.timestamp();
78
+ const captured = captureRepayWithdrawInputs(params);
79
+ const { chainId, account, marketId, marketData, now } = captured;
77
80
  let inputs;
78
- const prepared = await prepareBlue({ client, params: { ...params, now } }, (intent) => {
79
- const marketParams = params.marketData.market.params;
81
+ const prepared = await prepareBlue({ client, params: captured }, (intent) => {
82
+ const marketParams = marketData.market.params;
80
83
  // Reject chain and referral mismatches before deriving a repayment quote.
81
- validateChainId(client.chain?.id, params.chainId);
84
+ validateChainId(client.chain?.id, chainId);
82
85
  const common = parseBlueBundlesV1Common({
83
- chainId: params.chainId,
84
- userAddress: params.account,
86
+ chainId,
87
+ userAddress: account,
85
88
  deadline: intent.deadline,
86
89
  referralFeePct: intent.referralFeePct,
87
90
  referralFeeRecipient: intent.referralFeeRecipient,
88
91
  });
89
- const { repayAssets, repayShares, collateralAssets, hasRepay } = getRepayWithdrawAmounts(params);
92
+ const { repayAssets, repayShares, collateralAssets, hasRepay } = getRepayWithdrawAmounts(params, marketId);
90
93
  const quoteParams = {
91
- positionData: getMatchingPosition(params),
92
- marketId: params.marketId,
94
+ positionData: getMatchingPosition(captured),
95
+ marketId,
93
96
  repayAssets,
94
97
  repayShares,
95
98
  deadline: intent.deadline,
@@ -100,7 +103,7 @@ export async function prepareBlueRepayWithdrawCollateral(client, params) {
100
103
  const maxRepayAssets = expectedRepayAssets +
101
104
  getBlueBundlesV1ReferralFeeAssets(expectedRepayAssets, common.referralFeePct);
102
105
  const nativeValue = parseNativeFunding({
103
- chainId: params.chainId,
106
+ chainId,
104
107
  token: marketParams.loanToken,
105
108
  fundedAmount: maxRepayAssets,
106
109
  nativeAmount: params.funding?.type === "native" ? maxRepayAssets : undefined,
@@ -115,13 +118,13 @@ export async function prepareBlueRepayWithdrawCollateral(client, params) {
115
118
  positionData: postRepayPosition,
116
119
  withdrawAmount: collateralAssets,
117
120
  lltv: marketParams.lltv,
118
- marketId: params.marketData.market.id,
121
+ marketId,
119
122
  });
120
123
  }
121
124
  const tx = blueRepayWithdrawCollateral({
122
- market: { chainId: params.chainId, marketParams },
125
+ market: { chainId, marketParams },
123
126
  args: {
124
- userAddress: params.account,
127
+ userAddress: account,
125
128
  repayAssets,
126
129
  repayShares,
127
130
  maxRepayAssets,
@@ -137,8 +140,8 @@ export async function prepareBlueRepayWithdrawCollateral(client, params) {
137
140
  inputs = {
138
141
  ...args,
139
142
  ...(nativeAmount !== undefined && { nativeAssets: nativeAmount }),
140
- chainId: params.chainId,
141
- account: params.account,
143
+ chainId,
144
+ account,
142
145
  marketParams: {
143
146
  loanToken: marketParams.loanToken,
144
147
  collateralToken: marketParams.collateralToken,
@@ -155,27 +158,20 @@ export async function prepareBlueRepayWithdrawCollateral(client, params) {
155
158
  needsAuthorization: args.collateralAssets > 0n,
156
159
  };
157
160
  });
158
- await validateClientChainId(client, params.chainId);
161
+ await validateClientChainId(client, chainId);
159
162
  if (inputs === undefined) {
160
163
  throw new IncompleteTransactionPlanError(id);
161
164
  }
162
- const signatureRequestIds = Object.fromEntries(prepared.signatureRequests
163
- .filter((request) => request.kind === "permit")
164
- .map((request) => ["tokenPermit", request.id]));
165
- if (prepared.morphoAuthorizationRequestId !== undefined) {
166
- signatureRequestIds.morphoAuthorization =
167
- prepared.morphoAuthorizationRequestId;
168
- }
165
+ const signatureRequestIds = signatureRoles({
166
+ tokenPermit: prepared.signatureRequests.find((request) => request.kind === "permit")?.id,
167
+ morphoAuthorization: prepared.morphoAuthorizationRequestId,
168
+ });
169
169
  const authorization = prepared.signatureRequests.find((request) => request.kind === "morphoAuthorization");
170
170
  if (authorization !== undefined) {
171
171
  inputs = { ...inputs, authorizationNonce: authorization.args.nonce };
172
172
  }
173
- return deepFreeze(structuredClone({
174
- version: 2,
175
- chainId: params.chainId,
176
- account: params.account,
177
- expiresAt: prepared.intent.expiresAt,
178
- calldataOrigin: prepared.intent.calldataOrigin,
173
+ return freezePlan({
174
+ ...planHeader({ chainId, account }, prepared.intent),
179
175
  steps: [
180
176
  ...prepared.steps,
181
177
  {
@@ -185,7 +181,7 @@ export async function prepareBlueRepayWithdrawCollateral(client, params) {
185
181
  },
186
182
  ],
187
183
  signatureRequests: prepared.signatureRequests,
188
- }));
184
+ }, { detach: true });
189
185
  }
190
186
  function getRepayWithdrawLabel(inputs) {
191
187
  if (inputs.collateralAssets === 0n) {
@@ -206,6 +202,25 @@ const MARKET_STATE_FIELDS = [
206
202
  "price",
207
203
  "rateAtTarget",
208
204
  ];
205
+ function captureRepayWithdrawInputs(params) {
206
+ const { chainId, account, marketId, marketData, positionData } = params;
207
+ return {
208
+ chainId,
209
+ account,
210
+ marketId,
211
+ marketData: { chainId: marketData.chainId, market: marketData.market },
212
+ positionData: {
213
+ chainId: positionData.chainId,
214
+ position: positionData.position,
215
+ },
216
+ now: params.now ?? Time.timestamp(),
217
+ expiresAt: params.expiresAt,
218
+ supportSignature: params.supportSignature,
219
+ referralFee: params.referralFee,
220
+ calldataOrigin: params.calldataOrigin,
221
+ deployless: params.deployless,
222
+ };
223
+ }
209
224
  function getMatchingPosition(params) {
210
225
  const { position } = params.positionData;
211
226
  const positionMarket = position.market;
@@ -247,8 +262,8 @@ function quoteWithdrawal(quoteParams, collateralAssets) {
247
262
  }),
248
263
  });
249
264
  }
250
- function getRepayWithdrawAmounts(params) {
251
- const { collateralAssets, marketId } = params;
265
+ function getRepayWithdrawAmounts(params, marketId) {
266
+ const { collateralAssets } = params;
252
267
  const repayAssets = params.repayAssets ?? 0n;
253
268
  const repayShares = params.repayShares ?? 0n;
254
269
  if (repayAssets < 0n) {
@@ -362,9 +377,7 @@ export function validateRepayWithdrawCollateralPlanAction(action, path) {
362
377
  maxRepayAssets: "uint256 bigint",
363
378
  collateralAssets: "uint256 bigint",
364
379
  maxLtv: "uint256 bigint",
365
- deadline: "uint256 bigint",
366
- referralFeePct: "uint256 bigint",
367
- referralFeeRecipient: "address",
380
+ ...BUNDLES_COMMON_FIELDS,
368
381
  },
369
382
  });
370
383
  if (inputs.repayAssets > 0n &&
@@ -380,16 +393,7 @@ export function validateRepayWithdrawCollateralPlanAction(action, path) {
380
393
  fields: { nativeAssets: "uint256 bigint" },
381
394
  });
382
395
  }
383
- validatePlanFields(getPlanObject(inputs.marketParams, `${path}.inputs.marketParams`), {
384
- path: `${path}.inputs.marketParams`,
385
- fields: {
386
- loanToken: "address",
387
- collateralToken: "address",
388
- oracle: "address",
389
- irm: "address",
390
- lltv: "uint256 bigint",
391
- },
392
- });
396
+ validateStoredBlueMarketParams(inputs.marketParams, `${path}.inputs.marketParams`);
393
397
  const ids = getPlanObject(action.signatureRequestIds, `${path}.signatureRequestIds`);
394
398
  if (inputs.authorizationNonce !== undefined ||
395
399
  ids.morphoAuthorization !== undefined) {
@@ -0,0 +1,26 @@
1
+ /** @internal The stored BlueBundlesV1 deadline and referral fields, in their validation order. */
2
+ export declare const BUNDLES_COMMON_FIELDS: {
3
+ readonly deadline: "uint256 bigint";
4
+ readonly referralFeePct: "uint256 bigint";
5
+ readonly referralFeeRecipient: "address";
6
+ };
7
+ /** @internal Validates a stored five-field Blue market tuple at `path`. */
8
+ export declare function validateStoredBlueMarketParams(value: unknown, path: string): void;
9
+ /** @internal Validates a stored Blue market tuple that also carries its 32-byte market ID. */
10
+ export declare function validateStoredBlueMarket(value: unknown, path: string): void;
11
+ /**
12
+ * @internal Validates stored Vault V2 reallocations at `path`, checking each source market tuple
13
+ * with `marketParams`.
14
+ */
15
+ export declare function validateStoredReallocations(reallocations: readonly unknown[], { path, marketParams, }: {
16
+ readonly path: string;
17
+ readonly marketParams: (value: unknown, path: string) => void;
18
+ }): void;
19
+ /** @internal Builds an action's role map with only the roles that reference a request, in argument order. */
20
+ export declare function signatureRoles({ tokenPermit, morphoAuthorization, }: {
21
+ readonly tokenPermit?: string;
22
+ readonly morphoAuthorization?: string;
23
+ }): {
24
+ tokenPermit?: string | undefined;
25
+ morphoAuthorization?: string | undefined;
26
+ };
@@ -0,0 +1,80 @@
1
+ import { InvalidTransactionPlanError } from "../error.js";
2
+ import { getPlanObject, validatePlanFields } from "../validation.js";
3
+ /** @internal The stored BlueBundlesV1 deadline and referral fields, in their validation order. */
4
+ export const BUNDLES_COMMON_FIELDS = {
5
+ deadline: "uint256 bigint",
6
+ referralFeePct: "uint256 bigint",
7
+ referralFeeRecipient: "address",
8
+ };
9
+ const MARKET_PARAMS_FIELDS = {
10
+ loanToken: "address",
11
+ collateralToken: "address",
12
+ oracle: "address",
13
+ irm: "address",
14
+ lltv: "uint256 bigint",
15
+ };
16
+ /** @internal Validates a stored five-field Blue market tuple at `path`. */
17
+ export function validateStoredBlueMarketParams(value, path) {
18
+ validatePlanFields(getPlanObject(value, path), {
19
+ path,
20
+ fields: MARKET_PARAMS_FIELDS,
21
+ });
22
+ }
23
+ /** @internal Validates a stored Blue market tuple that also carries its 32-byte market ID. */
24
+ export function validateStoredBlueMarket(value, path) {
25
+ const market = getPlanObject(value, path);
26
+ validatePlanFields(market, {
27
+ path,
28
+ fields: { id: "hex", ...MARKET_PARAMS_FIELDS },
29
+ });
30
+ if (typeof market.id !== "string" || market.id.length !== 66) {
31
+ throw new InvalidTransactionPlanError({
32
+ path: `${path}.id`,
33
+ reason: "expected a 32-byte market ID",
34
+ });
35
+ }
36
+ }
37
+ /**
38
+ * @internal Validates stored Vault V2 reallocations at `path`, checking each source market tuple
39
+ * with `marketParams`.
40
+ */
41
+ export function validateStoredReallocations(reallocations, { path, marketParams, }) {
42
+ for (const [index, value] of reallocations.entries()) {
43
+ const entryPath = `${path}[${index}]`;
44
+ const entry = getPlanObject(value, entryPath);
45
+ validatePlanFields(entry, {
46
+ path: entryPath,
47
+ fields: {
48
+ vault: "address",
49
+ assets: "uint256 bigint",
50
+ penalty: "uint256 bigint",
51
+ },
52
+ });
53
+ validatePlanFields(getPlanObject(entry.to, `${entryPath}.to`), {
54
+ path: `${entryPath}.to`,
55
+ fields: { adapter: "address" },
56
+ });
57
+ const from = getPlanObject(entry.from, `${entryPath}.from`);
58
+ if (from.type === "idle") {
59
+ continue;
60
+ }
61
+ if (from.type !== "market") {
62
+ throw new InvalidTransactionPlanError({
63
+ path: `${entryPath}.from.type`,
64
+ reason: "expected market or idle",
65
+ });
66
+ }
67
+ validatePlanFields(from, {
68
+ path: `${entryPath}.from`,
69
+ fields: { adapter: "address" },
70
+ });
71
+ marketParams(from.marketParams, `${entryPath}.from.marketParams`);
72
+ }
73
+ }
74
+ /** @internal Builds an action's role map with only the roles that reference a request, in argument order. */
75
+ export function signatureRoles({ tokenPermit, morphoAuthorization, }) {
76
+ return {
77
+ ...(tokenPermit !== undefined && { tokenPermit }),
78
+ ...(morphoAuthorization !== undefined && { morphoAuthorization }),
79
+ };
80
+ }