@morpho-org/morpho-sdk 10.1.0-next.0 → 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 (470) hide show
  1. package/README.md +6 -2
  2. package/lib/cjs/abis.d.ts +1 -1
  3. package/lib/cjs/abis.js +1 -5
  4. package/lib/cjs/actions/blue/borrow.d.ts +2 -1
  5. package/lib/cjs/actions/blue/borrow.internal.d.ts +13 -0
  6. package/lib/cjs/actions/blue/borrow.internal.js +35 -0
  7. package/lib/cjs/actions/blue/borrow.js +4 -16
  8. package/lib/cjs/actions/blue/common.d.ts +50 -28
  9. package/lib/cjs/actions/blue/common.js +21 -34
  10. package/lib/cjs/actions/blue/encode.d.ts +23 -0
  11. package/lib/cjs/actions/blue/encode.js +171 -0
  12. package/lib/cjs/actions/blue/refinance.d.ts +3 -2
  13. package/lib/cjs/actions/blue/refinance.internal.d.ts +42 -0
  14. package/lib/cjs/actions/blue/refinance.internal.js +62 -0
  15. package/lib/cjs/actions/blue/refinance.js +5 -63
  16. package/lib/cjs/actions/blue/refinanceValidation.d.ts +4 -5
  17. package/lib/cjs/actions/blue/refinanceValidation.js +1 -3
  18. package/lib/cjs/actions/blue/repay.d.ts +1 -1
  19. package/lib/cjs/actions/blue/repay.internal.d.ts +13 -0
  20. package/lib/cjs/actions/blue/repay.internal.js +38 -0
  21. package/lib/cjs/actions/blue/repay.js +2 -17
  22. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +2 -2
  23. package/lib/cjs/actions/blue/repayWithdrawCollateral.internal.d.ts +61 -0
  24. package/lib/cjs/actions/blue/repayWithdrawCollateral.internal.js +112 -0
  25. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +3 -116
  26. package/lib/cjs/actions/blue/signatures.d.ts +30 -0
  27. package/lib/cjs/actions/blue/signatures.js +90 -0
  28. package/lib/cjs/actions/blue/supply.d.ts +1 -1
  29. package/lib/cjs/actions/blue/supply.internal.d.ts +32 -0
  30. package/lib/cjs/actions/blue/supply.internal.js +101 -0
  31. package/lib/cjs/actions/blue/supply.js +2 -67
  32. package/lib/cjs/actions/blue/supplyCollateral.d.ts +1 -1
  33. package/lib/cjs/actions/blue/supplyCollateral.internal.d.ts +13 -0
  34. package/lib/cjs/actions/blue/supplyCollateral.internal.js +37 -0
  35. package/lib/cjs/actions/blue/supplyCollateral.js +2 -17
  36. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +4 -3
  37. package/lib/cjs/actions/blue/supplyCollateralBorrow.internal.d.ts +63 -0
  38. package/lib/cjs/actions/blue/supplyCollateralBorrow.internal.js +94 -0
  39. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +5 -106
  40. package/lib/cjs/actions/blue/withdraw.d.ts +4 -3
  41. package/lib/cjs/actions/blue/withdraw.internal.d.ts +56 -0
  42. package/lib/cjs/actions/blue/withdraw.internal.js +84 -0
  43. package/lib/cjs/actions/blue/withdraw.js +5 -78
  44. package/lib/cjs/actions/blue/withdrawBuyCallback.d.ts +2 -2
  45. package/lib/cjs/actions/blue/withdrawBuyCallback.internal.d.ts +20 -0
  46. package/lib/cjs/actions/blue/withdrawBuyCallback.internal.js +58 -0
  47. package/lib/cjs/actions/blue/withdrawBuyCallback.js +2 -39
  48. package/lib/cjs/actions/blue/withdrawCollateral.internal.d.ts +16 -0
  49. package/lib/cjs/actions/blue/withdrawCollateral.internal.js +39 -0
  50. package/lib/cjs/actions/blue/withdrawCollateral.js +2 -17
  51. package/lib/cjs/actions/bundles/common.d.ts +9 -0
  52. package/lib/cjs/actions/bundles/common.js +18 -6
  53. package/lib/cjs/actions/bundles/index.d.ts +1 -1
  54. package/lib/cjs/actions/bundles/index.js +3 -16
  55. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +14 -0
  56. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +59 -60
  57. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +22 -1
  58. package/lib/cjs/actions/midnight/cancelAndMake.js +46 -87
  59. package/lib/cjs/actions/midnight/cancelOffers.d.ts +11 -0
  60. package/lib/cjs/actions/midnight/cancelOffers.js +22 -4
  61. package/lib/cjs/actions/midnight/encode.d.ts +36 -0
  62. package/lib/cjs/actions/midnight/encode.js +554 -0
  63. package/lib/cjs/actions/midnight/index.d.ts +14 -13
  64. package/lib/cjs/actions/midnight/index.js +29 -13
  65. package/lib/cjs/actions/midnight/parse.d.ts +35 -0
  66. package/lib/cjs/actions/midnight/parse.js +73 -0
  67. package/lib/cjs/actions/midnight/parseCollateralBatch.d.ts +58 -0
  68. package/lib/cjs/actions/midnight/parseCollateralBatch.js +216 -0
  69. package/lib/cjs/actions/midnight/redeem.d.ts +16 -3
  70. package/lib/cjs/actions/midnight/redeem.js +22 -51
  71. package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +13 -0
  72. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +42 -67
  73. package/lib/cjs/actions/midnight/supplyCollateral.d.ts +40 -5
  74. package/lib/cjs/actions/midnight/supplyCollateral.js +60 -54
  75. package/lib/cjs/actions/midnight/supplyCollateralBatch.d.ts +3 -3
  76. package/lib/cjs/actions/midnight/supplyCollateralBatch.js +3 -62
  77. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +24 -0
  78. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +39 -66
  79. package/lib/cjs/actions/midnight/supplyCollateralWithNative.d.ts +77 -0
  80. package/lib/cjs/actions/midnight/supplyCollateralWithNative.js +142 -0
  81. package/lib/cjs/actions/midnight/takeBorrow.d.ts +17 -2
  82. package/lib/cjs/actions/midnight/takeBorrow.js +25 -55
  83. package/lib/cjs/actions/midnight/takeLend.d.ts +21 -1
  84. package/lib/cjs/actions/midnight/takeLend.js +30 -57
  85. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +22 -2
  86. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +34 -61
  87. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +17 -2
  88. package/lib/cjs/actions/midnight/takeWithdraw.js +78 -115
  89. package/lib/cjs/actions/midnight/withdrawCollateral.d.ts +16 -3
  90. package/lib/cjs/actions/midnight/withdrawCollateral.js +25 -56
  91. package/lib/cjs/actions/midnight/withdrawCollateralBatch.d.ts +3 -3
  92. package/lib/cjs/actions/midnight/withdrawCollateralBatch.js +3 -71
  93. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +13 -0
  94. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +39 -19
  95. package/lib/cjs/actions/requirements/blue/index.d.ts +1 -1
  96. package/lib/cjs/actions/requirements/blue/index.js +3 -15
  97. package/lib/cjs/actions/requirements/chainCheck.d.ts +5 -0
  98. package/lib/cjs/actions/requirements/chainCheck.js +10 -0
  99. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -0
  100. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +40 -27
  101. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +11 -1
  102. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +36 -17
  103. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +14 -1
  104. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +44 -9
  105. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +10 -0
  106. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +61 -24
  107. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +10 -0
  108. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +25 -4
  109. package/lib/cjs/actions/requirements/encode/index.d.ts +5 -5
  110. package/lib/cjs/actions/requirements/encode/index.js +11 -19
  111. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +26 -11
  112. package/lib/cjs/actions/requirements/getRequirementsApproval.js +40 -12
  113. package/lib/cjs/actions/requirements/index.d.ts +1 -1
  114. package/lib/cjs/actions/requirements/index.js +3 -1
  115. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +11 -0
  116. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +34 -19
  117. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +11 -0
  118. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +26 -12
  119. package/lib/cjs/actions/requirements/midnight/index.d.ts +2 -2
  120. package/lib/cjs/actions/requirements/midnight/index.js +5 -16
  121. package/lib/cjs/actions/vaultV1/deposit.d.ts +21 -0
  122. package/lib/cjs/actions/vaultV1/deposit.js +46 -10
  123. package/lib/cjs/actions/vaultV1/inKindRedeem.d.ts +18 -1
  124. package/lib/cjs/actions/vaultV1/inKindRedeem.js +36 -16
  125. package/lib/cjs/actions/vaultV1/index.d.ts +5 -5
  126. package/lib/cjs/actions/vaultV1/index.js +11 -19
  127. package/lib/cjs/actions/vaultV1/migrateToV2.d.ts +21 -0
  128. package/lib/cjs/actions/vaultV1/migrateToV2.js +49 -11
  129. package/lib/cjs/actions/vaultV1/redeem.d.ts +19 -0
  130. package/lib/cjs/actions/vaultV1/redeem.js +28 -7
  131. package/lib/cjs/actions/vaultV1/withdraw.d.ts +19 -0
  132. package/lib/cjs/actions/vaultV1/withdraw.js +28 -7
  133. package/lib/cjs/actions/vaultV2/deposit.d.ts +21 -0
  134. package/lib/cjs/actions/vaultV2/deposit.js +46 -10
  135. package/lib/cjs/actions/vaultV2/forceRedeem.d.ts +20 -2
  136. package/lib/cjs/actions/vaultV2/forceRedeem.js +39 -8
  137. package/lib/cjs/actions/vaultV2/forceWithdraw.d.ts +23 -1
  138. package/lib/cjs/actions/vaultV2/forceWithdraw.js +36 -14
  139. package/lib/cjs/actions/vaultV2/inKindRedeem.d.ts +18 -1
  140. package/lib/cjs/actions/vaultV2/inKindRedeem.js +35 -15
  141. package/lib/cjs/actions/vaultV2/index.d.ts +6 -6
  142. package/lib/cjs/actions/vaultV2/index.js +13 -20
  143. package/lib/cjs/actions/vaultV2/redeem.d.ts +19 -0
  144. package/lib/cjs/actions/vaultV2/redeem.js +28 -7
  145. package/lib/cjs/actions/vaultV2/withdraw.d.ts +19 -0
  146. package/lib/cjs/actions/vaultV2/withdraw.js +28 -7
  147. package/lib/cjs/blue/abis.d.ts +1 -1
  148. package/lib/cjs/blue/abis.js +1 -5
  149. package/lib/cjs/blue/entities.d.ts +4 -4
  150. package/lib/cjs/blue/entities.js +1 -3
  151. package/lib/cjs/blue/errors.d.ts +2 -2
  152. package/lib/cjs/blue/errors.js +1 -5
  153. package/lib/cjs/blue/fetch.d.ts +2 -2
  154. package/lib/cjs/blue/fetch.js +1 -3
  155. package/lib/cjs/blue/utils.d.ts +1 -1
  156. package/lib/cjs/blue/utils.js +1 -2
  157. package/lib/cjs/entities/blue/blue.d.ts +35 -8
  158. package/lib/cjs/entities/blue/blue.js +467 -406
  159. package/lib/cjs/entities/index.d.ts +4 -4
  160. package/lib/cjs/entities/index.js +1 -3
  161. package/lib/cjs/entities/midnight/midnight.d.ts +117 -41
  162. package/lib/cjs/entities/midnight/midnight.js +472 -843
  163. package/lib/cjs/entities/midnight/parse.d.ts +74 -0
  164. package/lib/cjs/entities/midnight/parse.js +336 -0
  165. package/lib/cjs/entities/midnight/prepare.d.ts +47 -0
  166. package/lib/cjs/entities/midnight/prepare.js +293 -0
  167. package/lib/cjs/entities/midnight/publication.d.ts +7 -3
  168. package/lib/cjs/entities/midnight/publication.js +10 -7
  169. package/lib/cjs/entities/midnight/types.d.ts +7 -0
  170. package/lib/cjs/entities/requirements/assertContractCode.d.ts +10 -5
  171. package/lib/cjs/entities/requirements/assertContractCode.js +24 -15
  172. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +15 -0
  173. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +59 -51
  174. package/lib/cjs/entities/requirements/getErc2612Permit.d.ts +7 -3
  175. package/lib/cjs/entities/requirements/getErc2612Permit.js +20 -4
  176. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.d.ts +15 -0
  177. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.js +24 -7
  178. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +14 -0
  179. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +27 -7
  180. package/lib/cjs/entities/requirements/getVaultV1InKindRedeemRequirements.js +4 -3
  181. package/lib/cjs/entities/requirements/getVaultV2ForceWithdrawRequirements.js +4 -3
  182. package/lib/cjs/entities/requirements/getVaultV2InKindRedeemRequirements.js +4 -3
  183. package/lib/cjs/entities/requirements/index.d.ts +2 -2
  184. package/lib/cjs/entities/requirements/index.js +5 -16
  185. package/lib/cjs/entities/requirements/validateNativeRequirements.d.ts +21 -0
  186. package/lib/cjs/entities/requirements/validateNativeRequirements.js +37 -0
  187. package/lib/cjs/entities/vaultV1/inKindRedeemQuote.d.ts +2 -2
  188. package/lib/cjs/entities/vaultV1/inKindRedeemQuote.js +1 -7
  189. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +17 -40
  190. package/lib/cjs/entities/vaultV1/vaultV1.js +228 -159
  191. package/lib/cjs/entities/vaultV2/forceWithdrawQuote.d.ts +4 -0
  192. package/lib/cjs/entities/vaultV2/forceWithdrawQuote.js +9 -4
  193. package/lib/cjs/entities/vaultV2/inKindRedeemQuote.d.ts +2 -2
  194. package/lib/cjs/entities/vaultV2/inKindRedeemQuote.js +1 -7
  195. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +29 -86
  196. package/lib/cjs/entities/vaultV2/vaultV2.js +226 -188
  197. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +2 -3
  198. package/lib/cjs/entities/vaultV2BlueReallocationData.js +2 -6
  199. package/lib/cjs/errors.d.ts +4 -4
  200. package/lib/cjs/errors.js +5 -7
  201. package/lib/cjs/fetch.d.ts +2 -2
  202. package/lib/cjs/fetch.js +1 -3
  203. package/lib/cjs/helpers/deadShares.js +0 -3
  204. package/lib/cjs/helpers/parse.d.ts +33 -0
  205. package/lib/cjs/helpers/parse.js +71 -0
  206. package/lib/cjs/helpers/parseMidnight.d.ts +48 -0
  207. package/lib/cjs/helpers/parseMidnight.js +95 -0
  208. package/lib/cjs/helpers/parseMidnightMaker.d.ts +44 -0
  209. package/lib/cjs/helpers/parseMidnightMaker.js +154 -0
  210. package/lib/cjs/helpers/validate.d.ts +3 -2
  211. package/lib/cjs/helpers/validate.js +4 -0
  212. package/lib/cjs/helpers/validateMidnightCancelAndMakePublication.d.ts +8 -0
  213. package/lib/cjs/helpers/validateMidnightCancelAndMakePublication.js +4 -4
  214. package/lib/cjs/helpers/validateMidnightPublication.d.ts +17 -1
  215. package/lib/cjs/index.d.ts +1 -0
  216. package/lib/cjs/midnight/errors.d.ts +1 -2
  217. package/lib/cjs/midnight/errors.js +4 -5
  218. package/lib/cjs/transactionPlan/blue/refinance.js +17 -9
  219. package/lib/cjs/transactionPlan/blue/repay.js +2 -1
  220. package/lib/cjs/transactionPlan/blue/repayWithdrawCollateral.js +23 -4
  221. package/lib/cjs/transactionPlan/blue/supplyCollateralBorrow.js +2 -2
  222. package/lib/cjs/transactionPlan/blue/withdraw.d.ts +2 -2
  223. package/lib/cjs/transactionPlan/blue/withdraw.js +3 -3
  224. package/lib/cjs/transactionPlan/blue/withdrawCollateral.js +6 -2
  225. package/lib/cjs/transactionPlan/validation.d.ts +1 -1
  226. package/lib/cjs/transactionPlan/validation.js +3 -0
  227. package/lib/cjs/transactionPlan/vaultv1/deposit.d.ts +2 -2
  228. package/lib/cjs/transactionPlan/vaultv1/deposit.js +2 -2
  229. package/lib/cjs/types/action.d.ts +13 -2
  230. package/lib/cjs/types/error.d.ts +20 -2
  231. package/lib/cjs/types/error.js +32 -3
  232. package/lib/cjs/utils.d.ts +2 -2
  233. package/lib/cjs/utils.js +2 -4
  234. package/lib/cjs/version.d.ts +1 -1
  235. package/lib/cjs/version.js +1 -1
  236. package/lib/esm/abis.d.ts +1 -1
  237. package/lib/esm/abis.js +1 -1
  238. package/lib/esm/actions/blue/borrow.d.ts +2 -1
  239. package/lib/esm/actions/blue/borrow.internal.d.ts +13 -0
  240. package/lib/esm/actions/blue/borrow.internal.js +30 -0
  241. package/lib/esm/actions/blue/borrow.js +4 -16
  242. package/lib/esm/actions/blue/common.d.ts +50 -28
  243. package/lib/esm/actions/blue/common.js +21 -33
  244. package/lib/esm/actions/blue/encode.d.ts +23 -0
  245. package/lib/esm/actions/blue/encode.js +164 -0
  246. package/lib/esm/actions/blue/refinance.d.ts +3 -2
  247. package/lib/esm/actions/blue/refinance.internal.d.ts +42 -0
  248. package/lib/esm/actions/blue/refinance.internal.js +56 -0
  249. package/lib/esm/actions/blue/refinance.js +5 -63
  250. package/lib/esm/actions/blue/refinanceValidation.d.ts +4 -5
  251. package/lib/esm/actions/blue/refinanceValidation.js +2 -4
  252. package/lib/esm/actions/blue/repay.d.ts +1 -1
  253. package/lib/esm/actions/blue/repay.internal.d.ts +13 -0
  254. package/lib/esm/actions/blue/repay.internal.js +33 -0
  255. package/lib/esm/actions/blue/repay.js +2 -17
  256. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +2 -2
  257. package/lib/esm/actions/blue/repayWithdrawCollateral.internal.d.ts +61 -0
  258. package/lib/esm/actions/blue/repayWithdrawCollateral.internal.js +104 -0
  259. package/lib/esm/actions/blue/repayWithdrawCollateral.js +3 -116
  260. package/lib/esm/actions/blue/signatures.d.ts +30 -0
  261. package/lib/esm/actions/blue/signatures.js +82 -0
  262. package/lib/esm/actions/blue/supply.d.ts +1 -1
  263. package/lib/esm/actions/blue/supply.internal.d.ts +32 -0
  264. package/lib/esm/actions/blue/supply.internal.js +95 -0
  265. package/lib/esm/actions/blue/supply.js +2 -67
  266. package/lib/esm/actions/blue/supplyCollateral.d.ts +1 -1
  267. package/lib/esm/actions/blue/supplyCollateral.internal.d.ts +13 -0
  268. package/lib/esm/actions/blue/supplyCollateral.internal.js +32 -0
  269. package/lib/esm/actions/blue/supplyCollateral.js +2 -17
  270. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +4 -3
  271. package/lib/esm/actions/blue/supplyCollateralBorrow.internal.d.ts +63 -0
  272. package/lib/esm/actions/blue/supplyCollateralBorrow.internal.js +87 -0
  273. package/lib/esm/actions/blue/supplyCollateralBorrow.js +5 -106
  274. package/lib/esm/actions/blue/withdraw.d.ts +4 -3
  275. package/lib/esm/actions/blue/withdraw.internal.d.ts +56 -0
  276. package/lib/esm/actions/blue/withdraw.internal.js +77 -0
  277. package/lib/esm/actions/blue/withdraw.js +5 -78
  278. package/lib/esm/actions/blue/withdrawBuyCallback.d.ts +2 -2
  279. package/lib/esm/actions/blue/withdrawBuyCallback.internal.d.ts +20 -0
  280. package/lib/esm/actions/blue/withdrawBuyCallback.internal.js +53 -0
  281. package/lib/esm/actions/blue/withdrawBuyCallback.js +2 -39
  282. package/lib/esm/actions/blue/withdrawCollateral.internal.d.ts +16 -0
  283. package/lib/esm/actions/blue/withdrawCollateral.internal.js +34 -0
  284. package/lib/esm/actions/blue/withdrawCollateral.js +2 -17
  285. package/lib/esm/actions/bundles/common.d.ts +9 -0
  286. package/lib/esm/actions/bundles/common.js +15 -4
  287. package/lib/esm/actions/bundles/index.d.ts +1 -1
  288. package/lib/esm/actions/bundles/index.js +1 -1
  289. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +14 -0
  290. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +58 -61
  291. package/lib/esm/actions/midnight/cancelAndMake.d.ts +22 -1
  292. package/lib/esm/actions/midnight/cancelAndMake.js +43 -85
  293. package/lib/esm/actions/midnight/cancelOffers.d.ts +11 -0
  294. package/lib/esm/actions/midnight/cancelOffers.js +18 -2
  295. package/lib/esm/actions/midnight/encode.d.ts +36 -0
  296. package/lib/esm/actions/midnight/encode.js +539 -0
  297. package/lib/esm/actions/midnight/index.d.ts +14 -13
  298. package/lib/esm/actions/midnight/index.js +14 -13
  299. package/lib/esm/actions/midnight/parse.d.ts +35 -0
  300. package/lib/esm/actions/midnight/parse.js +68 -0
  301. package/lib/esm/actions/midnight/parseCollateralBatch.d.ts +58 -0
  302. package/lib/esm/actions/midnight/parseCollateralBatch.js +209 -0
  303. package/lib/esm/actions/midnight/redeem.d.ts +16 -3
  304. package/lib/esm/actions/midnight/redeem.js +20 -50
  305. package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +13 -0
  306. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +38 -64
  307. package/lib/esm/actions/midnight/supplyCollateral.d.ts +40 -5
  308. package/lib/esm/actions/midnight/supplyCollateral.js +57 -53
  309. package/lib/esm/actions/midnight/supplyCollateralBatch.d.ts +3 -3
  310. package/lib/esm/actions/midnight/supplyCollateralBatch.js +3 -62
  311. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +24 -0
  312. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +33 -61
  313. package/lib/esm/actions/midnight/supplyCollateralWithNative.d.ts +77 -0
  314. package/lib/esm/actions/midnight/supplyCollateralWithNative.js +137 -0
  315. package/lib/esm/actions/midnight/takeBorrow.d.ts +17 -2
  316. package/lib/esm/actions/midnight/takeBorrow.js +20 -51
  317. package/lib/esm/actions/midnight/takeLend.d.ts +21 -1
  318. package/lib/esm/actions/midnight/takeLend.js +26 -54
  319. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +22 -2
  320. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +30 -58
  321. package/lib/esm/actions/midnight/takeWithdraw.d.ts +17 -2
  322. package/lib/esm/actions/midnight/takeWithdraw.js +76 -114
  323. package/lib/esm/actions/midnight/withdrawCollateral.d.ts +16 -3
  324. package/lib/esm/actions/midnight/withdrawCollateral.js +23 -55
  325. package/lib/esm/actions/midnight/withdrawCollateralBatch.d.ts +3 -3
  326. package/lib/esm/actions/midnight/withdrawCollateralBatch.js +3 -71
  327. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +13 -0
  328. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +36 -18
  329. package/lib/esm/actions/requirements/blue/index.d.ts +1 -1
  330. package/lib/esm/actions/requirements/blue/index.js +1 -1
  331. package/lib/esm/actions/requirements/chainCheck.d.ts +5 -0
  332. package/lib/esm/actions/requirements/chainCheck.js +6 -0
  333. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -0
  334. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +36 -25
  335. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +11 -1
  336. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +33 -16
  337. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +14 -1
  338. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +41 -8
  339. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +10 -0
  340. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +59 -24
  341. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +10 -0
  342. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +21 -2
  343. package/lib/esm/actions/requirements/encode/index.d.ts +5 -5
  344. package/lib/esm/actions/requirements/encode/index.js +5 -5
  345. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +26 -11
  346. package/lib/esm/actions/requirements/getRequirementsApproval.js +38 -12
  347. package/lib/esm/actions/requirements/index.d.ts +1 -1
  348. package/lib/esm/actions/requirements/index.js +1 -1
  349. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +11 -0
  350. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +31 -18
  351. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +11 -0
  352. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +22 -10
  353. package/lib/esm/actions/requirements/midnight/index.d.ts +2 -2
  354. package/lib/esm/actions/requirements/midnight/index.js +2 -2
  355. package/lib/esm/actions/vaultV1/deposit.d.ts +21 -0
  356. package/lib/esm/actions/vaultV1/deposit.js +43 -9
  357. package/lib/esm/actions/vaultV1/inKindRedeem.d.ts +18 -1
  358. package/lib/esm/actions/vaultV1/inKindRedeem.js +33 -15
  359. package/lib/esm/actions/vaultV1/index.d.ts +5 -5
  360. package/lib/esm/actions/vaultV1/index.js +5 -5
  361. package/lib/esm/actions/vaultV1/migrateToV2.d.ts +21 -0
  362. package/lib/esm/actions/vaultV1/migrateToV2.js +47 -11
  363. package/lib/esm/actions/vaultV1/redeem.d.ts +19 -0
  364. package/lib/esm/actions/vaultV1/redeem.js +26 -7
  365. package/lib/esm/actions/vaultV1/withdraw.d.ts +19 -0
  366. package/lib/esm/actions/vaultV1/withdraw.js +26 -7
  367. package/lib/esm/actions/vaultV2/deposit.d.ts +21 -0
  368. package/lib/esm/actions/vaultV2/deposit.js +43 -9
  369. package/lib/esm/actions/vaultV2/forceRedeem.d.ts +20 -2
  370. package/lib/esm/actions/vaultV2/forceRedeem.js +35 -6
  371. package/lib/esm/actions/vaultV2/forceWithdraw.d.ts +23 -1
  372. package/lib/esm/actions/vaultV2/forceWithdraw.js +33 -13
  373. package/lib/esm/actions/vaultV2/inKindRedeem.d.ts +18 -1
  374. package/lib/esm/actions/vaultV2/inKindRedeem.js +32 -14
  375. package/lib/esm/actions/vaultV2/index.d.ts +6 -6
  376. package/lib/esm/actions/vaultV2/index.js +6 -6
  377. package/lib/esm/actions/vaultV2/redeem.d.ts +19 -0
  378. package/lib/esm/actions/vaultV2/redeem.js +26 -7
  379. package/lib/esm/actions/vaultV2/withdraw.d.ts +19 -0
  380. package/lib/esm/actions/vaultV2/withdraw.js +26 -7
  381. package/lib/esm/blue/abis.d.ts +1 -1
  382. package/lib/esm/blue/abis.js +1 -1
  383. package/lib/esm/blue/entities.d.ts +4 -4
  384. package/lib/esm/blue/entities.js +2 -2
  385. package/lib/esm/blue/errors.d.ts +2 -2
  386. package/lib/esm/blue/errors.js +2 -2
  387. package/lib/esm/blue/fetch.d.ts +2 -2
  388. package/lib/esm/blue/fetch.js +2 -2
  389. package/lib/esm/blue/utils.d.ts +1 -1
  390. package/lib/esm/blue/utils.js +1 -1
  391. package/lib/esm/entities/blue/blue.d.ts +35 -8
  392. package/lib/esm/entities/blue/blue.js +449 -388
  393. package/lib/esm/entities/index.d.ts +4 -4
  394. package/lib/esm/entities/index.js +2 -2
  395. package/lib/esm/entities/midnight/midnight.d.ts +117 -41
  396. package/lib/esm/entities/midnight/midnight.js +455 -826
  397. package/lib/esm/entities/midnight/parse.d.ts +74 -0
  398. package/lib/esm/entities/midnight/parse.js +320 -0
  399. package/lib/esm/entities/midnight/prepare.d.ts +47 -0
  400. package/lib/esm/entities/midnight/prepare.js +282 -0
  401. package/lib/esm/entities/midnight/publication.d.ts +7 -3
  402. package/lib/esm/entities/midnight/publication.js +7 -3
  403. package/lib/esm/entities/midnight/types.d.ts +7 -0
  404. package/lib/esm/entities/requirements/assertContractCode.d.ts +10 -5
  405. package/lib/esm/entities/requirements/assertContractCode.js +24 -15
  406. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +15 -0
  407. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +53 -47
  408. package/lib/esm/entities/requirements/getErc2612Permit.d.ts +7 -3
  409. package/lib/esm/entities/requirements/getErc2612Permit.js +19 -4
  410. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.d.ts +15 -0
  411. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.js +20 -5
  412. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +14 -0
  413. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +23 -5
  414. package/lib/esm/entities/requirements/getVaultV1InKindRedeemRequirements.js +4 -3
  415. package/lib/esm/entities/requirements/getVaultV2ForceWithdrawRequirements.js +4 -3
  416. package/lib/esm/entities/requirements/getVaultV2InKindRedeemRequirements.js +4 -3
  417. package/lib/esm/entities/requirements/index.d.ts +2 -2
  418. package/lib/esm/entities/requirements/index.js +2 -2
  419. package/lib/esm/entities/requirements/validateNativeRequirements.d.ts +21 -0
  420. package/lib/esm/entities/requirements/validateNativeRequirements.js +33 -0
  421. package/lib/esm/entities/vaultV1/inKindRedeemQuote.d.ts +2 -2
  422. package/lib/esm/entities/vaultV1/inKindRedeemQuote.js +1 -7
  423. package/lib/esm/entities/vaultV1/vaultV1.d.ts +17 -40
  424. package/lib/esm/entities/vaultV1/vaultV1.js +208 -139
  425. package/lib/esm/entities/vaultV2/forceWithdrawQuote.d.ts +4 -0
  426. package/lib/esm/entities/vaultV2/forceWithdrawQuote.js +10 -5
  427. package/lib/esm/entities/vaultV2/inKindRedeemQuote.d.ts +2 -2
  428. package/lib/esm/entities/vaultV2/inKindRedeemQuote.js +1 -7
  429. package/lib/esm/entities/vaultV2/vaultV2.d.ts +29 -86
  430. package/lib/esm/entities/vaultV2/vaultV2.js +210 -172
  431. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +2 -3
  432. package/lib/esm/entities/vaultV2BlueReallocationData.js +2 -6
  433. package/lib/esm/errors.d.ts +4 -4
  434. package/lib/esm/errors.js +4 -4
  435. package/lib/esm/fetch.d.ts +2 -2
  436. package/lib/esm/fetch.js +2 -2
  437. package/lib/esm/helpers/deadShares.js +1 -4
  438. package/lib/esm/helpers/parse.d.ts +33 -0
  439. package/lib/esm/helpers/parse.js +61 -0
  440. package/lib/esm/helpers/parseMidnight.d.ts +48 -0
  441. package/lib/esm/helpers/parseMidnight.js +80 -0
  442. package/lib/esm/helpers/parseMidnightMaker.d.ts +44 -0
  443. package/lib/esm/helpers/parseMidnightMaker.js +147 -0
  444. package/lib/esm/helpers/validate.d.ts +3 -2
  445. package/lib/esm/helpers/validate.js +5 -1
  446. package/lib/esm/helpers/validateMidnightCancelAndMakePublication.d.ts +8 -0
  447. package/lib/esm/helpers/validateMidnightCancelAndMakePublication.js +2 -2
  448. package/lib/esm/helpers/validateMidnightPublication.d.ts +17 -1
  449. package/lib/esm/index.d.ts +1 -0
  450. package/lib/esm/midnight/errors.d.ts +1 -2
  451. package/lib/esm/midnight/errors.js +1 -2
  452. package/lib/esm/transactionPlan/blue/refinance.js +18 -10
  453. package/lib/esm/transactionPlan/blue/repay.js +3 -2
  454. package/lib/esm/transactionPlan/blue/repayWithdrawCollateral.js +24 -5
  455. package/lib/esm/transactionPlan/blue/supplyCollateralBorrow.js +2 -2
  456. package/lib/esm/transactionPlan/blue/withdraw.d.ts +2 -2
  457. package/lib/esm/transactionPlan/blue/withdraw.js +3 -3
  458. package/lib/esm/transactionPlan/blue/withdrawCollateral.js +6 -2
  459. package/lib/esm/transactionPlan/validation.d.ts +1 -1
  460. package/lib/esm/transactionPlan/validation.js +3 -0
  461. package/lib/esm/transactionPlan/vaultv1/deposit.d.ts +2 -2
  462. package/lib/esm/transactionPlan/vaultv1/deposit.js +2 -2
  463. package/lib/esm/types/action.d.ts +13 -2
  464. package/lib/esm/types/error.d.ts +20 -2
  465. package/lib/esm/types/error.js +27 -0
  466. package/lib/esm/utils.d.ts +2 -2
  467. package/lib/esm/utils.js +2 -2
  468. package/lib/esm/version.d.ts +1 -1
  469. package/lib/esm/version.js +1 -1
  470. package/package.json +7 -7
@@ -1,182 +1,24 @@
1
- import { MarketUtils as BlueMarketUtils, MathLib, UnsupportedMarketIrmError, } from "@morpho-org/blue-sdk";
2
- import { fetchMarket as fetchBlueMarket } from "@morpho-org/blue-sdk-viem";
3
- import { fetchAccrualPosition, fetchMarket, MarketParams, MarketUtils, Payload, PriceRatifierV1, RateRatifierV1, Tree, } from "@morpho-org/midnight-sdk";
4
- import { _try, getChainAddress, Time } from "@morpho-org/morpho-ts";
5
- import { isAddress, isAddressEqual, maxUint256, zeroAddress, } from "viem";
6
- import { midnightCancelAndMake, midnightCancelOffers, midnightRedeem, midnightRepayWithdrawCollateral, midnightSupplyCollateral, midnightSupplyCollateralBatch, midnightSupplyCollateralTakeBorrow, midnightTakeBorrow, midnightTakeLend, midnightTakeRepayWithdrawCollateral, midnightTakeWithdraw, midnightWithdrawCollateral, midnightWithdrawCollateralBatch, } from "../../actions/midnight/index.js";
7
- import { getMidnightApprovalRequirements, getMidnightAuthorizationRequirement, } from "../../actions/requirements/index.js";
8
- import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
- import { getMidnightBlueBuyCallbackAddress, getMidnightBlueBuyCallbackData, } from "../../helpers/callback.js";
10
- import { MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS } from "../../helpers/constant.js";
11
- import { encodeMidnightMarketId, wrapMidnightEncoding, } from "../../helpers/encodeMidnightCalldata.js";
1
+ import { MathLib } from "@morpho-org/blue-sdk";
2
+ import { fetchAccrualPosition, fetchMarket, MarketUtils, } from "@morpho-org/midnight-sdk";
3
+ import { getChainAddress, Time } from "@morpho-org/morpho-ts";
4
+ import { maxUint256 } from "viem";
5
+ import { getBlock } from "viem/actions";
6
+ import { encodeMidnightCancelOffers } from "../../actions/midnight/cancelOffers.js";
7
+ import { encodeMidnightCancelAndMake, encodeMidnightRedeem, encodeMidnightRepayWithdrawCollateral, encodeMidnightSupplyCollateral, encodeMidnightSupplyCollateralBatch, encodeMidnightSupplyCollateralTakeBorrow, encodeMidnightTakeBorrow, encodeMidnightTakeLend, encodeMidnightTakeRepayWithdrawCollateral, encodeMidnightTakeWithdraw, encodeMidnightWithdrawCollateral, encodeMidnightWithdrawCollateralBatch, } from "../../actions/midnight/encode.js";
8
+ import { prepareMidnightSupplyCollateralWithNative } from "../../actions/midnight/supplyCollateralWithNative.js";
9
+ import { createChainCheck, } from "../../actions/requirements/chainCheck.js";
10
+ import { getParsedMidnightApprovalRequirements, parseMidnightApprovalRequirements, } from "../../actions/requirements/midnight/getMidnightApprovalRequirements.js";
11
+ import { getParsedMidnightAuthorizationRequirement, parseMidnightAuthorizationRequirement, } from "../../actions/requirements/midnight/getMidnightAuthorizationRequirement.js";
12
12
  import { getMidnightMaxSafeDebt, validateChainId, } from "../../helpers/index.js";
13
13
  import { resolveTransactionMetadata } from "../../helpers/metadata.js";
14
- import { validateMidnightAccount, validateMidnightAddress, } from "../../helpers/validateMidnightAccount.js";
15
- import { validateMidnightUint128Field } from "../../helpers/validateMidnightBounds.js";
16
- import { validateMidnightCollateralBatch } from "../../helpers/validateMidnightCollateralBatch.js";
14
+ import { parseMidnightNativeCollateralAmount } from "../../helpers/parseMidnight.js";
15
+ import { validateMidnightAddress } from "../../helpers/validateMidnightAccount.js";
17
16
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
18
- import { validateMidnightBytes32 } from "../../helpers/validateMidnightPublication.js";
19
17
  import { validateMidnightTakeFeasibility } from "../../helpers/validateMidnightTakeFeasibility.js";
20
- import { validateOfferSides } from "../../helpers/validateOfferSides.js";
21
- import { AccrualPositionUserMismatchError, BorrowExceedsSafeLtvError, EmptyBlueParkingMarketError, EmptyMidnightCollateralSuppliesError, EmptyMidnightCollateralWithdrawalsError, InsufficientMidnightWithdrawableLiquidityError, MarketIdMismatchError, MidnightInvalidAccountAddressError, MidnightOfferCallbackDataMismatchError, MidnightOfferCallbackMismatchError, MidnightOfferContinuousFeeCapError, MidnightOfferMakerMismatchError, MidnightOfferMarketAddressMismatchError, MidnightOfferMarketChainMismatchError, MidnightOfferMarketLoanTokenMismatchError, MidnightOfferNotReduceOnlyError, MidnightOfferRatifierMismatchError, MidnightOfferReduceOnlyError, MidnightOfferSellerReceiverMismatchError, MidnightRedeemExceedsCreditError, MidnightRepayExceedsDebtError, MidnightTakeDeadlineTooFarError, MidnightTakeTargetUnreachableError, MidnightZeroOnBehalfError, MissingAccrualPositionError, NegativeInputError, NoMidnightCreditToRedeemError, NonPositiveInputError, WithdrawExceedsCollateralError, WithdrawMakesPositionUnhealthyError, ZeroBlueParkingSharesError, } from "../../types/index.js";
18
+ import { BorrowExceedsSafeLtvError, InvalidBigIntInputError, MidnightRepayExceedsDebtError, MidnightTakeTargetUnreachableError, NegativeInputError, WithdrawExceedsCollateralError, WithdrawMakesPositionUnhealthyError, } from "../../types/index.js";
22
19
  import { validateMidnightDeadline } from "./deadline.js";
23
- import { fetchMidnightMakerOfferStates, offerMarketParams, validateMidnightMakerOfferCallbacks, validateMidnightMakerOfferStates, } from "./publication.js";
24
- const validatePositionBinding = (params) => {
25
- if (params.positionData.marketId !== params.marketData.id) {
26
- throw new MarketIdMismatchError(params.positionData.marketId, params.marketData.id);
27
- }
28
- // Reject a malformed address before viem compares it.
29
- validateMidnightAddress("positionData.user", params.positionData.user);
30
- if (!isAddressEqual(params.positionData.user, params.accountAddress)) {
31
- throw new AccrualPositionUserMismatchError(params.positionData.user, params.accountAddress);
32
- }
33
- };
34
- const validateTakeDeadlineWindow = (deadline, now = Time.timestamp()) => {
35
- // Throws when the deadline is at or before now.
36
- validateMidnightDeadline(deadline, now);
37
- const maxDeadline = now + MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS;
38
- if (deadline > maxDeadline) {
39
- throw new MidnightTakeDeadlineTooFarError({ deadline, maxDeadline });
40
- }
41
- };
42
- const assertNonNegativeAmount = (label, amount) => {
43
- if (amount < 0n) {
44
- throw new NegativeInputError(label, amount);
45
- }
46
- };
47
- const assertPositiveAmount = (label, amount) => {
48
- if (amount <= 0n) {
49
- throw new NonPositiveInputError(label, amount);
50
- }
51
- };
52
- const rejectReduceOnlyOffers = (offers) => {
53
- offers.forEach((offer, index) => {
54
- if (offer.reduceOnly) {
55
- throw new MidnightOfferReduceOnlyError({ index });
56
- }
57
- });
58
- };
59
- const getOffersDataInternal = async ({ client, chainId, params, marketCreationTime = "expiry", }) => {
60
- validateChainId(client.viemClient.chain?.id, chainId);
61
- // Reject a malformed or zero maker before comparing offers against it.
62
- validateMidnightAccount("accountAddress", params.accountAddress);
63
- const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
64
- const midnight = getChainAddress(chainId, "midnight");
65
- tree.offers.forEach((offer, index) => {
66
- if (!isAddressEqual(offer.maker, params.accountAddress)) {
67
- throw new MidnightOfferMakerMismatchError({
68
- index,
69
- expectedMaker: params.accountAddress,
70
- actualMaker: offer.maker,
71
- });
72
- }
73
- if (offer.continuousFeeCap !== 0n) {
74
- throw new MidnightOfferContinuousFeeCapError({
75
- index,
76
- continuousFeeCap: offer.continuousFeeCap,
77
- });
78
- }
79
- if (!offer.buy &&
80
- !isAddressEqual(offer.receiverIfMakerIsSeller, offer.maker)) {
81
- throw new MidnightOfferSellerReceiverMismatchError({
82
- index,
83
- expectedReceiver: offer.maker,
84
- actualReceiver: offer.receiverIfMakerIsSeller,
85
- });
86
- }
87
- const market = offerMarketParams(offer);
88
- if (market.chainId !== BigInt(chainId)) {
89
- throw new MidnightOfferMarketChainMismatchError({
90
- index,
91
- expectedChainId: chainId,
92
- actualChainId: market.chainId,
93
- });
94
- }
95
- if (!isAddressEqual(market.midnight, midnight)) {
96
- throw new MidnightOfferMarketAddressMismatchError({
97
- index,
98
- expectedMidnight: midnight,
99
- actualMidnight: market.midnight,
100
- });
101
- }
102
- });
103
- const ratifierType = tree.type;
104
- const ratifier = getChainAddress(chainId, ratifierType === "priceV1" ? "priceRatifierV1" : "rateRatifierV1");
105
- tree.offers.forEach((offer, index) => {
106
- if (!isAddressEqual(offer.ratifier, ratifier)) {
107
- throw new MidnightOfferRatifierMismatchError({
108
- index,
109
- expectedRatifier: ratifier,
110
- actualRatifier: offer.ratifier,
111
- });
112
- }
113
- });
114
- const { states, now } = await fetchMidnightMakerOfferStates({
115
- client: client.viemClient,
116
- chainId,
117
- tree,
118
- });
119
- validateMidnightMakerOfferStates({
120
- tree,
121
- states,
122
- now,
123
- marketCreationTime,
124
- });
125
- const groups = [];
126
- const seenGroups = new Set();
127
- for (const offer of tree.offers) {
128
- const group = offer.group;
129
- const key = group.toLowerCase();
130
- if (!seenGroups.has(key)) {
131
- seenGroups.add(key);
132
- groups.push(group);
133
- }
134
- }
135
- if (params.validation !== false) {
136
- await tree.mempoolValidate({
137
- ...params.validation,
138
- chainId,
139
- });
140
- }
141
- const items = tree.type === "priceV1"
142
- ? PriceRatifierV1.ratify({ tree })
143
- : RateRatifierV1.ratify({ tree });
144
- return {
145
- accountAddress: params.accountAddress,
146
- groups,
147
- tree,
148
- ratifierType,
149
- ratifier,
150
- payload: await Payload.encode(items),
151
- };
152
- };
153
- const getPostWithdrawalCollateral = (params) => {
154
- const market = params.marketData.params;
155
- const collateralWithdrawals = params.collateralWithdrawals ?? [];
156
- const postCollateral = Array.from({ length: market.collateralParams.length }, (_, index) => params.positionData.collateral[index] ?? 0n);
157
- let withdrawAmount = 0n;
158
- for (const withdrawal of collateralWithdrawals) {
159
- // Reject unconfigured collateral indexes before updating postCollateral.
160
- MarketUtils.getCollateralByIndex(market, withdrawal.collateralIndex);
161
- const index = Number(withdrawal.collateralIndex);
162
- const available = postCollateral[index] ?? 0n;
163
- const amount = withdrawal.assets === maxUint256 ? available : withdrawal.assets;
164
- if (amount > available) {
165
- throw new WithdrawExceedsCollateralError({
166
- withdrawAmount: amount,
167
- available,
168
- market: params.marketData.id,
169
- });
170
- }
171
- postCollateral[index] = available - amount;
172
- withdrawAmount += amount;
173
- }
174
- return { postCollateral, withdrawAmount };
175
- };
176
- const validateMarketData = (market, chainId) => {
177
- // Reject snapshots from another chain deployment before exposing requirements.
178
- validateMidnightMarket({ market, chainId });
179
- };
20
+ import { parseCancelOffersParams, parseRedeemParams, parseRepayWithdrawCollateralParams, parseSupplyCollateralBatchParams, parseSupplyCollateralParams, parseSupplyCollateralTakeBorrowParams, parseTakeBorrowParams, parseTakeLendParams, parseTakeRepayWithdrawCollateralParams, parseTakeWithdrawParams, parseWithdrawCollateralBatchParams, parseWithdrawCollateralParams, validatePositionBinding, } from "./parse.js";
21
+ import { getOffersDataInternal, parseGetOffersDataParams, parseMakeBorrowParams, parseMakeLendParams, parseMakeRepayParams, parseMakeWithdrawParams, parseSupplyBlueMakeLendParams, parseSupplyCollateralMakeBorrowParams, } from "./prepare.js";
180
22
  /**
181
23
  * Entity facade for Midnight fixed-rate action flows.
182
24
  *
@@ -226,7 +68,7 @@ export class MorphoMidnight {
226
68
  * ```
227
69
  */
228
70
  async getMarketData(marketId, parameters) {
229
- await validateClientChainId(this.client.viemClient, this.chainId);
71
+ await createChainCheck(this.client.viemClient, this.chainId)();
230
72
  return await fetchMarket(this.client.viemClient, {
231
73
  ...parameters,
232
74
  marketId,
@@ -255,7 +97,7 @@ export class MorphoMidnight {
255
97
  * ```
256
98
  */
257
99
  async getPositionData(params) {
258
- await validateClientChainId(this.client.viemClient, this.chainId);
100
+ await createChainCheck(this.client.viemClient, this.chainId)();
259
101
  return fetchAccrualPosition(this.client.viemClient, {
260
102
  ...params.parameters,
261
103
  deployless: this.client.options.supportDeployless,
@@ -312,11 +154,8 @@ export class MorphoMidnight {
312
154
  * ```
313
155
  */
314
156
  async getOffersData(params) {
315
- return getOffersDataInternal({
316
- client: this.client,
317
- chainId: this.chainId,
318
- params,
319
- });
157
+ const context = { client: this.client, chainId: this.chainId };
158
+ return getOffersDataInternal(parseGetOffersDataParams(params, context), context);
320
159
  }
321
160
  /**
322
161
  * Prepares a `MidnightBundlesV2` buy that lends into borrow-side offers for `accountAddress`.
@@ -357,6 +196,7 @@ export class MorphoMidnight {
357
196
  * @throws {NonPositiveInputError} when the target amount, `minUnits` or `maxBuyerAssets` is not positive.
358
197
  * @throws {NegativeInputError} when a takeable offer cap, `maxContinuousFee`,
359
198
  * `referralFeePct` or `nativeAmount` is negative.
199
+ * @throws {InvalidMidnightNativeAmountTypeError} when `nativeAmount` is supplied as a non-bigint.
360
200
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
361
201
  * @throws {NativeAmountOnNonWNativeAssetError} when `marketData.params.loanToken` is not wNative.
362
202
  * @throws {UnboundedMidnightTakeInputError} when `target.units` or
@@ -392,56 +232,45 @@ export class MorphoMidnight {
392
232
  * });
393
233
  * ```
394
234
  */
395
- takeLend(params) {
396
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
397
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
398
- // Reject the zero account before preparing anything for it.
399
- validateMidnightAccount("accountAddress", params.accountAddress);
400
- const now = params.now ?? Time.timestamp();
401
- validateTakeDeadlineWindow(params.deadline, now);
402
- const market = params.marketData.params;
403
- const rawParams = {
235
+ takeLend(raw) {
236
+ const params = parseTakeLendParams(raw, {
237
+ client: this.client,
404
238
  chainId: this.chainId,
405
- market,
406
- target: params.target,
407
- nativeAmount: params.nativeAmount,
408
- takeableOffers: params.takeableOffers,
409
- maxContinuousFee: params.maxContinuousFee,
410
- deadline: params.deadline,
411
- referralFeePct: params.referralFeePct,
412
- referralFeeRecipient: params.referralFeeRecipient,
413
- metadata,
414
- };
415
- let tx = midnightTakeLend(rawParams);
239
+ });
240
+ const parsed = params;
241
+ const { accountAddress } = params;
242
+ const market = parsed.market;
243
+ let tx = encodeMidnightTakeLend(parsed);
416
244
  const takeableOffers = validateMidnightTakeFeasibility({
417
245
  side: "buy",
418
- takeableOffers: params.takeableOffers,
419
- accountAddress: params.accountAddress,
246
+ takeableOffers: parsed.takeableOffers,
247
+ accountAddress: accountAddress,
420
248
  marketData: params.marketData,
421
249
  now: params.now ?? Time.timestamp(),
422
- deadline: params.deadline,
423
- referralFeePct: tx.action.args.referralFeePct,
250
+ deadline: parsed.deadline,
251
+ referralFeePct: parsed.referralFeePct,
424
252
  fallbackUnits: 0n,
425
- target: params.target,
426
- maxContinuousFee: params.maxContinuousFee,
253
+ target: parsed.target,
254
+ maxContinuousFee: parsed.maxContinuousFee,
427
255
  });
428
- if (takeableOffers !== params.takeableOffers) {
429
- tx = midnightTakeLend({ ...rawParams, takeableOffers });
256
+ if (takeableOffers !== parsed.takeableOffers) {
257
+ tx = encodeMidnightTakeLend(parsed, takeableOffers.map((offer) => parsed.takeableOffers.indexOf(offer)));
430
258
  }
431
- const pulledAssets = params.target.type === "assets"
432
- ? params.target.assets
433
- : params.target.maxBuyerAssets;
259
+ const pulledAssets = parsed.target.type === "assets"
260
+ ? parsed.target.assets
261
+ : parsed.target.maxBuyerAssets;
434
262
  return {
435
263
  getRequirements: async (_requirementsParams) => {
436
- const approvals = await getMidnightApprovalRequirements({
264
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
265
+ const approvals = await getParsedMidnightApprovalRequirements(parseMidnightApprovalRequirements({
437
266
  viemClient: this.client.viemClient,
438
267
  chainId: this.chainId,
439
268
  token: market.loanToken,
440
- owner: params.accountAddress,
269
+ owner: accountAddress,
441
270
  spender: tx.to,
442
271
  amount: pulledAssets,
443
- });
444
- const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
272
+ }), chainCheck);
273
+ const authorization = await this.getBundlesV2AuthorizationRequirements(accountAddress, chainCheck);
445
274
  return [...approvals, ...authorization];
446
275
  },
447
276
  buildTx: () => tx,
@@ -542,33 +371,22 @@ export class MorphoMidnight {
542
371
  * });
543
372
  * ```
544
373
  */
545
- takeBorrow(params) {
546
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
547
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
548
- // Reject the zero account before preparing anything for it.
549
- validateMidnightAccount("accountAddress", params.accountAddress);
550
- const now = params.now ?? Time.timestamp();
551
- validateTakeDeadlineWindow(params.deadline, now);
552
- const rawParams = {
374
+ takeBorrow(raw) {
375
+ const params = parseTakeBorrowParams(raw, {
376
+ client: this.client,
553
377
  chainId: this.chainId,
554
- market: params.marketData.params,
555
- target: params.target,
556
- receiver: params.receiver ?? params.accountAddress,
557
- takeableOffers: params.takeableOffers,
558
- deadline: params.deadline,
559
- referralFeePct: params.referralFeePct,
560
- referralFeeRecipient: params.referralFeeRecipient,
561
- metadata,
562
- };
563
- let tx = midnightTakeBorrow(rawParams);
378
+ });
379
+ const parsed = params;
380
+ const { accountAddress } = params;
381
+ let tx = encodeMidnightTakeBorrow(parsed);
564
382
  validatePositionBinding({
565
383
  positionData: params.positionData,
566
- accountAddress: params.accountAddress,
384
+ accountAddress: accountAddress,
567
385
  marketData: params.marketData,
568
386
  });
569
- const requestedUnits = params.target.type === "units"
570
- ? params.target.units
571
- : params.target.maxUnits;
387
+ const requestedUnits = parsed.target.type === "units"
388
+ ? parsed.target.units
389
+ : parsed.target.maxUnits;
572
390
  const postDebt = params.positionData.debt + requestedUnits;
573
391
  if (postDebt > 0n) {
574
392
  const maxSafeDebt = getMidnightMaxSafeDebt({
@@ -582,23 +400,23 @@ export class MorphoMidnight {
582
400
  }
583
401
  const takeableOffers = validateMidnightTakeFeasibility({
584
402
  side: "sell",
585
- takeableOffers: params.takeableOffers,
586
- accountAddress: params.accountAddress,
403
+ takeableOffers: parsed.takeableOffers,
404
+ accountAddress: accountAddress,
587
405
  marketData: params.marketData,
588
- now,
589
- deadline: params.deadline,
590
- referralFeePct: tx.action.args.referralFeePct,
406
+ now: params.now ?? Time.timestamp(),
407
+ deadline: parsed.deadline,
408
+ referralFeePct: parsed.referralFeePct,
591
409
  // Credit is withdrawn first, up to the market's withdrawable liquidity.
592
410
  fallbackUnits: MathLib.min(params.positionData.credit, params.marketData.withdrawable),
593
411
  credit: params.positionData.credit,
594
- target: params.target,
412
+ target: parsed.target,
595
413
  increasesDebt: true,
596
414
  });
597
- if (takeableOffers !== params.takeableOffers) {
598
- tx = midnightTakeBorrow({ ...rawParams, takeableOffers });
415
+ if (takeableOffers !== parsed.takeableOffers) {
416
+ tx = encodeMidnightTakeBorrow(parsed, takeableOffers.map((offer) => parsed.takeableOffers.indexOf(offer)));
599
417
  }
600
418
  return {
601
- getRequirements: () => this.getBundlesV2AuthorizationRequirements(params.accountAddress),
419
+ getRequirements: () => this.getBundlesV2AuthorizationRequirements(accountAddress),
602
420
  buildTx: () => tx,
603
421
  };
604
422
  }
@@ -671,43 +489,32 @@ export class MorphoMidnight {
671
489
  * });
672
490
  * ```
673
491
  */
674
- takeWithdraw(params) {
675
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
676
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
677
- // Reject the zero account before preparing anything for it.
678
- validateMidnightAccount("accountAddress", params.accountAddress);
679
- const now = params.now ?? Time.timestamp();
680
- validateTakeDeadlineWindow(params.deadline, now);
681
- const rawParams = {
492
+ takeWithdraw(raw) {
493
+ const params = parseTakeWithdrawParams(raw, {
494
+ client: this.client,
682
495
  chainId: this.chainId,
683
- market: params.marketData.params,
684
- target: params.target,
685
- receiver: params.receiver ?? params.accountAddress,
686
- takeableOffers: params.takeableOffers,
687
- deadline: params.deadline,
688
- referralFeePct: params.referralFeePct,
689
- referralFeeRecipient: params.referralFeeRecipient,
690
- metadata,
691
- };
692
- let tx = midnightTakeWithdraw(rawParams);
496
+ });
497
+ const parsed = params;
498
+ const { accountAddress } = params;
499
+ let tx = encodeMidnightTakeWithdraw(parsed);
693
500
  const takeableOffers = validateMidnightTakeFeasibility({
694
501
  side: "sell",
695
- takeableOffers: params.takeableOffers,
696
- accountAddress: params.accountAddress,
502
+ takeableOffers: parsed.takeableOffers,
503
+ accountAddress: accountAddress,
697
504
  marketData: params.marketData,
698
505
  now: params.now ?? Time.timestamp(),
699
- deadline: params.deadline,
700
- referralFeePct: tx.action.args.referralFeePct,
506
+ deadline: parsed.deadline,
507
+ referralFeePct: parsed.referralFeePct,
701
508
  // The bundle redeems credit first, up to the market's withdrawable liquidity.
702
509
  fallbackUnits: params.marketData.withdrawable,
703
- target: params.target,
510
+ target: parsed.target,
704
511
  increasesDebt: false,
705
512
  });
706
- if (takeableOffers !== params.takeableOffers) {
707
- tx = midnightTakeWithdraw({ ...rawParams, takeableOffers });
513
+ if (takeableOffers !== parsed.takeableOffers) {
514
+ tx = encodeMidnightTakeWithdraw(parsed, takeableOffers.map((offer) => parsed.takeableOffers.indexOf(offer)));
708
515
  }
709
516
  return {
710
- getRequirements: () => this.getBundlesV2AuthorizationRequirements(params.accountAddress),
517
+ getRequirements: () => this.getBundlesV2AuthorizationRequirements(accountAddress),
711
518
  buildTx: () => tx,
712
519
  };
713
520
  }
@@ -770,6 +577,7 @@ export class MorphoMidnight {
770
577
  * @throws {NonPositiveInputError} when a supply amount, the target amount, `maxUnits` or `minSellerAssets` is not positive.
771
578
  * @throws {NegativeInputError} when a takeable offer cap, `referralFeePct` or `nativeAmount`
772
579
  * is negative.
580
+ * @throws {InvalidMidnightNativeAmountTypeError} when `nativeAmount` is supplied as a non-bigint.
773
581
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
774
582
  * @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
775
583
  * @throws {UnboundedMidnightTakeInputError} when `target.units` or
@@ -807,43 +615,28 @@ export class MorphoMidnight {
807
615
  * });
808
616
  * ```
809
617
  */
810
- supplyCollateralTakeBorrow(params) {
811
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
812
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
813
- // Reject the zero account before preparing anything for it.
814
- validateMidnightAccount("accountAddress", params.accountAddress);
815
- const now = params.now ?? Time.timestamp();
816
- validateTakeDeadlineWindow(params.deadline, now);
817
- const market = params.marketData.params;
818
- const rawParams = {
618
+ supplyCollateralTakeBorrow(raw) {
619
+ const params = parseSupplyCollateralTakeBorrowParams(raw, {
620
+ client: this.client,
819
621
  chainId: this.chainId,
820
- market,
821
- collateralSupplies: params.collateralSupplies,
822
- nativeAmount: params.nativeAmount,
823
- target: params.target,
824
- receiver: params.receiver ?? params.accountAddress,
825
- takeableOffers: params.takeableOffers,
826
- deadline: params.deadline,
827
- referralFeePct: params.referralFeePct,
828
- referralFeeRecipient: params.referralFeeRecipient,
829
- metadata,
830
- };
831
- let tx = midnightSupplyCollateralTakeBorrow(rawParams);
622
+ });
623
+ const parsed = params;
624
+ const { accountAddress } = params;
625
+ const market = parsed.market;
626
+ let tx = encodeMidnightSupplyCollateralTakeBorrow(parsed);
832
627
  validatePositionBinding({
833
628
  positionData: params.positionData,
834
- accountAddress: params.accountAddress,
629
+ accountAddress: accountAddress,
835
630
  marketData: params.marketData,
836
631
  });
837
632
  const postCollateral = Array.from({ length: market.collateralParams.length }, (_, index) => params.positionData.collateral[index] ?? 0n);
838
- for (const { collateralIndex, assets } of params.collateralSupplies) {
839
- // Reject unconfigured collateral indexes before updating postCollateral.
840
- MarketUtils.getCollateralByIndex(market, collateralIndex);
633
+ for (const { collateralIndex, assets } of parsed.collateralSupplies) {
841
634
  const index = Number(collateralIndex);
842
635
  postCollateral[index] = (postCollateral[index] ?? 0n) + assets;
843
636
  }
844
- const requestedUnits = params.target.type === "units"
845
- ? params.target.units
846
- : params.target.maxUnits;
637
+ const requestedUnits = parsed.target.type === "units"
638
+ ? parsed.target.units
639
+ : parsed.target.maxUnits;
847
640
  const postDebt = params.positionData.debt + requestedUnits;
848
641
  if (postDebt > 0n) {
849
642
  const maxSafeDebt = getMidnightMaxSafeDebt({
@@ -857,39 +650,38 @@ export class MorphoMidnight {
857
650
  }
858
651
  const takeableOffers = validateMidnightTakeFeasibility({
859
652
  side: "sell",
860
- takeableOffers: params.takeableOffers,
861
- accountAddress: params.accountAddress,
653
+ takeableOffers: parsed.takeableOffers,
654
+ accountAddress: accountAddress,
862
655
  marketData: params.marketData,
863
- now,
864
- deadline: params.deadline,
865
- referralFeePct: tx.action.args.referralFeePct,
656
+ now: params.now ?? Time.timestamp(),
657
+ deadline: parsed.deadline,
658
+ referralFeePct: parsed.referralFeePct,
866
659
  // Credit is withdrawn first, up to the market's withdrawable liquidity.
867
660
  fallbackUnits: MathLib.min(params.positionData.credit, params.marketData.withdrawable),
868
661
  credit: params.positionData.credit,
869
- target: params.target,
662
+ target: parsed.target,
870
663
  increasesDebt: true,
871
664
  });
872
- if (takeableOffers !== params.takeableOffers) {
873
- tx = midnightSupplyCollateralTakeBorrow({ ...rawParams, takeableOffers });
665
+ if (takeableOffers !== parsed.takeableOffers) {
666
+ tx = encodeMidnightSupplyCollateralTakeBorrow(parsed, takeableOffers.map((offer) => parsed.takeableOffers.indexOf(offer)));
874
667
  }
875
668
  // Sum per token so a token supplied at several indices gets one approval.
876
669
  const collateralAmounts = new Map();
877
- for (const { collateralIndex, assets } of tx.action.args
878
- .collateralSupplies) {
879
- const { token } = MarketUtils.getCollateralByIndex(market, collateralIndex);
670
+ for (const { token, assets } of parsed.collateralSupplies) {
880
671
  collateralAmounts.set(token, (collateralAmounts.get(token) ?? 0n) + assets);
881
672
  }
882
673
  return {
883
674
  getRequirements: async (_requirementsParams) => {
884
- const approvals = await Promise.all([...collateralAmounts].map(([token, amount]) => getMidnightApprovalRequirements({
675
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
676
+ const approvals = await Promise.all([...collateralAmounts].map(async ([token, amount]) => getParsedMidnightApprovalRequirements(parseMidnightApprovalRequirements({
885
677
  viemClient: this.client.viemClient,
886
678
  chainId: this.chainId,
887
679
  token,
888
- owner: params.accountAddress,
680
+ owner: accountAddress,
889
681
  spender: tx.to,
890
682
  amount,
891
- })));
892
- const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
683
+ }), chainCheck)));
684
+ const authorization = await this.getBundlesV2AuthorizationRequirements(accountAddress, chainCheck);
893
685
  return [...approvals.flat(), ...authorization];
894
686
  },
895
687
  buildTx: () => tx,
@@ -954,6 +746,7 @@ export class MorphoMidnight {
954
746
  * bundle accepts `uint256`, but a higher ceiling gives no slippage protection); when
955
747
  * `maxContinuousFee` exceeds `uint256`; or when `nativeAmount` exceeds the maximum wNative
956
748
  * amount this call can pull, including zero for a withdraw-only call.
749
+ * @throws {InvalidMidnightNativeAmountTypeError} when `nativeAmount` is supplied as a non-bigint.
957
750
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
958
751
  * @throws {NativeAmountOnNonWNativeAssetError} when `marketData.params.loanToken` is not wNative.
959
752
  * @throws {UnknownCollateralIndexError} when a withdrawal targets a collateral index not configured on the market.
@@ -1003,40 +796,40 @@ export class MorphoMidnight {
1003
796
  * });
1004
797
  * ```
1005
798
  */
1006
- takeRepayWithdrawCollateral(params) {
1007
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
1008
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
1009
- // Reject the zero account before preparing anything for it.
1010
- validateMidnightAccount("accountAddress", params.accountAddress);
1011
- const now = params.now ?? Time.timestamp();
1012
- validateTakeDeadlineWindow(params.deadline, now);
1013
- const market = params.marketData.params;
1014
- const rawParams = {
799
+ takeRepayWithdrawCollateral(raw) {
800
+ const params = parseTakeRepayWithdrawCollateralParams(raw, {
801
+ client: this.client,
1015
802
  chainId: this.chainId,
1016
- market,
1017
- target: params.target,
1018
- nativeAmount: params.nativeAmount,
1019
- takeableOffers: params.takeableOffers,
1020
- repayEnabled: params.repayEnabled,
1021
- collateralWithdrawals: params.collateralWithdrawals ?? [],
1022
- collateralReceiver: params.collateralReceiver ?? params.accountAddress,
1023
- maxContinuousFee: params.maxContinuousFee,
1024
- deadline: params.deadline,
1025
- referralFeePct: params.referralFeePct,
1026
- referralFeeRecipient: params.referralFeeRecipient,
1027
- metadata,
1028
- };
1029
- let tx = midnightTakeRepayWithdrawCollateral(rawParams);
803
+ });
804
+ const parsed = params;
805
+ const { accountAddress } = params;
806
+ const market = parsed.market;
807
+ let tx = encodeMidnightTakeRepayWithdrawCollateral(parsed);
1030
808
  validatePositionBinding({
1031
809
  positionData: params.positionData,
1032
- accountAddress: params.accountAddress,
810
+ accountAddress: accountAddress,
1033
811
  marketData: params.marketData,
1034
812
  });
1035
- const collateralWithdrawals = params.collateralWithdrawals ?? [];
1036
- const { postCollateral, withdrawAmount } = getPostWithdrawalCollateral(params);
1037
- const debtReduction = params.target.type === "units"
1038
- ? params.target.units
1039
- : params.target.minUnits;
813
+ const collateralWithdrawals = parsed.collateralWithdrawals;
814
+ const postCollateral = Array.from({ length: market.collateralParams.length }, (_, index) => params.positionData.collateral[index] ?? 0n);
815
+ let withdrawAmount = 0n;
816
+ for (const withdrawal of collateralWithdrawals) {
817
+ const index = Number(withdrawal.collateralIndex);
818
+ const available = postCollateral[index] ?? 0n;
819
+ const amount = withdrawal.assets === maxUint256 ? available : withdrawal.assets;
820
+ if (amount > available) {
821
+ throw new WithdrawExceedsCollateralError({
822
+ withdrawAmount: amount,
823
+ available,
824
+ market: params.marketData.id,
825
+ });
826
+ }
827
+ postCollateral[index] = available - amount;
828
+ withdrawAmount += amount;
829
+ }
830
+ const debtReduction = parsed.target.type === "units"
831
+ ? parsed.target.units
832
+ : parsed.target.minUnits;
1040
833
  const postDebt = debtReduction >= params.positionData.debt
1041
834
  ? 0n
1042
835
  : params.positionData.debt - debtReduction;
@@ -1056,38 +849,36 @@ export class MorphoMidnight {
1056
849
  }
1057
850
  const takeableOffers = validateMidnightTakeFeasibility({
1058
851
  side: "buy",
1059
- takeableOffers: params.takeableOffers,
1060
- accountAddress: params.accountAddress,
852
+ takeableOffers: parsed.takeableOffers,
853
+ accountAddress: accountAddress,
1061
854
  marketData: params.marketData,
1062
855
  now: params.now ?? Time.timestamp(),
1063
- deadline: params.deadline,
1064
- referralFeePct: tx.action.args.referralFeePct,
856
+ deadline: parsed.deadline,
857
+ referralFeePct: parsed.referralFeePct,
1065
858
  // With repayEnabled the bundle repays the unfilled debt directly, at par.
1066
- fallbackUnits: params.repayEnabled ? params.positionData.debt : 0n,
1067
- target: params.target,
1068
- maxContinuousFee: params.maxContinuousFee,
859
+ fallbackUnits: parsed.repayEnabled ? params.positionData.debt : 0n,
860
+ target: parsed.target,
861
+ maxContinuousFee: parsed.maxContinuousFee,
1069
862
  debt: params.positionData.debt,
1070
863
  });
1071
- if (takeableOffers !== params.takeableOffers) {
1072
- tx = midnightTakeRepayWithdrawCollateral({
1073
- ...rawParams,
1074
- takeableOffers,
1075
- });
864
+ if (takeableOffers !== parsed.takeableOffers) {
865
+ tx = encodeMidnightTakeRepayWithdrawCollateral(parsed, takeableOffers.map((offer) => parsed.takeableOffers.indexOf(offer)));
1076
866
  }
1077
- const pulledAssets = params.target.type === "assets"
1078
- ? params.target.assets
1079
- : params.target.maxBuyerAssets;
867
+ const pulledAssets = parsed.target.type === "assets"
868
+ ? parsed.target.assets
869
+ : parsed.target.maxBuyerAssets;
1080
870
  return {
1081
871
  getRequirements: async (_requirementsParams) => {
1082
- const approvals = await getMidnightApprovalRequirements({
872
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
873
+ const approvals = await getParsedMidnightApprovalRequirements(parseMidnightApprovalRequirements({
1083
874
  viemClient: this.client.viemClient,
1084
875
  chainId: this.chainId,
1085
876
  token: market.loanToken,
1086
- owner: params.accountAddress,
877
+ owner: accountAddress,
1087
878
  spender: tx.to,
1088
879
  amount: pulledAssets,
1089
- });
1090
- const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
880
+ }), chainCheck);
881
+ const authorization = await this.getBundlesV2AuthorizationRequirements(accountAddress, chainCheck);
1091
882
  return [...approvals, ...authorization];
1092
883
  },
1093
884
  buildTx: () => tx,
@@ -1138,28 +929,15 @@ export class MorphoMidnight {
1138
929
  * const tx = output.buildTx();
1139
930
  * ```
1140
931
  */
1141
- withdrawCollateral(params) {
1142
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
1143
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
1144
- // Reject invalid owners before preparing the direct call.
1145
- validateMidnightAccount("accountAddress", params.accountAddress);
1146
- validateMarketData(params.marketData, this.chainId);
1147
- validatePositionBinding(params);
1148
- const collateralIndex = params.collateralIndex ?? 0n;
1149
- // Reject unconfigured indexes before reading the position balance.
1150
- MarketUtils.getCollateralByIndex(params.marketData.params, collateralIndex);
1151
- const index = Number(collateralIndex);
1152
- const available = params.positionData.collateral[index] ?? 0n;
1153
- const assets = params.assets === maxUint256 ? available : params.assets;
1154
- const tx = midnightWithdrawCollateral({
932
+ withdrawCollateral(raw) {
933
+ const params = parseWithdrawCollateralParams(raw, {
934
+ client: this.client,
1155
935
  chainId: this.chainId,
1156
- market: params.marketData.params,
1157
- collateralIndex,
1158
- assets,
1159
- onBehalf: params.accountAddress,
1160
- receiver: params.receiver ?? params.accountAddress,
1161
- metadata,
1162
936
  });
937
+ const parsed = params;
938
+ const { assets, available, collateralIndex } = params;
939
+ const index = Number(collateralIndex);
940
+ const tx = encodeMidnightWithdrawCollateral(parsed);
1163
941
  if (assets > available) {
1164
942
  throw new WithdrawExceedsCollateralError({
1165
943
  withdrawAmount: assets,
@@ -1230,33 +1008,14 @@ export class MorphoMidnight {
1230
1008
  * const tx = output.buildTx();
1231
1009
  * ```
1232
1010
  */
1233
- withdrawCollateralBatch(params) {
1234
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
1235
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
1236
- // Reject invalid owners before preparing the direct call.
1237
- validateMidnightAccount("accountAddress", params.accountAddress);
1238
- validateMarketData(params.marketData, this.chainId);
1239
- validatePositionBinding(params);
1240
- // Direct batches reject duplicates instead of summing them.
1241
- validateMidnightCollateralBatch(params.collateralWithdrawals, new EmptyMidnightCollateralWithdrawalsError());
1242
- const collateralWithdrawals = params.collateralWithdrawals.map(({ collateralIndex, assets }) => {
1243
- // Reject unconfigured indexes before reading the position balance.
1244
- MarketUtils.getCollateralByIndex(params.marketData.params, collateralIndex);
1245
- return {
1246
- collateralIndex,
1247
- assets: assets === maxUint256
1248
- ? (params.positionData.collateral[Number(collateralIndex)] ?? 0n)
1249
- : assets,
1250
- };
1251
- });
1252
- const tx = midnightWithdrawCollateralBatch({
1011
+ withdrawCollateralBatch(raw) {
1012
+ const params = parseWithdrawCollateralBatchParams(raw, {
1013
+ client: this.client,
1253
1014
  chainId: this.chainId,
1254
- market: params.marketData.params,
1255
- collateralWithdrawals,
1256
- onBehalf: params.accountAddress,
1257
- receiver: params.receiver ?? params.accountAddress,
1258
- metadata,
1259
1015
  });
1016
+ const { collateralWithdrawals } = params;
1017
+ // Withdrawal batches historically encode eagerly, before balance and health checks.
1018
+ const tx = encodeMidnightWithdrawCollateralBatch(params);
1260
1019
  const collateral = Array.from({ length: params.marketData.params.collateralParams.length }, (_, i) => params.positionData.collateral[i] ?? 0n);
1261
1020
  for (const { collateralIndex, assets } of collateralWithdrawals) {
1262
1021
  const index = Number(collateralIndex);
@@ -1289,7 +1048,6 @@ export class MorphoMidnight {
1289
1048
  /**
1290
1049
  * Prepares a direct collateral supply using a caller-provided market snapshot.
1291
1050
  *
1292
- * @param params - Supplier, market snapshot, collateral amount, reserve, and optional collateral index.
1293
1051
  * @param params.accountAddress - Account receiving the supplied collateral position. It must send
1294
1052
  * the transaction: Midnight pulls the collateral from `msg.sender` and only lets the position owner
1295
1053
  * or its operators supply for it, and the approval requirements are resolved for this account.
@@ -1301,19 +1059,24 @@ export class MorphoMidnight {
1301
1059
  * @param params.collateralIndex - Optional collateral index; defaults to `0n`. Indexes follow the
1302
1060
  * market's collateral parameters, which Midnight sorts by token address, not the order they were
1303
1061
  * listed in when the market was built; check `marketData.getCollateralByIndex(index).token`.
1062
+ * @param params.now - Optional reference timestamp in seconds; used for metadata only when the
1063
+ * client sets `metadata.timestamp: true`.
1304
1064
  * @returns Lazy token-approval requirements and a synchronous transaction builder.
1065
+ * @throws {NegativeInputError} when the resolved metadata timestamp is negative, or the reserve is negative.
1066
+ * @throws {InputExceedsMaxError} when the resolved metadata timestamp exceeds `uint32`, the
1067
+ * collateral exceeds `uint128`, or the collateral plus reserve exceeds `uint256` in `getRequirements()`.
1305
1068
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
1306
1069
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
1307
1070
  * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as a malformed `bytes32` or an out-of-range integer.
1308
- * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1309
- * RPC read fails.
1071
+ * @throws {UnsupportedChainIdError} when the chain has no address registry.
1072
+ * @throws {UnknownAddressError} when Midnight is not registered on the chain.
1310
1073
  * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
1311
1074
  * @throws {NonPositiveInputError} when `collateralAssets` is non-positive.
1312
- * @throws {InputExceedsMaxError} when `collateralAssets` exceeds `uint128`.
1313
- * @throws {NegativeInputError} when `reservedCollateralAssets` is negative.
1075
+ * @throws {UnknownCollateralIndexError} when the selected collateral is not configured.
1314
1076
  * @throws {MidnightZeroOnBehalfError} from `getRequirements()` and `buildTx()` when `accountAddress`
1315
1077
  * is the zero address.
1316
- * @throws {UnknownCollateralIndexError} when the selected collateral is not configured.
1078
+ * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
1079
+ * RPC read fails.
1317
1080
  * @example
1318
1081
  * ```ts
1319
1082
  * const output = midnight.supplyCollateral({
@@ -1323,42 +1086,171 @@ export class MorphoMidnight {
1323
1086
  * });
1324
1087
  * ```
1325
1088
  */
1326
- supplyCollateral(params) {
1089
+ supplyCollateral(raw) {
1090
+ const params = parseSupplyCollateralParams(raw, {
1091
+ client: this.client,
1092
+ chainId: this.chainId,
1093
+ });
1094
+ if ("error" in params) {
1095
+ const { error } = params;
1096
+ return {
1097
+ getRequirements: async () => {
1098
+ throw error;
1099
+ },
1100
+ buildTx: () => {
1101
+ throw error;
1102
+ },
1103
+ };
1104
+ }
1105
+ const { assets, onBehalf, reservedCollateralAssets } = params;
1106
+ const midnight = getChainAddress(this.chainId, "midnight");
1107
+ return {
1108
+ getRequirements: async (_requirementsParams) => {
1109
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
1110
+ return await getParsedMidnightApprovalRequirements(parseMidnightApprovalRequirements({
1111
+ viemClient: this.client.viemClient,
1112
+ chainId: this.chainId,
1113
+ token: params.token,
1114
+ owner: onBehalf,
1115
+ spender: midnight,
1116
+ amount: assets + reservedCollateralAssets,
1117
+ }), chainCheck);
1118
+ },
1119
+ buildTx: () => encodeMidnightSupplyCollateral(params),
1120
+ };
1121
+ }
1122
+ /**
1123
+ * Wraps a positive native amount and supplies the full wNative collateral in one bundle.
1124
+ * `accountAddress` must send the transaction; the bundle credits the sender.
1125
+ * The approval covers the full collateral plus the reserve, even with full native funding.
1126
+ * Requirements recheck a finite deadline against the latest block before reading permissions.
1127
+ *
1128
+ * Validation checks metadata, then the chain, account address, market, and collateral amount
1129
+ * and reserve. It resolves the collateral index before the builder checks for a zero account,
1130
+ * validates native funding, and checks the deadline's bounds. The entity then checks expiry.
1131
+ *
1132
+ * @param params.accountAddress - Transaction sender and collateral beneficiary.
1133
+ * @param params.marketData - Hydrated Midnight market receiving the collateral.
1134
+ * @param params.collateralAssets - Total collateral to supply, in wNative base units.
1135
+ * @param params.reservedCollateralAssets - Optional extra wNative included in the allowance check.
1136
+ * @param params.collateralIndex - Optional index of the registered wNative collateral; defaults to `0n`.
1137
+ * @param params.nativeAmount - Positive amount to wrap in wei, at most `collateralAssets`.
1138
+ * @param params.deadline - Unix timestamp in seconds after the reference time.
1139
+ * @param params.now - Optional reference timestamp in seconds for the deadline, independent of
1140
+ * metadata. It also supplies the metadata timestamp when the client sets `metadata.timestamp: true`.
1141
+ * @returns Lazy bundle approval and authorization requirements and a synchronous transaction builder.
1142
+ * @throws {NegativeInputError} when the resolved metadata timestamp or reserve is negative,
1143
+ * or when funding validation after index resolution finds a negative `nativeAmount`.
1144
+ * @throws {InputExceedsMaxError} when the resolved metadata timestamp exceeds `uint32` or
1145
+ * `collateralAssets` exceeds `uint128`; after index resolution, when `nativeAmount` exceeds
1146
+ * `collateralAssets` or `deadline` exceeds `uint256`; or in `getRequirements()` when
1147
+ * collateral plus reserve exceeds `uint256`.
1148
+ * @throws {ChainIdMismatchError} when the client or market targets another chain, or when
1149
+ * the RPC reports another chain from `getRequirements()`.
1150
+ * @throws {MidnightCalldataEncodingError} when an address is malformed or a market or bundle argument cannot be ABI-encoded.
1151
+ * @throws {UnsupportedChainIdError} when the chain has no address registry.
1152
+ * @throws {UnknownAddressError} when Midnight or MidnightBundlesV2 is not registered on the chain.
1153
+ * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
1154
+ * @throws {InvalidBigIntInputError} when `collateralAssets` or `reservedCollateralAssets` is not a bigint.
1155
+ * @throws {NonPositiveInputError} when `collateralAssets` is not positive; after index resolution,
1156
+ * when `nativeAmount` is zero or `deadline` is not positive.
1157
+ * @throws {UnknownCollateralIndexError} when `collateralIndex` is not configured on the market.
1158
+ * @throws {MidnightZeroOnBehalfError} when `accountAddress` is the zero address.
1159
+ * @throws {InvalidMidnightNativeAmountTypeError} when `nativeAmount` is supplied as a non-bigint.
1160
+ * @throws {ChainWNativeMissingError} when the chain has no wrapped-native asset.
1161
+ * @throws {NativeAmountOnNonWNativeAssetError} when the selected collateral is not wNative.
1162
+ * @throws {ExpiredDeadlineError} when the deadline is at or before the reference time,
1163
+ * or at or before the latest block's timestamp when resolving requirements.
1164
+ * @throws {viem.BaseError} from `getRequirements()` when a chain id, block, allowance or authorization read fails.
1165
+ * @example
1166
+ * ```ts
1167
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
1168
+ * import { type Address, type Hex, createPublicClient, http, maxUint256 } from "viem";
1169
+ * import { base } from "viem/chains";
1170
+ *
1171
+ * export async function supplyWithNative(
1172
+ * marketId: Hex,
1173
+ * accountAddress: Address,
1174
+ * collateralIndex: bigint,
1175
+ * sendAndConfirm: (tx: { to: Address; data: Hex; value: bigint }) => Promise<Hex>,
1176
+ * ) {
1177
+ * const client = createPublicClient({ chain: base, transport: http() }).extend(morphoViemExtension());
1178
+ * const midnight = client.morpho.midnight(base.id);
1179
+ * const marketData = await midnight.getMarketData(marketId);
1180
+ * const { getRequirements, buildTx } = midnight.supplyCollateralWithNative({
1181
+ * marketData, accountAddress, collateralIndex,
1182
+ * collateralAssets: 1_000_000_000_000_000n,
1183
+ * nativeAmount: 1_000_000_000_000_000n,
1184
+ * deadline: maxUint256,
1185
+ * });
1186
+ * // Use the wallet for accountAddress and confirm each prerequisite before supplying.
1187
+ * for (const requirement of await getRequirements()) {
1188
+ * if (!("sign" in requirement)) await sendAndConfirm(requirement);
1189
+ * }
1190
+ * return await sendAndConfirm(buildTx()); // Transaction hash (Hex)
1191
+ * }
1192
+ * ```
1193
+ */
1194
+ supplyCollateralWithNative(params) {
1327
1195
  const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
1328
1196
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1329
- // Reject a malformed account here; the builder rejects the zero account.
1330
1197
  validateMidnightAddress("accountAddress", params.accountAddress);
1331
- validateMarketData(params.marketData, this.chainId);
1332
- assertPositiveAmount("collateralAssets", params.collateralAssets);
1333
- validateMidnightUint128Field("collateralAssets", params.collateralAssets);
1334
- assertNonNegativeAmount("reservedCollateralAssets", params.reservedCollateralAssets ?? 0n);
1335
- const market = params.marketData;
1198
+ validateMidnightMarket({
1199
+ market: params.marketData,
1200
+ chainId: this.chainId,
1201
+ });
1202
+ const collateralAssets = parseMidnightNativeCollateralAmount("collateralAssets", params.collateralAssets);
1203
+ const reservedCollateralAssets = params.reservedCollateralAssets ?? 0n;
1204
+ if (typeof reservedCollateralAssets !== "bigint") {
1205
+ throw new InvalidBigIntInputError("reservedCollateralAssets", reservedCollateralAssets);
1206
+ }
1207
+ if (reservedCollateralAssets < 0n) {
1208
+ throw new NegativeInputError("reservedCollateralAssets", reservedCollateralAssets);
1209
+ }
1210
+ const market = params.marketData.params;
1336
1211
  const collateralIndex = params.collateralIndex ?? 0n;
1337
- const collateral = market.getCollateralByIndex(collateralIndex);
1338
- const midnight = getChainAddress(this.chainId, "midnight");
1212
+ // Validate the index before the builder checks for a zero account.
1213
+ MarketUtils.getCollateralByIndex(market, collateralIndex);
1214
+ const { accountAddress, nativeAmount, deadline } = params;
1215
+ const approvalAmount = collateralAssets + reservedCollateralAssets;
1216
+ const { tx, token } = prepareMidnightSupplyCollateralWithNative({
1217
+ chainId: this.chainId,
1218
+ market,
1219
+ collateralIndex,
1220
+ assets: collateralAssets,
1221
+ accountAddress,
1222
+ nativeAmount,
1223
+ deadline,
1224
+ metadata,
1225
+ });
1226
+ validateMidnightDeadline(deadline, params.now);
1339
1227
  return {
1340
1228
  getRequirements: async (_requirementsParams) => {
1341
- // Match buildTx(): the requirement helper would report a zero owner with another class.
1342
- if (isAddressEqual(params.accountAddress, zeroAddress)) {
1343
- throw new MidnightZeroOnBehalfError("onBehalf");
1229
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
1230
+ if (deadline !== maxUint256) {
1231
+ await chainCheck();
1232
+ const { timestamp } = await getBlock(this.client.viemClient, {
1233
+ blockTag: "latest",
1234
+ });
1235
+ validateMidnightDeadline(deadline, timestamp);
1344
1236
  }
1345
- return await getMidnightApprovalRequirements({
1237
+ const approval = await getParsedMidnightApprovalRequirements(parseMidnightApprovalRequirements({
1346
1238
  viemClient: this.client.viemClient,
1347
1239
  chainId: this.chainId,
1348
- token: collateral.token,
1349
- owner: params.accountAddress,
1350
- spender: midnight,
1351
- amount: params.collateralAssets + (params.reservedCollateralAssets ?? 0n),
1352
- });
1240
+ token,
1241
+ owner: accountAddress,
1242
+ spender: tx.to,
1243
+ amount: approvalAmount,
1244
+ }), chainCheck);
1245
+ const authorization = await getParsedMidnightAuthorizationRequirement(parseMidnightAuthorizationRequirement({
1246
+ viemClient: this.client.viemClient,
1247
+ chainId: this.chainId,
1248
+ owner: accountAddress,
1249
+ authorized: tx.to,
1250
+ }), chainCheck);
1251
+ return authorization ? [...approval, authorization] : approval;
1353
1252
  },
1354
- buildTx: () => midnightSupplyCollateral({
1355
- chainId: this.chainId,
1356
- market: market.params,
1357
- collateralIndex,
1358
- assets: params.collateralAssets,
1359
- onBehalf: params.accountAddress,
1360
- metadata,
1361
- }),
1253
+ buildTx: () => tx,
1362
1254
  };
1363
1255
  }
1364
1256
  /**
@@ -1388,51 +1280,42 @@ export class MorphoMidnight {
1388
1280
  * const tx = output.buildTx();
1389
1281
  * ```
1390
1282
  */
1391
- supplyCollateralBatch(params) {
1392
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
1393
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
1394
- // Reject malformed accounts before resolving token requirements.
1395
- validateMidnightAddress("accountAddress", params.accountAddress);
1396
- validateMarketData(params.marketData, this.chainId);
1397
- // Reject empty and duplicate-index batches before resolving allowance thresholds.
1398
- validateMidnightCollateralBatch(params.collateralSupplies, new EmptyMidnightCollateralSuppliesError());
1399
- for (const supply of params.collateralSupplies) {
1400
- assertPositiveAmount("assets", supply.assets);
1401
- validateMidnightUint128Field("assets", supply.assets);
1402
- assertNonNegativeAmount("reservedCollateralAssets", supply.reservedCollateralAssets ?? 0n);
1403
- // Fail eagerly for collateral absent from the supplied snapshot.
1404
- params.marketData.getCollateralByIndex(supply.collateralIndex);
1283
+ supplyCollateralBatch(raw) {
1284
+ const params = parseSupplyCollateralBatchParams(raw, {
1285
+ client: this.client,
1286
+ chainId: this.chainId,
1287
+ });
1288
+ if ("error" in params) {
1289
+ const { error } = params;
1290
+ return {
1291
+ getRequirements: async () => {
1292
+ throw error;
1293
+ },
1294
+ buildTx: () => {
1295
+ throw error;
1296
+ },
1297
+ };
1405
1298
  }
1406
1299
  const midnight = getChainAddress(this.chainId, "midnight");
1407
1300
  return {
1408
1301
  getRequirements: async (_requirementsParams) => {
1409
- if (isAddressEqual(params.accountAddress, zeroAddress)) {
1410
- throw new MidnightZeroOnBehalfError("onBehalf");
1411
- }
1412
- const amounts = new Map();
1413
- for (const supply of params.collateralSupplies) {
1414
- const token = params.marketData.getCollateralByIndex(supply.collateralIndex).token;
1415
- amounts.set(token, (amounts.get(token) ?? 0n) +
1416
- supply.assets +
1417
- (supply.reservedCollateralAssets ?? 0n));
1418
- }
1419
- const requirements = await Promise.all([...amounts].map(([token, amount]) => getMidnightApprovalRequirements({
1302
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
1303
+ const requirements = await Promise.all(params.approvals.map(async ({ token, amount }) => getParsedMidnightApprovalRequirements(parseMidnightApprovalRequirements({
1420
1304
  viemClient: this.client.viemClient,
1421
1305
  chainId: this.chainId,
1422
1306
  token,
1423
- owner: params.accountAddress,
1307
+ owner: params.onBehalf,
1424
1308
  spender: midnight,
1425
1309
  amount,
1426
- })));
1310
+ }), chainCheck)));
1427
1311
  return requirements.flat();
1428
1312
  },
1429
- buildTx: () => midnightSupplyCollateralBatch({
1430
- chainId: this.chainId,
1431
- market: params.marketData.params,
1432
- collateralSupplies: params.collateralSupplies.map(({ collateralIndex, assets }) => ({ collateralIndex, assets })),
1433
- onBehalf: params.accountAddress,
1434
- metadata,
1435
- }),
1313
+ buildTx: () => {
1314
+ if ("error" in params.action) {
1315
+ throw params.action.error;
1316
+ }
1317
+ return encodeMidnightSupplyCollateralBatch(params.action);
1318
+ },
1436
1319
  };
1437
1320
  }
1438
1321
  /**
@@ -1505,15 +1388,10 @@ export class MorphoMidnight {
1505
1388
  * ```
1506
1389
  */
1507
1390
  async makeLend(params) {
1508
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
1509
- // Reject the zero account before preparing anything for it.
1510
- validateMidnightAccount("accountAddress", params.accountAddress);
1511
- // Fails before any API read or build when the deadline has already passed.
1512
- const now = params.now ?? Time.timestamp();
1513
- validateMidnightDeadline(params.deadline, now);
1514
- const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1515
- rejectReduceOnlyOffers(tree.offers);
1516
- return this.prepareLendOffers({ ...params, offers: tree });
1391
+ return this.prepareLendOffers(await parseMakeLendParams(params, {
1392
+ client: this.client,
1393
+ chainId: this.chainId,
1394
+ }));
1517
1395
  }
1518
1396
  /**
1519
1397
  * Prepares an atomic borrow-offer publication or repost through `MidnightBundlesV2`.
@@ -1577,70 +1455,33 @@ export class MorphoMidnight {
1577
1455
  * ```
1578
1456
  */
1579
1457
  async makeBorrow(params) {
1580
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
1581
- // Reject the zero account before preparing anything for it.
1582
- validateMidnightAccount("accountAddress", params.accountAddress);
1583
- // Fails before any API read or build when the deadline has already passed.
1584
- const now = params.now ?? Time.timestamp();
1585
- validateMidnightDeadline(params.deadline, now);
1586
- const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1587
- rejectReduceOnlyOffers(tree.offers);
1588
- return this.prepareBorrowOffers({ ...params, offers: tree });
1458
+ return this.prepareBorrowOffers(await parseMakeBorrowParams(params, {
1459
+ client: this.client,
1460
+ chainId: this.chainId,
1461
+ }));
1589
1462
  }
1590
1463
  /**
1591
1464
  * Prepares lend-side offers for publication.
1592
1465
  */
1593
1466
  async prepareLendOffers(params) {
1594
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
1595
- // Reject a malformed address before viem compares offer markets with it.
1596
- validateMidnightAddress("loanToken", params.loanToken);
1597
- assertPositiveAmount("loanAssets", params.loanAssets);
1598
- assertNonNegativeAmount("reservedLoanAssets", params.reservedLoanAssets ?? 0n);
1599
- const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1600
- validateOfferSides(tree.offers, true);
1601
- validateMidnightMakerOfferCallbacks(tree.offers);
1602
- const data = await getOffersDataInternal({
1603
- client: this.client,
1604
- chainId: this.chainId,
1605
- params: { ...params, offers: tree },
1606
- });
1607
- data.tree.offers.forEach((offer, index) => {
1608
- const market = offerMarketParams(offer);
1609
- if (!isAddressEqual(market.loanToken, params.loanToken)) {
1610
- throw new MidnightOfferMarketLoanTokenMismatchError({
1611
- index,
1612
- expectedLoanToken: params.loanToken,
1613
- actualLoanToken: market.loanToken,
1614
- });
1615
- }
1616
- });
1617
- const tx = midnightCancelAndMake({
1618
- chainId: this.chainId,
1619
- cancellations: params.cancellations ?? [],
1620
- deadline: params.deadline,
1621
- metadata,
1622
- publication: {
1623
- ratifier: data.ratifier,
1624
- root: data.tree.root,
1625
- groups: data.groups,
1626
- payload: data.payload,
1627
- },
1628
- });
1467
+ const { data } = params;
1468
+ const tx = encodeMidnightCancelAndMake(params.action);
1629
1469
  const midnight = getChainAddress(this.chainId, "midnight");
1630
1470
  return {
1631
1471
  groups: data.groups,
1632
1472
  root: data.tree.root,
1633
1473
  ratifierType: data.ratifierType,
1634
1474
  getRequirements: async (_requirementsParams) => {
1635
- const approvals = await getMidnightApprovalRequirements({
1475
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
1476
+ const approvals = await getParsedMidnightApprovalRequirements(parseMidnightApprovalRequirements({
1636
1477
  viemClient: this.client.viemClient,
1637
1478
  chainId: this.chainId,
1638
1479
  token: params.loanToken,
1639
1480
  owner: data.accountAddress,
1640
1481
  spender: midnight,
1641
- amount: params.loanAssets + (params.reservedLoanAssets ?? 0n),
1642
- });
1643
- const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
1482
+ amount: params.approvalAmount,
1483
+ }), chainCheck);
1484
+ const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress, chainCheck);
1644
1485
  return [...approvals, ...authorization];
1645
1486
  },
1646
1487
  buildTx: () => tx,
@@ -1701,6 +1542,7 @@ export class MorphoMidnight {
1701
1542
  * @throws {NegativeInputError} when a `maxConsumed` ceiling or `nativeAmount` is negative.
1702
1543
  * @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds `uint128`, `deadline` exceeds
1703
1544
  * `uint256`, or `nativeAmount` exceeds `assetsToPark` when `blueMarket.loanToken` is wNative.
1545
+ * @throws {InvalidMidnightNativeAmountTypeError} when `nativeAmount` is supplied as a non-bigint.
1704
1546
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
1705
1547
  * @throws {NativeAmountOnNonWNativeAssetError} when `blueMarket.loanToken` is not wNative.
1706
1548
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
@@ -1753,106 +1595,27 @@ export class MorphoMidnight {
1753
1595
  * ```
1754
1596
  */
1755
1597
  async supplyBlueMakeLend(params) {
1756
- const suppliedNow = params.now;
1757
- const metadata = resolveTransactionMetadata(this.client.options.metadata, suppliedNow);
1758
- // Reject the zero account before preparing anything for it.
1759
- validateMidnightAccount("accountAddress", params.accountAddress);
1760
- // Reject wrong-sized salts before callback derivation pads them or any read occurs.
1761
- validateMidnightBytes32("callbackSalt", params.callbackSalt);
1762
- assertPositiveAmount("assetsToPark", params.assetsToPark);
1763
- validateMidnightUint128Field("assetsToPark", params.assetsToPark);
1764
- const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1765
- validateOfferSides(tree.offers, true);
1766
- rejectReduceOnlyOffers(tree.offers);
1767
- await validateClientChainId(this.client.viemClient, this.chainId);
1768
- // Fails before any API read or build when the deadline has already passed.
1769
- const now = suppliedNow ?? Time.timestamp();
1770
- validateMidnightDeadline(params.deadline, now);
1771
- const { callbackSalt } = params;
1772
- // Encode the whole Blue market first so a malformed field fails typed, before the RPC read.
1773
- const callbackData = wrapMidnightEncoding("blueMarket", () => getMidnightBlueBuyCallbackData(params.blueMarket));
1774
- const blueMarketId = BlueMarketUtils.getMarketId(params.blueMarket);
1775
- const callback = getMidnightBlueBuyCallbackAddress({
1776
- chainId: this.chainId,
1777
- owner: params.accountAddress,
1778
- salt: callbackSalt,
1779
- });
1780
- const [data, fetched] = await Promise.all([
1781
- getOffersDataInternal({
1782
- client: this.client,
1783
- chainId: this.chainId,
1784
- params: { ...params, offers: tree },
1785
- }),
1786
- fetchBlueMarket(blueMarketId, this.client.viemClient, {
1787
- deployless: this.client.options.supportDeployless,
1788
- }),
1789
- ]);
1790
- const market = _try(() => fetched.accrueInterest(MathLib.max(suppliedNow ?? Time.timestamp(), fetched.lastUpdate)), UnsupportedMarketIrmError) ?? fetched;
1791
- if (market.totalSupplyShares === 0n) {
1792
- throw new EmptyBlueParkingMarketError({ marketId: blueMarketId });
1793
- }
1794
- if (market.toSupplyShares(params.assetsToPark, "Down") === 0n) {
1795
- throw new ZeroBlueParkingSharesError({
1796
- marketId: blueMarketId,
1797
- assets: params.assetsToPark,
1798
- });
1799
- }
1800
- data.tree.offers.forEach((offer, index) => {
1801
- const offerMarket = offerMarketParams(offer);
1802
- if (!isAddressEqual(offerMarket.loanToken, params.blueMarket.loanToken)) {
1803
- throw new MidnightOfferMarketLoanTokenMismatchError({
1804
- index,
1805
- expectedLoanToken: params.blueMarket.loanToken,
1806
- actualLoanToken: offerMarket.loanToken,
1807
- });
1808
- }
1809
- if (!isAddressEqual(offer.callback, callback)) {
1810
- throw new MidnightOfferCallbackMismatchError({
1811
- index,
1812
- expectedCallback: callback,
1813
- actualCallback: offer.callback,
1814
- });
1815
- }
1816
- if (offer.callbackData.toLowerCase() !== callbackData.toLowerCase()) {
1817
- throw new MidnightOfferCallbackDataMismatchError({
1818
- index,
1819
- expectedCallbackData: callbackData,
1820
- actualCallbackData: offer.callbackData,
1821
- });
1822
- }
1823
- });
1824
- const tx = midnightCancelAndMake({
1598
+ const parsed = await parseSupplyBlueMakeLendParams(params, {
1599
+ client: this.client,
1825
1600
  chainId: this.chainId,
1826
- publication: {
1827
- ratifier: data.ratifier,
1828
- root: data.tree.root,
1829
- groups: data.groups,
1830
- payload: data.payload,
1831
- blueSupply: {
1832
- market: params.blueMarket,
1833
- assets: params.assetsToPark,
1834
- callbackSalt,
1835
- },
1836
- },
1837
- nativeAmount: params.nativeAmount,
1838
- cancellations: params.cancellations ?? [],
1839
- deadline: params.deadline,
1840
- metadata,
1841
1601
  });
1602
+ const { data } = parsed;
1603
+ const tx = encodeMidnightCancelAndMake(parsed.action);
1842
1604
  return {
1843
1605
  groups: data.groups,
1844
1606
  root: data.tree.root,
1845
1607
  ratifierType: data.ratifierType,
1846
1608
  getRequirements: async (_requirementsParams) => {
1847
- const approvals = await getMidnightApprovalRequirements({
1609
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
1610
+ const approvals = await getParsedMidnightApprovalRequirements(parseMidnightApprovalRequirements({
1848
1611
  viemClient: this.client.viemClient,
1849
1612
  chainId: this.chainId,
1850
- token: params.blueMarket.loanToken,
1613
+ token: parsed.loanToken,
1851
1614
  owner: data.accountAddress,
1852
1615
  spender: getChainAddress(this.chainId, "midnightBundlesV2"),
1853
- amount: params.assetsToPark,
1854
- });
1855
- const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress);
1616
+ amount: parsed.approvalAmount,
1617
+ }), chainCheck);
1618
+ const authorization = await this.getBundlesV2AuthorizationRequirements(data.accountAddress, chainCheck);
1856
1619
  return [...approvals, ...authorization];
1857
1620
  },
1858
1621
  buildTx: () => tx,
@@ -1862,27 +1625,8 @@ export class MorphoMidnight {
1862
1625
  * Prepares borrow-side offers for publication.
1863
1626
  */
1864
1627
  async prepareBorrowOffers(params) {
1865
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
1866
- const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1867
- validateOfferSides(tree.offers, false);
1868
- validateMidnightMakerOfferCallbacks(tree.offers);
1869
- const data = await getOffersDataInternal({
1870
- client: this.client,
1871
- chainId: this.chainId,
1872
- params: { ...params, offers: tree },
1873
- });
1874
- const tx = midnightCancelAndMake({
1875
- chainId: this.chainId,
1876
- cancellations: params.cancellations ?? [],
1877
- deadline: params.deadline,
1878
- metadata,
1879
- publication: {
1880
- ratifier: data.ratifier,
1881
- root: data.tree.root,
1882
- groups: data.groups,
1883
- payload: data.payload,
1884
- },
1885
- });
1628
+ const { data } = params;
1629
+ const tx = encodeMidnightCancelAndMake(params.action);
1886
1630
  return {
1887
1631
  groups: data.groups,
1888
1632
  root: data.tree.root,
@@ -1958,21 +1702,10 @@ export class MorphoMidnight {
1958
1702
  * ```
1959
1703
  */
1960
1704
  async makeWithdraw(params) {
1961
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
1962
- // Reject the zero account before preparing anything for it.
1963
- validateMidnightAccount("accountAddress", params.accountAddress);
1964
- // Fails before any API read or build when the deadline has already passed.
1965
- const now = params.now ?? Time.timestamp();
1966
- validateMidnightDeadline(params.deadline, now);
1967
- const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1968
- // Reject the wrong exit intent before calling the mempool validation API.
1969
- validateOfferSides(tree.offers, false);
1970
- for (const [index, offer] of tree.offers.entries()) {
1971
- if (!offer.reduceOnly) {
1972
- throw new MidnightOfferNotReduceOnlyError({ index });
1973
- }
1974
- }
1975
- return this.prepareBorrowOffers({ ...params, offers: tree });
1705
+ return this.prepareBorrowOffers(await parseMakeWithdrawParams(params, {
1706
+ client: this.client,
1707
+ chainId: this.chainId,
1708
+ }));
1976
1709
  }
1977
1710
  /**
1978
1711
  * Publishes reduce-only buy offers for a borrow limit exit through MidnightBundlesV2.
@@ -2050,21 +1783,10 @@ export class MorphoMidnight {
2050
1783
  * ```
2051
1784
  */
2052
1785
  async makeRepay(params) {
2053
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
2054
- // Reject the zero account before preparing anything for it.
2055
- validateMidnightAccount("accountAddress", params.accountAddress);
2056
- // Fails before any API read or build when the deadline has already passed.
2057
- const now = params.now ?? Time.timestamp();
2058
- validateMidnightDeadline(params.deadline, now);
2059
- const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
2060
- // Reject the wrong exit intent before calling the mempool validation API.
2061
- validateOfferSides(tree.offers, true);
2062
- for (const [index, offer] of tree.offers.entries()) {
2063
- if (!offer.reduceOnly) {
2064
- throw new MidnightOfferNotReduceOnlyError({ index });
2065
- }
2066
- }
2067
- return this.prepareLendOffers({ ...params, offers: tree });
1786
+ return this.prepareLendOffers(await parseMakeRepayParams(params, {
1787
+ client: this.client,
1788
+ chainId: this.chainId,
1789
+ }));
2068
1790
  }
2069
1791
  /**
2070
1792
  * Prepares an atomic borrow-offer publication or repost through `MidnightBundlesV2`,
@@ -2102,6 +1824,7 @@ export class MorphoMidnight {
2102
1824
  * @throws {InputExceedsMaxError} when a `maxConsumed` ceiling, a collateral supply amount or a
2103
1825
  * per-index sum exceeds `uint128`, `deadline` exceeds `uint256`, or `nativeAmount` exceeds the
2104
1826
  * maximum wNative collateral amount this call can pull.
1827
+ * @throws {InvalidMidnightNativeAmountTypeError} when `nativeAmount` is supplied as a non-bigint.
2105
1828
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
2106
1829
  * @throws {NativeAmountOnNonWNativeAssetError} when no collateral pull uses wNative.
2107
1830
  * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
@@ -2149,55 +1872,15 @@ export class MorphoMidnight {
2149
1872
  * ```
2150
1873
  */
2151
1874
  async supplyCollateralMakeBorrow(params) {
2152
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
2153
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
2154
- // Reject the zero account before preparing anything for it.
2155
- validateMidnightAccount("accountAddress", params.accountAddress);
2156
- // Fails before any API read or build when the deadline has already passed.
2157
- const now = params.now ?? Time.timestamp();
2158
- validateMidnightDeadline(params.deadline, now);
2159
- const market = params.collateral.market instanceof MarketParams
2160
- ? params.collateral.market
2161
- : MarketParams.from(params.collateral.market);
2162
- const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
2163
- validateOfferSides(tree.offers, false);
2164
- validateMidnightMakerOfferCallbacks(tree.offers);
2165
- rejectReduceOnlyOffers(tree.offers);
2166
- const data = await getOffersDataInternal({
1875
+ const paramsParsed = await parseSupplyCollateralMakeBorrowParams(params, {
2167
1876
  client: this.client,
2168
1877
  chainId: this.chainId,
2169
- params: { ...params, offers: tree },
2170
- marketCreationTime: "now",
2171
- });
2172
- const marketId = encodeMidnightMarketId(market);
2173
- for (const offer of data.tree.offers) {
2174
- const offerMarketId = encodeMidnightMarketId(offer.market);
2175
- if (offerMarketId.toLowerCase() !== marketId.toLowerCase()) {
2176
- throw new MarketIdMismatchError(offerMarketId, marketId);
2177
- }
2178
- }
2179
- const tx = midnightCancelAndMake({
2180
- chainId: this.chainId,
2181
- nativeAmount: params.nativeAmount,
2182
- cancellations: params.cancellations ?? [],
2183
- deadline: params.deadline,
2184
- metadata,
2185
- publication: {
2186
- ratifier: data.ratifier,
2187
- root: data.tree.root,
2188
- groups: data.groups,
2189
- payload: data.payload,
2190
- collateral: {
2191
- market,
2192
- supplies: params.collateral.supplies,
2193
- },
2194
- },
2195
1878
  });
1879
+ const { data, action: parsed } = paramsParsed;
1880
+ const tx = encodeMidnightCancelAndMake(parsed);
2196
1881
  const midnightBundlesV2 = getChainAddress(this.chainId, "midnightBundlesV2");
2197
1882
  const collateralAmounts = new Map();
2198
- for (const { collateralIndex, assets } of tx.action.args
2199
- .collateralSupplies) {
2200
- const { token } = MarketUtils.getCollateralByIndex(market, collateralIndex);
1883
+ for (const { token, assets } of parsed.collateralPulls) {
2201
1884
  collateralAmounts.set(token, (collateralAmounts.get(token) ?? 0n) + assets);
2202
1885
  }
2203
1886
  return {
@@ -2205,17 +1888,18 @@ export class MorphoMidnight {
2205
1888
  root: data.tree.root,
2206
1889
  ratifierType: data.ratifierType,
2207
1890
  getRequirements: async (_requirementsParams) => {
2208
- const approvals = await Promise.all([...collateralAmounts].map(([token, amount]) => getMidnightApprovalRequirements({
1891
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
1892
+ const approvals = await Promise.all([...collateralAmounts].map(async ([token, amount]) => getParsedMidnightApprovalRequirements(parseMidnightApprovalRequirements({
2209
1893
  viemClient: this.client.viemClient,
2210
1894
  chainId: this.chainId,
2211
1895
  token,
2212
1896
  owner: data.accountAddress,
2213
1897
  spender: midnightBundlesV2,
2214
1898
  amount,
2215
- })));
1899
+ }), chainCheck)));
2216
1900
  return [
2217
1901
  ...approvals.flat(),
2218
- ...(await this.getBundlesV2AuthorizationRequirements(data.accountAddress)),
1902
+ ...(await this.getBundlesV2AuthorizationRequirements(data.accountAddress, chainCheck)),
2219
1903
  ];
2220
1904
  },
2221
1905
  buildTx: () => tx,
@@ -2266,58 +1950,12 @@ export class MorphoMidnight {
2266
1950
  * });
2267
1951
  * ```
2268
1952
  */
2269
- redeem(params) {
2270
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
2271
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
2272
- // Reject a malformed account here; the builder rejects the zero account.
2273
- validateMidnightAddress("accountAddress", params.accountAddress);
2274
- if (!params.positionData) {
2275
- throw new MissingAccrualPositionError();
2276
- }
2277
- if (params.positionData.user != null) {
2278
- validateMidnightAddress("positionData.user", params.positionData.user);
2279
- }
2280
- if (params.positionData.user == null ||
2281
- !isAddressEqual(params.positionData.user, params.accountAddress)) {
2282
- throw new AccrualPositionUserMismatchError(params.positionData.user ?? "unbound", params.accountAddress);
2283
- }
2284
- const market = params.positionData.market;
2285
- validateMarketData(market, this.chainId);
2286
- // Apply realized losses and continuous fees the way `Midnight._updatePosition` does before a
2287
- // withdrawal; never accrue to before the snapshot's `lastAccrual`.
2288
- const now = params.now ?? Time.timestamp();
2289
- const accrued = params.positionData.accrueInterest(MathLib.max(now, params.positionData.lastAccrual));
2290
- const units = params.units ?? accrued.faceValue;
2291
- if (params.units !== undefined && units <= 0n) {
2292
- throw new NonPositiveInputError("units", units);
2293
- }
2294
- if (units <= 0n) {
2295
- throw new NoMidnightCreditToRedeemError(market.id);
2296
- }
2297
- validateMidnightUint128Field("units", units);
2298
- if (accrued.credit < units) {
2299
- throw new MidnightRedeemExceedsCreditError({
2300
- market: market.id,
2301
- units,
2302
- credit: accrued.credit,
2303
- });
2304
- }
2305
- if (market.withdrawable < units) {
2306
- throw new InsufficientMidnightWithdrawableLiquidityError({
2307
- market: market.id,
2308
- units,
2309
- withdrawable: market.withdrawable,
2310
- });
2311
- }
2312
- // Build eagerly so the receiver guard throws on this call like the other flows.
2313
- const tx = midnightRedeem({
1953
+ redeem(raw) {
1954
+ const parsed = parseRedeemParams(raw, {
1955
+ client: this.client,
2314
1956
  chainId: this.chainId,
2315
- market: market.params,
2316
- units,
2317
- onBehalf: params.accountAddress,
2318
- receiver: params.receiver,
2319
- metadata,
2320
1957
  });
1958
+ const tx = encodeMidnightRedeem(parsed);
2321
1959
  return {
2322
1960
  getRequirements: async () => [],
2323
1961
  buildTx: () => tx,
@@ -2370,6 +2008,7 @@ export class MorphoMidnight {
2370
2008
  * @throws {InputExceedsMaxError} when `repay.assets` or `repay.maxBuyerAssets` is at least
2371
2009
  * `maxUint256`, a withdrawal amount or `deadline` exceeds uint256, or `nativeAmount` exceeds
2372
2010
  * the maximum wNative amount this call can pull, including zero for a withdraw-only call.
2011
+ * @throws {InvalidMidnightNativeAmountTypeError} when `nativeAmount` is supplied as a non-bigint.
2373
2012
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
2374
2013
  * @throws {NativeAmountOnNonWNativeAssetError} when `marketData.params.loanToken` is not wNative.
2375
2014
  * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
@@ -2396,32 +2035,36 @@ export class MorphoMidnight {
2396
2035
  * });
2397
2036
  * ```
2398
2037
  */
2399
- repayWithdrawCollateral(params) {
2400
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
2401
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
2402
- // Reject the zero account before preparing anything for it.
2403
- validateMidnightAccount("accountAddress", params.accountAddress);
2404
- // Fails before any API read or build when the deadline has already passed.
2405
- const now = params.now ?? Time.timestamp();
2406
- validateMidnightDeadline(params.deadline, now);
2407
- const market = params.marketData.params;
2408
- const tx = midnightRepayWithdrawCollateral({
2038
+ repayWithdrawCollateral(raw) {
2039
+ const params = parseRepayWithdrawCollateralParams(raw, {
2040
+ client: this.client,
2409
2041
  chainId: this.chainId,
2410
- market,
2411
- repay: params.repay,
2412
- nativeAmount: params.nativeAmount,
2413
- collateralWithdrawals: params.collateralWithdrawals ?? [],
2414
- collateralReceiver: params.collateralReceiver ?? params.accountAddress,
2415
- deadline: params.deadline,
2416
- metadata,
2417
2042
  });
2043
+ const parsed = params;
2044
+ const market = params.market.struct;
2045
+ const tx = encodeMidnightRepayWithdrawCollateral(parsed);
2418
2046
  validatePositionBinding({
2419
2047
  positionData: params.positionData,
2420
2048
  accountAddress: params.accountAddress,
2421
2049
  marketData: params.marketData,
2422
2050
  });
2423
- const collateralWithdrawals = params.collateralWithdrawals ?? [];
2424
- const { postCollateral, withdrawAmount } = getPostWithdrawalCollateral(params);
2051
+ const collateralWithdrawals = parsed.collateralWithdrawals;
2052
+ const postCollateral = Array.from({ length: market.collateralParams.length }, (_, index) => params.positionData.collateral[index] ?? 0n);
2053
+ let withdrawAmount = 0n;
2054
+ for (const withdrawal of collateralWithdrawals) {
2055
+ const index = Number(withdrawal.collateralIndex);
2056
+ const available = postCollateral[index] ?? 0n;
2057
+ const amount = withdrawal.assets === maxUint256 ? available : withdrawal.assets;
2058
+ if (amount > available) {
2059
+ throw new WithdrawExceedsCollateralError({
2060
+ withdrawAmount: amount,
2061
+ available,
2062
+ market: params.marketData.id,
2063
+ });
2064
+ }
2065
+ postCollateral[index] = available - amount;
2066
+ withdrawAmount += amount;
2067
+ }
2425
2068
  // The bundle must fill the whole assets target and the direct repay is capped at the debt, so a repay above it reverts `OutOfOffers()`.
2426
2069
  if (params.repay.type === "assets" &&
2427
2070
  params.repay.assets > params.positionData.debt) {
@@ -2463,45 +2106,38 @@ export class MorphoMidnight {
2463
2106
  : params.repay.maxBuyerAssets;
2464
2107
  return {
2465
2108
  getRequirements: async (_requirementsParams) => {
2109
+ const chainCheck = createChainCheck(this.client.viemClient, this.chainId);
2466
2110
  const approvals = pulledAssets > 0n
2467
- ? await getMidnightApprovalRequirements({
2111
+ ? await getParsedMidnightApprovalRequirements(parseMidnightApprovalRequirements({
2468
2112
  viemClient: this.client.viemClient,
2469
2113
  chainId: this.chainId,
2470
2114
  token: market.loanToken,
2471
2115
  owner: params.accountAddress,
2472
2116
  spender: tx.to,
2473
2117
  amount: pulledAssets,
2474
- })
2118
+ }), chainCheck)
2475
2119
  : [];
2476
- const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress);
2120
+ const authorization = await this.getBundlesV2AuthorizationRequirements(params.accountAddress, chainCheck);
2477
2121
  return [...approvals, ...authorization];
2478
2122
  },
2479
2123
  buildTx: () => tx,
2480
2124
  };
2481
2125
  }
2482
2126
  /**
2483
- * Prepares a full cancellation of one or more maker offer groups as a direct call to Midnight.
2127
+ * Prepares direct cancellation of maker offer groups on Midnight.
2484
2128
  *
2485
- * One group builds a bare `setConsumed(group, maxUint128, accountAddress)`. Two or more groups
2486
- * build one Midnight `multicall` of such calls, in list order, which cancels every group or
2487
- * none. Only the single-group transaction is matchable by a wallet policy that allows
2488
- * `setConsumed` by method name; cancel one group per transaction when the signer's policy names
2489
- * `setConsumed`.
2129
+ * One group stays a bare `setConsumed(group, maxUint128, accountAddress)` so a wallet policy
2130
+ * can match it by method name. Two or more groups encode one atomic Midnight `multicall`.
2131
+ * This never targets MidnightBundlesV2 and requires no approval, authorization or deadline.
2132
+ * Cancellation does not unratify roots or revoke existing authorizations.
2490
2133
  *
2491
- * Nothing is required before sending: no Midnight authorization, approval, signature or
2492
- * deadline. Cancellation is per group and always full; it does not unratify roots or revoke
2493
- * authorizations, and cancelling a group again succeeds.
2494
- *
2495
- * @param params - Maker account and the offer groups to cancel.
2496
- * @param params.accountAddress - Maker whose groups are cancelled. The maker, or an operator it
2497
- * authorized on Midnight, must send the transaction; a transaction from any other account
2498
- * reverts `Unauthorized()` and changes no group.
2499
- * @param params.groups - Nonempty list of distinct 32-byte offer groups to cancel.
2500
- * @param params.now - Optional reference timestamp used to resolve `metadata.timestamp: true`.
2501
- * @returns A handle whose `getRequirements()` resolves to an empty list without reading the
2502
- * chain, and whose synchronous `buildTx()` returns the transaction targeting `Midnight`.
2134
+ * @param params - Maker account and nonempty ordered list of distinct offer groups.
2135
+ * @param params.accountAddress - Maker that must send the transaction, or authorize its sender on Midnight.
2136
+ * @param params.groups - Distinct 32-byte groups to cancel completely, regardless of prior consumption.
2137
+ * @returns An empty requirements list and a synchronous direct-cancellation builder.
2503
2138
  * @throws {ChainIdMismatchError} when the client targets another chain.
2504
2139
  * @throws {MidnightInvalidAccountAddressError} when `accountAddress` is malformed or zero.
2140
+ * @throws {MidnightCalldataEncodingError} when an address cannot be ABI-encoded.
2505
2141
  * @throws {EmptyMidnightGroupCancellationsError} when no groups are provided.
2506
2142
  * @throws {InvalidMidnightHexInputError} when a group is not 32-byte hex.
2507
2143
  * @throws {DuplicateMidnightGroupCancellationError} when a group appears more than once.
@@ -2519,37 +2155,30 @@ export class MorphoMidnight {
2519
2155
  * morphoViemExtension(),
2520
2156
  * );
2521
2157
  * const midnight = client.morpho.midnight(base.id);
2522
- * const output = midnight.cancelOffers({ accountAddress: maker, groups: [group] });
2523
- * await output.getRequirements(); // => []
2524
- * const tx = output.buildTx(); // calldata: setConsumed(group, maxUint128, maker)
2158
+ * const output = midnight.cancelOffers({
2159
+ * accountAddress: maker,
2160
+ * groups: [group],
2161
+ * });
2525
2162
  * ```
2526
2163
  */
2527
2164
  cancelOffers(params) {
2528
- const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
2529
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
2530
- const { accountAddress } = params;
2531
- if (!isAddress(accountAddress) ||
2532
- isAddressEqual(accountAddress, zeroAddress)) {
2533
- throw new MidnightInvalidAccountAddressError(accountAddress);
2534
- }
2535
- const tx = midnightCancelOffers({
2165
+ const parsed = parseCancelOffersParams(params, {
2166
+ client: this.client,
2536
2167
  chainId: this.chainId,
2537
- groups: params.groups,
2538
- onBehalf: accountAddress,
2539
- metadata,
2540
2168
  });
2169
+ const tx = encodeMidnightCancelOffers(parsed);
2541
2170
  return {
2542
2171
  getRequirements: async () => [],
2543
2172
  buildTx: () => tx,
2544
2173
  };
2545
2174
  }
2546
- async getBundlesV2AuthorizationRequirements(owner) {
2547
- const authorization = await getMidnightAuthorizationRequirement({
2175
+ async getBundlesV2AuthorizationRequirements(owner, chainCheck = createChainCheck(this.client.viemClient, this.chainId)) {
2176
+ const authorization = await getParsedMidnightAuthorizationRequirement(parseMidnightAuthorizationRequirement({
2548
2177
  viemClient: this.client.viemClient,
2549
2178
  chainId: this.chainId,
2550
2179
  owner,
2551
2180
  authorized: getChainAddress(this.chainId, "midnightBundlesV2"),
2552
- });
2181
+ }), chainCheck);
2553
2182
  return authorization ? [authorization] : [];
2554
2183
  }
2555
2184
  }