@morpho-org/morpho-sdk 10.0.1 → 10.1.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 (250) hide show
  1. package/README.md +31 -10
  2. package/lib/cjs/abis.d.ts +1 -1
  3. package/lib/cjs/abis.js +5 -1
  4. package/lib/cjs/actions/blue/refinance.d.ts +1 -1
  5. package/lib/cjs/actions/blue/refinance.js +3 -8
  6. package/lib/cjs/actions/blue/refinanceValidation.d.ts +19 -0
  7. package/lib/cjs/actions/blue/refinanceValidation.js +46 -0
  8. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +1 -1
  9. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +3 -7
  10. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +1 -1
  11. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +4 -20
  12. package/lib/cjs/actions/requirements/getRequirementsApproval.js +7 -21
  13. package/lib/cjs/actions/requirements/validateClientChainId.d.ts +1 -26
  14. package/lib/cjs/actions/requirements/validateClientChainId.js +2 -31
  15. package/lib/cjs/actions/vaultV2/forceRedeem.d.ts +2 -1
  16. package/lib/cjs/actions/vaultV2/forceRedeem.js +20 -2
  17. package/lib/cjs/blue/abis.d.ts +1 -1
  18. package/lib/cjs/blue/abis.js +5 -1
  19. package/lib/cjs/blue/entities.d.ts +4 -4
  20. package/lib/cjs/blue/entities.js +3 -1
  21. package/lib/cjs/blue/errors.d.ts +2 -2
  22. package/lib/cjs/blue/errors.js +5 -1
  23. package/lib/cjs/blue/fetch.d.ts +2 -2
  24. package/lib/cjs/blue/fetch.js +3 -1
  25. package/lib/cjs/blue/utils.d.ts +1 -1
  26. package/lib/cjs/blue/utils.js +2 -1
  27. package/lib/cjs/entities/blue/blue.js +24 -55
  28. package/lib/cjs/entities/index.d.ts +4 -4
  29. package/lib/cjs/entities/index.js +3 -1
  30. package/lib/cjs/entities/requirements/getErc2612Permit.d.ts +2 -5
  31. package/lib/cjs/entities/requirements/getErc2612Permit.js +9 -58
  32. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +34 -8
  33. package/lib/cjs/entities/vaultV2/vaultV2.js +39 -1
  34. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +3 -2
  35. package/lib/cjs/entities/vaultV2BlueReallocationData.js +6 -2
  36. package/lib/cjs/errors.d.ts +4 -4
  37. package/lib/cjs/errors.js +7 -5
  38. package/lib/cjs/fetch.d.ts +2 -2
  39. package/lib/cjs/fetch.js +3 -1
  40. package/lib/cjs/helpers/deadShares.js +3 -0
  41. package/lib/cjs/helpers/quoteBlueRepay.d.ts +16 -0
  42. package/lib/cjs/helpers/quoteBlueRepay.js +46 -0
  43. package/lib/cjs/helpers/tokenApproval.d.ts +14 -0
  44. package/lib/cjs/helpers/tokenApproval.js +20 -0
  45. package/lib/cjs/helpers/validate.d.ts +1 -1
  46. package/lib/cjs/helpers/validate.js +2 -2
  47. package/lib/cjs/index.d.ts +2 -2
  48. package/lib/cjs/index.js +13 -1
  49. package/lib/cjs/midnight/errors.d.ts +2 -1
  50. package/lib/cjs/midnight/errors.js +5 -4
  51. package/lib/cjs/reads/readErc2612Permit.d.ts +22 -0
  52. package/lib/cjs/reads/readErc2612Permit.js +77 -0
  53. package/lib/cjs/reads/validateClientChainId.d.ts +26 -0
  54. package/lib/cjs/reads/validateClientChainId.js +34 -0
  55. package/lib/cjs/transactionPlan/blue/authorization.d.ts +23 -0
  56. package/lib/cjs/transactionPlan/blue/authorization.js +128 -0
  57. package/lib/cjs/transactionPlan/blue/borrow.d.ts +80 -0
  58. package/lib/cjs/transactionPlan/blue/borrow.js +248 -0
  59. package/lib/cjs/transactionPlan/blue/prepare.d.ts +102 -0
  60. package/lib/cjs/transactionPlan/blue/prepare.js +191 -0
  61. package/lib/cjs/transactionPlan/blue/refinance.d.ts +93 -0
  62. package/lib/cjs/transactionPlan/blue/refinance.js +281 -0
  63. package/lib/cjs/transactionPlan/blue/refinanceValidation.d.ts +11 -0
  64. package/lib/cjs/transactionPlan/blue/refinanceValidation.js +20 -0
  65. package/lib/cjs/transactionPlan/blue/repay.d.ts +80 -0
  66. package/lib/cjs/transactionPlan/blue/repay.js +229 -0
  67. package/lib/cjs/transactionPlan/blue/repayWithdrawCollateral.d.ts +98 -0
  68. package/lib/cjs/transactionPlan/blue/repayWithdrawCollateral.js +379 -0
  69. package/lib/cjs/transactionPlan/blue/supply.d.ts +181 -0
  70. package/lib/cjs/transactionPlan/blue/supply.js +238 -0
  71. package/lib/cjs/transactionPlan/blue/supplyCollateral.d.ts +97 -0
  72. package/lib/cjs/transactionPlan/blue/supplyCollateral.js +231 -0
  73. package/lib/cjs/transactionPlan/blue/supplyCollateralBorrow.d.ts +102 -0
  74. package/lib/cjs/transactionPlan/blue/supplyCollateralBorrow.js +395 -0
  75. package/lib/cjs/transactionPlan/blue/withdraw.d.ts +136 -0
  76. package/lib/cjs/transactionPlan/blue/withdraw.js +340 -0
  77. package/lib/cjs/transactionPlan/blue/withdrawCollateral.d.ts +123 -0
  78. package/lib/cjs/transactionPlan/blue/withdrawCollateral.js +246 -0
  79. package/lib/cjs/transactionPlan/deposit.js +8 -19
  80. package/lib/cjs/transactionPlan/error.d.ts +50 -0
  81. package/lib/cjs/transactionPlan/error.js +60 -1
  82. package/lib/cjs/transactionPlan/getTokenPermit.d.ts +17 -8
  83. package/lib/cjs/transactionPlan/getTokenPermit.js +35 -7
  84. package/lib/cjs/transactionPlan/index.d.ts +21 -1
  85. package/lib/cjs/transactionPlan/index.js +27 -5
  86. package/lib/cjs/transactionPlan/intent.d.ts +2 -2
  87. package/lib/cjs/transactionPlan/intent.js +8 -4
  88. package/lib/cjs/transactionPlan/permit.d.ts +16 -2
  89. package/lib/cjs/transactionPlan/permit.js +77 -45
  90. package/lib/cjs/transactionPlan/plan.d.ts +67 -12
  91. package/lib/cjs/transactionPlan/plan.js +284 -50
  92. package/lib/cjs/transactionPlan/requirements.d.ts +14 -5
  93. package/lib/cjs/transactionPlan/requirements.js +30 -12
  94. package/lib/cjs/transactionPlan/serde.d.ts +7 -4
  95. package/lib/cjs/transactionPlan/serde.js +80 -61
  96. package/lib/cjs/transactionPlan/types.d.ts +141 -13
  97. package/lib/cjs/transactionPlan/validateActions.js +11 -1
  98. package/lib/cjs/transactionPlan/validation.d.ts +8 -0
  99. package/lib/cjs/transactionPlan/validation.js +90 -0
  100. package/lib/cjs/transactionPlan/vaultv1/deposit.d.ts +1 -0
  101. package/lib/cjs/transactionPlan/vaultv1/deposit.js +1 -0
  102. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.d.ts +1 -0
  103. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.js +1 -0
  104. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.d.ts +1 -0
  105. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.js +1 -0
  106. package/lib/cjs/transactionPlan/vaultv1/redeem.d.ts +1 -0
  107. package/lib/cjs/transactionPlan/vaultv1/redeem.js +1 -0
  108. package/lib/cjs/transactionPlan/vaultv1/withdraw.d.ts +1 -0
  109. package/lib/cjs/transactionPlan/vaultv1/withdraw.js +1 -0
  110. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +1 -0
  111. package/lib/cjs/transactionPlan/vaultv2/deposit.js +1 -0
  112. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.d.ts +1 -0
  113. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.js +1 -0
  114. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.d.ts +1 -0
  115. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.js +1 -0
  116. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.d.ts +1 -0
  117. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.js +1 -0
  118. package/lib/cjs/transactionPlan/vaultv2/redeem.d.ts +1 -0
  119. package/lib/cjs/transactionPlan/vaultv2/redeem.js +1 -0
  120. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +1 -0
  121. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +1 -0
  122. package/lib/cjs/utils.d.ts +2 -2
  123. package/lib/cjs/utils.js +4 -2
  124. package/lib/cjs/version.d.ts +1 -1
  125. package/lib/cjs/version.js +1 -1
  126. package/lib/esm/abis.d.ts +1 -1
  127. package/lib/esm/abis.js +1 -1
  128. package/lib/esm/actions/blue/refinance.d.ts +1 -1
  129. package/lib/esm/actions/blue/refinance.js +4 -9
  130. package/lib/esm/actions/blue/refinanceValidation.d.ts +19 -0
  131. package/lib/esm/actions/blue/refinanceValidation.js +41 -0
  132. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +1 -1
  133. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +4 -8
  134. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +1 -1
  135. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +5 -21
  136. package/lib/esm/actions/requirements/getRequirementsApproval.js +7 -21
  137. package/lib/esm/actions/requirements/validateClientChainId.d.ts +1 -26
  138. package/lib/esm/actions/requirements/validateClientChainId.js +1 -30
  139. package/lib/esm/actions/vaultV2/forceRedeem.d.ts +2 -1
  140. package/lib/esm/actions/vaultV2/forceRedeem.js +20 -2
  141. package/lib/esm/blue/abis.d.ts +1 -1
  142. package/lib/esm/blue/abis.js +1 -1
  143. package/lib/esm/blue/entities.d.ts +4 -4
  144. package/lib/esm/blue/entities.js +2 -2
  145. package/lib/esm/blue/errors.d.ts +2 -2
  146. package/lib/esm/blue/errors.js +2 -2
  147. package/lib/esm/blue/fetch.d.ts +2 -2
  148. package/lib/esm/blue/fetch.js +2 -2
  149. package/lib/esm/blue/utils.d.ts +1 -1
  150. package/lib/esm/blue/utils.js +1 -1
  151. package/lib/esm/entities/blue/blue.js +26 -57
  152. package/lib/esm/entities/index.d.ts +4 -4
  153. package/lib/esm/entities/index.js +2 -2
  154. package/lib/esm/entities/requirements/getErc2612Permit.d.ts +2 -5
  155. package/lib/esm/entities/requirements/getErc2612Permit.js +9 -58
  156. package/lib/esm/entities/vaultV2/vaultV2.d.ts +34 -8
  157. package/lib/esm/entities/vaultV2/vaultV2.js +40 -2
  158. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +3 -2
  159. package/lib/esm/entities/vaultV2BlueReallocationData.js +6 -2
  160. package/lib/esm/errors.d.ts +4 -4
  161. package/lib/esm/errors.js +4 -4
  162. package/lib/esm/fetch.d.ts +2 -2
  163. package/lib/esm/fetch.js +2 -2
  164. package/lib/esm/helpers/deadShares.js +4 -1
  165. package/lib/esm/helpers/quoteBlueRepay.d.ts +16 -0
  166. package/lib/esm/helpers/quoteBlueRepay.js +42 -0
  167. package/lib/esm/helpers/tokenApproval.d.ts +14 -0
  168. package/lib/esm/helpers/tokenApproval.js +16 -0
  169. package/lib/esm/helpers/validate.d.ts +1 -1
  170. package/lib/esm/helpers/validate.js +3 -3
  171. package/lib/esm/index.d.ts +2 -2
  172. package/lib/esm/index.js +1 -1
  173. package/lib/esm/midnight/errors.d.ts +2 -1
  174. package/lib/esm/midnight/errors.js +2 -1
  175. package/lib/esm/reads/readErc2612Permit.d.ts +22 -0
  176. package/lib/esm/reads/readErc2612Permit.js +73 -0
  177. package/lib/esm/reads/validateClientChainId.d.ts +26 -0
  178. package/lib/esm/reads/validateClientChainId.js +30 -0
  179. package/lib/esm/transactionPlan/blue/authorization.d.ts +23 -0
  180. package/lib/esm/transactionPlan/blue/authorization.js +122 -0
  181. package/lib/esm/transactionPlan/blue/borrow.d.ts +80 -0
  182. package/lib/esm/transactionPlan/blue/borrow.js +243 -0
  183. package/lib/esm/transactionPlan/blue/prepare.d.ts +102 -0
  184. package/lib/esm/transactionPlan/blue/prepare.js +187 -0
  185. package/lib/esm/transactionPlan/blue/refinance.d.ts +93 -0
  186. package/lib/esm/transactionPlan/blue/refinance.js +276 -0
  187. package/lib/esm/transactionPlan/blue/refinanceValidation.d.ts +11 -0
  188. package/lib/esm/transactionPlan/blue/refinanceValidation.js +17 -0
  189. package/lib/esm/transactionPlan/blue/repay.d.ts +80 -0
  190. package/lib/esm/transactionPlan/blue/repay.js +223 -0
  191. package/lib/esm/transactionPlan/blue/repayWithdrawCollateral.d.ts +98 -0
  192. package/lib/esm/transactionPlan/blue/repayWithdrawCollateral.js +373 -0
  193. package/lib/esm/transactionPlan/blue/supply.d.ts +181 -0
  194. package/lib/esm/transactionPlan/blue/supply.js +232 -0
  195. package/lib/esm/transactionPlan/blue/supplyCollateral.d.ts +97 -0
  196. package/lib/esm/transactionPlan/blue/supplyCollateral.js +225 -0
  197. package/lib/esm/transactionPlan/blue/supplyCollateralBorrow.d.ts +102 -0
  198. package/lib/esm/transactionPlan/blue/supplyCollateralBorrow.js +389 -0
  199. package/lib/esm/transactionPlan/blue/withdraw.d.ts +136 -0
  200. package/lib/esm/transactionPlan/blue/withdraw.js +334 -0
  201. package/lib/esm/transactionPlan/blue/withdrawCollateral.d.ts +123 -0
  202. package/lib/esm/transactionPlan/blue/withdrawCollateral.js +240 -0
  203. package/lib/esm/transactionPlan/deposit.js +9 -20
  204. package/lib/esm/transactionPlan/error.d.ts +50 -0
  205. package/lib/esm/transactionPlan/error.js +57 -0
  206. package/lib/esm/transactionPlan/getTokenPermit.d.ts +17 -8
  207. package/lib/esm/transactionPlan/getTokenPermit.js +35 -7
  208. package/lib/esm/transactionPlan/index.d.ts +21 -1
  209. package/lib/esm/transactionPlan/index.js +11 -1
  210. package/lib/esm/transactionPlan/intent.d.ts +2 -2
  211. package/lib/esm/transactionPlan/intent.js +8 -4
  212. package/lib/esm/transactionPlan/permit.d.ts +16 -2
  213. package/lib/esm/transactionPlan/permit.js +76 -44
  214. package/lib/esm/transactionPlan/plan.d.ts +67 -12
  215. package/lib/esm/transactionPlan/plan.js +279 -46
  216. package/lib/esm/transactionPlan/requirements.d.ts +14 -5
  217. package/lib/esm/transactionPlan/requirements.js +30 -12
  218. package/lib/esm/transactionPlan/serde.d.ts +7 -4
  219. package/lib/esm/transactionPlan/serde.js +73 -54
  220. package/lib/esm/transactionPlan/types.d.ts +141 -13
  221. package/lib/esm/transactionPlan/validateActions.js +11 -1
  222. package/lib/esm/transactionPlan/validation.d.ts +8 -0
  223. package/lib/esm/transactionPlan/validation.js +88 -1
  224. package/lib/esm/transactionPlan/vaultv1/deposit.d.ts +1 -0
  225. package/lib/esm/transactionPlan/vaultv1/deposit.js +1 -0
  226. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.d.ts +1 -0
  227. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.js +1 -0
  228. package/lib/esm/transactionPlan/vaultv1/migrateToV2.d.ts +1 -0
  229. package/lib/esm/transactionPlan/vaultv1/migrateToV2.js +1 -0
  230. package/lib/esm/transactionPlan/vaultv1/redeem.d.ts +1 -0
  231. package/lib/esm/transactionPlan/vaultv1/redeem.js +1 -0
  232. package/lib/esm/transactionPlan/vaultv1/withdraw.d.ts +1 -0
  233. package/lib/esm/transactionPlan/vaultv1/withdraw.js +1 -0
  234. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +1 -0
  235. package/lib/esm/transactionPlan/vaultv2/deposit.js +1 -0
  236. package/lib/esm/transactionPlan/vaultv2/forceRedeem.d.ts +1 -0
  237. package/lib/esm/transactionPlan/vaultv2/forceRedeem.js +1 -0
  238. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.d.ts +1 -0
  239. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.js +1 -0
  240. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.d.ts +1 -0
  241. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.js +1 -0
  242. package/lib/esm/transactionPlan/vaultv2/redeem.d.ts +1 -0
  243. package/lib/esm/transactionPlan/vaultv2/redeem.js +1 -0
  244. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +1 -0
  245. package/lib/esm/transactionPlan/vaultv2/withdraw.js +1 -0
  246. package/lib/esm/utils.d.ts +2 -2
  247. package/lib/esm/utils.js +2 -2
  248. package/lib/esm/version.d.ts +1 -1
  249. package/lib/esm/version.js +1 -1
  250. package/package.json +7 -7
@@ -1,4 +1,4 @@
1
- import { AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, MarketParams, VaultV2MorphoMarketV1Adapter, VaultV2MorphoMarketV1AdapterV2, VaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk";
1
+ import { AccrualVaultV2MidnightAdapter, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, MarketParams, VaultV2MorphoMarketV1Adapter, VaultV2MorphoMarketV1AdapterV2, VaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk";
2
2
  import { InsufficientDeadSharesError, MissingDeadSharesDataError, } from "../types/error.js";
3
3
  import { MIN_DEAD_SHARES, MIN_VAULT_V2_DEAD_ASSETS } from "./constant.js";
4
4
  /**
@@ -188,6 +188,9 @@ function getDeadSharesAbsoluteCap(id, { absoluteCaps, entity, adapter, }) {
188
188
  }
189
189
  /** Checks the currently allocated positions of one supported adapter. @internal */
190
190
  function assertAdapterDeadShares(adapter, { absoluteCaps, entity, }) {
191
+ if (adapter instanceof AccrualVaultV2MidnightAdapter) {
192
+ return;
193
+ }
191
194
  if (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter) {
192
195
  const id = VaultV2MorphoVaultV1Adapter.adapterCapId(adapter.address);
193
196
  if (getDeadSharesAbsoluteCap(id, {
@@ -0,0 +1,16 @@
1
+ import { type AccrualPosition, type MarketId } from "@morpho-org/blue-sdk";
2
+ /** @internal Quotes repayment funding without projecting a position for health checks. */
3
+ export declare function quoteBlueRepayFunding(params: Parameters<typeof quoteBlueRepay>[0]): bigint;
4
+ /** @internal Quotes Blue repayment funding and the position used for withdrawal health checks. */
5
+ export declare function quoteBlueRepay({ positionData, marketId, repayAssets, repayShares, deadline, now, }: {
6
+ readonly positionData: AccrualPosition;
7
+ readonly marketId: MarketId;
8
+ readonly repayAssets: bigint;
9
+ readonly repayShares: bigint;
10
+ readonly deadline: bigint;
11
+ readonly now: bigint;
12
+ }): {
13
+ simulatedRepayShares: bigint;
14
+ accruedPosition: AccrualPosition;
15
+ expectedRepayAssets: bigint;
16
+ };
@@ -0,0 +1,42 @@
1
+ import { MathLib, } from "@morpho-org/blue-sdk";
2
+ import { Time } from "@morpho-org/morpho-ts";
3
+ import { maxUint256 } from "viem";
4
+ import { InputExceedsMaxError } from "../types/error.js";
5
+ import { validateRepayAmount, validateRepayShares } from "./validate.js";
6
+ /** @internal Quotes repayment funding without projecting a position for health checks. */
7
+ export function quoteBlueRepayFunding(params) {
8
+ if (params.repayShares > 0n) {
9
+ return quoteBlueRepay(params).expectedRepayAssets;
10
+ }
11
+ if (params.repayAssets > 0n) {
12
+ validateRepayAmount(params);
13
+ }
14
+ return params.repayAssets;
15
+ }
16
+ /** @internal Quotes Blue repayment funding and the position used for withdrawal health checks. */
17
+ export function quoteBlueRepay({ positionData, marketId, repayAssets, repayShares, deadline, now, }) {
18
+ const saturatedRepay = repayShares === maxUint256;
19
+ const simulatedRepayShares = saturatedRepay
20
+ ? positionData.borrowShares
21
+ : repayShares;
22
+ if (repayAssets > 0n) {
23
+ validateRepayAmount({ positionData, repayAssets, marketId });
24
+ }
25
+ else if (repayShares > 0n && !saturatedRepay) {
26
+ validateRepayShares({ positionData, repayShares, marketId });
27
+ }
28
+ const quoteHorizon = MathLib.max(now, positionData.market.lastUpdate) + Time.s.from.h(2n);
29
+ if (repayShares > 0n && deadline > quoteHorizon) {
30
+ throw new InputExceedsMaxError({
31
+ field: "deadline",
32
+ value: deadline,
33
+ max: quoteHorizon,
34
+ });
35
+ }
36
+ const accrualTimestamp = repayShares > 0n ? deadline : quoteHorizon;
37
+ const accruedPosition = positionData.accrueInterest(accrualTimestamp);
38
+ const expectedRepayAssets = repayAssets <= 0n && repayShares > 0n
39
+ ? accruedPosition.market.toBorrowAssets(simulatedRepayShares, "Up")
40
+ : repayAssets;
41
+ return { simulatedRepayShares, accruedPosition, expectedRepayAssets };
42
+ }
@@ -0,0 +1,14 @@
1
+ import { type Address } from "@morpho-org/blue-sdk";
2
+ /** @internal Returns the requested approval amounts in execution order. */
3
+ export declare function getTokenApprovalAmounts({ token, chainId, allowance, spendAmount, }: {
4
+ readonly token: Address;
5
+ readonly chainId: number;
6
+ readonly allowance: bigint;
7
+ readonly spendAmount: bigint;
8
+ }): readonly bigint[];
9
+ /** @internal Caps a requested approval at the token's supported maximum. */
10
+ export declare function capTokenApproval({ token, chainId, amount, }: {
11
+ readonly token: Address;
12
+ readonly chainId: number;
13
+ readonly amount: bigint;
14
+ }): bigint;
@@ -0,0 +1,16 @@
1
+ import { MathLib } from "@morpho-org/blue-sdk";
2
+ import { getAddress, isAddressEqual, maxUint256 } from "viem";
3
+ import { APPROVE_ONLY_ONCE_TOKENS, MAX_TOKEN_APPROVALS } from "./constant.js";
4
+ /** @internal Returns the requested approval amounts in execution order. */
5
+ export function getTokenApprovalAmounts({ token, chainId, allowance, spendAmount, }) {
6
+ if (allowance >= spendAmount) {
7
+ return [];
8
+ }
9
+ const needsReset = allowance > 0n &&
10
+ APPROVE_ONLY_ONCE_TOKENS[chainId]?.some((address) => isAddressEqual(token, address));
11
+ return needsReset ? [0n, maxUint256] : [maxUint256];
12
+ }
13
+ /** @internal Caps a requested approval at the token's supported maximum. */
14
+ export function capTokenApproval({ token, chainId, amount, }) {
15
+ return MathLib.min(amount, MAX_TOKEN_APPROVALS[chainId]?.[getAddress(token)] ?? maxUint256);
16
+ }
@@ -336,7 +336,7 @@ export declare const validateNativeVaultAsset: (chainId: number, vaultAsset: Add
336
336
  * @param params.lltv - The market's liquidation LTV.
337
337
  * @param params.marketId - The market identifier (for error messages).
338
338
  * @returns `void` when the post-withdraw position stays within the safe LTV threshold.
339
- * @throws {MarketIdMismatchError} when `positionData.marketId` differs from `marketId`.
339
+ * @throws {MarketIdMismatchError} when the two market IDs differ beyond hex casing.
340
340
  * @throws {WithdrawExceedsCollateralError} when `withdrawAmount` exceeds the position's collateral.
341
341
  * @throws {MissingMarketPriceError} when the position carries debt but the market has no oracle price.
342
342
  * @throws {WithdrawMakesPositionUnhealthyError} when the remaining collateral cannot cover the debt
@@ -1,6 +1,6 @@
1
1
  import { getChainAddresses, MarketUtils, MathLib, ORACLE_PRICE_SCALE, } from "@morpho-org/blue-sdk";
2
2
  import { MarketUtils as MidnightMarketUtils, } from "@morpho-org/midnight-sdk";
3
- import { isDefined } from "@morpho-org/morpho-ts";
3
+ import { isDefined, isHexEqual } from "@morpho-org/morpho-ts";
4
4
  import { isAddress, isAddressEqual, maxUint128, maxUint256, zeroAddress, } from "viem";
5
5
  import { AccrualPositionUserMismatchError, AddressMismatchError, BorrowExceedsSafeLtvError, ChainIdMismatchError, ChainWNativeMissingError, ExcessiveSlippageToleranceError, InconsistentReallocationPenaltyError, InputExceedsMaxError, InvalidReallocationAddressError, InvalidReallocationSourceTypeError, InvalidVaultV2BlueReallocationShapeError, MarketIdMismatchError, MissingClientPropertyError, MissingMarketPriceError, NativeAmountOnNonWNativeAssetError, NativeAmountOnNonWNativeVaultError, NegativeInputError, NonPositiveInputError, ReallocationWithdrawalOnTargetMarketError, ReferralFeePctExceededError, ReferralFeeRecipientMissingError, RepayExceedsDebtError, RepaySharesExceedDebtError, WithdrawExceedsCollateralError, WithdrawExceedsSupplyError, WithdrawMakesPositionUnhealthyError, WithdrawSharesExceedSupplyError, } from "../types/index.js";
6
6
  import { DEFAULT_LLTV_BUFFER, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, } from "./constant.js";
@@ -456,7 +456,7 @@ export const validateNativeVaultAsset = (chainId, vaultAsset) => {
456
456
  * @param params.lltv - The market's liquidation LTV.
457
457
  * @param params.marketId - The market identifier (for error messages).
458
458
  * @returns `void` when the post-withdraw position stays within the safe LTV threshold.
459
- * @throws {MarketIdMismatchError} when `positionData.marketId` differs from `marketId`.
459
+ * @throws {MarketIdMismatchError} when the two market IDs differ beyond hex casing.
460
460
  * @throws {WithdrawExceedsCollateralError} when `withdrawAmount` exceeds the position's collateral.
461
461
  * @throws {MissingMarketPriceError} when the position carries debt but the market has no oracle price.
462
462
  * @throws {WithdrawMakesPositionUnhealthyError} when the remaining collateral cannot cover the debt
@@ -483,7 +483,7 @@ export const validateNativeVaultAsset = (chainId, vaultAsset) => {
483
483
  */
484
484
  export const validatePositionHealthAfterWithdraw = (params) => {
485
485
  const { positionData, withdrawAmount, lltv, marketId } = params;
486
- if (positionData.marketId !== marketId) {
486
+ if (!isHexEqual(positionData.marketId, marketId)) {
487
487
  throw new MarketIdMismatchError(positionData.marketId, marketId);
488
488
  }
489
489
  if (withdrawAmount > positionData.collateral) {
@@ -3,7 +3,7 @@ export { validateClientChainId } from "./actions/requirements/validateClientChai
3
3
  export * from "./client/index.js";
4
4
  export * from "./entities/requirements/index.js";
5
5
  export * from "./helpers/index.js";
6
- export type { Action, Funding, IntentParams, ReferralFee, SignatureRequest, Step, TransactionPlan, VaultV1DepositPlanParams, VaultV1InKindRedeemPlanParams, VaultV1MigrateToV2PlanParams, VaultV1RedeemPlanParams, VaultV1WithdrawPlanParams, VaultV2DepositPlanParams, VaultV2ForceRedeemPlanParams, VaultV2ForceWithdrawPlanParams, VaultV2InKindRedeemPlanParams, VaultV2RedeemPlanParams, VaultV2WithdrawPlanParams, } from "./transactionPlan/index.js";
7
- export { applySignatures, buildTransaction, buildTransactions, getPendingSignatureRequests, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, NonIntegerInputError, parseTransactionPlan, prepareVaultV1Deposit, prepareVaultV1InKindRedeem, prepareVaultV1MigrateToV2, prepareVaultV1Redeem, prepareVaultV1Withdraw, prepareVaultV2Deposit, prepareVaultV2ForceRedeem, prepareVaultV2ForceWithdraw, prepareVaultV2InKindRedeem, prepareVaultV2Redeem, prepareVaultV2Withdraw, serializeTransactionPlan, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, ZeroAccountError, } from "./transactionPlan/index.js";
6
+ export type { Action, BlueBorrowPlanParams, BlueMarketSnapshot, BluePositionSnapshot, BlueRefinancePlanParams, BlueRepayPlanParams, BlueRepayWithdrawCollateralPlanParams, BlueSupplyCollateralBorrowPlanParams, BlueSupplyCollateralPlanParams, BlueSupplyPlanParams, BlueWithdrawCollateralPlanParams, BlueWithdrawPlanParams, Funding, IntentParams, ReferralFee, SignatureRequest, Step, TransactionPlan, VaultV1DepositPlanParams, VaultV1InKindRedeemPlanParams, VaultV1MigrateToV2PlanParams, VaultV1RedeemPlanParams, VaultV1WithdrawPlanParams, VaultV2DepositPlanParams, VaultV2ForceRedeemPlanParams, VaultV2ForceWithdrawPlanParams, VaultV2InKindRedeemPlanParams, VaultV2RedeemPlanParams, VaultV2WithdrawPlanParams, } from "./transactionPlan/index.js";
7
+ export { applySignatures, BlueSnapshotChainMismatchError, BlueSnapshotStateMismatchError, buildTransaction, buildTransactions, getPendingSignatureRequests, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, NonIntegerInputError, parseTransactionPlan, prepareBlueBorrow, prepareBlueRefinance, prepareBlueRepay, prepareBlueRepayWithdrawCollateral, prepareBlueSupply, prepareBlueSupplyCollateral, prepareBlueSupplyCollateralBorrow, prepareBlueWithdraw, prepareBlueWithdrawCollateral, prepareVaultV1Deposit, prepareVaultV1InKindRedeem, prepareVaultV1MigrateToV2, prepareVaultV1Redeem, prepareVaultV1Withdraw, prepareVaultV2Deposit, prepareVaultV2ForceRedeem, prepareVaultV2ForceWithdraw, prepareVaultV2InKindRedeem, prepareVaultV2Redeem, prepareVaultV2Withdraw, serializeTransactionPlan, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, validateBlueMarketSnapshot, ZeroAccountError, } from "./transactionPlan/index.js";
8
8
  export * from "./types/index.js";
9
9
  export { version } from "./version.js";
package/lib/esm/index.js CHANGED
@@ -3,6 +3,6 @@ export { validateClientChainId } from "./actions/requirements/validateClientChai
3
3
  export * from "./client/index.js";
4
4
  export * from "./entities/requirements/index.js";
5
5
  export * from "./helpers/index.js";
6
- export { applySignatures, buildTransaction, buildTransactions, getPendingSignatureRequests, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, NonIntegerInputError, parseTransactionPlan, prepareVaultV1Deposit, prepareVaultV1InKindRedeem, prepareVaultV1MigrateToV2, prepareVaultV1Redeem, prepareVaultV1Withdraw, prepareVaultV2Deposit, prepareVaultV2ForceRedeem, prepareVaultV2ForceWithdraw, prepareVaultV2InKindRedeem, prepareVaultV2Redeem, prepareVaultV2Withdraw, serializeTransactionPlan, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, ZeroAccountError, } from "./transactionPlan/index.js";
6
+ export { applySignatures, BlueSnapshotChainMismatchError, BlueSnapshotStateMismatchError, buildTransaction, buildTransactions, getPendingSignatureRequests, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, NonIntegerInputError, parseTransactionPlan, prepareBlueBorrow, prepareBlueRefinance, prepareBlueRepay, prepareBlueRepayWithdrawCollateral, prepareBlueSupply, prepareBlueSupplyCollateral, prepareBlueSupplyCollateralBorrow, prepareBlueWithdraw, prepareBlueWithdrawCollateral, prepareVaultV1Deposit, prepareVaultV1InKindRedeem, prepareVaultV1MigrateToV2, prepareVaultV1Redeem, prepareVaultV1Withdraw, prepareVaultV2Deposit, prepareVaultV2ForceRedeem, prepareVaultV2ForceWithdraw, prepareVaultV2InKindRedeem, prepareVaultV2Redeem, prepareVaultV2Withdraw, serializeTransactionPlan, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, validateBlueMarketSnapshot, ZeroAccountError, } from "./transactionPlan/index.js";
7
7
  export * from "./types/index.js";
8
8
  export { version } from "./version.js";
@@ -1 +1,2 @@
1
- export { ChainIdMismatchError, InvalidEcrecoverSignatureError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
1
+ export { ChainIdMismatchError, InvalidEcrecoverSignatureError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
2
+ export { InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, } from "@morpho-org/morpho-ts";
@@ -1 +1,2 @@
1
- export { ChainIdMismatchError, InvalidEcrecoverSignatureError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
1
+ export { ChainIdMismatchError, InvalidEcrecoverSignatureError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
2
+ export { InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, } from "@morpho-org/morpho-ts";
@@ -0,0 +1,22 @@
1
+ import { type Address, type Client, type TypedDataDomain } from "viem";
2
+ interface PermitInputs {
3
+ readonly chainId: number;
4
+ readonly spender: Address;
5
+ readonly deadline?: bigint;
6
+ readonly now: bigint;
7
+ }
8
+ /** @internal Validates permit inputs and the transport chain before token metadata reads. */
9
+ export declare function validateErc2612Permit(client: Client, params: PermitInputs): Promise<bigint>;
10
+ /**
11
+ * @internal Reads the owner nonce and checks the resolved signing domain against the token.
12
+ * Returns undefined for an unsupported permit, while RPC transport failures propagate.
13
+ */
14
+ export declare function readErc2612Permit<T>(client: Client, { token, owner, resolve, }: {
15
+ readonly token: Address;
16
+ readonly owner: Address;
17
+ readonly resolve: (nonce: bigint) => Promise<{
18
+ readonly domain?: TypedDataDomain;
19
+ readonly result: T;
20
+ }>;
21
+ }): Promise<T | undefined>;
22
+ export {};
@@ -0,0 +1,73 @@
1
+ import { erc2612Abi, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isContractRevertError, isTransportError, isUndecodableResultError, MissingPermitDomainNameError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
2
+ import { _try, Time } from "@morpho-org/morpho-ts";
3
+ import { getTypesForEIP712Domain, hashDomain, } from "viem";
4
+ import { readContract } from "viem/actions";
5
+ import { validateChainId, validateDeadline } from "../helpers/validate.js";
6
+ import { validateRequirementSpender } from "../helpers/validateRequirementSpender.js";
7
+ import { ExpiredDeadlineError } from "../types/index.js";
8
+ import { validateClientChainId } from "./validateClientChainId.js";
9
+ function validatePermitInputs(clientChainId, { chainId, spender, deadline, now }) {
10
+ validateChainId(clientChainId, chainId);
11
+ validateRequirementSpender({
12
+ chainId,
13
+ spender,
14
+ allowed: ["vaultBundlesV1", "blueBundlesV1"],
15
+ });
16
+ if (deadline == null) {
17
+ return now + Time.s.from.h(2n);
18
+ }
19
+ validateDeadline(deadline);
20
+ if (deadline <= now) {
21
+ throw new ExpiredDeadlineError(deadline, now);
22
+ }
23
+ return deadline;
24
+ }
25
+ /** @internal Validates permit inputs and the transport chain before token metadata reads. */
26
+ export async function validateErc2612Permit(client, params) {
27
+ const deadline = validatePermitInputs(client.chain?.id, params);
28
+ await validateClientChainId(client, params.chainId);
29
+ return deadline;
30
+ }
31
+ function unsupportedPermitRead(error) {
32
+ if (!isTransportError(error) &&
33
+ (isContractRevertError(error) || isUndecodableResultError(error))) {
34
+ return undefined;
35
+ }
36
+ throw error;
37
+ }
38
+ function matchesPermitDomainSeparator(domain, separator) {
39
+ return (separator.toLowerCase() ===
40
+ hashDomain({
41
+ domain,
42
+ types: { EIP712Domain: getTypesForEIP712Domain({ domain }) },
43
+ }).toLowerCase());
44
+ }
45
+ /**
46
+ * @internal Reads the owner nonce and checks the resolved signing domain against the token.
47
+ * Returns undefined for an unsupported permit, while RPC transport failures propagate.
48
+ */
49
+ export async function readErc2612Permit(client, { token, owner, resolve, }) {
50
+ const nonce = await readContract(client, {
51
+ abi: erc2612Abi,
52
+ address: token,
53
+ functionName: "nonces",
54
+ args: [owner],
55
+ }).catch(unsupportedPermitRead);
56
+ if (nonce === undefined) {
57
+ return undefined;
58
+ }
59
+ const permit = await _try(() => resolve(nonce), MissingPermitDomainNameError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, UnsupportedPermitDomainExtensionsError);
60
+ if (permit === undefined) {
61
+ return undefined;
62
+ }
63
+ const separator = await readContract(client, {
64
+ abi: erc2612Abi,
65
+ address: token,
66
+ functionName: "DOMAIN_SEPARATOR",
67
+ }).catch(unsupportedPermitRead);
68
+ if (separator === undefined ||
69
+ !matchesPermitDomainSeparator(permit.domain ?? {}, separator)) {
70
+ return undefined;
71
+ }
72
+ return permit.result;
73
+ }
@@ -0,0 +1,26 @@
1
+ import type { Client } from "viem";
2
+ /**
3
+ * Validates both the chain the viem client declares and the chain its transport serves.
4
+ *
5
+ * Sends one `eth_chainId` request per call; the result is never cached, so every flow observes the
6
+ * endpoint it actually reads from. An honest RPC connected to another chain fails here, before any
7
+ * state read. A provider that lies about `eth_chainId` is not detected (see THREAT_MODEL.md, RPC).
8
+ *
9
+ * @param client - Viem client whose declared chain and transport are checked.
10
+ * @param expectedChainId - Chain ID expected by the entity or action.
11
+ * @returns Resolves only when both the declared and the observed chain IDs equal
12
+ * `expectedChainId`.
13
+ * @throws {ChainIdMismatchError} when the declared or the observed chain ID differs from
14
+ * `expectedChainId`.
15
+ * @throws {viem.BaseError} when the `eth_chainId` request fails.
16
+ * @example
17
+ * ```ts
18
+ * import { createPublicClient, http } from "viem";
19
+ * import { mainnet } from "viem/chains";
20
+ * import { validateClientChainId } from "@morpho-org/morpho-sdk";
21
+ *
22
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
23
+ * await validateClientChainId(client, mainnet.id);
24
+ * ```
25
+ */
26
+ export declare const validateClientChainId: (client: Client, expectedChainId: number) => Promise<void>;
@@ -0,0 +1,30 @@
1
+ import { getChainId } from "viem/actions";
2
+ import { validateChainId } from "../helpers/validate.js";
3
+ /**
4
+ * Validates both the chain the viem client declares and the chain its transport serves.
5
+ *
6
+ * Sends one `eth_chainId` request per call; the result is never cached, so every flow observes the
7
+ * endpoint it actually reads from. An honest RPC connected to another chain fails here, before any
8
+ * state read. A provider that lies about `eth_chainId` is not detected (see THREAT_MODEL.md, RPC).
9
+ *
10
+ * @param client - Viem client whose declared chain and transport are checked.
11
+ * @param expectedChainId - Chain ID expected by the entity or action.
12
+ * @returns Resolves only when both the declared and the observed chain IDs equal
13
+ * `expectedChainId`.
14
+ * @throws {ChainIdMismatchError} when the declared or the observed chain ID differs from
15
+ * `expectedChainId`.
16
+ * @throws {viem.BaseError} when the `eth_chainId` request fails.
17
+ * @example
18
+ * ```ts
19
+ * import { createPublicClient, http } from "viem";
20
+ * import { mainnet } from "viem/chains";
21
+ * import { validateClientChainId } from "@morpho-org/morpho-sdk";
22
+ *
23
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
24
+ * await validateClientChainId(client, mainnet.id);
25
+ * ```
26
+ */
27
+ export const validateClientChainId = async (client, expectedChainId) => {
28
+ validateChainId(client.chain?.id, expectedChainId);
29
+ validateChainId(await getChainId(client), expectedChainId);
30
+ };
@@ -0,0 +1,23 @@
1
+ import { type Address } from "viem";
2
+ import type { BlueAuthorizationAction, Transaction } from "../../types/index.js";
3
+ import type { Action, SignatureRequest } from "../types.js";
4
+ type AuthorizationRequest = Extract<SignatureRequest, {
5
+ kind: "morphoAuthorization";
6
+ }>;
7
+ interface AuthorizationBinding {
8
+ readonly chainId: number;
9
+ readonly account: Address;
10
+ readonly nonce: bigint;
11
+ readonly deadline: bigint;
12
+ }
13
+ /** @internal Binds the canonical Morpho grant to the prepared action and registered BlueBundlesV1. */
14
+ export declare function validateMorphoAuthorizationRequest(request: AuthorizationRequest, { chainId, account, nonce, deadline }: AuthorizationBinding): void;
15
+ /** @internal Encodes the standalone authorization prerequisite. */
16
+ export declare function buildMorphoAuthorization(action: Extract<Action, {
17
+ type: "morphoAuthorization";
18
+ }>): Transaction<BlueAuthorizationAction>;
19
+ /** @internal Rejects signature references on the standalone authorization step. */
20
+ export declare function validateMorphoAuthorizationPlanAction(action: Record<string, unknown>, path: string): void;
21
+ /** @internal Validates the stored authorization request shape without verifying its signature. */
22
+ export declare function validateMorphoAuthorizationPlanRequest(request: Record<string, unknown>, path: string): void;
23
+ export {};
@@ -0,0 +1,122 @@
1
+ import { getChainAddresses } from "@morpho-org/blue-sdk";
2
+ import { blueAbi, getAuthorizationTypedData } from "@morpho-org/blue-sdk-viem";
3
+ import { getChainAddress } from "@morpho-org/morpho-ts";
4
+ import { encodeFunctionData } from "viem";
5
+ import { InvalidTransactionPlanError, TransactionPlanSignatureMismatchError, } from "../error.js";
6
+ import { getPlanObject, matchesAddress, validatePlanField, validatePlanFields, } from "../validation.js";
7
+ /** @internal Binds the canonical Morpho grant to the prepared action and registered BlueBundlesV1. */
8
+ export function validateMorphoAuthorizationRequest(request, { chainId, account, nonce, deadline }) {
9
+ const authorized = getChainAddress(chainId, "bundles.blueBundlesV1");
10
+ const expected = getAuthorizationTypedData({ authorizer: account, authorized, isAuthorized: true, nonce, deadline }, chainId);
11
+ const { domain, message, types, primaryType } = request.typedData;
12
+ const fields = types?.Authorization;
13
+ const checks = [
14
+ ["domain.chainId", domain?.chainId === chainId],
15
+ [
16
+ "domain.verifyingContract",
17
+ matchesAddress(domain?.verifyingContract, getChainAddresses(chainId).blue),
18
+ ],
19
+ [
20
+ "domain",
21
+ domain?.name === undefined &&
22
+ domain?.version === undefined &&
23
+ domain?.salt === undefined,
24
+ ],
25
+ ["primaryType", primaryType === expected.primaryType],
26
+ [
27
+ "types",
28
+ Array.isArray(fields) &&
29
+ Object.keys(types).length === 1 &&
30
+ fields.length === expected.types.Authorization.length &&
31
+ expected.types.Authorization.every((field, index) => field.name === fields[index]?.name &&
32
+ field.type === fields[index]?.type),
33
+ ],
34
+ ["message.authorizer", matchesAddress(message?.authorizer, account)],
35
+ ["args.owner", matchesAddress(request.args.owner, account)],
36
+ ["message.authorized", matchesAddress(message?.authorized, authorized)],
37
+ ["args.authorized", matchesAddress(request.args.authorized, authorized)],
38
+ ["message.isAuthorized", message?.isAuthorized === true],
39
+ ["message.nonce", message?.nonce === nonce],
40
+ ["args.nonce", request.args.nonce === nonce],
41
+ ["message.deadline", message?.deadline === deadline],
42
+ ["args.deadline", request.args.deadline === deadline],
43
+ ];
44
+ const mismatch = checks.find(([, matches]) => !matches);
45
+ if (mismatch) {
46
+ throw new TransactionPlanSignatureMismatchError(request.id, mismatch[0]);
47
+ }
48
+ }
49
+ /** @internal Encodes the standalone authorization prerequisite. */
50
+ export function buildMorphoAuthorization(action) {
51
+ const { chainId } = action.inputs;
52
+ const to = getChainAddresses(chainId).blue;
53
+ const authorized = getChainAddress(chainId, "bundles.blueBundlesV1");
54
+ const args = { authorized, isAuthorized: true };
55
+ const data = encodeFunctionData({
56
+ abi: blueAbi,
57
+ functionName: "setAuthorization",
58
+ args: [authorized, true],
59
+ });
60
+ return { to, value: 0n, data, action: { type: "blueAuthorization", args } };
61
+ }
62
+ /** @internal Rejects signature references on the standalone authorization step. */
63
+ export function validateMorphoAuthorizationPlanAction(action, path) {
64
+ if (action.signatureRequestIds !== undefined) {
65
+ throw new InvalidTransactionPlanError({
66
+ path: `${path}.signatureRequestIds`,
67
+ reason: "standalone Morpho authorization does not consume signatures",
68
+ });
69
+ }
70
+ }
71
+ /** @internal Validates the stored authorization request shape without verifying its signature. */
72
+ export function validateMorphoAuthorizationPlanRequest(request, path) {
73
+ const args = getPlanObject(request.args, `${path}.args`);
74
+ validatePlanFields(args, {
75
+ path: `${path}.args`,
76
+ fields: {
77
+ owner: "address",
78
+ authorized: "address",
79
+ nonce: "uint256 bigint",
80
+ deadline: "uint256 bigint",
81
+ },
82
+ });
83
+ const typedData = getPlanObject(request.typedData, `${path}.typedData`);
84
+ if (typedData.primaryType !== "Authorization") {
85
+ throw new InvalidTransactionPlanError({
86
+ path: `${path}.typedData.primaryType`,
87
+ reason: "expected Authorization",
88
+ });
89
+ }
90
+ const types = getPlanObject(typedData.types, `${path}.typedData.types`);
91
+ validatePlanField(types.Authorization, {
92
+ path: `${path}.typedData.types.Authorization`,
93
+ type: "array",
94
+ });
95
+ const domain = getPlanObject(typedData.domain, `${path}.typedData.domain`);
96
+ validatePlanFields(domain, {
97
+ path: `${path}.typedData.domain`,
98
+ fields: { chainId: "positive safe integer", verifyingContract: "address" },
99
+ });
100
+ const message = getPlanObject(typedData.message, `${path}.typedData.message`);
101
+ if (message.isAuthorized !== true) {
102
+ throw new InvalidTransactionPlanError({
103
+ path: `${path}.typedData.message.isAuthorized`,
104
+ reason: "expected true",
105
+ });
106
+ }
107
+ validatePlanFields(message, {
108
+ path: `${path}.typedData.message`,
109
+ fields: {
110
+ authorizer: "address",
111
+ authorized: "address",
112
+ nonce: "uint256 bigint",
113
+ deadline: "uint256 bigint",
114
+ },
115
+ });
116
+ if (request.signature !== undefined) {
117
+ validatePlanField(request.signature, {
118
+ path: `${path}.signature`,
119
+ type: "hex",
120
+ });
121
+ }
122
+ }
@@ -0,0 +1,80 @@
1
+ import type { MarketId } from "@morpho-org/blue-sdk";
2
+ import type { Client } from "viem";
3
+ import type { VaultV2BlueReallocation } from "../../types/index.js";
4
+ import type { IntentParams } from "../intent.js";
5
+ import type { Action, SignatureRequest, TransactionPlan } from "../types.js";
6
+ import { type BlueMarketSnapshot, type BluePositionSnapshot } from "./prepare.js";
7
+ /**
8
+ * Borrow intent backed by caller-fetched market and position snapshots.
9
+ * @example
10
+ * ```ts
11
+ * const params: BlueBorrowPlanParams = { chainId: 1, account, marketId: market.id,
12
+ * marketData: { chainId: 1, market }, positionData: { chainId: 1, position }, borrowAssets: 100n };
13
+ * ```
14
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
15
+ */
16
+ export interface BlueBorrowPlanParams extends IntentParams {
17
+ readonly marketId: MarketId;
18
+ readonly marketData: BlueMarketSnapshot;
19
+ readonly positionData: BluePositionSnapshot;
20
+ /** Gross debt increase, before allocator penalties and referral fees. */
21
+ readonly borrowAssets: bigint;
22
+ readonly reallocations?: readonly VaultV2BlueReallocation[];
23
+ readonly now?: bigint;
24
+ }
25
+ /**
26
+ * Prepares a BlueBundlesV1 borrow against existing collateral. No token allowance is needed.
27
+ * Health is checked on the position accrued two hours beyond the later of now and last update,
28
+ * matching the existing Blue borrow handle. Snapshots are not retained in the stored plan.
29
+ * Reads Morpho authorization of BlueBundlesV1 (and its nonce when signing) from `client`.
30
+ * @param client - Viem client for `params.chainId`, used for Morpho authorization and contract code reads.
31
+ * @param params - Borrow intent and chain-tagged snapshots for the borrowing account.
32
+ * @returns A data-only plan with any Morpho authorization prerequisite before the borrow.
33
+ * @throws {ChainIdMismatchError} When the client declares another chain or its RPC reports another chain.
34
+ * @throws {MissingContractCodeError} When BlueBundlesV1 or Morpho Blue has no deployed code.
35
+ * @throws {UnsupportedBlueMarketIrmError} When positive debt requires an unsupported IRM projection.
36
+ * @throws {viem.BaseError} When a chain ID, authorization, nonce, or contract code read fails.
37
+ * @throws {BlueSnapshotChainMismatchError} When a snapshot was read from another chain.
38
+ * @throws {MarketIdMismatchError} When a snapshot describes another market.
39
+ * @throws {AccrualPositionUserMismatchError} When `positionData` belongs to another account.
40
+ * @throws {ZeroAccountError} When `account` is the zero address.
41
+ * @throws {NonIntegerInputError} When `expiresAt` or `referralFee.bps` is not a safe integer.
42
+ * @throws {NonPositiveInputError} When `expiresAt`, `borrowAssets` or a reallocation amount is not positive.
43
+ * @throws {ExpiredDeadlineError} When `expiresAt` is at or before `now`.
44
+ * @throws {NegativeInputError} When `referralFee.bps` or a reallocation penalty is negative.
45
+ * @throws {InputExceedsMaxError} When a fee or reallocation bound is exceeded, including aggregate allocator penalties above the borrow.
46
+ * @throws {InvalidCalldataOriginError} When `calldataOrigin` is empty, malformed or has an odd number of hex digits.
47
+ * @throws {ReferralFeePctExceededError} When `referralFee.bps` equals 10,000.
48
+ * @throws {ReferralFeeRecipientMissingError} When a positive referral fee has no recipient.
49
+ * @throws {InvalidVaultV2BlueReallocationShapeError} When a reallocation entry is malformed.
50
+ * @throws {ReallocationWithdrawalOnTargetMarketError} When a reallocation sources the target market.
51
+ * @throws {MissingMarketPriceError} When the market snapshot has no oracle price.
52
+ * @throws {BorrowExceedsSafeLtvError} When the resulting debt exceeds buffered LLTV.
53
+ * @see blueBorrow for the remaining reallocation encoding errors.
54
+ * @example
55
+ * ```ts
56
+ * import { prepareBlueBorrow } from "@morpho-org/morpho-sdk";
57
+ * import { fetchBlueAccrualPosition, fetchBlueMarket } from "@morpho-org/morpho-sdk/fetch";
58
+ * import type { MarketId } from "@morpho-org/blue-sdk";
59
+ * import { createPublicClient, http } from "viem";
60
+ * import { mainnet } from "viem/chains";
61
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
62
+ * const account = "0x0000000000000000000000000000000000000001";
63
+ * const marketId = "0xb8fc70e82bc5bb53e773626fcc6a23f7eefa036918d7ef216ecfb1950a94a85e" as MarketId;
64
+ * const plan = await prepareBlueBorrow(client, {
65
+ * chainId: 1, account, marketId, borrowAssets: 1_000_000n, supportSignature: true,
66
+ * marketData: { chainId: 1, market: await fetchBlueMarket(marketId, client) },
67
+ * positionData: { chainId: 1, position: await fetchBlueAccrualPosition(account, marketId, client) },
68
+ * now: (await client.getBlock()).timestamp,
69
+ * });
70
+ * // Sign the pending Morpho authorization request if any, attach it with applySignatures, then build.
71
+ * ```
72
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
73
+ */
74
+ export declare function prepareBlueBorrow(client: Client, { chainId, account, marketId, marketData, positionData, borrowAssets, reallocations, expiresAt, referralFee, supportSignature, calldataOrigin, deployless, now, }: BlueBorrowPlanParams): Promise<TransactionPlan>;
75
+ /** @internal Encodes a prepared borrow without state reads or signing. */
76
+ export declare function buildBlueBorrow(action: Extract<Action, {
77
+ type: "blueBorrow";
78
+ }>, requests: readonly SignatureRequest[]): Readonly<import("../../types/action.js").Transaction<import("../../types/action.js").BlueBorrowAction>>;
79
+ /** @internal Validates the stored borrow recipe, including each allocator input. */
80
+ export declare function validateBorrowPlanAction(action: Record<string, unknown>, path: string): void;