@morpho-org/morpho-sdk 10.0.2 → 10.1.0

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