@morpho-org/morpho-sdk 10.3.1 → 10.5.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 (344) hide show
  1. package/README.md +169 -5
  2. package/lib/cjs/abis.d.ts +1 -1
  3. package/lib/cjs/abis.js +5 -1
  4. package/lib/cjs/actions/blue/common.js +12 -3
  5. package/lib/cjs/actions/midnight/redeem.d.ts +20 -3
  6. package/lib/cjs/actions/midnight/redeem.js +58 -1
  7. package/lib/cjs/actions/midnight/supplyCollateralWithNative.d.ts +24 -1
  8. package/lib/cjs/actions/midnight/supplyCollateralWithNative.js +41 -0
  9. package/lib/cjs/actions/midnight/withdrawCollateral.d.ts +16 -2
  10. package/lib/cjs/actions/midnight/withdrawCollateral.js +26 -1
  11. package/lib/cjs/blue/abis.d.ts +1 -1
  12. package/lib/cjs/blue/abis.js +5 -1
  13. package/lib/cjs/blue/entities.d.ts +4 -4
  14. package/lib/cjs/blue/entities.js +3 -1
  15. package/lib/cjs/blue/errors.d.ts +2 -2
  16. package/lib/cjs/blue/errors.js +5 -1
  17. package/lib/cjs/blue/fetch.d.ts +2 -2
  18. package/lib/cjs/blue/fetch.js +3 -1
  19. package/lib/cjs/blue/utils.d.ts +1 -1
  20. package/lib/cjs/blue/utils.js +2 -1
  21. package/lib/cjs/entities/index.d.ts +4 -4
  22. package/lib/cjs/entities/index.js +3 -1
  23. package/lib/cjs/entities/midnight/midnight.d.ts +100 -103
  24. package/lib/cjs/entities/midnight/midnight.js +99 -99
  25. package/lib/cjs/entities/vaultV1/vaultV1.js +0 -1
  26. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +34 -8
  27. package/lib/cjs/entities/vaultV2/vaultV2.js +39 -2
  28. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +3 -2
  29. package/lib/cjs/entities/vaultV2BlueReallocationData.js +6 -2
  30. package/lib/cjs/errors.d.ts +4 -4
  31. package/lib/cjs/errors.js +7 -5
  32. package/lib/cjs/fetch.d.ts +2 -2
  33. package/lib/cjs/fetch.js +3 -1
  34. package/lib/cjs/helpers/callback.d.ts +3 -2
  35. package/lib/cjs/helpers/callback.js +4 -20
  36. package/lib/cjs/helpers/computeMidnightPostWithdrawalCollateral.d.ts +17 -0
  37. package/lib/cjs/helpers/computeMidnightPostWithdrawalCollateral.js +30 -0
  38. package/lib/cjs/helpers/deadShares.js +3 -0
  39. package/lib/cjs/helpers/parseMidnightMaker.d.ts +21 -0
  40. package/lib/cjs/helpers/parseMidnightMaker.js +41 -1
  41. package/lib/cjs/helpers/validate.d.ts +60 -2
  42. package/lib/cjs/helpers/validate.js +87 -1
  43. package/lib/cjs/helpers/validateMidnightPublication.d.ts +10 -0
  44. package/lib/cjs/helpers/validateMidnightPublication.js +18 -1
  45. package/lib/cjs/helpers/validateMidnightTakeableOfferFields.d.ts +28 -0
  46. package/lib/cjs/helpers/validateMidnightTakeableOfferFields.js +85 -0
  47. package/lib/cjs/index.d.ts +2 -2
  48. package/lib/cjs/index.js +23 -1
  49. package/lib/cjs/midnight/errors.d.ts +2 -1
  50. package/lib/cjs/midnight/errors.js +5 -4
  51. package/lib/cjs/midnight/utils.d.ts +1 -1
  52. package/lib/cjs/midnight/utils.js +2 -1
  53. package/lib/cjs/transactionPlan/assemble.d.ts +24 -0
  54. package/lib/cjs/transactionPlan/assemble.js +25 -0
  55. package/lib/cjs/transactionPlan/blue/borrow.js +14 -64
  56. package/lib/cjs/transactionPlan/blue/refinance.js +9 -11
  57. package/lib/cjs/transactionPlan/blue/repay.js +10 -24
  58. package/lib/cjs/transactionPlan/blue/repayWithdrawCollateral.js +49 -45
  59. package/lib/cjs/transactionPlan/blue/stored.d.ts +26 -0
  60. package/lib/cjs/transactionPlan/blue/stored.js +87 -0
  61. package/lib/cjs/transactionPlan/blue/supply.js +7 -22
  62. package/lib/cjs/transactionPlan/blue/supplyCollateral.d.ts +1 -1
  63. package/lib/cjs/transactionPlan/blue/supplyCollateral.js +10 -15
  64. package/lib/cjs/transactionPlan/blue/supplyCollateralBorrow.js +14 -64
  65. package/lib/cjs/transactionPlan/blue/withdraw.d.ts +2 -3
  66. package/lib/cjs/transactionPlan/blue/withdraw.js +67 -79
  67. package/lib/cjs/transactionPlan/blue/withdrawBuyCallback.d.ts +101 -0
  68. package/lib/cjs/transactionPlan/blue/withdrawBuyCallback.js +264 -0
  69. package/lib/cjs/transactionPlan/blue/withdrawCollateral.d.ts +2 -3
  70. package/lib/cjs/transactionPlan/blue/withdrawCollateral.js +31 -30
  71. package/lib/cjs/transactionPlan/deposit.js +4 -7
  72. package/lib/cjs/transactionPlan/error.d.ts +27 -0
  73. package/lib/cjs/transactionPlan/error.js +30 -1
  74. package/lib/cjs/transactionPlan/index.d.ts +40 -1
  75. package/lib/cjs/transactionPlan/index.js +46 -5
  76. package/lib/cjs/transactionPlan/intent.d.ts +1 -1
  77. package/lib/cjs/transactionPlan/midnight/authorization.d.ts +15 -0
  78. package/lib/cjs/transactionPlan/midnight/authorization.js +45 -0
  79. package/lib/cjs/transactionPlan/midnight/cancelOffers.d.ts +80 -0
  80. package/lib/cjs/transactionPlan/midnight/cancelOffers.js +125 -0
  81. package/lib/cjs/transactionPlan/midnight/makeBorrow.d.ts +104 -0
  82. package/lib/cjs/transactionPlan/midnight/makeBorrow.js +126 -0
  83. package/lib/cjs/transactionPlan/midnight/makeLend.d.ts +140 -0
  84. package/lib/cjs/transactionPlan/midnight/makeLend.js +176 -0
  85. package/lib/cjs/transactionPlan/midnight/makeRepay.d.ts +118 -0
  86. package/lib/cjs/transactionPlan/midnight/makeRepay.js +118 -0
  87. package/lib/cjs/transactionPlan/midnight/makeWithdraw.d.ts +104 -0
  88. package/lib/cjs/transactionPlan/midnight/makeWithdraw.js +126 -0
  89. package/lib/cjs/transactionPlan/midnight/makerPublication.d.ts +55 -0
  90. package/lib/cjs/transactionPlan/midnight/makerPublication.js +315 -0
  91. package/lib/cjs/transactionPlan/midnight/market.d.ts +49 -0
  92. package/lib/cjs/transactionPlan/midnight/market.js +120 -0
  93. package/lib/cjs/transactionPlan/midnight/prepare.d.ts +244 -0
  94. package/lib/cjs/transactionPlan/midnight/prepare.js +547 -0
  95. package/lib/cjs/transactionPlan/midnight/publicationState.d.ts +24 -0
  96. package/lib/cjs/transactionPlan/midnight/publicationState.js +50 -0
  97. package/lib/cjs/transactionPlan/midnight/redeem.d.ts +102 -0
  98. package/lib/cjs/transactionPlan/midnight/redeem.js +170 -0
  99. package/lib/cjs/transactionPlan/midnight/reduceOnlySellFeasibility.d.ts +25 -0
  100. package/lib/cjs/transactionPlan/midnight/reduceOnlySellFeasibility.js +51 -0
  101. package/lib/cjs/transactionPlan/midnight/repayWithdrawCollateral.d.ts +162 -0
  102. package/lib/cjs/transactionPlan/midnight/repayWithdrawCollateral.js +328 -0
  103. package/lib/cjs/transactionPlan/midnight/supplyBlueMakeLend.d.ts +155 -0
  104. package/lib/cjs/transactionPlan/midnight/supplyBlueMakeLend.js +199 -0
  105. package/lib/cjs/transactionPlan/midnight/supplyCollateral.d.ts +96 -0
  106. package/lib/cjs/transactionPlan/midnight/supplyCollateral.js +190 -0
  107. package/lib/cjs/transactionPlan/midnight/supplyCollateralBatch.d.ts +112 -0
  108. package/lib/cjs/transactionPlan/midnight/supplyCollateralBatch.js +221 -0
  109. package/lib/cjs/transactionPlan/midnight/supplyCollateralMakeBorrow.d.ts +129 -0
  110. package/lib/cjs/transactionPlan/midnight/supplyCollateralMakeBorrow.js +179 -0
  111. package/lib/cjs/transactionPlan/midnight/supplyCollateralWithNative.d.ts +115 -0
  112. package/lib/cjs/transactionPlan/midnight/supplyCollateralWithNative.js +259 -0
  113. package/lib/cjs/transactionPlan/midnight/takeBorrow.d.ts +304 -0
  114. package/lib/cjs/transactionPlan/midnight/takeBorrow.js +545 -0
  115. package/lib/cjs/transactionPlan/midnight/takeLend.d.ts +99 -0
  116. package/lib/cjs/transactionPlan/midnight/takeLend.js +263 -0
  117. package/lib/cjs/transactionPlan/midnight/takeRepayWithdrawCollateral.d.ts +175 -0
  118. package/lib/cjs/transactionPlan/midnight/takeRepayWithdrawCollateral.js +440 -0
  119. package/lib/cjs/transactionPlan/midnight/takeWithdraw.d.ts +139 -0
  120. package/lib/cjs/transactionPlan/midnight/takeWithdraw.js +240 -0
  121. package/lib/cjs/transactionPlan/midnight/validation.d.ts +22 -0
  122. package/lib/cjs/transactionPlan/midnight/validation.js +158 -0
  123. package/lib/cjs/transactionPlan/midnight/withdrawCollateral.d.ts +130 -0
  124. package/lib/cjs/transactionPlan/midnight/withdrawCollateral.js +228 -0
  125. package/lib/cjs/transactionPlan/midnight/withdrawCollateralBatch.d.ts +142 -0
  126. package/lib/cjs/transactionPlan/midnight/withdrawCollateralBatch.js +232 -0
  127. package/lib/cjs/transactionPlan/permit.d.ts +15 -2
  128. package/lib/cjs/transactionPlan/permit.js +26 -68
  129. package/lib/cjs/transactionPlan/plan.d.ts +99 -15
  130. package/lib/cjs/transactionPlan/plan.js +159 -31
  131. package/lib/cjs/transactionPlan/redeem.js +4 -7
  132. package/lib/cjs/transactionPlan/requirements.d.ts +7 -4
  133. package/lib/cjs/transactionPlan/requirements.js +2 -2
  134. package/lib/cjs/transactionPlan/serde.d.ts +13 -2
  135. package/lib/cjs/transactionPlan/serde.js +68 -21
  136. package/lib/cjs/transactionPlan/types.d.ts +151 -3
  137. package/lib/cjs/transactionPlan/validateActions.d.ts +3 -1
  138. package/lib/cjs/transactionPlan/validateActions.js +31 -3
  139. package/lib/cjs/transactionPlan/validation.d.ts +1 -1
  140. package/lib/cjs/transactionPlan/validation.js +37 -1
  141. package/lib/cjs/transactionPlan/vaultBinding.d.ts +29 -0
  142. package/lib/cjs/transactionPlan/vaultBinding.js +69 -0
  143. package/lib/cjs/transactionPlan/vaultRequirements.d.ts +20 -0
  144. package/lib/cjs/transactionPlan/vaultRequirements.js +37 -0
  145. package/lib/cjs/transactionPlan/vaultv1/deposit.d.ts +1 -1
  146. package/lib/cjs/transactionPlan/vaultv1/deposit.js +2 -13
  147. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.d.ts +2 -2
  148. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.js +10 -41
  149. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.d.ts +1 -1
  150. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.js +6 -18
  151. package/lib/cjs/transactionPlan/vaultv1/redeem.js +1 -12
  152. package/lib/cjs/transactionPlan/vaultv1/withdraw.d.ts +1 -1
  153. package/lib/cjs/transactionPlan/vaultv1/withdraw.js +2 -13
  154. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +1 -1
  155. package/lib/cjs/transactionPlan/vaultv2/deposit.js +2 -13
  156. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.d.ts +1 -1
  157. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.js +4 -7
  158. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.d.ts +2 -2
  159. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.js +12 -42
  160. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.d.ts +2 -2
  161. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.js +10 -41
  162. package/lib/cjs/transactionPlan/vaultv2/redeem.d.ts +1 -1
  163. package/lib/cjs/transactionPlan/vaultv2/redeem.js +2 -13
  164. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +1 -1
  165. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +2 -13
  166. package/lib/cjs/transactionPlan/withdraw.js +4 -7
  167. package/lib/cjs/types/error.d.ts +4 -1
  168. package/lib/cjs/types/error.js +5 -2
  169. package/lib/cjs/utils.d.ts +2 -2
  170. package/lib/cjs/utils.js +4 -2
  171. package/lib/cjs/version.d.ts +1 -1
  172. package/lib/cjs/version.js +1 -1
  173. package/lib/esm/abis.d.ts +1 -1
  174. package/lib/esm/abis.js +1 -1
  175. package/lib/esm/actions/blue/common.js +13 -4
  176. package/lib/esm/actions/midnight/redeem.d.ts +20 -3
  177. package/lib/esm/actions/midnight/redeem.js +56 -0
  178. package/lib/esm/actions/midnight/supplyCollateralWithNative.d.ts +24 -1
  179. package/lib/esm/actions/midnight/supplyCollateralWithNative.js +40 -0
  180. package/lib/esm/actions/midnight/withdrawCollateral.d.ts +16 -2
  181. package/lib/esm/actions/midnight/withdrawCollateral.js +25 -1
  182. package/lib/esm/blue/abis.d.ts +1 -1
  183. package/lib/esm/blue/abis.js +1 -1
  184. package/lib/esm/blue/entities.d.ts +4 -4
  185. package/lib/esm/blue/entities.js +2 -2
  186. package/lib/esm/blue/errors.d.ts +2 -2
  187. package/lib/esm/blue/errors.js +2 -2
  188. package/lib/esm/blue/fetch.d.ts +2 -2
  189. package/lib/esm/blue/fetch.js +2 -2
  190. package/lib/esm/blue/utils.d.ts +1 -1
  191. package/lib/esm/blue/utils.js +1 -1
  192. package/lib/esm/entities/index.d.ts +4 -4
  193. package/lib/esm/entities/index.js +2 -2
  194. package/lib/esm/entities/midnight/midnight.d.ts +100 -103
  195. package/lib/esm/entities/midnight/midnight.js +99 -99
  196. package/lib/esm/entities/vaultV1/vaultV1.js +0 -1
  197. package/lib/esm/entities/vaultV2/vaultV2.d.ts +34 -8
  198. package/lib/esm/entities/vaultV2/vaultV2.js +40 -3
  199. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +3 -2
  200. package/lib/esm/entities/vaultV2BlueReallocationData.js +6 -2
  201. package/lib/esm/errors.d.ts +4 -4
  202. package/lib/esm/errors.js +4 -4
  203. package/lib/esm/fetch.d.ts +2 -2
  204. package/lib/esm/fetch.js +2 -2
  205. package/lib/esm/helpers/callback.d.ts +3 -2
  206. package/lib/esm/helpers/callback.js +5 -21
  207. package/lib/esm/helpers/computeMidnightPostWithdrawalCollateral.d.ts +17 -0
  208. package/lib/esm/helpers/computeMidnightPostWithdrawalCollateral.js +27 -0
  209. package/lib/esm/helpers/deadShares.js +4 -1
  210. package/lib/esm/helpers/parseMidnightMaker.d.ts +21 -0
  211. package/lib/esm/helpers/parseMidnightMaker.js +40 -1
  212. package/lib/esm/helpers/validate.d.ts +60 -2
  213. package/lib/esm/helpers/validate.js +84 -1
  214. package/lib/esm/helpers/validateMidnightPublication.d.ts +10 -0
  215. package/lib/esm/helpers/validateMidnightPublication.js +16 -0
  216. package/lib/esm/helpers/validateMidnightTakeableOfferFields.d.ts +28 -0
  217. package/lib/esm/helpers/validateMidnightTakeableOfferFields.js +81 -0
  218. package/lib/esm/index.d.ts +2 -2
  219. package/lib/esm/index.js +1 -1
  220. package/lib/esm/midnight/errors.d.ts +2 -1
  221. package/lib/esm/midnight/errors.js +2 -1
  222. package/lib/esm/midnight/utils.d.ts +1 -1
  223. package/lib/esm/midnight/utils.js +1 -1
  224. package/lib/esm/transactionPlan/assemble.d.ts +24 -0
  225. package/lib/esm/transactionPlan/assemble.js +21 -0
  226. package/lib/esm/transactionPlan/blue/borrow.js +15 -65
  227. package/lib/esm/transactionPlan/blue/refinance.js +10 -12
  228. package/lib/esm/transactionPlan/blue/repay.js +11 -25
  229. package/lib/esm/transactionPlan/blue/repayWithdrawCollateral.js +50 -46
  230. package/lib/esm/transactionPlan/blue/stored.d.ts +26 -0
  231. package/lib/esm/transactionPlan/blue/stored.js +80 -0
  232. package/lib/esm/transactionPlan/blue/supply.js +7 -22
  233. package/lib/esm/transactionPlan/blue/supplyCollateral.d.ts +1 -1
  234. package/lib/esm/transactionPlan/blue/supplyCollateral.js +10 -15
  235. package/lib/esm/transactionPlan/blue/supplyCollateralBorrow.js +15 -65
  236. package/lib/esm/transactionPlan/blue/withdraw.d.ts +2 -3
  237. package/lib/esm/transactionPlan/blue/withdraw.js +70 -82
  238. package/lib/esm/transactionPlan/blue/withdrawBuyCallback.d.ts +101 -0
  239. package/lib/esm/transactionPlan/blue/withdrawBuyCallback.js +259 -0
  240. package/lib/esm/transactionPlan/blue/withdrawCollateral.d.ts +2 -3
  241. package/lib/esm/transactionPlan/blue/withdrawCollateral.js +32 -31
  242. package/lib/esm/transactionPlan/deposit.js +5 -8
  243. package/lib/esm/transactionPlan/error.d.ts +27 -0
  244. package/lib/esm/transactionPlan/error.js +28 -0
  245. package/lib/esm/transactionPlan/index.d.ts +40 -1
  246. package/lib/esm/transactionPlan/index.js +20 -1
  247. package/lib/esm/transactionPlan/intent.d.ts +1 -1
  248. package/lib/esm/transactionPlan/midnight/authorization.d.ts +15 -0
  249. package/lib/esm/transactionPlan/midnight/authorization.js +40 -0
  250. package/lib/esm/transactionPlan/midnight/cancelOffers.d.ts +80 -0
  251. package/lib/esm/transactionPlan/midnight/cancelOffers.js +120 -0
  252. package/lib/esm/transactionPlan/midnight/makeBorrow.d.ts +104 -0
  253. package/lib/esm/transactionPlan/midnight/makeBorrow.js +123 -0
  254. package/lib/esm/transactionPlan/midnight/makeLend.d.ts +140 -0
  255. package/lib/esm/transactionPlan/midnight/makeLend.js +172 -0
  256. package/lib/esm/transactionPlan/midnight/makeRepay.d.ts +118 -0
  257. package/lib/esm/transactionPlan/midnight/makeRepay.js +115 -0
  258. package/lib/esm/transactionPlan/midnight/makeWithdraw.d.ts +104 -0
  259. package/lib/esm/transactionPlan/midnight/makeWithdraw.js +123 -0
  260. package/lib/esm/transactionPlan/midnight/makerPublication.d.ts +55 -0
  261. package/lib/esm/transactionPlan/midnight/makerPublication.js +310 -0
  262. package/lib/esm/transactionPlan/midnight/market.d.ts +49 -0
  263. package/lib/esm/transactionPlan/midnight/market.js +112 -0
  264. package/lib/esm/transactionPlan/midnight/prepare.d.ts +244 -0
  265. package/lib/esm/transactionPlan/midnight/prepare.js +536 -0
  266. package/lib/esm/transactionPlan/midnight/publicationState.d.ts +24 -0
  267. package/lib/esm/transactionPlan/midnight/publicationState.js +47 -0
  268. package/lib/esm/transactionPlan/midnight/redeem.d.ts +102 -0
  269. package/lib/esm/transactionPlan/midnight/redeem.js +165 -0
  270. package/lib/esm/transactionPlan/midnight/reduceOnlySellFeasibility.d.ts +25 -0
  271. package/lib/esm/transactionPlan/midnight/reduceOnlySellFeasibility.js +47 -0
  272. package/lib/esm/transactionPlan/midnight/repayWithdrawCollateral.d.ts +162 -0
  273. package/lib/esm/transactionPlan/midnight/repayWithdrawCollateral.js +323 -0
  274. package/lib/esm/transactionPlan/midnight/supplyBlueMakeLend.d.ts +155 -0
  275. package/lib/esm/transactionPlan/midnight/supplyBlueMakeLend.js +196 -0
  276. package/lib/esm/transactionPlan/midnight/supplyCollateral.d.ts +96 -0
  277. package/lib/esm/transactionPlan/midnight/supplyCollateral.js +185 -0
  278. package/lib/esm/transactionPlan/midnight/supplyCollateralBatch.d.ts +112 -0
  279. package/lib/esm/transactionPlan/midnight/supplyCollateralBatch.js +216 -0
  280. package/lib/esm/transactionPlan/midnight/supplyCollateralMakeBorrow.d.ts +129 -0
  281. package/lib/esm/transactionPlan/midnight/supplyCollateralMakeBorrow.js +176 -0
  282. package/lib/esm/transactionPlan/midnight/supplyCollateralWithNative.d.ts +115 -0
  283. package/lib/esm/transactionPlan/midnight/supplyCollateralWithNative.js +254 -0
  284. package/lib/esm/transactionPlan/midnight/takeBorrow.d.ts +304 -0
  285. package/lib/esm/transactionPlan/midnight/takeBorrow.js +539 -0
  286. package/lib/esm/transactionPlan/midnight/takeLend.d.ts +99 -0
  287. package/lib/esm/transactionPlan/midnight/takeLend.js +258 -0
  288. package/lib/esm/transactionPlan/midnight/takeRepayWithdrawCollateral.d.ts +175 -0
  289. package/lib/esm/transactionPlan/midnight/takeRepayWithdrawCollateral.js +435 -0
  290. package/lib/esm/transactionPlan/midnight/takeWithdraw.d.ts +139 -0
  291. package/lib/esm/transactionPlan/midnight/takeWithdraw.js +236 -0
  292. package/lib/esm/transactionPlan/midnight/validation.d.ts +22 -0
  293. package/lib/esm/transactionPlan/midnight/validation.js +151 -0
  294. package/lib/esm/transactionPlan/midnight/withdrawCollateral.d.ts +130 -0
  295. package/lib/esm/transactionPlan/midnight/withdrawCollateral.js +223 -0
  296. package/lib/esm/transactionPlan/midnight/withdrawCollateralBatch.d.ts +142 -0
  297. package/lib/esm/transactionPlan/midnight/withdrawCollateralBatch.js +227 -0
  298. package/lib/esm/transactionPlan/permit.d.ts +15 -2
  299. package/lib/esm/transactionPlan/permit.js +25 -68
  300. package/lib/esm/transactionPlan/plan.d.ts +99 -15
  301. package/lib/esm/transactionPlan/plan.js +154 -27
  302. package/lib/esm/transactionPlan/redeem.js +5 -8
  303. package/lib/esm/transactionPlan/requirements.d.ts +7 -4
  304. package/lib/esm/transactionPlan/requirements.js +2 -2
  305. package/lib/esm/transactionPlan/serde.d.ts +13 -2
  306. package/lib/esm/transactionPlan/serde.js +49 -2
  307. package/lib/esm/transactionPlan/types.d.ts +151 -3
  308. package/lib/esm/transactionPlan/validateActions.d.ts +3 -1
  309. package/lib/esm/transactionPlan/validateActions.js +31 -3
  310. package/lib/esm/transactionPlan/validation.d.ts +1 -1
  311. package/lib/esm/transactionPlan/validation.js +38 -2
  312. package/lib/esm/transactionPlan/vaultBinding.d.ts +29 -0
  313. package/lib/esm/transactionPlan/vaultBinding.js +65 -0
  314. package/lib/esm/transactionPlan/vaultRequirements.d.ts +20 -0
  315. package/lib/esm/transactionPlan/vaultRequirements.js +34 -0
  316. package/lib/esm/transactionPlan/vaultv1/deposit.d.ts +1 -1
  317. package/lib/esm/transactionPlan/vaultv1/deposit.js +3 -14
  318. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.d.ts +2 -2
  319. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.js +12 -43
  320. package/lib/esm/transactionPlan/vaultv1/migrateToV2.d.ts +1 -1
  321. package/lib/esm/transactionPlan/vaultv1/migrateToV2.js +9 -21
  322. package/lib/esm/transactionPlan/vaultv1/redeem.js +2 -13
  323. package/lib/esm/transactionPlan/vaultv1/withdraw.d.ts +1 -1
  324. package/lib/esm/transactionPlan/vaultv1/withdraw.js +3 -14
  325. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +1 -1
  326. package/lib/esm/transactionPlan/vaultv2/deposit.js +3 -14
  327. package/lib/esm/transactionPlan/vaultv2/forceRedeem.d.ts +1 -1
  328. package/lib/esm/transactionPlan/vaultv2/forceRedeem.js +5 -8
  329. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.d.ts +2 -2
  330. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.js +15 -45
  331. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.d.ts +2 -2
  332. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.js +12 -43
  333. package/lib/esm/transactionPlan/vaultv2/redeem.d.ts +1 -1
  334. package/lib/esm/transactionPlan/vaultv2/redeem.js +3 -14
  335. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +1 -1
  336. package/lib/esm/transactionPlan/vaultv2/withdraw.js +3 -14
  337. package/lib/esm/transactionPlan/withdraw.js +5 -8
  338. package/lib/esm/types/error.d.ts +4 -1
  339. package/lib/esm/types/error.js +5 -2
  340. package/lib/esm/utils.d.ts +2 -2
  341. package/lib/esm/utils.js +2 -2
  342. package/lib/esm/version.d.ts +1 -1
  343. package/lib/esm/version.js +1 -1
  344. package/package.json +7 -7
@@ -1,15 +1,16 @@
1
- import { AccrualPosition, MarketParams, } from "@morpho-org/blue-sdk";
2
- import { deepFreeze } from "@morpho-org/morpho-ts";
1
+ import { AccrualPosition, MarketUtils, } from "@morpho-org/blue-sdk";
3
2
  import { zeroAddress } from "viem";
4
3
  import { getBlueBundlesV1PenaltyAssets } from "../../actions/blue/common.js";
5
4
  import { blueWithdraw } from "../../actions/blue/withdraw.js";
6
5
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
7
6
  import { validateVaultV2BlueReallocations, validateWithdrawAmount, validateWithdrawShares, } from "../../helpers/validate.js";
8
- import { InputExceedsMaxError, MissingAccrualPositionError, } from "../../types/index.js";
9
- import { IncompleteTransactionPlanError, InvalidTransactionPlanError, TransactionPlanSignatureMismatchError, } from "../error.js";
7
+ import { InputExceedsMaxError, InvalidVaultV2BlueReallocationShapeError, MissingAccrualPositionError, } from "../../types/index.js";
8
+ import { freezePlan, planHeader } from "../assemble.js";
9
+ import { IncompleteTransactionPlanError, TransactionPlanSignatureMismatchError, } from "../error.js";
10
10
  import { getPlanObject, validatePlanField, validatePlanFields, } from "../validation.js";
11
11
  import { validateMorphoAuthorizationRequest } from "./authorization.js";
12
12
  import { prepareBlue, } from "./prepare.js";
13
+ import { BUNDLES_COMMON_FIELDS, validateStoredBlueMarketParams, validateStoredReallocations, } from "./stored.js";
13
14
  /**
14
15
  * Prepares a BlueBundlesV1 withdrawal with only Morpho authorization prerequisites, never token approvals.
15
16
  * The caller supplies market and position snapshots; the SDK reads authorization but never signs.
@@ -42,7 +43,7 @@ import { prepareBlue, } from "./prepare.js";
42
43
  * @param params.supportSignature - Optional Morpho authorization signature preference; defaults to `false`, selecting a direct authorization transaction when needed. Neither mode requests a token allowance or Permit2 signature.
43
44
  * @param params.now - Optional reference timestamp in seconds, normally the latest block timestamp; defaults to the device clock.
44
45
  * @param params.expiresAt - Optional Unix expiry in safe-integer seconds, later than `now`; defaults to `now + 2h`.
45
- * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to every built transaction; omitted by default.
46
+ * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to the action transaction's calldata, not to approval or authorization steps; omitted by default.
46
47
  * @param params.deployless - Optional shared intent field; unused because withdrawal reads no token metadata.
47
48
  * @returns A deep-frozen, data-only `{ version, chainId, account, expiresAt, steps, signatureRequests, calldataOrigin? }` plan with a withdrawal step. Direct Morpho authorization is a preceding step; signed authorization is consumed inline by the withdrawal. Attach signatures before building.
48
49
  * @throws {InvalidBigIntInputError} when a supplied maxPenalty is not a bigint.
@@ -73,7 +74,6 @@ import { prepareBlue, } from "./prepare.js";
73
74
  * @throws {WithdrawSharesExceedSupplyError} when `shares` exceeds the position's supply shares.
74
75
  * @throws {MissingContractCodeError} when registered BlueBundlesV1 or Blue has no deployed code.
75
76
  * @throws {viem.BaseError} when a chain, bytecode, authorization or nonce RPC read fails, or ABI encoding rejects malformed input.
76
- * @throws {UnexpectedRequirementSignatureError} when an authorization requirement returns a nonce that is not a bigint.
77
77
  * @throws {TransactionPlanSignatureMismatchError} when the authorization requirement does not match the prepared account, chain, nonce or deadline.
78
78
  * @example
79
79
  * ```ts
@@ -93,33 +93,65 @@ import { prepareBlue, } from "./prepare.js";
93
93
  * positionData: { chainId: mainnet.id, position },
94
94
  * now: (await client.getBlock()).timestamp,
95
95
  * });
96
- * // plan: { version: 1, chainId, account, expiresAt, steps, signatureRequests }
96
+ * // plan: { version: 2, chainId, account, expiresAt, steps, signatureRequests }
97
97
  * // Sign any pending Morpho authorization request, then build and submit each step in order.
98
98
  * ```
99
99
  * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
100
100
  */
101
101
  export async function prepareBlueWithdraw(client, params) {
102
- const { maxPenalty } = params;
103
- await validateClientChainId(client, params.chainId);
102
+ const { maxPenalty, chainId, account } = params;
103
+ const supplied = params.reallocations ?? [];
104
+ let reallocations;
105
+ try {
106
+ reallocations = structuredClone(Array.isArray(supplied)
107
+ ? supplied.map((entry) => {
108
+ if (entry === null ||
109
+ typeof entry !== "object" ||
110
+ "withdrawals" in entry ||
111
+ "fee" in entry) {
112
+ return entry;
113
+ }
114
+ const { vault, from, to, assets, penalty } = entry;
115
+ return { vault, from, to, assets, penalty };
116
+ })
117
+ : supplied);
118
+ }
119
+ catch (cause) {
120
+ throw new InvalidVaultV2BlueReallocationShapeError({ cause });
121
+ }
122
+ await validateClientChainId(client, chainId);
104
123
  const { positionData: snapshot } = params;
105
124
  if (snapshot == null) {
106
125
  throw new MissingAccrualPositionError(params.marketId);
107
126
  }
108
127
  const withdrawals = [];
109
- const { intent: resolvedIntent, steps, signatureRequests, } = await prepareBlue({ client, params }, (intent) => {
128
+ const captured = {
129
+ chainId,
130
+ account,
131
+ marketId: params.marketId,
132
+ marketData: params.marketData,
133
+ positionData: snapshot,
134
+ now: params.now,
135
+ expiresAt: params.expiresAt,
136
+ supportSignature: params.supportSignature,
137
+ referralFee: params.referralFee,
138
+ calldataOrigin: params.calldataOrigin,
139
+ deployless: params.deployless,
140
+ };
141
+ const { intent: resolvedIntent, steps, signatureRequests, } = await prepareBlue({ client, params: captured }, (intent) => {
110
142
  const inputs = {
111
- chainId: params.chainId,
112
- account: params.account,
143
+ chainId,
144
+ account,
113
145
  marketParams: {
114
- loanToken: params.marketData.market.params.loanToken,
115
- collateralToken: params.marketData.market.params.collateralToken,
116
- oracle: params.marketData.market.params.oracle,
117
- irm: params.marketData.market.params.irm,
118
- lltv: params.marketData.market.params.lltv,
146
+ loanToken: captured.marketData.market.params.loanToken,
147
+ collateralToken: captured.marketData.market.params.collateralToken,
148
+ oracle: captured.marketData.market.params.oracle,
149
+ irm: captured.marketData.market.params.irm,
150
+ lltv: captured.marketData.market.params.lltv,
119
151
  },
120
152
  withdrawAssets: "assets" in params ? (params.assets ?? 0n) : 0n,
121
153
  withdrawShares: "shares" in params ? (params.shares ?? 0n) : 0n,
122
- reallocations: params.reallocations ?? [],
154
+ reallocations,
123
155
  ...(maxPenalty !== undefined && { maxPenalty }),
124
156
  deadline: intent.deadline,
125
157
  referralFeePct: intent.referralFeePct,
@@ -151,7 +183,7 @@ export async function prepareBlueWithdraw(client, params) {
151
183
  positionData,
152
184
  withdrawShares: inputs.withdrawShares,
153
185
  withdrawAssets: inputs.withdrawAssets,
154
- marketId: params.marketId,
186
+ marketId: captured.marketId,
155
187
  });
156
188
  withdrawals.push({
157
189
  id: "blueWithdraw",
@@ -160,14 +192,8 @@ export async function prepareBlueWithdraw(client, params) {
160
192
  });
161
193
  return { id: "blueWithdraw", needsAuthorization: true };
162
194
  });
163
- return deepFreeze(structuredClone({
164
- version: 2,
165
- chainId: params.chainId,
166
- account: params.account,
167
- expiresAt: resolvedIntent.expiresAt,
168
- ...(resolvedIntent.calldataOrigin && {
169
- calldataOrigin: resolvedIntent.calldataOrigin,
170
- }),
195
+ return freezePlan({
196
+ ...planHeader({ chainId, account }, resolvedIntent),
171
197
  steps: [
172
198
  ...steps,
173
199
  ...withdrawals.map((step) => {
@@ -190,7 +216,7 @@ export async function prepareBlueWithdraw(client, params) {
190
216
  }),
191
217
  ],
192
218
  signatureRequests,
193
- }));
219
+ }, { detach: true });
194
220
  }
195
221
  /** @internal Binds an inline authorization to the withdrawal that consumes it. */
196
222
  export function validateBlueWithdrawAuthorizationRequest(request, action) {
@@ -244,7 +270,7 @@ export function buildBlueWithdraw(action, requests = []) {
244
270
  },
245
271
  };
246
272
  }
247
- const targetMarketParams = new MarketParams(marketParams);
273
+ const targetMarketParams = toEncoderMarketParams(marketParams);
248
274
  // Reject malformed entries with typed errors before reading their source fields.
249
275
  validateVaultV2BlueReallocations(args.reallocations, {
250
276
  targetMarketId: targetMarketParams.id,
@@ -255,7 +281,7 @@ export function buildBlueWithdraw(action, requests = []) {
255
281
  from: entry.from.type === "market"
256
282
  ? {
257
283
  ...entry.from,
258
- marketParams: new MarketParams(entry.from.marketParams),
284
+ marketParams: toEncoderMarketParams(entry.from.marketParams),
259
285
  }
260
286
  : entry.from,
261
287
  }));
@@ -269,6 +295,15 @@ export function buildBlueWithdraw(action, requests = []) {
269
295
  },
270
296
  });
271
297
  }
298
+ function toEncoderMarketParams(marketParams) {
299
+ const { loanToken, collateralToken, oracle, irm, lltv } = marketParams;
300
+ const tuple = { loanToken, collateralToken, oracle, irm, lltv };
301
+ return {
302
+ ...tuple,
303
+ id: MarketUtils.getMarketId(tuple),
304
+ liquidationIncentiveFactor: MarketUtils.getLiquidationIncentiveFactor(tuple),
305
+ };
306
+ }
272
307
  /** @internal Validates stored withdrawal scalars and allocator input shapes. */
273
308
  export function validateBlueWithdrawPlanAction(action, path) {
274
309
  const inputs = getPlanObject(action.inputs, `${path}.inputs`);
@@ -294,60 +329,13 @@ export function validateBlueWithdrawPlanAction(action, path) {
294
329
  fields: {
295
330
  withdrawAssets: "uint256 bigint",
296
331
  withdrawShares: "uint256 bigint",
297
- deadline: "uint256 bigint",
298
- referralFeePct: "uint256 bigint",
299
- referralFeeRecipient: "address",
332
+ ...BUNDLES_COMMON_FIELDS,
300
333
  reallocations: "array",
301
334
  },
302
335
  });
303
- validatePlanFields(getPlanObject(inputs.marketParams, `${path}.inputs.marketParams`), {
304
- path: `${path}.inputs.marketParams`,
305
- fields: {
306
- loanToken: "address",
307
- collateralToken: "address",
308
- oracle: "address",
309
- irm: "address",
310
- lltv: "uint256 bigint",
311
- },
336
+ validateStoredBlueMarketParams(inputs.marketParams, `${path}.inputs.marketParams`);
337
+ validateStoredReallocations(inputs.reallocations, {
338
+ path: `${path}.inputs.reallocations`,
339
+ marketParams: validateStoredBlueMarketParams,
312
340
  });
313
- for (const [index, value] of inputs.reallocations.entries()) {
314
- const entryPath = `${path}.inputs.reallocations[${index}]`;
315
- const entry = getPlanObject(value, entryPath);
316
- validatePlanFields(entry, {
317
- path: entryPath,
318
- fields: {
319
- vault: "address",
320
- assets: "uint256 bigint",
321
- penalty: "uint256 bigint",
322
- },
323
- });
324
- validatePlanFields(getPlanObject(entry.to, `${entryPath}.to`), {
325
- path: `${entryPath}.to`,
326
- fields: { adapter: "address" },
327
- });
328
- const from = getPlanObject(entry.from, `${entryPath}.from`);
329
- if (from.type === "idle") {
330
- continue;
331
- }
332
- if (from.type !== "market") {
333
- throw new InvalidTransactionPlanError({
334
- path: `${entryPath}.from.type`,
335
- reason: "expected market or idle",
336
- });
337
- }
338
- validatePlanFields(from, {
339
- path: `${entryPath}.from`,
340
- fields: { adapter: "address" },
341
- });
342
- validatePlanFields(getPlanObject(from.marketParams, `${entryPath}.from.marketParams`), {
343
- path: `${entryPath}.from.marketParams`,
344
- fields: {
345
- loanToken: "address",
346
- collateralToken: "address",
347
- oracle: "address",
348
- irm: "address",
349
- lltv: "uint256 bigint",
350
- },
351
- });
352
- }
353
341
  }
@@ -0,0 +1,101 @@
1
+ import { type MarketId } from "@morpho-org/blue-sdk";
2
+ import { type Address, type Client } from "viem";
3
+ import { type BlueWithdrawBuyCallbackAction, type ReferenceTimestampParams, type Transaction } from "../../types/index.js";
4
+ import { type IntentParams } from "../intent.js";
5
+ import type { Action, TransactionPlan } from "../types.js";
6
+ import { type BlueMarketSnapshot, type BluePositionSnapshot } from "./prepare.js";
7
+ /**
8
+ * Caller intent and caller-fetched snapshots for withdrawing a BlueBuyCallback's whole supply
9
+ * position to its owner. The position belongs to `callbackAddress`, not to `account`.
10
+ * @example
11
+ * ```ts
12
+ * import type { BlueWithdrawBuyCallbackPlanParams } from "@morpho-org/morpho-sdk";
13
+ * import type { Address } from "viem";
14
+ * declare const callbackAddress: Address;
15
+ * const withdrawal = { callbackAddress, expiresAt: 1_900_000_000 } satisfies Pick<
16
+ * BlueWithdrawBuyCallbackPlanParams,
17
+ * "callbackAddress" | "expiresAt"
18
+ * >;
19
+ * ```
20
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
21
+ */
22
+ export interface BlueWithdrawBuyCallbackPlanParams extends Pick<IntentParams, "chainId" | "account" | "expiresAt" | "calldataOrigin">, ReferenceTimestampParams {
23
+ readonly marketId: MarketId;
24
+ readonly marketData: BlueMarketSnapshot;
25
+ /** BlueBuyCallback whose supply position is withdrawn; `account` must be its owner. */
26
+ readonly callbackAddress: Address;
27
+ /** Caller-fetched position of `callbackAddress`; every supply share in it is withdrawn. */
28
+ readonly positionData: BluePositionSnapshot;
29
+ }
30
+ /**
31
+ * Prepares a direct Morpho Blue withdrawal of a BlueBuyCallback's whole supply position to its owner.
32
+ * The call is `withdraw(marketParams, 0, shares, callbackAddress, account)` on Morpho Blue, not
33
+ * BlueBundlesV1: the callback authorizes its owner on Blue at construction, so the plan has no
34
+ * approval, authorization step or signature request. Preparation reads the chain and rejects a
35
+ * callback the registered factory did not create, another owner, or a revoked Blue authorization.
36
+ * The plan carries no referral fee, and `expiresAt` is plan metadata, not an onchain deadline.
37
+ * @param client - Viem client on the requested chain.
38
+ * @param params.chainId - Chain containing Morpho Blue and the registered `midnightBlueBuyCallbackFactory`.
39
+ * @param params.account - Non-zero callback owner that sends the transaction and receives the loan assets.
40
+ * @param params.marketId - Market ID matching both snapshots and the market tuple.
41
+ * @param params.marketData.chainId - Chain on which the market snapshot was fetched; must equal `chainId`.
42
+ * @param params.marketData.market - Caller-fetched `Market` snapshot used to fix the market tuple; its state must equal the position snapshot's market. Never stored in the plan.
43
+ * @param params.callbackAddress - BlueBuyCallback whose supply position is withdrawn.
44
+ * @param params.positionData.chainId - Position snapshot's chain; must equal `chainId`.
45
+ * @param params.positionData.position - Caller-fetched `AccrualPosition` of `callbackAddress` on `marketId`; all its supply shares are withdrawn and their assets must not exceed that market's liquidity.
46
+ * @param params.now - Optional reference timestamp in seconds, normally the latest block timestamp; defaults to the device clock.
47
+ * @param params.expiresAt - Optional Unix expiry in safe-integer seconds, later than `now`; defaults to `now + 2h`. Plan metadata only.
48
+ * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to the withdrawal calldata; omitted by default.
49
+ * @returns A deep-frozen, data-only `{ version, chainId, account, expiresAt, steps, signatureRequests, calldataOrigin? }` plan with one `blueWithdrawBuyCallback` step and no signature requests.
50
+ * @throws {BlueSnapshotChainMismatchError} when a market or position snapshot's chain differs from `chainId`.
51
+ * @throws {MarketIdMismatchError} when a snapshot's ID differs from `marketId` or does not hash from its market tuple.
52
+ * @throws {BlueSnapshotStateMismatchError} when the market snapshot's state differs from the position snapshot's market.
53
+ * @throws {MissingAccrualPositionError} when no position snapshot is provided.
54
+ * @throws {AccrualPositionUserMismatchError} when the position belongs to another address than `callbackAddress`.
55
+ * @throws {ZeroAccountError} when `account` is the zero address.
56
+ * @throws {InvalidTransactionPlanError} when `account` or `callbackAddress` is not a checksum-valid address, or `calldataOrigin` exceeds 1 MiB.
57
+ * @throws {NonIntegerInputError} when `expiresAt` is not a safe integer.
58
+ * @throws {NonPositiveInputError} when `expiresAt` is not positive.
59
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before `now`.
60
+ * @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty, malformed or has an odd number of hex digits.
61
+ * @throws {EmptyBlueSupplyPositionError} when the callback holds no supply shares.
62
+ * @throws {InsufficientBlueLiquidityError} when the position's supply assets exceed the snapshot market's liquidity.
63
+ * @throws {InputExceedsMaxError} when the supply shares exceed `uint256`.
64
+ * @throws {UnsupportedChainIdError} when `chainId` is absent from the registry.
65
+ * @throws {UnknownAddressError} when Morpho Blue or `midnightBlueBuyCallbackFactory` is not registered on `chainId`.
66
+ * @throws {ChainIdMismatchError} when the client declares another chain (checked before any snapshot) or its transport serves one.
67
+ * @throws {MissingContractCodeError} when Morpho Blue or the factory has no deployed code.
68
+ * @throws {NotBlueBuyCallbackError} when the factory did not create `callbackAddress`.
69
+ * @throws {BlueBuyCallbackOwnerMismatchError} when the callback's `OWNER()` is not `account`.
70
+ * @throws {BlueBuyCallbackUnauthorizedError} when Morpho Blue does not authorize `account` for the callback.
71
+ * @throws {viem.BaseError} when a chain, bytecode, factory, owner or authorization read fails.
72
+ * @example
73
+ * ```ts
74
+ * import { markets } from "@morpho-org/morpho-test";
75
+ * import { buildTransactions, prepareBlueWithdrawBuyCallback } from "@morpho-org/morpho-sdk";
76
+ * import { fetchBlueAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
77
+ * import { createPublicClient, type Address, http } from "viem";
78
+ * import { mainnet } from "viem/chains";
79
+ *
80
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
81
+ * declare const account: Address; // Owner of the BlueBuyCallback.
82
+ * declare const callbackAddress: Address; // BlueBuyCallback created by the registered factory.
83
+ * const position = await fetchBlueAccrualPosition(callbackAddress, markets[mainnet.id].usdc_wbtc.id, client);
84
+ * const plan = await prepareBlueWithdrawBuyCallback(client, {
85
+ * chainId: mainnet.id, account, callbackAddress, marketId: position.market.id,
86
+ * marketData: { chainId: mainnet.id, market: position.market },
87
+ * positionData: { chainId: mainnet.id, position },
88
+ * now: (await client.getBlock()).timestamp,
89
+ * });
90
+ * const [transaction] = buildTransactions(plan);
91
+ * // Submit transaction from account; it calls Morpho Blue directly.
92
+ * ```
93
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
94
+ */
95
+ export declare function prepareBlueWithdrawBuyCallback(client: Client, params: BlueWithdrawBuyCallbackPlanParams): Promise<TransactionPlan>;
96
+ /** @internal Encodes the stored callback withdrawal through the same action as the entity handle. */
97
+ export declare function buildBlueWithdrawBuyCallback(action: Extract<Action, {
98
+ type: "blueWithdrawBuyCallback";
99
+ }>): Readonly<Transaction<BlueWithdrawBuyCallbackAction>>;
100
+ /** @internal Validates the stored callback withdrawal's structural inputs. */
101
+ export declare function validateBlueWithdrawBuyCallbackPlanAction(action: Record<string, unknown>, path: string): void;
@@ -0,0 +1,259 @@
1
+ import { MarketUtils } from "@morpho-org/blue-sdk";
2
+ import { deepFreeze, getChainAddress, isHexEqual, Time, } from "@morpho-org/morpho-ts";
3
+ import { isAddressEqual } from "viem";
4
+ import { getBytecode, readContract } from "viem/actions";
5
+ import { blueAbi, midnightBlueBuyCallbackAbi, midnightBlueBuyCallbackFactoryAbi, } from "../../abis.js";
6
+ import { parseBlueWithdrawBuyCallback } from "../../actions/blue/withdrawBuyCallback.internal.js";
7
+ import { blueWithdrawBuyCallback } from "../../actions/blue/withdrawBuyCallback.js";
8
+ import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
+ import { validateChainId } from "../../helpers/index.js";
10
+ import { validateMarketParamsId } from "../../helpers/validate.js";
11
+ import { AccrualPositionUserMismatchError, BlueBuyCallbackOwnerMismatchError, BlueBuyCallbackUnauthorizedError, EmptyBlueSupplyPositionError, InsufficientBlueLiquidityError, MarketIdMismatchError, MissingAccrualPositionError, MissingContractCodeError, NotBlueBuyCallbackError, } from "../../types/index.js";
12
+ import { BlueSnapshotChainMismatchError, BlueSnapshotStateMismatchError, } from "../error.js";
13
+ import { resolveIntent } from "../intent.js";
14
+ import { getPlanObject, validatePlanField, validatePlanFields, } from "../validation.js";
15
+ import { validateBlueMarketSnapshot, } from "./prepare.js";
16
+ const MARKET_STATE_FIELDS = [
17
+ "totalSupplyAssets",
18
+ "totalSupplyShares",
19
+ "totalBorrowAssets",
20
+ "totalBorrowShares",
21
+ "lastUpdate",
22
+ "fee",
23
+ "price",
24
+ "rateAtTarget",
25
+ ];
26
+ /**
27
+ * Prepares a direct Morpho Blue withdrawal of a BlueBuyCallback's whole supply position to its owner.
28
+ * The call is `withdraw(marketParams, 0, shares, callbackAddress, account)` on Morpho Blue, not
29
+ * BlueBundlesV1: the callback authorizes its owner on Blue at construction, so the plan has no
30
+ * approval, authorization step or signature request. Preparation reads the chain and rejects a
31
+ * callback the registered factory did not create, another owner, or a revoked Blue authorization.
32
+ * The plan carries no referral fee, and `expiresAt` is plan metadata, not an onchain deadline.
33
+ * @param client - Viem client on the requested chain.
34
+ * @param params.chainId - Chain containing Morpho Blue and the registered `midnightBlueBuyCallbackFactory`.
35
+ * @param params.account - Non-zero callback owner that sends the transaction and receives the loan assets.
36
+ * @param params.marketId - Market ID matching both snapshots and the market tuple.
37
+ * @param params.marketData.chainId - Chain on which the market snapshot was fetched; must equal `chainId`.
38
+ * @param params.marketData.market - Caller-fetched `Market` snapshot used to fix the market tuple; its state must equal the position snapshot's market. Never stored in the plan.
39
+ * @param params.callbackAddress - BlueBuyCallback whose supply position is withdrawn.
40
+ * @param params.positionData.chainId - Position snapshot's chain; must equal `chainId`.
41
+ * @param params.positionData.position - Caller-fetched `AccrualPosition` of `callbackAddress` on `marketId`; all its supply shares are withdrawn and their assets must not exceed that market's liquidity.
42
+ * @param params.now - Optional reference timestamp in seconds, normally the latest block timestamp; defaults to the device clock.
43
+ * @param params.expiresAt - Optional Unix expiry in safe-integer seconds, later than `now`; defaults to `now + 2h`. Plan metadata only.
44
+ * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to the withdrawal calldata; omitted by default.
45
+ * @returns A deep-frozen, data-only `{ version, chainId, account, expiresAt, steps, signatureRequests, calldataOrigin? }` plan with one `blueWithdrawBuyCallback` step and no signature requests.
46
+ * @throws {BlueSnapshotChainMismatchError} when a market or position snapshot's chain differs from `chainId`.
47
+ * @throws {MarketIdMismatchError} when a snapshot's ID differs from `marketId` or does not hash from its market tuple.
48
+ * @throws {BlueSnapshotStateMismatchError} when the market snapshot's state differs from the position snapshot's market.
49
+ * @throws {MissingAccrualPositionError} when no position snapshot is provided.
50
+ * @throws {AccrualPositionUserMismatchError} when the position belongs to another address than `callbackAddress`.
51
+ * @throws {ZeroAccountError} when `account` is the zero address.
52
+ * @throws {InvalidTransactionPlanError} when `account` or `callbackAddress` is not a checksum-valid address, or `calldataOrigin` exceeds 1 MiB.
53
+ * @throws {NonIntegerInputError} when `expiresAt` is not a safe integer.
54
+ * @throws {NonPositiveInputError} when `expiresAt` is not positive.
55
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before `now`.
56
+ * @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty, malformed or has an odd number of hex digits.
57
+ * @throws {EmptyBlueSupplyPositionError} when the callback holds no supply shares.
58
+ * @throws {InsufficientBlueLiquidityError} when the position's supply assets exceed the snapshot market's liquidity.
59
+ * @throws {InputExceedsMaxError} when the supply shares exceed `uint256`.
60
+ * @throws {UnsupportedChainIdError} when `chainId` is absent from the registry.
61
+ * @throws {UnknownAddressError} when Morpho Blue or `midnightBlueBuyCallbackFactory` is not registered on `chainId`.
62
+ * @throws {ChainIdMismatchError} when the client declares another chain (checked before any snapshot) or its transport serves one.
63
+ * @throws {MissingContractCodeError} when Morpho Blue or the factory has no deployed code.
64
+ * @throws {NotBlueBuyCallbackError} when the factory did not create `callbackAddress`.
65
+ * @throws {BlueBuyCallbackOwnerMismatchError} when the callback's `OWNER()` is not `account`.
66
+ * @throws {BlueBuyCallbackUnauthorizedError} when Morpho Blue does not authorize `account` for the callback.
67
+ * @throws {viem.BaseError} when a chain, bytecode, factory, owner or authorization read fails.
68
+ * @example
69
+ * ```ts
70
+ * import { markets } from "@morpho-org/morpho-test";
71
+ * import { buildTransactions, prepareBlueWithdrawBuyCallback } from "@morpho-org/morpho-sdk";
72
+ * import { fetchBlueAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
73
+ * import { createPublicClient, type Address, http } from "viem";
74
+ * import { mainnet } from "viem/chains";
75
+ *
76
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
77
+ * declare const account: Address; // Owner of the BlueBuyCallback.
78
+ * declare const callbackAddress: Address; // BlueBuyCallback created by the registered factory.
79
+ * const position = await fetchBlueAccrualPosition(callbackAddress, markets[mainnet.id].usdc_wbtc.id, client);
80
+ * const plan = await prepareBlueWithdrawBuyCallback(client, {
81
+ * chainId: mainnet.id, account, callbackAddress, marketId: position.market.id,
82
+ * marketData: { chainId: mainnet.id, market: position.market },
83
+ * positionData: { chainId: mainnet.id, position },
84
+ * now: (await client.getBlock()).timestamp,
85
+ * });
86
+ * const [transaction] = buildTransactions(plan);
87
+ * // Submit transaction from account; it calls Morpho Blue directly.
88
+ * ```
89
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
90
+ */
91
+ export async function prepareBlueWithdrawBuyCallback(client, params) {
92
+ const { chainId, account, callbackAddress, marketId, marketData } = params;
93
+ const snapshot = params.positionData;
94
+ // Reject a client declaring another chain first, as the entity does.
95
+ validateChainId(client.chain?.id, chainId);
96
+ validatePlanField(callbackAddress, {
97
+ path: "$.callbackAddress",
98
+ type: "address",
99
+ });
100
+ // Reject mismatched snapshots before deriving the withdrawal or reading chain state.
101
+ validateBlueMarketSnapshot(marketData, { chainId, marketId });
102
+ if (snapshot == null) {
103
+ throw new MissingAccrualPositionError(marketId);
104
+ }
105
+ if (snapshot.chainId !== chainId) {
106
+ throw new BlueSnapshotChainMismatchError(snapshot.chainId, chainId);
107
+ }
108
+ const { position } = snapshot;
109
+ if (!isHexEqual(position.marketId, marketId)) {
110
+ throw new MarketIdMismatchError(position.marketId, marketId);
111
+ }
112
+ if (!isHexEqual(position.market.id, marketId)) {
113
+ throw new MarketIdMismatchError(position.market.id, marketId);
114
+ }
115
+ validateMarketParamsId(position.market.params);
116
+ if (!isAddressEqual(position.user, callbackAddress)) {
117
+ throw new AccrualPositionUserMismatchError(position.user, callbackAddress);
118
+ }
119
+ // Bind the withdrawal to one market state: the position's market bounds the liquidity check.
120
+ for (const field of MARKET_STATE_FIELDS) {
121
+ if (position.market[field] !== marketData.market[field]) {
122
+ throw new BlueSnapshotStateMismatchError({
123
+ field,
124
+ positionValue: position.market[field],
125
+ marketValue: marketData.market[field],
126
+ });
127
+ }
128
+ }
129
+ const intent = resolveIntent(params, params.now ?? Time.timestamp());
130
+ const market = marketData.market.id;
131
+ const shares = position.supplyShares;
132
+ if (shares === 0n) {
133
+ throw new EmptyBlueSupplyPositionError({ market, user: callbackAddress });
134
+ }
135
+ const assets = position.supplyAssets;
136
+ const liquidity = position.market.liquidity;
137
+ if (assets > liquidity) {
138
+ throw new InsufficientBlueLiquidityError({ market, assets, liquidity });
139
+ }
140
+ const { loanToken, collateralToken, oracle, irm, lltv } = marketData.market.params;
141
+ // Validate shares, the market tuple and the Blue registration before any RPC read.
142
+ parseBlueWithdrawBuyCallback({
143
+ market: { chainId, marketParams: marketData.market.params },
144
+ args: { callbackAddress, userAddress: account, shares },
145
+ });
146
+ const blue = getChainAddress(chainId, "blue");
147
+ const factory = getChainAddress(chainId, "midnightBlueBuyCallbackFactory");
148
+ await validateClientChainId(client, chainId);
149
+ const targets = [
150
+ { role: "blue", address: blue },
151
+ { role: "midnightBlueBuyCallbackFactory", address: factory },
152
+ ];
153
+ // Start every read, then consume them in target order so a stalled or failed
154
+ // later read cannot hide Blue's missing code, as `assertRegistryTargetsHaveCode` does.
155
+ const reads = targets.map(({ address }) => {
156
+ const read = getBytecode(client, { address });
157
+ read.catch(() => undefined);
158
+ return read;
159
+ });
160
+ for (const [index, { role, address }] of targets.entries()) {
161
+ const bytecode = await reads[index];
162
+ if (bytecode === undefined || bytecode === "0x") {
163
+ throw new MissingContractCodeError(address, chainId, role);
164
+ }
165
+ }
166
+ // Check the factory first: OWNER() on an arbitrary address can revert or lie.
167
+ const isBlueBuyCallback = await readContract(client, {
168
+ address: factory,
169
+ abi: midnightBlueBuyCallbackFactoryAbi,
170
+ functionName: "isBlueBuyCallback",
171
+ args: [callbackAddress],
172
+ });
173
+ if (!isBlueBuyCallback) {
174
+ throw new NotBlueBuyCallbackError(callbackAddress);
175
+ }
176
+ const [owner, isAuthorized] = await Promise.all([
177
+ readContract(client, {
178
+ address: callbackAddress,
179
+ abi: midnightBlueBuyCallbackAbi,
180
+ functionName: "OWNER",
181
+ }),
182
+ readContract(client, {
183
+ address: blue,
184
+ abi: blueAbi,
185
+ functionName: "isAuthorized",
186
+ args: [callbackAddress, account],
187
+ }),
188
+ ]);
189
+ if (!isAddressEqual(owner, account)) {
190
+ throw new BlueBuyCallbackOwnerMismatchError({
191
+ callback: callbackAddress,
192
+ owner,
193
+ userAddress: account,
194
+ });
195
+ }
196
+ if (!isAuthorized) {
197
+ throw new BlueBuyCallbackUnauthorizedError({
198
+ callback: callbackAddress,
199
+ userAddress: account,
200
+ });
201
+ }
202
+ return deepFreeze({
203
+ version: 2,
204
+ chainId,
205
+ account,
206
+ expiresAt: intent.expiresAt,
207
+ ...(intent.calldataOrigin && { calldataOrigin: intent.calldataOrigin }),
208
+ steps: [
209
+ {
210
+ id: "blueWithdrawBuyCallback",
211
+ label: "Withdraw BlueBuyCallback supply from Blue",
212
+ action: {
213
+ type: "blueWithdrawBuyCallback",
214
+ inputs: {
215
+ chainId,
216
+ account,
217
+ marketParams: { loanToken, collateralToken, oracle, irm, lltv },
218
+ callbackAddress,
219
+ shares,
220
+ },
221
+ },
222
+ },
223
+ ],
224
+ signatureRequests: [],
225
+ });
226
+ }
227
+ /** @internal Encodes the stored callback withdrawal through the same action as the entity handle. */
228
+ export function buildBlueWithdrawBuyCallback(action) {
229
+ const { chainId, account, marketParams, callbackAddress, shares } = action.inputs;
230
+ return blueWithdrawBuyCallback({
231
+ market: {
232
+ chainId,
233
+ marketParams: {
234
+ ...marketParams,
235
+ id: MarketUtils.getMarketId(marketParams),
236
+ liquidationIncentiveFactor: MarketUtils.getLiquidationIncentiveFactor(marketParams),
237
+ },
238
+ },
239
+ args: { callbackAddress, userAddress: account, shares },
240
+ });
241
+ }
242
+ /** @internal Validates the stored callback withdrawal's structural inputs. */
243
+ export function validateBlueWithdrawBuyCallbackPlanAction(action, path) {
244
+ const inputs = getPlanObject(action.inputs, `${path}.inputs`);
245
+ validatePlanFields(inputs, {
246
+ path: `${path}.inputs`,
247
+ fields: { callbackAddress: "address", shares: "uint256 bigint" },
248
+ });
249
+ validatePlanFields(getPlanObject(inputs.marketParams, `${path}.inputs.marketParams`), {
250
+ path: `${path}.inputs.marketParams`,
251
+ fields: {
252
+ loanToken: "address",
253
+ collateralToken: "address",
254
+ oracle: "address",
255
+ irm: "address",
256
+ lltv: "uint256 bigint",
257
+ },
258
+ });
259
+ }
@@ -48,7 +48,7 @@ export interface BlueWithdrawCollateralPlanParams extends IntentParams, Referenc
48
48
  * @param params.supportSignature - Optional Morpho authorization signature preference, defaulting to `false`; otherwise prepares a direct authorization transaction when needed.
49
49
  * @param params.now - Optional reference timestamp in Unix seconds, normally the latest block timestamp; defaults to the device clock.
50
50
  * @param params.expiresAt - Optional safe-integer Unix expiry later than `now`; defaults to `now + 2h` and governs every deadline.
51
- * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended verbatim to every built transaction.
51
+ * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended verbatim to the action transaction's calldata; approval and authorization steps carry none.
52
52
  * @param params.deployless - Optional shared intent field; unused because this operation reads no token metadata or allowances.
53
53
  * @returns A deep-frozen, data-only `TransactionPlan` with chain, account, expiry, withdrawal step,
54
54
  * and any preceding Morpho authorization step and signature request. The caller signs; the SDK never does.
@@ -74,7 +74,6 @@ export interface BlueWithdrawCollateralPlanParams extends IntentParams, Referenc
74
74
  * @throws {viem.BaseError} when a contract-code, chain ID, authorization or nonce RPC read fails.
75
75
  * @example
76
76
  * ```ts
77
- * import assert from "node:assert/strict";
78
77
  * import { markets } from "@morpho-org/morpho-test";
79
78
  * import { fetchAccrualPosition } from "@morpho-org/morpho-sdk/blue/fetch";
80
79
  * import {
@@ -89,7 +88,7 @@ export interface BlueWithdrawCollateralPlanParams extends IntentParams, Referenc
89
88
  * if (!ethereum) throw new Error("Install an Ethereum wallet to continue.");
90
89
  * const wallet = createWalletClient({ chain: mainnet, transport: custom(ethereum) });
91
90
  * const [account] = await wallet.requestAddresses();
92
- * assert(account, "Connect a wallet holding collateral in this market.");
91
+ * if (!account) throw new Error("Connect a wallet holding collateral in this market.");
93
92
  * const market = markets[mainnet.id].usdc_wbtc;
94
93
  * const position = await fetchAccrualPosition(account, market.id, client);
95
94
  * const plan = await prepareBlueWithdrawCollateral(client, {