@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,98 @@
1
+ import { type MarketId } from "@morpho-org/blue-sdk";
2
+ import { type Client } from "viem";
3
+ import type { Funding, IntentParams } from "../intent.js";
4
+ import type { Action, SignatureRequest, TransactionPlan } from "../types.js";
5
+ import { type BlueMarketSnapshot, type BluePositionSnapshot } from "./prepare.js";
6
+ /**
7
+ * Repayment and collateral withdrawal intent. Set `repayShares` to `maxUint256` for full repayment.
8
+ * Native funding wraps the computed repayment cap; omitted funding uses the loan-token balance.
9
+ * @example
10
+ * ```ts
11
+ * import type { BlueRepayWithdrawCollateralPlanParams } from "@morpho-org/morpho-sdk";
12
+ * const native = (params: BlueRepayWithdrawCollateralPlanParams) =>
13
+ * ({ ...params, funding: { type: "native" as const } });
14
+ * ```
15
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
16
+ */
17
+ export type BlueRepayWithdrawCollateralPlanParams = IntentParams & {
18
+ readonly marketId: MarketId;
19
+ readonly marketData: BlueMarketSnapshot;
20
+ readonly positionData: BluePositionSnapshot;
21
+ readonly collateralAssets: bigint;
22
+ /** Defaults to ERC-20; native funding is available only for wNative loan tokens. */
23
+ readonly funding?: Funding;
24
+ readonly now?: bigint;
25
+ } & ({
26
+ readonly repayAssets: bigint;
27
+ readonly repayShares?: never;
28
+ } | {
29
+ readonly repayShares: bigint;
30
+ readonly repayAssets?: never;
31
+ });
32
+ /**
33
+ * Prepares one BlueBundlesV1 repayment and collateral withdrawal from caller-fetched snapshots.
34
+ * Full repayment uses `repayShares: maxUint256`; `funding: { type: "native" }` funds the computed cap.
35
+ * Signatures are embedded in the operation; direct approvals and authorization precede it.
36
+ * @param client - Viem client used only for prerequisite reads.
37
+ * @param params - Intent, position and market snapshots from the same chain and account. Read
38
+ * both snapshots at one block, or use the market embedded in the position snapshot as below.
39
+ * @returns A static plan; collect its pending signatures before building transactions.
40
+ * @throws {BlueSnapshotChainMismatchError} when a market or position snapshot names another chain.
41
+ * @throws {MarketIdMismatchError} when a snapshot's market ID differs from `marketId` or its tuple.
42
+ * @throws {AccrualPositionUserMismatchError} when the position belongs to another account.
43
+ * @throws {BlueSnapshotStateMismatchError} when the market snapshot's state differs from the
44
+ * market embedded in the position snapshot.
45
+ * @throws {ZeroAccountError} when `account` is the zero address.
46
+ * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
47
+ * @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty or malformed hex bytes.
48
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before the reference timestamp.
49
+ * @throws {NegativeInputError} when an amount or referral fee is negative.
50
+ * @throws {NonPositiveInputError} when the expiry is not positive, both operation legs are zero,
51
+ * a repay leg has no positive funding cap, or native funding is set without a repay leg.
52
+ * @throws {InputExceedsMaxError} when a value exceeds uint256, referral basis points exceed
53
+ * 10,000, or a share-mode expiry exceeds the two-hour funding quote horizon.
54
+ * @throws {ReferralFeePctExceededError} when referral basis points equal 10,000.
55
+ * @throws {ReferralFeeRecipientMissingError} when a positive fee has no non-zero recipient.
56
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports, another chain.
57
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
58
+ * @throws {UnknownAddressError} when a required contract is not registered on the chain.
59
+ * @throws {UnsupportedBlueMarketIrmError} when debt projection requires an unsupported IRM.
60
+ * @throws {MutuallyExclusiveRepayAmountsError} when both repayment amounts are non-zero at runtime.
61
+ * @throws {RepayExceedsDebtError} when exact repayment assets exceed the position's debt.
62
+ * @throws {RepaySharesExceedDebtError} when non-saturated repayment shares exceed borrow shares.
63
+ * @throws {WithdrawExceedsCollateralError} when the requested withdrawal exceeds collateral.
64
+ * @throws {MissingMarketPriceError} when withdrawal health cannot be checked without a price.
65
+ * @throws {WithdrawMakesPositionUnhealthyError} when the post-repay withdrawal exceeds buffered LLTV.
66
+ * @throws {ChainWNativeMissingError} when native funding is requested on a chain without wNative.
67
+ * @throws {NativeAmountOnNonWNativeAssetError} when native funding targets a loan token other than wNative.
68
+ * @throws {UnknownTokenError} when permit metadata has no usable token decimals.
69
+ * @throws {MalformedTokenMetadataError} when token metadata returns malformed non-empty data.
70
+ * @throws {UnexpectedRequirementSignatureError} when a signable prerequisite has no bigint nonce.
71
+ * @throws {TransactionPlanSignatureMismatchError} when a permit request disagrees with the exact token pull.
72
+ * @throws {MissingContractCodeError} when BlueBundlesV1 or Morpho Blue has no deployed code.
73
+ * @throws {IncompleteTransactionPlanError} when no operation inputs were resolved during preparation.
74
+ * @throws {viem.BaseError} when an allowance, nonce, metadata, authorization, chain ID or bytecode read fails.
75
+ * @example
76
+ * ```ts
77
+ * import { prepareBlueRepayWithdrawCollateral, type BlueRepayWithdrawCollateralPlanParams } from "@morpho-org/morpho-sdk";
78
+ * import type { Client } from "viem";
79
+ * type AssetsParams = Extract<BlueRepayWithdrawCollateralPlanParams, { readonly repayAssets: bigint }>;
80
+ * const prepare = (client: Client, params: Omit<AssetsParams, "marketData">) =>
81
+ * prepareBlueRepayWithdrawCollateral(client, {
82
+ * ...params,
83
+ * marketData: { chainId: params.chainId, market: params.positionData.position.market },
84
+ * });
85
+ * ```
86
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
87
+ */
88
+ export declare function prepareBlueRepayWithdrawCollateral(client: Client, params: BlueRepayWithdrawCollateralPlanParams): Promise<TransactionPlan>;
89
+ /** @internal Checks signature bindings for the combined operation. */
90
+ export declare function validateRepayWithdrawCollateralRequest(request: SignatureRequest, action: Extract<Action, {
91
+ type: "blueRepayWithdrawCollateral";
92
+ }>): void;
93
+ /** @internal Builds without a client, snapshot, or mutable preparation state. */
94
+ export declare function buildBlueRepayWithdrawCollateral(action: Extract<Action, {
95
+ type: "blueRepayWithdrawCollateral";
96
+ }>, requests: readonly SignatureRequest[]): Readonly<import("../../types/action.js").Transaction<import("../../types/action.js").BlueRepayWithdrawCollateralAction>>;
97
+ /** @internal Validates stored combined-operation input shapes. */
98
+ export declare function validateRepayWithdrawCollateralPlanAction(action: Record<string, unknown>, path: string): void;
@@ -0,0 +1,373 @@
1
+ import { AccrualPosition, MarketParams, MathLib, } from "@morpho-org/blue-sdk";
2
+ import { deepFreeze, Time } from "@morpho-org/morpho-ts";
3
+ import { maxUint256 } from "viem";
4
+ import { getBlueBundlesV1ReferralFeeAssets, normalizeBlueBundlesV1CommonParams, validateBlueBundlesV1NativeFunding, } from "../../actions/blue/common.js";
5
+ import { blueRepayWithdrawCollateral } from "../../actions/blue/repayWithdrawCollateral.js";
6
+ import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
7
+ import { DEFAULT_LLTV_BUFFER, validateChainId, validatePositionHealthAfterWithdraw, } from "../../helpers/index.js";
8
+ import { quoteBlueRepay, quoteBlueRepayFunding, } from "../../helpers/quoteBlueRepay.js";
9
+ import { MutuallyExclusiveRepayAmountsError, NegativeInputError, NonPositiveInputError, } from "../../types/index.js";
10
+ import { BlueSnapshotStateMismatchError, IncompleteTransactionPlanError, InvalidTransactionPlanError, TransactionPlanSignatureMismatchError, } from "../error.js";
11
+ import { getVaultPermit, validateTokenPermitRequest } from "../permit.js";
12
+ import { getPlanObject, validatePlanFields } from "../validation.js";
13
+ import { validateMorphoAuthorizationRequest } from "./authorization.js";
14
+ import { prepareBlue, } from "./prepare.js";
15
+ /**
16
+ * Prepares one BlueBundlesV1 repayment and collateral withdrawal from caller-fetched snapshots.
17
+ * Full repayment uses `repayShares: maxUint256`; `funding: { type: "native" }` funds the computed cap.
18
+ * Signatures are embedded in the operation; direct approvals and authorization precede it.
19
+ * @param client - Viem client used only for prerequisite reads.
20
+ * @param params - Intent, position and market snapshots from the same chain and account. Read
21
+ * both snapshots at one block, or use the market embedded in the position snapshot as below.
22
+ * @returns A static plan; collect its pending signatures before building transactions.
23
+ * @throws {BlueSnapshotChainMismatchError} when a market or position snapshot names another chain.
24
+ * @throws {MarketIdMismatchError} when a snapshot's market ID differs from `marketId` or its tuple.
25
+ * @throws {AccrualPositionUserMismatchError} when the position belongs to another account.
26
+ * @throws {BlueSnapshotStateMismatchError} when the market snapshot's state differs from the
27
+ * market embedded in the position snapshot.
28
+ * @throws {ZeroAccountError} when `account` is the zero address.
29
+ * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
30
+ * @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty or malformed hex bytes.
31
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before the reference timestamp.
32
+ * @throws {NegativeInputError} when an amount or referral fee is negative.
33
+ * @throws {NonPositiveInputError} when the expiry is not positive, both operation legs are zero,
34
+ * a repay leg has no positive funding cap, or native funding is set without a repay leg.
35
+ * @throws {InputExceedsMaxError} when a value exceeds uint256, referral basis points exceed
36
+ * 10,000, or a share-mode expiry exceeds the two-hour funding quote horizon.
37
+ * @throws {ReferralFeePctExceededError} when referral basis points equal 10,000.
38
+ * @throws {ReferralFeeRecipientMissingError} when a positive fee has no non-zero recipient.
39
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports, another chain.
40
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
41
+ * @throws {UnknownAddressError} when a required contract is not registered on the chain.
42
+ * @throws {UnsupportedBlueMarketIrmError} when debt projection requires an unsupported IRM.
43
+ * @throws {MutuallyExclusiveRepayAmountsError} when both repayment amounts are non-zero at runtime.
44
+ * @throws {RepayExceedsDebtError} when exact repayment assets exceed the position's debt.
45
+ * @throws {RepaySharesExceedDebtError} when non-saturated repayment shares exceed borrow shares.
46
+ * @throws {WithdrawExceedsCollateralError} when the requested withdrawal exceeds collateral.
47
+ * @throws {MissingMarketPriceError} when withdrawal health cannot be checked without a price.
48
+ * @throws {WithdrawMakesPositionUnhealthyError} when the post-repay withdrawal exceeds buffered LLTV.
49
+ * @throws {ChainWNativeMissingError} when native funding is requested on a chain without wNative.
50
+ * @throws {NativeAmountOnNonWNativeAssetError} when native funding targets a loan token other than wNative.
51
+ * @throws {UnknownTokenError} when permit metadata has no usable token decimals.
52
+ * @throws {MalformedTokenMetadataError} when token metadata returns malformed non-empty data.
53
+ * @throws {UnexpectedRequirementSignatureError} when a signable prerequisite has no bigint nonce.
54
+ * @throws {TransactionPlanSignatureMismatchError} when a permit request disagrees with the exact token pull.
55
+ * @throws {MissingContractCodeError} when BlueBundlesV1 or Morpho Blue has no deployed code.
56
+ * @throws {IncompleteTransactionPlanError} when no operation inputs were resolved during preparation.
57
+ * @throws {viem.BaseError} when an allowance, nonce, metadata, authorization, chain ID or bytecode read fails.
58
+ * @example
59
+ * ```ts
60
+ * import { prepareBlueRepayWithdrawCollateral, type BlueRepayWithdrawCollateralPlanParams } from "@morpho-org/morpho-sdk";
61
+ * import type { Client } from "viem";
62
+ * type AssetsParams = Extract<BlueRepayWithdrawCollateralPlanParams, { readonly repayAssets: bigint }>;
63
+ * const prepare = (client: Client, params: Omit<AssetsParams, "marketData">) =>
64
+ * prepareBlueRepayWithdrawCollateral(client, {
65
+ * ...params,
66
+ * marketData: { chainId: params.chainId, market: params.positionData.position.market },
67
+ * });
68
+ * ```
69
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
70
+ */
71
+ export async function prepareBlueRepayWithdrawCollateral(client, params) {
72
+ const id = "blueRepayWithdrawCollateral";
73
+ const now = params.now ?? Time.timestamp();
74
+ let inputs;
75
+ const prepared = await prepareBlue({ client, params: { ...params, now } }, (intent) => {
76
+ const marketParams = params.marketData.market.params;
77
+ // Reject chain and referral mismatches before deriving a repayment quote.
78
+ validateChainId(client.chain?.id, params.chainId);
79
+ const common = normalizeBlueBundlesV1CommonParams({
80
+ chainId: params.chainId,
81
+ userAddress: params.account,
82
+ deadline: intent.deadline,
83
+ referralFeePct: intent.referralFeePct,
84
+ referralFeeRecipient: intent.referralFeeRecipient,
85
+ });
86
+ const { repayAssets, repayShares, collateralAssets, hasRepay } = getRepayWithdrawAmounts(params);
87
+ const quoteParams = {
88
+ positionData: getMatchingPosition(params),
89
+ marketId: params.marketId,
90
+ repayAssets,
91
+ repayShares,
92
+ deadline: intent.deadline,
93
+ now,
94
+ };
95
+ const healthQuote = collateralAssets > 0n ? quoteBlueRepay(quoteParams) : undefined;
96
+ const expectedRepayAssets = healthQuote?.expectedRepayAssets ?? quoteBlueRepayFunding(quoteParams);
97
+ const maxRepayAssets = expectedRepayAssets +
98
+ getBlueBundlesV1ReferralFeeAssets(expectedRepayAssets, common.referralFeePct);
99
+ const nativeValue = validateBlueBundlesV1NativeFunding({
100
+ chainId: params.chainId,
101
+ token: marketParams.loanToken,
102
+ fundedAmount: maxRepayAssets,
103
+ nativeAmount: params.funding?.type === "native" ? maxRepayAssets : undefined,
104
+ });
105
+ if (healthQuote !== undefined) {
106
+ const { accruedPosition, simulatedRepayShares } = healthQuote;
107
+ const postRepayPosition = hasRepay
108
+ ? accruedPosition.repay(repayAssets, simulatedRepayShares).position
109
+ : accruedPosition;
110
+ // Reject withdrawals that leave debt above the buffered LLTV.
111
+ validatePositionHealthAfterWithdraw({
112
+ positionData: postRepayPosition,
113
+ withdrawAmount: collateralAssets,
114
+ lltv: marketParams.lltv,
115
+ marketId: params.marketData.market.id,
116
+ });
117
+ }
118
+ const tx = blueRepayWithdrawCollateral({
119
+ market: { chainId: params.chainId, marketParams },
120
+ args: {
121
+ userAddress: params.account,
122
+ repayAssets,
123
+ repayShares,
124
+ maxRepayAssets,
125
+ collateralAssets,
126
+ maxLtv: collateralAssets > 0n
127
+ ? MathLib.zeroFloorSub(marketParams.lltv, DEFAULT_LLTV_BUFFER)
128
+ : maxUint256,
129
+ nativeAmount: nativeValue > 0n ? nativeValue : undefined,
130
+ deadline: intent.deadline,
131
+ ...common,
132
+ },
133
+ });
134
+ const { market: _market, onBehalf: _onBehalf, referralFeeAssets: _fee, nativeAmount, ...args } = tx.action.args;
135
+ inputs = {
136
+ ...args,
137
+ ...(nativeAmount !== undefined && { nativeAssets: nativeAmount }),
138
+ chainId: params.chainId,
139
+ account: params.account,
140
+ marketParams: {
141
+ loanToken: marketParams.loanToken,
142
+ collateralToken: marketParams.collateralToken,
143
+ oracle: marketParams.oracle,
144
+ irm: marketParams.irm,
145
+ lltv: marketParams.lltv,
146
+ },
147
+ };
148
+ return {
149
+ id,
150
+ tokenPull: args.maxRepayAssets > 0n && !nativeAmount
151
+ ? { token: marketParams.loanToken, amount: args.maxRepayAssets }
152
+ : undefined,
153
+ needsAuthorization: args.collateralAssets > 0n,
154
+ };
155
+ });
156
+ await validateClientChainId(client, params.chainId);
157
+ if (inputs === undefined) {
158
+ throw new IncompleteTransactionPlanError(id);
159
+ }
160
+ const signatureRequestIds = Object.fromEntries(prepared.signatureRequests
161
+ .filter((request) => request.kind === "permit")
162
+ .map((request) => ["tokenPermit", request.id]));
163
+ if (prepared.morphoAuthorizationRequestId !== undefined) {
164
+ signatureRequestIds.morphoAuthorization =
165
+ prepared.morphoAuthorizationRequestId;
166
+ }
167
+ const authorization = prepared.signatureRequests.find((request) => request.kind === "morphoAuthorization");
168
+ if (authorization !== undefined) {
169
+ inputs = { ...inputs, authorizationNonce: authorization.args.nonce };
170
+ }
171
+ return deepFreeze(structuredClone({
172
+ version: 2,
173
+ chainId: params.chainId,
174
+ account: params.account,
175
+ expiresAt: prepared.intent.expiresAt,
176
+ calldataOrigin: prepared.intent.calldataOrigin,
177
+ steps: [
178
+ ...prepared.steps,
179
+ {
180
+ id,
181
+ label: getRepayWithdrawLabel(inputs),
182
+ action: { type: id, inputs, signatureRequestIds },
183
+ },
184
+ ],
185
+ signatureRequests: prepared.signatureRequests,
186
+ }));
187
+ }
188
+ function getRepayWithdrawLabel(inputs) {
189
+ if (inputs.collateralAssets === 0n) {
190
+ return "Repay Blue debt";
191
+ }
192
+ if (inputs.repayAssets === 0n && inputs.repayShares === 0n) {
193
+ return "Withdraw Blue collateral";
194
+ }
195
+ return "Repay and withdraw collateral";
196
+ }
197
+ const MARKET_STATE_FIELDS = [
198
+ "totalSupplyAssets",
199
+ "totalSupplyShares",
200
+ "totalBorrowAssets",
201
+ "totalBorrowShares",
202
+ "lastUpdate",
203
+ "fee",
204
+ "price",
205
+ "rateAtTarget",
206
+ ];
207
+ function getMatchingPosition(params) {
208
+ const { position } = params.positionData;
209
+ const positionMarket = position.market;
210
+ const { market } = params.marketData;
211
+ for (const field of MARKET_STATE_FIELDS) {
212
+ if (positionMarket[field] !== market[field]) {
213
+ throw new BlueSnapshotStateMismatchError({
214
+ field,
215
+ positionValue: positionMarket[field],
216
+ marketValue: market[field],
217
+ });
218
+ }
219
+ }
220
+ return new AccrualPosition(position, positionMarket);
221
+ }
222
+ function getRepayWithdrawAmounts(params) {
223
+ const { collateralAssets, marketId } = params;
224
+ const repayAssets = params.repayAssets ?? 0n;
225
+ const repayShares = params.repayShares ?? 0n;
226
+ if (repayAssets < 0n) {
227
+ throw new NegativeInputError("repayAssets", repayAssets);
228
+ }
229
+ if (repayShares < 0n) {
230
+ throw new NegativeInputError("repayShares", repayShares);
231
+ }
232
+ if (collateralAssets < 0n) {
233
+ throw new NegativeInputError("collateralAssets", collateralAssets);
234
+ }
235
+ if (repayAssets > 0n && repayShares > 0n) {
236
+ throw new MutuallyExclusiveRepayAmountsError(marketId);
237
+ }
238
+ const hasRepay = repayAssets > 0n || repayShares > 0n;
239
+ if (!hasRepay && params.funding?.type === "native") {
240
+ throw new NonPositiveInputError("repayAssets or repayShares", 0n);
241
+ }
242
+ if (!hasRepay && collateralAssets === 0n) {
243
+ throw new NonPositiveInputError("repayAssets, repayShares, or collateralAssets", 0n);
244
+ }
245
+ return { repayAssets, repayShares, collateralAssets, hasRepay };
246
+ }
247
+ /** @internal Checks signature bindings for the combined operation. */
248
+ export function validateRepayWithdrawCollateralRequest(request, action) {
249
+ const { chainId, account, deadline, marketParams, maxRepayAssets } = action.inputs;
250
+ if (request.kind === "permit" &&
251
+ action.signatureRequestIds.tokenPermit === request.id) {
252
+ if ((action.inputs.nativeAssets ?? 0n) > 0n ||
253
+ (action.inputs.repayAssets === 0n && action.inputs.repayShares === 0n) ||
254
+ maxRepayAssets === 0n) {
255
+ throw new TransactionPlanSignatureMismatchError(request.id, "reference");
256
+ }
257
+ // Reject a permit that does not authorize this exact token pull.
258
+ validateTokenPermitRequest(request, {
259
+ chainId,
260
+ account,
261
+ deadline,
262
+ bundler: "bundles.blueBundlesV1",
263
+ asset: marketParams.loanToken,
264
+ amount: maxRepayAssets,
265
+ exact: true,
266
+ });
267
+ return;
268
+ }
269
+ if (request.kind === "morphoAuthorization" &&
270
+ action.signatureRequestIds.morphoAuthorization === request.id &&
271
+ action.inputs.collateralAssets > 0n &&
272
+ action.inputs.authorizationNonce !== undefined) {
273
+ // Reject an authorization that does not grant this account's bundle access.
274
+ validateMorphoAuthorizationRequest(request, {
275
+ chainId,
276
+ account,
277
+ deadline,
278
+ nonce: action.inputs.authorizationNonce,
279
+ });
280
+ return;
281
+ }
282
+ throw new TransactionPlanSignatureMismatchError(request.id, "reference");
283
+ }
284
+ /** @internal Builds without a client, snapshot, or mutable preparation state. */
285
+ export function buildBlueRepayWithdrawCollateral(action, requests) {
286
+ const { chainId, account, marketParams, nativeAssets, authorizationNonce: _authorizationNonce, ...args } = action.inputs;
287
+ const requirementSignature = getVaultPermit(requests, {
288
+ id: action.signatureRequestIds.tokenPermit,
289
+ asset: marketParams.loanToken,
290
+ owner: account,
291
+ });
292
+ let authorizationSignature;
293
+ const id = action.signatureRequestIds.morphoAuthorization;
294
+ if (id !== undefined) {
295
+ const request = requests.find((candidate) => candidate.id === id);
296
+ if (request?.signature === undefined) {
297
+ throw new IncompleteTransactionPlanError(id);
298
+ }
299
+ if (request.kind !== "morphoAuthorization") {
300
+ throw new TransactionPlanSignatureMismatchError(id, "reference");
301
+ }
302
+ authorizationSignature = {
303
+ action: {
304
+ type: "authorization",
305
+ args: { ...request.args, isAuthorized: true },
306
+ typedData: request.typedData,
307
+ },
308
+ args: {
309
+ ...request.args,
310
+ isAuthorized: true,
311
+ signature: request.signature,
312
+ },
313
+ };
314
+ }
315
+ return blueRepayWithdrawCollateral({
316
+ market: { chainId, marketParams: new MarketParams(marketParams) },
317
+ args: {
318
+ ...args,
319
+ nativeAmount: nativeAssets,
320
+ userAddress: account,
321
+ requirementSignature,
322
+ authorizationSignature,
323
+ },
324
+ });
325
+ }
326
+ /** @internal Validates stored combined-operation input shapes. */
327
+ export function validateRepayWithdrawCollateralPlanAction(action, path) {
328
+ const inputs = getPlanObject(action.inputs, `${path}.inputs`);
329
+ validatePlanFields(inputs, {
330
+ path: `${path}.inputs`,
331
+ fields: {
332
+ repayAssets: "uint256 bigint",
333
+ repayShares: "uint256 bigint",
334
+ maxRepayAssets: "uint256 bigint",
335
+ collateralAssets: "uint256 bigint",
336
+ maxLtv: "uint256 bigint",
337
+ deadline: "uint256 bigint",
338
+ referralFeePct: "uint256 bigint",
339
+ referralFeeRecipient: "address",
340
+ },
341
+ });
342
+ if (inputs.repayAssets > 0n &&
343
+ inputs.repayShares > 0n) {
344
+ throw new InvalidTransactionPlanError({
345
+ path: `${path}.inputs`,
346
+ reason: "repayAssets and repayShares are mutually exclusive",
347
+ });
348
+ }
349
+ if (inputs.nativeAssets !== undefined) {
350
+ validatePlanFields(inputs, {
351
+ path: `${path}.inputs`,
352
+ fields: { nativeAssets: "uint256 bigint" },
353
+ });
354
+ }
355
+ validatePlanFields(getPlanObject(inputs.marketParams, `${path}.inputs.marketParams`), {
356
+ path: `${path}.inputs.marketParams`,
357
+ fields: {
358
+ loanToken: "address",
359
+ collateralToken: "address",
360
+ oracle: "address",
361
+ irm: "address",
362
+ lltv: "uint256 bigint",
363
+ },
364
+ });
365
+ const ids = getPlanObject(action.signatureRequestIds, `${path}.signatureRequestIds`);
366
+ if (inputs.authorizationNonce !== undefined ||
367
+ ids.morphoAuthorization !== undefined) {
368
+ validatePlanFields(inputs, {
369
+ path: `${path}.inputs`,
370
+ fields: { authorizationNonce: "uint256 bigint" },
371
+ });
372
+ }
373
+ }
@@ -0,0 +1,181 @@
1
+ import { type MarketId } from "@morpho-org/blue-sdk";
2
+ import type { Client } from "viem";
3
+ import type { ReferenceTimestampParams } from "../../types/index.js";
4
+ import type { Funding, IntentParams } from "../intent.js";
5
+ import type { Action, SignatureRequest, TransactionPlan } from "../types.js";
6
+ import { type BlueMarketSnapshot } from "./prepare.js";
7
+ /**
8
+ * Intent for supplying gross loan assets to a Blue market. The snapshot is validated but not stored.
9
+ * @example
10
+ * ```ts
11
+ * import { MarketParams } from "@morpho-org/morpho-sdk/blue/entities";
12
+ * import { fetchMarket } from "@morpho-org/morpho-sdk/blue/fetch";
13
+ * import {
14
+ * applySignatures, buildTransactions, getPendingSignatureRequests,
15
+ * prepareBlueSupply, type BlueSupplyPlanParams,
16
+ * } from "@morpho-org/morpho-sdk";
17
+ * import {
18
+ * createPublicClient, createWalletClient, custom, http, type EIP1193Provider,
19
+ * } from "viem";
20
+ * import { mainnet } from "viem/chains";
21
+ *
22
+ * // Run in a browser with an injected wallet connected to Ethereum mainnet.
23
+ * const { ethereum } = window as Window & { ethereum?: EIP1193Provider };
24
+ * if (!ethereum) throw new Error("Install an Ethereum wallet to continue.");
25
+ * const walletClient = createWalletClient({
26
+ * chain: mainnet, transport: custom(ethereum),
27
+ * });
28
+ * const [account] = await walletClient.requestAddresses();
29
+ * if (!account) throw new Error("Connect a wallet before preparing supply.");
30
+ * const publicClient = createPublicClient({
31
+ * chain: mainnet, transport: http(),
32
+ * });
33
+ * // cbBTC collateral / USDC loan market on Ethereum.
34
+ * const marketParams = new MarketParams({
35
+ * loanToken: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
36
+ * collateralToken: "0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf",
37
+ * oracle: "0xA6D6950c9F177F1De7f7757FB33539e3Ec60182a",
38
+ * irm: "0x870aC11D48B15DB9a138Cf899d20F13F79Ba00BC",
39
+ * lltv: 860_000_000_000_000_000n,
40
+ * });
41
+ * const block = await publicClient.getBlock();
42
+ * const market = await fetchMarket(marketParams.id, publicClient, {
43
+ * blockNumber: block.number,
44
+ * });
45
+ * const params: BlueSupplyPlanParams = {
46
+ * chainId: mainnet.id,
47
+ * account,
48
+ * marketId: market.id,
49
+ * marketData: { chainId: mainnet.id, market },
50
+ * assets: 1_000_000n, // Supply 1 USDC, before any referral fee.
51
+ * funding: { type: "erc20" },
52
+ * supportSignature: true,
53
+ * now: block.timestamp,
54
+ * expiresAt: Number(block.timestamp + 1_200n),
55
+ * };
56
+ * const plan = await prepareBlueSupply(publicClient, params);
57
+ * const signatures = await Promise.all(
58
+ * getPendingSignatureRequests(plan).map(async (request) => ({
59
+ * id: request.id,
60
+ * signature: await walletClient.signTypedData({
61
+ * ...request.typedData, account,
62
+ * }),
63
+ * })),
64
+ * );
65
+ * const signedPlan = applySignatures(plan, signatures);
66
+ * const transactions = buildTransactions(signedPlan);
67
+ * // transactions: readonly Readonly<Transaction>[].
68
+ * // An optional ERC-20 approval precedes the BlueBundlesV1 supply transaction;
69
+ * // an ERC-2612 permit is embedded in supply instead. No Permit2 is used.
70
+ * // Simulate, then send each { to, data, value } in order from account on mainnet.
71
+ * ```
72
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
73
+ */
74
+ export interface BlueSupplyPlanParams extends IntentParams, ReferenceTimestampParams {
75
+ readonly marketId: MarketId;
76
+ readonly marketData: BlueMarketSnapshot;
77
+ /** Positive gross loan-token amount, before referral fees. */
78
+ readonly assets: bigint;
79
+ /** Defaults to ERC-20; native funding requires wNative and stores `nativeAssets = assets`. */
80
+ readonly funding?: Funding;
81
+ }
82
+ /** @internal Validates the stored supply recipe without requiring class instances. */
83
+ export declare function validateBlueSupplyPlanAction(action: Record<string, unknown>, path: string): void;
84
+ /**
85
+ * Prepares a static BlueBundlesV1 supply plan from a caller-fetched market snapshot.
86
+ * Insufficient allowance produces an unlimited direct approval, or an exact ERC-2612 permit
87
+ * when supported and requested. Native funding requires wNative and produces no token prerequisite.
88
+ * No Permit2 or Morpho authorization is requested. Only signatures are added before building.
89
+ * @param client - Viem client for the intent chain, used for prerequisite and deployment reads.
90
+ * @param params - Account, chain, snapshot, gross assets and shared funding/fee/expiry intent.
91
+ * @returns A frozen plan with funding prerequisites followed by the supply transaction.
92
+ * @throws {ZeroAccountError} when `account` is the zero address.
93
+ * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
94
+ * @throws {NonPositiveInputError} when `expiresAt`, `assets` or the deadline is not positive.
95
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before `now` (device clock when `now` is omitted).
96
+ * @throws {NegativeInputError} when `referralFee.bps` is negative.
97
+ * @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 10,000 or `assets` exceeds uint256.
98
+ * @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty, malformed or has an odd number of hex digits.
99
+ * @throws {ReferralFeePctExceededError} when `referralFee.bps` equals 10,000; the normalized fee must be below WAD.
100
+ * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient or a zero recipient.
101
+ * @throws {MarketIdMismatchError} When the snapshot describes another market.
102
+ * @throws {BlueSnapshotChainMismatchError} When the snapshot describes another chain.
103
+ * @throws {NativeAmountOnNonWNativeAssetError} When native funding targets another token.
104
+ * @throws {ChainIdMismatchError} When the client targets another chain.
105
+ * @throws {MissingContractCodeError} When BlueBundlesV1 or Morpho is not deployed.
106
+ * @example
107
+ * ```ts
108
+ * import { MarketParams } from "@morpho-org/morpho-sdk/blue/entities";
109
+ * import { fetchMarket } from "@morpho-org/morpho-sdk/blue/fetch";
110
+ * import {
111
+ * applySignatures, buildTransactions, getPendingSignatureRequests,
112
+ * prepareBlueSupply, type BlueSupplyPlanParams,
113
+ * } from "@morpho-org/morpho-sdk";
114
+ * import {
115
+ * createPublicClient, createWalletClient, custom, http, type EIP1193Provider,
116
+ * } from "viem";
117
+ * import { mainnet } from "viem/chains";
118
+ *
119
+ * // Run in a browser with an injected wallet connected to Ethereum mainnet.
120
+ * const { ethereum } = window as Window & { ethereum?: EIP1193Provider };
121
+ * if (!ethereum) throw new Error("Install an Ethereum wallet to continue.");
122
+ * const walletClient = createWalletClient({
123
+ * chain: mainnet, transport: custom(ethereum),
124
+ * });
125
+ * const [account] = await walletClient.requestAddresses();
126
+ * if (!account) throw new Error("Connect a wallet before preparing supply.");
127
+ * const publicClient = createPublicClient({
128
+ * chain: mainnet, transport: http(),
129
+ * });
130
+ * // cbBTC collateral / USDC loan market on Ethereum.
131
+ * const marketParams = new MarketParams({
132
+ * loanToken: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
133
+ * collateralToken: "0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf",
134
+ * oracle: "0xA6D6950c9F177F1De7f7757FB33539e3Ec60182a",
135
+ * irm: "0x870aC11D48B15DB9a138Cf899d20F13F79Ba00BC",
136
+ * lltv: 860_000_000_000_000_000n,
137
+ * });
138
+ * const block = await publicClient.getBlock();
139
+ * const market = await fetchMarket(marketParams.id, publicClient, {
140
+ * blockNumber: block.number,
141
+ * });
142
+ * const params: BlueSupplyPlanParams = {
143
+ * chainId: mainnet.id,
144
+ * account,
145
+ * marketId: market.id,
146
+ * marketData: { chainId: mainnet.id, market },
147
+ * assets: 1_000_000n, // Supply 1 USDC, before any referral fee.
148
+ * funding: { type: "erc20" },
149
+ * supportSignature: true,
150
+ * now: block.timestamp,
151
+ * expiresAt: Number(block.timestamp + 1_200n),
152
+ * };
153
+ * const plan = await prepareBlueSupply(publicClient, params);
154
+ * const signatures = await Promise.all(
155
+ * getPendingSignatureRequests(plan).map(async (request) => ({
156
+ * id: request.id,
157
+ * signature: await walletClient.signTypedData({
158
+ * ...request.typedData, account,
159
+ * }),
160
+ * })),
161
+ * );
162
+ * const signedPlan = applySignatures(plan, signatures);
163
+ * const transactions = buildTransactions(signedPlan);
164
+ * // transactions: readonly Readonly<Transaction>[].
165
+ * // An optional ERC-20 approval precedes the BlueBundlesV1 supply transaction;
166
+ * // an ERC-2612 permit is embedded in supply instead. No Permit2 is used.
167
+ * // Simulate, then send each { to, data, value } in order from account on mainnet.
168
+ * ```
169
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
170
+ */
171
+ export declare function prepareBlueSupply(client: Client, params: BlueSupplyPlanParams): Promise<TransactionPlan>;
172
+ /** @internal Binds an exact token permit to this supply's pull. */
173
+ export declare function validateBlueSupplyPermitRequest(request: Extract<SignatureRequest, {
174
+ kind: "permit";
175
+ }>, action: Extract<Action, {
176
+ type: "blueSupply";
177
+ }>): void;
178
+ /** @internal Encodes supply from stored inputs and resolved signatures without a client. */
179
+ export declare function buildBlueSupply(action: Extract<Action, {
180
+ type: "blueSupply";
181
+ }>, requests: readonly SignatureRequest[]): Readonly<import("../../types/action.js").Transaction<import("../../types/action.js").BlueSupplyAction>>;