@morpho-org/morpho-sdk 10.1.0 → 10.3.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 (260) hide show
  1. package/README.md +126 -140
  2. package/lib/cjs/abis.d.ts +34 -0
  3. package/lib/cjs/abis.js +21 -1
  4. package/lib/cjs/actions/blue/borrow.d.ts +11 -3
  5. package/lib/cjs/actions/blue/borrow.internal.js +1 -0
  6. package/lib/cjs/actions/blue/borrow.js +8 -2
  7. package/lib/cjs/actions/blue/common.d.ts +4 -1
  8. package/lib/cjs/actions/blue/common.js +17 -3
  9. package/lib/cjs/actions/blue/refinance.d.ts +11 -3
  10. package/lib/cjs/actions/blue/refinance.internal.js +4 -1
  11. package/lib/cjs/actions/blue/refinance.js +8 -2
  12. package/lib/cjs/actions/blue/refinanceValidation.d.ts +3 -2
  13. package/lib/cjs/actions/blue/refinanceValidation.js +10 -6
  14. package/lib/cjs/actions/blue/repay.d.ts +4 -3
  15. package/lib/cjs/actions/blue/repay.js +3 -2
  16. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +4 -3
  17. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +3 -2
  18. package/lib/cjs/actions/blue/supply.d.ts +5 -3
  19. package/lib/cjs/actions/blue/supply.js +4 -2
  20. package/lib/cjs/actions/blue/supplyCollateral.d.ts +4 -3
  21. package/lib/cjs/actions/blue/supplyCollateral.js +3 -2
  22. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +11 -3
  23. package/lib/cjs/actions/blue/supplyCollateralBorrow.internal.d.ts +2 -0
  24. package/lib/cjs/actions/blue/supplyCollateralBorrow.internal.js +5 -1
  25. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +8 -2
  26. package/lib/cjs/actions/blue/withdraw.d.ts +11 -3
  27. package/lib/cjs/actions/blue/withdraw.internal.js +4 -1
  28. package/lib/cjs/actions/blue/withdraw.js +8 -2
  29. package/lib/cjs/actions/blue/withdrawCollateral.d.ts +4 -3
  30. package/lib/cjs/actions/blue/withdrawCollateral.js +3 -2
  31. package/lib/cjs/actions/bundles/common.d.ts +2 -8
  32. package/lib/cjs/actions/bundles/common.js +8 -20
  33. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +0 -1
  34. package/lib/cjs/actions/midnight/takeBorrow.js +0 -1
  35. package/lib/cjs/actions/midnight/takeLend.js +0 -1
  36. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +0 -1
  37. package/lib/cjs/actions/midnight/takeWithdraw.js +0 -1
  38. package/lib/cjs/actions/vaultV1/deposit.d.ts +2 -1
  39. package/lib/cjs/actions/vaultV1/deposit.js +2 -1
  40. package/lib/cjs/actions/vaultV1/migrateToV2.d.ts +3 -2
  41. package/lib/cjs/actions/vaultV1/migrateToV2.js +2 -1
  42. package/lib/cjs/actions/vaultV1/redeem.d.ts +3 -2
  43. package/lib/cjs/actions/vaultV1/redeem.js +2 -1
  44. package/lib/cjs/actions/vaultV1/withdraw.d.ts +2 -1
  45. package/lib/cjs/actions/vaultV1/withdraw.js +2 -1
  46. package/lib/cjs/actions/vaultV2/deposit.d.ts +2 -1
  47. package/lib/cjs/actions/vaultV2/deposit.js +2 -1
  48. package/lib/cjs/actions/vaultV2/forceWithdraw.d.ts +2 -1
  49. package/lib/cjs/actions/vaultV2/forceWithdraw.js +2 -1
  50. package/lib/cjs/actions/vaultV2/redeem.d.ts +3 -2
  51. package/lib/cjs/actions/vaultV2/redeem.js +2 -1
  52. package/lib/cjs/actions/vaultV2/withdraw.d.ts +2 -1
  53. package/lib/cjs/actions/vaultV2/withdraw.js +2 -1
  54. package/lib/cjs/constants.d.ts +1 -1
  55. package/lib/cjs/constants.js +2 -0
  56. package/lib/cjs/entities/blue/blue.d.ts +83 -20
  57. package/lib/cjs/entities/blue/blue.js +38 -12
  58. package/lib/cjs/entities/vaultV1/migrateToV2Quote.d.ts +2 -0
  59. package/lib/cjs/entities/vaultV1/migrateToV2Quote.js +5 -0
  60. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +12 -6
  61. package/lib/cjs/entities/vaultV1/vaultV1.js +6 -0
  62. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +12 -7
  63. package/lib/cjs/entities/vaultV2/vaultV2.js +4 -0
  64. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +11 -2
  65. package/lib/cjs/entities/vaultV2BlueReallocationData.js +19 -21
  66. package/lib/cjs/helpers/constant.d.ts +2 -0
  67. package/lib/cjs/helpers/constant.js +3 -1
  68. package/lib/cjs/helpers/getBlueBundlesV1QuoteTimestamp.d.ts +10 -0
  69. package/lib/cjs/helpers/getBlueBundlesV1QuoteTimestamp.js +18 -0
  70. package/lib/cjs/helpers/index.d.ts +1 -1
  71. package/lib/cjs/helpers/index.js +2 -1
  72. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.d.ts +3 -3
  73. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.js +4 -5
  74. package/lib/cjs/helpers/quoteBlueRepay.d.ts +7 -3
  75. package/lib/cjs/helpers/quoteBlueRepay.js +20 -7
  76. package/lib/cjs/helpers/reallocationPenalty.d.ts +10 -0
  77. package/lib/cjs/helpers/reallocationPenalty.js +32 -0
  78. package/lib/cjs/helpers/referralFee.d.ts +2 -1
  79. package/lib/cjs/helpers/referralFee.js +5 -1
  80. package/lib/cjs/helpers/validate.d.ts +31 -4
  81. package/lib/cjs/helpers/validate.js +48 -9
  82. package/lib/cjs/helpers/validateMidnightBounds.d.ts +1 -2
  83. package/lib/cjs/helpers/validateMidnightBounds.js +1 -2
  84. package/lib/cjs/helpers/validateMidnightTakeFeasibility.d.ts +2 -2
  85. package/lib/cjs/helpers/validateMidnightTakeFeasibility.js +1 -1
  86. package/lib/cjs/transactionPlan/blue/borrow.d.ts +11 -5
  87. package/lib/cjs/transactionPlan/blue/borrow.js +26 -8
  88. package/lib/cjs/transactionPlan/blue/refinance.d.ts +9 -2
  89. package/lib/cjs/transactionPlan/blue/refinance.js +20 -3
  90. package/lib/cjs/transactionPlan/blue/repay.d.ts +1 -2
  91. package/lib/cjs/transactionPlan/blue/repay.js +1 -2
  92. package/lib/cjs/transactionPlan/blue/repayWithdrawCollateral.d.ts +4 -3
  93. package/lib/cjs/transactionPlan/blue/repayWithdrawCollateral.js +13 -4
  94. package/lib/cjs/transactionPlan/blue/supply.d.ts +1 -2
  95. package/lib/cjs/transactionPlan/blue/supply.js +1 -2
  96. package/lib/cjs/transactionPlan/blue/supplyCollateral.d.ts +2 -3
  97. package/lib/cjs/transactionPlan/blue/supplyCollateral.js +2 -3
  98. package/lib/cjs/transactionPlan/blue/supplyCollateralBorrow.d.ts +10 -4
  99. package/lib/cjs/transactionPlan/blue/supplyCollateralBorrow.js +23 -6
  100. package/lib/cjs/transactionPlan/blue/withdraw.d.ts +15 -5
  101. package/lib/cjs/transactionPlan/blue/withdraw.js +25 -6
  102. package/lib/cjs/transactionPlan/blue/withdrawCollateral.d.ts +5 -5
  103. package/lib/cjs/transactionPlan/blue/withdrawCollateral.js +11 -7
  104. package/lib/cjs/transactionPlan/deposit.js +4 -0
  105. package/lib/cjs/transactionPlan/intent.d.ts +1 -1
  106. package/lib/cjs/transactionPlan/intent.js +4 -2
  107. package/lib/cjs/transactionPlan/plan.d.ts +8 -4
  108. package/lib/cjs/transactionPlan/plan.js +8 -4
  109. package/lib/cjs/transactionPlan/types.d.ts +6 -0
  110. package/lib/cjs/transactionPlan/vaultv1/deposit.d.ts +3 -3
  111. package/lib/cjs/transactionPlan/vaultv1/deposit.js +3 -3
  112. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.d.ts +3 -3
  113. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.js +7 -3
  114. package/lib/cjs/transactionPlan/vaultv1/redeem.d.ts +1 -2
  115. package/lib/cjs/transactionPlan/vaultv1/redeem.js +1 -2
  116. package/lib/cjs/transactionPlan/vaultv1/withdraw.d.ts +2 -3
  117. package/lib/cjs/transactionPlan/vaultv1/withdraw.js +2 -3
  118. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +3 -3
  119. package/lib/cjs/transactionPlan/vaultv2/deposit.js +3 -3
  120. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.d.ts +3 -3
  121. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.js +3 -3
  122. package/lib/cjs/transactionPlan/vaultv2/redeem.d.ts +2 -3
  123. package/lib/cjs/transactionPlan/vaultv2/redeem.js +2 -3
  124. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +2 -3
  125. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +2 -3
  126. package/lib/cjs/types/error.d.ts +7 -6
  127. package/lib/cjs/types/error.js +10 -9
  128. package/lib/cjs/types/sharedLiquidity.d.ts +7 -2
  129. package/lib/cjs/version.d.ts +1 -1
  130. package/lib/cjs/version.js +1 -1
  131. package/lib/esm/abis.d.ts +34 -0
  132. package/lib/esm/abis.js +20 -0
  133. package/lib/esm/actions/blue/borrow.d.ts +11 -3
  134. package/lib/esm/actions/blue/borrow.internal.js +1 -0
  135. package/lib/esm/actions/blue/borrow.js +8 -2
  136. package/lib/esm/actions/blue/common.d.ts +4 -1
  137. package/lib/esm/actions/blue/common.js +17 -3
  138. package/lib/esm/actions/blue/refinance.d.ts +11 -3
  139. package/lib/esm/actions/blue/refinance.internal.js +4 -1
  140. package/lib/esm/actions/blue/refinance.js +8 -2
  141. package/lib/esm/actions/blue/refinanceValidation.d.ts +3 -2
  142. package/lib/esm/actions/blue/refinanceValidation.js +10 -6
  143. package/lib/esm/actions/blue/repay.d.ts +4 -3
  144. package/lib/esm/actions/blue/repay.js +3 -2
  145. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +4 -3
  146. package/lib/esm/actions/blue/repayWithdrawCollateral.js +3 -2
  147. package/lib/esm/actions/blue/supply.d.ts +5 -3
  148. package/lib/esm/actions/blue/supply.js +4 -2
  149. package/lib/esm/actions/blue/supplyCollateral.d.ts +4 -3
  150. package/lib/esm/actions/blue/supplyCollateral.js +3 -2
  151. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +11 -3
  152. package/lib/esm/actions/blue/supplyCollateralBorrow.internal.d.ts +2 -0
  153. package/lib/esm/actions/blue/supplyCollateralBorrow.internal.js +5 -1
  154. package/lib/esm/actions/blue/supplyCollateralBorrow.js +8 -2
  155. package/lib/esm/actions/blue/withdraw.d.ts +11 -3
  156. package/lib/esm/actions/blue/withdraw.internal.js +4 -1
  157. package/lib/esm/actions/blue/withdraw.js +8 -2
  158. package/lib/esm/actions/blue/withdrawCollateral.d.ts +4 -3
  159. package/lib/esm/actions/blue/withdrawCollateral.js +3 -2
  160. package/lib/esm/actions/bundles/common.d.ts +2 -8
  161. package/lib/esm/actions/bundles/common.js +4 -17
  162. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +1 -2
  163. package/lib/esm/actions/midnight/takeBorrow.js +1 -2
  164. package/lib/esm/actions/midnight/takeLend.js +1 -2
  165. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +1 -2
  166. package/lib/esm/actions/midnight/takeWithdraw.js +1 -2
  167. package/lib/esm/actions/vaultV1/deposit.d.ts +2 -1
  168. package/lib/esm/actions/vaultV1/deposit.js +2 -1
  169. package/lib/esm/actions/vaultV1/migrateToV2.d.ts +3 -2
  170. package/lib/esm/actions/vaultV1/migrateToV2.js +2 -1
  171. package/lib/esm/actions/vaultV1/redeem.d.ts +3 -2
  172. package/lib/esm/actions/vaultV1/redeem.js +2 -1
  173. package/lib/esm/actions/vaultV1/withdraw.d.ts +2 -1
  174. package/lib/esm/actions/vaultV1/withdraw.js +2 -1
  175. package/lib/esm/actions/vaultV2/deposit.d.ts +2 -1
  176. package/lib/esm/actions/vaultV2/deposit.js +2 -1
  177. package/lib/esm/actions/vaultV2/forceWithdraw.d.ts +2 -1
  178. package/lib/esm/actions/vaultV2/forceWithdraw.js +2 -1
  179. package/lib/esm/actions/vaultV2/redeem.d.ts +3 -2
  180. package/lib/esm/actions/vaultV2/redeem.js +2 -1
  181. package/lib/esm/actions/vaultV2/withdraw.d.ts +2 -1
  182. package/lib/esm/actions/vaultV2/withdraw.js +2 -1
  183. package/lib/esm/constants.d.ts +1 -1
  184. package/lib/esm/constants.js +1 -1
  185. package/lib/esm/entities/blue/blue.d.ts +83 -20
  186. package/lib/esm/entities/blue/blue.js +38 -12
  187. package/lib/esm/entities/vaultV1/migrateToV2Quote.d.ts +2 -0
  188. package/lib/esm/entities/vaultV1/migrateToV2Quote.js +5 -0
  189. package/lib/esm/entities/vaultV1/vaultV1.d.ts +12 -6
  190. package/lib/esm/entities/vaultV1/vaultV1.js +7 -1
  191. package/lib/esm/entities/vaultV2/vaultV2.d.ts +12 -7
  192. package/lib/esm/entities/vaultV2/vaultV2.js +5 -1
  193. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +11 -2
  194. package/lib/esm/entities/vaultV2BlueReallocationData.js +17 -19
  195. package/lib/esm/helpers/constant.d.ts +2 -0
  196. package/lib/esm/helpers/constant.js +2 -0
  197. package/lib/esm/helpers/getBlueBundlesV1QuoteTimestamp.d.ts +10 -0
  198. package/lib/esm/helpers/getBlueBundlesV1QuoteTimestamp.js +15 -0
  199. package/lib/esm/helpers/index.d.ts +1 -1
  200. package/lib/esm/helpers/index.js +1 -1
  201. package/lib/esm/helpers/previewVaultV2ForceWithdraw.d.ts +3 -3
  202. package/lib/esm/helpers/previewVaultV2ForceWithdraw.js +4 -5
  203. package/lib/esm/helpers/quoteBlueRepay.d.ts +7 -3
  204. package/lib/esm/helpers/quoteBlueRepay.js +21 -8
  205. package/lib/esm/helpers/reallocationPenalty.d.ts +10 -0
  206. package/lib/esm/helpers/reallocationPenalty.js +28 -0
  207. package/lib/esm/helpers/referralFee.d.ts +2 -1
  208. package/lib/esm/helpers/referralFee.js +5 -1
  209. package/lib/esm/helpers/validate.d.ts +31 -4
  210. package/lib/esm/helpers/validate.js +48 -11
  211. package/lib/esm/helpers/validateMidnightBounds.d.ts +1 -2
  212. package/lib/esm/helpers/validateMidnightBounds.js +1 -2
  213. package/lib/esm/helpers/validateMidnightTakeFeasibility.d.ts +2 -2
  214. package/lib/esm/helpers/validateMidnightTakeFeasibility.js +1 -1
  215. package/lib/esm/transactionPlan/blue/borrow.d.ts +11 -5
  216. package/lib/esm/transactionPlan/blue/borrow.js +27 -9
  217. package/lib/esm/transactionPlan/blue/refinance.d.ts +9 -2
  218. package/lib/esm/transactionPlan/blue/refinance.js +20 -3
  219. package/lib/esm/transactionPlan/blue/repay.d.ts +1 -2
  220. package/lib/esm/transactionPlan/blue/repay.js +1 -2
  221. package/lib/esm/transactionPlan/blue/repayWithdrawCollateral.d.ts +4 -3
  222. package/lib/esm/transactionPlan/blue/repayWithdrawCollateral.js +13 -4
  223. package/lib/esm/transactionPlan/blue/supply.d.ts +1 -2
  224. package/lib/esm/transactionPlan/blue/supply.js +1 -2
  225. package/lib/esm/transactionPlan/blue/supplyCollateral.d.ts +2 -3
  226. package/lib/esm/transactionPlan/blue/supplyCollateral.js +2 -3
  227. package/lib/esm/transactionPlan/blue/supplyCollateralBorrow.d.ts +10 -4
  228. package/lib/esm/transactionPlan/blue/supplyCollateralBorrow.js +23 -6
  229. package/lib/esm/transactionPlan/blue/withdraw.d.ts +15 -5
  230. package/lib/esm/transactionPlan/blue/withdraw.js +25 -6
  231. package/lib/esm/transactionPlan/blue/withdrawCollateral.d.ts +5 -5
  232. package/lib/esm/transactionPlan/blue/withdrawCollateral.js +11 -7
  233. package/lib/esm/transactionPlan/deposit.js +5 -1
  234. package/lib/esm/transactionPlan/intent.d.ts +1 -1
  235. package/lib/esm/transactionPlan/intent.js +4 -2
  236. package/lib/esm/transactionPlan/plan.d.ts +8 -4
  237. package/lib/esm/transactionPlan/plan.js +8 -4
  238. package/lib/esm/transactionPlan/types.d.ts +6 -0
  239. package/lib/esm/transactionPlan/vaultv1/deposit.d.ts +3 -3
  240. package/lib/esm/transactionPlan/vaultv1/deposit.js +3 -3
  241. package/lib/esm/transactionPlan/vaultv1/migrateToV2.d.ts +3 -3
  242. package/lib/esm/transactionPlan/vaultv1/migrateToV2.js +8 -4
  243. package/lib/esm/transactionPlan/vaultv1/redeem.d.ts +1 -2
  244. package/lib/esm/transactionPlan/vaultv1/redeem.js +1 -2
  245. package/lib/esm/transactionPlan/vaultv1/withdraw.d.ts +2 -3
  246. package/lib/esm/transactionPlan/vaultv1/withdraw.js +2 -3
  247. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +3 -3
  248. package/lib/esm/transactionPlan/vaultv2/deposit.js +3 -3
  249. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.d.ts +3 -3
  250. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.js +3 -3
  251. package/lib/esm/transactionPlan/vaultv2/redeem.d.ts +2 -3
  252. package/lib/esm/transactionPlan/vaultv2/redeem.js +2 -3
  253. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +2 -3
  254. package/lib/esm/transactionPlan/vaultv2/withdraw.js +2 -3
  255. package/lib/esm/types/error.d.ts +7 -6
  256. package/lib/esm/types/error.js +11 -10
  257. package/lib/esm/types/sharedLiquidity.d.ts +7 -2
  258. package/lib/esm/version.d.ts +1 -1
  259. package/lib/esm/version.js +1 -1
  260. package/package.json +3 -3
@@ -3,10 +3,11 @@
3
3
  *
4
4
  * @param params - Net target and WAD-scaled referral fee.
5
5
  * @param params.netAssets - Required proceeds after the fee, in the asset's smallest unit.
6
- * @param params.referralFeePct - Referral fee fraction scaled by WAD (`1e18`); must be below WAD.
6
+ * @param params.referralFeePct - Referral fee fraction scaled by WAD (`1e18`); at most 10%.
7
7
  * @returns The gross asset amount to pass to a bundles entrypoint.
8
8
  * @throws {NegativeInputError} when `netAssets` or `referralFeePct` is negative.
9
9
  * @throws {ReferralFeePctExceededError} when `referralFeePct >= WAD`.
10
+ * @throws {MidnightReferralFeePctExceededError} when the fee is above 10% but below WAD.
10
11
  * @example
11
12
  * ```ts
12
13
  * import { grossFromNetAssets } from "@morpho-org/morpho-sdk";
@@ -1,14 +1,16 @@
1
1
  import { MathLib } from "@morpho-org/blue-sdk";
2
2
  import { NegativeInputError, ReferralFeePctExceededError, } from "../types/index.js";
3
+ import { validateMidnightReferralFeeCap } from "./validateMidnightBounds.js";
3
4
  /**
4
5
  * Computes the gross amount whose post-referral-fee proceeds equal `netAssets` exactly.
5
6
  *
6
7
  * @param params - Net target and WAD-scaled referral fee.
7
8
  * @param params.netAssets - Required proceeds after the fee, in the asset's smallest unit.
8
- * @param params.referralFeePct - Referral fee fraction scaled by WAD (`1e18`); must be below WAD.
9
+ * @param params.referralFeePct - Referral fee fraction scaled by WAD (`1e18`); at most 10%.
9
10
  * @returns The gross asset amount to pass to a bundles entrypoint.
10
11
  * @throws {NegativeInputError} when `netAssets` or `referralFeePct` is negative.
11
12
  * @throws {ReferralFeePctExceededError} when `referralFeePct >= WAD`.
13
+ * @throws {MidnightReferralFeePctExceededError} when the fee is above 10% but below WAD.
12
14
  * @example
13
15
  * ```ts
14
16
  * import { grossFromNetAssets } from "@morpho-org/morpho-sdk";
@@ -27,5 +29,7 @@ export const grossFromNetAssets = (params) => {
27
29
  if (params.referralFeePct >= MathLib.WAD) {
28
30
  throw new ReferralFeePctExceededError(params.referralFeePct);
29
31
  }
32
+ // Reject fees that the SDK's bundle builders would reject.
33
+ validateMidnightReferralFeeCap(params.referralFeePct);
30
34
  return MathLib.mulDivDown(params.netAssets, MathLib.WAD, MathLib.WAD - params.referralFeePct);
31
35
  };
@@ -2,6 +2,30 @@ import { type AccrualPosition, type InputMarketParams, type MarketId, type Marke
2
2
  import { type Market as MidnightMarket, type MarketInput as MidnightMarketInput } from "@morpho-org/midnight-sdk";
3
3
  import { type Address } from "viem";
4
4
  import { type VaultV2BlueReallocation } from "../types/index.js";
5
+ /**
6
+ * Rejects a reference time that is not a bigint, so a serialized timestamp fails with a typed
7
+ * error before any deadline arithmetic.
8
+ * @param now - Handle creation or plan preparation timestamp in Unix seconds.
9
+ * @returns Nothing when `now` is a bigint.
10
+ * @throws {InvalidBigIntInputError} when `now` is not a bigint.
11
+ * @internal
12
+ */
13
+ export declare function validateReferenceTime(now: bigint): void;
14
+ /**
15
+ * Rejects vault deposit accrual beyond seven days after the reference time.
16
+ * @param deadline - Execution deadline in Unix seconds.
17
+ * @param params - Reference time and public input field for validation errors.
18
+ * @param params.now - Handle creation or plan preparation timestamp in Unix seconds.
19
+ * @param params.field - Public input field to identify in validation errors.
20
+ * @returns Nothing when the deadline is within the maximum window.
21
+ * @throws {InvalidBigIntInputError} when `now` is not a bigint.
22
+ * @throws {InputExceedsMaxError} when the deadline exceeds the seven-day window.
23
+ * @internal
24
+ */
25
+ export declare function validateVaultDepositDeadline(deadline: bigint, { now, field, }: {
26
+ now: bigint;
27
+ field?: "deadline" | "expiresAt";
28
+ }): void;
5
29
  /**
6
30
  * Rejects a `bigint` field that falls outside the unsigned 256-bit ABI range so a direct caller
7
31
  * gets the SDK's typed error instead of viem's `IntegerOutOfRangeError` at encode time. `maxUint256`
@@ -39,11 +63,10 @@ export declare const validateMarketParamsId: (marketParams: InputMarketParams &
39
63
  export declare const validateDeadline: (deadline: bigint) => void;
40
64
  /**
41
65
  * Validates an optional referral fee and returns the pair every referral-fee-bearing periphery
42
- * encodes. Shared by the direct BlueBundlesV1 writes and the VaultExitBundlesV1 force withdrawal,
43
- * whose contracts apply the same `[0, WAD)` bound and both transfer the fee unconditionally.
66
+ * encodes. The SDK caps the fee at 10% even though the peripheries accept fees below WAD.
44
67
  *
45
68
  * @param params - Referral fee inputs.
46
- * @param params.referralFeePct - Optional WAD-scaled fee share. Defaults to `0n`.
69
+ * @param params.referralFeePct - Optional WAD-scaled fee share, at most 10%. Defaults to `0n`.
47
70
  * @param params.referralFeeRecipient - Optional fee recipient. Defaults to the zero address, which
48
71
  * is only valid alongside a zero `referralFeePct`.
49
72
  * @returns The normalized `{ referralFeePct, referralFeeRecipient }` pair.
@@ -51,6 +74,7 @@ export declare const validateDeadline: (deadline: bigint) => void;
51
74
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD (the contracts reject
52
75
  * it with `PctExceeded`); it extends `InputExceedsMaxError`, preserving that pattern-match.
53
76
  * @throws {ReferralFeeRecipientMissingError} when a positive `referralFeePct` has no recipient.
77
+ * @throws {MidnightReferralFeePctExceededError} when the fee is above 10% but below WAD.
54
78
  * @internal
55
79
  */
56
80
  export declare const validateReferralFee: (params: {
@@ -426,7 +450,10 @@ export declare const validateRepayShares: (params: {
426
450
  marketId: MarketId;
427
451
  }) => void;
428
452
  /** @internal */
429
- export declare const validateVaultV2BlueReallocations: (reallocations: Iterable<VaultV2BlueReallocation>, targetMarketId: MarketId) => void;
453
+ export declare const validateVaultV2BlueReallocations: (reallocations: Iterable<VaultV2BlueReallocation>, { targetMarketId, maxPenalty, }: {
454
+ readonly targetMarketId: MarketId;
455
+ readonly maxPenalty?: bigint;
456
+ }) => void;
430
457
  /**
431
458
  * Validates that a slippage tolerance is within an acceptable range.
432
459
  *
@@ -2,9 +2,43 @@ import { getChainAddresses, MarketUtils, MathLib, ORACLE_PRICE_SCALE, } from "@m
2
2
  import { MarketUtils as MidnightMarketUtils, } from "@morpho-org/midnight-sdk";
3
3
  import { isDefined, isHexEqual } from "@morpho-org/morpho-ts";
4
4
  import { isAddress, isAddressEqual, maxUint128, maxUint256, zeroAddress, } from "viem";
5
- import { AccrualPositionUserMismatchError, AddressMismatchError, BorrowExceedsSafeLtvError, ChainIdMismatchError, ChainWNativeMissingError, ExcessiveSlippageToleranceError, InconsistentReallocationPenaltyError, InputExceedsMaxError, InvalidMidnightNativeAmountTypeError, InvalidReallocationAddressError, InvalidReallocationSourceTypeError, InvalidVaultV2BlueReallocationShapeError, MarketIdMismatchError, MissingClientPropertyError, MissingMarketPriceError, NativeAmountOnNonWNativeAssetError, NativeAmountOnNonWNativeVaultError, NegativeInputError, NonPositiveInputError, ReallocationWithdrawalOnTargetMarketError, ReferralFeePctExceededError, ReferralFeeRecipientMissingError, RepayExceedsDebtError, RepaySharesExceedDebtError, WithdrawExceedsCollateralError, WithdrawExceedsSupplyError, WithdrawMakesPositionUnhealthyError, WithdrawSharesExceedSupplyError, } from "../types/index.js";
6
- import { DEFAULT_LLTV_BUFFER, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, } from "./constant.js";
5
+ import { AccrualPositionUserMismatchError, AddressMismatchError, BorrowExceedsSafeLtvError, ChainIdMismatchError, ChainWNativeMissingError, ExcessiveSlippageToleranceError, InconsistentReallocationPenaltyError, InputExceedsMaxError, InvalidBigIntInputError, InvalidMidnightNativeAmountTypeError, InvalidReallocationAddressError, InvalidReallocationSourceTypeError, InvalidVaultV2BlueReallocationShapeError, MarketIdMismatchError, MissingClientPropertyError, MissingMarketPriceError, NativeAmountOnNonWNativeAssetError, NativeAmountOnNonWNativeVaultError, NegativeInputError, NonPositiveInputError, ReallocationWithdrawalOnTargetMarketError, ReferralFeePctExceededError, ReferralFeeRecipientMissingError, RepayExceedsDebtError, RepaySharesExceedDebtError, WithdrawExceedsCollateralError, WithdrawExceedsSupplyError, WithdrawMakesPositionUnhealthyError, WithdrawSharesExceedSupplyError, } from "../types/index.js";
6
+ import { DEFAULT_LLTV_BUFFER, MAX_SLIPPAGE_TOLERANCE, VAULT_DEPOSIT_MAX_DEADLINE_SECONDS, } from "./constant.js";
7
+ import { resolveMaxPenalty } from "./reallocationPenalty.js";
7
8
  import { validateMidnightAddress } from "./validateMidnightAccount.js";
9
+ import { validateMidnightReferralFeeCap } from "./validateMidnightBounds.js";
10
+ /**
11
+ * Rejects a reference time that is not a bigint, so a serialized timestamp fails with a typed
12
+ * error before any deadline arithmetic.
13
+ * @param now - Handle creation or plan preparation timestamp in Unix seconds.
14
+ * @returns Nothing when `now` is a bigint.
15
+ * @throws {InvalidBigIntInputError} when `now` is not a bigint.
16
+ * @internal
17
+ */
18
+ export function validateReferenceTime(now) {
19
+ if (typeof now !== "bigint") {
20
+ throw new InvalidBigIntInputError("now", now);
21
+ }
22
+ }
23
+ /**
24
+ * Rejects vault deposit accrual beyond seven days after the reference time.
25
+ * @param deadline - Execution deadline in Unix seconds.
26
+ * @param params - Reference time and public input field for validation errors.
27
+ * @param params.now - Handle creation or plan preparation timestamp in Unix seconds.
28
+ * @param params.field - Public input field to identify in validation errors.
29
+ * @returns Nothing when the deadline is within the maximum window.
30
+ * @throws {InvalidBigIntInputError} when `now` is not a bigint.
31
+ * @throws {InputExceedsMaxError} when the deadline exceeds the seven-day window.
32
+ * @internal
33
+ */
34
+ export function validateVaultDepositDeadline(deadline, { now, field = "deadline", }) {
35
+ // Reject a non-bigint clock so the window sum below cannot become string concatenation.
36
+ validateReferenceTime(now);
37
+ const max = now + VAULT_DEPOSIT_MAX_DEADLINE_SECONDS;
38
+ if (deadline > max) {
39
+ throw new InputExceedsMaxError({ field, value: deadline, max });
40
+ }
41
+ }
8
42
  /** @internal */
9
43
  const compareMarketIds = (idA, idB) => {
10
44
  const normalizedIdA = idA.toLowerCase();
@@ -71,11 +105,10 @@ export const validateDeadline = (deadline) => {
71
105
  };
72
106
  /**
73
107
  * Validates an optional referral fee and returns the pair every referral-fee-bearing periphery
74
- * encodes. Shared by the direct BlueBundlesV1 writes and the VaultExitBundlesV1 force withdrawal,
75
- * whose contracts apply the same `[0, WAD)` bound and both transfer the fee unconditionally.
108
+ * encodes. The SDK caps the fee at 10% even though the peripheries accept fees below WAD.
76
109
  *
77
110
  * @param params - Referral fee inputs.
78
- * @param params.referralFeePct - Optional WAD-scaled fee share. Defaults to `0n`.
111
+ * @param params.referralFeePct - Optional WAD-scaled fee share, at most 10%. Defaults to `0n`.
79
112
  * @param params.referralFeeRecipient - Optional fee recipient. Defaults to the zero address, which
80
113
  * is only valid alongside a zero `referralFeePct`.
81
114
  * @returns The normalized `{ referralFeePct, referralFeeRecipient }` pair.
@@ -83,6 +116,7 @@ export const validateDeadline = (deadline) => {
83
116
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD (the contracts reject
84
117
  * it with `PctExceeded`); it extends `InputExceedsMaxError`, preserving that pattern-match.
85
118
  * @throws {ReferralFeeRecipientMissingError} when a positive `referralFeePct` has no recipient.
119
+ * @throws {MidnightReferralFeePctExceededError} when the fee is above 10% but below WAD.
86
120
  * @internal
87
121
  */
88
122
  export const validateReferralFee = (params) => {
@@ -98,6 +132,8 @@ export const validateReferralFee = (params) => {
98
132
  isAddressEqual(params.referralFeeRecipient, zeroAddress))) {
99
133
  throw new ReferralFeeRecipientMissingError();
100
134
  }
135
+ // Enforce the SDK cap after validating the recipient, as in Midnight.
136
+ validateMidnightReferralFeeCap(referralFeePct);
101
137
  return {
102
138
  referralFeePct,
103
139
  referralFeeRecipient: params.referralFeeRecipient ?? zeroAddress,
@@ -585,14 +621,15 @@ export const validateRepayShares = (params) => {
585
621
  }
586
622
  };
587
623
  /** @internal */
588
- export const validateVaultV2BlueReallocations = (reallocations, targetMarketId) => {
624
+ export const validateVaultV2BlueReallocations = (reallocations, { targetMarketId, maxPenalty, }) => {
625
+ const penaltyBound = resolveMaxPenalty(maxPenalty);
589
626
  const penaltyByVault = new Map();
590
627
  for (const reallocation of reallocations) {
591
628
  // Validate shape before source and amounts so malformed entries keep their original error.
592
629
  assertReallocationShape(reallocation);
593
630
  const sourceMarketId = resolveReallocationSourceMarketId(reallocation);
594
631
  // Reject out-of-range amounts before comparing penalties across vault legs.
595
- assertReallocationAmounts(reallocation);
632
+ assertReallocationAmounts(reallocation, penaltyBound);
596
633
  const penaltyKey = reallocation.vault.toLowerCase();
597
634
  const expectedPenalty = penaltyByVault.get(penaltyKey);
598
635
  if (expectedPenalty !== undefined &&
@@ -751,16 +788,16 @@ function resolveReallocationSourceMarketId(reallocation) {
751
788
  }
752
789
  return sourceMarketId;
753
790
  }
754
- /** Checks penalty and asset amounts against the allocator's ABI bounds. @internal */
755
- function assertReallocationAmounts(reallocation) {
791
+ /** Checks asset ABI bounds and the caller's penalty bound. @internal */
792
+ function assertReallocationAmounts(reallocation, maxPenalty) {
756
793
  if (reallocation.penalty < 0n) {
757
794
  throw new NegativeInputError("reallocation.penalty", reallocation.penalty);
758
795
  }
759
- if (reallocation.penalty > MAX_REALLOCATION_PENALTY) {
796
+ if (reallocation.penalty > maxPenalty) {
760
797
  throw new InputExceedsMaxError({
761
798
  field: "reallocation.penalty",
762
799
  value: reallocation.penalty,
763
- max: MAX_REALLOCATION_PENALTY,
800
+ max: maxPenalty,
764
801
  });
765
802
  }
766
803
  if (reallocation.assets <= 0n) {
@@ -11,8 +11,7 @@ import type { OfferStruct } from "@morpho-org/midnight-sdk";
11
11
  */
12
12
  export declare const validateMidnightUint128Field: (field: string, value: bigint) => void;
13
13
  /**
14
- * Enforces the SDK's 10% (`WAD / 10n`) Midnight referral-fee cap. The contract
15
- * itself only requires `referralFeePct < WAD`.
14
+ * Enforces the SDK's 10% (`WAD / 10n`) referral-fee cap, originally used by Midnight.
16
15
  *
17
16
  * @param referralFeePct - Candidate referral fee percentage.
18
17
  * @returns Nothing when the fee is within the SDK cap.
@@ -20,8 +20,7 @@ export const validateMidnightUint128Field = (field, value) => {
20
20
  }
21
21
  };
22
22
  /**
23
- * Enforces the SDK's 10% (`WAD / 10n`) Midnight referral-fee cap. The contract
24
- * itself only requires `referralFeePct < WAD`.
23
+ * Enforces the SDK's 10% (`WAD / 10n`) referral-fee cap, originally used by Midnight.
25
24
  *
26
25
  * @param referralFeePct - Candidate referral fee percentage.
27
26
  * @returns Nothing when the fee is within the SDK cap.
@@ -14,7 +14,7 @@ type TakeableOfferLike = {
14
14
  *
15
15
  * @param params - Sell target and validated referral fee.
16
16
  * @param params.target - Sell target of `takeBorrow`, `takeWithdraw` or `supplyCollateralTakeBorrow`.
17
- * @param params.referralFeePct - WAD-scaled referral fee, already checked to be below WAD.
17
+ * @param params.referralFeePct - WAD-scaled referral fee, already checked to be at most 10%.
18
18
  * @returns Nothing when the target is reachable at some price.
19
19
  * @throws {MidnightTakeTargetUnreachableError} when `target.minSellerAssets` exceeds the most the
20
20
  * units can yield, or `target.maxUnits` is below the units the assets need.
@@ -40,7 +40,7 @@ export type MidnightTakeFeasibilityParams<T extends TakeableOfferLike = Takeable
40
40
  readonly now: bigint;
41
41
  /** Bundle deadline in seconds. */
42
42
  readonly deadline: bigint;
43
- /** WAD-scaled referral fee, already checked to be below WAD. */
43
+ /** WAD-scaled referral fee, already checked to be at most 10%. */
44
44
  readonly referralFeePct: bigint;
45
45
  /**
46
46
  * Units the bundle fills without offers: withdrawn credit for sells, the direct repay at par for
@@ -12,7 +12,7 @@ const netOfReferralFee = (assets, referralFeePct) => assets - MathLib.mulDivDown
12
12
  *
13
13
  * @param params - Sell target and validated referral fee.
14
14
  * @param params.target - Sell target of `takeBorrow`, `takeWithdraw` or `supplyCollateralTakeBorrow`.
15
- * @param params.referralFeePct - WAD-scaled referral fee, already checked to be below WAD.
15
+ * @param params.referralFeePct - WAD-scaled referral fee, already checked to be at most 10%.
16
16
  * @returns Nothing when the target is reachable at some price.
17
17
  * @throws {MidnightTakeTargetUnreachableError} when `target.minSellerAssets` exceeds the most the
18
18
  * units can yield, or `target.maxUnits` is below the units the assets need.
@@ -20,16 +20,21 @@ export interface BlueBorrowPlanParams extends IntentParams {
20
20
  /** Gross debt increase, before allocator penalties and referral fees. */
21
21
  readonly borrowAssets: bigint;
22
22
  readonly reallocations?: readonly VaultV2BlueReallocation[];
23
+ /** Maximum WAD-scaled penalty rate per reallocation in [0, WAD], defaulting to zero. Each rate applies to that reallocation's assets, so it does not bound total proceeds lost. */
24
+ readonly maxPenalty?: bigint;
23
25
  readonly now?: bigint;
24
26
  }
25
27
  /**
26
28
  * 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
+ * Health uses the expiry, floored at max(now, lastUpdate), like the entity handle.
30
+ * Expiries more than 365 days out retain the legacy +2h projection for unlimited sentinels.
31
+ * Snapshots are not retained in the stored plan.
29
32
  * Reads Morpho authorization of BlueBundlesV1 (and its nonce when signing) from `client`.
30
33
  * @param client - Viem client for `params.chainId`, used for Morpho authorization and contract code reads.
31
34
  * @param params - Borrow intent and chain-tagged snapshots for the borrowing account.
35
+ * @param params.maxPenalty - Maximum WAD-scaled penalty rate per reallocation in [0, WAD], defaulting to zero. Each rate applies to that reallocation's assets, so it does not bound total proceeds lost.
32
36
  * @returns A data-only plan with any Morpho authorization prerequisite before the borrow.
37
+ * @throws {InvalidBigIntInputError} when a supplied maxPenalty is not a bigint.
33
38
  * @throws {ChainIdMismatchError} When the client declares another chain or its RPC reports another chain.
34
39
  * @throws {MissingContractCodeError} When BlueBundlesV1 or Morpho Blue has no deployed code.
35
40
  * @throws {UnsupportedBlueMarketIrmError} When positive debt requires an unsupported IRM projection.
@@ -41,10 +46,11 @@ export interface BlueBorrowPlanParams extends IntentParams {
41
46
  * @throws {NonIntegerInputError} When `expiresAt` or `referralFee.bps` is not a safe integer.
42
47
  * @throws {NonPositiveInputError} When `expiresAt`, `borrowAssets` or a reallocation amount is not positive.
43
48
  * @throws {ExpiredDeadlineError} When `expiresAt` is at or before `now`.
44
- * @throws {NegativeInputError} When `referralFee.bps` or a reallocation penalty is negative.
49
+ * @throws {NegativeInputError} When `referralFee.bps`, maxPenalty or a reallocation penalty is negative.
45
50
  * @throws {InputExceedsMaxError} When a fee or reallocation bound is exceeded, including aggregate allocator penalties above the borrow.
51
+ * Also thrown when maxPenalty exceeds WAD or a penalty exceeds maxPenalty (zero by default).
46
52
  * @throws {InvalidCalldataOriginError} When `calldataOrigin` is empty, malformed or has an odd number of hex digits.
47
- * @throws {ReferralFeePctExceededError} When `referralFee.bps` equals 10,000.
53
+ * @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 1,000.
48
54
  * @throws {ReferralFeeRecipientMissingError} When a positive referral fee has no recipient.
49
55
  * @throws {InvalidVaultV2BlueReallocationShapeError} When a reallocation entry is malformed.
50
56
  * @throws {ReallocationWithdrawalOnTargetMarketError} When a reallocation sources the target market.
@@ -71,7 +77,7 @@ export interface BlueBorrowPlanParams extends IntentParams {
71
77
  * ```
72
78
  * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
73
79
  */
74
- export declare function prepareBlueBorrow(client: Client, { chainId, account, marketId, marketData, positionData, borrowAssets, reallocations, expiresAt, referralFee, supportSignature, calldataOrigin, deployless, now, }: BlueBorrowPlanParams): Promise<TransactionPlan>;
80
+ export declare function prepareBlueBorrow(client: Client, { chainId, account, marketId, marketData, positionData, borrowAssets, reallocations, maxPenalty, expiresAt, referralFee, supportSignature, calldataOrigin, deployless, now, }: BlueBorrowPlanParams): Promise<TransactionPlan>;
75
81
  /** @internal Encodes a prepared borrow without state reads or signing. */
76
82
  export declare function buildBlueBorrow(action: Extract<Action, {
77
83
  type: "blueBorrow";
@@ -1,19 +1,23 @@
1
1
  import { deepFreeze, MathLib, Time } from "@morpho-org/morpho-ts";
2
2
  import { blueBorrow } from "../../actions/blue/borrow.js";
3
3
  import { normalizeBundlesCommonParams } from "../../actions/bundles/common.js";
4
+ import { getBlueBundlesV1QuoteTimestamp } from "../../helpers/getBlueBundlesV1QuoteTimestamp.js";
4
5
  import { DEFAULT_LLTV_BUFFER } from "../../helpers/index.js";
5
6
  import { validatePositionHealth } from "../../helpers/validate.js";
6
7
  import { IncompleteTransactionPlanError, InvalidTransactionPlanError, } from "../error.js";
7
- import { getPlanObject, validatePlanFields } from "../validation.js";
8
+ import { getPlanObject, validatePlanField, validatePlanFields, } from "../validation.js";
8
9
  import { prepareBlue, } from "./prepare.js";
9
10
  /**
10
11
  * Prepares a BlueBundlesV1 borrow against existing collateral. No token allowance is needed.
11
- * Health is checked on the position accrued two hours beyond the later of now and last update,
12
- * matching the existing Blue borrow handle. Snapshots are not retained in the stored plan.
12
+ * Health uses the expiry, floored at max(now, lastUpdate), like the entity handle.
13
+ * Expiries more than 365 days out retain the legacy +2h projection for unlimited sentinels.
14
+ * Snapshots are not retained in the stored plan.
13
15
  * Reads Morpho authorization of BlueBundlesV1 (and its nonce when signing) from `client`.
14
16
  * @param client - Viem client for `params.chainId`, used for Morpho authorization and contract code reads.
15
17
  * @param params - Borrow intent and chain-tagged snapshots for the borrowing account.
18
+ * @param params.maxPenalty - Maximum WAD-scaled penalty rate per reallocation in [0, WAD], defaulting to zero. Each rate applies to that reallocation's assets, so it does not bound total proceeds lost.
16
19
  * @returns A data-only plan with any Morpho authorization prerequisite before the borrow.
20
+ * @throws {InvalidBigIntInputError} when a supplied maxPenalty is not a bigint.
17
21
  * @throws {ChainIdMismatchError} When the client declares another chain or its RPC reports another chain.
18
22
  * @throws {MissingContractCodeError} When BlueBundlesV1 or Morpho Blue has no deployed code.
19
23
  * @throws {UnsupportedBlueMarketIrmError} When positive debt requires an unsupported IRM projection.
@@ -25,10 +29,11 @@ import { prepareBlue, } from "./prepare.js";
25
29
  * @throws {NonIntegerInputError} When `expiresAt` or `referralFee.bps` is not a safe integer.
26
30
  * @throws {NonPositiveInputError} When `expiresAt`, `borrowAssets` or a reallocation amount is not positive.
27
31
  * @throws {ExpiredDeadlineError} When `expiresAt` is at or before `now`.
28
- * @throws {NegativeInputError} When `referralFee.bps` or a reallocation penalty is negative.
32
+ * @throws {NegativeInputError} When `referralFee.bps`, maxPenalty or a reallocation penalty is negative.
29
33
  * @throws {InputExceedsMaxError} When a fee or reallocation bound is exceeded, including aggregate allocator penalties above the borrow.
34
+ * Also thrown when maxPenalty exceeds WAD or a penalty exceeds maxPenalty (zero by default).
30
35
  * @throws {InvalidCalldataOriginError} When `calldataOrigin` is empty, malformed or has an odd number of hex digits.
31
- * @throws {ReferralFeePctExceededError} When `referralFee.bps` equals 10,000.
36
+ * @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 1,000.
32
37
  * @throws {ReferralFeeRecipientMissingError} When a positive referral fee has no recipient.
33
38
  * @throws {InvalidVaultV2BlueReallocationShapeError} When a reallocation entry is malformed.
34
39
  * @throws {ReallocationWithdrawalOnTargetMarketError} When a reallocation sources the target market.
@@ -55,7 +60,7 @@ import { prepareBlue, } from "./prepare.js";
55
60
  * ```
56
61
  * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
57
62
  */
58
- export async function prepareBlueBorrow(client, { chainId, account, marketId, marketData, positionData, borrowAssets, reallocations, expiresAt, referralFee, supportSignature, calldataOrigin, deployless, now = Time.timestamp(), }) {
63
+ export async function prepareBlueBorrow(client, { chainId, account, marketId, marketData, positionData, borrowAssets, reallocations, maxPenalty, expiresAt, referralFee, supportSignature, calldataOrigin, deployless, now = Time.timestamp(), }) {
59
64
  const params = {
60
65
  chainId,
61
66
  account,
@@ -64,6 +69,7 @@ export async function prepareBlueBorrow(client, { chainId, account, marketId, ma
64
69
  positionData,
65
70
  borrowAssets,
66
71
  reallocations,
72
+ maxPenalty,
67
73
  expiresAt,
68
74
  referralFee,
69
75
  supportSignature,
@@ -83,6 +89,7 @@ export async function prepareBlueBorrow(client, { chainId, account, marketId, ma
83
89
  authorizationNonce: 0n,
84
90
  maxLtv: MathLib.zeroFloorSub(marketParams.lltv, DEFAULT_LLTV_BUFFER),
85
91
  reallocations: structuredClone(params.reallocations ?? []),
92
+ ...(maxPenalty !== undefined && { maxPenalty }),
86
93
  ...normalizeBundlesCommonParams({
87
94
  deadline: resolvedIntent.deadline,
88
95
  referralFeePct: resolvedIntent.referralFeePct,
@@ -91,9 +98,13 @@ export async function prepareBlueBorrow(client, { chainId, account, marketId, ma
91
98
  };
92
99
  // Validate the pure encoding, including aggregate penalties, before any RPC reads.
93
100
  buildBlueBorrow({ type: "blueBorrow", inputs, signatureRequestIds: {} }, []);
94
- // Apply the same deadline-independent two-hour health quote as the existing handle.
101
+ // Reject debt that exceeds the buffered LLTV at the shared health horizon.
95
102
  validatePositionHealth({
96
- positionData: position.accrueInterest(MathLib.max(now, position.market.lastUpdate) + Time.s.from.h(2n)),
103
+ positionData: position.accrueInterest(getBlueBundlesV1QuoteTimestamp({
104
+ lastUpdate: position.market.lastUpdate,
105
+ now,
106
+ deadline: resolvedIntent.deadline,
107
+ })),
97
108
  additionalCollateral: 0n,
98
109
  borrowAmount: params.borrowAssets,
99
110
  marketId: params.marketId,
@@ -135,7 +146,7 @@ export async function prepareBlueBorrow(client, { chainId, account, marketId, ma
135
146
  }
136
147
  /** @internal Encodes a prepared borrow without state reads or signing. */
137
148
  export function buildBlueBorrow(action, requests) {
138
- const { chainId, account, marketParams, borrowAssets, maxLtv, reallocations, deadline, referralFeePct, referralFeeRecipient, } = action.inputs;
149
+ const { chainId, account, marketParams, borrowAssets, maxLtv, reallocations, maxPenalty, deadline, referralFeePct, referralFeeRecipient, } = action.inputs;
139
150
  const id = action.signatureRequestIds.morphoAuthorization;
140
151
  const request = requests.find((candidate) => candidate.id === id);
141
152
  if (id !== undefined &&
@@ -165,6 +176,7 @@ export function buildBlueBorrow(action, requests) {
165
176
  borrowAssets,
166
177
  maxLtv,
167
178
  reallocations,
179
+ maxPenalty,
168
180
  deadline,
169
181
  referralFeePct,
170
182
  referralFeeRecipient,
@@ -210,6 +222,12 @@ export function validateBorrowPlanAction(action, path) {
210
222
  },
211
223
  });
212
224
  validateMarket(inputs.marketParams, `${path}.inputs.marketParams`);
225
+ if (inputs.maxPenalty !== undefined) {
226
+ validatePlanField(inputs.maxPenalty, {
227
+ path: `${path}.inputs.maxPenalty`,
228
+ type: "uint256 bigint",
229
+ });
230
+ }
213
231
  for (const [index, value] of inputs.reallocations.entries()) {
214
232
  const entryPath = `${path}.inputs.reallocations[${index}]`;
215
233
  const entry = getPlanObject(value, entryPath);
@@ -33,18 +33,24 @@ export interface BlueRefinancePlanParams extends Omit<IntentParams, "deployless"
33
33
  readonly destination: RefinanceMarket;
34
34
  /** Optional ordered Vault V2 reallocations into the destination market. */
35
35
  readonly reallocations?: readonly VaultV2BlueReallocation[];
36
+ /** Maximum WAD-scaled penalty rate per reallocation in [0, WAD], defaulting to zero. Each rate applies to that reallocation's assets, so it does not bound the total penalty added to destination debt. */
37
+ readonly maxPenalty?: bigint;
36
38
  }
37
39
  /**
38
40
  * Prepares a full Blue borrow-position migration. Fetch both market and position snapshots at the
39
41
  * same block and pass that block's timestamp as `now`. Penalties and fees increase destination debt;
40
42
  * the quote checks the buffered destination LLTV and the transaction enforces it again onchain.
43
+ * Health uses the expiry floored at now and both market snapshots. Expiries more than
44
+ * 365 days out retain the legacy +2h projection for unlimited sentinels.
41
45
  *
42
46
  * BlueBundlesV1 moves the full live debt and collateral without pulling tokens from the account.
43
47
  * When Morpho authorization is missing, the plan requests a signature inline if supported,
44
48
  * otherwise it puts a direct authorization step before the migration.
45
49
  * @param client - Viem client used to check deployed contracts and resolve Morpho authorization.
46
50
  * @param params - Chain, sending account, market and position snapshots, and optional reallocations.
51
+ * @param params.maxPenalty - Maximum WAD-scaled penalty rate per reallocation in [0, WAD], defaulting to zero. Each rate applies to that reallocation's assets, so it does not bound the total penalty added to destination debt.
47
52
  * @returns A frozen plan with only the steps and signature requests required for the migration.
53
+ * @throws {InvalidBigIntInputError} when a supplied maxPenalty is not a bigint.
48
54
  * @throws {BlueSnapshotChainMismatchError} when either snapshot comes from another chain.
49
55
  * @throws {MarketIdMismatchError} when a snapshot or embedded market tuple does not match its market ID.
50
56
  * @throws {AccrualPositionUserMismatchError} when a position belongs to another account.
@@ -57,9 +63,10 @@ export interface BlueRefinancePlanParams extends Omit<IntentParams, "deployless"
57
63
  * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
58
64
  * @throws {NonPositiveInputError} when the source has no debt shares, or expiry or reallocation assets are not positive.
59
65
  * @throws {ExpiredDeadlineError} when expiry is at or before `now`.
60
- * @throws {NegativeInputError} when a referral fee or reallocation penalty is negative.
66
+ * @throws {NegativeInputError} when a referral fee, maxPenalty or reallocation penalty is negative.
61
67
  * @throws {InputExceedsMaxError} when the fee or a reallocation value exceeds its bound.
62
- * @throws {ReferralFeePctExceededError} when `referralFee.bps` is 10,000.
68
+ * Also thrown when maxPenalty exceeds WAD or a penalty exceeds maxPenalty (zero by default).
69
+ * @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 1,000.
63
70
  * @throws {ReferralFeeRecipientMissingError} when a positive fee has no nonzero recipient.
64
71
  * @throws {InvalidTransactionPlanError} when the account, referral fee recipient, market tuples, or stored reallocation fields are malformed.
65
72
  * @throws {InvalidCalldataOriginError} when calldata origin is not nonempty, whole-byte hex.
@@ -13,13 +13,17 @@ import { validateBlueRefinanceDestination } from "./refinanceValidation.js";
13
13
  * Prepares a full Blue borrow-position migration. Fetch both market and position snapshots at the
14
14
  * same block and pass that block's timestamp as `now`. Penalties and fees increase destination debt;
15
15
  * the quote checks the buffered destination LLTV and the transaction enforces it again onchain.
16
+ * Health uses the expiry floored at now and both market snapshots. Expiries more than
17
+ * 365 days out retain the legacy +2h projection for unlimited sentinels.
16
18
  *
17
19
  * BlueBundlesV1 moves the full live debt and collateral without pulling tokens from the account.
18
20
  * When Morpho authorization is missing, the plan requests a signature inline if supported,
19
21
  * otherwise it puts a direct authorization step before the migration.
20
22
  * @param client - Viem client used to check deployed contracts and resolve Morpho authorization.
21
23
  * @param params - Chain, sending account, market and position snapshots, and optional reallocations.
24
+ * @param params.maxPenalty - Maximum WAD-scaled penalty rate per reallocation in [0, WAD], defaulting to zero. Each rate applies to that reallocation's assets, so it does not bound the total penalty added to destination debt.
22
25
  * @returns A frozen plan with only the steps and signature requests required for the migration.
26
+ * @throws {InvalidBigIntInputError} when a supplied maxPenalty is not a bigint.
23
27
  * @throws {BlueSnapshotChainMismatchError} when either snapshot comes from another chain.
24
28
  * @throws {MarketIdMismatchError} when a snapshot or embedded market tuple does not match its market ID.
25
29
  * @throws {AccrualPositionUserMismatchError} when a position belongs to another account.
@@ -32,9 +36,10 @@ import { validateBlueRefinanceDestination } from "./refinanceValidation.js";
32
36
  * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
33
37
  * @throws {NonPositiveInputError} when the source has no debt shares, or expiry or reallocation assets are not positive.
34
38
  * @throws {ExpiredDeadlineError} when expiry is at or before `now`.
35
- * @throws {NegativeInputError} when a referral fee or reallocation penalty is negative.
39
+ * @throws {NegativeInputError} when a referral fee, maxPenalty or reallocation penalty is negative.
36
40
  * @throws {InputExceedsMaxError} when the fee or a reallocation value exceeds its bound.
37
- * @throws {ReferralFeePctExceededError} when `referralFee.bps` is 10,000.
41
+ * Also thrown when maxPenalty exceeds WAD or a penalty exceeds maxPenalty (zero by default).
42
+ * @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 1,000.
38
43
  * @throws {ReferralFeeRecipientMissingError} when a positive fee has no nonzero recipient.
39
44
  * @throws {InvalidTransactionPlanError} when the account, referral fee recipient, market tuples, or stored reallocation fields are malformed.
40
45
  * @throws {InvalidCalldataOriginError} when calldata origin is not nonempty, whole-byte hex.
@@ -62,6 +67,7 @@ import { validateBlueRefinanceDestination } from "./refinanceValidation.js";
62
67
  */
63
68
  export async function prepareBlueRefinance(client, params) {
64
69
  const { account, chainId, source, destination } = params;
70
+ const { maxPenalty } = params;
65
71
  const now = params.now ?? Time.timestamp();
66
72
  const sourceMarketParams = structuredClone(source.marketData.market.params);
67
73
  const destinationMarketParams = structuredClone(destination.marketData.market.params);
@@ -108,7 +114,10 @@ export async function prepareBlueRefinance(client, params) {
108
114
  borrowShares: source.positionData.position.borrowShares,
109
115
  });
110
116
  // The quote only gates preparation; the contract migrates the actual live position.
111
- const { penaltyAssets } = parseBlueAllocations(reallocations, parseBlueMarket(destinationMarketParams));
117
+ const { penaltyAssets } = parseBlueAllocations(reallocations, {
118
+ marketParams: parseBlueMarket(destinationMarketParams),
119
+ maxPenalty,
120
+ });
112
121
  for (const [index, reallocation] of reallocations.entries()) {
113
122
  validatePlanReallocationShape(reallocation, `$.reallocations[${index}]`);
114
123
  }
@@ -119,6 +128,7 @@ export async function prepareBlueRefinance(client, params) {
119
128
  penaltyAssets,
120
129
  referralFeePct,
121
130
  now,
131
+ deadline,
122
132
  });
123
133
  return { id, needsAuthorization: true };
124
134
  });
@@ -139,6 +149,7 @@ export async function prepareBlueRefinance(client, params) {
139
149
  maxLtv: MathLib.zeroFloorSub(destinationMarketParams.lltv, DEFAULT_LLTV_BUFFER),
140
150
  ...common,
141
151
  reallocations,
152
+ ...(maxPenalty !== undefined && { maxPenalty }),
142
153
  ...(request && { authorizationNonce: request.args.nonce }),
143
154
  },
144
155
  signatureRequestIds: request === undefined ? {} : { morphoAuthorization: request.id },
@@ -220,6 +231,12 @@ function validatePlanReallocationShape(value, path) {
220
231
  /** @internal Validates the stored migration inputs and optional authorization binding. */
221
232
  export function validateRefinancePlanAction(action, path) {
222
233
  const inputs = getPlanObject(action.inputs, `${path}.inputs`);
234
+ if (inputs.maxPenalty !== undefined) {
235
+ validatePlanField(inputs.maxPenalty, {
236
+ path: `${path}.inputs.maxPenalty`,
237
+ type: "uint256 bigint",
238
+ });
239
+ }
223
240
  validatePlanFields(inputs, {
224
241
  path: `${path}.inputs`,
225
242
  fields: {
@@ -40,12 +40,11 @@ export interface BlueRepayPlanParams extends IntentParams {
40
40
  * @throws {NonPositiveInputError} If expiry, repayment, or derived funding is not positive.
41
41
  * @throws {ExpiredDeadlineError} If expiry is at or before `now`.
42
42
  * @throws {NegativeInputError} If `referralFee.bps` is negative.
43
- * @throws {InputExceedsMaxError} If a share-mode expiry exceeds the quote horizon, the referral fee exceeds 10,000 bps, or an encoded amount exceeds uint256.
43
+ * @throws {InputExceedsMaxError} If a share-mode expiry exceeds the quote horizon, the referral fee exceeds 1,000 bps, or an encoded amount exceeds uint256.
44
44
  * @throws {InvalidCalldataOriginError} If attribution bytes are empty, malformed, or have an odd number of hex digits.
45
45
  * @throws {BlueSnapshotChainMismatchError} If either snapshot describes another chain.
46
46
  * @throws {MarketIdMismatchError} If either snapshot's market ID disagrees with `marketId` or its market tuple.
47
47
  * @throws {AccrualPositionUserMismatchError} If the position belongs to another account.
48
- * @throws {ReferralFeePctExceededError} If the referral fee equals 10,000 bps; the normalized fee must be below WAD.
49
48
  * @throws {ReferralFeeRecipientMissingError} If a positive referral fee has no recipient or a zero recipient.
50
49
  * @throws {RepayExceedsDebtError} If an asset repayment exceeds the snapshot's borrow assets.
51
50
  * @throws {RepaySharesExceedDebtError} If a non-saturated share repayment exceeds the snapshot's borrow shares.
@@ -23,12 +23,11 @@ import { prepareBlue, } from "./prepare.js";
23
23
  * @throws {NonPositiveInputError} If expiry, repayment, or derived funding is not positive.
24
24
  * @throws {ExpiredDeadlineError} If expiry is at or before `now`.
25
25
  * @throws {NegativeInputError} If `referralFee.bps` is negative.
26
- * @throws {InputExceedsMaxError} If a share-mode expiry exceeds the quote horizon, the referral fee exceeds 10,000 bps, or an encoded amount exceeds uint256.
26
+ * @throws {InputExceedsMaxError} If a share-mode expiry exceeds the quote horizon, the referral fee exceeds 1,000 bps, or an encoded amount exceeds uint256.
27
27
  * @throws {InvalidCalldataOriginError} If attribution bytes are empty, malformed, or have an odd number of hex digits.
28
28
  * @throws {BlueSnapshotChainMismatchError} If either snapshot describes another chain.
29
29
  * @throws {MarketIdMismatchError} If either snapshot's market ID disagrees with `marketId` or its market tuple.
30
30
  * @throws {AccrualPositionUserMismatchError} If the position belongs to another account.
31
- * @throws {ReferralFeePctExceededError} If the referral fee equals 10,000 bps; the normalized fee must be below WAD.
32
31
  * @throws {ReferralFeeRecipientMissingError} If a positive referral fee has no recipient or a zero recipient.
33
32
  * @throws {RepayExceedsDebtError} If an asset repayment exceeds the snapshot's borrow assets.
34
33
  * @throws {RepaySharesExceedDebtError} If a non-saturated share repayment exceeds the snapshot's borrow shares.
@@ -31,6 +31,8 @@ export type BlueRepayWithdrawCollateralPlanParams = IntentParams & {
31
31
  });
32
32
  /**
33
33
  * Prepares one BlueBundlesV1 repayment and collateral withdrawal from caller-fetched snapshots.
34
+ * Withdrawal health uses the expiry floored at max(now, lastUpdate); expiries more than
35
+ * 365 days out retain the legacy +2h projection. Repay-only funding is independent.
34
36
  * Full repayment uses `repayShares: maxUint256`; `funding: { type: "native" }` funds the computed cap.
35
37
  * Signatures are embedded in the operation; direct approvals and authorization precede it.
36
38
  * @param client - Viem client used only for prerequisite reads.
@@ -49,9 +51,8 @@ export type BlueRepayWithdrawCollateralPlanParams = IntentParams & {
49
51
  * @throws {NegativeInputError} when an amount or referral fee is negative.
50
52
  * @throws {NonPositiveInputError} when the expiry is not positive, both operation legs are zero,
51
53
  * 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.
54
+ * @throws {InputExceedsMaxError} when a value exceeds uint256, `referralFee.bps` exceeds 1,000,
55
+ * or a share-mode expiry exceeds the two-hour funding quote horizon.
55
56
  * @throws {ReferralFeeRecipientMissingError} when a positive fee has no non-zero recipient.
56
57
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports, another chain.
57
58
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.