@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
@@ -0,0 +1,93 @@
1
+ import { type MarketId } from "@morpho-org/blue-sdk";
2
+ import type { Client } from "viem";
3
+ import type { BlueRefinanceAction, ReferenceTimestampParams, Transaction, 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
+ type RefinanceAction = Extract<Action, {
8
+ type: "blueRefinance";
9
+ }>;
10
+ interface RefinanceMarket {
11
+ readonly marketId: MarketId;
12
+ readonly marketData: BlueMarketSnapshot;
13
+ readonly positionData: BluePositionSnapshot;
14
+ }
15
+ /**
16
+ * Intent and caller-fetched snapshots for a full Blue borrow-position migration.
17
+ * @example
18
+ * ```ts
19
+ * import type { BlueRefinancePlanParams } from "@morpho-org/morpho-sdk";
20
+ * const withSignature = (params: BlueRefinancePlanParams): BlueRefinancePlanParams => ({
21
+ * ...params,
22
+ * supportSignature: true,
23
+ * });
24
+ * ```
25
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
26
+ */
27
+ export interface BlueRefinancePlanParams extends Omit<IntentParams, "deployless">, ReferenceTimestampParams {
28
+ /** Request a Morpho authorization signature instead of a direct transaction when needed. Defaults to `false`. */
29
+ readonly supportSignature?: boolean;
30
+ /** Source market and borrowing account's position. */
31
+ readonly source: RefinanceMarket;
32
+ /** Destination market and the same account's position, including an empty position. */
33
+ readonly destination: RefinanceMarket;
34
+ /** Optional ordered Vault V2 reallocations into the destination market. */
35
+ readonly reallocations?: readonly VaultV2BlueReallocation[];
36
+ }
37
+ /**
38
+ * Prepares a full Blue borrow-position migration. Fetch both market and position snapshots at the
39
+ * same block and pass that block's timestamp as `now`. Penalties and fees increase destination debt;
40
+ * the quote checks the buffered destination LLTV and the transaction enforces it again onchain.
41
+ *
42
+ * BlueBundlesV1 moves the full live debt and collateral without pulling tokens from the account.
43
+ * When Morpho authorization is missing, the plan requests a signature inline if supported,
44
+ * otherwise it puts a direct authorization step before the migration.
45
+ * @param client - Viem client used to check deployed contracts and resolve Morpho authorization.
46
+ * @param params - Chain, sending account, market and position snapshots, and optional reallocations.
47
+ * @returns A frozen plan with only the steps and signature requests required for the migration.
48
+ * @throws {BlueSnapshotChainMismatchError} when either snapshot comes from another chain.
49
+ * @throws {MarketIdMismatchError} when a snapshot or embedded market tuple does not match its market ID.
50
+ * @throws {AccrualPositionUserMismatchError} when a position belongs to another account.
51
+ * @throws {RefinanceSameMarketError} when the source and destination are the same market.
52
+ * @throws {RefinanceTokenMismatchError} when the markets have different loan or collateral tokens.
53
+ * @throws {MissingMarketPriceError} when the destination price is unavailable.
54
+ * @throws {UnsupportedBlueMarketIrmError} when debt projection requires an unsupported IRM.
55
+ * @throws {BorrowExceedsSafeLtvError} when the resulting debt exceeds the buffered destination LLTV.
56
+ * @throws {ZeroAccountError} when the sending account is the zero address.
57
+ * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
58
+ * @throws {NonPositiveInputError} when the source has no debt shares, or expiry or reallocation assets are not positive.
59
+ * @throws {ExpiredDeadlineError} when expiry is at or before `now`.
60
+ * @throws {NegativeInputError} when a referral fee or reallocation penalty is negative.
61
+ * @throws {InputExceedsMaxError} when the fee or a reallocation value exceeds its bound.
62
+ * @throws {ReferralFeePctExceededError} when `referralFee.bps` is 10,000.
63
+ * @throws {ReferralFeeRecipientMissingError} when a positive fee has no nonzero recipient.
64
+ * @throws {InvalidTransactionPlanError} when the account, referral fee recipient, market tuples, or stored reallocation fields are malformed.
65
+ * @throws {InvalidCalldataOriginError} when calldata origin is not nonempty, whole-byte hex.
66
+ * @throws {InvalidVaultV2BlueReallocationShapeError} when a reallocation is not a Vault V2 entry.
67
+ * @throws {InvalidReallocationAddressError} when a vault or adapter address is invalid.
68
+ * @throws {InvalidReallocationSourceTypeError} when a reallocation source is malformed.
69
+ * @throws {InconsistentReallocationPenaltyError} when one vault uses different penalties.
70
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation withdraws from the destination market.
71
+ * @throws {ReallocationLoanTokenMismatchError} when a reallocation uses another loan token.
72
+ * @throws {ChainIdMismatchError} when the client or RPC serves another chain.
73
+ * @throws {UnsupportedChainIdError} when the chain is not in the address registry.
74
+ * @throws {UnknownAddressError} when Morpho Blue or BlueBundlesV1 is not registered on the chain.
75
+ * @throws {MissingContractCodeError} when either registered contract has no deployed code.
76
+ * @throws {viem.BaseError} when a required RPC read fails.
77
+ * @example
78
+ * ```ts
79
+ * import { getPendingSignatureRequests, prepareBlueRefinance, type BlueRefinancePlanParams } from "@morpho-org/morpho-sdk";
80
+ * import type { Client } from "viem";
81
+ * async function prepare(client: Client, snapshots: BlueRefinancePlanParams) {
82
+ * const plan = await prepareBlueRefinance(client, { ...snapshots, supportSignature: true });
83
+ * return { plan, requests: getPendingSignatureRequests(plan) };
84
+ * }
85
+ * ```
86
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
87
+ */
88
+ export declare function prepareBlueRefinance(client: Client, params: BlueRefinancePlanParams): Promise<TransactionPlan>;
89
+ /** @internal Validates the stored migration inputs and optional authorization binding. */
90
+ export declare function validateRefinancePlanAction(action: Record<string, unknown>, path: string): void;
91
+ /** @internal Encodes the stored migration with the referenced signature inline, if required. */
92
+ export declare function buildBlueRefinance(action: RefinanceAction, requests: readonly SignatureRequest[]): Readonly<Transaction<BlueRefinanceAction>>;
93
+ export {};
@@ -0,0 +1,281 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareBlueRefinance = prepareBlueRefinance;
4
+ exports.validateRefinancePlanAction = validateRefinancePlanAction;
5
+ exports.buildBlueRefinance = buildBlueRefinance;
6
+ const blue_sdk_1 = require("@morpho-org/blue-sdk");
7
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
8
+ const common_js_1 = require("../../actions/blue/common.js");
9
+ const refinance_js_1 = require("../../actions/blue/refinance.js");
10
+ const refinanceValidation_js_1 = require("../../actions/blue/refinanceValidation.js");
11
+ const index_js_1 = require("../../helpers/index.js");
12
+ const error_js_1 = require("../error.js");
13
+ const validation_js_1 = require("../validation.js");
14
+ const prepare_js_1 = require("./prepare.js");
15
+ const refinanceValidation_js_2 = require("./refinanceValidation.js");
16
+ /**
17
+ * Prepares a full Blue borrow-position migration. Fetch both market and position snapshots at the
18
+ * same block and pass that block's timestamp as `now`. Penalties and fees increase destination debt;
19
+ * the quote checks the buffered destination LLTV and the transaction enforces it again onchain.
20
+ *
21
+ * BlueBundlesV1 moves the full live debt and collateral without pulling tokens from the account.
22
+ * When Morpho authorization is missing, the plan requests a signature inline if supported,
23
+ * otherwise it puts a direct authorization step before the migration.
24
+ * @param client - Viem client used to check deployed contracts and resolve Morpho authorization.
25
+ * @param params - Chain, sending account, market and position snapshots, and optional reallocations.
26
+ * @returns A frozen plan with only the steps and signature requests required for the migration.
27
+ * @throws {BlueSnapshotChainMismatchError} when either snapshot comes from another chain.
28
+ * @throws {MarketIdMismatchError} when a snapshot or embedded market tuple does not match its market ID.
29
+ * @throws {AccrualPositionUserMismatchError} when a position belongs to another account.
30
+ * @throws {RefinanceSameMarketError} when the source and destination are the same market.
31
+ * @throws {RefinanceTokenMismatchError} when the markets have different loan or collateral tokens.
32
+ * @throws {MissingMarketPriceError} when the destination price is unavailable.
33
+ * @throws {UnsupportedBlueMarketIrmError} when debt projection requires an unsupported IRM.
34
+ * @throws {BorrowExceedsSafeLtvError} when the resulting debt exceeds the buffered destination LLTV.
35
+ * @throws {ZeroAccountError} when the sending account is the zero address.
36
+ * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
37
+ * @throws {NonPositiveInputError} when the source has no debt shares, or expiry or reallocation assets are not positive.
38
+ * @throws {ExpiredDeadlineError} when expiry is at or before `now`.
39
+ * @throws {NegativeInputError} when a referral fee or reallocation penalty is negative.
40
+ * @throws {InputExceedsMaxError} when the fee or a reallocation value exceeds its bound.
41
+ * @throws {ReferralFeePctExceededError} when `referralFee.bps` is 10,000.
42
+ * @throws {ReferralFeeRecipientMissingError} when a positive fee has no nonzero recipient.
43
+ * @throws {InvalidTransactionPlanError} when the account, referral fee recipient, market tuples, or stored reallocation fields are malformed.
44
+ * @throws {InvalidCalldataOriginError} when calldata origin is not nonempty, whole-byte hex.
45
+ * @throws {InvalidVaultV2BlueReallocationShapeError} when a reallocation is not a Vault V2 entry.
46
+ * @throws {InvalidReallocationAddressError} when a vault or adapter address is invalid.
47
+ * @throws {InvalidReallocationSourceTypeError} when a reallocation source is malformed.
48
+ * @throws {InconsistentReallocationPenaltyError} when one vault uses different penalties.
49
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation withdraws from the destination market.
50
+ * @throws {ReallocationLoanTokenMismatchError} when a reallocation uses another loan token.
51
+ * @throws {ChainIdMismatchError} when the client or RPC serves another chain.
52
+ * @throws {UnsupportedChainIdError} when the chain is not in the address registry.
53
+ * @throws {UnknownAddressError} when Morpho Blue or BlueBundlesV1 is not registered on the chain.
54
+ * @throws {MissingContractCodeError} when either registered contract has no deployed code.
55
+ * @throws {viem.BaseError} when a required RPC read fails.
56
+ * @example
57
+ * ```ts
58
+ * import { getPendingSignatureRequests, prepareBlueRefinance, type BlueRefinancePlanParams } from "@morpho-org/morpho-sdk";
59
+ * import type { Client } from "viem";
60
+ * async function prepare(client: Client, snapshots: BlueRefinancePlanParams) {
61
+ * const plan = await prepareBlueRefinance(client, { ...snapshots, supportSignature: true });
62
+ * return { plan, requests: getPendingSignatureRequests(plan) };
63
+ * }
64
+ * ```
65
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
66
+ */
67
+ async function prepareBlueRefinance(client, params) {
68
+ const { account, chainId, source, destination } = params;
69
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
70
+ const sourceMarketParams = structuredClone(source.marketData.market.params);
71
+ const destinationMarketParams = structuredClone(destination.marketData.market.params);
72
+ const reallocations = structuredClone(params.reallocations ?? []);
73
+ const id = "blueRefinance";
74
+ const { intent, steps, signatureRequests, morphoAuthorizationRequestId } = await (0, prepare_js_1.prepareBlue)({
75
+ client,
76
+ params: {
77
+ ...params,
78
+ marketId: source.marketId,
79
+ marketData: source.marketData,
80
+ positionData: source.positionData,
81
+ now,
82
+ },
83
+ }, ({ deadline, referralFeePct, referralFeeRecipient }) => {
84
+ // Reject malformed market tuples before quoting or resolving authorization.
85
+ validatePlanMarketParams(sourceMarketParams, "$.source.marketData.market.params");
86
+ validatePlanMarketParams(destinationMarketParams, "$.destination.marketData.market.params");
87
+ // Validate destination identity and fee before using them to quote migration health.
88
+ (0, refinanceValidation_js_2.validateBlueRefinanceDestination)({
89
+ chainId,
90
+ account,
91
+ marketId: destination.marketId,
92
+ marketData: destination.marketData,
93
+ positionData: destination.positionData,
94
+ });
95
+ if (referralFeeRecipient !== undefined) {
96
+ (0, validation_js_1.validatePlanField)(referralFeeRecipient, {
97
+ path: "$.referralFee.recipient",
98
+ type: "address",
99
+ });
100
+ }
101
+ (0, common_js_1.normalizeBlueBundlesV1CommonParams)({
102
+ chainId,
103
+ userAddress: account,
104
+ deadline,
105
+ referralFeePct,
106
+ referralFeeRecipient,
107
+ });
108
+ // Check that the source debt can move into this destination market.
109
+ (0, refinanceValidation_js_1.validateBlueRefinanceSource)({
110
+ sourceMarketParams,
111
+ destinationMarketParams,
112
+ borrowShares: source.positionData.position.borrowShares,
113
+ });
114
+ // The quote only gates preparation; the contract migrates the actual live position.
115
+ (0, refinanceValidation_js_1.validateBlueRefinanceQuote)({
116
+ destinationMarketParams,
117
+ sourcePosition: source.positionData.position,
118
+ destinationPosition: destination.positionData.position,
119
+ reallocations,
120
+ referralFeePct,
121
+ now,
122
+ });
123
+ validatePlanReallocations(reallocations, "$.reallocations");
124
+ return { id, needsAuthorization: true };
125
+ });
126
+ const request = signatureRequests.find((candidate) => candidate.kind === "morphoAuthorization" &&
127
+ candidate.id === morphoAuthorizationRequestId);
128
+ const common = (0, common_js_1.normalizeBlueBundlesV1CommonParams)({
129
+ chainId,
130
+ userAddress: account,
131
+ ...intent,
132
+ });
133
+ const action = {
134
+ type: "blueRefinance",
135
+ inputs: {
136
+ chainId,
137
+ account,
138
+ sourceMarketParams,
139
+ destinationMarketParams,
140
+ maxLtv: blue_sdk_1.MathLib.zeroFloorSub(destinationMarketParams.lltv, index_js_1.DEFAULT_LLTV_BUFFER),
141
+ deadline: intent.deadline,
142
+ ...common,
143
+ reallocations,
144
+ ...(request && { authorizationNonce: request.args.nonce }),
145
+ },
146
+ signatureRequestIds: request === undefined ? {} : { morphoAuthorization: request.id },
147
+ };
148
+ return (0, morpho_ts_1.deepFreeze)(structuredClone({
149
+ version: 2,
150
+ account,
151
+ chainId,
152
+ expiresAt: intent.expiresAt,
153
+ ...(intent.calldataOrigin && { calldataOrigin: intent.calldataOrigin }),
154
+ steps: [
155
+ ...steps,
156
+ { id, label: "Refinance Blue borrow position", action },
157
+ ],
158
+ signatureRequests,
159
+ }));
160
+ }
161
+ function validatePlanMarketParams(value, path) {
162
+ const params = (0, validation_js_1.getPlanObject)(value, path);
163
+ (0, validation_js_1.validatePlanFields)(params, {
164
+ path,
165
+ fields: {
166
+ loanToken: "address",
167
+ collateralToken: "address",
168
+ oracle: "address",
169
+ irm: "address",
170
+ lltv: "uint256 bigint",
171
+ id: "hex",
172
+ liquidationIncentiveFactor: "uint256 bigint",
173
+ },
174
+ });
175
+ if (typeof params.id !== "string" || params.id.length !== 66) {
176
+ throw new error_js_1.InvalidTransactionPlanError({
177
+ path: `${path}.id`,
178
+ reason: "expected a 32-byte market ID",
179
+ });
180
+ }
181
+ }
182
+ function validatePlanReallocations(legs, path) {
183
+ for (const [index, leg] of legs.entries()) {
184
+ validatePlanReallocation(leg, `${path}[${index}]`);
185
+ }
186
+ }
187
+ function validatePlanReallocation(value, path) {
188
+ const leg = (0, validation_js_1.getPlanObject)(value, path);
189
+ (0, validation_js_1.validatePlanFields)(leg, {
190
+ path,
191
+ fields: {
192
+ vault: "address",
193
+ assets: "uint256 bigint",
194
+ penalty: "uint256 bigint",
195
+ },
196
+ });
197
+ (0, validation_js_1.validatePlanField)((0, validation_js_1.getPlanObject)(leg.to, `${path}.to`).adapter, {
198
+ path: `${path}.to.adapter`,
199
+ type: "address",
200
+ });
201
+ const from = (0, validation_js_1.getPlanObject)(leg.from, `${path}.from`);
202
+ if (from.type === "idle") {
203
+ return;
204
+ }
205
+ if (from.type !== "market") {
206
+ throw new error_js_1.InvalidTransactionPlanError({
207
+ path: `${path}.from.type`,
208
+ reason: "expected idle or market",
209
+ });
210
+ }
211
+ (0, validation_js_1.validatePlanField)(from.adapter, {
212
+ path: `${path}.from.adapter`,
213
+ type: "address",
214
+ });
215
+ validatePlanMarketParams(from.marketParams, `${path}.from.marketParams`);
216
+ }
217
+ /** @internal Validates the stored migration inputs and optional authorization binding. */
218
+ function validateRefinancePlanAction(action, path) {
219
+ const inputs = (0, validation_js_1.getPlanObject)(action.inputs, `${path}.inputs`);
220
+ (0, validation_js_1.validatePlanFields)(inputs, {
221
+ path: `${path}.inputs`,
222
+ fields: {
223
+ maxLtv: "uint256 bigint",
224
+ deadline: "uint256 bigint",
225
+ referralFeePct: "uint256 bigint",
226
+ referralFeeRecipient: "address",
227
+ reallocations: "array",
228
+ },
229
+ });
230
+ validatePlanMarketParams(inputs.sourceMarketParams, `${path}.inputs.sourceMarketParams`);
231
+ validatePlanMarketParams(inputs.destinationMarketParams, `${path}.inputs.destinationMarketParams`);
232
+ validatePlanReallocations(inputs.reallocations, `${path}.inputs.reallocations`);
233
+ const ids = (0, validation_js_1.getPlanObject)(action.signatureRequestIds, `${path}.signatureRequestIds`);
234
+ if (Object.keys(ids).some((role) => role !== "morphoAuthorization")) {
235
+ throw new error_js_1.InvalidTransactionPlanError({
236
+ path: `${path}.signatureRequestIds`,
237
+ reason: "expected only a Morpho authorization role",
238
+ });
239
+ }
240
+ if (ids.morphoAuthorization !== undefined) {
241
+ (0, validation_js_1.validatePlanField)(inputs.authorizationNonce, {
242
+ path: `${path}.inputs.authorizationNonce`,
243
+ type: "uint256 bigint",
244
+ });
245
+ }
246
+ else if (inputs.authorizationNonce !== undefined) {
247
+ throw new error_js_1.InvalidTransactionPlanError({
248
+ path: `${path}.inputs.authorizationNonce`,
249
+ reason: "expected a referenced authorization request",
250
+ });
251
+ }
252
+ }
253
+ /** @internal Encodes the stored migration with the referenced signature inline, if required. */
254
+ function buildBlueRefinance(action, requests) {
255
+ const { account, chainId, sourceMarketParams, destinationMarketParams, ...args } = action.inputs;
256
+ const id = action.signatureRequestIds.morphoAuthorization;
257
+ let authorizationSignature;
258
+ if (id !== undefined) {
259
+ const request = requests.find((candidate) => candidate.id === id);
260
+ if (request?.kind !== "morphoAuthorization" ||
261
+ request.signature === undefined) {
262
+ throw new error_js_1.IncompleteTransactionPlanError(id);
263
+ }
264
+ const { authorized, deadline } = request.args;
265
+ authorizationSignature = {
266
+ args: {
267
+ ...request.args,
268
+ isAuthorized: true,
269
+ signature: request.signature,
270
+ },
271
+ action: {
272
+ type: "authorization",
273
+ args: { authorized, isAuthorized: true, deadline },
274
+ },
275
+ };
276
+ }
277
+ return (0, refinance_js_1.blueRefinance)({
278
+ market: { chainId, sourceMarketParams, destinationMarketParams },
279
+ args: { ...args, userAddress: account, authorizationSignature },
280
+ });
281
+ }
@@ -0,0 +1,11 @@
1
+ import type { MarketParams } from "@morpho-org/blue-sdk";
2
+ import { type Address } from "viem";
3
+ import { type BlueMarketSnapshot, type BluePositionSnapshot } from "./prepare.js";
4
+ /** @internal Checks the destination snapshots before quoting the migration. */
5
+ export declare function validateBlueRefinanceDestination({ chainId, account, marketId, marketData, positionData, }: {
6
+ readonly chainId: number;
7
+ readonly account: Address;
8
+ readonly marketId: MarketParams["id"];
9
+ readonly marketData: BlueMarketSnapshot;
10
+ readonly positionData: BluePositionSnapshot;
11
+ }): void;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateBlueRefinanceDestination = validateBlueRefinanceDestination;
4
+ const viem_1 = require("viem");
5
+ const index_js_1 = require("../../types/index.js");
6
+ const prepare_js_1 = require("./prepare.js");
7
+ /** @internal Checks the destination snapshots before quoting the migration. */
8
+ function validateBlueRefinanceDestination({ chainId, account, marketId, marketData, positionData, }) {
9
+ const { position } = positionData;
10
+ const expected = { chainId, marketId };
11
+ // Check both supplied market tuples against the destination identity.
12
+ (0, prepare_js_1.validateBlueMarketSnapshot)(marketData, expected);
13
+ (0, prepare_js_1.validateBlueMarketSnapshot)({ chainId: positionData.chainId, market: position.market }, expected);
14
+ if (position.marketId.toLowerCase() !== marketId.toLowerCase()) {
15
+ throw new index_js_1.MarketIdMismatchError(position.marketId, marketId);
16
+ }
17
+ if (!(0, viem_1.isAddressEqual)(position.user, account)) {
18
+ throw new index_js_1.AccrualPositionUserMismatchError(position.user, account);
19
+ }
20
+ }
@@ -0,0 +1,80 @@
1
+ import { type MarketId } from "@morpho-org/blue-sdk";
2
+ import { type Client } from "viem";
3
+ import type { Funding, IntentParams } from "../intent.js";
4
+ import type { Action, SignatureRequest, TransactionPlan } from "../types.js";
5
+ import { type BlueMarketSnapshot, type BluePositionSnapshot } from "./prepare.js";
6
+ /**
7
+ * Intent for repaying Blue debt using caller-fetched market and position snapshots.
8
+ * Full repayment uses saturated shares and funds the deadline-accrued debt rounded up.
9
+ * @example
10
+ * ```ts
11
+ * import type { BlueRepayPlanParams } from "@morpho-org/morpho-sdk";
12
+ * const fullRepay = (params: BlueRepayPlanParams): BlueRepayPlanParams => ({ ...params, mode: { type: "full" } });
13
+ * ```
14
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
15
+ */
16
+ export interface BlueRepayPlanParams extends IntentParams {
17
+ readonly marketId: MarketId;
18
+ readonly marketData: BlueMarketSnapshot;
19
+ readonly positionData: BluePositionSnapshot;
20
+ readonly mode: {
21
+ readonly type: "assets";
22
+ readonly amount: bigint;
23
+ } | {
24
+ readonly type: "shares";
25
+ readonly amount: bigint;
26
+ } | {
27
+ readonly type: "full";
28
+ };
29
+ readonly funding?: Funding;
30
+ readonly now?: bigint;
31
+ }
32
+ /**
33
+ * Prepares an asset, share, or full Blue repayment through BlueBundlesV1, never Permit2.
34
+ * Share quotes accrue the supplied position to expiry, at most two hours from the reference time.
35
+ * @param client - Viem client used only for token allowance and permit reads.
36
+ * @param params - Repayment intent and caller-fetched snapshots. Native funding is exclusive and requires wNative.
37
+ * @returns A static plan containing any token prerequisite followed by repayment.
38
+ * @throws {ZeroAccountError} If `account` is the zero address.
39
+ * @throws {NonIntegerInputError} If `expiresAt` or `referralFee.bps` is not a safe integer.
40
+ * @throws {NonPositiveInputError} If expiry, repayment, or derived funding is not positive.
41
+ * @throws {ExpiredDeadlineError} If expiry is at or before `now`.
42
+ * @throws {NegativeInputError} If `referralFee.bps` is negative.
43
+ * @throws {InputExceedsMaxError} If a share-mode expiry exceeds the quote horizon, the referral fee exceeds 10,000 bps, or an encoded amount exceeds uint256.
44
+ * @throws {InvalidCalldataOriginError} If attribution bytes are empty, malformed, or have an odd number of hex digits.
45
+ * @throws {BlueSnapshotChainMismatchError} If either snapshot describes another chain.
46
+ * @throws {MarketIdMismatchError} If either snapshot's market ID disagrees with `marketId` or its market tuple.
47
+ * @throws {AccrualPositionUserMismatchError} If the position belongs to another account.
48
+ * @throws {ReferralFeePctExceededError} If the referral fee equals 10,000 bps; the normalized fee must be below WAD.
49
+ * @throws {ReferralFeeRecipientMissingError} If a positive referral fee has no recipient or a zero recipient.
50
+ * @throws {RepayExceedsDebtError} If an asset repayment exceeds the snapshot's borrow assets.
51
+ * @throws {RepaySharesExceedDebtError} If a non-saturated share repayment exceeds the snapshot's borrow shares.
52
+ * @throws {UnsupportedMarketIrmError} If interest accrual requires an unsupported IRM without a supplied rate at target.
53
+ * @throws {ChainWNativeMissingError} If native funding is requested on a chain without registered wNative.
54
+ * @throws {NativeAmountOnNonWNativeAssetError} If native funding targets a loan token other than wNative.
55
+ * @throws {ChainIdMismatchError} If the client's declared or served chain differs from the repayment chain.
56
+ * @throws {MissingContractCodeError} If registered BlueBundlesV1 or Morpho has no deployed code.
57
+ * @throws {UnsupportedChainIdError} If the chain is absent from the address registry.
58
+ * @throws {UnknownAddressError} If a required contract address is not registered.
59
+ * @throws {viem.BaseError} If an RPC read or ABI encoding fails.
60
+ * @example
61
+ * ```ts
62
+ * import { prepareBlueRepay, type BlueRepayPlanParams } from "@morpho-org/morpho-sdk";
63
+ * import type { Client } from "viem";
64
+ * const prepare = (client: Client, params: BlueRepayPlanParams) => prepareBlueRepay(client, params);
65
+ * ```
66
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
67
+ */
68
+ export declare function prepareBlueRepay(client: Client, { chainId, account, marketId, marketData, positionData, mode, funding, expiresAt, referralFee, supportSignature, calldataOrigin, deployless, now, }: BlueRepayPlanParams): Promise<TransactionPlan>;
69
+ /** @internal Checks a repayment permit against the fixed token pull. */
70
+ export declare function validateBlueRepayPermit(request: Extract<SignatureRequest, {
71
+ kind: "permit";
72
+ }>, action: Extract<Action, {
73
+ type: "blueRepay";
74
+ }>): void;
75
+ /** @internal Encodes a stored repayment using only fixed inputs and referenced signatures. */
76
+ export declare function buildBlueRepay(action: Extract<Action, {
77
+ type: "blueRepay";
78
+ }>, requests: readonly SignatureRequest[]): Readonly<import("../../index.js").Transaction<import("../../index.js").BlueRepayAction>>;
79
+ /** @internal Validates the stored repayment's structural fields. */
80
+ export declare function validateBlueRepayPlanAction(action: Record<string, unknown>, path: string): void;