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