@morpho-org/morpho-sdk 10.0.1 → 10.1.0-next.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 (250) hide show
  1. package/README.md +31 -10
  2. package/lib/cjs/abis.d.ts +1 -1
  3. package/lib/cjs/abis.js +5 -1
  4. package/lib/cjs/actions/blue/refinance.d.ts +1 -1
  5. package/lib/cjs/actions/blue/refinance.js +3 -8
  6. package/lib/cjs/actions/blue/refinanceValidation.d.ts +19 -0
  7. package/lib/cjs/actions/blue/refinanceValidation.js +46 -0
  8. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +1 -1
  9. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +3 -7
  10. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +1 -1
  11. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +4 -20
  12. package/lib/cjs/actions/requirements/getRequirementsApproval.js +7 -21
  13. package/lib/cjs/actions/requirements/validateClientChainId.d.ts +1 -26
  14. package/lib/cjs/actions/requirements/validateClientChainId.js +2 -31
  15. package/lib/cjs/actions/vaultV2/forceRedeem.d.ts +2 -1
  16. package/lib/cjs/actions/vaultV2/forceRedeem.js +20 -2
  17. package/lib/cjs/blue/abis.d.ts +1 -1
  18. package/lib/cjs/blue/abis.js +5 -1
  19. package/lib/cjs/blue/entities.d.ts +4 -4
  20. package/lib/cjs/blue/entities.js +3 -1
  21. package/lib/cjs/blue/errors.d.ts +2 -2
  22. package/lib/cjs/blue/errors.js +5 -1
  23. package/lib/cjs/blue/fetch.d.ts +2 -2
  24. package/lib/cjs/blue/fetch.js +3 -1
  25. package/lib/cjs/blue/utils.d.ts +1 -1
  26. package/lib/cjs/blue/utils.js +2 -1
  27. package/lib/cjs/entities/blue/blue.js +24 -55
  28. package/lib/cjs/entities/index.d.ts +4 -4
  29. package/lib/cjs/entities/index.js +3 -1
  30. package/lib/cjs/entities/requirements/getErc2612Permit.d.ts +2 -5
  31. package/lib/cjs/entities/requirements/getErc2612Permit.js +9 -58
  32. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +34 -8
  33. package/lib/cjs/entities/vaultV2/vaultV2.js +39 -1
  34. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +3 -2
  35. package/lib/cjs/entities/vaultV2BlueReallocationData.js +6 -2
  36. package/lib/cjs/errors.d.ts +4 -4
  37. package/lib/cjs/errors.js +7 -5
  38. package/lib/cjs/fetch.d.ts +2 -2
  39. package/lib/cjs/fetch.js +3 -1
  40. package/lib/cjs/helpers/deadShares.js +3 -0
  41. package/lib/cjs/helpers/quoteBlueRepay.d.ts +16 -0
  42. package/lib/cjs/helpers/quoteBlueRepay.js +46 -0
  43. package/lib/cjs/helpers/tokenApproval.d.ts +14 -0
  44. package/lib/cjs/helpers/tokenApproval.js +20 -0
  45. package/lib/cjs/helpers/validate.d.ts +1 -1
  46. package/lib/cjs/helpers/validate.js +2 -2
  47. package/lib/cjs/index.d.ts +2 -2
  48. package/lib/cjs/index.js +13 -1
  49. package/lib/cjs/midnight/errors.d.ts +2 -1
  50. package/lib/cjs/midnight/errors.js +5 -4
  51. package/lib/cjs/reads/readErc2612Permit.d.ts +22 -0
  52. package/lib/cjs/reads/readErc2612Permit.js +77 -0
  53. package/lib/cjs/reads/validateClientChainId.d.ts +26 -0
  54. package/lib/cjs/reads/validateClientChainId.js +34 -0
  55. package/lib/cjs/transactionPlan/blue/authorization.d.ts +23 -0
  56. package/lib/cjs/transactionPlan/blue/authorization.js +128 -0
  57. package/lib/cjs/transactionPlan/blue/borrow.d.ts +80 -0
  58. package/lib/cjs/transactionPlan/blue/borrow.js +248 -0
  59. package/lib/cjs/transactionPlan/blue/prepare.d.ts +102 -0
  60. package/lib/cjs/transactionPlan/blue/prepare.js +191 -0
  61. package/lib/cjs/transactionPlan/blue/refinance.d.ts +93 -0
  62. package/lib/cjs/transactionPlan/blue/refinance.js +281 -0
  63. package/lib/cjs/transactionPlan/blue/refinanceValidation.d.ts +11 -0
  64. package/lib/cjs/transactionPlan/blue/refinanceValidation.js +20 -0
  65. package/lib/cjs/transactionPlan/blue/repay.d.ts +80 -0
  66. package/lib/cjs/transactionPlan/blue/repay.js +229 -0
  67. package/lib/cjs/transactionPlan/blue/repayWithdrawCollateral.d.ts +98 -0
  68. package/lib/cjs/transactionPlan/blue/repayWithdrawCollateral.js +379 -0
  69. package/lib/cjs/transactionPlan/blue/supply.d.ts +181 -0
  70. package/lib/cjs/transactionPlan/blue/supply.js +238 -0
  71. package/lib/cjs/transactionPlan/blue/supplyCollateral.d.ts +97 -0
  72. package/lib/cjs/transactionPlan/blue/supplyCollateral.js +231 -0
  73. package/lib/cjs/transactionPlan/blue/supplyCollateralBorrow.d.ts +102 -0
  74. package/lib/cjs/transactionPlan/blue/supplyCollateralBorrow.js +395 -0
  75. package/lib/cjs/transactionPlan/blue/withdraw.d.ts +136 -0
  76. package/lib/cjs/transactionPlan/blue/withdraw.js +340 -0
  77. package/lib/cjs/transactionPlan/blue/withdrawCollateral.d.ts +123 -0
  78. package/lib/cjs/transactionPlan/blue/withdrawCollateral.js +246 -0
  79. package/lib/cjs/transactionPlan/deposit.js +8 -19
  80. package/lib/cjs/transactionPlan/error.d.ts +50 -0
  81. package/lib/cjs/transactionPlan/error.js +60 -1
  82. package/lib/cjs/transactionPlan/getTokenPermit.d.ts +17 -8
  83. package/lib/cjs/transactionPlan/getTokenPermit.js +35 -7
  84. package/lib/cjs/transactionPlan/index.d.ts +21 -1
  85. package/lib/cjs/transactionPlan/index.js +27 -5
  86. package/lib/cjs/transactionPlan/intent.d.ts +2 -2
  87. package/lib/cjs/transactionPlan/intent.js +8 -4
  88. package/lib/cjs/transactionPlan/permit.d.ts +16 -2
  89. package/lib/cjs/transactionPlan/permit.js +77 -45
  90. package/lib/cjs/transactionPlan/plan.d.ts +67 -12
  91. package/lib/cjs/transactionPlan/plan.js +284 -50
  92. package/lib/cjs/transactionPlan/requirements.d.ts +14 -5
  93. package/lib/cjs/transactionPlan/requirements.js +30 -12
  94. package/lib/cjs/transactionPlan/serde.d.ts +7 -4
  95. package/lib/cjs/transactionPlan/serde.js +80 -61
  96. package/lib/cjs/transactionPlan/types.d.ts +141 -13
  97. package/lib/cjs/transactionPlan/validateActions.js +11 -1
  98. package/lib/cjs/transactionPlan/validation.d.ts +8 -0
  99. package/lib/cjs/transactionPlan/validation.js +90 -0
  100. package/lib/cjs/transactionPlan/vaultv1/deposit.d.ts +1 -0
  101. package/lib/cjs/transactionPlan/vaultv1/deposit.js +1 -0
  102. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.d.ts +1 -0
  103. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.js +1 -0
  104. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.d.ts +1 -0
  105. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.js +1 -0
  106. package/lib/cjs/transactionPlan/vaultv1/redeem.d.ts +1 -0
  107. package/lib/cjs/transactionPlan/vaultv1/redeem.js +1 -0
  108. package/lib/cjs/transactionPlan/vaultv1/withdraw.d.ts +1 -0
  109. package/lib/cjs/transactionPlan/vaultv1/withdraw.js +1 -0
  110. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +1 -0
  111. package/lib/cjs/transactionPlan/vaultv2/deposit.js +1 -0
  112. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.d.ts +1 -0
  113. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.js +1 -0
  114. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.d.ts +1 -0
  115. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.js +1 -0
  116. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.d.ts +1 -0
  117. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.js +1 -0
  118. package/lib/cjs/transactionPlan/vaultv2/redeem.d.ts +1 -0
  119. package/lib/cjs/transactionPlan/vaultv2/redeem.js +1 -0
  120. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +1 -0
  121. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +1 -0
  122. package/lib/cjs/utils.d.ts +2 -2
  123. package/lib/cjs/utils.js +4 -2
  124. package/lib/cjs/version.d.ts +1 -1
  125. package/lib/cjs/version.js +1 -1
  126. package/lib/esm/abis.d.ts +1 -1
  127. package/lib/esm/abis.js +1 -1
  128. package/lib/esm/actions/blue/refinance.d.ts +1 -1
  129. package/lib/esm/actions/blue/refinance.js +4 -9
  130. package/lib/esm/actions/blue/refinanceValidation.d.ts +19 -0
  131. package/lib/esm/actions/blue/refinanceValidation.js +41 -0
  132. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +1 -1
  133. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +4 -8
  134. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +1 -1
  135. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +5 -21
  136. package/lib/esm/actions/requirements/getRequirementsApproval.js +7 -21
  137. package/lib/esm/actions/requirements/validateClientChainId.d.ts +1 -26
  138. package/lib/esm/actions/requirements/validateClientChainId.js +1 -30
  139. package/lib/esm/actions/vaultV2/forceRedeem.d.ts +2 -1
  140. package/lib/esm/actions/vaultV2/forceRedeem.js +20 -2
  141. package/lib/esm/blue/abis.d.ts +1 -1
  142. package/lib/esm/blue/abis.js +1 -1
  143. package/lib/esm/blue/entities.d.ts +4 -4
  144. package/lib/esm/blue/entities.js +2 -2
  145. package/lib/esm/blue/errors.d.ts +2 -2
  146. package/lib/esm/blue/errors.js +2 -2
  147. package/lib/esm/blue/fetch.d.ts +2 -2
  148. package/lib/esm/blue/fetch.js +2 -2
  149. package/lib/esm/blue/utils.d.ts +1 -1
  150. package/lib/esm/blue/utils.js +1 -1
  151. package/lib/esm/entities/blue/blue.js +26 -57
  152. package/lib/esm/entities/index.d.ts +4 -4
  153. package/lib/esm/entities/index.js +2 -2
  154. package/lib/esm/entities/requirements/getErc2612Permit.d.ts +2 -5
  155. package/lib/esm/entities/requirements/getErc2612Permit.js +9 -58
  156. package/lib/esm/entities/vaultV2/vaultV2.d.ts +34 -8
  157. package/lib/esm/entities/vaultV2/vaultV2.js +40 -2
  158. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +3 -2
  159. package/lib/esm/entities/vaultV2BlueReallocationData.js +6 -2
  160. package/lib/esm/errors.d.ts +4 -4
  161. package/lib/esm/errors.js +4 -4
  162. package/lib/esm/fetch.d.ts +2 -2
  163. package/lib/esm/fetch.js +2 -2
  164. package/lib/esm/helpers/deadShares.js +4 -1
  165. package/lib/esm/helpers/quoteBlueRepay.d.ts +16 -0
  166. package/lib/esm/helpers/quoteBlueRepay.js +42 -0
  167. package/lib/esm/helpers/tokenApproval.d.ts +14 -0
  168. package/lib/esm/helpers/tokenApproval.js +16 -0
  169. package/lib/esm/helpers/validate.d.ts +1 -1
  170. package/lib/esm/helpers/validate.js +3 -3
  171. package/lib/esm/index.d.ts +2 -2
  172. package/lib/esm/index.js +1 -1
  173. package/lib/esm/midnight/errors.d.ts +2 -1
  174. package/lib/esm/midnight/errors.js +2 -1
  175. package/lib/esm/reads/readErc2612Permit.d.ts +22 -0
  176. package/lib/esm/reads/readErc2612Permit.js +73 -0
  177. package/lib/esm/reads/validateClientChainId.d.ts +26 -0
  178. package/lib/esm/reads/validateClientChainId.js +30 -0
  179. package/lib/esm/transactionPlan/blue/authorization.d.ts +23 -0
  180. package/lib/esm/transactionPlan/blue/authorization.js +122 -0
  181. package/lib/esm/transactionPlan/blue/borrow.d.ts +80 -0
  182. package/lib/esm/transactionPlan/blue/borrow.js +243 -0
  183. package/lib/esm/transactionPlan/blue/prepare.d.ts +102 -0
  184. package/lib/esm/transactionPlan/blue/prepare.js +187 -0
  185. package/lib/esm/transactionPlan/blue/refinance.d.ts +93 -0
  186. package/lib/esm/transactionPlan/blue/refinance.js +276 -0
  187. package/lib/esm/transactionPlan/blue/refinanceValidation.d.ts +11 -0
  188. package/lib/esm/transactionPlan/blue/refinanceValidation.js +17 -0
  189. package/lib/esm/transactionPlan/blue/repay.d.ts +80 -0
  190. package/lib/esm/transactionPlan/blue/repay.js +223 -0
  191. package/lib/esm/transactionPlan/blue/repayWithdrawCollateral.d.ts +98 -0
  192. package/lib/esm/transactionPlan/blue/repayWithdrawCollateral.js +373 -0
  193. package/lib/esm/transactionPlan/blue/supply.d.ts +181 -0
  194. package/lib/esm/transactionPlan/blue/supply.js +232 -0
  195. package/lib/esm/transactionPlan/blue/supplyCollateral.d.ts +97 -0
  196. package/lib/esm/transactionPlan/blue/supplyCollateral.js +225 -0
  197. package/lib/esm/transactionPlan/blue/supplyCollateralBorrow.d.ts +102 -0
  198. package/lib/esm/transactionPlan/blue/supplyCollateralBorrow.js +389 -0
  199. package/lib/esm/transactionPlan/blue/withdraw.d.ts +136 -0
  200. package/lib/esm/transactionPlan/blue/withdraw.js +334 -0
  201. package/lib/esm/transactionPlan/blue/withdrawCollateral.d.ts +123 -0
  202. package/lib/esm/transactionPlan/blue/withdrawCollateral.js +240 -0
  203. package/lib/esm/transactionPlan/deposit.js +9 -20
  204. package/lib/esm/transactionPlan/error.d.ts +50 -0
  205. package/lib/esm/transactionPlan/error.js +57 -0
  206. package/lib/esm/transactionPlan/getTokenPermit.d.ts +17 -8
  207. package/lib/esm/transactionPlan/getTokenPermit.js +35 -7
  208. package/lib/esm/transactionPlan/index.d.ts +21 -1
  209. package/lib/esm/transactionPlan/index.js +11 -1
  210. package/lib/esm/transactionPlan/intent.d.ts +2 -2
  211. package/lib/esm/transactionPlan/intent.js +8 -4
  212. package/lib/esm/transactionPlan/permit.d.ts +16 -2
  213. package/lib/esm/transactionPlan/permit.js +76 -44
  214. package/lib/esm/transactionPlan/plan.d.ts +67 -12
  215. package/lib/esm/transactionPlan/plan.js +279 -46
  216. package/lib/esm/transactionPlan/requirements.d.ts +14 -5
  217. package/lib/esm/transactionPlan/requirements.js +30 -12
  218. package/lib/esm/transactionPlan/serde.d.ts +7 -4
  219. package/lib/esm/transactionPlan/serde.js +73 -54
  220. package/lib/esm/transactionPlan/types.d.ts +141 -13
  221. package/lib/esm/transactionPlan/validateActions.js +11 -1
  222. package/lib/esm/transactionPlan/validation.d.ts +8 -0
  223. package/lib/esm/transactionPlan/validation.js +88 -1
  224. package/lib/esm/transactionPlan/vaultv1/deposit.d.ts +1 -0
  225. package/lib/esm/transactionPlan/vaultv1/deposit.js +1 -0
  226. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.d.ts +1 -0
  227. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.js +1 -0
  228. package/lib/esm/transactionPlan/vaultv1/migrateToV2.d.ts +1 -0
  229. package/lib/esm/transactionPlan/vaultv1/migrateToV2.js +1 -0
  230. package/lib/esm/transactionPlan/vaultv1/redeem.d.ts +1 -0
  231. package/lib/esm/transactionPlan/vaultv1/redeem.js +1 -0
  232. package/lib/esm/transactionPlan/vaultv1/withdraw.d.ts +1 -0
  233. package/lib/esm/transactionPlan/vaultv1/withdraw.js +1 -0
  234. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +1 -0
  235. package/lib/esm/transactionPlan/vaultv2/deposit.js +1 -0
  236. package/lib/esm/transactionPlan/vaultv2/forceRedeem.d.ts +1 -0
  237. package/lib/esm/transactionPlan/vaultv2/forceRedeem.js +1 -0
  238. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.d.ts +1 -0
  239. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.js +1 -0
  240. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.d.ts +1 -0
  241. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.js +1 -0
  242. package/lib/esm/transactionPlan/vaultv2/redeem.d.ts +1 -0
  243. package/lib/esm/transactionPlan/vaultv2/redeem.js +1 -0
  244. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +1 -0
  245. package/lib/esm/transactionPlan/vaultv2/withdraw.js +1 -0
  246. package/lib/esm/utils.d.ts +2 -2
  247. package/lib/esm/utils.js +2 -2
  248. package/lib/esm/version.d.ts +1 -1
  249. package/lib/esm/version.js +1 -1
  250. package/package.json +7 -7
@@ -0,0 +1,80 @@
1
+ import type { MarketId } from "@morpho-org/blue-sdk";
2
+ import type { Client } from "viem";
3
+ import type { VaultV2BlueReallocation } from "../../types/index.js";
4
+ import type { IntentParams } from "../intent.js";
5
+ import type { Action, SignatureRequest, TransactionPlan } from "../types.js";
6
+ import { type BlueMarketSnapshot, type BluePositionSnapshot } from "./prepare.js";
7
+ /**
8
+ * Borrow intent backed by caller-fetched market and position snapshots.
9
+ * @example
10
+ * ```ts
11
+ * const params: BlueBorrowPlanParams = { chainId: 1, account, marketId: market.id,
12
+ * marketData: { chainId: 1, market }, positionData: { chainId: 1, position }, borrowAssets: 100n };
13
+ * ```
14
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
15
+ */
16
+ export interface BlueBorrowPlanParams extends IntentParams {
17
+ readonly marketId: MarketId;
18
+ readonly marketData: BlueMarketSnapshot;
19
+ readonly positionData: BluePositionSnapshot;
20
+ /** Gross debt increase, before allocator penalties and referral fees. */
21
+ readonly borrowAssets: bigint;
22
+ readonly reallocations?: readonly VaultV2BlueReallocation[];
23
+ readonly now?: bigint;
24
+ }
25
+ /**
26
+ * Prepares a BlueBundlesV1 borrow against existing collateral. No token allowance is needed.
27
+ * Health is checked on the position accrued two hours beyond the later of now and last update,
28
+ * matching the existing Blue borrow handle. Snapshots are not retained in the stored plan.
29
+ * Reads Morpho authorization of BlueBundlesV1 (and its nonce when signing) from `client`.
30
+ * @param client - Viem client for `params.chainId`, used for Morpho authorization and contract code reads.
31
+ * @param params - Borrow intent and chain-tagged snapshots for the borrowing account.
32
+ * @returns A data-only plan with any Morpho authorization prerequisite before the borrow.
33
+ * @throws {ChainIdMismatchError} When the client declares another chain or its RPC reports another chain.
34
+ * @throws {MissingContractCodeError} When BlueBundlesV1 or Morpho Blue has no deployed code.
35
+ * @throws {UnsupportedBlueMarketIrmError} When positive debt requires an unsupported IRM projection.
36
+ * @throws {viem.BaseError} When a chain ID, authorization, nonce, or contract code read fails.
37
+ * @throws {BlueSnapshotChainMismatchError} When a snapshot was read from another chain.
38
+ * @throws {MarketIdMismatchError} When a snapshot describes another market.
39
+ * @throws {AccrualPositionUserMismatchError} When `positionData` belongs to another account.
40
+ * @throws {ZeroAccountError} When `account` is the zero address.
41
+ * @throws {NonIntegerInputError} When `expiresAt` or `referralFee.bps` is not a safe integer.
42
+ * @throws {NonPositiveInputError} When `expiresAt`, `borrowAssets` or a reallocation amount is not positive.
43
+ * @throws {ExpiredDeadlineError} When `expiresAt` is at or before `now`.
44
+ * @throws {NegativeInputError} When `referralFee.bps` or a reallocation penalty is negative.
45
+ * @throws {InputExceedsMaxError} When a fee or reallocation bound is exceeded, including aggregate allocator penalties above the borrow.
46
+ * @throws {InvalidCalldataOriginError} When `calldataOrigin` is empty, malformed or has an odd number of hex digits.
47
+ * @throws {ReferralFeePctExceededError} When `referralFee.bps` equals 10,000.
48
+ * @throws {ReferralFeeRecipientMissingError} When a positive referral fee has no recipient.
49
+ * @throws {InvalidVaultV2BlueReallocationShapeError} When a reallocation entry is malformed.
50
+ * @throws {ReallocationWithdrawalOnTargetMarketError} When a reallocation sources the target market.
51
+ * @throws {MissingMarketPriceError} When the market snapshot has no oracle price.
52
+ * @throws {BorrowExceedsSafeLtvError} When the resulting debt exceeds buffered LLTV.
53
+ * @see blueBorrow for the remaining reallocation encoding errors.
54
+ * @example
55
+ * ```ts
56
+ * import { prepareBlueBorrow } from "@morpho-org/morpho-sdk";
57
+ * import { fetchBlueAccrualPosition, fetchBlueMarket } from "@morpho-org/morpho-sdk/fetch";
58
+ * import type { MarketId } from "@morpho-org/blue-sdk";
59
+ * import { createPublicClient, http } from "viem";
60
+ * import { mainnet } from "viem/chains";
61
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
62
+ * const account = "0x0000000000000000000000000000000000000001";
63
+ * const marketId = "0xb8fc70e82bc5bb53e773626fcc6a23f7eefa036918d7ef216ecfb1950a94a85e" as MarketId;
64
+ * const plan = await prepareBlueBorrow(client, {
65
+ * chainId: 1, account, marketId, borrowAssets: 1_000_000n, supportSignature: true,
66
+ * marketData: { chainId: 1, market: await fetchBlueMarket(marketId, client) },
67
+ * positionData: { chainId: 1, position: await fetchBlueAccrualPosition(account, marketId, client) },
68
+ * now: (await client.getBlock()).timestamp,
69
+ * });
70
+ * // Sign the pending Morpho authorization request if any, attach it with applySignatures, then build.
71
+ * ```
72
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
73
+ */
74
+ export declare function prepareBlueBorrow(client: Client, { chainId, account, marketId, marketData, positionData, borrowAssets, reallocations, expiresAt, referralFee, supportSignature, calldataOrigin, deployless, now, }: BlueBorrowPlanParams): Promise<TransactionPlan>;
75
+ /** @internal Encodes a prepared borrow without state reads or signing. */
76
+ export declare function buildBlueBorrow(action: Extract<Action, {
77
+ type: "blueBorrow";
78
+ }>, requests: readonly SignatureRequest[]): Readonly<import("../../index.js").Transaction<import("../../index.js").BlueBorrowAction>>;
79
+ /** @internal Validates the stored borrow recipe, including each allocator input. */
80
+ export declare function validateBorrowPlanAction(action: Record<string, unknown>, path: string): void;
@@ -0,0 +1,248 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareBlueBorrow = prepareBlueBorrow;
4
+ exports.buildBlueBorrow = buildBlueBorrow;
5
+ exports.validateBorrowPlanAction = validateBorrowPlanAction;
6
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
7
+ const borrow_js_1 = require("../../actions/blue/borrow.js");
8
+ const common_js_1 = require("../../actions/bundles/common.js");
9
+ const index_js_1 = require("../../helpers/index.js");
10
+ const validate_js_1 = require("../../helpers/validate.js");
11
+ const error_js_1 = require("../error.js");
12
+ const validation_js_1 = require("../validation.js");
13
+ const prepare_js_1 = require("./prepare.js");
14
+ /**
15
+ * Prepares a BlueBundlesV1 borrow against existing collateral. No token allowance is needed.
16
+ * Health is checked on the position accrued two hours beyond the later of now and last update,
17
+ * matching the existing Blue borrow handle. Snapshots are not retained in the stored plan.
18
+ * Reads Morpho authorization of BlueBundlesV1 (and its nonce when signing) from `client`.
19
+ * @param client - Viem client for `params.chainId`, used for Morpho authorization and contract code reads.
20
+ * @param params - Borrow intent and chain-tagged snapshots for the borrowing account.
21
+ * @returns A data-only plan with any Morpho authorization prerequisite before the borrow.
22
+ * @throws {ChainIdMismatchError} When the client declares another chain or its RPC reports another chain.
23
+ * @throws {MissingContractCodeError} When BlueBundlesV1 or Morpho Blue has no deployed code.
24
+ * @throws {UnsupportedBlueMarketIrmError} When positive debt requires an unsupported IRM projection.
25
+ * @throws {viem.BaseError} When a chain ID, authorization, nonce, or contract code read fails.
26
+ * @throws {BlueSnapshotChainMismatchError} When a snapshot was read from another chain.
27
+ * @throws {MarketIdMismatchError} When a snapshot describes another market.
28
+ * @throws {AccrualPositionUserMismatchError} When `positionData` belongs to another account.
29
+ * @throws {ZeroAccountError} When `account` is the zero address.
30
+ * @throws {NonIntegerInputError} When `expiresAt` or `referralFee.bps` is not a safe integer.
31
+ * @throws {NonPositiveInputError} When `expiresAt`, `borrowAssets` or a reallocation amount is not positive.
32
+ * @throws {ExpiredDeadlineError} When `expiresAt` is at or before `now`.
33
+ * @throws {NegativeInputError} When `referralFee.bps` or a reallocation penalty is negative.
34
+ * @throws {InputExceedsMaxError} When a fee or reallocation bound is exceeded, including aggregate allocator penalties above the borrow.
35
+ * @throws {InvalidCalldataOriginError} When `calldataOrigin` is empty, malformed or has an odd number of hex digits.
36
+ * @throws {ReferralFeePctExceededError} When `referralFee.bps` equals 10,000.
37
+ * @throws {ReferralFeeRecipientMissingError} When a positive referral fee has no recipient.
38
+ * @throws {InvalidVaultV2BlueReallocationShapeError} When a reallocation entry is malformed.
39
+ * @throws {ReallocationWithdrawalOnTargetMarketError} When a reallocation sources the target market.
40
+ * @throws {MissingMarketPriceError} When the market snapshot has no oracle price.
41
+ * @throws {BorrowExceedsSafeLtvError} When the resulting debt exceeds buffered LLTV.
42
+ * @see blueBorrow for the remaining reallocation encoding errors.
43
+ * @example
44
+ * ```ts
45
+ * import { prepareBlueBorrow } from "@morpho-org/morpho-sdk";
46
+ * import { fetchBlueAccrualPosition, fetchBlueMarket } from "@morpho-org/morpho-sdk/fetch";
47
+ * import type { MarketId } from "@morpho-org/blue-sdk";
48
+ * import { createPublicClient, http } from "viem";
49
+ * import { mainnet } from "viem/chains";
50
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
51
+ * const account = "0x0000000000000000000000000000000000000001";
52
+ * const marketId = "0xb8fc70e82bc5bb53e773626fcc6a23f7eefa036918d7ef216ecfb1950a94a85e" as MarketId;
53
+ * const plan = await prepareBlueBorrow(client, {
54
+ * chainId: 1, account, marketId, borrowAssets: 1_000_000n, supportSignature: true,
55
+ * marketData: { chainId: 1, market: await fetchBlueMarket(marketId, client) },
56
+ * positionData: { chainId: 1, position: await fetchBlueAccrualPosition(account, marketId, client) },
57
+ * now: (await client.getBlock()).timestamp,
58
+ * });
59
+ * // Sign the pending Morpho authorization request if any, attach it with applySignatures, then build.
60
+ * ```
61
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
62
+ */
63
+ async function prepareBlueBorrow(client, { chainId, account, marketId, marketData, positionData, borrowAssets, reallocations, expiresAt, referralFee, supportSignature, calldataOrigin, deployless, now = morpho_ts_1.Time.timestamp(), }) {
64
+ const params = {
65
+ chainId,
66
+ account,
67
+ marketId,
68
+ marketData,
69
+ positionData,
70
+ borrowAssets,
71
+ reallocations,
72
+ expiresAt,
73
+ referralFee,
74
+ supportSignature,
75
+ calldataOrigin,
76
+ deployless,
77
+ now,
78
+ };
79
+ let inputs;
80
+ const { intent, steps, signatureRequests, morphoAuthorizationRequestId } = await (0, prepare_js_1.prepareBlue)({ client, params }, (resolvedIntent) => {
81
+ const marketParams = params.marketData.market.params;
82
+ const position = params.positionData.position;
83
+ inputs = {
84
+ chainId: params.chainId,
85
+ account: params.account,
86
+ marketParams: { ...marketParams },
87
+ borrowAssets: params.borrowAssets,
88
+ authorizationNonce: 0n,
89
+ maxLtv: morpho_ts_1.MathLib.zeroFloorSub(marketParams.lltv, index_js_1.DEFAULT_LLTV_BUFFER),
90
+ reallocations: structuredClone(params.reallocations ?? []),
91
+ ...(0, common_js_1.normalizeBundlesCommonParams)({
92
+ deadline: resolvedIntent.deadline,
93
+ referralFeePct: resolvedIntent.referralFeePct,
94
+ referralFeeRecipient: resolvedIntent.referralFeeRecipient,
95
+ }),
96
+ };
97
+ // Validate the pure encoding, including aggregate penalties, before any RPC reads.
98
+ buildBlueBorrow({ type: "blueBorrow", inputs, signatureRequestIds: {} }, []);
99
+ // Apply the same deadline-independent two-hour health quote as the existing handle.
100
+ (0, validate_js_1.validatePositionHealth)({
101
+ positionData: position.accrueInterest(morpho_ts_1.MathLib.max(now, position.market.lastUpdate) + morpho_ts_1.Time.s.from.h(2n)),
102
+ additionalCollateral: 0n,
103
+ borrowAmount: params.borrowAssets,
104
+ marketId: params.marketId,
105
+ lltv: marketParams.lltv,
106
+ });
107
+ return { id: "blueBorrow", needsAuthorization: true };
108
+ });
109
+ if (inputs === undefined) {
110
+ throw new error_js_1.InvalidTransactionPlanError({
111
+ path: "inputs",
112
+ reason: "expected prepared borrow inputs",
113
+ });
114
+ }
115
+ return (0, morpho_ts_1.deepFreeze)(structuredClone({
116
+ version: 2,
117
+ account: inputs.account,
118
+ chainId: inputs.chainId,
119
+ expiresAt: intent.expiresAt,
120
+ ...(intent.calldataOrigin && { calldataOrigin: intent.calldataOrigin }),
121
+ steps: [
122
+ ...steps,
123
+ {
124
+ id: "blueBorrow",
125
+ label: "Borrow from Blue",
126
+ action: {
127
+ type: "blueBorrow",
128
+ inputs: {
129
+ ...inputs,
130
+ authorizationNonce: signatureRequests.find((request) => request.id === morphoAuthorizationRequestId)?.args.nonce ?? 0n,
131
+ },
132
+ signatureRequestIds: morphoAuthorizationRequestId
133
+ ? { morphoAuthorization: morphoAuthorizationRequestId }
134
+ : {},
135
+ },
136
+ },
137
+ ],
138
+ signatureRequests,
139
+ }));
140
+ }
141
+ /** @internal Encodes a prepared borrow without state reads or signing. */
142
+ function buildBlueBorrow(action, requests) {
143
+ const { chainId, account, marketParams, borrowAssets, maxLtv, reallocations, deadline, referralFeePct, referralFeeRecipient, } = action.inputs;
144
+ const id = action.signatureRequestIds.morphoAuthorization;
145
+ const request = requests.find((candidate) => candidate.id === id);
146
+ if (id !== undefined &&
147
+ (request?.kind !== "morphoAuthorization" || request.signature === undefined)) {
148
+ throw new error_js_1.IncompleteTransactionPlanError(id);
149
+ }
150
+ const authorizationSignature = request?.kind === "morphoAuthorization" && request.signature !== undefined
151
+ ? {
152
+ action: {
153
+ type: "authorization",
154
+ args: {
155
+ authorized: request.args.authorized,
156
+ isAuthorized: true,
157
+ deadline: request.args.deadline,
158
+ },
159
+ },
160
+ args: {
161
+ ...request.args,
162
+ isAuthorized: true,
163
+ signature: request.signature,
164
+ },
165
+ }
166
+ : undefined;
167
+ return (0, borrow_js_1.blueBorrow)({
168
+ market: { chainId, marketParams },
169
+ args: {
170
+ borrowAssets,
171
+ maxLtv,
172
+ reallocations,
173
+ deadline,
174
+ referralFeePct,
175
+ referralFeeRecipient,
176
+ userAddress: account,
177
+ authorizationSignature,
178
+ },
179
+ });
180
+ }
181
+ function validateMarket(value, path) {
182
+ const market = (0, validation_js_1.getPlanObject)(value, path);
183
+ (0, validation_js_1.validatePlanFields)(market, {
184
+ path,
185
+ fields: {
186
+ id: "hex",
187
+ loanToken: "address",
188
+ collateralToken: "address",
189
+ oracle: "address",
190
+ irm: "address",
191
+ lltv: "uint256 bigint",
192
+ },
193
+ });
194
+ if (typeof market.id !== "string" || market.id.length !== 66) {
195
+ throw new error_js_1.InvalidTransactionPlanError({
196
+ path: `${path}.id`,
197
+ reason: "expected a 32-byte market ID",
198
+ });
199
+ }
200
+ }
201
+ /** @internal Validates the stored borrow recipe, including each allocator input. */
202
+ function validateBorrowPlanAction(action, path) {
203
+ const inputs = (0, validation_js_1.getPlanObject)(action.inputs, `${path}.inputs`);
204
+ (0, validation_js_1.getPlanObject)(action.signatureRequestIds, `${path}.signatureRequestIds`);
205
+ (0, validation_js_1.validatePlanFields)(inputs, {
206
+ path: `${path}.inputs`,
207
+ fields: {
208
+ borrowAssets: "uint256 bigint",
209
+ authorizationNonce: "uint256 bigint",
210
+ maxLtv: "uint256 bigint",
211
+ deadline: "uint256 bigint",
212
+ referralFeePct: "uint256 bigint",
213
+ referralFeeRecipient: "address",
214
+ reallocations: "array",
215
+ },
216
+ });
217
+ validateMarket(inputs.marketParams, `${path}.inputs.marketParams`);
218
+ for (const [index, value] of inputs.reallocations.entries()) {
219
+ const entryPath = `${path}.inputs.reallocations[${index}]`;
220
+ const entry = (0, validation_js_1.getPlanObject)(value, entryPath);
221
+ (0, validation_js_1.validatePlanFields)(entry, {
222
+ path: entryPath,
223
+ fields: {
224
+ vault: "address",
225
+ assets: "uint256 bigint",
226
+ penalty: "uint256 bigint",
227
+ },
228
+ });
229
+ (0, validation_js_1.validatePlanFields)((0, validation_js_1.getPlanObject)(entry.to, `${entryPath}.to`), {
230
+ path: `${entryPath}.to`,
231
+ fields: { adapter: "address" },
232
+ });
233
+ const from = (0, validation_js_1.getPlanObject)(entry.from, `${entryPath}.from`);
234
+ if (from.type !== "market" && from.type !== "idle") {
235
+ throw new error_js_1.InvalidTransactionPlanError({
236
+ path: `${entryPath}.from.type`,
237
+ reason: "expected market or idle",
238
+ });
239
+ }
240
+ if (from.type === "market") {
241
+ (0, validation_js_1.validatePlanFields)(from, {
242
+ path: `${entryPath}.from`,
243
+ fields: { adapter: "address" },
244
+ });
245
+ validateMarket(from.marketParams, `${entryPath}.from.marketParams`);
246
+ }
247
+ }
248
+ }
@@ -0,0 +1,102 @@
1
+ import type { AccrualPosition, Market, MarketId } from "@morpho-org/blue-sdk";
2
+ import type { Address, Client } from "viem";
3
+ import { type IntentParams, resolveIntent } from "../intent.js";
4
+ import type { SignatureRequest, Step } from "../types.js";
5
+ /**
6
+ * Caller-fetched Blue market with the chain it was read from.
7
+ * @example
8
+ * ```ts
9
+ * import type { BlueMarketSnapshot } from "@morpho-org/morpho-sdk";
10
+ * import type { Market } from "@morpho-org/blue-sdk";
11
+ * const snapshot = (market: Market): BlueMarketSnapshot => ({ chainId: 1, market });
12
+ * ```
13
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
14
+ */
15
+ export interface BlueMarketSnapshot {
16
+ readonly chainId: number;
17
+ readonly market: Readonly<Market>;
18
+ }
19
+ /**
20
+ * Caller-fetched Blue accrual position with the chain it was read from.
21
+ * @example
22
+ * ```ts
23
+ * import type { BluePositionSnapshot } from "@morpho-org/morpho-sdk";
24
+ * import type { AccrualPosition } from "@morpho-org/blue-sdk";
25
+ * const snapshot = (position: AccrualPosition): BluePositionSnapshot => ({ chainId: 1, position });
26
+ * ```
27
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
28
+ */
29
+ export interface BluePositionSnapshot {
30
+ readonly chainId: number;
31
+ readonly position: Readonly<AccrualPosition>;
32
+ }
33
+ interface BluePrepareParams extends IntentParams {
34
+ readonly marketId: MarketId;
35
+ readonly marketData: BlueMarketSnapshot;
36
+ readonly positionData?: BluePositionSnapshot;
37
+ readonly now?: bigint;
38
+ }
39
+ /**
40
+ * Checks that a caller-fetched Blue market snapshot belongs to the expected chain
41
+ * and market, and that the market ID matches its parameters. Does not read RPC state.
42
+ * @param marketData - Caller-fetched market snapshot.
43
+ * @param expected - Expected chain ID and market ID.
44
+ * @param expected.chainId - Chain on which the market snapshot was read.
45
+ * @param expected.marketId - Market ID to match, regardless of hex casing.
46
+ * @returns Nothing when the snapshot matches the expected chain and market.
47
+ * @throws {BlueSnapshotChainMismatchError} If the snapshot belongs to a different chain.
48
+ * @throws {MarketIdMismatchError} If the snapshot identifies a different market.
49
+ * @example
50
+ * ```ts
51
+ * import { validateBlueMarketSnapshot } from "@morpho-org/morpho-sdk";
52
+ * import { addressesRegistry } from "@morpho-org/morpho-sdk/blue/addresses";
53
+ * import { Market, MarketParams } from "@morpho-org/morpho-sdk/blue/entities";
54
+ * import { mainnet } from "viem/chains";
55
+ *
56
+ * const chainId = mainnet.id;
57
+ * const params = MarketParams.idle(addressesRegistry[chainId].usdc);
58
+ * const market = new Market({
59
+ * params,
60
+ * totalSupplyAssets: 0n,
61
+ * totalSupplyShares: 0n,
62
+ * totalBorrowAssets: 0n,
63
+ * totalBorrowShares: 0n,
64
+ * lastUpdate: 0n,
65
+ * fee: 0n,
66
+ * });
67
+ * const result = validateBlueMarketSnapshot(
68
+ * { chainId, market },
69
+ * { chainId, marketId: params.id },
70
+ * );
71
+ * // result: undefined (the snapshot matched)
72
+ * ```
73
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
74
+ */
75
+ export declare function validateBlueMarketSnapshot(marketData: BlueMarketSnapshot, { chainId, marketId, }: {
76
+ readonly chainId: number;
77
+ readonly marketId: MarketId;
78
+ }): void;
79
+ /**
80
+ * @internal Validates supplied snapshots and the registered Blue targets, then resolves only
81
+ * the prerequisites requested by the operation. The callback derives funding from the
82
+ * validated inputs before any RPC read.
83
+ * An operation that receives a morphoAuthorizationRequestId must reference it
84
+ * in its action and encode the signed authorization in the BlueBundlesV1 call.
85
+ */
86
+ export declare function prepareBlue({ client, params, }: {
87
+ readonly client: Client;
88
+ readonly params: BluePrepareParams;
89
+ }, resolve: (intent: ReturnType<typeof resolveIntent>) => {
90
+ readonly id: string;
91
+ readonly tokenPull?: {
92
+ readonly token: Address;
93
+ readonly amount: bigint;
94
+ };
95
+ readonly needsAuthorization?: boolean;
96
+ }): Promise<{
97
+ intent: import("../intent.js").Intent;
98
+ steps: Step<import("../types.js").Action>[];
99
+ signatureRequests: SignatureRequest[];
100
+ morphoAuthorizationRequestId: string | undefined;
101
+ }>;
102
+ export {};
@@ -0,0 +1,191 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateBlueMarketSnapshot = validateBlueMarketSnapshot;
4
+ exports.prepareBlue = prepareBlue;
5
+ const blue_sdk_viem_1 = require("@morpho-org/blue-sdk-viem");
6
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
7
+ const viem_1 = require("viem");
8
+ const actions_1 = require("viem/actions");
9
+ const validateClientChainId_js_1 = require("../../actions/requirements/validateClientChainId.js");
10
+ const assertContractCode_js_1 = require("../../entities/requirements/assertContractCode.js");
11
+ const validate_js_1 = require("../../helpers/validate.js");
12
+ const index_js_1 = require("../../types/index.js");
13
+ const error_js_1 = require("../error.js");
14
+ const intent_js_1 = require("../intent.js");
15
+ const permit_js_1 = require("../permit.js");
16
+ const requirements_js_1 = require("../requirements.js");
17
+ const authorization_js_1 = require("./authorization.js");
18
+ /**
19
+ * Checks that a caller-fetched Blue market snapshot belongs to the expected chain
20
+ * and market, and that the market ID matches its parameters. Does not read RPC state.
21
+ * @param marketData - Caller-fetched market snapshot.
22
+ * @param expected - Expected chain ID and market ID.
23
+ * @param expected.chainId - Chain on which the market snapshot was read.
24
+ * @param expected.marketId - Market ID to match, regardless of hex casing.
25
+ * @returns Nothing when the snapshot matches the expected chain and market.
26
+ * @throws {BlueSnapshotChainMismatchError} If the snapshot belongs to a different chain.
27
+ * @throws {MarketIdMismatchError} If the snapshot identifies a different market.
28
+ * @example
29
+ * ```ts
30
+ * import { validateBlueMarketSnapshot } from "@morpho-org/morpho-sdk";
31
+ * import { addressesRegistry } from "@morpho-org/morpho-sdk/blue/addresses";
32
+ * import { Market, MarketParams } from "@morpho-org/morpho-sdk/blue/entities";
33
+ * import { mainnet } from "viem/chains";
34
+ *
35
+ * const chainId = mainnet.id;
36
+ * const params = MarketParams.idle(addressesRegistry[chainId].usdc);
37
+ * const market = new Market({
38
+ * params,
39
+ * totalSupplyAssets: 0n,
40
+ * totalSupplyShares: 0n,
41
+ * totalBorrowAssets: 0n,
42
+ * totalBorrowShares: 0n,
43
+ * lastUpdate: 0n,
44
+ * fee: 0n,
45
+ * });
46
+ * const result = validateBlueMarketSnapshot(
47
+ * { chainId, market },
48
+ * { chainId, marketId: params.id },
49
+ * );
50
+ * // result: undefined (the snapshot matched)
51
+ * ```
52
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
53
+ */
54
+ function validateBlueMarketSnapshot(marketData, { chainId, marketId, }) {
55
+ if (marketData.chainId !== chainId) {
56
+ throw new error_js_1.BlueSnapshotChainMismatchError(marketData.chainId, chainId);
57
+ }
58
+ if (!(0, morpho_ts_1.isHexEqual)(marketData.market.id, marketId)) {
59
+ throw new index_js_1.MarketIdMismatchError(marketData.market.id, marketId);
60
+ }
61
+ // Validate that the reported snapshot ID is derived from the market tuple.
62
+ (0, validate_js_1.validateMarketParamsId)(marketData.market.params);
63
+ }
64
+ function validateSnapshots(params) {
65
+ const { chainId, account, marketId, marketData, positionData } = params;
66
+ validateBlueMarketSnapshot(marketData, { chainId, marketId });
67
+ if (positionData === undefined) {
68
+ return;
69
+ }
70
+ if (positionData.chainId !== chainId) {
71
+ throw new error_js_1.BlueSnapshotChainMismatchError(positionData.chainId, chainId);
72
+ }
73
+ const { position } = positionData;
74
+ if (!(0, morpho_ts_1.isHexEqual)(position.marketId, marketId)) {
75
+ throw new index_js_1.MarketIdMismatchError(position.marketId, marketId);
76
+ }
77
+ if (!(0, morpho_ts_1.isHexEqual)(position.market.id, marketId)) {
78
+ throw new index_js_1.MarketIdMismatchError(position.market.id, marketId);
79
+ }
80
+ // Validate the embedded position market before deriving any operation inputs from it.
81
+ (0, validate_js_1.validateMarketParamsId)(position.market.params);
82
+ if (!(0, viem_1.isAddressEqual)(position.user, account)) {
83
+ throw new index_js_1.AccrualPositionUserMismatchError(position.user, account);
84
+ }
85
+ }
86
+ /**
87
+ * @internal Validates supplied snapshots and the registered Blue targets, then resolves only
88
+ * the prerequisites requested by the operation. The callback derives funding from the
89
+ * validated inputs before any RPC read.
90
+ * An operation that receives a morphoAuthorizationRequestId must reference it
91
+ * in its action and encode the signed authorization in the BlueBundlesV1 call.
92
+ */
93
+ async function prepareBlue({ client, params, }, resolve) {
94
+ // Reject mismatched snapshots before deriving operation inputs or reading chain state.
95
+ validateSnapshots(params);
96
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
97
+ const intent = (0, intent_js_1.resolveIntent)(params, now);
98
+ const { id, tokenPull, needsAuthorization } = resolve(intent);
99
+ const { chainId, account } = params;
100
+ const { deadline, supportSignature, deployless } = intent;
101
+ const spender = (0, morpho_ts_1.getChainAddress)(chainId, "bundles.blueBundlesV1");
102
+ const morpho = (0, morpho_ts_1.getChainAddress)(chainId, "blue");
103
+ // Reject missing targets before allowance or authorization reads can fail decoding empty data.
104
+ await (0, assertContractCode_js_1.assertRegistryTargetsHaveCode)(client, chainId, [
105
+ { role: "bundles.blueBundlesV1", address: spender },
106
+ { role: "blue", address: morpho },
107
+ ]);
108
+ const steps = [];
109
+ const signatureRequests = [];
110
+ let morphoAuthorizationRequestId;
111
+ if (tokenPull !== undefined) {
112
+ await (0, validateClientChainId_js_1.validateClientChainId)(client, chainId);
113
+ const { approvals, permit } = await (0, requirements_js_1.getTokenRequirements)(client, {
114
+ ...tokenPull,
115
+ spender,
116
+ owner: account,
117
+ chainId,
118
+ deadline,
119
+ now,
120
+ supportSignature,
121
+ deployless,
122
+ permitId: `${id}:tokenPermit`,
123
+ approvalId: (index) => `${id}:approval:${index + 1}`,
124
+ });
125
+ steps.push(...approvals);
126
+ if (permit !== undefined) {
127
+ // Pin permits to the same BlueBundlesV1 pull that selected the prerequisite.
128
+ (0, permit_js_1.validateTokenPermitRequest)(permit, {
129
+ chainId,
130
+ account,
131
+ deadline,
132
+ bundler: "bundles.blueBundlesV1",
133
+ asset: tokenPull.token,
134
+ amount: tokenPull.amount,
135
+ exact: true,
136
+ });
137
+ signatureRequests.push(permit);
138
+ }
139
+ }
140
+ if (needsAuthorization) {
141
+ if (tokenPull === undefined) {
142
+ await (0, validateClientChainId_js_1.validateClientChainId)(client, chainId);
143
+ }
144
+ const isAuthorized = await (0, actions_1.readContract)(client, {
145
+ abi: blue_sdk_viem_1.blueAbi,
146
+ address: morpho,
147
+ functionName: "isAuthorized",
148
+ args: [account, spender],
149
+ });
150
+ if (!isAuthorized) {
151
+ const authorizationId = `${id}:morphoAuthorization`;
152
+ if (supportSignature) {
153
+ const nonce = await (0, actions_1.readContract)(client, {
154
+ abi: blue_sdk_viem_1.blueAbi,
155
+ address: morpho,
156
+ functionName: "nonce",
157
+ args: [account],
158
+ });
159
+ const request = {
160
+ id: authorizationId,
161
+ kind: "morphoAuthorization",
162
+ args: { authorized: spender, owner: account, nonce, deadline },
163
+ typedData: (0, blue_sdk_viem_1.getAuthorizationTypedData)({
164
+ authorizer: account,
165
+ authorized: spender,
166
+ isAuthorized: true,
167
+ nonce,
168
+ deadline,
169
+ }, chainId),
170
+ };
171
+ // Check the request against the operation's authorization inputs before returning it.
172
+ (0, authorization_js_1.validateMorphoAuthorizationRequest)(request, {
173
+ chainId,
174
+ account,
175
+ nonce,
176
+ deadline,
177
+ });
178
+ signatureRequests.push(request);
179
+ morphoAuthorizationRequestId = authorizationId;
180
+ }
181
+ else {
182
+ steps.push({
183
+ id: authorizationId,
184
+ label: "Authorize BlueBundlesV1 on Morpho",
185
+ action: { type: "morphoAuthorization", inputs: { chainId, account } },
186
+ });
187
+ }
188
+ }
189
+ }
190
+ return { intent, steps, signatureRequests, morphoAuthorizationRequestId };
191
+ }