@morpho-org/morpho-sdk 7.1.0-next.1 → 8.2.0-next.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 (193) hide show
  1. package/MIGRATION-v7-to-v8.md +290 -0
  2. package/README.md +11 -6
  3. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +2 -0
  4. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +2 -0
  5. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +17 -71
  6. package/lib/cjs/actions/midnight/cancelAndMake.js +41 -29
  7. package/lib/cjs/actions/midnight/redeem.d.ts +8 -1
  8. package/lib/cjs/actions/midnight/redeem.js +18 -1
  9. package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +19 -3
  10. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +24 -2
  11. package/lib/cjs/actions/midnight/supplyCollateral.d.ts +1 -0
  12. package/lib/cjs/actions/midnight/supplyCollateral.js +3 -0
  13. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +21 -6
  14. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +49 -14
  15. package/lib/cjs/actions/midnight/takeBorrow.d.ts +18 -5
  16. package/lib/cjs/actions/midnight/takeBorrow.js +44 -12
  17. package/lib/cjs/actions/midnight/takeLend.d.ts +10 -5
  18. package/lib/cjs/actions/midnight/takeLend.js +27 -9
  19. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +22 -7
  20. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +51 -27
  21. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +14 -5
  22. package/lib/cjs/actions/midnight/takeWithdraw.js +40 -9
  23. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +6 -2
  24. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +11 -6
  25. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +3 -0
  26. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +2 -1
  27. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +13 -2
  28. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +17 -6
  29. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +3 -0
  30. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +2 -1
  31. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +5 -0
  32. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +4 -1
  33. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +3 -1
  34. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +5 -1
  35. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +3 -1
  36. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -1
  37. package/lib/cjs/actions/requirements/validateClientChainId.d.ts +26 -0
  38. package/lib/cjs/actions/requirements/validateClientChainId.js +34 -0
  39. package/lib/cjs/blue/errors.d.ts +1 -1
  40. package/lib/cjs/blue/errors.js +3 -1
  41. package/lib/cjs/blue/types.d.ts +1 -1
  42. package/lib/cjs/blue/utils.d.ts +1 -1
  43. package/lib/cjs/blue/utils.js +5 -1
  44. package/lib/cjs/entities/blue/blue.d.ts +109 -27
  45. package/lib/cjs/entities/blue/blue.js +103 -28
  46. package/lib/cjs/entities/index.d.ts +1 -1
  47. package/lib/cjs/entities/midnight/deadline.d.ts +15 -0
  48. package/lib/cjs/entities/midnight/deadline.js +24 -0
  49. package/lib/cjs/entities/midnight/midnight.d.ts +427 -72
  50. package/lib/cjs/entities/midnight/midnight.js +864 -186
  51. package/lib/cjs/entities/midnight/publication.d.ts +134 -0
  52. package/lib/cjs/entities/midnight/publication.js +404 -0
  53. package/lib/cjs/entities/midnight/types.d.ts +26 -5
  54. package/lib/cjs/entities/requirements/assertContractCode.d.ts +49 -0
  55. package/lib/cjs/entities/requirements/assertContractCode.js +79 -0
  56. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +19 -4
  57. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +45 -18
  58. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.d.ts +3 -2
  59. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.js +5 -2
  60. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -1
  61. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +8 -2
  62. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +63 -11
  63. package/lib/cjs/entities/vaultV1/vaultV1.js +52 -15
  64. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +54 -12
  65. package/lib/cjs/entities/vaultV2/vaultV2.js +52 -15
  66. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +12 -6
  67. package/lib/cjs/entities/vaultV2BlueReallocationData.js +42 -14
  68. package/lib/cjs/errors.d.ts +1 -1
  69. package/lib/cjs/errors.js +4 -2
  70. package/lib/cjs/helpers/constant.d.ts +5 -0
  71. package/lib/cjs/helpers/constant.js +6 -1
  72. package/lib/cjs/helpers/index.d.ts +1 -1
  73. package/lib/cjs/helpers/index.js +2 -1
  74. package/lib/cjs/helpers/validate.d.ts +163 -8
  75. package/lib/cjs/helpers/validate.js +179 -8
  76. package/lib/cjs/helpers/validateMidnightBounds.d.ts +47 -0
  77. package/lib/cjs/helpers/validateMidnightBounds.js +79 -0
  78. package/lib/cjs/helpers/validateMidnightPublication.d.ts +12 -0
  79. package/lib/cjs/helpers/validateMidnightPublication.js +144 -0
  80. package/lib/cjs/helpers/validateMidnightReceiver.d.ts +29 -0
  81. package/lib/cjs/helpers/validateMidnightReceiver.js +84 -0
  82. package/lib/cjs/helpers/validateMidnightTakeFeasibility.d.ts +102 -0
  83. package/lib/cjs/helpers/validateMidnightTakeFeasibility.js +231 -0
  84. package/lib/cjs/index.d.ts +1 -0
  85. package/lib/cjs/index.js +3 -0
  86. package/lib/cjs/types/error.d.ts +197 -4
  87. package/lib/cjs/types/error.js +265 -5
  88. package/lib/cjs/types/index.d.ts +1 -0
  89. package/lib/cjs/types/index.js +1 -0
  90. package/lib/cjs/types/midnightCancelAndMake.d.ts +70 -0
  91. package/lib/cjs/types/midnightCancelAndMake.js +2 -0
  92. package/lib/cjs/types/midnightPublicationError.d.ts +332 -0
  93. package/lib/cjs/types/midnightPublicationError.js +376 -0
  94. package/lib/cjs/types/sharedLiquidity.d.ts +12 -7
  95. package/lib/cjs/types.d.ts +1 -1
  96. package/lib/cjs/utils.d.ts +2 -1
  97. package/lib/cjs/utils.js +8 -2
  98. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +2 -0
  99. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +2 -0
  100. package/lib/esm/actions/midnight/cancelAndMake.d.ts +17 -71
  101. package/lib/esm/actions/midnight/cancelAndMake.js +42 -30
  102. package/lib/esm/actions/midnight/redeem.d.ts +8 -1
  103. package/lib/esm/actions/midnight/redeem.js +18 -1
  104. package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +19 -3
  105. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +24 -2
  106. package/lib/esm/actions/midnight/supplyCollateral.d.ts +1 -0
  107. package/lib/esm/actions/midnight/supplyCollateral.js +3 -0
  108. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +21 -6
  109. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +52 -17
  110. package/lib/esm/actions/midnight/takeBorrow.d.ts +18 -5
  111. package/lib/esm/actions/midnight/takeBorrow.js +47 -15
  112. package/lib/esm/actions/midnight/takeLend.d.ts +10 -5
  113. package/lib/esm/actions/midnight/takeLend.js +27 -9
  114. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +22 -7
  115. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +52 -28
  116. package/lib/esm/actions/midnight/takeWithdraw.d.ts +14 -5
  117. package/lib/esm/actions/midnight/takeWithdraw.js +41 -10
  118. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +6 -2
  119. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +13 -8
  120. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +3 -0
  121. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +2 -1
  122. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +13 -2
  123. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +17 -6
  124. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +3 -0
  125. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +2 -1
  126. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +5 -0
  127. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +4 -1
  128. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +3 -1
  129. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +5 -1
  130. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +3 -1
  131. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -1
  132. package/lib/esm/actions/requirements/validateClientChainId.d.ts +26 -0
  133. package/lib/esm/actions/requirements/validateClientChainId.js +30 -0
  134. package/lib/esm/blue/errors.d.ts +1 -1
  135. package/lib/esm/blue/errors.js +1 -1
  136. package/lib/esm/blue/types.d.ts +1 -1
  137. package/lib/esm/blue/utils.d.ts +1 -1
  138. package/lib/esm/blue/utils.js +1 -1
  139. package/lib/esm/entities/blue/blue.d.ts +109 -27
  140. package/lib/esm/entities/blue/blue.js +104 -29
  141. package/lib/esm/entities/index.d.ts +1 -1
  142. package/lib/esm/entities/midnight/deadline.d.ts +15 -0
  143. package/lib/esm/entities/midnight/deadline.js +20 -0
  144. package/lib/esm/entities/midnight/midnight.d.ts +427 -72
  145. package/lib/esm/entities/midnight/midnight.js +865 -187
  146. package/lib/esm/entities/midnight/publication.d.ts +134 -0
  147. package/lib/esm/entities/midnight/publication.js +397 -0
  148. package/lib/esm/entities/midnight/types.d.ts +26 -5
  149. package/lib/esm/entities/requirements/assertContractCode.d.ts +49 -0
  150. package/lib/esm/entities/requirements/assertContractCode.js +74 -0
  151. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +19 -4
  152. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +47 -20
  153. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.d.ts +3 -2
  154. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.js +5 -2
  155. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -1
  156. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +8 -2
  157. package/lib/esm/entities/vaultV1/vaultV1.d.ts +63 -11
  158. package/lib/esm/entities/vaultV1/vaultV1.js +53 -16
  159. package/lib/esm/entities/vaultV2/vaultV2.d.ts +54 -12
  160. package/lib/esm/entities/vaultV2/vaultV2.js +53 -16
  161. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +12 -6
  162. package/lib/esm/entities/vaultV2BlueReallocationData.js +42 -14
  163. package/lib/esm/errors.d.ts +1 -1
  164. package/lib/esm/errors.js +1 -1
  165. package/lib/esm/helpers/constant.d.ts +5 -0
  166. package/lib/esm/helpers/constant.js +5 -0
  167. package/lib/esm/helpers/index.d.ts +1 -1
  168. package/lib/esm/helpers/index.js +1 -1
  169. package/lib/esm/helpers/validate.d.ts +163 -8
  170. package/lib/esm/helpers/validate.js +177 -7
  171. package/lib/esm/helpers/validateMidnightBounds.d.ts +47 -0
  172. package/lib/esm/helpers/validateMidnightBounds.js +72 -0
  173. package/lib/esm/helpers/validateMidnightPublication.d.ts +12 -0
  174. package/lib/esm/helpers/validateMidnightPublication.js +139 -0
  175. package/lib/esm/helpers/validateMidnightReceiver.d.ts +29 -0
  176. package/lib/esm/helpers/validateMidnightReceiver.js +80 -0
  177. package/lib/esm/helpers/validateMidnightTakeFeasibility.d.ts +102 -0
  178. package/lib/esm/helpers/validateMidnightTakeFeasibility.js +226 -0
  179. package/lib/esm/index.d.ts +1 -0
  180. package/lib/esm/index.js +1 -0
  181. package/lib/esm/types/error.d.ts +197 -4
  182. package/lib/esm/types/error.js +253 -2
  183. package/lib/esm/types/index.d.ts +1 -0
  184. package/lib/esm/types/index.js +1 -0
  185. package/lib/esm/types/midnightCancelAndMake.d.ts +70 -0
  186. package/lib/esm/types/midnightCancelAndMake.js +1 -0
  187. package/lib/esm/types/midnightPublicationError.d.ts +332 -0
  188. package/lib/esm/types/midnightPublicationError.js +359 -0
  189. package/lib/esm/types/sharedLiquidity.d.ts +12 -7
  190. package/lib/esm/types.d.ts +1 -1
  191. package/lib/esm/utils.d.ts +2 -1
  192. package/lib/esm/utils.js +2 -1
  193. package/package.json +7 -6
@@ -0,0 +1,290 @@
1
+ # Migrating `@morpho-org/morpho-sdk` from v7 to v8
2
+
3
+ Version 8 makes token metadata and RPC-backed requirement reads fail closed.
4
+ These calls now throw typed errors instead of returning partial or default values.
5
+
6
+ ## Token metadata fails closed
7
+
8
+ `@morpho-org/blue-sdk-viem` v7 token metadata reads now fail closed. The
9
+ re-exported `fetchToken` and its `Token.fetch` facades change behavior, and
10
+ requirement resolvers that encode ERC-2612 permits can reject earlier and more
11
+ precisely.
12
+
13
+ The same behavior reaches vault share-token reads through `fetchVaultConfig`,
14
+ `fetchVault`, `fetchVaultUser`, `fetchAccrualVault`, `fetchVaultV2` and
15
+ `fetchAccrualVaultV2`. `MorphoVaultV1.getData()`, `MorphoVaultV2.getData()` and
16
+ `MorphoBlue.getVaultV2BlueReallocationData()` also use these fetch paths. These
17
+ calls can throw `UnknownTokenError` for unusable share-token decimals,
18
+ `MalformedTokenMetadataError` when the share token's `eip712Domain()` or `bytes32`
19
+ `name`/`symbol` retry — or the deployless query result — is malformed, and
20
+ propagate transport or RPC errors from share-token metadata reads.
21
+
22
+ Import these classes from `@morpho-org/morpho-sdk/blue/errors`, or from
23
+ `@morpho-org/morpho-sdk/errors`, which exports `UnknownTokenError` as
24
+ `UnknownBlueTokenError`. The package root doesn't export them.
25
+
26
+ ### Token fetches reject on missing decimals and transport failures
27
+
28
+ `fetchToken` throws `UnknownTokenError` when `decimals()` reverts, the address
29
+ has no code, the returned data cannot be decoded, or the value is outside
30
+ 0–255. v7 returned `decimals: 0` in every one of these cases. Genuine
31
+ 0-decimal tokens still resolve with `decimals: 0`.
32
+
33
+ Transport errors and JSON-RPC errors that are not revert-shaped now propagate
34
+ unchanged from any metadata read; a revert-shaped RPC error (a data-less
35
+ `-32000 "execution reverted"`, even on a 5xx response) still reads as the
36
+ method being absent. Only
37
+ `name`, `symbol` and `eip712Domain` resolve to `undefined`, and only when the
38
+ call reverts or the contract has no code; a `name`/`symbol` that does not
39
+ decode as `string` is retried as `bytes32`, and an undecodable `bytes32` retry
40
+ or `eip712Domain()` result throws `MalformedTokenMetadataError` — its `cause`
41
+ holds the viem decode error or the deployless query's revert when one exists,
42
+ while a `bytes32` retry returning data that is not exactly 32 bytes throws
43
+ with no `cause`. Transport errors propagate.
44
+ A deployless query that reports `decimals: 0` falls back to direct ERC-20
45
+ reads. With `deployless: true` or `"force"`, a query that reports malformed
46
+ `name()`/`symbol()`/`eip712Domain()` returndata throws
47
+ `MalformedTokenMetadataError` instead of falling back: the query is stricter
48
+ than viem's decoding (for example, it requires the `0x20` string offset), so a
49
+ token that direct reads accept can be rejected in the default mode.
50
+
51
+ ### Permit requirements throw typed errors
52
+
53
+ `encodeErc20Permit` throws `MissingPermitDomainNameError` when the token
54
+ exposes neither `name()` nor an EIP-5267 domain, and `UnknownTokenError` on
55
+ absent or invalid `decimals()`. Requirement resolution handles the missing
56
+ domain case for ERC-20 funding permits by falling back to Permit2 or a classic
57
+ approval. Vault V1 share permits do not use this fallback: when an insufficient
58
+ share allowance requires a permit, `encodeVaultSharesPermit` and the
59
+ `withdraw`, `redeem`, `migrateToV2`, and `inKindRedeem` requirement paths throw
60
+ `MissingPermitDomainNameError` if the share token has neither `name()` nor an
61
+ EIP-5267 domain. Transport errors from metadata reads and `UnknownTokenError`
62
+ still reject. With
63
+ `useSimplePermit`, a transport or RPC error from the ERC-2612 `nonces()` probe
64
+ now propagates instead of falling back; only recognized contract reverts and
65
+ undecodable return data fall back to Permit2 or classic approval.
66
+
67
+ ## Wrong-chain RPC fails closed
68
+
69
+ v8 checks the RPC's `eth_chainId` before allowance, nonce, or position reads.
70
+ Guarded `getRequirements()` flows first read `eth_getCode` for their registry
71
+ targets and probe `eth_chainId` when a target has no code, so a wrong-chain
72
+ endpoint still fails with `ChainIdMismatchError`. Vault V1 `inKindRedeem` and
73
+ Vault V2 `inKindRedeem` / `forceWithdraw` validate the client chain before
74
+ those code checks.
75
+
76
+ ### Calls that can now throw `ChainIdMismatchError` for the RPC's chain
77
+
78
+ Each of these calls sends its own uncached `eth_chainId` request and throws
79
+ `ChainIdMismatchError(observed, expected)` when the RPC reports another chain.
80
+ The same class was already thrown when the client declared another chain or
81
+ none, so existing `instanceof ChainIdMismatchError` handling covers both
82
+ cases. Treat it as a configuration error: point the client's transport at an
83
+ RPC URL for the expected chain.
84
+
85
+ - Entity reads: `MorphoBlue.getMarketData`, `MorphoBlue.getPositionData`,
86
+ `MorphoBlue.getVaultV2BlueReallocationData`, `MorphoVaultV1.getData`,
87
+ `MorphoVaultV2.getData`, `MorphoMidnight.getMarketData`,
88
+ `MorphoMidnight.getPositionData`, and `MorphoMidnight.supplyBlueMakeLend`.
89
+ - `getRequirements()` on action outputs that read on-chain state, including
90
+ Vault V1 `inKindRedeem` and Vault V2 `forceWithdraw` / `inKindRedeem`.
91
+ - Exported resolvers: `getBundlesTokenRequirements`, `getUnusedPermit2Nonce`,
92
+ `getBlueAuthorizationRequirement`, `getMidnightApprovalRequirements`,
93
+ `getMidnightAuthorizationRequirement` and `encodeErc20Permit`.
94
+
95
+ ### Calls that can now throw viem errors from `eth_chainId`
96
+
97
+ These calls can also throw a `viem.BaseError` (for example `HttpRequestError`
98
+ or `TimeoutError`) when the `eth_chainId` request itself fails. Handle it like
99
+ any other transport error from the call.
100
+
101
+ ### Not detected
102
+
103
+ An RPC that answers `eth_chainId` with the expected chain while serving another
104
+ chain's state is not detected (see `THREAT_MODEL.md`, RPC).
105
+
106
+ ## Missing contract code fails closed
107
+
108
+ Blue, VaultV1 and VaultV2 prepared `getRequirements()` calls now throw
109
+ `MissingContractCodeError` when a registered bundles or protocol target has no
110
+ code. `simulate()` rejects calldata transactions to code-less addresses before
111
+ `eth_simulateV1`. These checks normally read target code before other
112
+ requirements; VaultV1 `inKindRedeem` and VaultV2 `inKindRedeem` /
113
+ `forceWithdraw` first validate the client chain with `eth_chainId`.
114
+
115
+ Every guarded Blue, VaultV1 and VaultV2 `getRequirements()` call checks each
116
+ distinct registered target with one `eth_getCode` request before its other
117
+ requirement reads, after any `eth_chainId` validation noted above. This also
118
+ applies to native-funded `MorphoBlue.supply`, the native-only legs of
119
+ `repayWithdrawCollateral` and `supplyCollateralBorrow`, and native-funded
120
+ VaultV1 and VaultV2 deposits; in v7 these paths returned no requirements
121
+ without RPC reads.
122
+
123
+ The remaining requirement reads of VaultV1 `inKindRedeem`, VaultV2
124
+ `inKindRedeem` and VaultV2 `forceWithdraw` are unchanged from v7 and follow the
125
+ client's `batch.multicall` setting. They now run after the `eth_chainId`
126
+ validation and the `eth_getCode` checks.
127
+
128
+ ### Calls that can now throw viem errors from `eth_getCode`
129
+
130
+ A failed `eth_getCode` request rejects `getRequirements()` with the underlying
131
+ `viem.BaseError` (for example, `HttpRequestError` or `TimeoutError`). Handle it
132
+ like any other transport error from the call.
133
+
134
+ ## Midnight taker health checks
135
+
136
+ Midnight `takeBorrow`, `supplyCollateralTakeBorrow`, `takeRepayWithdrawCollateral`, and
137
+ `repayWithdrawCollateral` now require caller-supplied `positionData` and `collateralPrices` to
138
+ validate the position after the operation using the SDK's fixed `DEFAULT_LLTV_BUFFER` (0.5%), the
139
+ same buffer used by Blue flows.
140
+
141
+ Get `positionData` from
142
+ `midnight.getPositionData({ marketId: marketData.id, accountAddress })`. For each collateral index,
143
+ read `price()` from the oracle at `marketData.params.collateralParams[i].oracle` with viem's
144
+ `readContract`. Prices use `ORACLE_PRICE_SCALE` and must be in the same index order as the market's
145
+ collateral parameters. Pass `collateralPrices: []` only when the SDK's conservative post-operation
146
+ debt is zero, such as after a `full` repay, a repayment units target covering `positionData.debt`,
147
+ or `minUnits` / `repay.assets` covering it. Otherwise, pass the prices. For example:
148
+
149
+ ```ts
150
+ midnight.takeBorrow({
151
+ marketData,
152
+ positionData,
153
+ collateralPrices,
154
+ target,
155
+ // ...
156
+ });
157
+ ```
158
+
159
+ The methods can throw:
160
+
161
+ - `BorrowExceedsSafeLtvError` when a borrow exceeds the buffered maximum debt.
162
+ - `WithdrawMakesPositionUnhealthyError` when a withdrawal leaves debt above the buffered maximum.
163
+ - `WithdrawExceedsCollateralError` when a withdrawal exceeds the position's collateral.
164
+ - `MissingMarketPriceError` when held collateral has no supplied oracle price.
165
+ - `UnknownCollateralIndexError` when a supplied collateral index is not configured on the market.
166
+ - `AccrualPositionUserMismatchError` when `positionData.user` differs from `accountAddress`.
167
+ - `MarketIdMismatchError` when `positionData.marketId` differs from `marketData.id`.
168
+
169
+ ## Midnight `takeWithdraw` rejects a zero receiver
170
+
171
+ `midnightTakeWithdraw` and `MorphoMidnight.takeWithdraw` throw
172
+ `MidnightZeroReceiverError` (with `field: "receiver"`) when `receiver` is the
173
+ zero address. v7 built a transaction that sent the withdrawn loan assets to
174
+ `0x0`, burning them. The entity method defaults `receiver` to `accountAddress`,
175
+ so only an explicit `0x0` throws. Pass the address that should receive the
176
+ withdrawn assets.
177
+
178
+ Import `MidnightZeroReceiverError` from `@morpho-org/morpho-sdk`.
179
+
180
+ ## Midnight receivers reject contracts that cannot forward funds
181
+
182
+ The Midnight take, repay-withdraw and redeem flows throw
183
+ `MidnightContractReceiverError` when a receiver is a contract that would keep
184
+ the assets permanently. v7 built these transactions, and the assets were lost
185
+ once they executed. The check covers:
186
+
187
+ - `receiver` on `takeBorrow`, `supplyCollateralTakeBorrow`, `takeWithdraw` and
188
+ `redeem`;
189
+ - `collateralReceiver` on `takeRepayWithdrawCollateral` and
190
+ `repayWithdrawCollateral`, when collateral withdrawals are requested;
191
+ - `referralFeeRecipient` on `takeLend`, `takeBorrow`,
192
+ `supplyCollateralTakeBorrow`, `takeWithdraw` and
193
+ `takeRepayWithdrawCollateral`, when `referralFeePct` is positive.
194
+
195
+ It applies to the `MorphoMidnight` entity methods and to their `midnight*`
196
+ builders (`midnightTakeBorrow`, `midnightRedeem`, and so on). A receiver is
197
+ rejected when it is one of the chain's Midnight protocol contracts
198
+ (`midnight`, `midnightBundlesV2`, `midnightBlueBuyCallbackFactory`,
199
+ `midnightMempool`, `ecrecoverRatifier`, `ecrecoverAuthorizer`,
200
+ `setterRatifier`, `priceRatifierV1`, `rateRatifierV1`), the market's loan
201
+ token, or one of its collateral tokens. The error's `field`, `receiver` and
202
+ `contract` properties name the rejected input. Pass an account that can hold
203
+ or forward the assets.
204
+
205
+ ### `redeem` rejects a zero receiver and throws on the method call
206
+
207
+ `midnightRedeem` and `MorphoMidnight.redeem` also throw
208
+ `MidnightZeroReceiverError` (with `field: "receiver"`) when `receiver` is the
209
+ zero address. When `receiver` is omitted it defaults to the position owner, so
210
+ only an explicit `0x0` throws.
211
+
212
+ In v7, `MorphoMidnight.redeem` built its transaction inside `buildTx()`. v8
213
+ builds it when `redeem()` is called, so the receiver errors, and any other
214
+ error from `midnightRedeem`, now throw from `redeem()` itself. Move a `try`
215
+ that wraps only `buildTx()` so it also wraps the `redeem()` call:
216
+
217
+ ```ts
218
+ // v7
219
+ const output = midnight.redeem({ accountAddress, positionData, receiver });
220
+ try {
221
+ const tx = output.buildTx();
222
+ } catch (error) {
223
+ // ...
224
+ }
225
+
226
+ // v8
227
+ try {
228
+ const output = midnight.redeem({ accountAddress, positionData, receiver });
229
+ const tx = output.buildTx();
230
+ } catch (error) {
231
+ // ...
232
+ }
233
+ ```
234
+
235
+ ## Midnight `MidnightZeroReceiverError.field` adds `"collateralReceiver"`
236
+
237
+ `midnightRepayWithdrawCollateral`, `midnightTakeRepayWithdrawCollateral`,
238
+ `MorphoMidnight.repayWithdrawCollateral` and
239
+ `MorphoMidnight.takeRepayWithdrawCollateral` throw `MidnightZeroReceiverError`
240
+ with `field: "collateralReceiver"` when collateral withdrawals are requested
241
+ and `collateralReceiver` is the zero address. v7 built a transaction that sent
242
+ the collateral to `0x0`. Calls without collateral withdrawals still accept a
243
+ zero `collateralReceiver`.
244
+
245
+ The type of `MidnightZeroReceiverError.field` widens from `"receiver"` to
246
+ `"receiver" | "collateralReceiver"`. An exhaustive `switch` on `field` no
247
+ longer compiles until it handles `"collateralReceiver"`:
248
+
249
+ ```ts
250
+ if (error instanceof MidnightZeroReceiverError) {
251
+ switch (error.field) {
252
+ case "receiver":
253
+ // ...
254
+ break;
255
+ case "collateralReceiver":
256
+ // ...
257
+ break;
258
+ }
259
+ }
260
+ ```
261
+
262
+ ## Midnight referral fees are capped at 10%
263
+
264
+ `takeLend`, `takeBorrow`, `supplyCollateralTakeBorrow`, `takeWithdraw` and
265
+ `takeRepayWithdrawCollateral`, as entity methods and as `midnight*` builders,
266
+ throw `MidnightReferralFeePctExceededError` when `referralFeePct` is above 10%
267
+ (`WAD / 10n`). v7 accepted any fee the contract accepts, which is any value
268
+ below `WAD`. The cap is enforced only by the SDK; the contract does not
269
+ enforce it. `MidnightReferralFeePctExceededError` extends
270
+ `InputExceedsMaxError`, so existing `instanceof InputExceedsMaxError` handling
271
+ also catches it. Lower `referralFeePct` to 10% or less.
272
+
273
+ ## Midnight maker deadlines throw `ExpiredDeadlineError`
274
+
275
+ `makeLend`, `makeBorrow`, `supplyBlueMakeLend`, `makeWithdraw`, `makeRepay`,
276
+ `supplyCollateralMakeBorrow`, `repayWithdrawCollateral` and `cancelOffers`
277
+ throw `ExpiredDeadlineError` when `deadline` is at or before the local clock
278
+ (`Time.timestamp()`), before any API read. v7 built a transaction that
279
+ reverted on-chain with `DeadlinePassed()`. `maxUint256` still means no expiry.
280
+
281
+ A zero or negative `deadline` on these methods now throws
282
+ `ExpiredDeadlineError` instead of `NonPositiveInputError`. Code that catches
283
+ `NonPositiveInputError` to detect a bad deadline must catch
284
+ `ExpiredDeadlineError` instead; its `deadline` and `timestamp` properties hold
285
+ the rejected deadline and the time it was checked against. The `midnight*`
286
+ transaction builders stay clock-free and do not run this check.
287
+
288
+ Import `MidnightContractReceiverError`, `MidnightZeroReceiverError`,
289
+ `MidnightReferralFeePctExceededError`, `InputExceedsMaxError` and
290
+ `ExpiredDeadlineError` from `@morpho-org/morpho-sdk`.
package/README.md CHANGED
@@ -24,9 +24,14 @@ General Vault V1 operations remain supported.
24
24
  pnpm add @morpho-org/morpho-sdk
25
25
  ```
26
26
 
27
- Upgrading from v6? Read the [v6 → v7 migration guide](./MIGRATION-v6-to-v7.md) before updating Midnight
28
- maker integrations. Upgrading from v5? Read the [v5 → v6 migration guide](./MIGRATION-v5-to-v6.md) before updating vault
29
- deposit or Blue write integrations.
27
+ Upgrading from v6? Read the [v6 → v7 migration guide](./MIGRATION-v6-to-v7.md) before updating
28
+ Midnight maker integrations. Upgrading from v7? Read the
29
+ [v7 → v8 migration guide](./MIGRATION-v7-to-v8.md) before relying on fail-closed token metadata or
30
+ permit requirement errors. The guide also covers wrong-chain RPC checks (`eth_chainId`)
31
+ on entity reads and requirement resolvers. It also covers missing-contract checks. Upgrading from
32
+ v5? Read the
33
+ [v5 → v6 migration guide](./MIGRATION-v5-to-v6.md) before updating vault deposit or Blue write
34
+ integrations.
30
35
 
31
36
  ## Actions
32
37
 
@@ -42,9 +47,9 @@ BlueBundlesV1, and the remaining rows identify their destination.
42
47
  | | `forceRedeem` | Vault multicall |
43
48
  | | `inKindRedeem` | VaultExitBundlesV1 |
44
49
  | **Blue** | `supply`, `withdraw`, `supplyCollateral`, `borrow`, `supplyCollateralBorrow`, `repay`, `withdrawCollateral`, `repayWithdrawCollateral`, `refinance` | BlueBundlesV1 |
45
- | **Midnight** | `takeLend`, `takeBorrow`, `supplyCollateralTakeBorrow`, `takeRepayWithdrawCollateral`, `repayWithdrawCollateral`, `takeWithdraw` | MidnightBundlesV2 (Ethereum, Base, Arc, Robinhood) |
50
+ | **Midnight** | `takeLend`, `takeBorrow`, `supplyCollateralTakeBorrow`, `takeRepayWithdrawCollateral`, `repayWithdrawCollateral`, `takeWithdraw` | MidnightBundlesV2 (Ethereum, Base, Arc, Robinhood, Tempo) |
46
51
  | | `supplyCollateral`, `redeem` | Direct call |
47
- | | `makeLend`, `makeBorrow`, `makeWithdraw`, `makeRepay`, `supplyCollateralMakeBorrow`, `supplyBlueMakeLend`, `cancelOffers` | MidnightBundlesV2 (Ethereum, Base, Arc, Robinhood) |
52
+ | | `makeLend`, `makeBorrow`, `makeWithdraw`, `makeRepay`, `supplyCollateralMakeBorrow`, `supplyBlueMakeLend`, `cancelOffers` | MidnightBundlesV2 (Ethereum, Base, Arc, Robinhood, Tempo) |
48
53
 
49
54
  `makeBorrow` publishes without collateral; `supplyCollateralMakeBorrow` requires collateral and
50
55
  supplies it in the same transaction.
@@ -240,7 +245,7 @@ instant liquidation. Blue writes do not accept `slippageTolerance`, `minSharePri
240
245
 
241
246
  Protocol-specific names are qualified in shared facades, for example `fetchBluePosition` and `fetchMidnightPosition` from `@morpho-org/morpho-sdk/fetch`. Canonical raw upstream names remain available under `/blue/{abis,addresses,constants,entities,errors,fetch,types,utils}` and `/midnight/{abis,constants,entities,errors,fetch,types,utils}`.
242
247
 
243
- Morpho-ts registers MidnightBundlesV2 on Ethereum, Base, Arc, and Robinhood.
248
+ Morpho-ts registers MidnightBundlesV2 on Ethereum, Base, Arc, Robinhood, and Tempo.
244
249
 
245
250
  ```typescript
246
251
  const midnight = client.morpho.midnight(8453);
@@ -32,6 +32,7 @@ export type BundlesTokenRequirementsState = {
32
32
  * @param params.amount - Exact pull amount in the token's smallest unit; zero returns no requirements.
33
33
  * @param params.deadline - Signature expiration as a Unix timestamp in seconds; in the
34
34
  * SignatureTransfer branch it must be positive, within uint256, and in the future.
35
+ * @param params.now - Timestamp the SignatureTransfer deadline is validated against; defaults to the current time.
35
36
  * @param params.state - Prefetched state for either classic approval or Permit2 SignatureTransfer.
36
37
  * @param params.state.type - `approval` for a direct allowance or `permit2SignatureTransfer` for a signed pull.
37
38
  * @param params.state.allowance - In the approval branch, current token allowance from `owner` to `spender`.
@@ -76,5 +77,6 @@ export declare const resolveBundlesTokenRequirements: (params: {
76
77
  readonly chainId: number;
77
78
  readonly amount: bigint;
78
79
  readonly deadline: bigint;
80
+ readonly now?: bigint;
79
81
  readonly state: BundlesTokenRequirementsState;
80
82
  }) => readonly (Readonly<Transaction<ERC20ApprovalAction>> | BundlesTokenSignatureRequirement)[];
@@ -27,6 +27,7 @@ const getRequirementsApproval_js_1 = require("../requirements/getRequirementsApp
27
27
  * @param params.amount - Exact pull amount in the token's smallest unit; zero returns no requirements.
28
28
  * @param params.deadline - Signature expiration as a Unix timestamp in seconds; in the
29
29
  * SignatureTransfer branch it must be positive, within uint256, and in the future.
30
+ * @param params.now - Timestamp the SignatureTransfer deadline is validated against; defaults to the current time.
30
31
  * @param params.state - Prefetched state for either classic approval or Permit2 SignatureTransfer.
31
32
  * @param params.state.type - `approval` for a direct allowance or `permit2SignatureTransfer` for a signed pull.
32
33
  * @param params.state.allowance - In the approval branch, current token allowance from `owner` to `spender`.
@@ -123,6 +124,7 @@ const resolveBundlesTokenRequirements = (params) => {
123
124
  chainId: params.chainId,
124
125
  nonce: params.state.permit2Nonce,
125
126
  deadline: params.deadline,
127
+ now: params.now,
126
128
  }),
127
129
  ];
128
130
  };
@@ -1,78 +1,19 @@
1
- import { type MarketInput } from "@morpho-org/midnight-sdk";
2
- import { type Address, type Hex } from "viem";
3
- import { type Metadata, type MidnightBlueSupply, type MidnightCancelAndMakeAction, type MidnightCollateralTransfer, type MidnightGroupCancellation, type Transaction } from "../../types/index.js";
4
- /**
5
- * Delegated root-activation signature passed to the ratifier's `setIsRootRatifiedWithSig`.
6
- * Omit it to activate the root directly with `setIsRootRatified`.
7
- */
8
- export interface MidnightRootActivationSignature {
9
- /** Tree height committed by the signature. */
10
- readonly height: bigint;
11
- /** Ratifier signature nonce. */
12
- readonly nonce: bigint;
13
- /** Signature deadline timestamp, independent of the bundle deadline. */
14
- readonly deadline: bigint;
15
- readonly v: number;
16
- readonly r: Hex;
17
- readonly s: Hex;
18
- }
19
- /** Collateral supplied for the maker before root activation; every offer must target `market`. */
20
- export interface MidnightMakeBorrowCollateral {
21
- readonly market: MarketInput;
22
- readonly supplies: readonly MidnightCollateralTransfer[];
23
- }
24
- /** Offer root activated and published by a Midnight Bundles V2 maker bundle. */
25
- export interface MidnightOfferPublication {
26
- /**
27
- * The chain's registered `priceRatifierV1` or `rateRatifierV1`, which activates `root`.
28
- * MidnightBundlesV2 authorizes it over the maker's whole Midnight account.
29
- */
30
- readonly ratifier: Address;
31
- /** Offer tree root to activate. */
32
- readonly root: Hex;
33
- /** Distinct offer groups contained in `root`. */
34
- readonly groups: readonly Hex[];
35
- /** Encoded offer payload for `root`, published to the Midnight log. */
36
- readonly payload: Hex;
37
- /** Optional delegated root-activation signature. */
38
- readonly rootSignature?: MidnightRootActivationSignature;
39
- /** Optional loan assets parked on Morpho Blue for the maker; share-price slippage is not checked. */
40
- readonly blueSupply?: MidnightBlueSupply;
41
- /** Optional collateral supplied to `market` for the maker before activation. */
42
- readonly collateral?: MidnightMakeBorrowCollateral;
43
- }
44
- /**
45
- * Parameters for encoding a Midnight Bundles V2 maker bundle: an offer publication or repost, or,
46
- * without a publication, a cancellation of offer groups only.
47
- */
48
- export interface MidnightCancelAndMakeParams {
49
- /** Chain id used to resolve `MidnightBundlesV2`. */
50
- readonly chainId: number;
51
- /** Offer groups to cancel, each with its largest accepted consumption. Empty for a new publication. */
52
- readonly cancellations: readonly MidnightGroupCancellation[];
53
- /** Bundle execution deadline timestamp. Pass `maxUint256` explicitly for no expiry. */
54
- readonly deadline: bigint;
55
- /**
56
- * Optional native ETH sent as `value`; the bundle wraps it into the chain's wNative and transfers
57
- * it to `msg.sender` before pulling. It may cover part or all of the maximum wNative amount this
58
- * call can pull, but not more. Any wrapped native not pulled stays in the sender's wallet as
59
- * wNative. The wNative approval to `MidnightBundlesV2` is still required for the full pulled amount.
60
- */
61
- readonly nativeAmount?: bigint;
62
- /** Optional analytics metadata appended to calldata. */
63
- readonly metadata?: Metadata;
64
- /** Offers to publish after the cancellations. Omit to cancel offer groups only. */
65
- readonly publication?: MidnightOfferPublication;
66
- }
1
+ import { type MidnightCancelAndMakeAction, type Transaction } from "../../types/index.js";
2
+ import type { MidnightCancelAndMakeParams } from "../../types/midnightCancelAndMake.js";
3
+ export type { MidnightCancelAndMakeParams, MidnightMakeBorrowCollateral, MidnightOfferPublication, MidnightRootActivationSignature, } from "../../types/midnightCancelAndMake.js";
67
4
  /**
68
5
  * Encodes `MidnightBundlesV2.midnightBundlesV2CancelAndMake` for `msg.sender`: cancel previous
69
6
  * groups under consumption guards, optionally park loan assets on Morpho Blue for the maker's
70
7
  * `BlueBuyCallback` or supply collateral, activate `root`, and publish `payload`.
71
8
  * Without `publication`, it only cancels groups (`cancelOffers` uses this).
72
9
  * Execution reverts as a whole if any group's consumption exceeds its `maxConsumed` ceiling.
10
+ * The builder snapshots every input field once before validation and encoding. It checks root,
11
+ * groups, cancellation groups, Blue callback salt, and root-signature `r`/`s` as 32-byte hex and
12
+ * checks payload hex shape and size, but cannot decode it; callers must supply a mutually
13
+ * consistent root, group list, and payload.
73
14
  *
74
- * The contract does not check that `payload` matches `root`; callers must derive both from the
75
- * same tree. Prefer `client.morpho.midnight(chainId).makeLend(...)`,
15
+ * The contract does not check that `payload` matches `root`. Prefer
16
+ * `client.morpho.midnight(chainId).makeLend(...)`,
76
17
  * `makeBorrow(...)`, `supplyCollateralMakeBorrow(...)`, or `supplyBlueMakeLend(...)`, which derive
77
18
  * the tree data and resolve the requirements for each flow; `supplyBlueMakeLend` also runs the
78
19
  * Blue parking checks (callback, callbackData, empty-market and zero-share guards) that this builder
@@ -80,7 +21,7 @@ export interface MidnightCancelAndMakeParams {
80
21
  *
81
22
  * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
82
23
  * @param params.cancellations - Offer groups to cancel and their consumption ceilings.
83
- * @param params.deadline - Bundle execution deadline timestamp; pass `maxUint256` explicitly for no expiry.
24
+ * @param params.deadline - Bundle execution deadline timestamp; pass `maxUint256` explicitly for no expiry. Not checked against the clock; validate freshness before building.
84
25
  * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
85
26
  * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of the
86
27
  * maximum wNative amount this call can pull, but not more. Any wrapped native not pulled stays in
@@ -93,7 +34,9 @@ export interface MidnightCancelAndMakeParams {
93
34
  * @param params.publication.root - Offer tree root to activate.
94
35
  * @param params.publication.groups - Distinct offer groups contained in the root.
95
36
  * @param params.publication.payload - Encoded offer payload published to the Midnight log.
96
- * @param params.publication.rootSignature - Optional delegated root-activation signature; omitted, all fields are zero.
37
+ * @param params.publication.rootSignature - Optional builder-only delegated root-activation
38
+ * signature. Maker entity methods never set it; they encode zero signature fields and rely on
39
+ * MidnightBundlesV2 authorization.
97
40
  * @param params.publication.rootSignature.height - Tree height committed by the signature.
98
41
  * @param params.publication.rootSignature.nonce - Ratifier signature nonce.
99
42
  * @param params.publication.rootSignature.deadline - Signature deadline timestamp, independent of the bundle `deadline`.
@@ -114,11 +57,14 @@ export interface MidnightCancelAndMakeParams {
114
57
  * @throws {EmptyMidnightGroupCancellationsError} when nothing is published and no groups are cancelled.
115
58
  * @throws {EmptyMidnightCollateralSuppliesError} when a collateral market has no collateral supplies.
116
59
  * @throws {InvalidTreeError} when `root` is zero, or `payload` or `groups` is empty.
60
+ * @throws {InvalidMidnightHexInputError} when a publication root or group, cancellation group,
61
+ * Blue callback salt, or root-signature `r`/`s` is not 32-byte hex, or when payload is malformed,
62
+ * odd-length, or larger than 1,000,000 bytes.
117
63
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
118
64
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
119
65
  * @throws {NonPositiveInputError} when `deadline` is not positive.
120
66
  * @throws {NegativeInputError} when a `maxConsumed` ceiling or `nativeAmount` is negative.
121
- * @throws {InputExceedsMaxError} when a `maxConsumed` ceiling exceeds `uint128`, or `deadline` or a collateral supply amount exceeds `uint256`, or `nativeAmount` exceeds the maximum wNative pull, including zero when no wNative is pulled.
67
+ * @throws {InputExceedsMaxError} when a `maxConsumed` ceiling, collateral supply amount, collateral supply sum, or Blue supply amount exceeds `uint128`, `deadline` exceeds `uint256`, or `nativeAmount` exceeds the maximum wNative pull, including zero when no wNative is pulled.
122
68
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
123
69
  * @throws {NativeAmountOnNonWNativeAssetError} when configured token pulls contain no wNative token.
124
70
  * @throws {ChainIdMismatchError} when the collateral market targets another chain.