@morpho-org/morpho-sdk 10.0.2 → 10.1.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 (420) hide show
  1. package/README.md +6 -2
  2. package/lib/cjs/actions/blue/borrow.d.ts +2 -1
  3. package/lib/cjs/actions/blue/borrow.internal.d.ts +13 -0
  4. package/lib/cjs/actions/blue/borrow.internal.js +35 -0
  5. package/lib/cjs/actions/blue/borrow.js +4 -16
  6. package/lib/cjs/actions/blue/common.d.ts +50 -28
  7. package/lib/cjs/actions/blue/common.js +21 -34
  8. package/lib/cjs/actions/blue/encode.d.ts +23 -0
  9. package/lib/cjs/actions/blue/encode.js +171 -0
  10. package/lib/cjs/actions/blue/refinance.d.ts +3 -2
  11. package/lib/cjs/actions/blue/refinance.internal.d.ts +42 -0
  12. package/lib/cjs/actions/blue/refinance.internal.js +62 -0
  13. package/lib/cjs/actions/blue/refinance.js +5 -63
  14. package/lib/cjs/actions/blue/refinanceValidation.d.ts +4 -5
  15. package/lib/cjs/actions/blue/refinanceValidation.js +1 -3
  16. package/lib/cjs/actions/blue/repay.d.ts +1 -1
  17. package/lib/cjs/actions/blue/repay.internal.d.ts +13 -0
  18. package/lib/cjs/actions/blue/repay.internal.js +38 -0
  19. package/lib/cjs/actions/blue/repay.js +2 -17
  20. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +2 -2
  21. package/lib/cjs/actions/blue/repayWithdrawCollateral.internal.d.ts +61 -0
  22. package/lib/cjs/actions/blue/repayWithdrawCollateral.internal.js +112 -0
  23. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +3 -116
  24. package/lib/cjs/actions/blue/signatures.d.ts +30 -0
  25. package/lib/cjs/actions/blue/signatures.js +90 -0
  26. package/lib/cjs/actions/blue/supply.d.ts +1 -1
  27. package/lib/cjs/actions/blue/supply.internal.d.ts +32 -0
  28. package/lib/cjs/actions/blue/supply.internal.js +101 -0
  29. package/lib/cjs/actions/blue/supply.js +2 -67
  30. package/lib/cjs/actions/blue/supplyCollateral.d.ts +1 -1
  31. package/lib/cjs/actions/blue/supplyCollateral.internal.d.ts +13 -0
  32. package/lib/cjs/actions/blue/supplyCollateral.internal.js +37 -0
  33. package/lib/cjs/actions/blue/supplyCollateral.js +2 -17
  34. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +4 -3
  35. package/lib/cjs/actions/blue/supplyCollateralBorrow.internal.d.ts +63 -0
  36. package/lib/cjs/actions/blue/supplyCollateralBorrow.internal.js +94 -0
  37. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +5 -106
  38. package/lib/cjs/actions/blue/withdraw.d.ts +4 -3
  39. package/lib/cjs/actions/blue/withdraw.internal.d.ts +56 -0
  40. package/lib/cjs/actions/blue/withdraw.internal.js +84 -0
  41. package/lib/cjs/actions/blue/withdraw.js +5 -78
  42. package/lib/cjs/actions/blue/withdrawBuyCallback.d.ts +2 -2
  43. package/lib/cjs/actions/blue/withdrawBuyCallback.internal.d.ts +20 -0
  44. package/lib/cjs/actions/blue/withdrawBuyCallback.internal.js +58 -0
  45. package/lib/cjs/actions/blue/withdrawBuyCallback.js +2 -39
  46. package/lib/cjs/actions/blue/withdrawCollateral.internal.d.ts +16 -0
  47. package/lib/cjs/actions/blue/withdrawCollateral.internal.js +39 -0
  48. package/lib/cjs/actions/blue/withdrawCollateral.js +2 -17
  49. package/lib/cjs/actions/bundles/common.d.ts +9 -0
  50. package/lib/cjs/actions/bundles/common.js +18 -6
  51. package/lib/cjs/actions/bundles/index.d.ts +1 -1
  52. package/lib/cjs/actions/bundles/index.js +3 -16
  53. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +14 -0
  54. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +59 -60
  55. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +22 -1
  56. package/lib/cjs/actions/midnight/cancelAndMake.js +46 -87
  57. package/lib/cjs/actions/midnight/cancelOffers.d.ts +11 -0
  58. package/lib/cjs/actions/midnight/cancelOffers.js +22 -4
  59. package/lib/cjs/actions/midnight/encode.d.ts +36 -0
  60. package/lib/cjs/actions/midnight/encode.js +554 -0
  61. package/lib/cjs/actions/midnight/index.d.ts +14 -13
  62. package/lib/cjs/actions/midnight/index.js +29 -13
  63. package/lib/cjs/actions/midnight/parse.d.ts +35 -0
  64. package/lib/cjs/actions/midnight/parse.js +73 -0
  65. package/lib/cjs/actions/midnight/parseCollateralBatch.d.ts +58 -0
  66. package/lib/cjs/actions/midnight/parseCollateralBatch.js +216 -0
  67. package/lib/cjs/actions/midnight/redeem.d.ts +16 -3
  68. package/lib/cjs/actions/midnight/redeem.js +22 -51
  69. package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +13 -0
  70. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +42 -67
  71. package/lib/cjs/actions/midnight/supplyCollateral.d.ts +40 -5
  72. package/lib/cjs/actions/midnight/supplyCollateral.js +60 -54
  73. package/lib/cjs/actions/midnight/supplyCollateralBatch.d.ts +3 -3
  74. package/lib/cjs/actions/midnight/supplyCollateralBatch.js +3 -62
  75. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +24 -0
  76. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +39 -66
  77. package/lib/cjs/actions/midnight/supplyCollateralWithNative.d.ts +77 -0
  78. package/lib/cjs/actions/midnight/supplyCollateralWithNative.js +142 -0
  79. package/lib/cjs/actions/midnight/takeBorrow.d.ts +17 -2
  80. package/lib/cjs/actions/midnight/takeBorrow.js +25 -55
  81. package/lib/cjs/actions/midnight/takeLend.d.ts +21 -1
  82. package/lib/cjs/actions/midnight/takeLend.js +30 -57
  83. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +22 -2
  84. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +34 -61
  85. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +17 -2
  86. package/lib/cjs/actions/midnight/takeWithdraw.js +78 -115
  87. package/lib/cjs/actions/midnight/withdrawCollateral.d.ts +16 -3
  88. package/lib/cjs/actions/midnight/withdrawCollateral.js +25 -56
  89. package/lib/cjs/actions/midnight/withdrawCollateralBatch.d.ts +3 -3
  90. package/lib/cjs/actions/midnight/withdrawCollateralBatch.js +3 -71
  91. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +13 -0
  92. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +39 -19
  93. package/lib/cjs/actions/requirements/blue/index.d.ts +1 -1
  94. package/lib/cjs/actions/requirements/blue/index.js +3 -15
  95. package/lib/cjs/actions/requirements/chainCheck.d.ts +5 -0
  96. package/lib/cjs/actions/requirements/chainCheck.js +10 -0
  97. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -0
  98. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +40 -27
  99. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +11 -1
  100. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +36 -17
  101. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +14 -1
  102. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +44 -9
  103. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +10 -0
  104. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +61 -24
  105. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +10 -0
  106. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +25 -4
  107. package/lib/cjs/actions/requirements/encode/index.d.ts +5 -5
  108. package/lib/cjs/actions/requirements/encode/index.js +11 -19
  109. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +26 -11
  110. package/lib/cjs/actions/requirements/getRequirementsApproval.js +40 -12
  111. package/lib/cjs/actions/requirements/index.d.ts +1 -1
  112. package/lib/cjs/actions/requirements/index.js +3 -1
  113. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +11 -0
  114. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +34 -19
  115. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +11 -0
  116. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +26 -12
  117. package/lib/cjs/actions/requirements/midnight/index.d.ts +2 -2
  118. package/lib/cjs/actions/requirements/midnight/index.js +5 -16
  119. package/lib/cjs/actions/vaultV1/deposit.d.ts +21 -0
  120. package/lib/cjs/actions/vaultV1/deposit.js +46 -10
  121. package/lib/cjs/actions/vaultV1/inKindRedeem.d.ts +18 -1
  122. package/lib/cjs/actions/vaultV1/inKindRedeem.js +36 -16
  123. package/lib/cjs/actions/vaultV1/index.d.ts +5 -5
  124. package/lib/cjs/actions/vaultV1/index.js +11 -19
  125. package/lib/cjs/actions/vaultV1/migrateToV2.d.ts +21 -0
  126. package/lib/cjs/actions/vaultV1/migrateToV2.js +49 -11
  127. package/lib/cjs/actions/vaultV1/redeem.d.ts +19 -0
  128. package/lib/cjs/actions/vaultV1/redeem.js +28 -7
  129. package/lib/cjs/actions/vaultV1/withdraw.d.ts +19 -0
  130. package/lib/cjs/actions/vaultV1/withdraw.js +28 -7
  131. package/lib/cjs/actions/vaultV2/deposit.d.ts +21 -0
  132. package/lib/cjs/actions/vaultV2/deposit.js +46 -10
  133. package/lib/cjs/actions/vaultV2/forceRedeem.d.ts +20 -2
  134. package/lib/cjs/actions/vaultV2/forceRedeem.js +39 -8
  135. package/lib/cjs/actions/vaultV2/forceWithdraw.d.ts +23 -1
  136. package/lib/cjs/actions/vaultV2/forceWithdraw.js +36 -14
  137. package/lib/cjs/actions/vaultV2/inKindRedeem.d.ts +18 -1
  138. package/lib/cjs/actions/vaultV2/inKindRedeem.js +35 -15
  139. package/lib/cjs/actions/vaultV2/index.d.ts +6 -6
  140. package/lib/cjs/actions/vaultV2/index.js +13 -20
  141. package/lib/cjs/actions/vaultV2/redeem.d.ts +19 -0
  142. package/lib/cjs/actions/vaultV2/redeem.js +28 -7
  143. package/lib/cjs/actions/vaultV2/withdraw.d.ts +19 -0
  144. package/lib/cjs/actions/vaultV2/withdraw.js +28 -7
  145. package/lib/cjs/entities/blue/blue.d.ts +35 -8
  146. package/lib/cjs/entities/blue/blue.js +467 -406
  147. package/lib/cjs/entities/midnight/midnight.d.ts +117 -41
  148. package/lib/cjs/entities/midnight/midnight.js +472 -843
  149. package/lib/cjs/entities/midnight/parse.d.ts +74 -0
  150. package/lib/cjs/entities/midnight/parse.js +336 -0
  151. package/lib/cjs/entities/midnight/prepare.d.ts +47 -0
  152. package/lib/cjs/entities/midnight/prepare.js +293 -0
  153. package/lib/cjs/entities/midnight/publication.d.ts +7 -3
  154. package/lib/cjs/entities/midnight/publication.js +10 -7
  155. package/lib/cjs/entities/midnight/types.d.ts +7 -0
  156. package/lib/cjs/entities/requirements/assertContractCode.d.ts +10 -5
  157. package/lib/cjs/entities/requirements/assertContractCode.js +24 -15
  158. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +15 -0
  159. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +59 -51
  160. package/lib/cjs/entities/requirements/getErc2612Permit.d.ts +7 -3
  161. package/lib/cjs/entities/requirements/getErc2612Permit.js +20 -4
  162. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.d.ts +15 -0
  163. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.js +24 -7
  164. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +14 -0
  165. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +27 -7
  166. package/lib/cjs/entities/requirements/getVaultV1InKindRedeemRequirements.js +4 -3
  167. package/lib/cjs/entities/requirements/getVaultV2ForceWithdrawRequirements.js +4 -3
  168. package/lib/cjs/entities/requirements/getVaultV2InKindRedeemRequirements.js +4 -3
  169. package/lib/cjs/entities/requirements/index.d.ts +2 -2
  170. package/lib/cjs/entities/requirements/index.js +5 -16
  171. package/lib/cjs/entities/requirements/validateNativeRequirements.d.ts +21 -0
  172. package/lib/cjs/entities/requirements/validateNativeRequirements.js +37 -0
  173. package/lib/cjs/entities/vaultV1/inKindRedeemQuote.d.ts +2 -2
  174. package/lib/cjs/entities/vaultV1/inKindRedeemQuote.js +1 -7
  175. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +17 -40
  176. package/lib/cjs/entities/vaultV1/vaultV1.js +228 -159
  177. package/lib/cjs/entities/vaultV2/forceWithdrawQuote.d.ts +4 -0
  178. package/lib/cjs/entities/vaultV2/forceWithdrawQuote.js +9 -4
  179. package/lib/cjs/entities/vaultV2/inKindRedeemQuote.d.ts +2 -2
  180. package/lib/cjs/entities/vaultV2/inKindRedeemQuote.js +1 -7
  181. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +21 -52
  182. package/lib/cjs/entities/vaultV2/vaultV2.js +226 -150
  183. package/lib/cjs/helpers/parse.d.ts +33 -0
  184. package/lib/cjs/helpers/parse.js +71 -0
  185. package/lib/cjs/helpers/parseMidnight.d.ts +48 -0
  186. package/lib/cjs/helpers/parseMidnight.js +95 -0
  187. package/lib/cjs/helpers/parseMidnightMaker.d.ts +44 -0
  188. package/lib/cjs/helpers/parseMidnightMaker.js +154 -0
  189. package/lib/cjs/helpers/validate.d.ts +3 -2
  190. package/lib/cjs/helpers/validate.js +4 -0
  191. package/lib/cjs/helpers/validateMidnightCancelAndMakePublication.d.ts +8 -0
  192. package/lib/cjs/helpers/validateMidnightCancelAndMakePublication.js +4 -4
  193. package/lib/cjs/helpers/validateMidnightPublication.d.ts +17 -1
  194. package/lib/cjs/index.d.ts +1 -0
  195. package/lib/cjs/transactionPlan/blue/refinance.js +17 -9
  196. package/lib/cjs/transactionPlan/blue/repay.js +2 -1
  197. package/lib/cjs/transactionPlan/blue/repayWithdrawCollateral.js +23 -4
  198. package/lib/cjs/transactionPlan/blue/supplyCollateralBorrow.js +2 -2
  199. package/lib/cjs/transactionPlan/blue/withdraw.d.ts +2 -2
  200. package/lib/cjs/transactionPlan/blue/withdraw.js +3 -3
  201. package/lib/cjs/transactionPlan/blue/withdrawCollateral.js +6 -2
  202. package/lib/cjs/transactionPlan/validation.d.ts +1 -1
  203. package/lib/cjs/transactionPlan/validation.js +3 -0
  204. package/lib/cjs/transactionPlan/vaultv1/deposit.d.ts +2 -2
  205. package/lib/cjs/transactionPlan/vaultv1/deposit.js +2 -2
  206. package/lib/cjs/types/action.d.ts +13 -2
  207. package/lib/cjs/types/error.d.ts +20 -2
  208. package/lib/cjs/types/error.js +32 -3
  209. package/lib/cjs/version.d.ts +1 -1
  210. package/lib/cjs/version.js +1 -1
  211. package/lib/esm/actions/blue/borrow.d.ts +2 -1
  212. package/lib/esm/actions/blue/borrow.internal.d.ts +13 -0
  213. package/lib/esm/actions/blue/borrow.internal.js +30 -0
  214. package/lib/esm/actions/blue/borrow.js +4 -16
  215. package/lib/esm/actions/blue/common.d.ts +50 -28
  216. package/lib/esm/actions/blue/common.js +21 -33
  217. package/lib/esm/actions/blue/encode.d.ts +23 -0
  218. package/lib/esm/actions/blue/encode.js +164 -0
  219. package/lib/esm/actions/blue/refinance.d.ts +3 -2
  220. package/lib/esm/actions/blue/refinance.internal.d.ts +42 -0
  221. package/lib/esm/actions/blue/refinance.internal.js +56 -0
  222. package/lib/esm/actions/blue/refinance.js +5 -63
  223. package/lib/esm/actions/blue/refinanceValidation.d.ts +4 -5
  224. package/lib/esm/actions/blue/refinanceValidation.js +2 -4
  225. package/lib/esm/actions/blue/repay.d.ts +1 -1
  226. package/lib/esm/actions/blue/repay.internal.d.ts +13 -0
  227. package/lib/esm/actions/blue/repay.internal.js +33 -0
  228. package/lib/esm/actions/blue/repay.js +2 -17
  229. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +2 -2
  230. package/lib/esm/actions/blue/repayWithdrawCollateral.internal.d.ts +61 -0
  231. package/lib/esm/actions/blue/repayWithdrawCollateral.internal.js +104 -0
  232. package/lib/esm/actions/blue/repayWithdrawCollateral.js +3 -116
  233. package/lib/esm/actions/blue/signatures.d.ts +30 -0
  234. package/lib/esm/actions/blue/signatures.js +82 -0
  235. package/lib/esm/actions/blue/supply.d.ts +1 -1
  236. package/lib/esm/actions/blue/supply.internal.d.ts +32 -0
  237. package/lib/esm/actions/blue/supply.internal.js +95 -0
  238. package/lib/esm/actions/blue/supply.js +2 -67
  239. package/lib/esm/actions/blue/supplyCollateral.d.ts +1 -1
  240. package/lib/esm/actions/blue/supplyCollateral.internal.d.ts +13 -0
  241. package/lib/esm/actions/blue/supplyCollateral.internal.js +32 -0
  242. package/lib/esm/actions/blue/supplyCollateral.js +2 -17
  243. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +4 -3
  244. package/lib/esm/actions/blue/supplyCollateralBorrow.internal.d.ts +63 -0
  245. package/lib/esm/actions/blue/supplyCollateralBorrow.internal.js +87 -0
  246. package/lib/esm/actions/blue/supplyCollateralBorrow.js +5 -106
  247. package/lib/esm/actions/blue/withdraw.d.ts +4 -3
  248. package/lib/esm/actions/blue/withdraw.internal.d.ts +56 -0
  249. package/lib/esm/actions/blue/withdraw.internal.js +77 -0
  250. package/lib/esm/actions/blue/withdraw.js +5 -78
  251. package/lib/esm/actions/blue/withdrawBuyCallback.d.ts +2 -2
  252. package/lib/esm/actions/blue/withdrawBuyCallback.internal.d.ts +20 -0
  253. package/lib/esm/actions/blue/withdrawBuyCallback.internal.js +53 -0
  254. package/lib/esm/actions/blue/withdrawBuyCallback.js +2 -39
  255. package/lib/esm/actions/blue/withdrawCollateral.internal.d.ts +16 -0
  256. package/lib/esm/actions/blue/withdrawCollateral.internal.js +34 -0
  257. package/lib/esm/actions/blue/withdrawCollateral.js +2 -17
  258. package/lib/esm/actions/bundles/common.d.ts +9 -0
  259. package/lib/esm/actions/bundles/common.js +15 -4
  260. package/lib/esm/actions/bundles/index.d.ts +1 -1
  261. package/lib/esm/actions/bundles/index.js +1 -1
  262. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +14 -0
  263. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +58 -61
  264. package/lib/esm/actions/midnight/cancelAndMake.d.ts +22 -1
  265. package/lib/esm/actions/midnight/cancelAndMake.js +43 -85
  266. package/lib/esm/actions/midnight/cancelOffers.d.ts +11 -0
  267. package/lib/esm/actions/midnight/cancelOffers.js +18 -2
  268. package/lib/esm/actions/midnight/encode.d.ts +36 -0
  269. package/lib/esm/actions/midnight/encode.js +539 -0
  270. package/lib/esm/actions/midnight/index.d.ts +14 -13
  271. package/lib/esm/actions/midnight/index.js +14 -13
  272. package/lib/esm/actions/midnight/parse.d.ts +35 -0
  273. package/lib/esm/actions/midnight/parse.js +68 -0
  274. package/lib/esm/actions/midnight/parseCollateralBatch.d.ts +58 -0
  275. package/lib/esm/actions/midnight/parseCollateralBatch.js +209 -0
  276. package/lib/esm/actions/midnight/redeem.d.ts +16 -3
  277. package/lib/esm/actions/midnight/redeem.js +20 -50
  278. package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +13 -0
  279. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +38 -64
  280. package/lib/esm/actions/midnight/supplyCollateral.d.ts +40 -5
  281. package/lib/esm/actions/midnight/supplyCollateral.js +57 -53
  282. package/lib/esm/actions/midnight/supplyCollateralBatch.d.ts +3 -3
  283. package/lib/esm/actions/midnight/supplyCollateralBatch.js +3 -62
  284. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +24 -0
  285. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +33 -61
  286. package/lib/esm/actions/midnight/supplyCollateralWithNative.d.ts +77 -0
  287. package/lib/esm/actions/midnight/supplyCollateralWithNative.js +137 -0
  288. package/lib/esm/actions/midnight/takeBorrow.d.ts +17 -2
  289. package/lib/esm/actions/midnight/takeBorrow.js +20 -51
  290. package/lib/esm/actions/midnight/takeLend.d.ts +21 -1
  291. package/lib/esm/actions/midnight/takeLend.js +26 -54
  292. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +22 -2
  293. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +30 -58
  294. package/lib/esm/actions/midnight/takeWithdraw.d.ts +17 -2
  295. package/lib/esm/actions/midnight/takeWithdraw.js +76 -114
  296. package/lib/esm/actions/midnight/withdrawCollateral.d.ts +16 -3
  297. package/lib/esm/actions/midnight/withdrawCollateral.js +23 -55
  298. package/lib/esm/actions/midnight/withdrawCollateralBatch.d.ts +3 -3
  299. package/lib/esm/actions/midnight/withdrawCollateralBatch.js +3 -71
  300. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +13 -0
  301. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +36 -18
  302. package/lib/esm/actions/requirements/blue/index.d.ts +1 -1
  303. package/lib/esm/actions/requirements/blue/index.js +1 -1
  304. package/lib/esm/actions/requirements/chainCheck.d.ts +5 -0
  305. package/lib/esm/actions/requirements/chainCheck.js +6 -0
  306. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -0
  307. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +36 -25
  308. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +11 -1
  309. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +33 -16
  310. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +14 -1
  311. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +41 -8
  312. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +10 -0
  313. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +59 -24
  314. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +10 -0
  315. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +21 -2
  316. package/lib/esm/actions/requirements/encode/index.d.ts +5 -5
  317. package/lib/esm/actions/requirements/encode/index.js +5 -5
  318. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +26 -11
  319. package/lib/esm/actions/requirements/getRequirementsApproval.js +38 -12
  320. package/lib/esm/actions/requirements/index.d.ts +1 -1
  321. package/lib/esm/actions/requirements/index.js +1 -1
  322. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +11 -0
  323. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +31 -18
  324. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +11 -0
  325. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +22 -10
  326. package/lib/esm/actions/requirements/midnight/index.d.ts +2 -2
  327. package/lib/esm/actions/requirements/midnight/index.js +2 -2
  328. package/lib/esm/actions/vaultV1/deposit.d.ts +21 -0
  329. package/lib/esm/actions/vaultV1/deposit.js +43 -9
  330. package/lib/esm/actions/vaultV1/inKindRedeem.d.ts +18 -1
  331. package/lib/esm/actions/vaultV1/inKindRedeem.js +33 -15
  332. package/lib/esm/actions/vaultV1/index.d.ts +5 -5
  333. package/lib/esm/actions/vaultV1/index.js +5 -5
  334. package/lib/esm/actions/vaultV1/migrateToV2.d.ts +21 -0
  335. package/lib/esm/actions/vaultV1/migrateToV2.js +47 -11
  336. package/lib/esm/actions/vaultV1/redeem.d.ts +19 -0
  337. package/lib/esm/actions/vaultV1/redeem.js +26 -7
  338. package/lib/esm/actions/vaultV1/withdraw.d.ts +19 -0
  339. package/lib/esm/actions/vaultV1/withdraw.js +26 -7
  340. package/lib/esm/actions/vaultV2/deposit.d.ts +21 -0
  341. package/lib/esm/actions/vaultV2/deposit.js +43 -9
  342. package/lib/esm/actions/vaultV2/forceRedeem.d.ts +20 -2
  343. package/lib/esm/actions/vaultV2/forceRedeem.js +35 -6
  344. package/lib/esm/actions/vaultV2/forceWithdraw.d.ts +23 -1
  345. package/lib/esm/actions/vaultV2/forceWithdraw.js +33 -13
  346. package/lib/esm/actions/vaultV2/inKindRedeem.d.ts +18 -1
  347. package/lib/esm/actions/vaultV2/inKindRedeem.js +32 -14
  348. package/lib/esm/actions/vaultV2/index.d.ts +6 -6
  349. package/lib/esm/actions/vaultV2/index.js +6 -6
  350. package/lib/esm/actions/vaultV2/redeem.d.ts +19 -0
  351. package/lib/esm/actions/vaultV2/redeem.js +26 -7
  352. package/lib/esm/actions/vaultV2/withdraw.d.ts +19 -0
  353. package/lib/esm/actions/vaultV2/withdraw.js +26 -7
  354. package/lib/esm/entities/blue/blue.d.ts +35 -8
  355. package/lib/esm/entities/blue/blue.js +449 -388
  356. package/lib/esm/entities/midnight/midnight.d.ts +117 -41
  357. package/lib/esm/entities/midnight/midnight.js +455 -826
  358. package/lib/esm/entities/midnight/parse.d.ts +74 -0
  359. package/lib/esm/entities/midnight/parse.js +320 -0
  360. package/lib/esm/entities/midnight/prepare.d.ts +47 -0
  361. package/lib/esm/entities/midnight/prepare.js +282 -0
  362. package/lib/esm/entities/midnight/publication.d.ts +7 -3
  363. package/lib/esm/entities/midnight/publication.js +7 -3
  364. package/lib/esm/entities/midnight/types.d.ts +7 -0
  365. package/lib/esm/entities/requirements/assertContractCode.d.ts +10 -5
  366. package/lib/esm/entities/requirements/assertContractCode.js +24 -15
  367. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +15 -0
  368. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +53 -47
  369. package/lib/esm/entities/requirements/getErc2612Permit.d.ts +7 -3
  370. package/lib/esm/entities/requirements/getErc2612Permit.js +19 -4
  371. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.d.ts +15 -0
  372. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.js +20 -5
  373. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +14 -0
  374. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +23 -5
  375. package/lib/esm/entities/requirements/getVaultV1InKindRedeemRequirements.js +4 -3
  376. package/lib/esm/entities/requirements/getVaultV2ForceWithdrawRequirements.js +4 -3
  377. package/lib/esm/entities/requirements/getVaultV2InKindRedeemRequirements.js +4 -3
  378. package/lib/esm/entities/requirements/index.d.ts +2 -2
  379. package/lib/esm/entities/requirements/index.js +2 -2
  380. package/lib/esm/entities/requirements/validateNativeRequirements.d.ts +21 -0
  381. package/lib/esm/entities/requirements/validateNativeRequirements.js +33 -0
  382. package/lib/esm/entities/vaultV1/inKindRedeemQuote.d.ts +2 -2
  383. package/lib/esm/entities/vaultV1/inKindRedeemQuote.js +1 -7
  384. package/lib/esm/entities/vaultV1/vaultV1.d.ts +17 -40
  385. package/lib/esm/entities/vaultV1/vaultV1.js +208 -139
  386. package/lib/esm/entities/vaultV2/forceWithdrawQuote.d.ts +4 -0
  387. package/lib/esm/entities/vaultV2/forceWithdrawQuote.js +10 -5
  388. package/lib/esm/entities/vaultV2/inKindRedeemQuote.d.ts +2 -2
  389. package/lib/esm/entities/vaultV2/inKindRedeemQuote.js +1 -7
  390. package/lib/esm/entities/vaultV2/vaultV2.d.ts +21 -52
  391. package/lib/esm/entities/vaultV2/vaultV2.js +209 -133
  392. package/lib/esm/helpers/parse.d.ts +33 -0
  393. package/lib/esm/helpers/parse.js +61 -0
  394. package/lib/esm/helpers/parseMidnight.d.ts +48 -0
  395. package/lib/esm/helpers/parseMidnight.js +80 -0
  396. package/lib/esm/helpers/parseMidnightMaker.d.ts +44 -0
  397. package/lib/esm/helpers/parseMidnightMaker.js +147 -0
  398. package/lib/esm/helpers/validate.d.ts +3 -2
  399. package/lib/esm/helpers/validate.js +5 -1
  400. package/lib/esm/helpers/validateMidnightCancelAndMakePublication.d.ts +8 -0
  401. package/lib/esm/helpers/validateMidnightCancelAndMakePublication.js +2 -2
  402. package/lib/esm/helpers/validateMidnightPublication.d.ts +17 -1
  403. package/lib/esm/index.d.ts +1 -0
  404. package/lib/esm/transactionPlan/blue/refinance.js +18 -10
  405. package/lib/esm/transactionPlan/blue/repay.js +3 -2
  406. package/lib/esm/transactionPlan/blue/repayWithdrawCollateral.js +24 -5
  407. package/lib/esm/transactionPlan/blue/supplyCollateralBorrow.js +2 -2
  408. package/lib/esm/transactionPlan/blue/withdraw.d.ts +2 -2
  409. package/lib/esm/transactionPlan/blue/withdraw.js +3 -3
  410. package/lib/esm/transactionPlan/blue/withdrawCollateral.js +6 -2
  411. package/lib/esm/transactionPlan/validation.d.ts +1 -1
  412. package/lib/esm/transactionPlan/validation.js +3 -0
  413. package/lib/esm/transactionPlan/vaultv1/deposit.d.ts +2 -2
  414. package/lib/esm/transactionPlan/vaultv1/deposit.js +2 -2
  415. package/lib/esm/types/action.d.ts +13 -2
  416. package/lib/esm/types/error.d.ts +20 -2
  417. package/lib/esm/types/error.js +27 -0
  418. package/lib/esm/version.d.ts +1 -1
  419. package/lib/esm/version.js +1 -1
  420. package/package.json +3 -3
@@ -1,26 +1,34 @@
1
- import { MathLib, } from "@morpho-org/blue-sdk";
1
+ import { MarketParams, MathLib, } from "@morpho-org/blue-sdk";
2
2
  import { fetchAccrualPosition, fetchAccrualVaultV2, fetchMarket, fetchVaultV2BluePublicAllocatorData, } from "@morpho-org/blue-sdk-viem";
3
- import { getChainAddress, getChainAddresses, Time, } from "@morpho-org/morpho-ts";
3
+ import { deepFreeze, getChainAddress, getChainAddresses, Time, } from "@morpho-org/morpho-ts";
4
4
  import { erc20Abi, isAddressEqual, maxUint256 } from "viem";
5
5
  import { readContract } from "viem/actions";
6
6
  import { blueAbi, midnightBlueBuyCallbackAbi, midnightBlueBuyCallbackFactoryAbi, } from "../../abis.js";
7
- import { getBlueBundlesV1PenaltyAssets, getBlueBundlesV1PublicAllocations, getBlueBundlesV1ReferralFeeAssets, normalizeBlueBundlesV1CommonParams, selectBlueBundlesV1RequirementSignatures, validateBlueBundlesV1NativeFunding, } from "../../actions/blue/common.js";
8
- import { validateBlueRefinanceQuote, validateBlueRefinanceSource, } from "../../actions/blue/refinanceValidation.js";
9
- import { blueBorrow, blueRefinance, blueRepay, blueRepayWithdrawCollateral, blueSupply, blueSupplyCollateral, blueSupplyCollateralBorrow, blueWithdraw, blueWithdrawBuyCallback, blueWithdrawCollateral, getBlueAuthorizationRequirement, } from "../../actions/index.js";
10
- import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
7
+ import { getBlueBundlesV1ReferralFeeAssets, parseBlueAllocations, parseBlueBundlesV1Common, selectBlueBundlesV1RequirementSignatures, } from "../../actions/blue/common.js";
8
+ import { buildBlueRefinance, parseBlueRefinanceMarkets, } from "../../actions/blue/refinance.internal.js";
9
+ import { validateBlueRefinanceQuote } from "../../actions/blue/refinanceValidation.js";
10
+ import { buildBlueRepayWithdrawCollateral, parseBlueRepayCap, parseBlueRepayCoverage, parseBlueRepayMode, } from "../../actions/blue/repayWithdrawCollateral.internal.js";
11
+ import { buildBlueSupply, } from "../../actions/blue/supply.internal.js";
12
+ import { buildBlueSupplyCollateralBorrow, parseBlueSupplyCollateralBorrowAllocations, parseBlueSupplyCollateralBorrowMode, } from "../../actions/blue/supplyCollateralBorrow.internal.js";
13
+ import { buildBlueWithdraw, parseBlueWithdrawMode, parseBlueWithdrawPenalty, } from "../../actions/blue/withdraw.internal.js";
14
+ import { buildBlueWithdrawBuyCallback, } from "../../actions/blue/withdrawBuyCallback.internal.js";
15
+ import { getParsedBlueAuthorizationRequirement, parseBlueAuthorizationRequirement, } from "../../actions/requirements/blue/getBlueAuthorizationRequirement.js";
16
+ import { createChainCheck, } from "../../actions/requirements/chainCheck.js";
11
17
  import { DEFAULT_LLTV_BUFFER, validateAccrualPosition, validateChainId, validatePositionHealth, validatePositionHealthAfterWithdraw, validateWithdrawAmount, validateWithdrawShares, } from "../../helpers/index.js";
12
18
  import { resolveTransactionMetadata } from "../../helpers/metadata.js";
19
+ import { parseBlueMarket, parseNativeFunding, parseNonnegative, parseUint256, parseUint256Max, } from "../../helpers/parse.js";
13
20
  import { quoteBlueRepay } from "../../helpers/quoteBlueRepay.js";
14
- import { validateMarketParamsId } from "../../helpers/validate.js";
15
- import { BlueBuyCallbackOwnerMismatchError, BlueBuyCallbackUnauthorizedError, EmptyBlueSupplyPositionError, ExpiredDeadlineError, InputExceedsMaxError, InsufficientBlueLiquidityError, MarketIdMismatchError, MaxRepayAssetsBelowRepayAssetsError, MissingAccrualPositionError, MutuallyExclusiveRepayAmountsError, MutuallyExclusiveWithdrawAmountsError, NegativeInputError, NonPositiveInputError, NotBlueBuyCallbackError, ReallocationsRequireBorrowError, } from "../../types/index.js";
21
+ import { BlueBuyCallbackOwnerMismatchError, BlueBuyCallbackUnauthorizedError, EmptyBlueSupplyPositionError, ExpiredDeadlineError, InputExceedsMaxError, InsufficientBlueLiquidityError, MarketIdMismatchError, MissingAccrualPositionError, NonPositiveInputError, NotBlueBuyCallbackError, } from "../../types/index.js";
16
22
  import { assertRegistryTargetsHaveCode } from "../requirements/assertContractCode.js";
17
- import { getBundlesTokenRequirements } from "../requirements/index.js";
23
+ import { getParsedBundlesTokenRequirements, parseGetBundlesTokenRequirements, } from "../requirements/getBundlesTokenRequirements.js";
24
+ import { validateNativeRequirements } from "../requirements/validateNativeRequirements.js";
18
25
  import { VaultV2BlueReallocationData } from "../vaultV2BlueReallocationData.js";
19
26
  /** Binds a viem client to a Morpho Blue market's action builders. */
20
27
  export class MorphoBlue {
21
28
  client;
22
29
  marketParams;
23
30
  chainId;
31
+ parsedMarket;
24
32
  /**
25
33
  * Binds `client` to the market described by `marketParams` on `chainId`.
26
34
  *
@@ -34,7 +42,7 @@ export class MorphoBlue {
34
42
  this.client = client;
35
43
  this.marketParams = marketParams;
36
44
  this.chainId = chainId;
37
- validateMarketParamsId(marketParams);
45
+ this.parsedMarket = parseBlueMarket(marketParams);
38
46
  }
39
47
  validateDeadline(deadline, now = Time.timestamp()) {
40
48
  if (deadline <= now) {
@@ -42,13 +50,13 @@ export class MorphoBlue {
42
50
  }
43
51
  }
44
52
  validateWriteCommon(params, now) {
53
+ // Reject cross-chain inputs before continuing.
45
54
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
55
+ // Reject expiry before continuing this call.
46
56
  this.validateDeadline(params.deadline, now);
47
57
  // Resolve at handle creation so unsupported deployments fail before any RPC prerequisite work.
48
58
  getChainAddress(this.chainId, "bundles.blueBundlesV1");
49
- // Validate the referral inputs eagerly; the normalized result is intentionally discarded here
50
- // because the pure action re-normalizes it at encode time.
51
- normalizeBlueBundlesV1CommonParams({
59
+ return parseBlueBundlesV1Common({
52
60
  chainId: this.chainId,
53
61
  userAddress: params.userAddress,
54
62
  deadline: params.deadline,
@@ -59,10 +67,13 @@ export class MorphoBlue {
59
67
  /**
60
68
  * Asserts that every registry contract this flow's transaction targets or names as
61
69
  * spender/authorized operator holds code, with one `eth_getCode` per distinct address
62
- * before any other requirement read. Blue write flows probe `eth_chainId` only after a target
63
- * has no code and report a chain mismatch when the RPC serves another chain.
70
+ * before any other requirement read. Native-only funding validates the served chain
71
+ * concurrently; other flows probe it here only when a target has no code.
72
+ *
73
+ * @param chainCheck - Chain validation shared within this operation.
74
+ * @param nativeFundingOnly - Whether no token or authorization resolver checks the chain.
64
75
  */
65
- async assertWriteTargets() {
76
+ async assertWriteTargets(chainCheck, nativeFundingOnly = false) {
66
77
  const targets = [
67
78
  {
68
79
  role: "bundles.blueBundlesV1",
@@ -70,27 +81,28 @@ export class MorphoBlue {
70
81
  },
71
82
  { role: "blue", address: getChainAddress(this.chainId, "blue") },
72
83
  ];
73
- await assertRegistryTargetsHaveCode(this.client.viemClient, this.chainId, targets);
84
+ const assertTargets = () => assertRegistryTargetsHaveCode(this.client.viemClient, this.chainId, targets, chainCheck);
85
+ if (nativeFundingOnly) {
86
+ await validateNativeRequirements(this.client.viemClient, {
87
+ chainId: this.chainId,
88
+ chainCheck,
89
+ assertWriteTargets: assertTargets,
90
+ });
91
+ }
92
+ else {
93
+ await assertTargets();
94
+ }
74
95
  }
75
- getMaxLtv(marketParams = this.marketParams) {
96
+ getMaxLtv(marketParams = this.parsedMarket) {
76
97
  return MathLib.zeroFloorSub(marketParams.lltv, DEFAULT_LLTV_BUFFER);
77
98
  }
78
99
  getBlueBundlesV1QuoteTimestamp(lastUpdate, now = Time.timestamp()) {
79
100
  return MathLib.max(now, lastUpdate) + Time.s.from.h(2n);
80
101
  }
81
- quoteRepay({ positionData, repayAssets, repayShares, deadline, now, }) {
82
- return quoteBlueRepay({
83
- positionData,
84
- marketId: this.marketParams.id,
85
- repayAssets,
86
- repayShares,
87
- deadline,
88
- now,
89
- });
90
- }
91
- async getTokenRequirements(params) {
102
+ async getTokenRequirements(chainCheck, params) {
103
+ // Reject expiry before continuing this call.
92
104
  this.validateDeadline(params.deadline, params.now);
93
- return getBundlesTokenRequirements(this.client.viemClient, {
105
+ return getParsedBundlesTokenRequirements({ viemClient: this.client.viemClient, chainCheck }, parseGetBundlesTokenRequirements(this.client.viemClient, {
94
106
  token: params.token,
95
107
  spender: getChainAddress(this.chainId, "bundles.blueBundlesV1"),
96
108
  amount: params.amount,
@@ -101,11 +113,12 @@ export class MorphoBlue {
101
113
  supportDeployless: this.client.options.supportDeployless,
102
114
  useSimplePermit: params.useSimplePermit,
103
115
  now: params.now,
104
- });
116
+ }));
105
117
  }
106
- async getAuthorizationRequirements(params) {
118
+ async getAuthorizationRequirements(chainCheck, params) {
119
+ // Reject expiry before continuing this call.
107
120
  this.validateDeadline(params.deadline, params.now);
108
- const requirement = await getBlueAuthorizationRequirement({
121
+ const requirement = await getParsedBlueAuthorizationRequirement(parseBlueAuthorizationRequirement({
109
122
  viemClient: this.client.viemClient,
110
123
  chainId: this.chainId,
111
124
  userAddress: params.userAddress,
@@ -113,135 +126,165 @@ export class MorphoBlue {
113
126
  authorized: getChainAddress(this.chainId, "bundles.blueBundlesV1"),
114
127
  deadline: params.deadline,
115
128
  now: params.now,
116
- });
129
+ }), chainCheck);
117
130
  return requirement == null ? [] : [requirement];
118
131
  }
119
132
  async getMarketData(parameters) {
120
- await validateClientChainId(this.client.viemClient, this.chainId);
121
- return fetchMarket(this.marketParams.id, this.client.viemClient, {
133
+ // Confirm the RPC chain before contract reads.
134
+ await createChainCheck(this.client.viemClient, this.chainId)();
135
+ return fetchMarket(this.parsedMarket.id, this.client.viemClient, {
122
136
  ...parameters,
123
137
  deployless: this.client.options.supportDeployless,
124
138
  });
125
139
  }
126
140
  async getPositionData(userAddress, parameters) {
127
- await validateClientChainId(this.client.viemClient, this.chainId);
128
- return fetchAccrualPosition(userAddress, this.marketParams.id, this.client.viemClient, {
141
+ // Confirm the RPC chain before contract reads.
142
+ await createChainCheck(this.client.viemClient, this.chainId)();
143
+ return fetchAccrualPosition(userAddress, this.parsedMarket.id, this.client.viemClient, {
129
144
  ...parameters,
130
145
  deployless: this.client.options.supportDeployless,
131
146
  });
132
147
  }
133
148
  supply(params) {
134
- const suppliedNow = params.now;
135
- const metadata = resolveTransactionMetadata(this.client.options.metadata, suppliedNow);
136
- const { userAddress, assets, nativeAmount, deadline, referralFeePct, referralFeeRecipient, } = params;
137
- const createdAt = suppliedNow ?? Time.timestamp();
138
- this.validateWriteCommon(params, createdAt);
149
+ return this.supplyPrepared(this.parseSupplyParams(params));
150
+ }
151
+ parseSupplyParams(params) {
152
+ const { assets } = params;
153
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
154
+ const createdAt = params.now ?? Time.timestamp();
155
+ const normalized = this.validateWriteCommon(params, createdAt);
139
156
  if (assets <= 0n) {
140
157
  throw new NonPositiveInputError("assets", assets);
141
158
  }
142
- const nativeValue = validateBlueBundlesV1NativeFunding({
159
+ const nativeValue = parseNativeFunding({
143
160
  chainId: this.chainId,
144
- token: this.marketParams.loanToken,
161
+ token: this.parsedMarket.loanToken,
145
162
  fundedAmount: assets,
146
- nativeAmount,
163
+ nativeAmount: params.nativeAmount,
147
164
  });
148
- if (params.marketData != null) {
149
- if (params.marketData.id !== this.marketParams.id) {
150
- throw new MarketIdMismatchError(params.marketData.id, this.marketParams.id);
151
- }
165
+ if (params.marketData != null &&
166
+ params.marketData.id !== this.parsedMarket.id) {
167
+ throw new MarketIdMismatchError(params.marketData.id, this.parsedMarket.id);
152
168
  }
169
+ const input = {
170
+ ...normalized,
171
+ chainId: this.chainId,
172
+ userAddress: params.userAddress,
173
+ marketParams: this.parsedMarket,
174
+ now: params.now,
175
+ metadata,
176
+ assets: parseUint256Max("assets", assets),
177
+ value: nativeValue,
178
+ };
179
+ return input;
180
+ }
181
+ supplyPrepared(parsed) {
182
+ const { userAddress, assets, deadline, value: nativeValue, marketParams, } = parsed;
153
183
  return {
154
184
  getRequirements: (requirementsParams) => {
155
- const now = suppliedNow ?? Time.timestamp();
185
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
186
+ const now = parsed.now ?? Time.timestamp();
187
+ // Reject expiry before continuing this call.
156
188
  this.validateDeadline(deadline, now);
157
- return this.assertWriteTargets().then(() => {
158
- if (nativeValue > 0n) {
159
- return [];
160
- }
161
- return this.getTokenRequirements({
162
- token: this.marketParams.loanToken,
163
- amount: assets,
164
- userAddress,
165
- deadline,
166
- now,
167
- useSimplePermit: requirementsParams?.useSimplePermit,
168
- });
169
- });
189
+ if (nativeValue > 0n) {
190
+ // Neither token requirements nor authorization will validate the chain.
191
+ return this.assertWriteTargets(chainCheck, true).then(() => []);
192
+ }
193
+ return this.assertWriteTargets(chainCheck).then(() => this.getTokenRequirements(chainCheck, {
194
+ token: marketParams.loanToken,
195
+ amount: assets,
196
+ userAddress,
197
+ deadline,
198
+ now,
199
+ useSimplePermit: requirementsParams?.useSimplePermit,
200
+ }));
170
201
  },
171
202
  buildTx: (signatures) => {
172
203
  const { token } = selectBlueBundlesV1RequirementSignatures(signatures, {
173
204
  token: nativeValue === 0n,
174
205
  });
175
- return blueSupply({
176
- market: { chainId: this.chainId, marketParams: this.marketParams },
177
- args: {
178
- userAddress,
179
- assets,
180
- nativeAmount: nativeValue > 0n ? nativeValue : undefined,
181
- deadline,
182
- referralFeePct,
183
- referralFeeRecipient,
184
- requirementSignature: token,
185
- },
186
- metadata,
187
- });
206
+ return buildBlueSupply(parsed, { requirementSignature: token });
188
207
  },
189
208
  };
190
209
  }
191
210
  /** {@inheritDoc BlueActions.withdraw} */
192
211
  withdraw(params) {
193
- const suppliedNow = params.now;
194
- const metadata = resolveTransactionMetadata(this.client.options.metadata, suppliedNow);
195
- const { userAddress, positionData, deadline, referralFeePct, referralFeeRecipient, } = params;
196
- const createdAt = suppliedNow ?? Time.timestamp();
197
- this.validateWriteCommon(params, createdAt);
212
+ return this.withdrawPrepared(this.parseWithdrawParams(params));
213
+ }
214
+ parseWithdrawParams(params) {
215
+ const { userAddress, positionData } = params;
216
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
217
+ const createdAt = params.now ?? Time.timestamp();
218
+ const normalized = this.validateWriteCommon(params, createdAt);
198
219
  const assets = ("assets" in params ? params.assets : undefined) ?? 0n;
199
220
  const shares = ("shares" in params ? params.shares : undefined) ?? 0n;
200
- if (assets < 0n) {
201
- throw new NegativeInputError("assets", assets);
202
- }
203
- if (shares < 0n) {
204
- throw new NegativeInputError("shares", shares);
205
- }
206
- if (assets > 0n && shares > 0n) {
207
- throw new MutuallyExclusiveWithdrawAmountsError(this.marketParams.id);
208
- }
209
- if (assets === 0n && shares === 0n) {
210
- throw new NonPositiveInputError("assets or shares", 0n);
211
- }
221
+ const lowerAssets = parseNonnegative("assets", assets);
222
+ const lowerShares = parseNonnegative("shares", shares);
223
+ const mode = parseBlueWithdrawMode(this.parsedMarket, {
224
+ withdrawAssets: assets,
225
+ withdrawShares: shares,
226
+ field: "assets or shares",
227
+ });
212
228
  if (positionData == null) {
213
- throw new MissingAccrualPositionError(this.marketParams.id);
229
+ throw new MissingAccrualPositionError(this.parsedMarket.id);
214
230
  }
231
+ // Reject a snapshot for another user or market.
215
232
  validateAccrualPosition({
216
233
  positionData,
217
- expectedMarketId: this.marketParams.id,
234
+ expectedMarketId: this.parsedMarket.id,
218
235
  expectedUser: userAddress,
219
236
  });
220
- const validateWithdrawal = shares > 0n ? validateWithdrawShares : validateWithdrawAmount;
221
- validateWithdrawal({
222
- positionData,
223
- withdrawShares: shares,
224
- withdrawAssets: assets,
225
- marketId: this.marketParams.id,
226
- });
227
- const reallocations = [...(params.reallocations ?? [])];
228
- // Validate the exact PublicAllocations mapping before requirement reads.
229
- const publicAllocations = getBlueBundlesV1PublicAllocations(reallocations, this.marketParams);
230
- const reallocationPenaltyAssets = getBlueBundlesV1PenaltyAssets(publicAllocations);
237
+ if (shares > 0n) {
238
+ // Reject a withdrawal larger than the supplied share balance.
239
+ validateWithdrawShares({
240
+ positionData,
241
+ withdrawShares: shares,
242
+ marketId: this.parsedMarket.id,
243
+ });
244
+ }
245
+ else {
246
+ // Reject a withdrawal larger than the supplied asset balance.
247
+ validateWithdrawAmount({
248
+ positionData,
249
+ withdrawAssets: assets,
250
+ marketId: this.parsedMarket.id,
251
+ });
252
+ }
253
+ const allocations = parseBlueWithdrawPenalty(parseBlueAllocations([...(params.reallocations ?? [])], this.parsedMarket), mode);
254
+ const reallocationPenaltyAssets = allocations.penaltyAssets;
231
255
  const expectedWithdrawAssets = assets > 0n ? assets : positionData.market.toSupplyAssets(shares, "Down");
232
- if (reallocationPenaltyAssets > expectedWithdrawAssets) {
256
+ if (shares > 0n && reallocationPenaltyAssets > expectedWithdrawAssets) {
233
257
  throw new InputExceedsMaxError({
234
258
  field: "reallocationPenaltyAssets",
235
259
  value: reallocationPenaltyAssets,
236
260
  max: expectedWithdrawAssets,
237
261
  });
238
262
  }
263
+ const input = {
264
+ ...normalized,
265
+ chainId: this.chainId,
266
+ userAddress,
267
+ marketParams: this.parsedMarket,
268
+ now: params.now,
269
+ metadata,
270
+ publicAllocations: allocations.publicAllocations,
271
+ reallocationPenaltyAssets,
272
+ withdrawAssets: parseUint256Max("withdrawAssets", lowerAssets),
273
+ withdrawShares: parseUint256Max("withdrawShares", lowerShares),
274
+ };
275
+ return input;
276
+ }
277
+ withdrawPrepared(parsed) {
278
+ const { userAddress, deadline } = parsed;
239
279
  return {
240
280
  getRequirements: async () => {
241
- const now = suppliedNow ?? Time.timestamp();
281
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
282
+ const now = parsed.now ?? Time.timestamp();
283
+ // Reject expiry before continuing this call.
242
284
  this.validateDeadline(deadline, now);
243
- await this.assertWriteTargets();
244
- return this.getAuthorizationRequirements({
285
+ // Reject missing write targets before resolving requirements.
286
+ await this.assertWriteTargets(chainCheck);
287
+ return this.getAuthorizationRequirements(chainCheck, {
245
288
  userAddress,
246
289
  deadline,
247
290
  now,
@@ -251,40 +294,34 @@ export class MorphoBlue {
251
294
  const { authorization } = selectBlueBundlesV1RequirementSignatures(signatures, {
252
295
  authorization: true,
253
296
  });
254
- return blueWithdraw({
255
- market: { chainId: this.chainId, marketParams: this.marketParams },
256
- args: {
257
- userAddress,
258
- withdrawAssets: assets,
259
- withdrawShares: shares,
260
- reallocations,
261
- deadline,
262
- referralFeePct,
263
- referralFeeRecipient,
264
- authorizationSignature: authorization,
265
- },
266
- metadata,
297
+ return buildBlueWithdraw(parsed, {
298
+ authorizationSignature: authorization,
267
299
  });
268
300
  },
269
301
  };
270
302
  }
271
303
  /** {@inheritDoc BlueActions.withdrawBuyCallback} */
272
304
  withdrawBuyCallback(params) {
305
+ return this.withdrawBuyCallbackPrepared(this.parseWithdrawBuyCallbackParams(params));
306
+ }
307
+ parseWithdrawBuyCallbackParams(params) {
273
308
  const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
274
309
  const { userAddress, callbackAddress, positionData } = params;
310
+ // Reject cross-chain inputs before continuing.
275
311
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
276
312
  if (positionData == null) {
277
- throw new MissingAccrualPositionError(this.marketParams.id);
313
+ throw new MissingAccrualPositionError(this.parsedMarket.id);
278
314
  }
315
+ // Reject a snapshot for another user or market.
279
316
  validateAccrualPosition({
280
317
  positionData,
281
- expectedMarketId: this.marketParams.id,
318
+ expectedMarketId: this.parsedMarket.id,
282
319
  expectedUser: callbackAddress,
283
320
  });
284
321
  const shares = positionData.supplyShares;
285
322
  if (shares === 0n) {
286
323
  throw new EmptyBlueSupplyPositionError({
287
- market: this.marketParams.id,
324
+ market: this.parsedMarket.id,
288
325
  user: callbackAddress,
289
326
  });
290
327
  }
@@ -292,26 +329,41 @@ export class MorphoBlue {
292
329
  const liquidity = positionData.market.liquidity;
293
330
  if (assets > liquidity) {
294
331
  throw new InsufficientBlueLiquidityError({
295
- market: this.marketParams.id,
332
+ market: this.parsedMarket.id,
296
333
  assets,
297
334
  liquidity,
298
335
  });
299
336
  }
300
337
  const blue = getChainAddress(this.chainId, "blue");
301
338
  const factory = getChainAddress(this.chainId, "midnightBlueBuyCallbackFactory");
302
- const tx = blueWithdrawBuyCallback({
303
- market: { chainId: this.chainId, marketParams: this.marketParams },
304
- args: { callbackAddress, userAddress, shares },
339
+ const boundedShares = parseUint256("shares", shares);
340
+ if (boundedShares === 0n) {
341
+ throw new NonPositiveInputError("shares", boundedShares);
342
+ }
343
+ return {
344
+ marketParams: this.parsedMarket,
345
+ callbackAddress,
346
+ userAddress,
347
+ shares: boundedShares,
305
348
  metadata,
306
- });
349
+ to: blue,
350
+ factory,
351
+ };
352
+ }
353
+ withdrawBuyCallbackPrepared(parsed) {
354
+ const { userAddress, callbackAddress, factory, to: blue } = parsed;
355
+ const tx = buildBlueWithdrawBuyCallback(parsed);
307
356
  return {
308
357
  getRequirements: async () => {
358
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
309
359
  const viemClient = this.client.viemClient;
310
- await validateClientChainId(viemClient, this.chainId);
360
+ // Confirm the RPC chain before prerequisite reads.
361
+ await chainCheck();
362
+ // Reject missing registry contracts before prerequisite reads.
311
363
  await assertRegistryTargetsHaveCode(viemClient, this.chainId, [
312
364
  { role: "blue", address: blue },
313
365
  { role: "midnightBlueBuyCallbackFactory", address: factory },
314
- ]);
366
+ ], chainCheck);
315
367
  // Check the factory first: OWNER() on an arbitrary address can revert or lie.
316
368
  const isBlueBuyCallback = await readContract(viemClient, {
317
369
  address: factory,
@@ -355,183 +407,173 @@ export class MorphoBlue {
355
407
  }
356
408
  /** {@inheritDoc BlueActions.supplyCollateral} */
357
409
  supplyCollateral(params) {
358
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
410
+ return this.supplyCollateralPrepared(this.parseSupplyCollateralParams(params));
411
+ }
412
+ parseSupplyCollateralParams(params) {
359
413
  const { userAddress, collateralAssets, nativeAmount, deadline, referralFeePct, referralFeeRecipient, } = params;
360
- const combinedAction = this.supplyCollateralBorrow({
361
- now: params.now,
362
- userAddress,
363
- collateralAssets,
414
+ return {
415
+ ...this.parseSupplyCollateralBorrowParams({
416
+ now: params.now,
417
+ userAddress,
418
+ collateralAssets,
419
+ borrowAssets: 0n,
420
+ nativeAmount,
421
+ deadline,
422
+ referralFeePct,
423
+ referralFeeRecipient,
424
+ }),
364
425
  borrowAssets: 0n,
365
- nativeAmount,
366
- deadline,
367
- referralFeePct,
368
- referralFeeRecipient,
369
- });
426
+ };
427
+ }
428
+ supplyCollateralPrepared(parsed) {
429
+ const combinedAction = this.supplyCollateralBorrowPrepared(parsed);
370
430
  return {
371
431
  getRequirements: combinedAction.getRequirements,
372
432
  buildTx: (signatures) => {
373
- const { token } = selectBlueBundlesV1RequirementSignatures(signatures, {
374
- token: (nativeAmount ?? 0n) === 0n,
375
- });
376
- return blueSupplyCollateral({
377
- market: { chainId: this.chainId, marketParams: this.marketParams },
378
- args: {
379
- userAddress,
380
- collateralAssets,
381
- nativeAmount,
382
- deadline,
383
- referralFeePct,
384
- referralFeeRecipient,
385
- requirementSignature: token,
433
+ const transaction = combinedAction.buildTx(signatures);
434
+ return deepFreeze({
435
+ ...transaction,
436
+ action: {
437
+ ...transaction.action,
438
+ type: "blueSupplyCollateral",
386
439
  },
387
- metadata,
388
440
  });
389
441
  },
390
442
  };
391
443
  }
392
444
  /** {@inheritDoc BlueActions.borrow} */
393
445
  borrow(params) {
394
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
446
+ return this.borrowPrepared(this.parseBorrowParams(params));
447
+ }
448
+ parseBorrowParams(params) {
395
449
  const { userAddress, borrowAssets, positionData, reallocations, deadline, referralFeePct, referralFeeRecipient, } = params;
396
450
  const normalizedReallocations = [...(reallocations ?? [])];
397
- const combinedAction = this.supplyCollateralBorrow({
398
- now: params.now,
399
- userAddress,
451
+ return {
452
+ ...this.parseSupplyCollateralBorrowParams({
453
+ now: params.now,
454
+ userAddress,
455
+ collateralAssets: 0n,
456
+ borrowAssets,
457
+ positionData,
458
+ reallocations: normalizedReallocations,
459
+ deadline,
460
+ referralFeePct,
461
+ referralFeeRecipient,
462
+ }),
400
463
  collateralAssets: 0n,
401
- borrowAssets,
402
- positionData,
403
- reallocations: normalizedReallocations,
404
- deadline,
405
- referralFeePct,
406
- referralFeeRecipient,
407
- });
464
+ };
465
+ }
466
+ borrowPrepared(parsed) {
467
+ const combinedAction = this.supplyCollateralBorrowPrepared(parsed);
408
468
  return {
409
469
  getRequirements: () => combinedAction.getRequirements(),
410
470
  buildTx: (signatures) => {
411
- const { authorization } = selectBlueBundlesV1RequirementSignatures(signatures, { authorization: true });
412
- return blueBorrow({
413
- market: { chainId: this.chainId, marketParams: this.marketParams },
414
- args: {
415
- userAddress,
416
- borrowAssets,
417
- maxLtv: this.getMaxLtv(),
418
- reallocations: normalizedReallocations,
419
- deadline,
420
- referralFeePct,
421
- referralFeeRecipient,
422
- authorizationSignature: authorization,
423
- },
424
- metadata,
471
+ const transaction = combinedAction.buildTx(signatures);
472
+ return deepFreeze({
473
+ ...transaction,
474
+ action: { ...transaction.action, type: "blueBorrow" },
425
475
  });
426
476
  },
427
477
  };
428
478
  }
429
479
  /** {@inheritDoc BlueActions.repay} */
430
480
  repay(params) {
431
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
432
- const combinedAction = this.repayWithdrawCollateral({
433
- ...params,
481
+ return this.repayPrepared(this.parseRepayParams(params));
482
+ }
483
+ parseRepayParams(params) {
484
+ return {
485
+ ...this.parseRepayWithdrawCollateralParams({
486
+ now: params.now,
487
+ ...params,
488
+ collateralAssets: 0n,
489
+ }),
434
490
  collateralAssets: 0n,
435
- });
491
+ };
492
+ }
493
+ repayPrepared(parsed) {
494
+ const combinedAction = this.repayWithdrawCollateralPrepared(parsed);
436
495
  return {
437
496
  getRequirements: combinedAction.getRequirements,
438
497
  buildTx: (signatures) => {
439
- const combinedTransaction = combinedAction.buildTx(signatures);
440
- const { token } = selectBlueBundlesV1RequirementSignatures(signatures, {
441
- token: combinedTransaction.value === 0n,
442
- });
443
- const { repayAssets, repayShares, maxRepayAssets, nativeAmount, referralFeePct, referralFeeRecipient, deadline, } = combinedTransaction.action.args;
444
- return blueRepay({
445
- market: { chainId: this.chainId, marketParams: this.marketParams },
446
- args: {
447
- userAddress: params.userAddress,
448
- repayAssets,
449
- repayShares,
450
- maxRepayAssets,
451
- nativeAmount,
452
- deadline,
453
- referralFeePct,
454
- referralFeeRecipient,
455
- requirementSignature: token,
456
- },
457
- metadata,
498
+ const transaction = combinedAction.buildTx(signatures);
499
+ return deepFreeze({
500
+ ...transaction,
501
+ action: { ...transaction.action, type: "blueRepay" },
458
502
  });
459
503
  },
460
504
  };
461
505
  }
462
506
  /** {@inheritDoc BlueActions.withdrawCollateral} */
463
507
  withdrawCollateral(params) {
464
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
508
+ return this.withdrawCollateralPrepared(this.parseWithdrawCollateralParams(params));
509
+ }
510
+ parseWithdrawCollateralParams(params) {
465
511
  const { userAddress, positionData, collateralAssets, deadline, referralFeePct, referralFeeRecipient, } = params;
466
- const combinedAction = this.repayWithdrawCollateral({
467
- now: params.now,
468
- userAddress,
469
- positionData,
512
+ return {
513
+ ...this.parseRepayWithdrawCollateralParams({
514
+ now: params.now,
515
+ userAddress,
516
+ positionData,
517
+ repayAssets: 0n,
518
+ collateralAssets,
519
+ deadline,
520
+ referralFeePct,
521
+ referralFeeRecipient,
522
+ }),
470
523
  repayAssets: 0n,
471
- collateralAssets,
472
- deadline,
473
- referralFeePct,
474
- referralFeeRecipient,
475
- });
524
+ repayShares: 0n,
525
+ maxRepayAssets: 0n,
526
+ hasRepay: false,
527
+ };
528
+ }
529
+ withdrawCollateralPrepared(parsed) {
530
+ const combinedAction = this.repayWithdrawCollateralPrepared(parsed);
476
531
  return {
477
532
  getRequirements: () => combinedAction.getRequirements(),
478
533
  buildTx: (signatures) => {
479
- const combinedTransaction = combinedAction.buildTx(signatures);
480
- const { authorization } = selectBlueBundlesV1RequirementSignatures(signatures, { authorization: true });
481
- const combinedArgs = combinedTransaction.action.args;
482
- return blueWithdrawCollateral({
483
- market: { chainId: this.chainId, marketParams: this.marketParams },
484
- args: {
485
- userAddress,
486
- collateralAssets: combinedArgs.collateralAssets,
487
- maxLtv: combinedArgs.maxLtv,
488
- deadline: combinedArgs.deadline,
489
- referralFeePct: combinedArgs.referralFeePct,
490
- referralFeeRecipient: combinedArgs.referralFeeRecipient,
491
- authorizationSignature: authorization,
534
+ const transaction = combinedAction.buildTx(signatures);
535
+ return deepFreeze({
536
+ ...transaction,
537
+ action: {
538
+ ...transaction.action,
539
+ type: "blueWithdrawCollateral",
492
540
  },
493
- metadata,
494
541
  });
495
542
  },
496
543
  };
497
544
  }
498
545
  /** {@inheritDoc BlueActions.repayWithdrawCollateral} */
499
546
  repayWithdrawCollateral(params) {
500
- const suppliedNow = params.now;
501
- const metadata = resolveTransactionMetadata(this.client.options.metadata, suppliedNow);
502
- const { userAddress, positionData, collateralAssets, nativeAmount, deadline, referralFeeRecipient, } = params;
503
- const createdAt = suppliedNow ?? Time.timestamp();
504
- this.validateWriteCommon(params, createdAt);
505
- // `validateWriteCommon` returns void, so default an omitted `referralFeePct` to `0n`
506
- // here, matching the pure action's normalization.
507
- const referralFeePct = params.referralFeePct ?? 0n;
547
+ return this.repayWithdrawCollateralPrepared(this.parseRepayWithdrawCollateralParams(params));
548
+ }
549
+ parseRepayWithdrawCollateralParams(params) {
550
+ const { userAddress, positionData, collateralAssets, nativeAmount, deadline, } = params;
551
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
552
+ const createdAt = params.now ?? Time.timestamp();
553
+ const normalized = this.validateWriteCommon(params, createdAt);
508
554
  const repayAssets = params.repayAssets ?? 0n;
509
555
  const repayShares = params.repayShares ?? 0n;
510
- if (repayAssets < 0n) {
511
- throw new NegativeInputError("repayAssets", repayAssets);
512
- }
513
- if (repayShares < 0n) {
514
- throw new NegativeInputError("repayShares", repayShares);
515
- }
516
- if (collateralAssets < 0n) {
517
- throw new NegativeInputError("collateralAssets", collateralAssets);
518
- }
519
- if (repayAssets > 0n && repayShares > 0n) {
520
- throw new MutuallyExclusiveRepayAmountsError(this.marketParams.id);
521
- }
556
+ const lowerRepayAssets = parseNonnegative("repayAssets", repayAssets);
557
+ const lowerRepayShares = parseNonnegative("repayShares", repayShares);
558
+ const lowerCollateralAssets = parseNonnegative("collateralAssets", collateralAssets);
559
+ const mode = parseBlueRepayMode(this.parsedMarket, {
560
+ repayAssets,
561
+ repayShares,
562
+ collateralAssets,
563
+ });
564
+ const referralFeePct = normalized.referralFeePct;
522
565
  const hasRepay = repayAssets > 0n || repayShares > 0n;
523
- if (!hasRepay && collateralAssets === 0n) {
524
- throw new NonPositiveInputError("repayAssets, repayShares, or collateralAssets", 0n);
525
- }
526
566
  if (positionData == null) {
527
- throw new MissingAccrualPositionError(this.marketParams.id);
567
+ throw new MissingAccrualPositionError(this.parsedMarket.id);
528
568
  }
569
+ // Reject a snapshot for another user or market.
529
570
  validateAccrualPosition({
530
571
  positionData,
531
- expectedMarketId: this.marketParams.id,
572
+ expectedMarketId: this.parsedMarket.id,
532
573
  expectedUser: userAddress,
533
574
  });
534
- const { simulatedRepayShares, accruedPosition, expectedRepayAssets } = this.quoteRepay({
575
+ const { simulatedRepayShares, accruedPosition, expectedRepayAssets } = quoteBlueRepay({
576
+ marketId: this.parsedMarket.id,
535
577
  positionData,
536
578
  repayAssets,
537
579
  repayShares,
@@ -540,9 +582,9 @@ export class MorphoBlue {
540
582
  });
541
583
  const referralFeeAssets = getBlueBundlesV1ReferralFeeAssets(expectedRepayAssets, referralFeePct);
542
584
  const maxRepayAssets = expectedRepayAssets + referralFeeAssets;
543
- const nativeValue = validateBlueBundlesV1NativeFunding({
585
+ const nativeValue = parseNativeFunding({
544
586
  chainId: this.chainId,
545
- token: this.marketParams.loanToken,
587
+ token: this.parsedMarket.loanToken,
546
588
  fundedAmount: maxRepayAssets,
547
589
  nativeAmount,
548
590
  });
@@ -550,22 +592,52 @@ export class MorphoBlue {
550
592
  const postRepayPosition = hasRepay
551
593
  ? accruedPosition.repay(repayAssets, simulatedRepayShares).position
552
594
  : accruedPosition;
595
+ // Reject collateral withdrawal that would leave unsafe debt.
553
596
  validatePositionHealthAfterWithdraw({
554
597
  positionData: postRepayPosition,
555
598
  withdrawAmount: collateralAssets,
556
- lltv: this.marketParams.lltv,
557
- marketId: this.marketParams.id,
599
+ lltv: this.parsedMarket.lltv,
600
+ marketId: this.parsedMarket.id,
558
601
  });
559
602
  }
603
+ const legs = {
604
+ ...normalized,
605
+ chainId: this.chainId,
606
+ userAddress,
607
+ marketParams: this.parsedMarket,
608
+ now: params.now,
609
+ metadata,
610
+ repayAssets: parseUint256Max("repayAssets", lowerRepayAssets),
611
+ repayShares: parseUint256Max("repayShares", lowerRepayShares),
612
+ collateralAssets: parseUint256Max("collateralAssets", lowerCollateralAssets),
613
+ maxLtv: parseUint256("maxLtv", collateralAssets > 0n ? this.getMaxLtv() : maxUint256),
614
+ hasRepay,
615
+ minimumRepayAssets: repayAssets +
616
+ getBlueBundlesV1ReferralFeeAssets(repayAssets, referralFeePct),
617
+ };
618
+ const cap = parseBlueRepayCap(mode, parseUint256("maxRepayAssets", maxRepayAssets));
619
+ const coveredCap = parseBlueRepayCoverage(legs, cap);
620
+ const input = {
621
+ ...legs,
622
+ maxRepayAssets: coveredCap,
623
+ value: nativeValue,
624
+ };
625
+ return input;
626
+ }
627
+ repayWithdrawCollateralPrepared(parsed) {
628
+ const { userAddress, collateralAssets, deadline, hasRepay, maxRepayAssets, value: nativeValue, marketParams, } = parsed;
560
629
  return {
561
630
  getRequirements: async (requirementsParams) => {
562
- const now = suppliedNow ?? Time.timestamp();
631
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
632
+ const now = parsed.now ?? Time.timestamp();
633
+ // Reject expiry before continuing this call.
563
634
  this.validateDeadline(deadline, now);
564
- await this.assertWriteTargets();
635
+ const nativeOnly = nativeValue > 0n && collateralAssets === 0n;
636
+ await this.assertWriteTargets(chainCheck, nativeOnly);
565
637
  const [tokenRequirements, authorizationRequirements] = await Promise.all([
566
638
  hasRepay && nativeValue === 0n
567
- ? this.getTokenRequirements({
568
- token: this.marketParams.loanToken,
639
+ ? this.getTokenRequirements(chainCheck, {
640
+ token: marketParams.loanToken,
569
641
  amount: maxRepayAssets,
570
642
  userAddress,
571
643
  deadline,
@@ -574,7 +646,7 @@ export class MorphoBlue {
574
646
  })
575
647
  : Promise.resolve([]),
576
648
  collateralAssets > 0n
577
- ? this.getAuthorizationRequirements({
649
+ ? this.getAuthorizationRequirements(chainCheck, {
578
650
  userAddress,
579
651
  deadline,
580
652
  now,
@@ -588,95 +660,89 @@ export class MorphoBlue {
588
660
  token: hasRepay && nativeValue === 0n,
589
661
  authorization: collateralAssets > 0n,
590
662
  });
591
- const selectedMaxRepayAssets = repayShares > 0n && token != null
592
- ? token.args.amount
593
- : maxRepayAssets;
594
- if (selectedMaxRepayAssets < maxRepayAssets) {
595
- throw new MaxRepayAssetsBelowRepayAssetsError(selectedMaxRepayAssets, maxRepayAssets);
596
- }
597
- return blueRepayWithdrawCollateral({
598
- market: { chainId: this.chainId, marketParams: this.marketParams },
599
- args: {
600
- userAddress,
601
- repayAssets,
602
- repayShares,
603
- maxRepayAssets: selectedMaxRepayAssets,
604
- collateralAssets,
605
- maxLtv: collateralAssets > 0n ? this.getMaxLtv() : maxUint256,
606
- nativeAmount: nativeValue > 0n ? nativeValue : undefined,
607
- deadline,
608
- referralFeePct,
609
- referralFeeRecipient,
610
- requirementSignature: token,
611
- authorizationSignature: authorization,
612
- },
613
- metadata,
663
+ return buildBlueRepayWithdrawCollateral(parsed, {
664
+ requirementSignature: token,
665
+ authorizationSignature: authorization,
666
+ signatureFunding: true,
614
667
  });
615
668
  },
616
669
  };
617
670
  }
618
671
  /** {@inheritDoc BlueActions.supplyCollateralBorrow} */
619
672
  supplyCollateralBorrow(params) {
620
- const suppliedNow = params.now;
621
- const metadata = resolveTransactionMetadata(this.client.options.metadata, suppliedNow);
622
- const { userAddress, collateralAssets, borrowAssets, positionData, nativeAmount, deadline, referralFeePct, referralFeeRecipient, } = params;
623
- const createdAt = suppliedNow ?? Time.timestamp();
624
- this.validateWriteCommon(params, createdAt);
625
- if (collateralAssets < 0n) {
626
- throw new NegativeInputError("collateralAssets", collateralAssets);
627
- }
628
- if (borrowAssets < 0n) {
629
- throw new NegativeInputError("borrowAssets", borrowAssets);
630
- }
673
+ return this.supplyCollateralBorrowPrepared(this.parseSupplyCollateralBorrowParams(params));
674
+ }
675
+ parseSupplyCollateralBorrowParams(params) {
676
+ const { userAddress, collateralAssets, borrowAssets, positionData } = params;
677
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
678
+ const createdAt = params.now ?? Time.timestamp();
679
+ const normalized = this.validateWriteCommon(params, createdAt);
680
+ const lowerCollateralAssets = parseNonnegative("collateralAssets", collateralAssets);
681
+ const lowerBorrowAssets = parseNonnegative("borrowAssets", borrowAssets);
631
682
  if (collateralAssets === 0n && borrowAssets === 0n) {
632
683
  throw new NonPositiveInputError("collateralAssets or borrowAssets", 0n);
633
684
  }
634
- const reallocations = [...(params.reallocations ?? [])];
635
- if (borrowAssets === 0n && reallocations.length > 0) {
636
- throw new ReallocationsRequireBorrowError();
637
- }
638
- // Validate the exact PublicAllocations mapping before requirement reads.
639
- const publicAllocations = getBlueBundlesV1PublicAllocations(reallocations, this.marketParams);
640
- const reallocationPenaltyAssets = getBlueBundlesV1PenaltyAssets(publicAllocations);
641
- if (reallocationPenaltyAssets > borrowAssets) {
642
- throw new InputExceedsMaxError({
643
- field: "reallocationPenaltyAssets",
644
- value: reallocationPenaltyAssets,
645
- max: borrowAssets,
646
- });
647
- }
685
+ const mode = parseBlueSupplyCollateralBorrowMode({
686
+ collateralAssets,
687
+ borrowAssets,
688
+ reallocations: [...(params.reallocations ?? [])],
689
+ });
690
+ const allocations = parseBlueSupplyCollateralBorrowAllocations(this.parsedMarket, mode);
648
691
  if (borrowAssets > 0n) {
649
692
  if (positionData == null) {
650
- throw new MissingAccrualPositionError(this.marketParams.id);
693
+ throw new MissingAccrualPositionError(this.parsedMarket.id);
651
694
  }
695
+ // Reject a snapshot for another user or market.
652
696
  validateAccrualPosition({
653
697
  positionData,
654
- expectedMarketId: this.marketParams.id,
698
+ expectedMarketId: this.parsedMarket.id,
655
699
  expectedUser: userAddress,
656
700
  });
701
+ // Reject resulting debt above the buffered LLTV.
657
702
  validatePositionHealth({
658
703
  positionData: positionData.accrueInterest(this.getBlueBundlesV1QuoteTimestamp(positionData.market.lastUpdate, createdAt)),
659
704
  additionalCollateral: collateralAssets,
660
705
  borrowAmount: borrowAssets,
661
- marketId: this.marketParams.id,
662
- lltv: this.marketParams.lltv,
706
+ marketId: this.parsedMarket.id,
707
+ lltv: this.parsedMarket.lltv,
663
708
  });
664
709
  }
665
- const nativeValue = validateBlueBundlesV1NativeFunding({
710
+ const nativeValue = parseNativeFunding({
666
711
  chainId: this.chainId,
667
- token: this.marketParams.collateralToken,
712
+ token: this.parsedMarket.collateralToken,
668
713
  fundedAmount: collateralAssets,
669
- nativeAmount,
714
+ nativeAmount: params.nativeAmount,
670
715
  });
716
+ const input = {
717
+ ...normalized,
718
+ chainId: this.chainId,
719
+ userAddress,
720
+ marketParams: this.parsedMarket,
721
+ now: params.now,
722
+ metadata,
723
+ publicAllocations: allocations.publicAllocations,
724
+ reallocationPenaltyAssets: allocations.penaltyAssets,
725
+ value: nativeValue,
726
+ collateralAssets: parseUint256Max("collateralAssets", lowerCollateralAssets),
727
+ borrowAssets: parseUint256Max("borrowAssets", lowerBorrowAssets),
728
+ maxLtv: parseUint256("maxLtv", borrowAssets > 0n ? this.getMaxLtv() : maxUint256),
729
+ };
730
+ return input;
731
+ }
732
+ supplyCollateralBorrowPrepared(parsed) {
733
+ const { userAddress, collateralAssets, borrowAssets, deadline, value: nativeValue, marketParams, } = parsed;
671
734
  return {
672
735
  getRequirements: async (requirementsParams) => {
673
- const now = suppliedNow ?? Time.timestamp();
736
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
737
+ const now = parsed.now ?? Time.timestamp();
738
+ // Reject expiry before continuing this call.
674
739
  this.validateDeadline(deadline, now);
675
- await this.assertWriteTargets();
740
+ // Native-only funding has no token or authorization chain check.
741
+ await this.assertWriteTargets(chainCheck, nativeValue > 0n && borrowAssets === 0n);
676
742
  const [tokenRequirements, authorizationRequirements] = await Promise.all([
677
743
  collateralAssets > 0n && nativeValue === 0n
678
- ? this.getTokenRequirements({
679
- token: this.marketParams.collateralToken,
744
+ ? this.getTokenRequirements(chainCheck, {
745
+ token: marketParams.collateralToken,
680
746
  amount: collateralAssets,
681
747
  userAddress,
682
748
  deadline,
@@ -685,7 +751,7 @@ export class MorphoBlue {
685
751
  })
686
752
  : Promise.resolve([]),
687
753
  borrowAssets > 0n
688
- ? this.getAuthorizationRequirements({
754
+ ? this.getAuthorizationRequirements(chainCheck, {
689
755
  userAddress,
690
756
  deadline,
691
757
  now,
@@ -699,75 +765,82 @@ export class MorphoBlue {
699
765
  token: collateralAssets > 0n && nativeValue === 0n,
700
766
  authorization: borrowAssets > 0n,
701
767
  });
702
- return blueSupplyCollateralBorrow({
703
- market: { chainId: this.chainId, marketParams: this.marketParams },
704
- args: {
705
- userAddress,
706
- collateralAssets,
707
- borrowAssets,
708
- maxLtv: borrowAssets > 0n ? this.getMaxLtv() : maxUint256,
709
- nativeAmount: nativeValue > 0n ? nativeValue : undefined,
710
- reallocations,
711
- deadline,
712
- referralFeePct,
713
- referralFeeRecipient,
714
- requirementSignature: token,
715
- authorizationSignature: authorization,
716
- },
717
- metadata,
768
+ return buildBlueSupplyCollateralBorrow(parsed, {
769
+ requirementSignature: token,
770
+ authorizationSignature: authorization,
718
771
  });
719
772
  },
720
773
  };
721
774
  }
722
775
  /** {@inheritDoc BlueActions.refinance} */
723
776
  refinance(params) {
724
- const suppliedNow = params.now;
725
- const metadata = resolveTransactionMetadata(this.client.options.metadata, suppliedNow);
726
- const { userAddress, positionData, destination, deadline, referralFeeRecipient, } = params;
727
- const createdAt = suppliedNow ?? Time.timestamp();
728
- this.validateWriteCommon(params, createdAt);
729
- validateMarketParamsId(destination.marketParams);
730
- // `validateWriteCommon` returns void, so default an omitted `referralFeePct` to `0n`
731
- // here, matching the pure action's normalization.
732
- const referralFeePct = params.referralFeePct ?? 0n;
777
+ return this.refinancePrepared(this.parseRefinanceParams(params));
778
+ }
779
+ parseRefinanceParams(params) {
780
+ const { userAddress, positionData, destination } = params;
781
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
782
+ const createdAt = params.now ?? Time.timestamp();
783
+ const normalized = this.validateWriteCommon(params, createdAt);
784
+ const destinationMarketParams = parseBlueMarket(destination.marketParams);
785
+ const referralFeePct = normalized.referralFeePct;
733
786
  if (positionData == null) {
734
- throw new MissingAccrualPositionError(this.marketParams.id);
787
+ throw new MissingAccrualPositionError(this.parsedMarket.id);
735
788
  }
789
+ // Reject a snapshot for another user or market.
736
790
  validateAccrualPosition({
737
791
  positionData,
738
- expectedMarketId: this.marketParams.id,
792
+ expectedMarketId: this.parsedMarket.id,
739
793
  expectedUser: userAddress,
740
794
  });
741
- // Reject an empty source debt or incompatible markets before quoting.
742
- validateBlueRefinanceSource({
743
- sourceMarketParams: this.marketParams,
744
- destinationMarketParams: destination.marketParams,
745
- borrowShares: positionData.borrowShares,
795
+ if (positionData.borrowShares <= 0n) {
796
+ throw new NonPositiveInputError("positionData.borrowShares", positionData.borrowShares);
797
+ }
798
+ const markets = parseBlueRefinanceMarkets({
799
+ sourceMarketParams: this.parsedMarket,
800
+ destinationMarketParams,
746
801
  });
747
802
  if (destination.positionData == null) {
748
- throw new MissingAccrualPositionError(destination.marketParams.id);
803
+ throw new MissingAccrualPositionError(destinationMarketParams.id);
749
804
  }
805
+ // Reject a snapshot for another user or market.
750
806
  validateAccrualPosition({
751
807
  positionData: destination.positionData,
752
- expectedMarketId: destination.marketParams.id,
808
+ expectedMarketId: destinationMarketParams.id,
753
809
  expectedUser: userAddress,
754
810
  });
755
- const reallocations = [...(params.reallocations ?? [])];
756
- // Reject migrations that cannot meet the buffered destination LLTV.
811
+ const allocations = parseBlueAllocations([...(params.reallocations ?? [])], markets.destinationMarketParams);
757
812
  validateBlueRefinanceQuote({
758
- destinationMarketParams: destination.marketParams,
813
+ destinationMarketParams,
759
814
  sourcePosition: positionData,
760
815
  destinationPosition: destination.positionData,
761
- reallocations,
816
+ penaltyAssets: allocations.penaltyAssets,
762
817
  referralFeePct,
763
818
  now: createdAt,
764
819
  });
820
+ const input = {
821
+ ...markets,
822
+ ...normalized,
823
+ chainId: this.chainId,
824
+ userAddress,
825
+ now: params.now,
826
+ metadata,
827
+ publicAllocations: allocations.publicAllocations,
828
+ reallocationPenaltyAssets: allocations.penaltyAssets,
829
+ maxLtv: parseUint256("maxLtv", this.getMaxLtv(destinationMarketParams)),
830
+ };
831
+ return input;
832
+ }
833
+ refinancePrepared(parsed) {
834
+ const { userAddress, deadline } = parsed;
765
835
  return {
766
836
  getRequirements: async () => {
767
- const now = suppliedNow ?? Time.timestamp();
837
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
838
+ const now = parsed.now ?? Time.timestamp();
839
+ // Reject expiry before continuing this call.
768
840
  this.validateDeadline(deadline, now);
769
- await this.assertWriteTargets();
770
- return this.getAuthorizationRequirements({
841
+ // Reject missing write targets before resolving requirements.
842
+ await this.assertWriteTargets(chainCheck);
843
+ return this.getAuthorizationRequirements(chainCheck, {
771
844
  userAddress,
772
845
  deadline,
773
846
  now,
@@ -777,22 +850,8 @@ export class MorphoBlue {
777
850
  const { authorization } = selectBlueBundlesV1RequirementSignatures(signatures, {
778
851
  authorization: true,
779
852
  });
780
- return blueRefinance({
781
- market: {
782
- chainId: this.chainId,
783
- sourceMarketParams: this.marketParams,
784
- destinationMarketParams: destination.marketParams,
785
- },
786
- args: {
787
- userAddress,
788
- maxLtv: this.getMaxLtv(destination.marketParams),
789
- reallocations,
790
- deadline,
791
- referralFeePct,
792
- referralFeeRecipient,
793
- authorizationSignature: authorization,
794
- },
795
- metadata,
853
+ return buildBlueRefinance(parsed, {
854
+ authorizationSignature: authorization,
796
855
  });
797
856
  },
798
857
  };
@@ -851,7 +910,8 @@ export class MorphoBlue {
851
910
  * ```
852
911
  */
853
912
  async getVaultV2BlueReallocationData({ vaultAddresses, block, }) {
854
- await validateClientChainId(this.client.viemClient, this.chainId);
913
+ // Confirm the RPC chain before prerequisite reads.
914
+ await createChainCheck(this.client.viemClient, this.chainId)();
855
915
  const client = this.client.viemClient;
856
916
  const fetchParams = {
857
917
  blockNumber: block.number,
@@ -859,17 +919,17 @@ export class MorphoBlue {
859
919
  deployless: this.client.options.supportDeployless,
860
920
  };
861
921
  const [targetMarket, vaultEntries, blueBalance] = await Promise.all([
862
- fetchMarket(this.marketParams.id, client, fetchParams),
922
+ fetchMarket(this.parsedMarket.id, client, fetchParams),
863
923
  Promise.all(vaultAddresses.map(async (address) => {
864
924
  const vault = await fetchAccrualVaultV2(address, client, fetchParams);
865
925
  const publicAllocatorData = await fetchVaultV2BluePublicAllocatorData(vault, client, {
866
926
  ...fetchParams,
867
- targetMarketParams: this.marketParams,
927
+ targetMarketParams: new MarketParams(this.parsedMarket),
868
928
  });
869
929
  return { publicAllocatorData, vault };
870
930
  })),
871
931
  readContract(client, {
872
- address: this.marketParams.loanToken,
932
+ address: this.parsedMarket.loanToken,
873
933
  abi: erc20Abi,
874
934
  functionName: "balanceOf",
875
935
  args: [getChainAddresses(this.chainId).blue],
@@ -879,7 +939,7 @@ export class MorphoBlue {
879
939
  return new VaultV2BlueReallocationData({
880
940
  chainId: this.chainId,
881
941
  timestamp: block.timestamp,
882
- blueBalances: { [this.marketParams.loanToken]: blueBalance },
942
+ blueBalances: { [this.parsedMarket.loanToken]: blueBalance },
883
943
  markets: { [targetMarket.id]: targetMarket },
884
944
  vaults: Object.fromEntries(vaultEntries.map(({ vault }) => [vault.address, vault])),
885
945
  allocations: Object.fromEntries(vaultEntries.map(({ publicAllocatorData, vault }) => [
@@ -952,7 +1012,8 @@ export class MorphoBlue {
952
1012
  * ```
953
1013
  */
954
1014
  getVaultV2BlueReallocations({ reallocationData, options, }) {
1015
+ // Reject cross-chain inputs before continuing.
955
1016
  validateChainId(reallocationData.chainId, this.chainId);
956
- return reallocationData.computeVaultV2BlueReallocations(this.marketParams.id, options);
1017
+ return reallocationData.computeVaultV2BlueReallocations(this.parsedMarket.id, options);
957
1018
  }
958
1019
  }