@morpho-org/morpho-sdk 5.1.2 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (270) hide show
  1. package/README.md +46 -2
  2. package/lib/cjs/abis.d.ts +1 -0
  3. package/lib/cjs/abis.js +6 -1
  4. package/lib/cjs/actions/blue/borrow.d.ts +3 -7
  5. package/lib/cjs/actions/blue/borrow.js +5 -9
  6. package/lib/cjs/actions/blue/buildReallocationActions.d.ts +3 -4
  7. package/lib/cjs/actions/blue/buildReallocationActions.js +3 -4
  8. package/lib/cjs/actions/blue/refinance.d.ts +4 -8
  9. package/lib/cjs/actions/blue/refinance.js +10 -14
  10. package/lib/cjs/actions/blue/repay.d.ts +2 -5
  11. package/lib/cjs/actions/blue/repay.js +2 -5
  12. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +3 -6
  13. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +4 -7
  14. package/lib/cjs/actions/blue/resolveRepayFunding.d.ts +2 -5
  15. package/lib/cjs/actions/blue/resolveRepayFunding.js +15 -12
  16. package/lib/cjs/actions/blue/supply.d.ts +2 -4
  17. package/lib/cjs/actions/blue/supply.js +6 -8
  18. package/lib/cjs/actions/blue/supplyCollateral.d.ts +2 -3
  19. package/lib/cjs/actions/blue/supplyCollateral.js +5 -6
  20. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +4 -9
  21. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +9 -14
  22. package/lib/cjs/actions/blue/withdraw.d.ts +9 -7
  23. package/lib/cjs/actions/blue/withdraw.js +18 -10
  24. package/lib/cjs/actions/blue/withdrawCollateral.d.ts +1 -1
  25. package/lib/cjs/actions/blue/withdrawCollateral.js +2 -2
  26. package/lib/cjs/actions/index.d.ts +2 -0
  27. package/lib/cjs/actions/index.js +1 -0
  28. package/lib/cjs/actions/midnight/authorization.d.ts +37 -0
  29. package/lib/cjs/actions/midnight/authorization.js +69 -0
  30. package/lib/cjs/actions/midnight/cancelOffer.d.ts +38 -0
  31. package/lib/cjs/actions/midnight/cancelOffer.js +73 -0
  32. package/lib/cjs/actions/midnight/index.d.ts +11 -0
  33. package/lib/cjs/actions/midnight/index.js +27 -0
  34. package/lib/cjs/actions/midnight/mempoolSubmitOffers.d.ts +52 -0
  35. package/lib/cjs/actions/midnight/mempoolSubmitOffers.js +72 -0
  36. package/lib/cjs/actions/midnight/redeem.d.ts +43 -0
  37. package/lib/cjs/actions/midnight/redeem.js +79 -0
  38. package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +53 -0
  39. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +121 -0
  40. package/lib/cjs/actions/midnight/setterRatifierRatifyRoot.d.ts +40 -0
  41. package/lib/cjs/actions/midnight/setterRatifierRatifyRoot.js +59 -0
  42. package/lib/cjs/actions/midnight/supplyCollateral.d.ts +45 -0
  43. package/lib/cjs/actions/midnight/supplyCollateral.js +83 -0
  44. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +51 -0
  45. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +128 -0
  46. package/lib/cjs/actions/midnight/takeBorrow.d.ts +57 -0
  47. package/lib/cjs/actions/midnight/takeBorrow.js +110 -0
  48. package/lib/cjs/actions/midnight/takeLend.d.ts +57 -0
  49. package/lib/cjs/actions/midnight/takeLend.js +110 -0
  50. package/lib/cjs/actions/midnight/types.d.ts +39 -0
  51. package/lib/cjs/actions/midnight/types.js +15 -0
  52. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +1 -1
  53. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +5 -16
  54. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +5 -4
  55. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +10 -14
  56. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +2 -2
  57. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +11 -28
  58. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2Approve.d.ts +1 -1
  59. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2Approve.js +5 -17
  60. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  61. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +10 -4
  62. package/lib/cjs/actions/requirements/getRequirementsApproval.js +10 -4
  63. package/lib/cjs/actions/requirements/index.d.ts +1 -0
  64. package/lib/cjs/actions/requirements/index.js +1 -0
  65. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +49 -0
  66. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +76 -0
  67. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +44 -0
  68. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +78 -0
  69. package/lib/cjs/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.d.ts +42 -0
  70. package/lib/cjs/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.js +70 -0
  71. package/lib/cjs/actions/requirements/midnight/index.d.ts +3 -0
  72. package/lib/cjs/actions/requirements/midnight/index.js +19 -0
  73. package/lib/cjs/actions/vaultV1/deposit.d.ts +3 -4
  74. package/lib/cjs/actions/vaultV1/deposit.js +7 -8
  75. package/lib/cjs/actions/vaultV1/migrateToV2.d.ts +2 -3
  76. package/lib/cjs/actions/vaultV1/migrateToV2.js +5 -6
  77. package/lib/cjs/actions/vaultV1/redeem.d.ts +1 -1
  78. package/lib/cjs/actions/vaultV1/redeem.js +2 -2
  79. package/lib/cjs/actions/vaultV1/withdraw.d.ts +1 -1
  80. package/lib/cjs/actions/vaultV1/withdraw.js +2 -2
  81. package/lib/cjs/actions/vaultV2/deposit.d.ts +3 -4
  82. package/lib/cjs/actions/vaultV2/deposit.js +7 -8
  83. package/lib/cjs/actions/vaultV2/forceRedeem.d.ts +2 -3
  84. package/lib/cjs/actions/vaultV2/forceRedeem.js +3 -4
  85. package/lib/cjs/actions/vaultV2/forceWithdraw.d.ts +1 -1
  86. package/lib/cjs/actions/vaultV2/forceWithdraw.js +2 -2
  87. package/lib/cjs/actions/vaultV2/redeem.d.ts +1 -1
  88. package/lib/cjs/actions/vaultV2/redeem.js +2 -2
  89. package/lib/cjs/actions/vaultV2/withdraw.d.ts +1 -1
  90. package/lib/cjs/actions/vaultV2/withdraw.js +2 -2
  91. package/lib/cjs/client/morphoViemExtension.d.ts +1 -1
  92. package/lib/cjs/client/morphoViemExtension.js +5 -2
  93. package/lib/cjs/constants.d.ts +1 -0
  94. package/lib/cjs/constants.js +15 -1
  95. package/lib/cjs/entities/blue/blue.d.ts +5 -5
  96. package/lib/cjs/entities/blue/blue.js +105 -86
  97. package/lib/cjs/entities/index.d.ts +1 -0
  98. package/lib/cjs/entities/index.js +15 -0
  99. package/lib/cjs/entities/midnight/index.d.ts +2 -0
  100. package/lib/cjs/entities/midnight/index.js +18 -0
  101. package/lib/cjs/entities/midnight/midnight.d.ts +402 -0
  102. package/lib/cjs/entities/midnight/midnight.js +1036 -0
  103. package/lib/cjs/entities/midnight/types.d.ts +164 -0
  104. package/lib/cjs/entities/midnight/types.js +2 -0
  105. package/lib/cjs/entities/vaultV1/vaultV1.js +10 -17
  106. package/lib/cjs/entities/vaultV2/vaultV2.js +19 -21
  107. package/lib/cjs/errors.d.ts +1 -0
  108. package/lib/cjs/errors.js +17 -1
  109. package/lib/cjs/helpers/encodeDeallocation.d.ts +1 -0
  110. package/lib/cjs/helpers/encodeDeallocation.js +2 -1
  111. package/lib/cjs/helpers/index.d.ts +4 -1
  112. package/lib/cjs/helpers/index.js +8 -1
  113. package/lib/cjs/helpers/signAndVerifyTypedData.d.ts +34 -0
  114. package/lib/cjs/helpers/signAndVerifyTypedData.js +58 -0
  115. package/lib/cjs/helpers/validate.d.ts +40 -1
  116. package/lib/cjs/helpers/validate.js +47 -5
  117. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.d.ts +15 -0
  118. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.js +32 -0
  119. package/lib/cjs/helpers/validateMidnightMarket.d.ts +10 -0
  120. package/lib/cjs/helpers/validateMidnightMarket.js +24 -0
  121. package/lib/cjs/helpers/validateOfferSides.d.ts +21 -0
  122. package/lib/cjs/helpers/validateOfferSides.js +36 -0
  123. package/lib/cjs/helpers/validateRequirementSpender.d.ts +29 -0
  124. package/lib/cjs/helpers/validateRequirementSpender.js +49 -0
  125. package/lib/cjs/helpers/validateTakeableOffers.d.ts +18 -0
  126. package/lib/cjs/helpers/validateTakeableOffers.js +35 -0
  127. package/lib/cjs/midnight-api.d.ts +1 -0
  128. package/lib/cjs/midnight-api.js +17 -0
  129. package/lib/cjs/types/action.d.ts +189 -23
  130. package/lib/cjs/types/action.js +27 -7
  131. package/lib/cjs/types/client.d.ts +3 -2
  132. package/lib/cjs/types/error.d.ts +288 -114
  133. package/lib/cjs/types/error.js +259 -175
  134. package/lib/cjs/utils.d.ts +1 -0
  135. package/lib/cjs/utils.js +12 -2
  136. package/lib/esm/abis.d.ts +1 -0
  137. package/lib/esm/abis.js +1 -0
  138. package/lib/esm/actions/blue/borrow.d.ts +3 -7
  139. package/lib/esm/actions/blue/borrow.js +6 -10
  140. package/lib/esm/actions/blue/buildReallocationActions.d.ts +3 -4
  141. package/lib/esm/actions/blue/buildReallocationActions.js +3 -4
  142. package/lib/esm/actions/blue/refinance.d.ts +4 -8
  143. package/lib/esm/actions/blue/refinance.js +11 -15
  144. package/lib/esm/actions/blue/repay.d.ts +2 -5
  145. package/lib/esm/actions/blue/repay.js +2 -5
  146. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +3 -6
  147. package/lib/esm/actions/blue/repayWithdrawCollateral.js +5 -8
  148. package/lib/esm/actions/blue/resolveRepayFunding.d.ts +2 -5
  149. package/lib/esm/actions/blue/resolveRepayFunding.js +16 -13
  150. package/lib/esm/actions/blue/supply.d.ts +2 -4
  151. package/lib/esm/actions/blue/supply.js +7 -9
  152. package/lib/esm/actions/blue/supplyCollateral.d.ts +2 -3
  153. package/lib/esm/actions/blue/supplyCollateral.js +6 -7
  154. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +4 -9
  155. package/lib/esm/actions/blue/supplyCollateralBorrow.js +10 -15
  156. package/lib/esm/actions/blue/withdraw.d.ts +9 -7
  157. package/lib/esm/actions/blue/withdraw.js +19 -11
  158. package/lib/esm/actions/blue/withdrawCollateral.d.ts +1 -1
  159. package/lib/esm/actions/blue/withdrawCollateral.js +3 -3
  160. package/lib/esm/actions/index.d.ts +2 -0
  161. package/lib/esm/actions/index.js +1 -0
  162. package/lib/esm/actions/midnight/authorization.d.ts +37 -0
  163. package/lib/esm/actions/midnight/authorization.js +65 -0
  164. package/lib/esm/actions/midnight/cancelOffer.d.ts +38 -0
  165. package/lib/esm/actions/midnight/cancelOffer.js +69 -0
  166. package/lib/esm/actions/midnight/index.d.ts +11 -0
  167. package/lib/esm/actions/midnight/index.js +11 -0
  168. package/lib/esm/actions/midnight/mempoolSubmitOffers.d.ts +52 -0
  169. package/lib/esm/actions/midnight/mempoolSubmitOffers.js +68 -0
  170. package/lib/esm/actions/midnight/redeem.d.ts +43 -0
  171. package/lib/esm/actions/midnight/redeem.js +75 -0
  172. package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +53 -0
  173. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +117 -0
  174. package/lib/esm/actions/midnight/setterRatifierRatifyRoot.d.ts +40 -0
  175. package/lib/esm/actions/midnight/setterRatifierRatifyRoot.js +55 -0
  176. package/lib/esm/actions/midnight/supplyCollateral.d.ts +45 -0
  177. package/lib/esm/actions/midnight/supplyCollateral.js +79 -0
  178. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +51 -0
  179. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +124 -0
  180. package/lib/esm/actions/midnight/takeBorrow.d.ts +57 -0
  181. package/lib/esm/actions/midnight/takeBorrow.js +106 -0
  182. package/lib/esm/actions/midnight/takeLend.d.ts +57 -0
  183. package/lib/esm/actions/midnight/takeLend.js +106 -0
  184. package/lib/esm/actions/midnight/types.d.ts +39 -0
  185. package/lib/esm/actions/midnight/types.js +12 -0
  186. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +1 -1
  187. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +6 -17
  188. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +5 -4
  189. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +12 -16
  190. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +2 -2
  191. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +12 -29
  192. package/lib/esm/actions/requirements/encode/encodeErc20Permit2Approve.d.ts +1 -1
  193. package/lib/esm/actions/requirements/encode/encodeErc20Permit2Approve.js +5 -17
  194. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  195. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +10 -4
  196. package/lib/esm/actions/requirements/getRequirementsApproval.js +10 -4
  197. package/lib/esm/actions/requirements/index.d.ts +1 -0
  198. package/lib/esm/actions/requirements/index.js +1 -0
  199. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +49 -0
  200. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +72 -0
  201. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +44 -0
  202. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +74 -0
  203. package/lib/esm/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.d.ts +42 -0
  204. package/lib/esm/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.js +66 -0
  205. package/lib/esm/actions/requirements/midnight/index.d.ts +3 -0
  206. package/lib/esm/actions/requirements/midnight/index.js +3 -0
  207. package/lib/esm/actions/vaultV1/deposit.d.ts +3 -4
  208. package/lib/esm/actions/vaultV1/deposit.js +8 -9
  209. package/lib/esm/actions/vaultV1/migrateToV2.d.ts +2 -3
  210. package/lib/esm/actions/vaultV1/migrateToV2.js +6 -7
  211. package/lib/esm/actions/vaultV1/redeem.d.ts +1 -1
  212. package/lib/esm/actions/vaultV1/redeem.js +3 -3
  213. package/lib/esm/actions/vaultV1/withdraw.d.ts +1 -1
  214. package/lib/esm/actions/vaultV1/withdraw.js +3 -3
  215. package/lib/esm/actions/vaultV2/deposit.d.ts +3 -4
  216. package/lib/esm/actions/vaultV2/deposit.js +8 -9
  217. package/lib/esm/actions/vaultV2/forceRedeem.d.ts +2 -3
  218. package/lib/esm/actions/vaultV2/forceRedeem.js +4 -5
  219. package/lib/esm/actions/vaultV2/forceWithdraw.d.ts +1 -1
  220. package/lib/esm/actions/vaultV2/forceWithdraw.js +3 -3
  221. package/lib/esm/actions/vaultV2/redeem.d.ts +1 -1
  222. package/lib/esm/actions/vaultV2/redeem.js +3 -3
  223. package/lib/esm/actions/vaultV2/withdraw.d.ts +1 -1
  224. package/lib/esm/actions/vaultV2/withdraw.js +3 -3
  225. package/lib/esm/client/morphoViemExtension.d.ts +1 -1
  226. package/lib/esm/client/morphoViemExtension.js +6 -3
  227. package/lib/esm/constants.d.ts +1 -0
  228. package/lib/esm/constants.js +1 -0
  229. package/lib/esm/entities/blue/blue.d.ts +5 -5
  230. package/lib/esm/entities/blue/blue.js +107 -88
  231. package/lib/esm/entities/index.d.ts +1 -0
  232. package/lib/esm/entities/index.js +1 -0
  233. package/lib/esm/entities/midnight/index.d.ts +2 -0
  234. package/lib/esm/entities/midnight/index.js +2 -0
  235. package/lib/esm/entities/midnight/midnight.d.ts +402 -0
  236. package/lib/esm/entities/midnight/midnight.js +1032 -0
  237. package/lib/esm/entities/midnight/types.d.ts +164 -0
  238. package/lib/esm/entities/midnight/types.js +1 -0
  239. package/lib/esm/entities/vaultV1/vaultV1.js +13 -20
  240. package/lib/esm/entities/vaultV2/vaultV2.js +9 -11
  241. package/lib/esm/errors.d.ts +1 -0
  242. package/lib/esm/errors.js +1 -0
  243. package/lib/esm/helpers/encodeDeallocation.d.ts +1 -0
  244. package/lib/esm/helpers/encodeDeallocation.js +3 -2
  245. package/lib/esm/helpers/index.d.ts +4 -1
  246. package/lib/esm/helpers/index.js +4 -1
  247. package/lib/esm/helpers/signAndVerifyTypedData.d.ts +34 -0
  248. package/lib/esm/helpers/signAndVerifyTypedData.js +54 -0
  249. package/lib/esm/helpers/validate.d.ts +40 -1
  250. package/lib/esm/helpers/validate.js +46 -5
  251. package/lib/esm/helpers/validateMidnightAuthorizationTarget.d.ts +15 -0
  252. package/lib/esm/helpers/validateMidnightAuthorizationTarget.js +28 -0
  253. package/lib/esm/helpers/validateMidnightMarket.d.ts +10 -0
  254. package/lib/esm/helpers/validateMidnightMarket.js +20 -0
  255. package/lib/esm/helpers/validateOfferSides.d.ts +21 -0
  256. package/lib/esm/helpers/validateOfferSides.js +32 -0
  257. package/lib/esm/helpers/validateRequirementSpender.d.ts +29 -0
  258. package/lib/esm/helpers/validateRequirementSpender.js +45 -0
  259. package/lib/esm/helpers/validateTakeableOffers.d.ts +18 -0
  260. package/lib/esm/helpers/validateTakeableOffers.js +31 -0
  261. package/lib/esm/midnight-api.d.ts +1 -0
  262. package/lib/esm/midnight-api.js +1 -0
  263. package/lib/esm/types/action.d.ts +189 -23
  264. package/lib/esm/types/action.js +26 -7
  265. package/lib/esm/types/client.d.ts +3 -2
  266. package/lib/esm/types/error.d.ts +288 -114
  267. package/lib/esm/types/error.js +232 -149
  268. package/lib/esm/utils.d.ts +1 -0
  269. package/lib/esm/utils.js +1 -0
  270. package/package.json +13 -4
@@ -0,0 +1,1032 @@
1
+ import { EcrecoverRatifierUtils, fetchAccrualPosition, fetchMarket, InvalidTreeError, MarketParams, MarketUtils, Payload, SetterRatifierUtils, Tree, } from "@morpho-org/midnight-sdk";
2
+ import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
+ import { isAddressEqual, } from "viem";
4
+ import { mempoolSubmitOffers, midnightCancelOffer, midnightRedeem, midnightRepayWithdrawCollateral, midnightSupplyCollateral, midnightSupplyCollateralTakeBorrow, midnightTakeBorrow, midnightTakeLend, } from "../../actions/midnight/index.js";
5
+ import { getMidnightApprovalRequirements, getMidnightAuthorizationRequirement, getSetterRatifierRatifyRootRequirement, } from "../../actions/requirements/index.js";
6
+ import { validateChainId } from "../../helpers/index.js";
7
+ import { signAndVerifyTypedData } from "../../helpers/signAndVerifyTypedData.js";
8
+ import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
9
+ import { validateOfferSides } from "../../helpers/validateOfferSides.js";
10
+ import { validateTakeableOffers } from "../../helpers/validateTakeableOffers.js";
11
+ import { AccrualPositionUserMismatchError, InsufficientMidnightWithdrawableLiquidityError, MarketIdMismatchError, MidnightOfferMakerMismatchError, MidnightOfferMarketAddressMismatchError, MidnightOfferMarketChainMismatchError, MidnightOfferMarketLoanTokenMismatchError, MidnightOfferRootMismatchError, MidnightOfferRootOfferCountMismatchError, MidnightOfferRootOwnerMismatchError, MidnightOfferRootRatifierMismatchError, MidnightRedeemExceedsCreditError, MissingAccrualPositionError, MissingMidnightOfferRootSignatureError, NegativeInputError, NoMidnightCreditToRedeemError, NonPositiveInputError, selectRequirementSignatures, UnknownMidnightRatifierError, UnpreparedMidnightOfferRootSignatureError, } from "../../types/index.js";
12
+ const assertNonNegativeAmount = (label, amount) => {
13
+ if (amount < 0n)
14
+ throw new NegativeInputError(label, amount);
15
+ };
16
+ const assertPositiveAmount = (label, amount) => {
17
+ if (amount <= 0n)
18
+ throw new NonPositiveInputError(label, amount);
19
+ };
20
+ const validateMarketData = (market, chainId) => {
21
+ // Reject snapshots from another chain deployment before exposing requirements.
22
+ validateMidnightMarket({ market, chainId });
23
+ };
24
+ /**
25
+ * Entity facade for Midnight fixed-rate action flows.
26
+ *
27
+ * `MorphoMidnight` keeps reads and transaction construction separated. Methods
28
+ * that need chain or API state fetch it up front, while returned `buildTx`
29
+ * callbacks are synchronous and only consume the data already passed in.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * const midnight = client.morpho.midnight(8453);
34
+ * const block = await client.getBlock();
35
+ * const positionData = (
36
+ * await midnight.getPositionData({
37
+ * marketId,
38
+ * accountAddress: user,
39
+ * parameters: { blockNumber: block.number },
40
+ * })
41
+ * ).accrueInterest(block.timestamp);
42
+ * const { buildTx } = midnight.redeem({
43
+ * accountAddress: user,
44
+ * positionData,
45
+ * });
46
+ * const tx = buildTx();
47
+ * ```
48
+ */
49
+ export class MorphoMidnight {
50
+ client;
51
+ chainId;
52
+ constructor(client, chainId) {
53
+ this.client = client;
54
+ this.chainId = chainId;
55
+ }
56
+ /**
57
+ * Fetches a hydrated Midnight market from `Midnight.toMarket` and `Midnight.marketState`.
58
+ *
59
+ * @param marketId - Market id to fetch.
60
+ * @param parameters - Optional block, account, and state-override parameters forwarded to every read.
61
+ * @returns The market parameters and current onchain market state.
62
+ * @throws {ChainIdMismatchError} when the client chain differs from this entity's chain.
63
+ * @example
64
+ * ```ts
65
+ * const midnight = client.morpho.midnight(8453);
66
+ * const marketData = await midnight.getMarketData(marketId, {
67
+ * blockNumber: 48_287_000n,
68
+ * });
69
+ * ```
70
+ */
71
+ async getMarketData(marketId, parameters) {
72
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
73
+ return await fetchMarket(this.client.viemClient, {
74
+ ...parameters,
75
+ marketId,
76
+ });
77
+ }
78
+ /**
79
+ * Fetches a Midnight position and its hydrated market from onchain state.
80
+ *
81
+ * Reads `Midnight.toMarket`, `Midnight.marketState`, and either the deployless
82
+ * position query or the direct position and collateral getters.
83
+ *
84
+ * @param params - Position owner, market id, and optional fetch parameters.
85
+ * @param params.marketId - Market id whose position is fetched.
86
+ * @param params.accountAddress - Position owner address.
87
+ * @param params.parameters - Optional block, account, and state-override parameters forwarded to every read.
88
+ * @returns The account's position paired with the fetched market.
89
+ * @throws {ChainIdMismatchError} when the client chain differs from this entity's chain.
90
+ * @example
91
+ * ```ts
92
+ * const positionData = await midnight.getPositionData({
93
+ * marketId,
94
+ * accountAddress: user,
95
+ * parameters: { blockNumber: 48_287_000n },
96
+ * });
97
+ * ```
98
+ */
99
+ async getPositionData(params) {
100
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
101
+ return fetchAccrualPosition(this.client.viemClient, {
102
+ ...params.parameters,
103
+ deployless: this.client.options.supportDeployless,
104
+ marketId: params.marketId,
105
+ user: params.accountAddress,
106
+ });
107
+ }
108
+ /**
109
+ * Builds and validates a maker offer tree against the Midnight mempool API.
110
+ *
111
+ * @param params - Maker account, raw offer or group inputs, and optional API validation controls.
112
+ * @param params.accountAddress - Maker expected on every offer.
113
+ * @param params.offers - Offer, group, tree, or list accepted by `Tree.create`.
114
+ * @param params.validation - Optional Midnight mempool API request controls.
115
+ * @returns Prepared tree data used by maker flows.
116
+ * @throws {ChainIdMismatchError} when the client chain differs from this entity's chain.
117
+ * @throws {InvalidTreeError} when the input does not form a non-empty valid tree.
118
+ * @throws {MidnightOfferMakerMismatchError} when an offer belongs to another maker.
119
+ * @throws {MidnightOfferMarketChainMismatchError} when an offer targets another chain.
120
+ * @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
121
+ * @throws {UnknownMidnightRatifierError} when the tree uses an unsupported ratifier.
122
+ * @example
123
+ * ```ts
124
+ * const offersData = await midnight.getOffersData({
125
+ * accountAddress: maker,
126
+ * offers: [offer],
127
+ * });
128
+ * ```
129
+ */
130
+ async getOffersData(params) {
131
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
132
+ const tree = Tree.from(params.offers);
133
+ const midnight = getChainAddress(this.chainId, "midnight");
134
+ tree.offers.forEach((offer, index) => {
135
+ if (!isAddressEqual(offer.maker, params.accountAddress)) {
136
+ throw new MidnightOfferMakerMismatchError({
137
+ index,
138
+ expectedMaker: params.accountAddress,
139
+ actualMaker: offer.maker,
140
+ });
141
+ }
142
+ const market = "params" in offer.market ? offer.market.params : offer.market;
143
+ if (market.chainId !== BigInt(this.chainId)) {
144
+ throw new MidnightOfferMarketChainMismatchError({
145
+ index,
146
+ expectedChainId: this.chainId,
147
+ actualChainId: market.chainId,
148
+ });
149
+ }
150
+ if (!isAddressEqual(market.midnight, midnight)) {
151
+ throw new MidnightOfferMarketAddressMismatchError({
152
+ index,
153
+ expectedMidnight: midnight,
154
+ actualMidnight: market.midnight,
155
+ });
156
+ }
157
+ });
158
+ const firstOffer = tree.offers[0];
159
+ if (firstOffer == null) {
160
+ throw new InvalidTreeError("Tree must contain at least one offer.");
161
+ }
162
+ const ratifier = firstOffer.ratifier;
163
+ const ecrecoverRatifier = getChainAddress(this.chainId, "ecrecoverRatifier");
164
+ const setterRatifier = getChainAddress(this.chainId, "setterRatifier");
165
+ const ratifierType = isAddressEqual(ratifier, ecrecoverRatifier)
166
+ ? "ecrecover"
167
+ : isAddressEqual(ratifier, setterRatifier)
168
+ ? "setter"
169
+ : undefined;
170
+ if (ratifierType == null) {
171
+ throw new UnknownMidnightRatifierError({
172
+ ratifier,
173
+ ecrecoverRatifier,
174
+ setterRatifier,
175
+ });
176
+ }
177
+ const groups = [];
178
+ const seenGroups = new Set();
179
+ for (const offer of tree.offers) {
180
+ const group = offer.group;
181
+ const key = group.toLowerCase();
182
+ if (!seenGroups.has(key)) {
183
+ seenGroups.add(key);
184
+ groups.push(group);
185
+ }
186
+ }
187
+ await tree.mempoolValidate({
188
+ ...params.validation,
189
+ chainId: this.chainId,
190
+ });
191
+ if (ratifierType === "setter") {
192
+ // Setter ratifier payload generation validates that the created tree has one ratifier.
193
+ const items = SetterRatifierUtils.ratify({ tree });
194
+ return {
195
+ accountAddress: params.accountAddress,
196
+ groups,
197
+ tree,
198
+ ratifierType,
199
+ ratifier,
200
+ setterPayload: await Payload.encode(items),
201
+ };
202
+ }
203
+ // Ecrecover typed-data generation validates that the created tree has one ratifier.
204
+ EcrecoverRatifierUtils.typedData({ tree, chainId: this.chainId });
205
+ return {
206
+ accountAddress: params.accountAddress,
207
+ groups,
208
+ tree,
209
+ ratifierType,
210
+ ratifier,
211
+ };
212
+ }
213
+ /**
214
+ * Prepares a lend-side take using caller-provided market data and API offers.
215
+ *
216
+ * @param params - Lender, market snapshot, target assets, units, offers, and deadline.
217
+ * @param params.accountAddress - Lender executing the take.
218
+ * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
219
+ * @param params.assets - Loan assets spent by the lender.
220
+ * @param params.minUnits - Minimum credit units accepted.
221
+ * @param params.takeableOffers - Borrow-side offers returned by the Midnight API.
222
+ * @param params.deadline - Bundle execution deadline timestamp.
223
+ * @returns Lazy approval/authorization requirements and a synchronous transaction builder.
224
+ * @throws {ChainIdMismatchError} when client or market data targets another chain.
225
+ * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
226
+ * @throws {NonPositiveInputError} when `assets` is non-positive.
227
+ * @throws {NegativeInputError} when `minUnits` or `deadline` is negative.
228
+ * @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
229
+ * @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
230
+ * @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
231
+ * @example
232
+ * ```ts
233
+ * const output = midnight.takeLend({
234
+ * accountAddress: lender,
235
+ * marketData,
236
+ * assets: 1_000_000n,
237
+ * minUnits: 900_000n,
238
+ * takeableOffers: quote.data.takeableOffers,
239
+ * deadline: maxUint256,
240
+ * });
241
+ * ```
242
+ */
243
+ takeLend(params) {
244
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
245
+ validateMarketData(params.marketData, this.chainId);
246
+ assertPositiveAmount("assets", params.assets);
247
+ assertNonNegativeAmount("minUnits", params.minUnits);
248
+ assertNonNegativeAmount("deadline", params.deadline);
249
+ // Reject inconsistent quotes before exposing requirement reads.
250
+ validateTakeableOffers({
251
+ market: params.marketData.params,
252
+ takeableOffers: params.takeableOffers,
253
+ expectedBuy: false,
254
+ });
255
+ const market = params.marketData;
256
+ const midnightBundles = getChainAddress(this.chainId, "midnightBundles");
257
+ return {
258
+ getRequirements: async () => {
259
+ const requirements = [
260
+ ...(await getMidnightApprovalRequirements({
261
+ viemClient: this.client.viemClient,
262
+ chainId: this.chainId,
263
+ token: market.params.loanToken,
264
+ owner: params.accountAddress,
265
+ spender: midnightBundles,
266
+ amount: params.assets,
267
+ })),
268
+ ];
269
+ const authorization = await getMidnightAuthorizationRequirement({
270
+ viemClient: this.client.viemClient,
271
+ chainId: this.chainId,
272
+ owner: params.accountAddress,
273
+ authorized: midnightBundles,
274
+ });
275
+ if (authorization)
276
+ requirements.push(authorization);
277
+ return requirements;
278
+ },
279
+ buildTx: () => midnightTakeLend({
280
+ chainId: this.chainId,
281
+ market: market.params,
282
+ assets: params.assets,
283
+ minUnits: params.minUnits,
284
+ taker: params.accountAddress,
285
+ takeableOffers: params.takeableOffers,
286
+ deadline: params.deadline,
287
+ metadata: this.client.options.metadata,
288
+ }),
289
+ };
290
+ }
291
+ /**
292
+ * Prepares a borrow-side take using caller-provided market data and API offers.
293
+ *
294
+ * @param params - Borrower, market snapshot, target assets, unit cap, offers, and deadline.
295
+ * @param params.accountAddress - Borrower executing the take.
296
+ * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
297
+ * @param params.loanAssets - Loan assets received by the borrower.
298
+ * @param params.maxUnits - Maximum debt units accepted.
299
+ * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
300
+ * @param params.deadline - Bundle execution deadline timestamp.
301
+ * @returns Lazy authorization requirements and a synchronous transaction builder.
302
+ * @throws {ChainIdMismatchError} when client or market data targets another chain.
303
+ * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
304
+ * @throws {NonPositiveInputError} when `loanAssets` or `maxUnits` is non-positive.
305
+ * @throws {NegativeInputError} when `deadline` is negative.
306
+ * @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
307
+ * @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
308
+ * @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
309
+ * @example
310
+ * ```ts
311
+ * const output = midnight.takeBorrow({
312
+ * accountAddress: borrower,
313
+ * marketData,
314
+ * loanAssets: 1_000_000n,
315
+ * maxUnits: 1_100_000n,
316
+ * takeableOffers: quote.data.takeableOffers,
317
+ * deadline: maxUint256,
318
+ * });
319
+ * ```
320
+ */
321
+ takeBorrow(params) {
322
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
323
+ validateMarketData(params.marketData, this.chainId);
324
+ assertPositiveAmount("loanAssets", params.loanAssets);
325
+ assertPositiveAmount("maxUnits", params.maxUnits);
326
+ assertNonNegativeAmount("deadline", params.deadline);
327
+ // Reject inconsistent quotes before exposing requirement reads.
328
+ validateTakeableOffers({
329
+ market: params.marketData.params,
330
+ takeableOffers: params.takeableOffers,
331
+ expectedBuy: true,
332
+ });
333
+ const market = params.marketData;
334
+ const midnightBundles = getChainAddress(this.chainId, "midnightBundles");
335
+ return {
336
+ getRequirements: async () => {
337
+ const requirements = [];
338
+ const authorization = await getMidnightAuthorizationRequirement({
339
+ viemClient: this.client.viemClient,
340
+ chainId: this.chainId,
341
+ owner: params.accountAddress,
342
+ authorized: midnightBundles,
343
+ });
344
+ if (authorization)
345
+ requirements.push(authorization);
346
+ return requirements;
347
+ },
348
+ buildTx: () => midnightTakeBorrow({
349
+ chainId: this.chainId,
350
+ market: market.params,
351
+ loanAssets: params.loanAssets,
352
+ maxUnits: params.maxUnits,
353
+ taker: params.accountAddress,
354
+ takeableOffers: params.takeableOffers,
355
+ deadline: params.deadline,
356
+ metadata: this.client.options.metadata,
357
+ }),
358
+ };
359
+ }
360
+ /**
361
+ * Prepares one bundle that supplies collateral and takes borrow-side offers.
362
+ *
363
+ * @param params - Borrower, market snapshot, collateral and loan amounts, unit cap, offers, and deadline.
364
+ * @param params.accountAddress - Borrower executing the bundle.
365
+ * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
366
+ * @param params.collateralAssets - Collateral assets supplied before borrowing.
367
+ * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
368
+ * @param params.loanAssets - Loan assets received by the borrower.
369
+ * @param params.maxUnits - Maximum debt units accepted.
370
+ * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
371
+ * @param params.deadline - Bundle execution deadline timestamp.
372
+ * @returns Lazy collateral approval/authorization requirements and a synchronous transaction builder.
373
+ * @throws {ChainIdMismatchError} when client or market data targets another chain.
374
+ * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
375
+ * @throws {NonPositiveInputError} when collateral, loan assets, or `maxUnits` is non-positive.
376
+ * @throws {NegativeInputError} when `deadline` is negative.
377
+ * @throws {UnknownCollateralIndexError} when the selected collateral is not configured.
378
+ * @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
379
+ * @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
380
+ * @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
381
+ * @example
382
+ * ```ts
383
+ * const output = midnight.supplyCollateralTakeBorrow({
384
+ * accountAddress: borrower,
385
+ * marketData,
386
+ * collateralAssets: 2_000_000n,
387
+ * loanAssets: 1_000_000n,
388
+ * maxUnits: 1_100_000n,
389
+ * takeableOffers: quote.data.takeableOffers,
390
+ * deadline: maxUint256,
391
+ * });
392
+ * ```
393
+ */
394
+ supplyCollateralTakeBorrow(params) {
395
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
396
+ validateMarketData(params.marketData, this.chainId);
397
+ assertPositiveAmount("collateralAssets", params.collateralAssets);
398
+ assertPositiveAmount("loanAssets", params.loanAssets);
399
+ assertPositiveAmount("maxUnits", params.maxUnits);
400
+ assertNonNegativeAmount("deadline", params.deadline);
401
+ // Reject inconsistent quotes before exposing requirement reads.
402
+ validateTakeableOffers({
403
+ market: params.marketData.params,
404
+ takeableOffers: params.takeableOffers,
405
+ expectedBuy: true,
406
+ });
407
+ const market = params.marketData;
408
+ const collateralIndex = params.collateralIndex ?? 0n;
409
+ const midnightBundles = getChainAddress(this.chainId, "midnightBundles");
410
+ const collateral = market.getCollateralByIndex(collateralIndex);
411
+ return {
412
+ getRequirements: async () => {
413
+ const requirements = [
414
+ ...(await getMidnightApprovalRequirements({
415
+ viemClient: this.client.viemClient,
416
+ chainId: this.chainId,
417
+ token: collateral.token,
418
+ owner: params.accountAddress,
419
+ spender: midnightBundles,
420
+ amount: params.collateralAssets,
421
+ })),
422
+ ];
423
+ const authorization = await getMidnightAuthorizationRequirement({
424
+ viemClient: this.client.viemClient,
425
+ chainId: this.chainId,
426
+ owner: params.accountAddress,
427
+ authorized: midnightBundles,
428
+ });
429
+ if (authorization)
430
+ requirements.push(authorization);
431
+ return requirements;
432
+ },
433
+ buildTx: () => midnightSupplyCollateralTakeBorrow({
434
+ chainId: this.chainId,
435
+ market: market.params,
436
+ collateralAssets: params.collateralAssets,
437
+ loanAssets: params.loanAssets,
438
+ maxUnits: params.maxUnits,
439
+ taker: params.accountAddress,
440
+ collateralIndex,
441
+ takeableOffers: params.takeableOffers,
442
+ deadline: params.deadline,
443
+ metadata: this.client.options.metadata,
444
+ }),
445
+ };
446
+ }
447
+ /**
448
+ * Prepares a direct collateral supply using a caller-provided market snapshot.
449
+ *
450
+ * @param params - Supplier, market snapshot, collateral amount, reserve, and optional collateral index.
451
+ * @param params.accountAddress - Account receiving the supplied collateral position.
452
+ * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
453
+ * @param params.collateralAssets - Collateral assets supplied in this transaction.
454
+ * @param params.reservedCollateralAssets - Existing collateral reserved by other open maker groups.
455
+ * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
456
+ * @returns Lazy token-approval requirements and a synchronous transaction builder.
457
+ * @throws {ChainIdMismatchError} when client or market data targets another chain.
458
+ * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
459
+ * @throws {NonPositiveInputError} when `collateralAssets` is non-positive.
460
+ * @throws {NegativeInputError} when `reservedCollateralAssets` is negative.
461
+ * @throws {UnknownCollateralIndexError} when the selected collateral is not configured.
462
+ * @example
463
+ * ```ts
464
+ * const output = midnight.supplyCollateral({
465
+ * accountAddress: borrower,
466
+ * marketData,
467
+ * collateralAssets: 2_000_000n,
468
+ * });
469
+ * ```
470
+ */
471
+ supplyCollateral(params) {
472
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
473
+ validateMarketData(params.marketData, this.chainId);
474
+ assertPositiveAmount("collateralAssets", params.collateralAssets);
475
+ assertNonNegativeAmount("reservedCollateralAssets", params.reservedCollateralAssets ?? 0n);
476
+ const market = params.marketData;
477
+ const collateralIndex = params.collateralIndex ?? 0n;
478
+ const collateral = market.getCollateralByIndex(collateralIndex);
479
+ const midnight = getChainAddress(this.chainId, "midnight");
480
+ return {
481
+ getRequirements: async () => await getMidnightApprovalRequirements({
482
+ viemClient: this.client.viemClient,
483
+ chainId: this.chainId,
484
+ token: collateral.token,
485
+ owner: params.accountAddress,
486
+ spender: midnight,
487
+ amount: params.collateralAssets + (params.reservedCollateralAssets ?? 0n),
488
+ }),
489
+ buildTx: () => midnightSupplyCollateral({
490
+ chainId: this.chainId,
491
+ market: market.params,
492
+ collateralIndex,
493
+ assets: params.collateralAssets,
494
+ onBehalf: params.accountAddress,
495
+ metadata: this.client.options.metadata,
496
+ }),
497
+ };
498
+ }
499
+ /**
500
+ * Validates lend-side maker offers and prepares their reserve and ratifier requirements.
501
+ *
502
+ * Calls the Midnight mempool validation API while preparing the offer tree;
503
+ * allowance and ratifier state are read lazily by `getRequirements()`.
504
+ *
505
+ * @param params - Maker, raw offers, loan token, reserve amounts, and validation controls.
506
+ * @param params.accountAddress - Maker expected on every offer.
507
+ * @param params.offers - Raw lend-side offers or groups.
508
+ * @param params.validation - Optional Midnight mempool API request controls.
509
+ * @param params.loanToken - Loan token shared by every offer market.
510
+ * @param params.loanAssets - New loan reserve assigned to the submitted groups.
511
+ * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups.
512
+ * @returns Prepared group metadata, lazy requirements, and a synchronous mempool transaction builder.
513
+ * @throws {ChainIdMismatchError} when the client targets another chain.
514
+ * @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
515
+ * @throws {NonPositiveInputError} when `loanAssets` is non-positive.
516
+ * @throws {NegativeInputError} when `reservedLoanAssets` is negative.
517
+ * @throws {MidnightOfferSideMismatchError} when an offer is not lend-side.
518
+ * @throws {MidnightOfferMarketLoanTokenMismatchError} when an offer uses another loan token.
519
+ * @example
520
+ * ```ts
521
+ * const output = await midnight.makeLend({
522
+ * accountAddress: maker,
523
+ * offers: [offer],
524
+ * loanToken,
525
+ * loanAssets: 1_000_000n,
526
+ * });
527
+ * ```
528
+ */
529
+ async makeLend(params) {
530
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
531
+ assertPositiveAmount("loanAssets", params.loanAssets);
532
+ assertNonNegativeAmount("reservedLoanAssets", params.reservedLoanAssets ?? 0n);
533
+ const data = await this.getOffersData({
534
+ accountAddress: params.accountAddress,
535
+ offers: params.offers,
536
+ validation: params.validation,
537
+ });
538
+ validateOfferSides(data.tree.offers, true);
539
+ data.tree.offers.forEach((offer, index) => {
540
+ const market = "params" in offer.market ? offer.market.params : offer.market;
541
+ if (!isAddressEqual(market.loanToken, params.loanToken)) {
542
+ throw new MidnightOfferMarketLoanTokenMismatchError({
543
+ index,
544
+ expectedLoanToken: params.loanToken,
545
+ actualLoanToken: market.loanToken,
546
+ });
547
+ }
548
+ });
549
+ const midnight = getChainAddress(this.chainId, "midnight");
550
+ const signedPayloads = new Map();
551
+ return {
552
+ groups: data.groups,
553
+ root: data.tree.root,
554
+ ratifierType: data.ratifierType,
555
+ getRequirements: async () => {
556
+ const requirements = [];
557
+ requirements.push(...(await getMidnightApprovalRequirements({
558
+ viemClient: this.client.viemClient,
559
+ chainId: this.chainId,
560
+ token: params.loanToken,
561
+ owner: data.accountAddress,
562
+ spender: midnight,
563
+ amount: params.loanAssets + (params.reservedLoanAssets ?? 0n),
564
+ })));
565
+ requirements.push(...(await this.getRatifierRequirements({
566
+ offersData: data,
567
+ signedPayloads,
568
+ })));
569
+ return requirements;
570
+ },
571
+ buildTx: (signatures) => this.buildSubmitOffersTx({
572
+ offersData: data,
573
+ signatures,
574
+ signedPayloads,
575
+ }),
576
+ };
577
+ }
578
+ /**
579
+ * Validates borrow-side maker offers and prepares their ratifier requirements.
580
+ *
581
+ * @param params - Maker, raw borrow-side offers, and optional mempool validation controls.
582
+ * @param params.accountAddress - Maker expected on every offer.
583
+ * @param params.offers - Raw borrow-side offers or groups.
584
+ * @param params.validation - Optional Midnight mempool API request controls.
585
+ * @returns Prepared group metadata, lazy ratifier requirements, and a synchronous mempool transaction builder.
586
+ * @throws {ChainIdMismatchError} when the client targets another chain.
587
+ * @throws {MidnightOfferMarketAddressMismatchError} when an offer targets another Midnight deployment.
588
+ * @throws {MidnightOfferSideMismatchError} when an offer is not borrow-side.
589
+ * @example
590
+ * ```ts
591
+ * const output = await midnight.makeBorrow({
592
+ * accountAddress: maker,
593
+ * offers: [offer],
594
+ * });
595
+ * ```
596
+ */
597
+ async makeBorrow(params) {
598
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
599
+ const data = await this.getOffersData({
600
+ accountAddress: params.accountAddress,
601
+ offers: params.offers,
602
+ validation: params.validation,
603
+ });
604
+ validateOfferSides(data.tree.offers, false);
605
+ const signedPayloads = new Map();
606
+ return {
607
+ groups: data.groups,
608
+ root: data.tree.root,
609
+ ratifierType: data.ratifierType,
610
+ getRequirements: async () => {
611
+ return await this.getRatifierRequirements({
612
+ offersData: data,
613
+ signedPayloads,
614
+ });
615
+ },
616
+ buildTx: (signatures) => this.buildSubmitOffersTx({
617
+ offersData: data,
618
+ signatures,
619
+ signedPayloads,
620
+ }),
621
+ };
622
+ }
623
+ /**
624
+ * Prepares collateral supply followed by borrow-side maker-offer submission.
625
+ *
626
+ * @param params - Maker, market, collateral reserve, raw offers, and validation controls.
627
+ * @param params.accountAddress - Maker expected on every offer.
628
+ * @param params.offers - Raw borrow-side offers or groups.
629
+ * @param params.validation - Optional Midnight mempool API request controls.
630
+ * @param params.market - Market shared by every submitted offer.
631
+ * @param params.collateralAssets - Collateral supplied before offer submission.
632
+ * @param params.reservedCollateralAssets - Existing collateral reserved by other open groups.
633
+ * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
634
+ * @returns Prepared group metadata, lazy supply/ratifier requirements, and a synchronous mempool transaction builder.
635
+ * @throws {ChainIdMismatchError} when the client targets another chain.
636
+ * @throws {MidnightMarketAddressMismatchError} when the market targets another Midnight deployment.
637
+ * @throws {NonPositiveInputError} when `collateralAssets` is non-positive.
638
+ * @throws {NegativeInputError} when `reservedCollateralAssets` is negative.
639
+ * @throws {UnknownCollateralIndexError} when the selected collateral is not configured.
640
+ * @throws {MidnightOfferSideMismatchError} when an offer is not borrow-side.
641
+ * @throws {MarketIdMismatchError} when an offer targets another market.
642
+ * @example
643
+ * ```ts
644
+ * const output = await midnight.supplyCollateralMakeBorrow({
645
+ * accountAddress: maker,
646
+ * market: marketData.params,
647
+ * collateralAssets: 2_000_000n,
648
+ * offers: [offer],
649
+ * });
650
+ * ```
651
+ */
652
+ async supplyCollateralMakeBorrow(params) {
653
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
654
+ assertPositiveAmount("collateralAssets", params.collateralAssets);
655
+ assertNonNegativeAmount("reservedCollateralAssets", params.reservedCollateralAssets ?? 0n);
656
+ const market = params.market instanceof MarketParams
657
+ ? params.market
658
+ : MarketParams.from(params.market);
659
+ // Reject markets from another chain deployment before preparing requirements.
660
+ validateMidnightMarket({ market, chainId: this.chainId });
661
+ const collateralIndex = params.collateralIndex ?? 0n;
662
+ const collateral = MarketUtils.getCollateralByIndex(market, collateralIndex);
663
+ const data = await this.getOffersData({
664
+ accountAddress: params.accountAddress,
665
+ offers: params.offers,
666
+ validation: params.validation,
667
+ });
668
+ validateOfferSides(data.tree.offers, false);
669
+ const marketId = MarketUtils.toId(market);
670
+ for (const offer of data.tree.offers) {
671
+ const offerMarketId = MarketUtils.toId(offer.market);
672
+ if (offerMarketId.toLowerCase() !== marketId.toLowerCase()) {
673
+ throw new MarketIdMismatchError(offerMarketId, marketId);
674
+ }
675
+ }
676
+ const midnight = getChainAddress(this.chainId, "midnight");
677
+ const signedPayloads = new Map();
678
+ return {
679
+ groups: data.groups,
680
+ root: data.tree.root,
681
+ ratifierType: data.ratifierType,
682
+ getRequirements: async () => {
683
+ const requirements = [
684
+ ...(await getMidnightApprovalRequirements({
685
+ viemClient: this.client.viemClient,
686
+ chainId: this.chainId,
687
+ token: collateral.token,
688
+ owner: data.accountAddress,
689
+ spender: midnight,
690
+ amount: params.collateralAssets + (params.reservedCollateralAssets ?? 0n),
691
+ })),
692
+ midnightSupplyCollateral({
693
+ chainId: this.chainId,
694
+ market,
695
+ collateralIndex,
696
+ assets: params.collateralAssets,
697
+ onBehalf: data.accountAddress,
698
+ metadata: this.client.options.metadata,
699
+ }),
700
+ ...(await this.getRatifierRequirements({
701
+ offersData: data,
702
+ signedPayloads,
703
+ })),
704
+ ];
705
+ return requirements;
706
+ },
707
+ buildTx: (signatures) => this.buildSubmitOffersTx({
708
+ offersData: data,
709
+ signatures,
710
+ signedPayloads,
711
+ }),
712
+ };
713
+ }
714
+ /**
715
+ * Prepares redemption of accrued Midnight credit from a position snapshot.
716
+ *
717
+ * @param params - Position owner, accrued position, optional unit amount, and receiver.
718
+ * @param params.accountAddress - Position owner whose credit is redeemed.
719
+ * @param params.positionData - Accrued position and hydrated market snapshot.
720
+ * @param params.receiver - Optional credit receiver; defaults to the position owner.
721
+ * @param params.units - Optional credit units to redeem; defaults to the position face value.
722
+ * @returns No requirements and a synchronous redemption transaction builder.
723
+ * @throws {ChainIdMismatchError} when the position market targets another chain.
724
+ * @throws {MidnightMarketAddressMismatchError} when the position market targets another Midnight deployment.
725
+ * @throws {MissingAccrualPositionError} when no position snapshot is supplied.
726
+ * @throws {AccrualPositionUserMismatchError} when the position snapshot belongs to another account.
727
+ * @throws {NoMidnightCreditToRedeemError} when the selected unit amount is non-positive.
728
+ * @throws {MidnightRedeemExceedsCreditError} when the selected amount exceeds position credit.
729
+ * @throws {InsufficientMidnightWithdrawableLiquidityError} when market liquidity cannot cover the redemption.
730
+ * @example
731
+ * ```ts
732
+ * const output = midnight.redeem({
733
+ * accountAddress: lender,
734
+ * positionData,
735
+ * receiver: lender,
736
+ * });
737
+ * ```
738
+ */
739
+ redeem(params) {
740
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
741
+ if (!params.positionData) {
742
+ throw new MissingAccrualPositionError();
743
+ }
744
+ if (params.positionData.user == null ||
745
+ !isAddressEqual(params.positionData.user, params.accountAddress)) {
746
+ throw new AccrualPositionUserMismatchError(params.positionData.user ?? "unbound", params.accountAddress);
747
+ }
748
+ const market = params.positionData.market;
749
+ validateMarketData(market, this.chainId);
750
+ const units = params.units ?? params.positionData.faceValue;
751
+ if (params.units !== undefined && units <= 0n) {
752
+ throw new NonPositiveInputError("units", units);
753
+ }
754
+ if (units <= 0n)
755
+ throw new NoMidnightCreditToRedeemError(market.id);
756
+ if (params.positionData.credit < units) {
757
+ throw new MidnightRedeemExceedsCreditError({
758
+ market: market.id,
759
+ units,
760
+ credit: params.positionData.credit,
761
+ });
762
+ }
763
+ if (market.withdrawable < units) {
764
+ throw new InsufficientMidnightWithdrawableLiquidityError({
765
+ market: market.id,
766
+ units,
767
+ withdrawable: market.withdrawable,
768
+ });
769
+ }
770
+ return {
771
+ getRequirements: async () => [],
772
+ buildTx: () => midnightRedeem({
773
+ chainId: this.chainId,
774
+ market: market.params,
775
+ units,
776
+ onBehalf: params.accountAddress,
777
+ receiver: params.receiver,
778
+ metadata: this.client.options.metadata,
779
+ }),
780
+ };
781
+ }
782
+ /**
783
+ * Prepares a bundle that repays debt, withdraws collateral, or performs both.
784
+ *
785
+ * @param params - Account, market snapshot, repay and withdrawal amounts, collateral index, and deadline.
786
+ * @param params.accountAddress - Position owner whose debt or collateral is updated.
787
+ * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
788
+ * @param params.repayAssets - Loan assets repaid; may be zero for withdrawal-only flows.
789
+ * @param params.withdrawCollateralAssets - Collateral assets withdrawn; may be zero for repay-only flows.
790
+ * @param params.collateralIndex - Optional collateral index; defaults to `0n`.
791
+ * @param params.deadline - Bundle execution deadline timestamp.
792
+ * @returns Lazy loan approval/authorization requirements and a synchronous transaction builder.
793
+ * @throws {ChainIdMismatchError} when client or market data targets another chain.
794
+ * @throws {MidnightMarketAddressMismatchError} when market data targets another Midnight deployment.
795
+ * @throws {NegativeInputError} when an amount, index, or deadline is negative.
796
+ * @throws {NonPositiveInputError} when both repay and withdrawal amounts are zero.
797
+ * @throws {UnknownCollateralIndexError} when a positive withdrawal selects an unconfigured collateral.
798
+ * @example
799
+ * ```ts
800
+ * const output = midnight.repayWithdrawCollateral({
801
+ * accountAddress: borrower,
802
+ * marketData,
803
+ * repayAssets: 1_000_000n,
804
+ * withdrawCollateralAssets: 2_000_000n,
805
+ * deadline: maxUint256,
806
+ * });
807
+ * ```
808
+ */
809
+ repayWithdrawCollateral(params) {
810
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
811
+ validateMarketData(params.marketData, this.chainId);
812
+ assertNonNegativeAmount("repayAssets", params.repayAssets);
813
+ assertNonNegativeAmount("withdrawCollateralAssets", params.withdrawCollateralAssets);
814
+ assertNonNegativeAmount("deadline", params.deadline);
815
+ const market = params.marketData;
816
+ const collateralWithdrawals = params.withdrawCollateralAssets > 0n
817
+ ? [
818
+ {
819
+ collateralIndex: params.collateralIndex ?? 0n,
820
+ assets: params.withdrawCollateralAssets,
821
+ },
822
+ ]
823
+ : [];
824
+ for (const [index, withdrawal] of collateralWithdrawals.entries()) {
825
+ assertNonNegativeAmount(`collateralWithdrawals[${index}].collateralIndex`, withdrawal.collateralIndex);
826
+ // Validate the configured collateral before exposing requirement reads.
827
+ market.getCollateralByIndex(withdrawal.collateralIndex);
828
+ }
829
+ if (params.repayAssets === 0n &&
830
+ collateralWithdrawals.every((withdrawal) => withdrawal.assets === 0n)) {
831
+ throw new NonPositiveInputError("repay or withdraw amount", 0n);
832
+ }
833
+ const midnightBundles = getChainAddress(this.chainId, "midnightBundles");
834
+ return {
835
+ getRequirements: async () => {
836
+ const requirements = [];
837
+ if (params.repayAssets > 0n) {
838
+ requirements.push(...(await getMidnightApprovalRequirements({
839
+ viemClient: this.client.viemClient,
840
+ chainId: this.chainId,
841
+ token: market.params.loanToken,
842
+ owner: params.accountAddress,
843
+ spender: midnightBundles,
844
+ amount: params.repayAssets,
845
+ })));
846
+ }
847
+ const authorization = await getMidnightAuthorizationRequirement({
848
+ viemClient: this.client.viemClient,
849
+ chainId: this.chainId,
850
+ owner: params.accountAddress,
851
+ authorized: midnightBundles,
852
+ });
853
+ if (authorization)
854
+ requirements.push(authorization);
855
+ return requirements;
856
+ },
857
+ buildTx: () => midnightRepayWithdrawCollateral({
858
+ chainId: this.chainId,
859
+ market: market.params,
860
+ repayAssets: params.repayAssets,
861
+ withdrawCollateralAssets: params.withdrawCollateralAssets,
862
+ onBehalf: params.accountAddress,
863
+ collateralIndex: params.collateralIndex,
864
+ deadline: params.deadline,
865
+ metadata: this.client.options.metadata,
866
+ }),
867
+ };
868
+ }
869
+ /**
870
+ * Prepares full cancellation of a maker offer group.
871
+ *
872
+ * @param params - Group id and maker account whose consumption is updated.
873
+ * @param params.group - Offer group id to fully consume.
874
+ * @param params.accountAddress - Maker whose group consumption is updated.
875
+ * @returns No requirements and a synchronous cancellation transaction builder.
876
+ * @throws {ChainIdMismatchError} when the client targets another chain.
877
+ * @example
878
+ * ```ts
879
+ * const output = midnight.cancelOffer({
880
+ * group,
881
+ * accountAddress: maker,
882
+ * });
883
+ * ```
884
+ */
885
+ cancelOffer(params) {
886
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
887
+ return {
888
+ getRequirements: async () => [],
889
+ buildTx: () => midnightCancelOffer({
890
+ chainId: this.chainId,
891
+ group: params.group,
892
+ onBehalf: params.accountAddress,
893
+ metadata: this.client.options.metadata,
894
+ }),
895
+ };
896
+ }
897
+ async getRatifierRequirements(params) {
898
+ const data = params.offersData;
899
+ const requirements = [];
900
+ const authorization = await getMidnightAuthorizationRequirement({
901
+ viemClient: this.client.viemClient,
902
+ chainId: this.chainId,
903
+ owner: data.accountAddress,
904
+ authorized: data.ratifier,
905
+ });
906
+ if (authorization)
907
+ requirements.push(authorization);
908
+ if (data.ratifierType === "ecrecover") {
909
+ const chainId = this.chainId;
910
+ const action = {
911
+ type: "midnightOfferRootSignature",
912
+ args: {
913
+ root: data.tree.root,
914
+ ratifier: data.ratifier,
915
+ offers: data.tree.offers.length,
916
+ },
917
+ };
918
+ requirements.push({
919
+ action,
920
+ async sign(client, userAddress) {
921
+ const typedData = EcrecoverRatifierUtils.typedData({
922
+ tree: data.tree,
923
+ chainId,
924
+ });
925
+ const typedDataDefinition = {
926
+ domain: typedData.domain,
927
+ types: typedData.types,
928
+ primaryType: typedData.primaryType,
929
+ message: typedData.message,
930
+ };
931
+ const signature = await signAndVerifyTypedData({
932
+ client,
933
+ userAddress,
934
+ typedData: typedDataDefinition,
935
+ });
936
+ const items = await EcrecoverRatifierUtils.ratify({
937
+ tree: data.tree,
938
+ account: userAddress,
939
+ signature,
940
+ });
941
+ const payload = await Payload.encode(items);
942
+ params.signedPayloads.set(signature.toLowerCase(), payload);
943
+ return deepFreeze({
944
+ args: {
945
+ owner: userAddress,
946
+ root: data.tree.root,
947
+ signature,
948
+ payload,
949
+ },
950
+ action,
951
+ });
952
+ },
953
+ });
954
+ return requirements;
955
+ }
956
+ const ratifyRoot = await getSetterRatifierRatifyRootRequirement({
957
+ viemClient: this.client.viemClient,
958
+ chainId: this.chainId,
959
+ maker: data.accountAddress,
960
+ root: data.tree.root,
961
+ });
962
+ if (ratifyRoot)
963
+ requirements.push(ratifyRoot);
964
+ return requirements;
965
+ }
966
+ buildSubmitOffersTx(params) {
967
+ const data = params.offersData;
968
+ const collectedSignatures = params.signatures == null
969
+ ? undefined
970
+ : "action" in params.signatures
971
+ ? [params.signatures]
972
+ : params.signatures;
973
+ let payload;
974
+ if (data.ratifierType === "ecrecover") {
975
+ const { midnightOfferRoot: signature } = selectRequirementSignatures(collectedSignatures, { midnightOfferRoot: true });
976
+ if (signature == null) {
977
+ throw new MissingMidnightOfferRootSignatureError();
978
+ }
979
+ if (!isAddressEqual(signature.args.owner, data.accountAddress)) {
980
+ throw new MidnightOfferRootOwnerMismatchError({
981
+ expectedOwner: data.accountAddress,
982
+ actualOwner: signature.args.owner,
983
+ });
984
+ }
985
+ if (signature.args.root.toLowerCase() !== data.tree.root.toLowerCase()) {
986
+ throw new MidnightOfferRootMismatchError({
987
+ expectedRoot: data.tree.root,
988
+ actualRoot: signature.args.root,
989
+ });
990
+ }
991
+ if (signature.action.args.root.toLowerCase() !==
992
+ data.tree.root.toLowerCase()) {
993
+ throw new MidnightOfferRootMismatchError({
994
+ expectedRoot: data.tree.root,
995
+ actualRoot: signature.action.args.root,
996
+ });
997
+ }
998
+ if (!isAddressEqual(signature.action.args.ratifier, data.ratifier)) {
999
+ throw new MidnightOfferRootRatifierMismatchError({
1000
+ expectedRatifier: data.ratifier,
1001
+ actualRatifier: signature.action.args.ratifier,
1002
+ });
1003
+ }
1004
+ if (signature.action.args.offers !== data.tree.offers.length) {
1005
+ throw new MidnightOfferRootOfferCountMismatchError({
1006
+ expectedOffers: data.tree.offers.length,
1007
+ actualOffers: signature.action.args.offers,
1008
+ });
1009
+ }
1010
+ const signedPayload = params.signedPayloads.get(signature.args.signature.toLowerCase());
1011
+ if (signedPayload == null) {
1012
+ throw new UnpreparedMidnightOfferRootSignatureError();
1013
+ }
1014
+ payload = signedPayload;
1015
+ }
1016
+ else {
1017
+ selectRequirementSignatures(collectedSignatures, {});
1018
+ payload = data.setterPayload;
1019
+ }
1020
+ return mempoolSubmitOffers({
1021
+ chainId: this.chainId,
1022
+ groups: data.groups,
1023
+ root: data.tree.root,
1024
+ maker: data.accountAddress,
1025
+ ratifier: data.ratifier,
1026
+ ratifierType: data.ratifierType,
1027
+ offers: data.tree.offers.length,
1028
+ payload,
1029
+ metadata: this.client.options.metadata,
1030
+ });
1031
+ }
1032
+ }