@oakagentkit/core 0.3.0 → 0.3.1

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 (265) hide show
  1. package/build/dist/api/history.js +1 -1
  2. package/build/dist/api/modules/beefy/clm.d.ts +9 -0
  3. package/build/dist/api/modules/beefy/clm.js +1 -1
  4. package/build/dist/api/modules/beefy/guard.js +1 -1
  5. package/build/dist/api/modules/beefy/index.js +1 -1
  6. package/build/dist/api/modules/beefy/liquidity.js +1 -1
  7. package/build/dist/api/modules/borro/index.js +1 -1
  8. package/build/dist/api/modules/borro/positions.js +1 -1
  9. package/build/dist/api/modules/borro/reader.js +1 -1
  10. package/build/dist/api/modules/chop/actions.js +1 -1
  11. package/build/dist/api/modules/chop/checks.js +1 -1
  12. package/build/dist/api/modules/chop/copy.js +1 -1
  13. package/build/dist/api/modules/chop/guard.js +1 -1
  14. package/build/dist/api/modules/chop/index.js +1 -1
  15. package/build/dist/api/modules/chop/pins.d.ts +13 -0
  16. package/build/dist/api/modules/chop/pins.js +1 -1
  17. package/build/dist/api/modules/chop/positions.js +1 -1
  18. package/build/dist/api/modules/chop/reader.js +1 -1
  19. package/build/dist/api/modules/clanker/index.js +1 -1
  20. package/build/dist/api/modules/earn/index.js +1 -1
  21. package/build/dist/api/modules/fobo/client.d.ts +9 -0
  22. package/build/dist/api/modules/fobo/client.js +1 -0
  23. package/build/dist/api/modules/fobo/index.d.ts +16 -0
  24. package/build/dist/api/modules/fobo/index.js +1 -0
  25. package/build/dist/api/modules/fobo/intent.d.ts +243 -0
  26. package/build/dist/api/modules/fobo/intent.js +1 -0
  27. package/build/dist/api/modules/fobo/pins.d.ts +178 -0
  28. package/build/dist/api/modules/fobo/pins.js +1 -0
  29. package/build/dist/api/modules/fobo/steps.d.ts +25 -0
  30. package/build/dist/api/modules/fobo/steps.js +1 -0
  31. package/build/dist/api/modules/fobo/verify.d.ts +89 -0
  32. package/build/dist/api/modules/fobo/verify.js +1 -0
  33. package/build/dist/api/modules/gloam/copy.d.ts +1 -1
  34. package/build/dist/api/modules/gloam/copy.js +1 -1
  35. package/build/dist/api/modules/gloam/index.js +1 -1
  36. package/build/dist/api/modules/grove/index.js +1 -1
  37. package/build/dist/api/modules/heyresearch/index.js +1 -1
  38. package/build/dist/api/modules/heyresearch/public-reads.js +1 -1
  39. package/build/dist/api/modules/hoodlock/airdrop.js +1 -1
  40. package/build/dist/api/modules/hoodlock/fee.js +1 -1
  41. package/build/dist/api/modules/hoodlock/guard.js +1 -1
  42. package/build/dist/api/modules/hoodlock/index.js +1 -1
  43. package/build/dist/api/modules/hoodlock/lifecycle.js +1 -1
  44. package/build/dist/api/modules/hoodlock/locks-burn.js +1 -1
  45. package/build/dist/api/modules/hoodlock/public.js +1 -1
  46. package/build/dist/api/modules/hookr/actions.js +1 -1
  47. package/build/dist/api/modules/hookr/create-cancel.js +1 -1
  48. package/build/dist/api/modules/hookr/discovery.js +1 -1
  49. package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
  50. package/build/dist/api/modules/hookr/index.js +1 -1
  51. package/build/dist/api/modules/hookr/launch-options.js +1 -1
  52. package/build/dist/api/modules/hookr/launch-receipt.js +1 -1
  53. package/build/dist/api/modules/hookr/launch.js +1 -1
  54. package/build/dist/api/modules/hookr/liquidity.js +1 -1
  55. package/build/dist/api/modules/hookr/lp-positions.js +1 -1
  56. package/build/dist/api/modules/hookr/lp-reads.js +1 -1
  57. package/build/dist/api/modules/hookr/lp-receipt.js +1 -1
  58. package/build/dist/api/modules/hookr/lp-state.js +1 -1
  59. package/build/dist/api/modules/hookr/public-reads.js +1 -1
  60. package/build/dist/api/modules/hookr/relay.js +1 -1
  61. package/build/dist/api/modules/kyberswap/index.js +1 -1
  62. package/build/dist/api/modules/layerbank/actions.js +1 -1
  63. package/build/dist/api/modules/layerbank/index.js +1 -1
  64. package/build/dist/api/modules/layerbank/reader.js +1 -1
  65. package/build/dist/api/modules/longbow/administration.js +1 -1
  66. package/build/dist/api/modules/longbow/fixed.js +1 -1
  67. package/build/dist/api/modules/longbow/index.js +1 -1
  68. package/build/dist/api/modules/meridian/index.js +1 -1
  69. package/build/dist/api/modules/meridian/rfq.js +1 -1
  70. package/build/dist/api/modules/merkl/discovery.js +1 -1
  71. package/build/dist/api/modules/merkl/index.js +1 -1
  72. package/build/dist/api/modules/merkl/manage.js +1 -1
  73. package/build/dist/api/modules/morpho/bundles.js +1 -1
  74. package/build/dist/api/modules/morpho/in-kind.js +1 -1
  75. package/build/dist/api/modules/morpho/index.js +1 -1
  76. package/build/dist/api/modules/morpho/local-guard.d.ts +2 -1
  77. package/build/dist/api/modules/morpho/local-guard.js +1 -1
  78. package/build/dist/api/modules/morpho/midnight.js +1 -1
  79. package/build/dist/api/modules/morpho/protocol.js +1 -1
  80. package/build/dist/api/modules/morpho/surface.js +1 -1
  81. package/build/dist/api/modules/morpho/vault-tools.js +1 -1
  82. package/build/dist/api/modules/netnet/card-plan.js +1 -1
  83. package/build/dist/api/modules/netnet/card-read.js +1 -1
  84. package/build/dist/api/modules/netnet/card-recovery.js +1 -1
  85. package/build/dist/api/modules/netnet/desk-action.js +1 -1
  86. package/build/dist/api/modules/netnet/financial.js +1 -1
  87. package/build/dist/api/modules/netnet/index.js +1 -1
  88. package/build/dist/api/modules/orbio/index.js +1 -1
  89. package/build/dist/api/modules/pendle/index.js +1 -1
  90. package/build/dist/api/modules/pendle/reader.js +1 -1
  91. package/build/dist/api/modules/pons/claim.js +1 -1
  92. package/build/dist/api/modules/pons/index.js +1 -1
  93. package/build/dist/api/modules/pons/launch-status.js +1 -1
  94. package/build/dist/api/modules/pons/reads.js +1 -1
  95. package/build/dist/api/modules/pons/swap-terms.d.ts +2 -8
  96. package/build/dist/api/modules/pons/swap-terms.js +1 -1
  97. package/build/dist/api/modules/pons/trade.js +1 -1
  98. package/build/dist/api/modules/poolstrade/index.js +1 -1
  99. package/build/dist/api/modules/priors/coverage.js +1 -1
  100. package/build/dist/api/modules/priors/discovery.js +1 -1
  101. package/build/dist/api/modules/priors/holdings.js +1 -1
  102. package/build/dist/api/modules/priors/index.js +1 -1
  103. package/build/dist/api/modules/priors/integration.js +1 -1
  104. package/build/dist/api/modules/priors/stock-swap.js +1 -1
  105. package/build/dist/api/modules/raeto/index.js +1 -1
  106. package/build/dist/api/modules/relay/discovery.js +1 -1
  107. package/build/dist/api/modules/relay/inbound.js +1 -1
  108. package/build/dist/api/modules/relay/index.js +1 -1
  109. package/build/dist/api/modules/relay/outbound-status.js +1 -1
  110. package/build/dist/api/modules/spark/index.js +1 -1
  111. package/build/dist/api/modules/steakhouse/analytics.js +1 -1
  112. package/build/dist/api/modules/steakhouse/index.js +1 -1
  113. package/build/dist/api/modules/steakhouse/local-guard.js +1 -1
  114. package/build/dist/api/modules/steakhouse/management.js +1 -1
  115. package/build/dist/api/modules/steakhouse/v2-exit.js +1 -1
  116. package/build/dist/api/modules/tickerspring/basket-routes.js +1 -1
  117. package/build/dist/api/modules/tickerspring/contract-reads.js +1 -1
  118. package/build/dist/api/modules/tickerspring/exit-preview.js +1 -1
  119. package/build/dist/api/modules/tickerspring/guards.js +1 -1
  120. package/build/dist/api/modules/tickerspring/index.js +1 -1
  121. package/build/dist/api/modules/tickerspring/journeys.js +1 -1
  122. package/build/dist/api/modules/tickerspring/ladder.js +1 -1
  123. package/build/dist/api/modules/tickerspring/maker.js +1 -1
  124. package/build/dist/api/modules/tickerspring/order-accounting.js +1 -1
  125. package/build/dist/api/modules/tickerspring/research.js +1 -1
  126. package/build/dist/api/modules/tickerspring/strategies.js +1 -1
  127. package/build/dist/api/modules/uniswap/auction-create.js +1 -1
  128. package/build/dist/api/modules/uniswap/auction.js +1 -1
  129. package/build/dist/api/modules/uniswap/batch.js +1 -1
  130. package/build/dist/api/modules/uniswap/common.js +1 -1
  131. package/build/dist/api/modules/uniswap/fees.js +1 -1
  132. package/build/dist/api/modules/uniswap/index.js +1 -1
  133. package/build/dist/api/modules/uniswap/local-guard.js +1 -1
  134. package/build/dist/api/modules/uniswap/oracle.js +1 -1
  135. package/build/dist/api/modules/uniswap/pool-math.js +1 -1
  136. package/build/dist/api/modules/uniswap/pools.js +1 -1
  137. package/build/dist/api/modules/uniswap/position.js +1 -1
  138. package/build/dist/api/modules/uniswap/protocol.js +1 -1
  139. package/build/dist/api/modules/uniswap/quote-guard.js +1 -1
  140. package/build/dist/api/modules/uniswap/token-jar.js +1 -1
  141. package/build/dist/api/modules/uniswap/trade-batch.js +1 -1
  142. package/build/dist/api/modules/uniswap/trade.js +1 -1
  143. package/build/dist/api/modules/uniswap/v2.js +1 -1
  144. package/build/dist/api/modules/uniswap/v3.js +1 -1
  145. package/build/dist/api/modules/uniswap/v4.js +1 -1
  146. package/build/dist/api/modules/uniswap/wrap.js +1 -1
  147. package/build/dist/api/modules/velora/claims.js +1 -1
  148. package/build/dist/api/modules/velora/index.js +1 -1
  149. package/build/dist/api/modules/wormhole/index.js +1 -1
  150. package/build/dist/api/prices.d.ts +5 -0
  151. package/build/dist/api/prices.js +1 -1
  152. package/build/dist/api/signing-registry.js +1 -1
  153. package/build/dist/api/swap.d.ts +1 -0
  154. package/build/dist/api/swap.js +1 -1
  155. package/build/dist/api/tokens.js +1 -1
  156. package/build/dist/api/universal-router.d.ts +45 -0
  157. package/build/dist/api/universal-router.js +1 -0
  158. package/build/dist/api/usd-estimate.js +1 -1
  159. package/build/dist/chunks/{ROQQ62LP.js → 22TU5PFT.js} +1 -1
  160. package/build/dist/chunks/{2WRXH6BL.js → 257N7343.js} +1 -1
  161. package/build/dist/chunks/{B2HSLY5F.js → 27PVS6BU.js} +1 -1
  162. package/build/dist/chunks/{25C4DTVA.js → 2JWAFLJU.js} +1 -1
  163. package/build/dist/chunks/{24Q3FNGX.js → 35LXCSHY.js} +1 -1
  164. package/build/dist/chunks/{OYDKAIS2.js → 3BMM3V4P.js} +1 -1
  165. package/build/dist/chunks/{VZVW5J7J.js → 3FU6XP6S.js} +1 -1
  166. package/build/dist/chunks/{KH4QFN72.js → 3PHJUFU2.js} +1 -1
  167. package/build/dist/chunks/43BG2JRB.js +1 -0
  168. package/build/dist/chunks/{KMSAUFYV.js → 47HSRR7G.js} +1 -1
  169. package/build/dist/chunks/{2ZBSE2LD.js → 4NDIYRH5.js} +1 -1
  170. package/build/dist/chunks/{M7BUKZW2.js → 4RCYYN6O.js} +1 -1
  171. package/build/dist/chunks/4ZD5D2UP.js +1 -0
  172. package/build/dist/chunks/{X5AL3DUK.js → 6D3XNCOX.js} +1 -1
  173. package/build/dist/chunks/{W4RYRLL5.js → 6GWXPQZ6.js} +1 -1
  174. package/build/dist/chunks/{KBU3PYP7.js → 73BZPPRS.js} +1 -1
  175. package/build/dist/chunks/{XV3YJ4P6.js → 7FIEBJOZ.js} +1 -1
  176. package/build/dist/chunks/{CI5ENLYA.js → 7FZXSYFD.js} +1 -1
  177. package/build/dist/chunks/{K4P5VYDP.js → 7TSIF3F4.js} +1 -1
  178. package/build/dist/chunks/AG2G7BHH.js +6 -0
  179. package/build/dist/chunks/{QMEGAKLI.js → AIYNFIG6.js} +1 -1
  180. package/build/dist/chunks/{KZA5GYZR.js → AWV24X7F.js} +1 -1
  181. package/build/dist/chunks/{JPPQDELB.js → AXHFNE6L.js} +1 -1
  182. package/build/dist/chunks/{WOGWLFAL.js → BGVC5NI6.js} +1 -1
  183. package/build/dist/chunks/BJK75C7G.js +1 -0
  184. package/build/dist/chunks/BSX4LFYI.js +1 -0
  185. package/build/dist/chunks/{OTYB6BHK.js → BZPFPQ2I.js} +1 -1
  186. package/build/dist/chunks/{PQXYTOV5.js → DCGNVMKG.js} +1 -1
  187. package/build/dist/chunks/{OTLUQWLF.js → DLNA5272.js} +1 -1
  188. package/build/dist/chunks/{VMZYFO6I.js → DXAPKN7H.js} +1 -1
  189. package/build/dist/chunks/{NMQBOBWJ.js → EHGH646D.js} +1 -1
  190. package/build/dist/chunks/{PZEF5LBL.js → ETMD747Y.js} +1 -1
  191. package/build/dist/chunks/{XEBMS5KU.js → GGMVT5A6.js} +1 -1
  192. package/build/dist/chunks/GK3D7OKG.js +1 -0
  193. package/build/dist/chunks/GYPMUYB5.js +1 -0
  194. package/build/dist/chunks/{U7UPLF4F.js → H64QC4QR.js} +1 -1
  195. package/build/dist/chunks/{HS5HWBMU.js → HIG7JY3J.js} +1 -1
  196. package/build/dist/chunks/{NWPAQER2.js → HOBIXKGO.js} +1 -1
  197. package/build/dist/chunks/HQIS3QI7.js +3 -0
  198. package/build/dist/chunks/{C6VJAL5B.js → HUKDISRE.js} +1 -1
  199. package/build/dist/chunks/{XPWGPZ2C.js → HZSYMGJ2.js} +1 -1
  200. package/build/dist/chunks/{YARZE7SJ.js → I4473OC6.js} +1 -1
  201. package/build/dist/chunks/{DMB64UIN.js → IJ4HZIDG.js} +1 -1
  202. package/build/dist/chunks/{YBLJ75U5.js → IPU656WB.js} +1 -1
  203. package/build/dist/chunks/{QLAOBULN.js → JTPHZCO3.js} +1 -1
  204. package/build/dist/chunks/{CSOO4SW7.js → K4GUZ5QS.js} +1 -1
  205. package/build/dist/chunks/{WBNFRPAT.js → KLEJ3W4T.js} +1 -1
  206. package/build/dist/chunks/{ACH4BSME.js → KOKLM63Q.js} +1 -1
  207. package/build/dist/chunks/{VB36EHIR.js → KVVBT43U.js} +1 -1
  208. package/build/dist/chunks/{6MDYKE2O.js → KXX7ZBFY.js} +1 -1
  209. package/build/dist/chunks/{I6PQW2JI.js → L2AE32SL.js} +1 -1
  210. package/build/dist/chunks/{KOTGFD2V.js → LGLWEGPY.js} +1 -1
  211. package/build/dist/chunks/{2HN3U6OG.js → LQSPWRHN.js} +1 -1
  212. package/build/dist/chunks/{C3WBHFLX.js → LTDF2LNP.js} +1 -1
  213. package/build/dist/chunks/{RNCMXKKS.js → M4AGEGWW.js} +1 -1
  214. package/build/dist/chunks/{HVFMIURK.js → M6SQPOOL.js} +1 -1
  215. package/build/dist/chunks/{XBNZ7GTY.js → M7CQPTRK.js} +1 -1
  216. package/build/dist/chunks/{OODSXDIH.js → MGVX5EUH.js} +1 -1
  217. package/build/dist/chunks/{D2IYA4LP.js → MQ37QX6U.js} +1 -1
  218. package/build/dist/chunks/{TMRAF2L2.js → NDSNE6PS.js} +1 -1
  219. package/build/dist/chunks/{6OCLWSMZ.js → NTUXDIY6.js} +1 -1
  220. package/build/dist/chunks/{CZQ2CGYV.js → NUERUFH7.js} +1 -1
  221. package/build/dist/chunks/NV6FDIYT.js +1 -0
  222. package/build/dist/chunks/{A2V4NFVA.js → O3CC5SRM.js} +1 -1
  223. package/build/dist/chunks/{JI5DXDMY.js → ODV3XT5U.js} +1 -1
  224. package/build/dist/chunks/OLDQV43V.js +1 -0
  225. package/build/dist/chunks/{B7BNDW35.js → OY5W7ZSL.js} +1 -1
  226. package/build/dist/chunks/{CD2JQ32C.js → PDGYM2WG.js} +1 -1
  227. package/build/dist/chunks/{5R576SDB.js → PKYQ3XVA.js} +1 -1
  228. package/build/dist/chunks/{FN6GNTPR.js → PWJVC2FV.js} +1 -1
  229. package/build/dist/chunks/{Q7L3BX6U.js → QHV5GORV.js} +1 -1
  230. package/build/dist/chunks/{PSGRZWES.js → QN45T4N3.js} +1 -1
  231. package/build/dist/chunks/{LJJYYUEG.js → QPY6UTLU.js} +1 -1
  232. package/build/dist/chunks/{ATEVAJ5Y.js → RA7DOR7F.js} +1 -1
  233. package/build/dist/chunks/{U762746N.js → RUSXMQSJ.js} +1 -1
  234. package/build/dist/chunks/{UPKVD7WG.js → RXP7ZUPY.js} +1 -1
  235. package/build/dist/chunks/{2QGLPY2D.js → SMKO7GKX.js} +1 -1
  236. package/build/dist/chunks/{EHK7CDTU.js → SNCV6HV7.js} +1 -1
  237. package/build/dist/chunks/{2ZQ7X223.js → SOJHYMD7.js} +1 -1
  238. package/build/dist/chunks/{ORG6LVKJ.js → UBI3HBXD.js} +1 -1
  239. package/build/dist/chunks/{N64JJN37.js → UEHN2IDF.js} +1 -1
  240. package/build/dist/chunks/{FTMA24EC.js → UHIJMDD2.js} +1 -1
  241. package/build/dist/chunks/UJQYOTO5.js +1 -0
  242. package/build/dist/chunks/{GP6YO24Z.js → UYULQHZJ.js} +1 -1
  243. package/build/dist/chunks/{MMCM3GSM.js → V4UJMUIB.js} +1 -1
  244. package/build/dist/chunks/{ZNPVBNC5.js → VC5ZCQYZ.js} +1 -1
  245. package/build/dist/chunks/{FGEGJOAA.js → VDJPDIBV.js} +1 -1
  246. package/build/dist/chunks/{TGFQQCRY.js → VFM2BICB.js} +1 -1
  247. package/build/dist/chunks/{MSMHS456.js → VOJULRNU.js} +1 -1
  248. package/build/dist/chunks/{5W74Z4WZ.js → W3DGFMQE.js} +1 -1
  249. package/build/dist/chunks/W7OCS4AM.js +6 -0
  250. package/build/dist/chunks/{QLFPAN6S.js → W7QNSNOH.js} +1 -1
  251. package/build/dist/chunks/{OQFNUDMQ.js → XVOW6UCI.js} +1 -1
  252. package/build/dist/chunks/{P6OB2AFW.js → Y7HBFQYG.js} +1 -1
  253. package/build/dist/chunks/{LDJI2JAL.js → YGW4ODAP.js} +1 -1
  254. package/build/dist/chunks/{U243AWCH.js → YW4W3LPQ.js} +1 -1
  255. package/build/dist/chunks/{65356YKW.js → Z2QV6EZY.js} +1 -1
  256. package/build/dist/chunks/{S4UJDZGN.js → ZDCCFEVL.js} +1 -1
  257. package/build/dist/chunks/{D7QXZM3S.js → ZOLHVZDK.js} +1 -1
  258. package/build/dist/chunks/{SMSXZ3FN.js → ZSVAGOF2.js} +1 -1
  259. package/package.json +1 -1
  260. package/build/dist/chunks/4R3G3H42.js +0 -1
  261. package/build/dist/chunks/LKX5WDOQ.js +0 -1
  262. package/build/dist/chunks/ND32LJWI.js +0 -1
  263. package/build/dist/chunks/URBEK2VV.js +0 -1
  264. package/build/dist/chunks/UVAR6BHU.js +0 -1
  265. package/build/dist/chunks/V6SDKPZS.js +0 -1
@@ -1,4 +1,4 @@
1
- import{a as ae}from"./3CCBUYUM.js";import{a as xt,d as It,e as Tt}from"./ZTKT3ZQK.js";import{a as Re}from"./7MR37STI.js";import{a as Ze,b as Ge,d as At}from"./X24YTJST.js";import{h as Je,i as St}from"./2GXHYI23.js";import{b as kt,c as yt,d as gt}from"./QLFPAN6S.js";import{d as wt,e as te}from"./LKX5WDOQ.js";import{a as ht}from"./Z7FGEWO2.js";import{b as bt}from"./SPJCSEKP.js";import{a as q}from"./43LI5NKJ.js";import{a as A,d as W}from"./66F5ZH34.js";import{d as Oe,g as R,i as Ee}from"./NWNYJ26T.js";import{b as Le}from"./IX3GZMTM.js";import{o as ft}from"./MQ5F2VOK.js";import{b as f,j as z}from"./TI727O2H.js";import{a as i,e as ie}from"./XSD5NL7J.js";import{a as Ye}from"./JXOEJPJ4.js";import{encodeFunctionData as be,erc20Abi as Qa,getAddress as aa,parseAbi as pt,zeroAddress as Xa}from"viem";import{decodeAbiParameters as ca,encodeFunctionData as ua,getAddress as le,parseAbiParameters as ma,zeroAddress as he,zeroHash as Dt}from"viem";import{decodeAbiParameters as ra,encodeFunctionData as na,erc20Abi as sa,getAddress as Ct,parseAbi as ia,parseAbiParameters as la,zeroHash as Mt}from"viem";var et=Ct("0xCE29862924756584BBD0D75CA1249d22007E2813"),Lt="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",da="(uint256 value,uint256 nonce,uint256 deadline,uint8 v,bytes32 r,bytes32 s)",vt=ia(["function BLUE() view returns (address)",`function vaultExitBundlesV1InKindRedemptionVaultV2(address vault,address adapter,${Lt}[] marketParamsList,uint256 exitAssets,${da} sharesPermit,uint256 deadline)`]);function N(e,t=!1){if(typeof e!="string"||!/^\d{1,78}$/.test(e)||BigInt(e)>=1n<<256n||!t&&BigInt(e)===0n)throw new i("Provide a positive uint256 decimal base-unit string.");return BigInt(e)}var Pt=(e,t)=>e<t?e:t;async function io(e,t,s,r,n){q(n);let l=N(r.amount),a=N(r.maxShares),o=N(r.maxPenaltyAssets,!0),u=N(r.deadline),c=e.clientFor(f),m=await At(c,t,s),d=(S,B,Ce,ee=[])=>c.readContract({address:S,abi:B,functionName:Ce,args:ee,blockNumber:m.blockNumber}),[p,b,h,w]=await Promise.all([c.getBlock({blockNumber:m.blockNumber}),d(et,vt,"BLUE"),d(t,sa,"balanceOf",[n]),d(t,Ze,"previewRedeem",[a])]);if(typeof b!="string"||Ct(b)!==$)throw new i("VaultExitBundlesV1 does not report the pinned Morpho Blue.");if(u<p.timestamp||u>p.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");if(a>Ge(h))throw new i("maxShares exceeds the wallet share balance.");let y=Pt(m.idle,l),k=m.markets.filter(S=>S.supplied>0n&&j(S.id)),g=l-y,T=k[0]?.penalty??0n,x=g*10n**18n/(10n**18n+T);if(g>0n&&x===0n)throw new i("The penalty-adjusted in-kind amount rounds to zero.");let M=[];for(let S of k){if(x===0n)break;let B=Pt(S.supplied,x);M.push({marketId:S.id,assets:B,penalty:(B*S.penalty+10n**18n-1n)/10n**18n}),x-=B}if(x>0n)throw new i("The supported adapter positions cannot cover the requested in-kind exit. Reduce the amount; unverified market positions are not transferred.");if(l+BigInt(M.length)>Ge(w))throw new i("maxShares cannot cover the exit and per-market rounding buffer.");if(M.some(S=>S.assets>m.blueCash))throw new i("Morpho Blue cannot fund the largest in-kind callback. Reduce the amount.");let C=M.reduce((S,B)=>S+B.penalty,0n);if(C>o)throw new i("In-kind penalty exceeds maxPenaltyAssets.");let P=[...y?[y]:[],...M.flatMap(S=>[S.assets,S.penalty].filter(B=>B>0n))],E=(await Promise.all(P.map(S=>d(t,Ze,"previewWithdraw",[S])))).reduce((S,B)=>S+Ge(B),0n);if(E===0n||E>a)throw new i("Separately rounded burns exceed maxShares.");let Z=M.map(S=>ra(la(Lt),m.markets.find(B=>B.id===S.marketId).data)[0]),H=m.markets[0]?.adapter;if(!H)throw new i("In-kind exit requires a verified market adapter.");let F=`In-kind exit from ${t}: spend at most ${E} share base units; receive ${y} ${s.symbol} base units and Morpho Blue supply positions ${M.map(S=>`${S.marketId}: ${S.assets} ${s.symbol} base units`).join(", ")||"none"}. Penalty ${C} ${s.symbol} base units. Deadline ${u} (Unix seconds). Supply positions remain exposed to borrower default and can only be withdrawn when market liquidity returns. This is not a cash exit. The exact share allowance bounds drift; accrual can require a fresh preview.`,v=na({abi:vt,functionName:"vaultExitBundlesV1InKindRedemptionVaultV2",args:[t,H,Z,l,{value:0n,nonce:0n,deadline:0n,v:0,r:Mt,s:Mt},u]}),U=[e.approval(t,et,E.toString(),f),e.unsignedTx({to:et,data:v,value:"0",chainId:f,description:F})],D=await e.preview(U,n),V=-D.changes.filter(S=>S.token.chainId===f&&R(S.token.address,t)).reduce((S,B)=>{if(B.token.decimals!==18||!/^-?\d+$/.test(B.amount))throw new i("Invalid in-kind share preview.");return S+BigInt(B.amount)},0n);if(V<=0n||V>E)throw new i("In-kind preview exceeds the exact share authorization or burns no shares.");return{txs:U,preview:D,summary:F,receipt:{idleAssets:y.toString(),positions:M.map(S=>({marketId:S.marketId,asset:s,assets:S.assets.toString()})),penaltyAssets:C.toString()}}}var we=le("0x53A1eB6589861F686af7c531211E35Aefe30210f"),Ut=["supply","withdraw","supplyCollateralAndBorrow","repayAndWithdrawCollateral","migrateBorrowPosition"],tt={kind:0,data:"0x"},_e={nonce:0n,deadline:0n,signature:{v:0,r:Dt,s:Dt}},pa=ma("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),$t=e=>({tools:[{name:"morpho_bundle",inputSchema:{type:"object",additionalProperties:!1,required:["operation","marketId","deadline"],properties:{operation:{type:"string",enum:Ut,description:"Bundle: supply, withdraw, supplyCollateralAndBorrow, repayAndWithdrawCollateral, or migrateBorrowPosition (move debt to destinationMarketId)."},marketId:{type:"string",description:"Verified Morpho Blue market id (0x + 64 hex digits); the source market for migrateBorrowPosition."},destinationMarketId:{type:"string",description:"Only for migrateBorrowPosition: verified market id (0x + 64 hex) to move the borrow into; must share the same tokens."},assets:A(`Amount of the market's loan token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`),collateralAssets:A(`Collateral amount in base units of the market's collateral token (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`),shares:A("Market share amount in base units (supply or borrow shares, read the position), instead of assets. Give assets or shares, not both."),maxRepayAssets:A('Most loan token you accept paying to repay, in base units of the loan token (read its decimals). Example: "1000000" = 1 USDG.'),maxLtv:A("Highest loan-to-value allowed after the bundle, as an 18-decimal wad in base units (0.8e18 = 80 percent); cannot exceed the market LLTV."),deadline:A("Absolute Unix seconds deadline, no more than five minutes ahead. Example: 1800000000."),allocations:{type:"array",maxItems:4,description:"Up to four Public Allocator moves that add liquidity to the market before borrowing or withdrawing; one per vault.",items:{type:"object",additionalProperties:!1,required:["vault","assets","maxPenaltyAssets"],properties:{vault:{type:"string",description:"Pinned NetNet or Longbow V2 vault address (0x + 40 hex) to pull liquidity from; one entry per vault."},sourceMarketId:{type:"string",description:"Source market id (0x + 64 hex) to pull from; omit to allocate idle vault assets."},assets:A(`Amount to reallocate, in base units of the vault's asset (USDG 6 decimals, WETH 18). Example: "1000000" = 1 USDG.`),maxPenaltyAssets:A(`Highest allocator penalty you accept, in base units of the vault's asset. Example: "10000" = 0.01 USDG for a 6-decimal asset.`)}}}}},execute:async(t,s)=>{try{q(s);let r=t.operation,n=e.clientFor(f);if(await n.getChainId()!==f||typeof r!="string"||!Ut.includes(r))throw new i("Choose a supported Blue bundle on chain 4663.");let l=["operation","marketId","deadline",...r==="supply"?["assets"]:r==="withdraw"?["assets","shares","allocations"]:r==="supplyCollateralAndBorrow"?["collateralAssets","assets","maxLtv","allocations"]:r==="repayAndWithdrawCollateral"?["assets","shares","maxRepayAssets","collateralAssets","maxLtv"]:["destinationMarketId","maxLtv","allocations"]];if(Object.keys(t).some(v=>!l.includes(v)))throw new i("Unexpected argument for this Blue bundle.");let a=await n.getBlock(),o=N(t.deadline);if(o<a.timestamp||o>a.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");let[u,c]=await Promise.all([n.readContract({address:we,abi:Re,functionName:"BLUE",blockNumber:a.number}),n.readContract({address:we,abi:Re,functionName:"PUBLIC_ALLOCATOR",blockNumber:a.number})]);if(le(u)!==$||le(c)!==xt)throw new i("BlueBundlesV1 deployment does not match Oak\u2019s pinned Blue and Public Allocator.");let m=async v=>{if(typeof v!="string"||!j(v))throw new i("Choose a verified Morpho market with a supported exit.");let U=await n.readContract({address:$,abi:O,functionName:"idToMarketParams",args:[v],blockNumber:a.number}),D={loanToken:le(U[0]),collateralToken:le(U[1]),oracle:le(U[2]),irm:le(U[3]),lltv:U[4]};if(!R(ke({...D,lltv:String(D.lltv)}),v))throw new i("Blue bundle market identity mismatch.");return D},d=await m(t.marketId),p=r==="migrateBorrowPosition"?await m(t.destinationMarketId):d;if(d.loanToken!==p.loanToken||d.collateralToken!==p.collateralToken)throw new i("Migration requires the same loan and collateral tokens.");if(r==="migrateBorrowPosition"&&t.marketId===t.destinationMarketId)throw new i("Choose a different destination market.");if(r!=="supply"&&!await n.readContract({address:$,abi:O,functionName:"isAuthorized",args:[s,we],blockNumber:a.number}))throw new i(`Authorize the pinned Blue bundle explicitly with morpho_manage setAuthorization account ${we}, enabled true, then retry. That authority covers all Blue positions. Revoke it with enabled false after the bundle.`);let b=t.assets===void 0?0n:N(t.assets,!0),h=t.shares===void 0?0n:N(t.shares,!0),w=t.collateralAssets===void 0?0n:N(t.collateralAssets,!0),y=r==="supply"||r==="withdraw"?0n:N(t.maxLtv,!0);if(y>p.lltv)throw new i("maxLtv cannot exceed the verified destination market LLTV.");if(r==="supply"&&b===0n||r==="withdraw"&&b===0n==(h===0n)||r==="supplyCollateralAndBorrow"&&w===0n&&b===0n||r==="repayAndWithdrawCollateral"&&(b>0n&&h>0n||b===0n&&h===0n&&w===0n))throw new i("Choose a nonzero amount; assets and shares are mutually exclusive for repayment/withdrawal.");let k=t.allocations??[];if(!Array.isArray(k)||k.length>4||k.length&&r==="supplyCollateralAndBorrow"&&b===0n)throw new i("Provide at most four explicit allocations, only with a borrow or withdrawal.");let g=new Set,T=[],x=0n;for(let v of k){if(!v||typeof v!="object"||Array.isArray(v)||Object.keys(v).some(Xe=>!["vault","sourceMarketId","assets","maxPenaltyAssets"].includes(Xe)))throw new i("Unsupported bundled allocation input.");let U=v,D=await It(e,{vault:U.vault,marketId:r==="migrateBorrowPosition"?t.destinationMarketId:t.marketId});if(g.has(D.definition.vault.toLowerCase()))throw new i("Use each source vault at most once per bundle.");g.add(D.definition.vault.toLowerCase());let V=N(U.assets),S=N(U.maxPenaltyAssets,!0);if(!D.permission||V>=1n<<128n||V>D.headroom||D.penalty>10n**18n||D.asset.address!==p.loanToken)throw new i("Bundled allocation is disabled, unqualified or exceeds target capacity.");let B=(V*D.penalty+10n**18n-1n)/10n**18n;if(B>S)throw new i("Bundled allocation exceeds maxPenaltyAssets.");x+=B;let Ce=U.sourceMarketId===void 0,ee=Ce?void 0:D.sources.find(Xe=>R(Xe.id,String(U.sourceMarketId)));if(Ce?!D.canIdle||V>D.data.idle:!ee||!ee.canPull||V>ee.capacity||V>D.data.blueCash)throw new i("Bundled allocation source cannot cover the requested amount.");T.push({vault:D.definition.vault,adapter:D.target.adapter,marketParams:D.params,sourceAdapter:ee?.adapter??he,sourceMarketParams:ee?ca(pa,ee.data)[0]:D.params,assets:V,penalty:D.penalty,fromIdle:Ce})}let M,C,P,I=0n;if(r==="supply")M="blueBundlesV1Supply",P=d.loanToken,I=b,C=[d,b,tt,0n,he,o];else if(r==="withdraw")M="blueBundlesV1Withdraw",C=[d,b,h,_e,T,0n,he,o];else if(r==="supplyCollateralAndBorrow"){if(M="blueBundlesV1SupplyCollateralAndBorrow",P=d.collateralToken,I=w,x>=b&&x>0n)throw new i("Allocation penalties would consume the borrow proceeds.");C=[d,w,b,y,tt,_e,T,0n,he,o]}else if(r==="repayAndWithdrawCollateral"){if(M="blueBundlesV1RepayAndWithdrawCollateral",P=d.loanToken,I=N(t.maxRepayAssets,!0),b>I||h>0n&&I===0n)throw new i("Repayment requires a sufficient maxRepayAssets budget.");C=[d,b,h,I,w,y,tt,_e,0n,he,o]}else M="blueBundlesV1MigrateBorrowPosition",C=[d,p,y,_e,T,0n,he,o];let E=`Morpho Blue atomic ${r}: ${JSON.stringify(t)}. Allocation penalties ${x} loan-token base units; zero referral fee. Max LTV ${y}; absolute deadline ${o}. Migration adds allocation penalties to destination debt; borrowing deducts them from proceeds. Exact input approval ${I}. Existing Blue bundle authorization remains until explicitly revoked with morpho_manage. No opaque callback, permit or signature is accepted.`,Z=[...P&&I?[e.approval(P,we,I.toString(),f)]:[],e.unsignedTx({to:we,data:ua({abi:Re,functionName:M,args:C}),value:"0",chainId:f,description:E})],H=await e.preview(Z,s),F=new Map;for(let v of H.changes)if(BigInt(v.amount)<0n){let U=v.token.address.toLowerCase();F.set(U,(F.get(U)??0n)-BigInt(v.amount))}if([...F].some(([v,U])=>!P||v!==P.toLowerCase()||U>I))throw new i("Bundle preview spends outside the exact input budget.");return{txs:Z,preview:H,summary:E}}catch(r){throw new i(e.plainError(r))}}}]});import{concatHex as Bt,decodeAbiParameters as fa,encodeAbiParameters as Rt,encodeFunctionData as at,erc20Abi as Nt,getAddress as K,keccak256 as rt,zeroAddress as ye,zeroHash as ba}from"viem";var Y=K("0x6120765Ba5336150BbdDdD0Cd9108B5bFD369632"),ha=["0x90B800999e4ACd1bD20283BD450bBd2e06D91F7C","0x708d6Bf6F847202a0755bb5636bE663B174242ea"].map(e=>K(e)),nt=ae.find(e=>e.name==="take"),Ot=[nt.inputs[0]],wa=[nt.inputs[0].components[0]];function Et(e){let t=rt(Bt(["0x600b380380600b5f395ff3",Rt(wa,[e])]));return rt(Bt(["0xff",e.midnight,ba,t]))}var de=10n**18n,Gt=(e,t)=>(e+(t-1n)/2n)/t;function _t(e){if(e<0n)return 10n**36n/_t(-e);let t=693147180559945309n,s=(e+322611214989459870n)/t,r=e-s*t,n=r*r/(2n*de),l=n*r/(3n*de);return de+r+n+l<<s}function ka(e){if(e<0n||e>6744n)throw new i("Midnight tick is outside 0..6744.");return Gt(Gt(10n**36n,de+_t(4987541511039073n*(3372n-e))),10n**11n)*10n**11n}function He(e,t){if(typeof e!="string"||!/^0x([0-9a-f]{2})*$/i.test(e)||e.length>32770||t!==void 0&&e.length!==2+t*2)throw new i("Provide bounded canonical hex data.");return e}function ot(e,t){if(!Array.isArray(e)||e.length!==t)throw new i("Invalid Midnight state tuple.");return e.map(s=>{if(typeof s=="number"&&Number.isSafeInteger(s)&&s>=0)return BigInt(s);if(typeof s=="bigint"&&s>=0n)return s;throw new i("Invalid Midnight integer state.")})}var ya=e=>JSON.parse(JSON.stringify(e,(t,s)=>typeof s=="bigint"?s.toString():s)),Ht=e=>{async function t(n,l){let a=He(n,32),o=e.clientFor(f);if(await o.getChainId()!==f)throw new i("Midnight requires chain 4663.");let u=await o.getBlock(),c=(k,g=[])=>o.readContract({address:Y,abi:ae,functionName:k,args:g,blockNumber:u.number}),m=await c("toMarket",[a]);if(m.chainId!==BigInt(f)||K(m.midnight)!==Y||!R(Et(m),a))throw new i("Midnight market identity does not match the pinned chain and contract.");if(![z[f].tokens.USDG.address,z[f].tokens.WETH.address].some(k=>R(k,m.loanToken)))throw new i("This Midnight loan token needs a qualified transfer and exit fixture.");if(!m.collateralParams.length||m.collateralParams.length>128)throw new i("Invalid Midnight collateral inventory.");let[p,b,h,w]=await Promise.all([c("position",[a,l]),c("updatePositionView",[m,a,l]),c("marketState",[a]),c("isHealthy",[m,a,l])]),y=async k=>{let[g,T]=await Promise.all([o.readContract({address:k,abi:Nt,functionName:"decimals",blockNumber:u.number}),o.readContract({address:k,abi:Nt,functionName:"symbol",blockNumber:u.number})]);if(!Number.isInteger(g)||g>36||typeof T!="string")throw new i("Invalid Midnight token metadata.");return{address:K(k),decimals:g,symbol:T.replace(/[^a-zA-Z0-9.$_-]/g,"").slice(0,32),chainId:f}};return{id:a,rpc:o,block:u,market:m,read:c,token:y,loan:await y(m.loanToken),position:ot(p,6),updated:ot(b,3),state:ot(h,13),healthy:w}}let s=(n,l,a,o)=>({name:n,inputSchema:{type:"object",properties:l,required:a,additionalProperties:!1},execute:async(u,c)=>{try{if(q(c),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Midnight argument.");return await o(u,c)}catch(m){throw new i(e.plainError(m))}}});async function r(n,l,a){return{txs:n,preview:await e.preview(n,l),summary:a}}return{tools:[s("morpho_midnight_status",{marketId:{type:"string",description:"Midnight market id: 0x + 64 hex digits (bytes32)."}},["marketId"],async(n,l)=>{let a=await t(n.marketId,l),o=await Promise.all(a.market.collateralParams.map(async(m,d)=>({token:await a.token(m.token),lltvWad:m.lltv.toString(),oracle:m.oracle,assets:String(await a.read("collateral",[a.id,l,BigInt(d)]))}))),u=["configurator","feeSetter","feeClaimer","tickSpacingSetter"],c=await Promise.all(u.map(m=>a.read(m)));return{protocol:Object.fromEntries(u.map((m,d)=>[m,K(String(c[d]))])),continuousFeePerSecondWad:String(a.state[11]),tickSpacing:String(a.state[12]),settlementFeeCbps:a.state.slice(4,11).map(String),settlementFeeCbpWadScale:"1000000000000",chainId:f,midnight:Y,marketId:a.id,blockNumber:String(a.block.number),market:ya(a.market),loanToken:a.loan,collaterals:o,debtUnits:String(a.position[4]),creditUnits:String(a.updated[0]),pendingFeeUnits:String(a.updated[1]),withdrawableUnits:String(a.state[2]),healthy:a.healthy,maturity:String(a.market.maturity),matured:a.block.timestamp>a.market.maturity,warning:"Maturity does not guarantee lender liquidity. Borrowers become liquidatable after maturity even when collateralized. Lender credit may absorb borrower default losses."}}),s("morpho_midnight_take",{offer:{type:"string",description:"ABI-encoded Offer struct, never transaction calldata."},ratifierData:{type:"string",description:"Hex proof data (0x...) that the offer's pinned ratifier uses to confirm the maker approved this offer."},units:A("Fixed debt units to trade, as a decimal string below 2^128. The asset cost or proceeds follow from the offer price; maxAssets and minAssets bound them."),maxAssets:A('Most loan token you will spend when buying credit, in base units of the market loan token (read its decimals). Example: "1000000" = 1 USDG.'),minAssets:A('Least loan token you must receive when selling credit or borrowing, in base units of the market loan token. Example: "1000000" = 1 USDG.')},["offer","ratifierData","units","maxAssets","minAssets"],async(n,l)=>{let a=He(n.offer),[o]=fa(Ot,a);if(!R(Rt(Ot,[o]),a))throw new i("Offer encoding is not canonical.");let u=await t(Et(o.market),l),c=N(n.units),m=N(n.maxAssets,!0),d=N(n.minAssets,!0),p=He(n.ratifierData);if(c>=1n<<128n||R(o.maker,l)||o.callback!==ye||o.callbackData!=="0x"||!ha.includes(K(o.ratifier)))throw new i("Use a non-self offer with a pinned ratifier and no maker callbacks. Callback routes need a separate qualified builder.");if(u.block.timestamp<o.start||u.block.timestamp>o.expiry||o.expiry<o.start)throw new i("The Midnight offer is not currently live.");if(o.buy&&o.receiverIfMakerIsSeller!==ye||!o.buy&&o.receiverIfMakerIsSeller===ye)throw new i("Invalid offer seller receiver.");if(o.buy&&u.block.timestamp>u.market.maturity&&c>u.updated[0])throw new i("Post-maturity sales cannot increase this wallet\u2019s debt.");let b=await u.read("settlementFee",[u.id,u.market.maturity>u.block.timestamp?u.market.maturity-u.block.timestamp:0n]),h=ka(o.tick);if(b>h&&o.buy)throw new i("Settlement fee exceeds the offer price.");let w=o.buy?h-b:h,y=w+b,k=v=>o.buy?v/de:(v+de-1n)/de,g=k(c*y),T=k(c*w);if(o.buy?T<d||T===0n:g>m||g===0n)throw new i("Midnight proceeds/spend do not fit the requested bounds.");let x=await u.read("consumed",[o.maker,o.group]);if(o.maxAssets===0n==(o.maxUnits===0n)||x+(o.maxAssets?o.buy?g:T:c)>(o.maxAssets||o.maxUnits))throw new i("Midnight offer capacity is exhausted or invalid.");if(u.state[11]>o.continuousFeeCap||o.tick%u.state[12]!==0n)throw new i("Offer fee cap or market tick spacing no longer permits execution.");let M=await u.read("isAuthorized",[o.maker,o.ratifier]),C=[{type:"function",name:"isRatified",stateMutability:"view",inputs:[nt.inputs[0],{type:"bytes"},{type:"address"}],outputs:[{type:"bytes32"}]}],P=await u.rpc.readContract({address:o.ratifier,abi:C,functionName:"isRatified",args:[o,p,l],blockNumber:u.block.number});if(M!==!0||P!==rt(new TextEncoder().encode("morpho.midnight.callbackSuccess")))throw new i("The maker has not authorized and ratified this exact offer.");let I=at({abi:ae,functionName:"take",args:[o,p,c,l,o.buy?l:ye,ye,"0x"]}),E=`Midnight ${o.buy?"sell credit or borrow":"buy credit or reduce debt"}: ${c} fixed debt units; ${o.buy?`receive ${T}`:`spend ${g}`} ${u.loan.symbol} base units (token ${u.loan.address}, decimals ${u.loan.decimals}). Maturity ${u.market.maturity} Unix seconds; offer expiry ${o.expiry}. A borrower can lose collateral after maturity; lender withdrawal depends on repayments and bears default losses. No lender signature or callback is created. Bounds are rechecked locally; the take calldata fixes the offer and units. Exact buyer approval caps wallet spending.`,Z=[...o.buy?[]:[e.approval(u.loan.address,Y,g.toString(),f)],e.unsignedTx({to:Y,data:I,value:"0",chainId:f,description:E})],H=await r(Z,l,E),F=H.preview.changes.filter(v=>v.token.chainId===f&&R(v.token.address,u.loan.address)).reduce((v,U)=>v+BigInt(U.amount),0n);if(o.buy?F<T:F!==-g)throw new i("Midnight preview does not match the exact quoted cash flow.");return H}),s("morpho_midnight_action",{marketId:{type:"string",description:"Midnight market id: 0x + 64 hex digits (bytes32)."},operation:{enum:["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"],description:"Action: add or remove collateral, repay debt, withdraw matured credit, refresh the position, or claim continuous fees (fee claimer only)."},amount:A('Amount in base units of the relevant token: the collateral token for collateral operations, else the loan token (read decimals). Example: "1000000" = 1 USDG.'),collateralIndex:{type:"integer",minimum:0,maximum:127,description:"Zero-based position of the collateral in the market collateral list; required for supplyCollateral and withdrawCollateral only."}},["marketId","operation"],async(n,l)=>{let a=await t(n.marketId,l),o=n.operation;if(!["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"].includes(String(o)))throw new i("Choose a finite Midnight position operation.");let u,c,m=a.loan,d=0n;if(o==="updatePosition"){if(n.amount!==void 0||n.collateralIndex!==void 0)throw new i("Position update takes no amount or collateral index.");u=[a.market,l]}else if(o==="claimContinuousFee"){if(d=N(n.amount),n.collateralIndex!==void 0||K(String(await a.read("feeClaimer")))!==K(l))throw new i("This wallet lacks the Midnight fee claimer role or supplied an unused collateral index.");u=[a.market,d,l]}else{if(d=N(n.amount),d>=1n<<128n)throw new i("Midnight position amount exceeds uint128.");if(o==="supplyCollateral"||o==="withdrawCollateral"){if(!Number.isInteger(n.collateralIndex)||Number(n.collateralIndex)<0||Number(n.collateralIndex)>=a.market.collateralParams.length)throw new i("Choose a current collateral index.");let h=BigInt(String(n.collateralIndex)),w=await a.token(a.market.collateralParams[Number(h)].token);if(m=w,o==="withdrawCollateral"&&d>await a.read("collateral",[a.id,l,h]))throw new i("Insufficient Midnight collateral.");u=o==="supplyCollateral"?[a.market,h,d,l]:[a.market,h,d,l,l],o==="supplyCollateral"&&(c=w)}else{if(n.collateralIndex!==void 0)throw new i("This operation takes no collateral index.");if(o==="repay"&&d>a.position[4]||o==="withdraw"&&(d>a.updated[0]||d>a.state[2]))throw new i("Amount exceeds current debt, credit or available repayment liquidity.");u=o==="repay"?[a.market,d,l,ye,"0x"]:[a.market,d,l,l],o==="repay"&&(c=a.loan)}}let p=`Midnight ${o}: ${d} ${m.symbol} base units (token ${m.address}, decimals ${m.decimals}) on ${a.id}; beneficiary ${l}; maturity ${a.market.maturity} Unix seconds. No callbacks or delegation. Withdrawal can fail if collateral health or lender liquidity changes.`,b=[...c?[e.approval(c.address,Y,d.toString(),f)]:[],e.unsignedTx({to:Y,data:at({abi:ae,functionName:String(o),args:u}),value:"0",chainId:f,description:p})];return r(b,l,p)}),s("morpho_midnight_manage",{operation:{type:"string",enum:["setConsumed","setIsAuthorized","setConfigurator","setFeeSetter","setFeeClaimer","setTickSpacingSetter","enableLltv","enableLiquidationCursor","setMarketTickSpacing","setMarketSettlementFee","setMarketContinuousFee","setDefaultSettlementFee","setDefaultContinuousFee","claimSettlementFee"],description:"Midnight management function name; role-gated except setConsumed and setIsAuthorized, which act on this wallet."},values:{type:"array",maxItems:3,description:"Ordered arguments for the chosen operation, as in the Midnight ABI: decimal strings for integers (base units), 0x addresses or bytes32, or booleans.",items:{oneOf:[{type:"string"},{type:"boolean"}]}}},["operation","values"],async(n,l)=>{let a={setConfigurator:"configurator",setFeeSetter:"configurator",setFeeClaimer:"configurator",setTickSpacingSetter:"configurator",enableLltv:"configurator",enableLiquidationCursor:"configurator",setMarketTickSpacing:"tickSpacingSetter",setMarketSettlementFee:"feeSetter",setMarketContinuousFee:"feeSetter",setDefaultSettlementFee:"feeSetter",setDefaultContinuousFee:"feeSetter",claimSettlementFee:"feeClaimer"};if(typeof n.operation!="string"||!["setConsumed","setIsAuthorized",...Object.keys(a)].includes(n.operation)||!Array.isArray(n.values))throw new i("Choose a finite Midnight management operation and ordered values.");let o=n.operation,u=ae.find(p=>p.name===o);if(n.values.length!==u.inputs.length)throw new i("Provide the exact ordered operation values.");let c=e.clientFor(f);if(await c.getChainId()!==f)throw new i("Midnight requires chain 4663.");let m=u.inputs.map((p,b)=>{let h=n.values[b];if(p.type==="bool"){if(typeof h!="boolean")throw new i("Use boolean management values.");return h}if(p.type==="address")return Ee(h,"Use explicit management addresses.",Oe);if(p.type==="bytes32")return He(h,32);if(/^uint/.test(p.type)){let w=N(h,!0);if(w>=1n<<BigInt(p.type.slice(4)))throw new i("Management integer exceeds its ABI width.");return w}throw new i("Unsupported management argument type.")});if(o==="setConsumed"||o==="setIsAuthorized"){if(!R(String(m[2]),l))throw new i("Midnight management is bound to this wallet.")}else{let p=await c.readContract({address:Y,abi:ae,functionName:a[o]});if(typeof p!="string"||K(p)!==K(l))throw new i("This wallet lacks the Midnight configuration, fee or tick role.")}let d=`Midnight ${o}, ordered values ${JSON.stringify(n.values)}. ${o==="setIsAuthorized"&&m[1]?"This grants authority over all Midnight positions, cancellations and further delegation, without an amount cap. Revoke with false when done.":""}${o==="setConsumed"?"Consumption only increases; setting uint128 maximum permanently cancels this offer group.":""}`;return r([e.unsignedTx({to:Y,data:at({abi:ae,functionName:o,args:m}),value:"0",chainId:f,description:d})],l,d)})]}};import{decodeAbiParameters as re,encodeAbiParameters as ga,encodeFunctionData as G,erc20Abi as it,getAddress as L,isAddress as Fe,keccak256 as Sa,parseAbi as Ve,parseAbiParameters as J}from"viem";var De="morpho",Aa="https://api.morpho.org/graphql",$=L(z[f].morpho.morpho_blue.address),xa=L(z[f].morpho.adaptive_curve_irm.address),Ia=L(z[f].morpho.USDG.address),me=L(z[f].morpho.WETH.address),Ta=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],Ma={"oak-recorded":"Oak recorded chain observations (block 100362239).","morpho-listed":"Morpho API (POST https://api.morpho.org/graphql, markets where chainId_in [4663]) returned listed: true, fetched 2026-10-31 UTC.",longbow:"Longbow market list: Longbow MCP list_markets/get_market (https://mcp.longbow.credit/mcp, named on https://longbow.cash/mcp) and the live market list on https://longbow.cash/earn, fetched 2026-10-31 UTC; each ID re-read on chain.",netnet:"NetNet Credit: six stock-token market IDs printed at https://docs.netnet.capital/credit, plus the Loopback wsNET/USDG market returned by NetNet's Turbo router marketId() and Credit adapter marketIds(6); fetched 2026-10-31 UTC."},lt=[{marketId:"0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2",label:"WETH/USDG 77%",source:"oak-recorded"},{marketId:"0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8",label:"USDG/WETH",source:"oak-recorded"},{marketId:"0x0309c02dabf0be02682af1a2bde9a457f4df0f0b6bc889cde3f948e5315e4114",label:"spUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x10151e2ac82a820153520d9d77d56de1c84775e23b79bdc11e2e34282d9afa10",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x127353ba63e08f74d8e9ce8a1c2b41b5f89c7167135b1c09fbed34a71b4cb06b",label:"WETH/USDG 86%",source:"morpho-listed"},{marketId:"0x1a31d1c8c05a98b94777663912e4166bf50f3fcdc9c3c3d29deb55634ac58239",label:"PONS/USDG 62.5%",source:"morpho-listed"},{marketId:"0x1efd13a2d1dc66a2466e7c25820537028e604791f00454d9c686fdfbf70f404d",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x21ea2a012b888120e328775c2a7bf6fb4619cf4c4c631ad1c9b6db51f8882d5a",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x22e4598e5cc16cff0056e72d61c5f1f2f8bf5bbffc22da5277ab196939c8a59e",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x66306c087add8907752320b309934abcc354d21626de8115c79df49d9c214edc",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x69400cfe81f2ae381b9a9f27076a4d637338379d999e9ffdfbde52f0876312ee",label:"META/USDG 62.5%",source:"morpho-listed"},{marketId:"0x7408b08b03e05ffd2d21c797489a0e77a28e4bb36acb4e827c69e805d06272b4",label:"GOOGL/USDG 77%",source:"morpho-listed"},{marketId:"0x7c1e38bf461da47df9805ae9b7e97a12ec023625a1f92d2a403b3b9a92260894",label:"CASHCAT/USDG 62.5%",source:"morpho-listed"},{marketId:"0x919a9b6b94dae7c86620eaf7a08e597aae8a4c3a9e9c7671771fbaf62b6b61c7",label:"syrupUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x93ed7865910b09f5a2e0dbfd4670c2d3bc1da9647f7c68e7975f37f497898cdb",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x947ae981cc823024ea00b602f6ea72d049cac05d66ef096198ceeb998651c175",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0x95312f02c1dae8407b2c80468a5657a9bd19c45ac277f1a61aa52c11444c5314",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xba01f6625137b692c5dd86afb8e654b4016d7b64e36dfca4124e84bef98bc4d2",label:"GOOGL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xc845da65a020ddca5f132efa8fea79676d8edfdea504226a4c01e7a9e34cddd6",label:"USDe/USDG 91.5%",source:"morpho-listed"},{marketId:"0xcaa167af7ba0422c76424fae56167b7db25bf19f4f435215e6dd7d06a943bdac",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe29c7d3790037800101ecbad9c45de2067698d206cbcab7c25069a9f43c9eb98",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe5a6d99c3721ef2ab00fb16f0ad226bc7c87a90394f82e27dc6bbca4b1d95c5d",label:"AI/USDG 62.5%",source:"morpho-listed"},{marketId:"0xeb1739b2a69dd22a4285d366a06698a01018b37c24d2994fefe19cc72f313613",label:"SPY/USDG 77%",source:"morpho-listed"},{marketId:"0xf5ff7d546af5e72f3912d2aa723088fd0bf66fddc158714995637714d9db6e4c",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xaa586d26a6fe62d9c0f0948fede6e2130500ac7a655587447e2d4a37e6330589",label:"wsNET/USDG 62.5% (NetNet Loopback)",source:"netnet"},{marketId:"0x8b16891f032a93b771347c9cb470a780e6699dd701553d3402aa3cdba6189c3e",label:"NVDA/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x9b4b47cdf7e295341c6c6cdfd3efb9805c4a5b3d580dba0c0c39d3a4232b297b",label:"SPCX/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0xdeb4782d012d5fd3b24962538c2f6559049d70bda4dabd2e4212dacb96c28d45",label:"AAPL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x7fa81b10e5d21b2e4c571f862442bc11aff2ed14f02335868d0ff933fd40d0ba",label:"GOOGL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x2e1859aa8f143b7220088f80562c6dfe0bf8e52b87d9cedf8da8805f231994ce",label:"MSFT/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x3ebd43d91c3960a9fac32bedd5c60428e0e414de5bdd67fda770207afb0eb615",label:"COIN/USDG 38.5% (NetNet Credit)",source:"netnet"},{marketId:"0x26f3bd5919ba0e6ea6f4bca1b8bd95ce29cbe3aad4ef824fb007570eac35103b",label:"cbBTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb095654f06f4d17d4fc010c2d89a107649e3c5b58e53a3812d1736c95e63e3f8",label:"NVDAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x947c05e7c0fa3ba187d57db710d04ba8be4fef53baba0cfbe71ce61b34a1367d",label:"SPCXon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf8f0b5badf06192908bc47af32b93742d9b4fb6072d388cb183ff7849ee6534c",label:"SPYon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x26c80a00f8facc6b081989965d89cedc274b90b81be660e69245a74e5384f5de",label:"METAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xeefec6c3e5cb7df1f2366ea7cf96a583081205b9720e807d2868d9866a702229",label:"GOOGLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf511a080dcb4d0a3b9d6aebb06e24afa011cda87f9f71ada70c60f8220e94f35",label:"AAPLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xa87da1cc931faa945a41861cc9c90076772ceeae9a663836df6b265c4f30106d",label:"MSTRon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x0279ea145eff84ed2ffd3b1ed1f2aca333060d9cef6fdd48bd21073c13ec86bf",label:"CRCLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xff2063ef18bc5f71867c56d6d3290b61f3da1d010c8a0552bdb7995cfad8cacc",label:"TSLAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x83d542605940b5495ef38d4b62a39293766a486a24e5c67930f41acd919cf1d1",label:"QQQon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9b01d5ad5ce8e477510854132cc47853f6e82a708c9c4723887550412f4ee522",label:"GMEon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8b2af4d69ad861a4099b995b6279aeaf6a905225a0ee889bce424c7faf19b7d9",label:"AMZN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4edbd2f2f3b33bc5f80ab588def67fab8c10945fc99f855d80ff4bef2c4aa1f0",label:"SLV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x7e6ebfdc58a893a5cddba0fba0483baf4fac2efece627ad50821dbe27d6f9738",label:"GOOGL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x30a2a5f1a098b23ed91eadc4529a8d1c967f2cdc2e40a709f3a5992004b01ac0",label:"AAPL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x14973a168cf6c6b1148309f5d567c255b292863ffe9cca59f4284e1426636f00",label:"RKLB/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf049167e6bf18a1b41b8e2acefcf7bc9b13ea013d8d65c7fbc7cbaeb3fe9b4e2",label:"NBIS/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8114b65dfc5e64222103e5588de261eca9defd25f47ea4ae2f91d49fe4fa2993",label:"CLSK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x96d3d5f9bc842e4c8a935c5628abd02fb0e10115560c35a9add768781434f471",label:"CRWV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x1b3555f7c1273688f01ae82da7dc8e508e6a7841ec0038dbb15767154a277b86",label:"EWY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x039503b6308d6d818d181e626d3fbc667d6e68393c3d74332a6124cd2dd6e755",label:"CASHCAT_LEGACY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x597227ca652ea5e8afb6e4801ecd766a4d6eb9b3b9fafa9127ba88a8b1f19629",label:"SPCX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x50bc39b5722fb5634c436d74c6787f3c125b879e7b73cf9e9ecc01bbb57b8e55",label:"SPY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x315b99abb698487891243a84afd28a5ff56fe02143f203c03edd3f103936bf60",label:"QQQ/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4979137c23c8fb519cd507adc290944c3c2120e8a3191547531fced28360e9c2",label:"GME/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x6b8a1f62d88d1cd1e8de609aef07cafc8226172ba703e57c52c3730350e61df1",label:"USO/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xafc86936af4f7edf083eb2550b8c42311b83c685982742b9271b309a58268855",label:"MSFT/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf6f3dbe0a19e948147e79e66502c6b05709d8dfde977fec7db1528fc8f0ebdfa",label:"SGOV/USDG 86% (Longbow)",source:"longbow"},{marketId:"0x2ab6a14c9f68d4216dcb3b4e6ed607cf82f2e6badfa2bd5618d7f69d012d7fab",label:"USAR/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb41b34c5989420ad080e79363a9cfe3e23bec7459fcd2d88029250da370288df",label:"TSLA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4d2075836fd32183b10e5be1b383f6430de859df6d2bd5ec5b859970c4dd14e8",label:"AMD/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9df4f54a2e46b35bd326cec97dbabc4203fa6c64a8e4182128f277adba8fefaf",label:"MU/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb5ba72c0d55c353fa37c0bea104eb117afb2f4934473bcb736d2218ae5686746",label:"PLTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xda5584635e8b14ea18f674dbe4243365505910fefd8e3aa1ac9bfaac0eba74e8",label:"INTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x74fece475178af9e06d31fb64f405046a305f8f0abc588782f596d6f261c1fbb",label:"SNDK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xee04847a312224d551d2267bb5c2c2695777af5fd1f05347bdcca397e8f54336",label:"ORCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x508b47fb12dbb8747644d4436aae65489b5f2819936adefc8a591323f64a5b01",label:"COIN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x243ac165f79a75a0590d2e994ffa9e260b70292fd1ca134ace95f3640895b19f",label:"TSM/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x01baec96478004fc7b74c8dfe38abef8d716fea59ffd481b6ec74db915d3bc80",label:"MSTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf0959f62e748938cf260ca6fe7cb21a412e0a6643913460f4a6770c3f4b90af6",label:"CRCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xbe881499e682850931951c998e76cfbf38c7979b1beeae7cbbb97a39b3336a07",label:"ASML/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xdd578ca54b4ef6a7827c6e9fc06905699a577f6e2f00712853d8aab13383bc38",label:"BABA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xd8b502d5c43f6e5cfff7f938c7ef18e684f114fb5b362611981144397e5d5aef",label:"DELL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x003390b057d753bd839981a0d45f9a567aa0b0ed6373fd42e951eac8ee86c2ba",label:"RGTI/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xc6e16cff2bcf185639562ab937b7a1c381522768ff16aefc85a25ff6ab1c45ea",label:"AI/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xaba3ac501ce4c6b80c08ed0dba19e1ac0de495f17af3ed692a38e92d176a6c9e",label:"PONS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8097c1d1000eb657e75265384137041ac92856c8dc0b72c99569c3681320a430",label:"DELTA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6e6762ae397a2b3f2500ea2f48f8adce0eadfbf54cbc37f6108602e907e844ad",label:"INDEX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x378713071c58206c6a826287d0051bcae113d83d6e3d3b6370b7e73128d06162",label:"STONKBROKER/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x2695be2638c98241c887e4cad4eeba0f01137205f46b9e302edab04b5fee0570",label:"AVGO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6c12c02536aa27831f713d658b59f74e149cc62b48528cb74455e79fab32f772",label:"GLD/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x298e8ff9b31f22be90507bc61b55e66ab93e78b55a60593035e309ed93137cb8",label:"RDDT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb33399a677e1a21152fa9969f02c57a7a342e692ec45608a3fa0d3d92519c343",label:"COST/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x3be7fe1b6b439cfeb737d9921e9b83c92095a23a4f50aeee0d6d04f44446170f",label:"DJT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0066bc47b87597993af0bca6f526175c0abae011b764d4bf12a3def45e1f4e78",label:"NFLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8c170f5c5df593791640ac9fbac297d59d08c2e92e86f38fe52d38e929e60fa3",label:"AMC/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0f18d4fd8d86bd4d100b867b67e1fd38c80981fcd43e442313c2d5408da9352d",label:"LLY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x7d4313cf1b0ede39395a2c7495dc1b1b47370caf51f70571d927f22e715e5f58",label:"LULU/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xa85928d77bd25cc348e13ea6587b8b3ca3793f4af5e5db8ca07d0f20fd5cfa99",label:"IBM/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x9d61e320efb766ce5c375032b399f08afe644b095a9cb0b2d6d1f6ab68399a6f",label:"F/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x43c51f6ff44ab406ab9c97cb5512c881f4a7498209f94bbcfd874d8f97fad79d",label:"HIMS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe6284cf12d0603aee18ff5ab412e262cf99f120e967579111d7a51f37f276f54",label:"TTWO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe8d9b45cdbedc4401a3145be7726c9f72b715e03c5399c961439f11636ee9fb6",label:"MRNA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x46eea143d473cdb8587505f8886dad452037f285f7729a7763e8c233c63b2e8e",label:"RIVN/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8338aed363a309039b2f271a83558831e7e445f2d13c6e72c576ec0b8a969415",label:"RBLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x4e92b336ecad6c842be20ae2ae27b28b3cf5ced6c5388a808167c03a8d75fdf8",label:"SPY/WETH 38.5% (Longbow)",source:"longbow"},{marketId:"0x141c2b1d2bbecf7f8a76563307d7e5bf586457e873c3d97c4bb1502e57b77952",label:"NVDA/WETH 38.5% (Longbow)",source:"longbow"}],va=new Map(lt.map(e=>[e.marketId.toLowerCase(),e]));function j(e){return va.get(e.toLowerCase())}function ct(e){let t=j(e);return t?{actions:"enabled",label:t.label,source:Ma[t.source]}:{actions:"read-only",reason:"Not in Oak's verified Morpho market registry; Oak builds no transactions for it."}}var qt=20,Ue=120n,ze=1000000n,We=1n,Se=10n**18n,Pa=10n**36n,jt=(1n<<128n)-1n,Ca=(1n<<256n)-1n,X=Ve(["function idToMarketParams(bytes32 id) view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv)","function market(bytes32 id) view returns (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee)","function position(bytes32 id, address user) view returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral)","function supplyCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, bytes data)","function withdrawCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, address receiver)","function borrow((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsBorrowed, uint256 sharesBorrowed)","function repay((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsRepaid, uint256 sharesRepaid)","function supply((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsSupplied, uint256 sharesSupplied)","function withdraw((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn)"]),La=Ve(["function price() view returns (uint256)"]),Da=Ve(["function borrowRateView((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee) market) view returns (uint256)"]),Kt=Ve(["function deposit() payable"]);function pe(e){return{loanToken:e.loanToken,collateralToken:e.collateralToken,oracle:e.oracle,irm:e.irm,lltv:e.lltv.toString()}}function $e(e,t){return e===0n?0n:(e+t-1n)/t}function Ua(e,t,s){return e*(s+ze)/(t+We)}function $a(e,t,s){return $e(e*(s+ze),t+We)}function ut(e,t,s){return e*(t+We)/(s+ze)}function se(e,t,s){return $e(e*(t+We),s+ze)}function Ae(e,t,s){return e*t/Pa*s/Se}function Ba(e,t,s){return t.startsWith("-")?`-${e.formatAmount(t.slice(1),s)}`:e.formatAmount(t,s)}function xe(e,t){let s=[],r={};for(let n of t.changes){let l=Ba(e,n.amount,n.token.decimals);s.push({token:n.token,amount:n.amount,formattedAmount:l}),r[n.token.address.toLowerCase()]=l}return{formattedChanges:s,formattedNetOutflows:r}}function Qt(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new i("Morpho marketId must be a 32-byte hex string.");return e.toLowerCase()}function je(e){if(!e||typeof e!="object")throw new i("Morpho marketParams must be an object.");for(let a of[e.loanToken,e.collateralToken,e.oracle,e.irm])if(typeof a!="string"||!Fe(a,{strict:!1}))throw new i("Morpho marketParams contains an invalid address.");let t=L(e.loanToken),s=L(e.collateralToken),r=L(e.oracle),n=L(e.irm),l=typeof e.lltv=="bigint"?e.lltv:Le(String(e.lltv));if(t===te||s===te||r===te)throw new i("Morpho marketParams loan, collateral, and oracle addresses must be non-zero.");if(l<=0n||l>=Se)throw new i("Morpho marketParams LLTV must be between 0 and 1e18.");return{loanToken:t,collateralToken:s,oracle:r,irm:n,lltv:l}}function ke(e){let t=je(e),s=ga(J("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return Sa(s)}function dt(e){let t=e.toLowerCase();return t===ht.toLowerCase()||t===wt.toLowerCase()||t===te.toLowerCase()}function Ie(e,t){let s=t??e.wallet;if(!s)throw new i("Provide a valid wallet address.");return q(s),L(s)}async function ne(e,t,s){if(typeof e.call=="function"){let r=await e.call({to:t,data:s});if(r&&typeof r.data=="string")return r.data}if(typeof e.request=="function"){let r=await e.request({method:"eth_call",params:[{to:t,data:s},"latest"]});if(typeof r=="string")return r}throw new i(`Unable to execute eth_call on contract ${t}.`)}function Xt(e){return typeof e=="string"&&/^[A-Za-z0-9$._+-]{1,32}$/.test(e)?e:"UNKNOWN"}async function Q(e,t,s=f){if(q(t),dt(t))return{...kt,chainId:s};let r=L(t),n=r.toLowerCase();if(s===f){if(n===Ia.toLowerCase())return yt;if(n===me.toLowerCase())return gt}let[l,a]=await Promise.all([ne(e,r,G({abi:it,functionName:"symbol"})),ne(e,r,G({abi:it,functionName:"decimals"}))]),[o]=re(J("string"),l),[u]=re(J("uint8"),a);return{address:r,symbol:Xt(o),decimals:Number(u),chainId:s}}async function Yt(e,t){let s=await ne(e,$,G({abi:X,functionName:"idToMarketParams",args:[t]})),[r,n,l,a,o]=re(J("address, address, address, address, uint256"),s);return{loanToken:L(r),collateralToken:L(n),oracle:L(l),irm:L(a),lltv:o}}async function Jt(e,t){let s=await ne(e,$,G({abi:X,functionName:"market",args:[t]})),[r,n,l,a,o,u]=re(J("uint128, uint128, uint128, uint128, uint128, uint128"),s);return{totalSupplyAssets:r,totalSupplyShares:n,totalBorrowAssets:l,totalBorrowShares:a,lastUpdate:o,fee:u}}async function Te(e,t,s){let r=await ne(e,$,G({abi:X,functionName:"position",args:[t,L(s)]})),[n,l,a]=re(J("uint256, uint128, uint128"),r);return{supplyShares:n,borrowShares:l,collateral:a}}async function Ke(e,t){let s=await ne(e,L(t),G({abi:La,functionName:"price"})),[r]=re(J("uint256"),s);return r}async function Na(e,t,s){if(t.irm===te)return 0n;let r=await ne(e,L(t.irm),G({abi:Da,functionName:"borrowRateView",args:[t,s]})),[n]=re(J("uint256"),r);return n}function Qe(e,t,s){let r=s>e.lastUpdate?s-e.lastUpdate:0n,n=t*r,l=$e(n*n,2n*Se),a=$e(l*n,3n*Se);return e.totalBorrowAssets+$e(e.totalBorrowAssets*(n+l+a),Se)}async function Be(e,t,s,r=0n){let[n,l]=await Promise.all([e.getBlock({blockTag:"latest"}),Na(e,t,s)]),a=BigInt(Math.ceil(Date.now()/1e3)),o=(n.timestamp>a?n.timestamp:a)+r;return{totalBorrowAssets:Qe(s,l,o),accruedThrough:o,rate:l}}async function Zt(e,t,s){let r=await ne(e,L(t),G({abi:it,functionName:"balanceOf",args:[L(s)]})),[n]=re(J("uint256"),r);return n}async function fe(e,t,s=!1){let r=t.marketId,n=t.marketParams;if(!r&&!n)throw new i("Provide either marketId or marketParams for the Morpho Blue market.");let l=n?je(n):void 0,a=l?ke(l):void 0,o=r!==void 0?Qt(r):void 0;if(o&&a&&o!==a.toLowerCase())throw new i(`MarketParams tuple hash (${a}) does not match marketId (${o}).`);let u=(o??a).toLowerCase();if(s&&!j(u))throw new i(`Morpho actions require a known market from Oak's verified registry, which pins its oracle. Find one with morpho_status {"discover":true}; other markets are read-only.`);let[c,m]=await Promise.all([Yt(e,u),Jt(e,u)]);if(c.loanToken===te||c.collateralToken===te||c.lltv===0n||m.lastUpdate===0n)throw new i(`Morpho market ${u} is not initialized on chain ${f}.`);let d=ke(c);if(d.toLowerCase()!==u.toLowerCase())throw new i(`On-chain idToMarketParams tuple hash (${d}) does not match marketId (${u}).`);if(l&&!(l.loanToken.toLowerCase()===c.loanToken.toLowerCase()&&l.collateralToken.toLowerCase()===c.collateralToken.toLowerCase()&&l.oracle.toLowerCase()===c.oracle.toLowerCase()&&l.irm.toLowerCase()===c.irm.toLowerCase()&&l.lltv===c.lltv))throw new i(`Provided marketParams tuple does not match on-chain idToMarketParams for ${u}.`);return{marketId:u,marketParams:c,marketState:m}}function Me(e){if(e.assets!==void 0&&e.amount!==void 0)throw new i("Specify either assets or amount, not both.");let t=e.assets??e.amount;if(typeof t!="string")throw new i("Provide an amount as a base-unit integer string.");let s=Le(t);if(s<=0n||s>jt)throw new i("Asset amount must be greater than zero and fit in uint128.");return s}function ve(e,t){for(let s of["onBehalf","receiver"])if(e[s]!==void 0&&(typeof e[s]!="string"||e[s].toLowerCase()!==t.toLowerCase()))throw new i(`Morpho ${s} must be the wallet; overrides are not supported.`);if(e.data!==void 0&&e.data!=="0x")throw new i("Morpho callback data must be empty (0x).")}async function Oa(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=e.clientFor(f),{marketId:a,marketParams:o}=await fe(l,t,!0),u=await Q(l,o.collateralToken,f),c=o.collateralToken.toLowerCase()===me.toLowerCase(),m=typeof t.collateralToken=="string"?(q(t.collateralToken),L(t.collateralToken)):void 0,d=W("wrapNative",t.wrapNative)===!0||m!==void 0&&dt(m);if(m&&!dt(m)&&m.toLowerCase()!==o.collateralToken.toLowerCase())throw new i(`Collateral token ${m} does not match market collateral ${o.collateralToken}.`);if(d&&!c)throw new i("Native ETH wrapping is only supported when market collateralToken is WETH.");let p=Me(t),b=p.toString(),h=e.formatAmount(b,u.decimals),w=[];d&&w.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:b,description:`Wrap ${h} ETH into WETH at ${me}.`})),w.push(e.approval(o.collateralToken,$,b,f)),w.push(e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"supplyCollateral",args:[o,p,n,"0x"]}),value:"0",description:`Supply ${h} ${u.symbol} (${b} base units) collateral to Morpho market ${a}.`}));let y=await e.preview(w,r),{formattedChanges:k,formattedNetOutflows:g}=xe(e,y);return{action:"morpho_supply_collateral",chainId:f,marketId:a,marketParams:pe(o),collateralToken:u,assets:b,formattedAssets:h,onBehalf:n,txs:w,summary:`${d?`Send ${h} ETH to wrap into WETH. `:""}Supply ${h} ${u.symbol} collateral to Morpho Blue market ${a}.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ea(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,a=e.clientFor(f),{marketId:o,marketParams:u,marketState:c}=await fe(a,t,!0),[m,d,p,b]=await Promise.all([Q(a,u.loanToken,f),Te(a,o,n),Ke(a,u.oracle),Be(a,u,c,Ue)]),h=Me(t),w=h.toString(),y=e.formatAmount(w,m.decimals),k=c.totalSupplyAssets>c.totalBorrowAssets?c.totalSupplyAssets-c.totalBorrowAssets:0n;if(h>k)throw new i(`Insufficient market liquidity: requested ${w} base units, available ${k.toString()} base units.`);let g=Ae(d.collateral,p,u.lltv),T=se(d.borrowShares,b.totalBorrowAssets,c.totalBorrowShares);if(d.collateral===0n||T+h>g)throw new i(`Insufficient collateral or unhealthy borrow: total debt ${(T+h).toString()} exceeds max borrow ${g.toString()} base units.`);let x=$a(h,b.totalBorrowAssets,c.totalBorrowShares),C=[e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"borrow",args:[u,h,0n,n,l]}),value:"0",description:`Borrow ${y} ${m.symbol} (${w} base units) from Morpho market ${o}.`})],P=await e.preview(C,r),{formattedChanges:I,formattedNetOutflows:E}=xe(e,P);return{action:"morpho_borrow",chainId:f,marketId:o,marketParams:pe(u),loanToken:m,assets:w,formattedAssets:y,borrowShares:x.toString(),onBehalf:n,receiver:l,txs:C,summary:`Borrow ${y} ${m.symbol} from Morpho Blue market ${o}.`,preview:P,formattedChanges:I,formattedNetOutflows:E}}async function Ga(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=e.clientFor(f);if(t.shares!==void 0){let I=Le(t.shares);if(I<=0n||I===Ca||I>jt)throw new i("Morpho Blue core does not accept maxUint256 or out-of-range share sentinels; pass exact position.borrowShares.")}if(W("repayAll",t.repayAll)===!0&&(t.shares!==void 0||t.assets!==void 0||t.amount!==void 0))throw new i("Specify repayAll alone, without shares or assets/amount.");if(t.shares!==void 0&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify either assets/amount or shares for Morpho repay, not both.");let{marketId:a,marketParams:o,marketState:u}=await fe(l,t,!0),[c,m,d]=await Promise.all([Q(l,o.loanToken,f),Te(l,a,n),Zt(l,o.loanToken,r)]);if(m.borrowShares===0n)throw new i(`Position has no active borrow debt on Morpho market ${a}.`);let p=0n,b=0n;if(W("repayAll",t.repayAll)===!0)b=m.borrowShares;else if(t.shares!==void 0){let I=Le(t.shares);if(I>m.borrowShares)throw new i(`Repay shares (${I.toString()}) exceed current position borrowShares (${m.borrowShares.toString()}).`);b=I}else p=Me(t);let h=b>0n?await Be(l,o,u,Ue):void 0,w=b>0n?se(b,h.totalBorrowAssets,u.totalBorrowShares):p;if(d<w)throw new i(`Insufficient loan token balance for repayment: wallet holds ${d.toString()} base units, but ${w.toString()} base units are required (including accrued interest).`);let y=w.toString(),k=e.formatAmount(y,c.decimals),g=e.approval(o.loanToken,$,y,f),T=e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"repay",args:[o,p,b,n,"0x"]}),value:"0",description:b>0n?`Repay ${b.toString()} borrow shares (${k} ${c.symbol}) on Morpho market ${a}.`:`Repay ${k} ${c.symbol} (${p.toString()} base units) on Morpho market ${a}.`}),x=[g,T],M=await e.preview(x,r),{formattedChanges:C,formattedNetOutflows:P}=xe(e,M);return{action:"morpho_repay",chainId:f,marketId:a,marketParams:pe(o),loanToken:c,repayAssets:p.toString(),repayShares:b.toString(),requiredAssets:y,...h?{accruedThrough:h.accruedThrough.toString(),borrowRatePerSecond:h.rate.toString(),inclusionSeconds:Ue.toString()}:{},formattedRequiredAssets:k,onBehalf:n,txs:x,summary:b>0n?`Repay ${b.toString()} borrow shares (approval up to ${k} ${c.symbol}) on Morpho Blue market ${a}. Refresh if signing/inclusion takes more than ${Ue} seconds.`:`Repay ${k} ${c.symbol} on Morpho Blue market ${a}.`,preview:M,formattedChanges:C,formattedNetOutflows:P}}async function Ra(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,a=e.clientFor(f),{marketId:o,marketParams:u,marketState:c}=await fe(a,t,!0),[m,d,p,b]=await Promise.all([Q(a,u.collateralToken,f),Te(a,o,n),Ke(a,u.oracle),Be(a,u,c,Ue)]),h=W("withdrawAll",t.withdrawAll)===!0?d.collateral:Me(t);if(h<=0n||h>d.collateral)throw new i(`Insufficient collateral to withdraw: requested ${h.toString()} base units, position holds ${d.collateral.toString()} base units.`);if(d.borrowShares>0n){let C=d.collateral-h,P=Ae(C,p,u.lltv),I=se(d.borrowShares,b.totalBorrowAssets,c.totalBorrowShares);if(I>P)throw new i(`Unhealthy collateral withdrawal: remaining max borrow ${P.toString()} would fall below current debt ${I.toString()} base units.`)}let w=h.toString(),y=e.formatAmount(w,m.decimals),g=[e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"withdrawCollateral",args:[u,h,n,l]}),value:"0",description:`Withdraw ${y} ${m.symbol} (${w} base units) collateral from Morpho market ${o}.`})],T=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:M}=xe(e,T);return{action:"morpho_withdraw_collateral",chainId:f,marketId:o,marketParams:pe(u),collateralToken:m,assets:w,formattedAssets:y,onBehalf:n,receiver:l,txs:g,summary:`Withdraw ${y} ${m.symbol} collateral from Morpho Blue market ${o}.`,preview:T,formattedChanges:x,formattedNetOutflows:M}}async function _a(e,t,s){let r=Ie(t,s);ve(t,r);let n=e.clientFor(f),{marketId:l,marketParams:a,marketState:o}=await fe(n,t,!0),u=W("wrapNative",t.wrapNative)===!0;if(u&&a.loanToken.toLowerCase()!==me.toLowerCase())throw new i("Native ETH wrapping is only supported when the market loanToken is WETH.");let c=Me(t),m=c.toString(),[d,p]=await Promise.all([Q(n,a.loanToken,f),u?Promise.resolve(c):Zt(n,a.loanToken,r)]);if(p<c)throw new i(`Insufficient ${d.symbol} balance to lend: wallet holds ${p.toString()} base units, requested ${m}.`);let b=e.formatAmount(m,d.decimals),h=[];u&&h.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:m,description:`Wrap ${b} ETH into WETH at ${me}.`})),h.push(e.approval(a.loanToken,$,m,f)),h.push(e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"supply",args:[a,c,0n,r,"0x"]}),value:"0",description:`Lend ${b} ${d.symbol} (${m} base units) to Morpho market ${l}.`}));let w=Ua(c,o.totalSupplyAssets,o.totalSupplyShares),y=await e.preview(h,r),{formattedChanges:k,formattedNetOutflows:g}=xe(e,y);return{action:"morpho_supply",chainId:f,marketId:l,marketParams:pe(a),loanToken:d,assets:m,formattedAssets:b,supplySharesEstimated:w.toString(),onBehalf:r,oak:ct(l),txs:h,summary:`${u?`Send ${b} ETH to wrap into WETH. `:""}Lend ${b} ${d.symbol} to Morpho Blue market ${l}. It earns the market supply rate and is exposed to the market's collateral, oracle and liquidity risk.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ha(e,t,s){let r=Ie(t,s);ve(t,r);let n=e.clientFor(f),l=W("withdrawAll",t.withdrawAll)===!0;if(l&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify withdrawAll alone, without assets/amount.");let{marketId:a,marketParams:o,marketState:u}=await fe(n,t,!0),[c,m]=await Promise.all([Q(n,o.loanToken,f),Te(n,a,r)]);if(m.supplyShares===0n)throw new i(`This wallet has no lent ${c.symbol} on Morpho market ${a}.`);let d=ut(m.supplyShares,u.totalSupplyAssets,u.totalSupplyShares),p=l?0n:Me(t),b=l?m.supplyShares:0n;if(!l&&p>d)throw new i(`Withdrawal exceeds the lent balance: requested ${p.toString()} base units, position holds about ${d.toString()}. Use withdrawAll for a full exit.`);let h=u.totalSupplyAssets>u.totalBorrowAssets?u.totalSupplyAssets-u.totalBorrowAssets:0n,w=l?d:p;if(w>h)throw new i(`Insufficient market liquidity: withdrawing ${w.toString()} base units needs idle assets, but only ${h.toString()} are available until borrowers repay. Withdraw at most that amount, or retry later.`);let y=e.formatAmount(w.toString(),c.decimals),g=[e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"withdraw",args:[o,p,b,r,r]}),value:"0",description:l?`Withdraw all ${m.supplyShares.toString()} supply shares (about ${y} ${c.symbol}) from Morpho market ${a}.`:`Withdraw ${y} ${c.symbol} (${p.toString()} base units) of lent assets from Morpho market ${a}.`})],T=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:M}=xe(e,T);return{action:"morpho_withdraw",chainId:f,marketId:a,marketParams:pe(o),loanToken:c,withdrawAssets:p.toString(),withdrawShares:b.toString(),estimatedAssets:w.toString(),formattedAssets:y,receiver:r,txs:g,summary:l?`Withdraw all lent ${c.symbol} (about ${y}, including interest) from Morpho Blue market ${a}.`:`Withdraw ${y} lent ${c.symbol} from Morpho Blue market ${a}.`,preview:T,formattedChanges:x,formattedNetOutflows:M}}async function ea(e,t,s){let r=await e.http(Aa,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:t,variables:s})});if(!r.ok)throw new i(`Morpho GraphQL request failed (HTTP ${r.status}).`);let n=await r.json();if(n.errors?.length)throw new i("Morpho GraphQL returned query errors.");return n.data??{}}async function ta(e){let t=`query Markets($chainId: Int!) {
1
+ import{a as xt,d as It,e as Tt}from"./ZTKT3ZQK.js";import{a as Re}from"./7MR37STI.js";import{a as ae}from"./3CCBUYUM.js";import{a as Ze,b as Ge,d as At}from"./X24YTJST.js";import{h as Je,i as St}from"./2GXHYI23.js";import{b as kt,c as yt,d as gt}from"./W7QNSNOH.js";import{d as wt,e as te}from"./GYPMUYB5.js";import{a as ht}from"./Z7FGEWO2.js";import{b as bt}from"./SPJCSEKP.js";import{a as q}from"./43LI5NKJ.js";import{a as A,d as W}from"./66F5ZH34.js";import{d as Oe,g as R,i as Ee}from"./NWNYJ26T.js";import{b as Le}from"./IX3GZMTM.js";import{o as ft}from"./MQ5F2VOK.js";import{b as f,j as z}from"./TI727O2H.js";import{a as i,e as ie}from"./XSD5NL7J.js";import{a as Ye}from"./JXOEJPJ4.js";import{encodeFunctionData as be,erc20Abi as Qa,getAddress as aa,parseAbi as pt,zeroAddress as Xa}from"viem";import{decodeAbiParameters as ca,encodeFunctionData as ua,getAddress as le,parseAbiParameters as ma,zeroAddress as he,zeroHash as Dt}from"viem";import{decodeAbiParameters as ra,encodeFunctionData as na,erc20Abi as sa,getAddress as Ct,parseAbi as ia,parseAbiParameters as la,zeroHash as Mt}from"viem";var et=Ct("0xCE29862924756584BBD0D75CA1249d22007E2813"),Lt="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",da="(uint256 value,uint256 nonce,uint256 deadline,uint8 v,bytes32 r,bytes32 s)",vt=ia(["function BLUE() view returns (address)",`function vaultExitBundlesV1InKindRedemptionVaultV2(address vault,address adapter,${Lt}[] marketParamsList,uint256 exitAssets,${da} sharesPermit,uint256 deadline)`]);function N(e,t=!1){if(typeof e!="string"||!/^\d{1,78}$/.test(e)||BigInt(e)>=1n<<256n||!t&&BigInt(e)===0n)throw new i("Provide a positive uint256 decimal base-unit string.");return BigInt(e)}var Pt=(e,t)=>e<t?e:t;async function io(e,t,s,r,n){q(n);let l=N(r.amount),a=N(r.maxShares),o=N(r.maxPenaltyAssets,!0),u=N(r.deadline),c=e.clientFor(f),m=await At(c,t,s),d=(S,B,Ce,ee=[])=>c.readContract({address:S,abi:B,functionName:Ce,args:ee,blockNumber:m.blockNumber}),[p,b,h,w]=await Promise.all([c.getBlock({blockNumber:m.blockNumber}),d(et,vt,"BLUE"),d(t,sa,"balanceOf",[n]),d(t,Ze,"previewRedeem",[a])]);if(typeof b!="string"||Ct(b)!==$)throw new i("VaultExitBundlesV1 does not report the pinned Morpho Blue.");if(u<p.timestamp||u>p.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");if(a>Ge(h))throw new i("maxShares exceeds the wallet share balance.");let y=Pt(m.idle,l),k=m.markets.filter(S=>S.supplied>0n&&j(S.id)),g=l-y,T=k[0]?.penalty??0n,x=g*10n**18n/(10n**18n+T);if(g>0n&&x===0n)throw new i("The penalty-adjusted in-kind amount rounds to zero.");let M=[];for(let S of k){if(x===0n)break;let B=Pt(S.supplied,x);M.push({marketId:S.id,assets:B,penalty:(B*S.penalty+10n**18n-1n)/10n**18n}),x-=B}if(x>0n)throw new i("The supported adapter positions cannot cover the requested in-kind exit. Reduce the amount; unverified market positions are not transferred.");if(l+BigInt(M.length)>Ge(w))throw new i("maxShares cannot cover the exit and per-market rounding buffer.");if(M.some(S=>S.assets>m.blueCash))throw new i("Morpho Blue cannot fund the largest in-kind callback. Reduce the amount.");let C=M.reduce((S,B)=>S+B.penalty,0n);if(C>o)throw new i("In-kind penalty exceeds maxPenaltyAssets.");let P=[...y?[y]:[],...M.flatMap(S=>[S.assets,S.penalty].filter(B=>B>0n))],E=(await Promise.all(P.map(S=>d(t,Ze,"previewWithdraw",[S])))).reduce((S,B)=>S+Ge(B),0n);if(E===0n||E>a)throw new i("Separately rounded burns exceed maxShares.");let Z=M.map(S=>ra(la(Lt),m.markets.find(B=>B.id===S.marketId).data)[0]),H=m.markets[0]?.adapter;if(!H)throw new i("In-kind exit requires a verified market adapter.");let F=`In-kind exit from ${t}: spend at most ${E} share base units; receive ${y} ${s.symbol} base units and Morpho Blue supply positions ${M.map(S=>`${S.marketId}: ${S.assets} ${s.symbol} base units`).join(", ")||"none"}. Penalty ${C} ${s.symbol} base units. Deadline ${u} (Unix seconds). Supply positions remain exposed to borrower default and can only be withdrawn when market liquidity returns. This is not a cash exit. The exact share allowance bounds drift; accrual can require a fresh preview.`,v=na({abi:vt,functionName:"vaultExitBundlesV1InKindRedemptionVaultV2",args:[t,H,Z,l,{value:0n,nonce:0n,deadline:0n,v:0,r:Mt,s:Mt},u]}),U=[e.approval(t,et,E.toString(),f),e.unsignedTx({to:et,data:v,value:"0",chainId:f,description:F})],D=await e.preview(U,n),V=-D.changes.filter(S=>S.token.chainId===f&&R(S.token.address,t)).reduce((S,B)=>{if(B.token.decimals!==18||!/^-?\d+$/.test(B.amount))throw new i("Invalid in-kind share preview.");return S+BigInt(B.amount)},0n);if(V<=0n||V>E)throw new i("In-kind preview exceeds the exact share authorization or burns no shares.");return{txs:U,preview:D,summary:F,receipt:{idleAssets:y.toString(),positions:M.map(S=>({marketId:S.marketId,asset:s,assets:S.assets.toString()})),penaltyAssets:C.toString()}}}var we=le("0x53A1eB6589861F686af7c531211E35Aefe30210f"),Ut=["supply","withdraw","supplyCollateralAndBorrow","repayAndWithdrawCollateral","migrateBorrowPosition"],tt={kind:0,data:"0x"},_e={nonce:0n,deadline:0n,signature:{v:0,r:Dt,s:Dt}},pa=ma("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),$t=e=>({tools:[{name:"morpho_bundle",inputSchema:{type:"object",additionalProperties:!1,required:["operation","marketId","deadline"],properties:{operation:{type:"string",enum:Ut,description:"Bundle: supply, withdraw, supplyCollateralAndBorrow, repayAndWithdrawCollateral, or migrateBorrowPosition (move debt to destinationMarketId)."},marketId:{type:"string",description:"Verified Morpho Blue market id (0x + 64 hex digits); the source market for migrateBorrowPosition."},destinationMarketId:{type:"string",description:"Only for migrateBorrowPosition: verified market id (0x + 64 hex) to move the borrow into; must share the same tokens."},assets:A(`Amount of the market's loan token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`),collateralAssets:A(`Collateral amount in base units of the market's collateral token (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`),shares:A("Market share amount in base units (supply or borrow shares, read the position), instead of assets. Give assets or shares, not both."),maxRepayAssets:A('Most loan token you accept paying to repay, in base units of the loan token (read its decimals). Example: "1000000" = 1 USDG.'),maxLtv:A("Highest loan-to-value allowed after the bundle, as an 18-decimal wad in base units (0.8e18 = 80 percent); cannot exceed the market LLTV."),deadline:A("Absolute Unix seconds deadline, no more than five minutes ahead. Example: 1800000000."),allocations:{type:"array",maxItems:4,description:"Up to four Public Allocator moves that add liquidity to the market before borrowing or withdrawing; one per vault.",items:{type:"object",additionalProperties:!1,required:["vault","assets","maxPenaltyAssets"],properties:{vault:{type:"string",description:"Pinned NetNet or Longbow V2 vault address (0x + 40 hex) to pull liquidity from; one entry per vault."},sourceMarketId:{type:"string",description:"Source market id (0x + 64 hex) to pull from; omit to allocate idle vault assets."},assets:A(`Amount to reallocate, in base units of the vault's asset (USDG 6 decimals, WETH 18). Example: "1000000" = 1 USDG.`),maxPenaltyAssets:A(`Highest allocator penalty you accept, in base units of the vault's asset. Example: "10000" = 0.01 USDG for a 6-decimal asset.`)}}}}},execute:async(t,s)=>{try{q(s);let r=t.operation,n=e.clientFor(f);if(await n.getChainId()!==f||typeof r!="string"||!Ut.includes(r))throw new i("Choose a supported Blue bundle on chain 4663.");let l=["operation","marketId","deadline",...r==="supply"?["assets"]:r==="withdraw"?["assets","shares","allocations"]:r==="supplyCollateralAndBorrow"?["collateralAssets","assets","maxLtv","allocations"]:r==="repayAndWithdrawCollateral"?["assets","shares","maxRepayAssets","collateralAssets","maxLtv"]:["destinationMarketId","maxLtv","allocations"]];if(Object.keys(t).some(v=>!l.includes(v)))throw new i("Unexpected argument for this Blue bundle.");let a=await n.getBlock(),o=N(t.deadline);if(o<a.timestamp||o>a.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");let[u,c]=await Promise.all([n.readContract({address:we,abi:Re,functionName:"BLUE",blockNumber:a.number}),n.readContract({address:we,abi:Re,functionName:"PUBLIC_ALLOCATOR",blockNumber:a.number})]);if(le(u)!==$||le(c)!==xt)throw new i("BlueBundlesV1 deployment does not match Oak\u2019s pinned Blue and Public Allocator.");let m=async v=>{if(typeof v!="string"||!j(v))throw new i("Choose a verified Morpho market with a supported exit.");let U=await n.readContract({address:$,abi:O,functionName:"idToMarketParams",args:[v],blockNumber:a.number}),D={loanToken:le(U[0]),collateralToken:le(U[1]),oracle:le(U[2]),irm:le(U[3]),lltv:U[4]};if(!R(ke({...D,lltv:String(D.lltv)}),v))throw new i("Blue bundle market identity mismatch.");return D},d=await m(t.marketId),p=r==="migrateBorrowPosition"?await m(t.destinationMarketId):d;if(d.loanToken!==p.loanToken||d.collateralToken!==p.collateralToken)throw new i("Migration requires the same loan and collateral tokens.");if(r==="migrateBorrowPosition"&&t.marketId===t.destinationMarketId)throw new i("Choose a different destination market.");if(r!=="supply"&&!await n.readContract({address:$,abi:O,functionName:"isAuthorized",args:[s,we],blockNumber:a.number}))throw new i(`Authorize the pinned Blue bundle explicitly with morpho_manage setAuthorization account ${we}, enabled true, then retry. That authority covers all Blue positions. Revoke it with enabled false after the bundle.`);let b=t.assets===void 0?0n:N(t.assets,!0),h=t.shares===void 0?0n:N(t.shares,!0),w=t.collateralAssets===void 0?0n:N(t.collateralAssets,!0),y=r==="supply"||r==="withdraw"?0n:N(t.maxLtv,!0);if(y>p.lltv)throw new i("maxLtv cannot exceed the verified destination market LLTV.");if(r==="supply"&&b===0n||r==="withdraw"&&b===0n==(h===0n)||r==="supplyCollateralAndBorrow"&&w===0n&&b===0n||r==="repayAndWithdrawCollateral"&&(b>0n&&h>0n||b===0n&&h===0n&&w===0n))throw new i("Choose a nonzero amount; assets and shares are mutually exclusive for repayment/withdrawal.");let k=t.allocations??[];if(!Array.isArray(k)||k.length>4||k.length&&r==="supplyCollateralAndBorrow"&&b===0n)throw new i("Provide at most four explicit allocations, only with a borrow or withdrawal.");let g=new Set,T=[],x=0n;for(let v of k){if(!v||typeof v!="object"||Array.isArray(v)||Object.keys(v).some(Xe=>!["vault","sourceMarketId","assets","maxPenaltyAssets"].includes(Xe)))throw new i("Unsupported bundled allocation input.");let U=v,D=await It(e,{vault:U.vault,marketId:r==="migrateBorrowPosition"?t.destinationMarketId:t.marketId});if(g.has(D.definition.vault.toLowerCase()))throw new i("Use each source vault at most once per bundle.");g.add(D.definition.vault.toLowerCase());let V=N(U.assets),S=N(U.maxPenaltyAssets,!0);if(!D.permission||V>=1n<<128n||V>D.headroom||D.penalty>10n**18n||D.asset.address!==p.loanToken)throw new i("Bundled allocation is disabled, unqualified or exceeds target capacity.");let B=(V*D.penalty+10n**18n-1n)/10n**18n;if(B>S)throw new i("Bundled allocation exceeds maxPenaltyAssets.");x+=B;let Ce=U.sourceMarketId===void 0,ee=Ce?void 0:D.sources.find(Xe=>R(Xe.id,String(U.sourceMarketId)));if(Ce?!D.canIdle||V>D.data.idle:!ee||!ee.canPull||V>ee.capacity||V>D.data.blueCash)throw new i("Bundled allocation source cannot cover the requested amount.");T.push({vault:D.definition.vault,adapter:D.target.adapter,marketParams:D.params,sourceAdapter:ee?.adapter??he,sourceMarketParams:ee?ca(pa,ee.data)[0]:D.params,assets:V,penalty:D.penalty,fromIdle:Ce})}let M,C,P,I=0n;if(r==="supply")M="blueBundlesV1Supply",P=d.loanToken,I=b,C=[d,b,tt,0n,he,o];else if(r==="withdraw")M="blueBundlesV1Withdraw",C=[d,b,h,_e,T,0n,he,o];else if(r==="supplyCollateralAndBorrow"){if(M="blueBundlesV1SupplyCollateralAndBorrow",P=d.collateralToken,I=w,x>=b&&x>0n)throw new i("Allocation penalties would consume the borrow proceeds.");C=[d,w,b,y,tt,_e,T,0n,he,o]}else if(r==="repayAndWithdrawCollateral"){if(M="blueBundlesV1RepayAndWithdrawCollateral",P=d.loanToken,I=N(t.maxRepayAssets,!0),b>I||h>0n&&I===0n)throw new i("Repayment requires a sufficient maxRepayAssets budget.");C=[d,b,h,I,w,y,tt,_e,0n,he,o]}else M="blueBundlesV1MigrateBorrowPosition",C=[d,p,y,_e,T,0n,he,o];let E=`Morpho Blue atomic ${r}: ${JSON.stringify(t)}. Allocation penalties ${x} loan-token base units; zero referral fee. Max LTV ${y}; absolute deadline ${o}. Migration adds allocation penalties to destination debt; borrowing deducts them from proceeds. Exact input approval ${I}. Existing Blue bundle authorization remains until explicitly revoked with morpho_manage. No opaque callback, permit or signature is accepted.`,Z=[...P&&I?[e.approval(P,we,I.toString(),f)]:[],e.unsignedTx({to:we,data:ua({abi:Re,functionName:M,args:C}),value:"0",chainId:f,description:E})],H=await e.preview(Z,s),F=new Map;for(let v of H.changes)if(BigInt(v.amount)<0n){let U=v.token.address.toLowerCase();F.set(U,(F.get(U)??0n)-BigInt(v.amount))}if([...F].some(([v,U])=>!P||v!==P.toLowerCase()||U>I))throw new i("Bundle preview spends outside the exact input budget.");return{txs:Z,preview:H,summary:E}}catch(r){throw new i(e.plainError(r))}}}]});import{concatHex as Bt,decodeAbiParameters as fa,encodeAbiParameters as Rt,encodeFunctionData as at,erc20Abi as Nt,getAddress as K,keccak256 as rt,zeroAddress as ye,zeroHash as ba}from"viem";var Y=K("0x6120765Ba5336150BbdDdD0Cd9108B5bFD369632"),ha=["0x90B800999e4ACd1bD20283BD450bBd2e06D91F7C","0x708d6Bf6F847202a0755bb5636bE663B174242ea"].map(e=>K(e)),nt=ae.find(e=>e.name==="take"),Ot=[nt.inputs[0]],wa=[nt.inputs[0].components[0]];function Et(e){let t=rt(Bt(["0x600b380380600b5f395ff3",Rt(wa,[e])]));return rt(Bt(["0xff",e.midnight,ba,t]))}var de=10n**18n,Gt=(e,t)=>(e+(t-1n)/2n)/t;function _t(e){if(e<0n)return 10n**36n/_t(-e);let t=693147180559945309n,s=(e+322611214989459870n)/t,r=e-s*t,n=r*r/(2n*de),l=n*r/(3n*de);return de+r+n+l<<s}function ka(e){if(e<0n||e>6744n)throw new i("Midnight tick is outside 0..6744.");return Gt(Gt(10n**36n,de+_t(4987541511039073n*(3372n-e))),10n**11n)*10n**11n}function He(e,t){if(typeof e!="string"||!/^0x([0-9a-f]{2})*$/i.test(e)||e.length>32770||t!==void 0&&e.length!==2+t*2)throw new i("Provide bounded canonical hex data.");return e}function ot(e,t){if(!Array.isArray(e)||e.length!==t)throw new i("Invalid Midnight state tuple.");return e.map(s=>{if(typeof s=="number"&&Number.isSafeInteger(s)&&s>=0)return BigInt(s);if(typeof s=="bigint"&&s>=0n)return s;throw new i("Invalid Midnight integer state.")})}var ya=e=>JSON.parse(JSON.stringify(e,(t,s)=>typeof s=="bigint"?s.toString():s)),Ht=e=>{async function t(n,l){let a=He(n,32),o=e.clientFor(f);if(await o.getChainId()!==f)throw new i("Midnight requires chain 4663.");let u=await o.getBlock(),c=(k,g=[])=>o.readContract({address:Y,abi:ae,functionName:k,args:g,blockNumber:u.number}),m=await c("toMarket",[a]);if(m.chainId!==BigInt(f)||K(m.midnight)!==Y||!R(Et(m),a))throw new i("Midnight market identity does not match the pinned chain and contract.");if(![z[f].tokens.USDG.address,z[f].tokens.WETH.address].some(k=>R(k,m.loanToken)))throw new i("This Midnight loan token needs a qualified transfer and exit fixture.");if(!m.collateralParams.length||m.collateralParams.length>128)throw new i("Invalid Midnight collateral inventory.");let[p,b,h,w]=await Promise.all([c("position",[a,l]),c("updatePositionView",[m,a,l]),c("marketState",[a]),c("isHealthy",[m,a,l])]),y=async k=>{let[g,T]=await Promise.all([o.readContract({address:k,abi:Nt,functionName:"decimals",blockNumber:u.number}),o.readContract({address:k,abi:Nt,functionName:"symbol",blockNumber:u.number})]);if(!Number.isInteger(g)||g>36||typeof T!="string")throw new i("Invalid Midnight token metadata.");return{address:K(k),decimals:g,symbol:T.replace(/[^a-zA-Z0-9.$_-]/g,"").slice(0,32),chainId:f}};return{id:a,rpc:o,block:u,market:m,read:c,token:y,loan:await y(m.loanToken),position:ot(p,6),updated:ot(b,3),state:ot(h,13),healthy:w}}let s=(n,l,a,o)=>({name:n,inputSchema:{type:"object",properties:l,required:a,additionalProperties:!1},execute:async(u,c)=>{try{if(q(c),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Midnight argument.");return await o(u,c)}catch(m){throw new i(e.plainError(m))}}});async function r(n,l,a){return{txs:n,preview:await e.preview(n,l),summary:a}}return{tools:[s("morpho_midnight_status",{marketId:{type:"string",description:"Midnight market id: 0x + 64 hex digits (bytes32)."}},["marketId"],async(n,l)=>{let a=await t(n.marketId,l),o=await Promise.all(a.market.collateralParams.map(async(m,d)=>({token:await a.token(m.token),lltvWad:m.lltv.toString(),oracle:m.oracle,assets:String(await a.read("collateral",[a.id,l,BigInt(d)]))}))),u=["configurator","feeSetter","feeClaimer","tickSpacingSetter"],c=await Promise.all(u.map(m=>a.read(m)));return{protocol:Object.fromEntries(u.map((m,d)=>[m,K(String(c[d]))])),continuousFeePerSecondWad:String(a.state[11]),tickSpacing:String(a.state[12]),settlementFeeCbps:a.state.slice(4,11).map(String),settlementFeeCbpWadScale:"1000000000000",chainId:f,midnight:Y,marketId:a.id,blockNumber:String(a.block.number),market:ya(a.market),loanToken:a.loan,collaterals:o,debtUnits:String(a.position[4]),creditUnits:String(a.updated[0]),pendingFeeUnits:String(a.updated[1]),withdrawableUnits:String(a.state[2]),healthy:a.healthy,maturity:String(a.market.maturity),matured:a.block.timestamp>a.market.maturity,warning:"Maturity does not guarantee lender liquidity. Borrowers become liquidatable after maturity even when collateralized. Lender credit may absorb borrower default losses."}}),s("morpho_midnight_take",{offer:{type:"string",description:"ABI-encoded Offer struct, never transaction calldata."},ratifierData:{type:"string",description:"Hex proof data (0x...) that the offer's pinned ratifier uses to confirm the maker approved this offer."},units:A("Fixed debt units to trade, as a decimal string below 2^128. The asset cost or proceeds follow from the offer price; maxAssets and minAssets bound them."),maxAssets:A('Most loan token you will spend when buying credit, in base units of the market loan token (read its decimals). Example: "1000000" = 1 USDG.'),minAssets:A('Least loan token you must receive when selling credit or borrowing, in base units of the market loan token. Example: "1000000" = 1 USDG.')},["offer","ratifierData","units","maxAssets","minAssets"],async(n,l)=>{let a=He(n.offer),[o]=fa(Ot,a);if(!R(Rt(Ot,[o]),a))throw new i("Offer encoding is not canonical.");let u=await t(Et(o.market),l),c=N(n.units),m=N(n.maxAssets,!0),d=N(n.minAssets,!0),p=He(n.ratifierData);if(c>=1n<<128n||R(o.maker,l)||o.callback!==ye||o.callbackData!=="0x"||!ha.includes(K(o.ratifier)))throw new i("Use a non-self offer with a pinned ratifier and no maker callbacks. Callback routes need a separate qualified builder.");if(u.block.timestamp<o.start||u.block.timestamp>o.expiry||o.expiry<o.start)throw new i("The Midnight offer is not currently live.");if(o.buy&&o.receiverIfMakerIsSeller!==ye||!o.buy&&o.receiverIfMakerIsSeller===ye)throw new i("Invalid offer seller receiver.");if(o.buy&&u.block.timestamp>u.market.maturity&&c>u.updated[0])throw new i("Post-maturity sales cannot increase this wallet\u2019s debt.");let b=await u.read("settlementFee",[u.id,u.market.maturity>u.block.timestamp?u.market.maturity-u.block.timestamp:0n]),h=ka(o.tick);if(b>h&&o.buy)throw new i("Settlement fee exceeds the offer price.");let w=o.buy?h-b:h,y=w+b,k=v=>o.buy?v/de:(v+de-1n)/de,g=k(c*y),T=k(c*w);if(o.buy?T<d||T===0n:g>m||g===0n)throw new i("Midnight proceeds/spend do not fit the requested bounds.");let x=await u.read("consumed",[o.maker,o.group]);if(o.maxAssets===0n==(o.maxUnits===0n)||x+(o.maxAssets?o.buy?g:T:c)>(o.maxAssets||o.maxUnits))throw new i("Midnight offer capacity is exhausted or invalid.");if(u.state[11]>o.continuousFeeCap||o.tick%u.state[12]!==0n)throw new i("Offer fee cap or market tick spacing no longer permits execution.");let M=await u.read("isAuthorized",[o.maker,o.ratifier]),C=[{type:"function",name:"isRatified",stateMutability:"view",inputs:[nt.inputs[0],{type:"bytes"},{type:"address"}],outputs:[{type:"bytes32"}]}],P=await u.rpc.readContract({address:o.ratifier,abi:C,functionName:"isRatified",args:[o,p,l],blockNumber:u.block.number});if(M!==!0||P!==rt(new TextEncoder().encode("morpho.midnight.callbackSuccess")))throw new i("The maker has not authorized and ratified this exact offer.");let I=at({abi:ae,functionName:"take",args:[o,p,c,l,o.buy?l:ye,ye,"0x"]}),E=`Midnight ${o.buy?"sell credit or borrow":"buy credit or reduce debt"}: ${c} fixed debt units; ${o.buy?`receive ${T}`:`spend ${g}`} ${u.loan.symbol} base units (token ${u.loan.address}, decimals ${u.loan.decimals}). Maturity ${u.market.maturity} Unix seconds; offer expiry ${o.expiry}. A borrower can lose collateral after maturity; lender withdrawal depends on repayments and bears default losses. No lender signature or callback is created. Bounds are rechecked locally; the take calldata fixes the offer and units. Exact buyer approval caps wallet spending.`,Z=[...o.buy?[]:[e.approval(u.loan.address,Y,g.toString(),f)],e.unsignedTx({to:Y,data:I,value:"0",chainId:f,description:E})],H=await r(Z,l,E),F=H.preview.changes.filter(v=>v.token.chainId===f&&R(v.token.address,u.loan.address)).reduce((v,U)=>v+BigInt(U.amount),0n);if(o.buy?F<T:F!==-g)throw new i("Midnight preview does not match the exact quoted cash flow.");return H}),s("morpho_midnight_action",{marketId:{type:"string",description:"Midnight market id: 0x + 64 hex digits (bytes32)."},operation:{enum:["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"],description:"Action: add or remove collateral, repay debt, withdraw matured credit, refresh the position, or claim continuous fees (fee claimer only)."},amount:A('Amount in base units of the relevant token: the collateral token for collateral operations, else the loan token (read decimals). Example: "1000000" = 1 USDG.'),collateralIndex:{type:"integer",minimum:0,maximum:127,description:"Zero-based position of the collateral in the market collateral list; required for supplyCollateral and withdrawCollateral only."}},["marketId","operation"],async(n,l)=>{let a=await t(n.marketId,l),o=n.operation;if(!["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"].includes(String(o)))throw new i("Choose a finite Midnight position operation.");let u,c,m=a.loan,d=0n;if(o==="updatePosition"){if(n.amount!==void 0||n.collateralIndex!==void 0)throw new i("Position update takes no amount or collateral index.");u=[a.market,l]}else if(o==="claimContinuousFee"){if(d=N(n.amount),n.collateralIndex!==void 0||K(String(await a.read("feeClaimer")))!==K(l))throw new i("This wallet lacks the Midnight fee claimer role or supplied an unused collateral index.");u=[a.market,d,l]}else{if(d=N(n.amount),d>=1n<<128n)throw new i("Midnight position amount exceeds uint128.");if(o==="supplyCollateral"||o==="withdrawCollateral"){if(!Number.isInteger(n.collateralIndex)||Number(n.collateralIndex)<0||Number(n.collateralIndex)>=a.market.collateralParams.length)throw new i("Choose a current collateral index.");let h=BigInt(String(n.collateralIndex)),w=await a.token(a.market.collateralParams[Number(h)].token);if(m=w,o==="withdrawCollateral"&&d>await a.read("collateral",[a.id,l,h]))throw new i("Insufficient Midnight collateral.");u=o==="supplyCollateral"?[a.market,h,d,l]:[a.market,h,d,l,l],o==="supplyCollateral"&&(c=w)}else{if(n.collateralIndex!==void 0)throw new i("This operation takes no collateral index.");if(o==="repay"&&d>a.position[4]||o==="withdraw"&&(d>a.updated[0]||d>a.state[2]))throw new i("Amount exceeds current debt, credit or available repayment liquidity.");u=o==="repay"?[a.market,d,l,ye,"0x"]:[a.market,d,l,l],o==="repay"&&(c=a.loan)}}let p=`Midnight ${o}: ${d} ${m.symbol} base units (token ${m.address}, decimals ${m.decimals}) on ${a.id}; beneficiary ${l}; maturity ${a.market.maturity} Unix seconds. No callbacks or delegation. Withdrawal can fail if collateral health or lender liquidity changes.`,b=[...c?[e.approval(c.address,Y,d.toString(),f)]:[],e.unsignedTx({to:Y,data:at({abi:ae,functionName:String(o),args:u}),value:"0",chainId:f,description:p})];return r(b,l,p)}),s("morpho_midnight_manage",{operation:{type:"string",enum:["setConsumed","setIsAuthorized","setConfigurator","setFeeSetter","setFeeClaimer","setTickSpacingSetter","enableLltv","enableLiquidationCursor","setMarketTickSpacing","setMarketSettlementFee","setMarketContinuousFee","setDefaultSettlementFee","setDefaultContinuousFee","claimSettlementFee"],description:"Midnight management function name; role-gated except setConsumed and setIsAuthorized, which act on this wallet."},values:{type:"array",maxItems:3,description:"Ordered arguments for the chosen operation, as in the Midnight ABI: decimal strings for integers (base units), 0x addresses or bytes32, or booleans.",items:{oneOf:[{type:"string"},{type:"boolean"}]}}},["operation","values"],async(n,l)=>{let a={setConfigurator:"configurator",setFeeSetter:"configurator",setFeeClaimer:"configurator",setTickSpacingSetter:"configurator",enableLltv:"configurator",enableLiquidationCursor:"configurator",setMarketTickSpacing:"tickSpacingSetter",setMarketSettlementFee:"feeSetter",setMarketContinuousFee:"feeSetter",setDefaultSettlementFee:"feeSetter",setDefaultContinuousFee:"feeSetter",claimSettlementFee:"feeClaimer"};if(typeof n.operation!="string"||!["setConsumed","setIsAuthorized",...Object.keys(a)].includes(n.operation)||!Array.isArray(n.values))throw new i("Choose a finite Midnight management operation and ordered values.");let o=n.operation,u=ae.find(p=>p.name===o);if(n.values.length!==u.inputs.length)throw new i("Provide the exact ordered operation values.");let c=e.clientFor(f);if(await c.getChainId()!==f)throw new i("Midnight requires chain 4663.");let m=u.inputs.map((p,b)=>{let h=n.values[b];if(p.type==="bool"){if(typeof h!="boolean")throw new i("Use boolean management values.");return h}if(p.type==="address")return Ee(h,"Use explicit management addresses.",Oe);if(p.type==="bytes32")return He(h,32);if(/^uint/.test(p.type)){let w=N(h,!0);if(w>=1n<<BigInt(p.type.slice(4)))throw new i("Management integer exceeds its ABI width.");return w}throw new i("Unsupported management argument type.")});if(o==="setConsumed"||o==="setIsAuthorized"){if(!R(String(m[2]),l))throw new i("Midnight management is bound to this wallet.")}else{let p=await c.readContract({address:Y,abi:ae,functionName:a[o]});if(typeof p!="string"||K(p)!==K(l))throw new i("This wallet lacks the Midnight configuration, fee or tick role.")}let d=`Midnight ${o}, ordered values ${JSON.stringify(n.values)}. ${o==="setIsAuthorized"&&m[1]?"This grants authority over all Midnight positions, cancellations and further delegation, without an amount cap. Revoke with false when done.":""}${o==="setConsumed"?"Consumption only increases; setting uint128 maximum permanently cancels this offer group.":""}`;return r([e.unsignedTx({to:Y,data:at({abi:ae,functionName:o,args:m}),value:"0",chainId:f,description:d})],l,d)})]}};import{decodeAbiParameters as re,encodeAbiParameters as ga,encodeFunctionData as G,erc20Abi as it,getAddress as L,isAddress as Fe,keccak256 as Sa,parseAbi as Ve,parseAbiParameters as J}from"viem";var De="morpho",Aa="https://api.morpho.org/graphql",$=L(z[f].morpho.morpho_blue.address),xa=L(z[f].morpho.adaptive_curve_irm.address),Ia=L(z[f].morpho.USDG.address),me=L(z[f].morpho.WETH.address),Ta=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],Ma={"oak-recorded":"Oak recorded chain observations (block 100362239).","morpho-listed":"Morpho API (POST https://api.morpho.org/graphql, markets where chainId_in [4663]) returned listed: true, fetched 2026-10-31 UTC.",longbow:"Longbow market list: Longbow MCP list_markets/get_market (https://mcp.longbow.credit/mcp, named on https://longbow.cash/mcp) and the live market list on https://longbow.cash/earn, fetched 2026-10-31 UTC; each ID re-read on chain.",netnet:"NetNet Credit: six stock-token market IDs printed at https://docs.netnet.capital/credit, plus the Loopback wsNET/USDG market returned by NetNet's Turbo router marketId() and Credit adapter marketIds(6); fetched 2026-10-31 UTC."},lt=[{marketId:"0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2",label:"WETH/USDG 77%",source:"oak-recorded"},{marketId:"0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8",label:"USDG/WETH",source:"oak-recorded"},{marketId:"0x0309c02dabf0be02682af1a2bde9a457f4df0f0b6bc889cde3f948e5315e4114",label:"spUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x10151e2ac82a820153520d9d77d56de1c84775e23b79bdc11e2e34282d9afa10",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x127353ba63e08f74d8e9ce8a1c2b41b5f89c7167135b1c09fbed34a71b4cb06b",label:"WETH/USDG 86%",source:"morpho-listed"},{marketId:"0x1a31d1c8c05a98b94777663912e4166bf50f3fcdc9c3c3d29deb55634ac58239",label:"PONS/USDG 62.5%",source:"morpho-listed"},{marketId:"0x1efd13a2d1dc66a2466e7c25820537028e604791f00454d9c686fdfbf70f404d",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x21ea2a012b888120e328775c2a7bf6fb4619cf4c4c631ad1c9b6db51f8882d5a",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x22e4598e5cc16cff0056e72d61c5f1f2f8bf5bbffc22da5277ab196939c8a59e",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x66306c087add8907752320b309934abcc354d21626de8115c79df49d9c214edc",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x69400cfe81f2ae381b9a9f27076a4d637338379d999e9ffdfbde52f0876312ee",label:"META/USDG 62.5%",source:"morpho-listed"},{marketId:"0x7408b08b03e05ffd2d21c797489a0e77a28e4bb36acb4e827c69e805d06272b4",label:"GOOGL/USDG 77%",source:"morpho-listed"},{marketId:"0x7c1e38bf461da47df9805ae9b7e97a12ec023625a1f92d2a403b3b9a92260894",label:"CASHCAT/USDG 62.5%",source:"morpho-listed"},{marketId:"0x919a9b6b94dae7c86620eaf7a08e597aae8a4c3a9e9c7671771fbaf62b6b61c7",label:"syrupUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x93ed7865910b09f5a2e0dbfd4670c2d3bc1da9647f7c68e7975f37f497898cdb",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x947ae981cc823024ea00b602f6ea72d049cac05d66ef096198ceeb998651c175",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0x95312f02c1dae8407b2c80468a5657a9bd19c45ac277f1a61aa52c11444c5314",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xba01f6625137b692c5dd86afb8e654b4016d7b64e36dfca4124e84bef98bc4d2",label:"GOOGL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xc845da65a020ddca5f132efa8fea79676d8edfdea504226a4c01e7a9e34cddd6",label:"USDe/USDG 91.5%",source:"morpho-listed"},{marketId:"0xcaa167af7ba0422c76424fae56167b7db25bf19f4f435215e6dd7d06a943bdac",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe29c7d3790037800101ecbad9c45de2067698d206cbcab7c25069a9f43c9eb98",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe5a6d99c3721ef2ab00fb16f0ad226bc7c87a90394f82e27dc6bbca4b1d95c5d",label:"AI/USDG 62.5%",source:"morpho-listed"},{marketId:"0xeb1739b2a69dd22a4285d366a06698a01018b37c24d2994fefe19cc72f313613",label:"SPY/USDG 77%",source:"morpho-listed"},{marketId:"0xf5ff7d546af5e72f3912d2aa723088fd0bf66fddc158714995637714d9db6e4c",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xaa586d26a6fe62d9c0f0948fede6e2130500ac7a655587447e2d4a37e6330589",label:"wsNET/USDG 62.5% (NetNet Loopback)",source:"netnet"},{marketId:"0x8b16891f032a93b771347c9cb470a780e6699dd701553d3402aa3cdba6189c3e",label:"NVDA/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x9b4b47cdf7e295341c6c6cdfd3efb9805c4a5b3d580dba0c0c39d3a4232b297b",label:"SPCX/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0xdeb4782d012d5fd3b24962538c2f6559049d70bda4dabd2e4212dacb96c28d45",label:"AAPL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x7fa81b10e5d21b2e4c571f862442bc11aff2ed14f02335868d0ff933fd40d0ba",label:"GOOGL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x2e1859aa8f143b7220088f80562c6dfe0bf8e52b87d9cedf8da8805f231994ce",label:"MSFT/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x3ebd43d91c3960a9fac32bedd5c60428e0e414de5bdd67fda770207afb0eb615",label:"COIN/USDG 38.5% (NetNet Credit)",source:"netnet"},{marketId:"0x26f3bd5919ba0e6ea6f4bca1b8bd95ce29cbe3aad4ef824fb007570eac35103b",label:"cbBTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb095654f06f4d17d4fc010c2d89a107649e3c5b58e53a3812d1736c95e63e3f8",label:"NVDAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x947c05e7c0fa3ba187d57db710d04ba8be4fef53baba0cfbe71ce61b34a1367d",label:"SPCXon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf8f0b5badf06192908bc47af32b93742d9b4fb6072d388cb183ff7849ee6534c",label:"SPYon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x26c80a00f8facc6b081989965d89cedc274b90b81be660e69245a74e5384f5de",label:"METAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xeefec6c3e5cb7df1f2366ea7cf96a583081205b9720e807d2868d9866a702229",label:"GOOGLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf511a080dcb4d0a3b9d6aebb06e24afa011cda87f9f71ada70c60f8220e94f35",label:"AAPLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xa87da1cc931faa945a41861cc9c90076772ceeae9a663836df6b265c4f30106d",label:"MSTRon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x0279ea145eff84ed2ffd3b1ed1f2aca333060d9cef6fdd48bd21073c13ec86bf",label:"CRCLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xff2063ef18bc5f71867c56d6d3290b61f3da1d010c8a0552bdb7995cfad8cacc",label:"TSLAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x83d542605940b5495ef38d4b62a39293766a486a24e5c67930f41acd919cf1d1",label:"QQQon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9b01d5ad5ce8e477510854132cc47853f6e82a708c9c4723887550412f4ee522",label:"GMEon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8b2af4d69ad861a4099b995b6279aeaf6a905225a0ee889bce424c7faf19b7d9",label:"AMZN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4edbd2f2f3b33bc5f80ab588def67fab8c10945fc99f855d80ff4bef2c4aa1f0",label:"SLV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x7e6ebfdc58a893a5cddba0fba0483baf4fac2efece627ad50821dbe27d6f9738",label:"GOOGL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x30a2a5f1a098b23ed91eadc4529a8d1c967f2cdc2e40a709f3a5992004b01ac0",label:"AAPL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x14973a168cf6c6b1148309f5d567c255b292863ffe9cca59f4284e1426636f00",label:"RKLB/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf049167e6bf18a1b41b8e2acefcf7bc9b13ea013d8d65c7fbc7cbaeb3fe9b4e2",label:"NBIS/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8114b65dfc5e64222103e5588de261eca9defd25f47ea4ae2f91d49fe4fa2993",label:"CLSK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x96d3d5f9bc842e4c8a935c5628abd02fb0e10115560c35a9add768781434f471",label:"CRWV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x1b3555f7c1273688f01ae82da7dc8e508e6a7841ec0038dbb15767154a277b86",label:"EWY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x039503b6308d6d818d181e626d3fbc667d6e68393c3d74332a6124cd2dd6e755",label:"CASHCAT_LEGACY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x597227ca652ea5e8afb6e4801ecd766a4d6eb9b3b9fafa9127ba88a8b1f19629",label:"SPCX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x50bc39b5722fb5634c436d74c6787f3c125b879e7b73cf9e9ecc01bbb57b8e55",label:"SPY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x315b99abb698487891243a84afd28a5ff56fe02143f203c03edd3f103936bf60",label:"QQQ/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4979137c23c8fb519cd507adc290944c3c2120e8a3191547531fced28360e9c2",label:"GME/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x6b8a1f62d88d1cd1e8de609aef07cafc8226172ba703e57c52c3730350e61df1",label:"USO/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xafc86936af4f7edf083eb2550b8c42311b83c685982742b9271b309a58268855",label:"MSFT/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf6f3dbe0a19e948147e79e66502c6b05709d8dfde977fec7db1528fc8f0ebdfa",label:"SGOV/USDG 86% (Longbow)",source:"longbow"},{marketId:"0x2ab6a14c9f68d4216dcb3b4e6ed607cf82f2e6badfa2bd5618d7f69d012d7fab",label:"USAR/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb41b34c5989420ad080e79363a9cfe3e23bec7459fcd2d88029250da370288df",label:"TSLA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4d2075836fd32183b10e5be1b383f6430de859df6d2bd5ec5b859970c4dd14e8",label:"AMD/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9df4f54a2e46b35bd326cec97dbabc4203fa6c64a8e4182128f277adba8fefaf",label:"MU/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb5ba72c0d55c353fa37c0bea104eb117afb2f4934473bcb736d2218ae5686746",label:"PLTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xda5584635e8b14ea18f674dbe4243365505910fefd8e3aa1ac9bfaac0eba74e8",label:"INTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x74fece475178af9e06d31fb64f405046a305f8f0abc588782f596d6f261c1fbb",label:"SNDK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xee04847a312224d551d2267bb5c2c2695777af5fd1f05347bdcca397e8f54336",label:"ORCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x508b47fb12dbb8747644d4436aae65489b5f2819936adefc8a591323f64a5b01",label:"COIN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x243ac165f79a75a0590d2e994ffa9e260b70292fd1ca134ace95f3640895b19f",label:"TSM/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x01baec96478004fc7b74c8dfe38abef8d716fea59ffd481b6ec74db915d3bc80",label:"MSTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf0959f62e748938cf260ca6fe7cb21a412e0a6643913460f4a6770c3f4b90af6",label:"CRCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xbe881499e682850931951c998e76cfbf38c7979b1beeae7cbbb97a39b3336a07",label:"ASML/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xdd578ca54b4ef6a7827c6e9fc06905699a577f6e2f00712853d8aab13383bc38",label:"BABA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xd8b502d5c43f6e5cfff7f938c7ef18e684f114fb5b362611981144397e5d5aef",label:"DELL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x003390b057d753bd839981a0d45f9a567aa0b0ed6373fd42e951eac8ee86c2ba",label:"RGTI/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xc6e16cff2bcf185639562ab937b7a1c381522768ff16aefc85a25ff6ab1c45ea",label:"AI/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xaba3ac501ce4c6b80c08ed0dba19e1ac0de495f17af3ed692a38e92d176a6c9e",label:"PONS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8097c1d1000eb657e75265384137041ac92856c8dc0b72c99569c3681320a430",label:"DELTA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6e6762ae397a2b3f2500ea2f48f8adce0eadfbf54cbc37f6108602e907e844ad",label:"INDEX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x378713071c58206c6a826287d0051bcae113d83d6e3d3b6370b7e73128d06162",label:"STONKBROKER/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x2695be2638c98241c887e4cad4eeba0f01137205f46b9e302edab04b5fee0570",label:"AVGO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6c12c02536aa27831f713d658b59f74e149cc62b48528cb74455e79fab32f772",label:"GLD/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x298e8ff9b31f22be90507bc61b55e66ab93e78b55a60593035e309ed93137cb8",label:"RDDT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb33399a677e1a21152fa9969f02c57a7a342e692ec45608a3fa0d3d92519c343",label:"COST/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x3be7fe1b6b439cfeb737d9921e9b83c92095a23a4f50aeee0d6d04f44446170f",label:"DJT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0066bc47b87597993af0bca6f526175c0abae011b764d4bf12a3def45e1f4e78",label:"NFLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8c170f5c5df593791640ac9fbac297d59d08c2e92e86f38fe52d38e929e60fa3",label:"AMC/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0f18d4fd8d86bd4d100b867b67e1fd38c80981fcd43e442313c2d5408da9352d",label:"LLY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x7d4313cf1b0ede39395a2c7495dc1b1b47370caf51f70571d927f22e715e5f58",label:"LULU/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xa85928d77bd25cc348e13ea6587b8b3ca3793f4af5e5db8ca07d0f20fd5cfa99",label:"IBM/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x9d61e320efb766ce5c375032b399f08afe644b095a9cb0b2d6d1f6ab68399a6f",label:"F/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x43c51f6ff44ab406ab9c97cb5512c881f4a7498209f94bbcfd874d8f97fad79d",label:"HIMS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe6284cf12d0603aee18ff5ab412e262cf99f120e967579111d7a51f37f276f54",label:"TTWO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe8d9b45cdbedc4401a3145be7726c9f72b715e03c5399c961439f11636ee9fb6",label:"MRNA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x46eea143d473cdb8587505f8886dad452037f285f7729a7763e8c233c63b2e8e",label:"RIVN/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8338aed363a309039b2f271a83558831e7e445f2d13c6e72c576ec0b8a969415",label:"RBLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x4e92b336ecad6c842be20ae2ae27b28b3cf5ced6c5388a808167c03a8d75fdf8",label:"SPY/WETH 38.5% (Longbow)",source:"longbow"},{marketId:"0x141c2b1d2bbecf7f8a76563307d7e5bf586457e873c3d97c4bb1502e57b77952",label:"NVDA/WETH 38.5% (Longbow)",source:"longbow"}],va=new Map(lt.map(e=>[e.marketId.toLowerCase(),e]));function j(e){return va.get(e.toLowerCase())}function ct(e){let t=j(e);return t?{actions:"enabled",label:t.label,source:Ma[t.source]}:{actions:"read-only",reason:"Not in Oak's verified Morpho market registry; Oak builds no transactions for it."}}var qt=20,Ue=120n,ze=1000000n,We=1n,Se=10n**18n,Pa=10n**36n,jt=(1n<<128n)-1n,Ca=(1n<<256n)-1n,X=Ve(["function idToMarketParams(bytes32 id) view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv)","function market(bytes32 id) view returns (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee)","function position(bytes32 id, address user) view returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral)","function supplyCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, bytes data)","function withdrawCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, address receiver)","function borrow((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsBorrowed, uint256 sharesBorrowed)","function repay((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsRepaid, uint256 sharesRepaid)","function supply((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsSupplied, uint256 sharesSupplied)","function withdraw((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn)"]),La=Ve(["function price() view returns (uint256)"]),Da=Ve(["function borrowRateView((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee) market) view returns (uint256)"]),Kt=Ve(["function deposit() payable"]);function pe(e){return{loanToken:e.loanToken,collateralToken:e.collateralToken,oracle:e.oracle,irm:e.irm,lltv:e.lltv.toString()}}function $e(e,t){return e===0n?0n:(e+t-1n)/t}function Ua(e,t,s){return e*(s+ze)/(t+We)}function $a(e,t,s){return $e(e*(s+ze),t+We)}function ut(e,t,s){return e*(t+We)/(s+ze)}function se(e,t,s){return $e(e*(t+We),s+ze)}function Ae(e,t,s){return e*t/Pa*s/Se}function Ba(e,t,s){return t.startsWith("-")?`-${e.formatAmount(t.slice(1),s)}`:e.formatAmount(t,s)}function xe(e,t){let s=[],r={};for(let n of t.changes){let l=Ba(e,n.amount,n.token.decimals);s.push({token:n.token,amount:n.amount,formattedAmount:l}),r[n.token.address.toLowerCase()]=l}return{formattedChanges:s,formattedNetOutflows:r}}function Qt(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new i("Morpho marketId must be a 32-byte hex string.");return e.toLowerCase()}function je(e){if(!e||typeof e!="object")throw new i("Morpho marketParams must be an object.");for(let a of[e.loanToken,e.collateralToken,e.oracle,e.irm])if(typeof a!="string"||!Fe(a,{strict:!1}))throw new i("Morpho marketParams contains an invalid address.");let t=L(e.loanToken),s=L(e.collateralToken),r=L(e.oracle),n=L(e.irm),l=typeof e.lltv=="bigint"?e.lltv:Le(String(e.lltv));if(t===te||s===te||r===te)throw new i("Morpho marketParams loan, collateral, and oracle addresses must be non-zero.");if(l<=0n||l>=Se)throw new i("Morpho marketParams LLTV must be between 0 and 1e18.");return{loanToken:t,collateralToken:s,oracle:r,irm:n,lltv:l}}function ke(e){let t=je(e),s=ga(J("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return Sa(s)}function dt(e){let t=e.toLowerCase();return t===ht.toLowerCase()||t===wt.toLowerCase()||t===te.toLowerCase()}function Ie(e,t){let s=t??e.wallet;if(!s)throw new i("Provide a valid wallet address.");return q(s),L(s)}async function ne(e,t,s){if(typeof e.call=="function"){let r=await e.call({to:t,data:s});if(r&&typeof r.data=="string")return r.data}if(typeof e.request=="function"){let r=await e.request({method:"eth_call",params:[{to:t,data:s},"latest"]});if(typeof r=="string")return r}throw new i(`Unable to execute eth_call on contract ${t}.`)}function Xt(e){return typeof e=="string"&&/^[A-Za-z0-9$._+-]{1,32}$/.test(e)?e:"UNKNOWN"}async function Q(e,t,s=f){if(q(t),dt(t))return{...kt,chainId:s};let r=L(t),n=r.toLowerCase();if(s===f){if(n===Ia.toLowerCase())return yt;if(n===me.toLowerCase())return gt}let[l,a]=await Promise.all([ne(e,r,G({abi:it,functionName:"symbol"})),ne(e,r,G({abi:it,functionName:"decimals"}))]),[o]=re(J("string"),l),[u]=re(J("uint8"),a);return{address:r,symbol:Xt(o),decimals:Number(u),chainId:s}}async function Yt(e,t){let s=await ne(e,$,G({abi:X,functionName:"idToMarketParams",args:[t]})),[r,n,l,a,o]=re(J("address, address, address, address, uint256"),s);return{loanToken:L(r),collateralToken:L(n),oracle:L(l),irm:L(a),lltv:o}}async function Jt(e,t){let s=await ne(e,$,G({abi:X,functionName:"market",args:[t]})),[r,n,l,a,o,u]=re(J("uint128, uint128, uint128, uint128, uint128, uint128"),s);return{totalSupplyAssets:r,totalSupplyShares:n,totalBorrowAssets:l,totalBorrowShares:a,lastUpdate:o,fee:u}}async function Te(e,t,s){let r=await ne(e,$,G({abi:X,functionName:"position",args:[t,L(s)]})),[n,l,a]=re(J("uint256, uint128, uint128"),r);return{supplyShares:n,borrowShares:l,collateral:a}}async function Ke(e,t){let s=await ne(e,L(t),G({abi:La,functionName:"price"})),[r]=re(J("uint256"),s);return r}async function Na(e,t,s){if(t.irm===te)return 0n;let r=await ne(e,L(t.irm),G({abi:Da,functionName:"borrowRateView",args:[t,s]})),[n]=re(J("uint256"),r);return n}function Qe(e,t,s){let r=s>e.lastUpdate?s-e.lastUpdate:0n,n=t*r,l=$e(n*n,2n*Se),a=$e(l*n,3n*Se);return e.totalBorrowAssets+$e(e.totalBorrowAssets*(n+l+a),Se)}async function Be(e,t,s,r=0n){let[n,l]=await Promise.all([e.getBlock({blockTag:"latest"}),Na(e,t,s)]),a=BigInt(Math.ceil(Date.now()/1e3)),o=(n.timestamp>a?n.timestamp:a)+r;return{totalBorrowAssets:Qe(s,l,o),accruedThrough:o,rate:l}}async function Zt(e,t,s){let r=await ne(e,L(t),G({abi:it,functionName:"balanceOf",args:[L(s)]})),[n]=re(J("uint256"),r);return n}async function fe(e,t,s=!1){let r=t.marketId,n=t.marketParams;if(!r&&!n)throw new i("Provide either marketId or marketParams for the Morpho Blue market.");let l=n?je(n):void 0,a=l?ke(l):void 0,o=r!==void 0?Qt(r):void 0;if(o&&a&&o!==a.toLowerCase())throw new i(`MarketParams tuple hash (${a}) does not match marketId (${o}).`);let u=(o??a).toLowerCase();if(s&&!j(u))throw new i(`Morpho actions require a known market from Oak's verified registry, which pins its oracle. Find one with morpho_status {"discover":true}; other markets are read-only.`);let[c,m]=await Promise.all([Yt(e,u),Jt(e,u)]);if(c.loanToken===te||c.collateralToken===te||c.lltv===0n||m.lastUpdate===0n)throw new i(`Morpho market ${u} is not initialized on chain ${f}.`);let d=ke(c);if(d.toLowerCase()!==u.toLowerCase())throw new i(`On-chain idToMarketParams tuple hash (${d}) does not match marketId (${u}).`);if(l&&!(l.loanToken.toLowerCase()===c.loanToken.toLowerCase()&&l.collateralToken.toLowerCase()===c.collateralToken.toLowerCase()&&l.oracle.toLowerCase()===c.oracle.toLowerCase()&&l.irm.toLowerCase()===c.irm.toLowerCase()&&l.lltv===c.lltv))throw new i(`Provided marketParams tuple does not match on-chain idToMarketParams for ${u}.`);return{marketId:u,marketParams:c,marketState:m}}function Me(e){if(e.assets!==void 0&&e.amount!==void 0)throw new i("Specify either assets or amount, not both.");let t=e.assets??e.amount;if(typeof t!="string")throw new i("Provide an amount as a base-unit integer string.");let s=Le(t);if(s<=0n||s>jt)throw new i("Asset amount must be greater than zero and fit in uint128.");return s}function ve(e,t){for(let s of["onBehalf","receiver"])if(e[s]!==void 0&&(typeof e[s]!="string"||e[s].toLowerCase()!==t.toLowerCase()))throw new i(`Morpho ${s} must be the wallet; overrides are not supported.`);if(e.data!==void 0&&e.data!=="0x")throw new i("Morpho callback data must be empty (0x).")}async function Oa(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=e.clientFor(f),{marketId:a,marketParams:o}=await fe(l,t,!0),u=await Q(l,o.collateralToken,f),c=o.collateralToken.toLowerCase()===me.toLowerCase(),m=typeof t.collateralToken=="string"?(q(t.collateralToken),L(t.collateralToken)):void 0,d=W("wrapNative",t.wrapNative)===!0||m!==void 0&&dt(m);if(m&&!dt(m)&&m.toLowerCase()!==o.collateralToken.toLowerCase())throw new i(`Collateral token ${m} does not match market collateral ${o.collateralToken}.`);if(d&&!c)throw new i("Native ETH wrapping is only supported when market collateralToken is WETH.");let p=Me(t),b=p.toString(),h=e.formatAmount(b,u.decimals),w=[];d&&w.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:b,description:`Wrap ${h} ETH into WETH at ${me}.`})),w.push(e.approval(o.collateralToken,$,b,f)),w.push(e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"supplyCollateral",args:[o,p,n,"0x"]}),value:"0",description:`Supply ${h} ${u.symbol} (${b} base units) collateral to Morpho market ${a}.`}));let y=await e.preview(w,r),{formattedChanges:k,formattedNetOutflows:g}=xe(e,y);return{action:"morpho_supply_collateral",chainId:f,marketId:a,marketParams:pe(o),collateralToken:u,assets:b,formattedAssets:h,onBehalf:n,txs:w,summary:`${d?`Send ${h} ETH to wrap into WETH. `:""}Supply ${h} ${u.symbol} collateral to Morpho Blue market ${a}.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ea(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,a=e.clientFor(f),{marketId:o,marketParams:u,marketState:c}=await fe(a,t,!0),[m,d,p,b]=await Promise.all([Q(a,u.loanToken,f),Te(a,o,n),Ke(a,u.oracle),Be(a,u,c,Ue)]),h=Me(t),w=h.toString(),y=e.formatAmount(w,m.decimals),k=c.totalSupplyAssets>c.totalBorrowAssets?c.totalSupplyAssets-c.totalBorrowAssets:0n;if(h>k)throw new i(`Insufficient market liquidity: requested ${w} base units, available ${k.toString()} base units.`);let g=Ae(d.collateral,p,u.lltv),T=se(d.borrowShares,b.totalBorrowAssets,c.totalBorrowShares);if(d.collateral===0n||T+h>g)throw new i(`Insufficient collateral or unhealthy borrow: total debt ${(T+h).toString()} exceeds max borrow ${g.toString()} base units.`);let x=$a(h,b.totalBorrowAssets,c.totalBorrowShares),C=[e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"borrow",args:[u,h,0n,n,l]}),value:"0",description:`Borrow ${y} ${m.symbol} (${w} base units) from Morpho market ${o}.`})],P=await e.preview(C,r),{formattedChanges:I,formattedNetOutflows:E}=xe(e,P);return{action:"morpho_borrow",chainId:f,marketId:o,marketParams:pe(u),loanToken:m,assets:w,formattedAssets:y,borrowShares:x.toString(),onBehalf:n,receiver:l,txs:C,summary:`Borrow ${y} ${m.symbol} from Morpho Blue market ${o}.`,preview:P,formattedChanges:I,formattedNetOutflows:E}}async function Ga(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=e.clientFor(f);if(t.shares!==void 0){let I=Le(t.shares);if(I<=0n||I===Ca||I>jt)throw new i("Morpho Blue core does not accept maxUint256 or out-of-range share sentinels; pass exact position.borrowShares.")}if(W("repayAll",t.repayAll)===!0&&(t.shares!==void 0||t.assets!==void 0||t.amount!==void 0))throw new i("Specify repayAll alone, without shares or assets/amount.");if(t.shares!==void 0&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify either assets/amount or shares for Morpho repay, not both.");let{marketId:a,marketParams:o,marketState:u}=await fe(l,t,!0),[c,m,d]=await Promise.all([Q(l,o.loanToken,f),Te(l,a,n),Zt(l,o.loanToken,r)]);if(m.borrowShares===0n)throw new i(`Position has no active borrow debt on Morpho market ${a}.`);let p=0n,b=0n;if(W("repayAll",t.repayAll)===!0)b=m.borrowShares;else if(t.shares!==void 0){let I=Le(t.shares);if(I>m.borrowShares)throw new i(`Repay shares (${I.toString()}) exceed current position borrowShares (${m.borrowShares.toString()}).`);b=I}else p=Me(t);let h=b>0n?await Be(l,o,u,Ue):void 0,w=b>0n?se(b,h.totalBorrowAssets,u.totalBorrowShares):p;if(d<w)throw new i(`Insufficient loan token balance for repayment: wallet holds ${d.toString()} base units, but ${w.toString()} base units are required (including accrued interest).`);let y=w.toString(),k=e.formatAmount(y,c.decimals),g=e.approval(o.loanToken,$,y,f),T=e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"repay",args:[o,p,b,n,"0x"]}),value:"0",description:b>0n?`Repay ${b.toString()} borrow shares (${k} ${c.symbol}) on Morpho market ${a}.`:`Repay ${k} ${c.symbol} (${p.toString()} base units) on Morpho market ${a}.`}),x=[g,T],M=await e.preview(x,r),{formattedChanges:C,formattedNetOutflows:P}=xe(e,M);return{action:"morpho_repay",chainId:f,marketId:a,marketParams:pe(o),loanToken:c,repayAssets:p.toString(),repayShares:b.toString(),requiredAssets:y,...h?{accruedThrough:h.accruedThrough.toString(),borrowRatePerSecond:h.rate.toString(),inclusionSeconds:Ue.toString()}:{},formattedRequiredAssets:k,onBehalf:n,txs:x,summary:b>0n?`Repay ${b.toString()} borrow shares (approval up to ${k} ${c.symbol}) on Morpho Blue market ${a}. Refresh if signing/inclusion takes more than ${Ue} seconds.`:`Repay ${k} ${c.symbol} on Morpho Blue market ${a}.`,preview:M,formattedChanges:C,formattedNetOutflows:P}}async function Ra(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,a=e.clientFor(f),{marketId:o,marketParams:u,marketState:c}=await fe(a,t,!0),[m,d,p,b]=await Promise.all([Q(a,u.collateralToken,f),Te(a,o,n),Ke(a,u.oracle),Be(a,u,c,Ue)]),h=W("withdrawAll",t.withdrawAll)===!0?d.collateral:Me(t);if(h<=0n||h>d.collateral)throw new i(`Insufficient collateral to withdraw: requested ${h.toString()} base units, position holds ${d.collateral.toString()} base units.`);if(d.borrowShares>0n){let C=d.collateral-h,P=Ae(C,p,u.lltv),I=se(d.borrowShares,b.totalBorrowAssets,c.totalBorrowShares);if(I>P)throw new i(`Unhealthy collateral withdrawal: remaining max borrow ${P.toString()} would fall below current debt ${I.toString()} base units.`)}let w=h.toString(),y=e.formatAmount(w,m.decimals),g=[e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"withdrawCollateral",args:[u,h,n,l]}),value:"0",description:`Withdraw ${y} ${m.symbol} (${w} base units) collateral from Morpho market ${o}.`})],T=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:M}=xe(e,T);return{action:"morpho_withdraw_collateral",chainId:f,marketId:o,marketParams:pe(u),collateralToken:m,assets:w,formattedAssets:y,onBehalf:n,receiver:l,txs:g,summary:`Withdraw ${y} ${m.symbol} collateral from Morpho Blue market ${o}.`,preview:T,formattedChanges:x,formattedNetOutflows:M}}async function _a(e,t,s){let r=Ie(t,s);ve(t,r);let n=e.clientFor(f),{marketId:l,marketParams:a,marketState:o}=await fe(n,t,!0),u=W("wrapNative",t.wrapNative)===!0;if(u&&a.loanToken.toLowerCase()!==me.toLowerCase())throw new i("Native ETH wrapping is only supported when the market loanToken is WETH.");let c=Me(t),m=c.toString(),[d,p]=await Promise.all([Q(n,a.loanToken,f),u?Promise.resolve(c):Zt(n,a.loanToken,r)]);if(p<c)throw new i(`Insufficient ${d.symbol} balance to lend: wallet holds ${p.toString()} base units, requested ${m}.`);let b=e.formatAmount(m,d.decimals),h=[];u&&h.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:m,description:`Wrap ${b} ETH into WETH at ${me}.`})),h.push(e.approval(a.loanToken,$,m,f)),h.push(e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"supply",args:[a,c,0n,r,"0x"]}),value:"0",description:`Lend ${b} ${d.symbol} (${m} base units) to Morpho market ${l}.`}));let w=Ua(c,o.totalSupplyAssets,o.totalSupplyShares),y=await e.preview(h,r),{formattedChanges:k,formattedNetOutflows:g}=xe(e,y);return{action:"morpho_supply",chainId:f,marketId:l,marketParams:pe(a),loanToken:d,assets:m,formattedAssets:b,supplySharesEstimated:w.toString(),onBehalf:r,oak:ct(l),txs:h,summary:`${u?`Send ${b} ETH to wrap into WETH. `:""}Lend ${b} ${d.symbol} to Morpho Blue market ${l}. It earns the market supply rate and is exposed to the market's collateral, oracle and liquidity risk.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ha(e,t,s){let r=Ie(t,s);ve(t,r);let n=e.clientFor(f),l=W("withdrawAll",t.withdrawAll)===!0;if(l&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify withdrawAll alone, without assets/amount.");let{marketId:a,marketParams:o,marketState:u}=await fe(n,t,!0),[c,m]=await Promise.all([Q(n,o.loanToken,f),Te(n,a,r)]);if(m.supplyShares===0n)throw new i(`This wallet has no lent ${c.symbol} on Morpho market ${a}.`);let d=ut(m.supplyShares,u.totalSupplyAssets,u.totalSupplyShares),p=l?0n:Me(t),b=l?m.supplyShares:0n;if(!l&&p>d)throw new i(`Withdrawal exceeds the lent balance: requested ${p.toString()} base units, position holds about ${d.toString()}. Use withdrawAll for a full exit.`);let h=u.totalSupplyAssets>u.totalBorrowAssets?u.totalSupplyAssets-u.totalBorrowAssets:0n,w=l?d:p;if(w>h)throw new i(`Insufficient market liquidity: withdrawing ${w.toString()} base units needs idle assets, but only ${h.toString()} are available until borrowers repay. Withdraw at most that amount, or retry later.`);let y=e.formatAmount(w.toString(),c.decimals),g=[e.unsignedTx({chainId:f,to:$,data:G({abi:X,functionName:"withdraw",args:[o,p,b,r,r]}),value:"0",description:l?`Withdraw all ${m.supplyShares.toString()} supply shares (about ${y} ${c.symbol}) from Morpho market ${a}.`:`Withdraw ${y} ${c.symbol} (${p.toString()} base units) of lent assets from Morpho market ${a}.`})],T=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:M}=xe(e,T);return{action:"morpho_withdraw",chainId:f,marketId:a,marketParams:pe(o),loanToken:c,withdrawAssets:p.toString(),withdrawShares:b.toString(),estimatedAssets:w.toString(),formattedAssets:y,receiver:r,txs:g,summary:l?`Withdraw all lent ${c.symbol} (about ${y}, including interest) from Morpho Blue market ${a}.`:`Withdraw ${y} lent ${c.symbol} from Morpho Blue market ${a}.`,preview:T,formattedChanges:x,formattedNetOutflows:M}}async function ea(e,t,s){let r=await e.http(Aa,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:t,variables:s})});if(!r.ok)throw new i(`Morpho GraphQL request failed (HTTP ${r.status}).`);let n=await r.json();if(n.errors?.length)throw new i("Morpho GraphQL returned query errors.");return n.data??{}}async function ta(e){let t=`query Markets($chainId: Int!) {
2
2
  markets(first: 1000, where: { chainId_in: [$chainId] }) {
3
3
  items {
4
4
  marketId chain { id } lltv listed
@@ -1,3 +1,3 @@
1
- import{d as F,e as M}from"./ACH4BSME.js";import{g as H,j as R}from"./PZEF5LBL.js";import{a as y,b as x,c,f as $,j as L,l as S,m as O,n as U}from"./CSOO4SW7.js";import{a as r}from"./I6PQW2JI.js";import{a as N}from"./K6D6SDIG.js";import{c as q}from"./43LI5NKJ.js";import{g as _}from"./NWNYJ26T.js";import{a as h}from"./XSD5NL7J.js";import{encodeFunctionData as W}from"viem";var j={chop_wrap:["log","underlying","amount","minLogOut"],chop_unwrap:["log","amount","quotedNet"],chop_farm:["log","amount","pairedAmount","minPaired","minStakedLp","slippageBps","deadline"],chop_unfarm:["log","amount","minLogOut","minPairedOut","deadline"],chop_harvest:["log"]};function z(l,o){if(Object.keys(l).some(n=>!o.includes(n)))throw new h("Unexpected Chop argument.");if(o.some(n=>l[n]===void 0))throw new h("Provide every required Chop input.")}async function V(l,o,n){let d=c(o),p=await l.getBlock({blockNumber:BigInt(n.measuredAtBlock)});if(p.number!==BigInt(n.measuredAtBlock)||d<=x(p.timestamp)||d>p.timestamp+1200n)throw new h("Chop deadline must be in the next 20 minutes.");return d}async function D(l,o,n,d){if(z(n,j[o]),y(d),l.network==="testnet")throw new h("Chop requires chain 4663.");let p=y(n.log),u=l.clientFor(4663),i=await S(u,p,o==="chop_wrap"||o==="chop_farm"?"enter":"exit"),s=BigInt(i.measuredAtBlock),f=[],g=[],C=(e,t,a)=>{f.push(q(e.address,t,a.toString(),4663)),g.push(l.approval(e.address,t,a.toString(),4663))},P=(e,t,a)=>{let m={to:e,data:W({abi:N,functionName:t,args:a}),value:"0",chainId:4663,description:`${o} on verified log ${p}.`,...o==="chop_harvest"?{gasLimit:"1000000"}:{}};f.push(m),g.push({...l.unsignedTx(m),...m.gasLimit===void 0?{}:{gasLimit:m.gasLimit}})},A=[],v=(e,t,a=!0)=>A.push({token:e,min:-t,max:a?-t:-1n}),w=(e,t)=>A.push({token:e,min:t}),T=async(e,t)=>{if(x(await $(u,e.address,"balanceOf",[d],s))<t)throw new h("This wallet does not hold enough tokens for the Chop action.")},k;if(o==="chop_wrap"){let e=c(n.amount),t=c(n.minLogOut);if(!_(y(n.underlying),i.underlying.address))throw new h("The underlying token does not match the verified Chop log.");await T(i.underlying,e),C(i.underlying,p,e),P(p,"bond",[i.underlying.address,e,t]),v(i.underlying,e,!1),w(i.log,t),k=`Wrap at most ${e} underlying base units; on-chain minimum ${t} log base units.`}else if(o==="chop_unwrap"){let e=c(n.amount),t=c(n.quotedNet);await T(i.log,e);let a=await M(u,i,d,e);if(BigInt(a.net.amount)<t)throw new h("Chop unwrap no longer meets the quoted net amount. Request a fresh quote.");let m=F(i,e);f.push(m),g.push(l.unsignedTx(m)),v(i.log,e),w(i.underlying,t),k=`Unwrap ${e} log base units; preview must return at least quoted ${t} underlying base units.`}else if(o==="chop_farm"){await L(u,r.helper,s);let e=c(n.amount),t=c(n.pairedAmount),a=c(n.minPaired),m=c(n.minStakedLp),I=await V(u,n.deadline,i),b=n.slippageBps;if(typeof b!="number"||!Number.isInteger(b)||b<0||b>1e3||b%10!==0||a>t)throw new h("Chop LP slippage must be 0\u20131000 basis points in multiples of 10; the paired minimum cannot exceed its input.");await Promise.all([T(i.log,e),T(i.paired,t)]),C(i.log,r.helper.address,e),C(i.paired,r.helper.address,t),P(r.helper.address,"addLPAndStake",[p,e,i.paired.address,t,a,BigInt(b/10),I]),v(i.log,e,!1),A.push({token:i.paired,min:-t,max:-a}),w(i.staking,m),k=`Farm up to ${e} log + ${t} paired base units; slippage ${b} bps; deadline ${I}. Staked LP minimum ${m} is checked in simulation; two-sided token minimums from slippage are enforced on chain. Paired consumption must also meet ${a} base units in the preview. This tool does not zap; the helper's paired minimum alone has no on-chain effect for a direct pair.`}else if(o==="chop_unfarm"){await L(u,r.helper,s);let e=c(n.amount),t=c(n.minLogOut),a=c(n.minPairedOut),m=await V(u,n.deadline,i);if(x(await $(u,i.staking.address,"withdrawableStake",[d],s))<e)throw new h("Chop stake is still locked or too small. Wait at least 10 minutes after staking.");C(i.staking,r.helper.address,e),P(r.helper.address,"unstakeAndRemoveLP",[p,e,t,a,m]),v(i.staking,e),w(i.log,t),w(i.paired,a),k=`Unfarm ${e} staked LP base units; on-chain minimums ${t} log and ${a} paired base units; deadline ${m}.`}else{if(await L(u,r.whitelist,s),await $(u,r.whitelist.address,"paused",[r.chop],s)!==!1)throw new h("Chop rewards are paused or their pause state is unavailable.");let e=x(await $(u,i.rewards,"getClaimable",[r.chop,d],s));if(e===0n)throw new h("No CHOP is claimable now. Rewards may still be inside the 10-minute maturity lock.");P(i.rewards,"claimReward",[d]),w({address:y(r.chop),symbol:"CHOP",decimals:18,chainId:4663},e),k=`Harvest at least ${e} CHOP base units to ${d} in the preview. ${H} Allow at least 1,000,000 gas for this call.`}return(o==="chop_farm"||o==="chop_unfarm")&&!A.some(e=>_(e.token.address,r.chop))&&w({address:y(r.chop),symbol:"CHOP",decimals:18,chainId:4663},0n),O(g,f),{built:g,expected:f,rules:A,details:k,facts:i,log:p}}async function ie(l,o,n,d){let{built:p,expected:u,rules:B,details:i,facts:s,log:f}=await D(l,o,n,d),g=await l.preview(p,d);return O(g.txs,u,!0),U(g,B),{txs:p,preview:g,log:f,measuredAtBlock:s.measuredAtBlock,summary:`${R(s)}
1
+ import{d as F,e as M}from"./KOKLM63Q.js";import{g as H,j as R}from"./ETMD747Y.js";import{a as y,b as x,c,f as $,j as L,l as S,m as O,n as U}from"./K4GUZ5QS.js";import{a as N}from"./K6D6SDIG.js";import{a as r}from"./L2AE32SL.js";import{c as q}from"./43LI5NKJ.js";import{g as _}from"./NWNYJ26T.js";import{a as h}from"./XSD5NL7J.js";import{encodeFunctionData as W}from"viem";var j={chop_wrap:["log","underlying","amount","minLogOut"],chop_unwrap:["log","amount","quotedNet"],chop_farm:["log","amount","pairedAmount","minPaired","minStakedLp","slippageBps","deadline"],chop_unfarm:["log","amount","minLogOut","minPairedOut","deadline"],chop_harvest:["log"]};function z(l,o){if(Object.keys(l).some(n=>!o.includes(n)))throw new h("Unexpected Chop argument.");if(o.some(n=>l[n]===void 0))throw new h("Provide every required Chop input.")}async function V(l,o,n){let d=c(o),p=await l.getBlock({blockNumber:BigInt(n.measuredAtBlock)});if(p.number!==BigInt(n.measuredAtBlock)||d<=x(p.timestamp)||d>p.timestamp+1200n)throw new h("Chop deadline must be in the next 20 minutes.");return d}async function D(l,o,n,d){if(z(n,j[o]),y(d),l.network==="testnet")throw new h("Chop requires chain 4663.");let p=y(n.log),u=l.clientFor(4663),i=await S(u,p,o==="chop_wrap"||o==="chop_farm"?"enter":"exit"),s=BigInt(i.measuredAtBlock),f=[],g=[],C=(e,t,a)=>{f.push(q(e.address,t,a.toString(),4663)),g.push(l.approval(e.address,t,a.toString(),4663))},P=(e,t,a)=>{let m={to:e,data:W({abi:N,functionName:t,args:a}),value:"0",chainId:4663,description:`${o} on verified log ${p}.`,...o==="chop_harvest"?{gasLimit:"1000000"}:{}};f.push(m),g.push({...l.unsignedTx(m),...m.gasLimit===void 0?{}:{gasLimit:m.gasLimit}})},A=[],v=(e,t,a=!0)=>A.push({token:e,min:-t,max:a?-t:-1n}),w=(e,t)=>A.push({token:e,min:t}),T=async(e,t)=>{if(x(await $(u,e.address,"balanceOf",[d],s))<t)throw new h("This wallet does not hold enough tokens for the Chop action.")},k;if(o==="chop_wrap"){let e=c(n.amount),t=c(n.minLogOut);if(!_(y(n.underlying),i.underlying.address))throw new h("The underlying token does not match the verified Chop log.");await T(i.underlying,e),C(i.underlying,p,e),P(p,"bond",[i.underlying.address,e,t]),v(i.underlying,e,!1),w(i.log,t),k=`Wrap at most ${e} underlying base units; on-chain minimum ${t} log base units.`}else if(o==="chop_unwrap"){let e=c(n.amount),t=c(n.quotedNet);await T(i.log,e);let a=await M(u,i,d,e);if(BigInt(a.net.amount)<t)throw new h("Chop unwrap no longer meets the quoted net amount. Request a fresh quote.");let m=F(i,e);f.push(m),g.push(l.unsignedTx(m)),v(i.log,e),w(i.underlying,t),k=`Unwrap ${e} log base units; preview must return at least quoted ${t} underlying base units.`}else if(o==="chop_farm"){await L(u,r.helper,s);let e=c(n.amount),t=c(n.pairedAmount),a=c(n.minPaired),m=c(n.minStakedLp),I=await V(u,n.deadline,i),b=n.slippageBps;if(typeof b!="number"||!Number.isInteger(b)||b<0||b>1e3||b%10!==0||a>t)throw new h("Chop LP slippage must be 0\u20131000 basis points in multiples of 10; the paired minimum cannot exceed its input.");await Promise.all([T(i.log,e),T(i.paired,t)]),C(i.log,r.helper.address,e),C(i.paired,r.helper.address,t),P(r.helper.address,"addLPAndStake",[p,e,i.paired.address,t,a,BigInt(b/10),I]),v(i.log,e,!1),A.push({token:i.paired,min:-t,max:-a}),w(i.staking,m),k=`Farm up to ${e} log + ${t} paired base units; slippage ${b} bps; deadline ${I}. Staked LP minimum ${m} is checked in simulation; two-sided token minimums from slippage are enforced on chain. Paired consumption must also meet ${a} base units in the preview. This tool does not zap; the helper's paired minimum alone has no on-chain effect for a direct pair.`}else if(o==="chop_unfarm"){await L(u,r.helper,s);let e=c(n.amount),t=c(n.minLogOut),a=c(n.minPairedOut),m=await V(u,n.deadline,i);if(x(await $(u,i.staking.address,"withdrawableStake",[d],s))<e)throw new h("Chop stake is still locked or too small. Wait at least 10 minutes after staking.");C(i.staking,r.helper.address,e),P(r.helper.address,"unstakeAndRemoveLP",[p,e,t,a,m]),v(i.staking,e),w(i.log,t),w(i.paired,a),k=`Unfarm ${e} staked LP base units; on-chain minimums ${t} log and ${a} paired base units; deadline ${m}.`}else{if(await L(u,r.whitelist,s),await $(u,r.whitelist.address,"paused",[r.chop],s)!==!1)throw new h("Chop rewards are paused or their pause state is unavailable.");let e=x(await $(u,i.rewards,"getClaimable",[r.chop,d],s));if(e===0n)throw new h("No CHOP is claimable now. Rewards may still be inside the 10-minute maturity lock.");P(i.rewards,"claimReward",[d]),w({address:y(r.chop),symbol:"CHOP",decimals:18,chainId:4663},e),k=`Harvest at least ${e} CHOP base units to ${d} in the preview. ${H} Allow at least 1,000,000 gas for this call.`}return(o==="chop_farm"||o==="chop_unfarm")&&!A.some(e=>_(e.token.address,r.chop))&&w({address:y(r.chop),symbol:"CHOP",decimals:18,chainId:4663},0n),O(g,f),{built:g,expected:f,rules:A,details:k,facts:i,log:p}}async function ie(l,o,n,d){let{built:p,expected:u,rules:B,details:i,facts:s,log:f}=await D(l,o,n,d),g=await l.preview(p,d);return O(g.txs,u,!0),U(g,B),{txs:p,preview:g,log:f,measuredAtBlock:s.measuredAtBlock,summary:`${R(s)}
2
2
  ${i}
3
3
  Underlying ${s.underlying.address} (decimals ${s.underlying.decimals}); log ${f} (decimals ${s.log.decimals}); paired ${s.paired.address} (decimals ${s.paired.decimals}).`}}export{j as a,z as b,D as c,ie as d};
@@ -0,0 +1 @@
1
+ import{c as t}from"./LCH6F5HT.js";import{c as o}from"./W7QNSNOH.js";function s(e,n,a){return t(e,n,a,o)}export{s as a};
@@ -0,0 +1 @@
1
+ import{g as t}from"./NWNYJ26T.js";import{b as x,j as b,n as C}from"./TI727O2H.js";import{a as s}from"./XSD5NL7J.js";import{decodeAbiParameters as y,decodeFunctionData as q,encodeAbiParameters as f,encodeFunctionData as J,getAddress as U,parseAbi as Q,parseAbiParameters as A,zeroAddress as g}from"viem";var Y=U(b[x].ponsTrade.universal_router.address),ie=U(b[x].ponsTrade.permit2.address),H="0x0Af57F62982D03066ef917AcAd87F771c06528Ec",ae=Object.freeze({pons:U(C),fobo:H}),Z=Object.freeze({currency0:g,currency1:U(b[x].tokens.USDG.address),fee:500,tickSpacing:10,hooks:g}),ce=Object.freeze([H,g]),M=Q(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),L=A("bytes,bytes[]"),X=A("((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 amountIn,uint128 amountOutMinimum,uint256 minHopPriceX36,bytes hookData)"),j=A("(address currencyIn,(address intermediateCurrency,uint24 fee,int24 tickSpacing,address hooks,bytes hookData)[] path,uint256[] minHopPriceX36,uint128 amountIn,uint128 amountOutMinimum)"),R=A("address,uint256"),G=A("((address token,uint160 amount,uint48 expiration,uint48 nonce) details,address spender,uint256 sigDeadline),bytes"),ee="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",I="Universal Router calldata must be one canonical v4 swap command, optionally after one Permit2 permit.",h="Universal Router actions must swap an exact input, settle it and take all output to the sender.",E="Universal Router settlement and receipt must match the swap.",W="Universal Router swap must carry no hook data or per-hop price limit.",te="Universal Router permit must cover the swap input token and name the Universal Router as spender.";function ue(o){return t(o,ee)?g:o}function m(o,n,a,l){let u;try{if(u=o(),t(n(u),a))return u}catch{}throw new s(l)}function le(o,n){let a=m(()=>q({abi:M,data:o}),e=>J({abi:M,...e}),o,I),[l,u,$]=a.args,P=t(l,"0x0a10");if(!P&&!t(l,"0x10")||u.length!==(P?2:1))throw new s(I);let K=u.at(-1),[T,c]=m(()=>y(L,K),e=>f(L,e),K,h),_=t(T,"0x060c0f");if(!_&&!t(T,"0x070c0f")||c.length!==3)throw new s(h);let S,d,O,w,k;if(_){let[e]=m(()=>y(X,c[0]),F=>f(X,F),c[0],h);if(e.hookData!=="0x"||e.minHopPriceX36!==0n)throw new s(W);let{currency0:r,currency1:i,fee:p,tickSpacing:v,hooks:D}=e.poolKey;S=[{poolKey:{currency0:r,currency1:i,fee:p,tickSpacing:v,hooks:D},zeroForOne:e.zeroForOne}],[d,O]=e.zeroForOne?[r,i]:[i,r],{amountIn:w,amountOutMinimum:k}=e}else{let[e]=m(()=>y(j,c[0]),i=>f(j,i),c[0],h);if(e.path.length<2)throw new s(h);if(e.minHopPriceX36.length!==0||e.path.some(i=>i.hookData!=="0x"))throw new s(W);let r=e.currencyIn;S=e.path.map(i=>{let p=i.intermediateCurrency;if(t(r,p))throw new s(h);let[v,D]=BigInt(r)<BigInt(p)?[r,p]:[p,r],F={poolKey:{currency0:v,currency1:D,fee:i.fee,tickSpacing:i.tickSpacing,hooks:i.hooks},zeroForOne:t(r,v)};return r=p,F}),d=e.currencyIn,O=r,{amountIn:w,amountOutMinimum:k}=e}if(w<=0n)throw new s("Universal Router swap input must be a positive exact amount.");if(t(d,O))throw new s("Universal Router swap must end in a different currency than it starts.");for(let{poolKey:e}of S)if(!n.some(r=>t(r,e.hooks)))throw new s(`Universal Router swap uses pool hook ${e.hooks}, which this route does not allow.`);let N=m(()=>y(R,c[1]),e=>f(R,e),c[1],E),z=m(()=>y(R,c[2]),e=>f(R,e),c[2],E);if(!t(N[0],d)||N[1]!==w||!t(z[0],O)||z[1]!==k)throw new s(E);let B={legs:S,currencyIn:d,currencyOut:O,amountIn:w,amountOutMinimum:k,deadline:$};if(P){let[e,r]=m(()=>y(G,u[0]),i=>f(G,i),u[0],I);if(t(d,g)||!t(e.details.token,d)||!t(e.spender,Y))throw new s(te);B.permit={...e.details,spender:e.spender,sigDeadline:e.sigDeadline,signature:r}}return B}function V(o,n){return t(o.currency0,n.currency0)&&t(o.currency1,n.currency1)&&o.fee===n.fee&&o.tickSpacing===n.tickSpacing&&t(o.hooks,n.hooks)}function de(o,n){return o.length===n.length&&o.every((a,l)=>V(a.poolKey,n[l].poolKey)&&a.zeroForOne===n[l].zeroForOne)}var pe=1200,me=1800;function ye(o){let n=0;for(let{poolKey:a}of o.legs)if(t(a.hooks,H))n++;else if(!V(a,Z))throw new s("Swap leaves the FOBO route: every pool must be a FoboHook pool or FOBO's ETH/USDG pool.");if(n===0)throw new s("Swap is not a FOBO route: it uses no FoboHook pool.")}export{Y as a,ie as b,H as c,ae as d,Z as e,ce as f,ue as g,le as h,V as i,de as j,pe as k,me as l,ye as m};
@@ -1 +1 @@
1
- import{k as s}from"./UVAR6BHU.js";import{formatUnits as c}from"viem";function l(e){return`HoodLock creation fee: ${e.eth} ETH (${e.amount} wei; ${e.usd===null?"USD unavailable: no fresh ETH/USD reference":`approximately $${e.usd} USD`}), not refundable after creation. Paid to ${e.contract}; separate from network gas.`}async function p(e,t,d,r){let o=r===0n?"0":null;if(r>0n)try{let a=await s("ETH",{client:e.clientFor(4663),chainId:4663});BigInt(a.usdE18)>0n&&(o=c(r*BigInt(a.usdE18)/10n**18n,18))}catch{}let n={contract:d,amount:r.toString(),eth:c(r,18),usd:o,refundable:!1},i=l(n);return{...t,summary:`${t.summary} ${i}`,preview:{...t.preview,summary:`${t.preview.summary} ${i}`},protocolFee:n}}export{l as a,p as b};
1
+ import{m as s}from"./NV6FDIYT.js";import{formatUnits as c}from"viem";function l(e){return`HoodLock creation fee: ${e.eth} ETH (${e.amount} wei; ${e.usd===null?"USD unavailable: no fresh ETH/USD reference":`approximately $${e.usd} USD`}), not refundable after creation. Paid to ${e.contract}; separate from network gas.`}async function p(e,t,d,r){let o=r===0n?"0":null;if(r>0n)try{let a=await s("ETH",{client:e.clientFor(4663),chainId:4663});BigInt(a.usdE18)>0n&&(o=c(r*BigInt(a.usdE18)/10n**18n,18))}catch{}let n={contract:d,amount:r.toString(),eth:c(r,18),usd:o,refundable:!1},i=l(n);return{...t,summary:`${t.summary} ${i}`,preview:{...t.preview,summary:`${t.preview.summary} ${i}`},protocolFee:n}}export{l as a,p as b};
@@ -1 +1 @@
1
- import{b as Ce,o as le}from"./LKX5WDOQ.js";import{a as ue}from"./Z7FGEWO2.js";import{b as Ne}from"./SPJCSEKP.js";import{a as Ae}from"./IOYRL6AY.js";import{a as ve}from"./66F5ZH34.js";import{e as X,g as p,i as xe,n as Ie}from"./NWNYJ26T.js";import{b as A,j as Te}from"./TI727O2H.js";import{a as r}from"./XSD5NL7J.js";import{a as de}from"./JXOEJPJ4.js";import{decodeErrorResult as Me,decodeEventLog as ce,encodeAbiParameters as U,encodeFunctionData as C,erc20Abi as J,parseAbi as $e,parseAbiParameters as q,toHex as Be,zeroAddress as F}from"viem";var g=Te[A].poolsTrade,Y=g.liquidityLauncher.address,B=g.uerc20BeneficiaryVault.address,fe=g.universalRouter.address,ie=10n**27n,j=(1n<<128n)-1n,Se=`0x${"00".repeat(32)}`,D=63127652n,pe=100000n,ae=10000000n,Ue=2000n,me={address:ue,symbol:"ETH",decimals:18,chainId:A},h=$e(["function multicall(bytes[] data) payable returns (bytes[])","function createToken(address factory,string name,string symbol,uint8 decimals,uint128 initialSupply,address recipient,bytes tokenData) payable returns (address)","function distributeToken(address token,(address strategy,uint128 amount,bytes configData) distribution,bytes32 salt) payable","function distributeWithNative(address strategy,bytes configData,bytes32 salt,uint256 nativeAmount) payable","function getGraffiti(address sender) view returns (bytes32)","function getUERC20Address(string name,string symbol,uint8 decimals,address recipient,bytes32 graffiti) view returns (address)","function execute(bytes commands,bytes[] inputs,uint256 deadline) payable","function collectFees(uint256[] ids)","function claim(uint256 id,uint256 minCurrency0Amount,uint256 minCurrency1Amount)","function amounts(uint256 id) view returns (uint128 eth,uint128 token)","function ownerOf(uint256 id) view returns (address)","function getApproved(uint256 id) view returns (address)","function approve(address spender,uint256 id)","function safeTransferFrom(address from,address to,uint256 id)","function approve(address token,address spender,uint160 amount,uint48 expiration)","error V4TooLittleReceived(uint256 minAmountOut,uint256 amountOut)"]),K=$e(["event TokenLaunched(bytes32 indexed poolId,address indexed token,address indexed feeSplitter,(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey)","event Transfer(address indexed from,address indexed to,uint256 indexed tokenId)"]),V=[g.instantLaunchStrategyFeesOn.address,g.instantLaunchStrategyFeesOff.address];function re(l){if(l.status!=="success")throw new r("The launch receipt did not succeed.");let c=[];for(let k of l.logs){let H=V.findIndex(L=>p(L,k.address));if(H===-1||k.topics[0]!=="0x3b3d2bafdcae274a232217e1f80ee4305d3af6aa25c8b14b1681bd68d18042a4")continue;let G=ce({abi:K,eventName:"TokenLaunched",data:k.data,topics:[...k.topics]}),{token:x,poolId:ee,poolKey:M,feeSplitter:te}=G.args,_=H===0?g.feeSplitterFeesOn.address:g.feeSplitterFeesOff.address;if(!p(te,_)||!p(M.currency0,F)||!p(M.currency1,x)||M.fee!==2500||M.tickSpacing!==25||!p(M.hooks,F))throw new r("The launch does not match the current native ETH strategy.");let ne=l.logs.filter(L=>p(L.address,g.v4PositionManager.address)).flatMap(L=>{if(L.topics[0]!=="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef")return[];let O=ce({abi:K,eventName:"Transfer",data:L.data,topics:[...L.topics]}).args;return p(O.from,F)&&p(O.to,V[H])?[O.tokenId]:[]});if(ne.length!==1)throw new r("The launch receipt must identify one matching position mint.");c.push({token:x,poolId:ee,positionId:ne[0].toString(),creatorFees:H===0})}return c}function S(l){return xe(l,"Provide a valid wallet or token address.")}function P(l,c,k=!1){return Ie(l,`${c} is outside its supported range.`,{notString:`${c} must be an integer string in base units.`,positive:!k})}function Z(l,c,k=!1){if(k&&l===void 0)return"";if(typeof l!="string"||!k&&!l.trim()||l.length>4096)throw new r(`Provide a valid ${c}.`);return l}function he(l){if(typeof l!="string"||!/^0x[0-9a-fA-F]{64}$/.test(l))throw new r("Provide a valid launch transaction hash.");return l}function ge(l,c,k="minAmountOut"){let H=c.slippageBps??Ce;if(typeof H!="number")throw new r("Slippage must be an integer in basis points.");let G=le(l.toString(),H),x=c[k]===void 0?BigInt(G):P(c[k],k,l===0n);if(x>l||l>0n&&x===0n||x>j)throw new r("The minimum output must be positive and no larger than the simulated output.");return x}var qe=l=>{let c=l.clientFor(A),k=(e,o,n,s)=>l.unsignedTx({to:e,data:o,value:n.toString(),chainId:A,description:s}),H=e=>{throw new r(l.plainError(e))};async function G(){if(await c.getChainId()!==A)throw new r("pools.trade requires Robinhood Chain 4663.")}async function x(e,o,n){let s=await l.preview(e,o),t=s.changes.map(({token:a,amount:d})=>{let i=d.startsWith("-");return`${i?"-":""}${l.formatAmount(i?d.slice(1):d,a.decimals)} ${de(a.symbol)} (${a.address}, chain ${a.chainId})`});return{txs:e,summary:[n,s.summary,...t].join(" ")}}async function ee(){return(await c.getBlock()).timestamp+600n}function M(e,o,n,s,t,a){let d=[F,e,2500,25,F],i=[U(q("((address,address,uint24,int24,address),bool,uint128,uint128,uint256,bytes)"),[[d,o,n,s,0n,"0x"]]),U(q("address,uint256"),[o?F:e,n]),U(q("address,address,uint256"),[o?e:F,t,0n])],m=[U(q("bytes,bytes[]"),["0x060c0e",i])];return{inputs:m,encoded:U(q("bytes,bytes[],uint256"),["0x10",m,a])}}async function te(e,o){let n=await c.request({method:"eth_simulateV1",params:[{blockStateCalls:[{calls:e.map(i=>({from:o,gas:Be(Ae),to:i.to,data:i.data,value:Be(BigInt(i.value))}))}],validation:!1,traceTransfers:!1},"latest"]},{retryCount:0});if(!Array.isArray(n)||n.length!==1||!X(n[0])||!Array.isArray(n[0].calls)||n[0].calls.length!==e.length)throw new r("The output simulation returned a malformed response.");let s=n[0].calls;if(!s.slice(0,-1).every(i=>X(i)&&i.status==="0x1"&&!i.error))throw new r("A prerequisite failed during the output simulation.");let t=s.at(-1);if(!X(t)||t.status!=="0x0")throw new r("The output simulation did not return the expected minimum-output control.");let a=typeof t.returnData=="string"&&t.returnData!=="0x"?t.returnData:X(t.error)?t.error.data:void 0;if(typeof a!="string"||!/^0x[0-9a-fA-F]+$/.test(a))throw new r("The output simulation did not report an expected amount.");let d=Me({abi:h,data:a});if(d.errorName!=="V4TooLittleReceived"||d.args[0]!==j||d.args[1]<=0n||d.args[1]>=j)throw new r("The output simulation did not report a valid amount.");return d.args[1]}let _=new Map,ne=2e3;async function L(e,o,n,s=()=>!0){let t=await c.getBlockNumber(),a=t<D?0n:(t-D)/ae+1n,d=1n,i=(u=1n)=>{if(d+=u,d>Ue)throw new r("Pools.trade scan exceeds the 2000-request limit. Use launchTx for a specific launch; positions coverage is incomplete.")};i(a*BigInt(V.length+(e&&!n?1:0)));let m=new Map,b=new Set;for(let u=D;u<=t&&s();u+=ae){let f=u+ae-1n>t?t:u+ae-1n,y=(await Promise.all(V.map(T=>c.getLogs({address:T,event:K[0],...o?{args:{token:o}}:{},fromBlock:u,toBlock:f,strict:!0})))).flat(),$=[...new Set(y.map(T=>T.transactionHash))].filter(T=>!T||!m.has(T));for(let T=0;T<$.length&&s();T+=8)await Promise.all($.slice(T,T+8).map(async E=>{if(!E)throw new r("A launch log is missing its transaction hash.");let R=_.get(E);R||(i(),R=await c.getTransactionReceipt({hash:E}),_.size>=ne&&_.delete(_.keys().next().value),_.set(E,R)),m.set(E,R),s()&&await n?.(R)}));if(!s())break;if(e&&!n){let T=await c.getLogs({address:B,event:K[1],args:{to:e},fromBlock:u,toBlock:f,strict:!0});for(let E of T){let R=ce({abi:K,eventName:"Transfer",data:E.data,topics:E.topics}).args;b.add(R.tokenId.toString())}}}return{receipts:[...m.values()],feeIds:b}}async function O(e){let n=(e.launchTx!==void 0?[await c.getTransactionReceipt({hash:he(e.launchTx)})]:(await L(void 0,e.token===void 0?void 0:S(e.token))).receipts).flatMap(re).filter(s=>e.positionId!==void 0?s.positionId===P(e.positionId,"positionId").toString():p(s.token,S(e.token)));if(n.length!==1)throw new r("No unique current-strategy launch was found. Older strategy generations are unsupported.");return n[0]}async function Ee(e,o){if(typeof e.creatorFees!="boolean")throw new r("creatorFees must be an explicit boolean; the choice is permanent.");if(e.pair!==void 0&&!p(S(e.pair),F)&&!p(S(e.pair),ue))throw new r("Only the native ETH pair is supported.");if(e.decimals!==void 0&&e.decimals!==18)throw new r("Instant Launch requires 18 decimals.");if(e.supply!==void 0&&P(e.supply,"supply")!==ie)throw new r("Instant Launch requires a supply of one billion tokens.");let n=S(e.feeBeneficiary);if(p(n,F)||p(n,Y))throw new r("The fee beneficiary must be a wallet other than the launcher or zero address.");let s=Z(e.name,"name"),t=Z(e.symbol,"symbol"),a=e.initialBuy===void 0?0n:P(e.initialBuy,"initialBuy",!0);if(a>j)throw new r("The initial buy exceeds uint128.");if(a===0n&&e.minAmountOut!==void 0)throw new r("A minimum output requires an initial buy.");let d=await c.readContract({address:Y,abi:h,functionName:"getGraffiti",args:[o]}),i=S(await c.readContract({address:g.uerc20Factory.address,abi:h,functionName:"getUERC20Address",args:[s,t,18,Y,d]})),m=await c.getCode({address:i});if(m&&m!=="0x")throw new r("This wallet already launched that name and symbol.");let b=U(q("(string,string,string,bytes)"),[[Z(e.description,"description",!0),Z(e.website,"website",!0),Z(e.imageUri,"image URI",!0),"0x"]]),u=e.creatorFees?V[0]:V[1],f=[C({abi:h,functionName:"createToken",args:[g.uerc20Factory.address,s,t,18,ie,Y,b]}),C({abi:h,functionName:"distributeToken",args:[i,{strategy:u,amount:ie,configData:U(q("address"),[n])},Se]})],y=await ee(),v=T=>{let E=[...f];if(a>0n){let R=U(q("(address,address,bytes)"),[[fe,o,M(i,!0,a,T,o,y).encoded]]);E.push(C({abi:h,functionName:"distributeWithNative",args:[g.universalRouterStrategyApp.address,R,Se,a]}))}return k(Y,C({abi:h,functionName:"multicall",args:[E]}),a,`Atomic Instant Launch: creator fees ${e.creatorFees?"on":"off"} (permanent); beneficiary ${n}.`)},$=a>0n?ge(await te([v(j)],o),e):0n;return x([v($)],o,`Launch ${s} (${i}, chain 4663), supply 1000000000, decimals 18. Creator fees ${e.creatorFees?"on":"off"} are permanent; fee beneficiary ${n}. Creator ETH fees come from buys only (recorded 0.09996%); sells compound into locked liquidity. Initial-buy minimum ${$} token base units. Off-chain image/display unproven; no private metadata registration. No transaction sent.`)}async function Fe(e,o,n){let s=P(e.amountIn,"amountIn");if(s>j)throw new r("The trade amount exceeds uint128.");let t=S(e.token);await O(e);let a=await ee(),d=[];n||(await c.readContract({address:t,abi:J,functionName:"allowance",args:[o,g.permit2.address]})<s&&d.push(l.approval(t,g.permit2.address,s.toString(),A)),d.push(k(g.permit2.address,C({abi:h,functionName:"approve",args:[t,fe,s,Number(a)]}),0n,`Permit the exact ${s} token base units until ${a}.`)));let i=u=>[...d,k(fe,C({abi:h,functionName:"execute",args:["0x10",M(t,n,s,u,o,a).inputs,a]}),n?s:0n,`${n?"Buy":"Sell"} ${t} with minimum output ${u}.`)],m=await te(i(j),o),b=ge(m,e);return x(i(b),o,`${n?"Buy":"Sell"} token ${t} (chain 4663, 18 decimals), amountIn ${s}, minimum output ${b} ${n?"token":"ETH"} base units (18 decimals). Recorded swap fee 0.2899%; creator ETH fees from buys only, none from sells. No transaction sent.`)}async function we(e,o,n){let s=await O(e),t=BigInt(s.positionId),a=s.creatorFees?g.feeSplitterFeesOn.address:g.feeSplitterFeesOff.address,d=await c.readContract({address:g.v4PositionManager.address,abi:h,functionName:"ownerOf",args:[t]});if(!p(d,a))throw new r("The position is not locked in its current-strategy splitter.");if(!n)return x([k(a,C({abi:h,functionName:"collectFees",args:[[t]]}),0n,`Collect fees for position ${t}; permissionless.`)],o,"Collect fees for the entitled recipients; collection does not transfer creator fees to the collector. No transaction sent.");if(!s.creatorFees)throw new r("Creator fees are permanently disabled for this position.");let i=await c.readContract({address:B,abi:h,functionName:"ownerOf",args:[t]});if(!p(i,o))throw new r("Only the current fee NFT holder is entitled to claim.");let m=await c.readContract({address:B,abi:h,functionName:"amounts",args:[t]}),b=ge(m[0],e,"minEth");if(m[1]!==0n)throw new r("The current buy-only creator fee configuration returned unexpected token fees.");return x([k(B,C({abi:h,functionName:"claim",args:[t,b,0n]}),0n,`Claim collected ETH fees for position ${t} to ${o}.`)],o,`Claim collected fees: ${m[0]} ETH base units (18 decimals), minimum ${b}. Uncollected fees require poolstrade_collect first. No transaction sent.`)}async function Le(e,o){let n=await O(e),s=S(e.to);if(p(s,F))throw new r("The token recipient cannot be the zero address.");let t=P(e.amount,"amount"),a=await oe(n.token,await c.getBlockNumber());return x([k(a.address,C({abi:J,functionName:"transfer",args:[s,t]}),0n,`Transfer exactly ${t} ${de(a.symbol)} base units to ${s}.`)],o,`Transfer ${t} token base units (token ${a.address}, decimals ${a.decimals}, chain ${a.chainId}) to ${s}. No approval; no transaction sent.`)}async function Oe(e,o){if(!Array.isArray(e.positionIds)||e.positionIds.length<1||e.positionIds.length>20||!Array.isArray(e.launchTxs)||e.launchTxs.length!==e.positionIds.length)throw new r("Provide 1 to 20 positionIds and one matching launchTxs entry for each.");let n=e.positionIds.map(d=>P(d,"positionId").toString());if(new Set(n).size!==n.length)throw new r("Each position ID must appear once.");let s=e.launchTxs.map(he),t=new Map;for(let[d,i]of n.entries()){let b=(await O({positionId:i,launchTx:s[d]})).creatorFees?g.feeSplitterFeesOn.address:g.feeSplitterFeesOff.address,u=BigInt(i),f=await c.readContract({address:g.v4PositionManager.address,abi:h,functionName:"ownerOf",args:[u]});if(!p(f,b))throw new r("The position is not locked in its current-strategy splitter.");t.set(b,[...t.get(b)??[],u])}let a=[...t].map(([d,i])=>k(d,C({abi:h,functionName:"collectFees",args:[i]}),0n,`Collect fees for positions ${i.join(", ")}; permissionless.`));return x(a,o,"Collect fees in batches for the fixed entitled recipients. Collection does not pay the collector. No transaction sent.")}let Q="Current native ETH Instant Launch strategies only. Crowd Launch and older deployments are not covered.";async function oe(e,o){let[n,s]=await Promise.all([c.readContract({address:e,abi:J,functionName:"symbol",blockNumber:o}),c.readContract({address:e,abi:J,functionName:"decimals",blockNumber:o})]);if(typeof n!="string"||!n||n.length>256||s!==18)throw new r("The current launch token returned invalid metadata.");return{address:e,symbol:n,decimals:s,chainId:A}}async function be(e,o,n,s){let t=s??await oe(e.token,n),a=await c.readContract({address:t.address,abi:J,functionName:"balanceOf",args:[o],blockNumber:n});return{token:t,amount:a.toString(),humanAmount:l.formatAmount(a.toString(),t.decimals)}}async function Pe(e,o){let n=await O(e),s=await c.getBlockNumber();return{wallet:o,...await be(n,o,s),blockNumber:s.toString(),coverage:Q}}async function He(e,o){let n=he(e.launchTx),s=await c.getTransactionReceipt({hash:n}),t=re(s);if(e.token!==void 0&&(t=t.filter(i=>p(i.token,S(e.token)))),e.positionId!==void 0&&(t=t.filter(i=>i.positionId===P(e.positionId,"positionId").toString())),!t.length)throw new r("The receipt contains no matching current Instant Launch. Crowd Launch and older strategies are not covered.");let a=await c.getBlockNumber(),d=await Promise.all(t.map(async i=>{let m=i.creatorFees?g.feeSplitterFeesOn.address:g.feeSplitterFeesOff.address,b=await c.readContract({address:g.v4PositionManager.address,abi:h,functionName:"ownerOf",args:[BigInt(i.positionId)],blockNumber:a});if(!p(b,m))throw new r("The position is not locked in its current-strategy splitter.");let u=i.creatorFees?{owner:await c.readContract({address:B,abi:h,functionName:"ownerOf",args:[BigInt(i.positionId)],blockNumber:a}),approved:await c.readContract({address:B,abi:h,functionName:"getApproved",args:[BigInt(i.positionId)],blockNumber:a}),collected:await c.readContract({address:B,abi:h,functionName:"amounts",args:[BigInt(i.positionId)],blockNumber:a})}:void 0,f=await oe(i.token,a);return{...i,token:f,custodian:b,holding:await be(i,o,a,f),...u?{feeEntitlement:{owner:u.owner,approved:u.approved,collected:[{token:me,amount:u.collected[0].toString()},{token:f,amount:u.collected[1].toString()}],uncollectedFeesIncluded:!1}}:{}}}));return{launchTx:n,wallet:o,creator:s.from,blockNumber:a.toString(),launches:d,coverage:Q}}async function Re(e){let o=await c.getBlockNumber(),n=e.limit??20;if(typeof n!="number"||!Number.isInteger(n)||n<1||n>50)throw new r("limit must be an integer from 1 to 50.");let s=e.fromBlock===void 0?o>=D+pe?o-pe+1n:D:P(e.fromBlock,"fromBlock",!0),t=e.toBlock===void 0?o:P(e.toBlock,"toBlock",!0),a=0;if(e.cursor!==void 0){if(typeof e.cursor!="string"||!/^[0-9]{1,78}:[0-9]{1,78}:[0-9]{1,10}$/.test(e.cursor))throw new r("Provide the browse cursor exactly as returned.");let u=e.cursor.split(":"),f=BigInt(u[0]),y=BigInt(u[1]);if(e.fromBlock!==void 0&&s!==f||e.toBlock!==void 0&&t!==y)throw new r("The cursor does not match this block range.");s=f,t=y,a=Number(u[2])}if(o<D&&e.fromBlock===void 0&&e.toBlock===void 0&&e.cursor===void 0)return{launches:[],cursor:null,fromBlock:D.toString(),toBlock:o.toString(),coverage:Q,predeployment:!0};if(s<D||t<s||t>o||t-s>=pe)throw new r("Choose a deployed block range of at most 100000 blocks, ending no later than the current head.");let d=await c.getLogs({address:V,event:K[0],fromBlock:s,toBlock:t,strict:!0});if(d.some(u=>u.blockNumber===null||u.logIndex===null||!u.transactionHash))throw new r("The launch feed returned an incomplete log.");if(d.sort((u,f)=>u.blockNumber===f.blockNumber?f.logIndex-u.logIndex:u.blockNumber>f.blockNumber?-1:1),a>d.length)throw new r("The browse cursor is outside the launch feed.");let i=new Map,m=[];for(let u of d.slice(a,a+n)){let f=u.transactionHash,y=i.get(f);y||(y=await c.getTransactionReceipt({hash:f}),i.set(f,y));let v=ce({abi:K,eventName:"TokenLaunched",data:u.data,topics:u.topics}).args,$=re(y).filter(T=>p(T.token,v.token)&&p(T.poolId,v.poolId));if($.length!==1)throw new r("The launch feed log does not match one verified receipt launch.");m.push({...$[0],launchTx:f,blockNumber:u.blockNumber.toString(),token:await oe($[0].token,t),creator:y.from})}let b=a+n;return{launches:m,cursor:b<d.length?`${s}:${t}:${b}`:null,fromBlock:s.toString(),toBlock:t.toString(),coverage:Q,previousToBlock:s>D?(s-1n).toString():null,summary:"Newest launches first within this fixed block range. Empty does not establish absence outside the range or covered strategies."}}async function ye(e,o,n){let s=await O(e);if(!s.creatorFees)throw new r("Creator fees are permanently disabled for this position.");let t=BigInt(s.positionId),a=await c.readContract({address:g.v4PositionManager.address,abi:h,functionName:"ownerOf",args:[t]});if(!p(a,g.feeSplitterFeesOn.address))throw new r("The position is not locked in its current-strategy splitter.");let d=await c.readContract({address:B,abi:h,functionName:"ownerOf",args:[t]});if(!p(d,o))throw new r("Only the current fee NFT holder can change this entitlement.");let i=S(n?e.to:e.spender);if(p(i,B)||n&&p(i,F))throw new r("The fee NFT recipient cannot be the vault or zero address.");let m=n?C({abi:h,functionName:"safeTransferFrom",args:[o,i,t]}):C({abi:h,functionName:"approve",args:[i,t]});return x([k(B,m,0n,n?`Transfer fee NFT ${t} to ${i}, including accrued and future fees.`:`Approve ${i} for fee NFT ${t} only; zero address revokes approval.`)],o,n?`Transfer the entire fee entitlement for position ${t} to ${i}. This includes collected and future fees; locked LP remains in its splitter. No transaction sent.`:`Set the exact single-NFT approval for position ${t} to ${i}. This permits transfer of that fee entitlement; zero address revokes. No transaction sent.`)}async function De(){return{chainId:A,instant:{supported:!0,supply:ie.toString(),decimals:18,currency:me,permanentCreatorFeeChoice:!0},crowd:{status:"BLOCKED",strategy:"0xbf1aB81f7d534b2CC0Da76fcf4d541322bB0e000",factory:"0x000000001F26a0044BaA66024e7b6599c61963F8",missing:"A verified Pools-specific auction configuration (BlockNumberish timing, reserve allocation, Q96 floor/tick, USD FDV conversion, issuance steps, locked LP plan) and a bytecode-matched factory-created auction ABI with success/refund fixtures. Generic CCA parameters are not a verified Pools Crowd Launch.",source:"https://github.com/Uniswap/sdks/blob/main/sdks/liquidity-launcher-sdk/src/addresses.ts"},coverage:Q}}let w=e=>({type:"string",description:e}),I=e=>ve(e),se="Launched token contract address (0x + 40 hex digits).",z="Transaction hash (0x + 64 hex digits) of the token launch; lets the tool find the launch without scanning. Optional where the token or position is given.",W='Liquidity position NFT id for the launch, as a decimal string. Example: "1".',ke={chainId:{type:"integer",const:A,description:"Chain id; only 4663 (Robinhood Chain mainnet) is accepted. Optional."},slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage tolerance in basis points (50 = 0.5%) used to derive minimum outputs when none is given. Optional."}};function N(e,o,n,s){return{name:`poolstrade_${e}`,inputSchema:{type:"object",additionalProperties:!1,properties:{...ke,...o},required:n},execute:async(t,a)=>{try{let d=new Set([...Object.keys(ke),...Object.keys(o)]);if(Object.keys(t).some(i=>!d.has(i)))throw new r("Unsupported input for this pools.trade tool.");if(t.chainId!==void 0&&t.chainId!==A)throw new r("pools.trade requires chain 4663.");if(S(a),t.slippageBps!==void 0){if(typeof t.slippageBps!="number")throw new r("Slippage must be an integer in basis points.");le("10000",t.slippageBps)}return await G(),await s(t,a)}catch(d){H(d)}}}}return{tools:[N("launch",{name:w("Token name, shown in wallets and explorers."),symbol:w("Token ticker symbol."),creatorFees:{type:"boolean",description:"Permanent choice; must be explicit. true enables creator fees paid to feeBeneficiary from buys; false disables them forever."},feeBeneficiary:w("Address that receives creator fees; must not be the zero address or the launcher."),pair:w("Optional pair currency; only native ETH is supported (the zero address or the native ETH sentinel)."),decimals:{type:"integer",const:18,description:"Token decimals; must be 18 for an Instant Launch."},supply:I("Total token supply in base units (18 decimals); must be 1000000000000000000000000000 = one billion tokens."),initialBuy:I('ETH to spend on an initial buy in the same transaction, in wei base units (ETH has 18 decimals). Example: "1000000000000000" = 0.001 ETH.'),minAmountOut:I('Least new tokens to receive from the initial buy, in token base units (18 decimals). Requires initialBuy. Example: "1000000000000000000" = 1 token.'),description:w("Optional token description stored in token metadata."),website:w("Optional website URL stored in token metadata."),imageUri:w("Optional image URI stored in token metadata.")},["name","symbol","creatorFees","feeBeneficiary"],Ee),...["buy","sell"].map(e=>N(e,{token:w(se),amountIn:I(e==="buy"?'ETH to spend, in wei base units (ETH has 18 decimals). Example: "1000000000000000" = 0.001 ETH.':'Tokens to sell, in token base units (launched tokens have 18 decimals). Example: "1000000000000000000" = 1 token.'),minAmountOut:I(e==="buy"?'Least tokens to receive, in token base units (18 decimals). Example: "1000000000000000000" = 1 token. Defaults from slippageBps.':'Least ETH to receive, in wei base units (18 decimals). Example: "1000000000000000" = 0.001 ETH. Defaults from slippageBps.'),launchTx:w(z)},["token","amountIn"],(o,n)=>Fe(o,n,e==="buy"))),N("collect",{positionId:I(W),launchTx:w(z)},["positionId"],(e,o)=>we(e,o,!1)),N("claim",{positionId:I(W),launchTx:w(z),minEth:I('Least ETH you must receive from the claim, in wei base units (ETH has 18 decimals). Example: "1000000000000000" = 0.001 ETH.')},["positionId"],(e,o)=>we(e,o,!0)),N("browse",{fromBlock:I("First block number of the scan range, as a decimal string. Defaults to the most recent 100000 blocks."),toBlock:I("Last block number of the scan range, as a decimal string. Defaults to the latest block."),limit:{type:"integer",minimum:1,maximum:50,description:"Launches per page, 1 to 50 (default 20)."},cursor:w("Opaque pagination cursor exactly as returned by the previous browse call.")},[],Re),N("balance",{token:w(se),launchTx:w(z)},["token"],Pe),N("status",{launchTx:w("Transaction hash (0x + 64 hex digits) of the token launch to inspect."),token:w(se),positionId:I(W)},["launchTx"],He),N("launch_options",{},[],De),N("fee_transfer",{positionId:I(W),launchTx:w(z),to:w("Address that will become the new holder of the fee NFT and its future creator fees. Use the intended address.")},["positionId","to"],(e,o)=>ye(e,o,!0)),N("fee_approve",{positionId:I(W),launchTx:w(z),spender:w("Address approved to move the fee NFT. Use the intended address.")},["positionId","spender"],(e,o)=>ye(e,o,!1)),N("transfer",{token:w(se),amount:I('Tokens to send, in token base units (launched tokens have 18 decimals). Example: "1000000000000000000" = 1 token.'),to:w("Recipient address of the tokens; must not be the zero address. Use the intended address."),launchTx:w(z)},["token","amount","to"],Le),N("collect_many",{positionIds:{type:"array",items:I(W),minItems:1,maxItems:20,description:"Position NFT ids to collect fees for, decimal strings; same order as launchTxs."},launchTxs:{type:"array",items:w("Launch transaction hash (0x + 64 hex digits) matching the position id at the same index."),minItems:1,maxItems:20,description:"Launch transaction hashes, one per position id, in the same order."}},["positionIds","launchTxs"],Oe)],positions:async(e,o)=>{S(e);let n=[],s=0,t=!0,a=o?.deepScan?2e4:6e3,d=o?.signal,i,m,b=f=>({module:"poolstrade",id:"poolstrade-discovery-incomplete",chainId:A,assets:[],incomplete:!0,description:`${f} Checked ${s} launch receipts. Readable holdings are retained. Check a known launch with poolstrade_status {"launchTx":"<hash>"} or its token holding with poolstrade_balance {"token":"<address>","launchTx":"<hash>"}. Crowd Launch and older deployments are outside this reader's coverage.`}),u=async()=>{await G(),t&&await L(e,void 0,async f=>{s++;for(let y of re(f)){if(!t)return;let v=y.creatorFees&&p(await c.readContract({address:B,abi:h,functionName:"ownerOf",args:[BigInt(y.positionId)]}),e);if(!t)return;if(!v&&!p(f.from,e))continue;let $=v?[{token:me,amount:(await c.readContract({address:B,abi:h,functionName:"amounts",args:[BigInt(y.positionId)]}))[0].toString()}]:[];t&&n.push({module:"poolstrade",id:y.positionId,chainId:A,assets:$,description:`Current Instant Launch ${y.token} (18 decimals, supply 1000000000), pool ${y.poolId}; creator fees ${y.creatorFees?"on":"off"} (permanent). ${v?"Collected ETH fees only; uncollected fees excluded.":"Launch record; no fee entitlement held."} Liquidity is permanently locked.`})}},()=>t)};try{if(d?.aborted)return[b("Pools.trade discovery was cancelled; the historical scan is incomplete.")];let f=new Promise(v=>{i=()=>{t=!1,v("aborted")},d?.addEventListener("abort",i,{once:!0}),m=setTimeout(()=>{t=!1,v("budget")},a)}),y=await Promise.race([u().then(()=>"complete"),f]);return y==="complete"?n:[...n,b(y==="aborted"?"Pools.trade discovery was cancelled; the historical scan is incomplete.":`Pools.trade global launch discovery reached its ${a} ms read budget; the historical scan is incomplete.`)]}catch(f){return[...n,b(`Pools.trade discovery could not finish: ${l.plainError(f)}`)]}finally{t=!1,m!==void 0&&clearTimeout(m),i&&d?.removeEventListener("abort",i)}}}};function Ye(l){return Ne("poolstrade",[qe(l)])}export{re as a,qe as b,Ye as c};
1
+ import{b as Ce,o as le}from"./GYPMUYB5.js";import{a as ue}from"./Z7FGEWO2.js";import{b as Ne}from"./SPJCSEKP.js";import{a as Ae}from"./IOYRL6AY.js";import{a as ve}from"./66F5ZH34.js";import{e as X,g as p,i as xe,n as Ie}from"./NWNYJ26T.js";import{b as A,j as Te}from"./TI727O2H.js";import{a as r}from"./XSD5NL7J.js";import{a as de}from"./JXOEJPJ4.js";import{decodeErrorResult as Me,decodeEventLog as ce,encodeAbiParameters as U,encodeFunctionData as C,erc20Abi as J,parseAbi as $e,parseAbiParameters as q,toHex as Be,zeroAddress as F}from"viem";var g=Te[A].poolsTrade,Y=g.liquidityLauncher.address,B=g.uerc20BeneficiaryVault.address,fe=g.universalRouter.address,ie=10n**27n,j=(1n<<128n)-1n,Se=`0x${"00".repeat(32)}`,D=63127652n,pe=100000n,ae=10000000n,Ue=2000n,me={address:ue,symbol:"ETH",decimals:18,chainId:A},h=$e(["function multicall(bytes[] data) payable returns (bytes[])","function createToken(address factory,string name,string symbol,uint8 decimals,uint128 initialSupply,address recipient,bytes tokenData) payable returns (address)","function distributeToken(address token,(address strategy,uint128 amount,bytes configData) distribution,bytes32 salt) payable","function distributeWithNative(address strategy,bytes configData,bytes32 salt,uint256 nativeAmount) payable","function getGraffiti(address sender) view returns (bytes32)","function getUERC20Address(string name,string symbol,uint8 decimals,address recipient,bytes32 graffiti) view returns (address)","function execute(bytes commands,bytes[] inputs,uint256 deadline) payable","function collectFees(uint256[] ids)","function claim(uint256 id,uint256 minCurrency0Amount,uint256 minCurrency1Amount)","function amounts(uint256 id) view returns (uint128 eth,uint128 token)","function ownerOf(uint256 id) view returns (address)","function getApproved(uint256 id) view returns (address)","function approve(address spender,uint256 id)","function safeTransferFrom(address from,address to,uint256 id)","function approve(address token,address spender,uint160 amount,uint48 expiration)","error V4TooLittleReceived(uint256 minAmountOut,uint256 amountOut)"]),K=$e(["event TokenLaunched(bytes32 indexed poolId,address indexed token,address indexed feeSplitter,(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey)","event Transfer(address indexed from,address indexed to,uint256 indexed tokenId)"]),V=[g.instantLaunchStrategyFeesOn.address,g.instantLaunchStrategyFeesOff.address];function re(l){if(l.status!=="success")throw new r("The launch receipt did not succeed.");let c=[];for(let k of l.logs){let H=V.findIndex(L=>p(L,k.address));if(H===-1||k.topics[0]!=="0x3b3d2bafdcae274a232217e1f80ee4305d3af6aa25c8b14b1681bd68d18042a4")continue;let G=ce({abi:K,eventName:"TokenLaunched",data:k.data,topics:[...k.topics]}),{token:x,poolId:ee,poolKey:M,feeSplitter:te}=G.args,_=H===0?g.feeSplitterFeesOn.address:g.feeSplitterFeesOff.address;if(!p(te,_)||!p(M.currency0,F)||!p(M.currency1,x)||M.fee!==2500||M.tickSpacing!==25||!p(M.hooks,F))throw new r("The launch does not match the current native ETH strategy.");let ne=l.logs.filter(L=>p(L.address,g.v4PositionManager.address)).flatMap(L=>{if(L.topics[0]!=="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef")return[];let O=ce({abi:K,eventName:"Transfer",data:L.data,topics:[...L.topics]}).args;return p(O.from,F)&&p(O.to,V[H])?[O.tokenId]:[]});if(ne.length!==1)throw new r("The launch receipt must identify one matching position mint.");c.push({token:x,poolId:ee,positionId:ne[0].toString(),creatorFees:H===0})}return c}function S(l){return xe(l,"Provide a valid wallet or token address.")}function P(l,c,k=!1){return Ie(l,`${c} is outside its supported range.`,{notString:`${c} must be an integer string in base units.`,positive:!k})}function Z(l,c,k=!1){if(k&&l===void 0)return"";if(typeof l!="string"||!k&&!l.trim()||l.length>4096)throw new r(`Provide a valid ${c}.`);return l}function he(l){if(typeof l!="string"||!/^0x[0-9a-fA-F]{64}$/.test(l))throw new r("Provide a valid launch transaction hash.");return l}function ge(l,c,k="minAmountOut"){let H=c.slippageBps??Ce;if(typeof H!="number")throw new r("Slippage must be an integer in basis points.");let G=le(l.toString(),H),x=c[k]===void 0?BigInt(G):P(c[k],k,l===0n);if(x>l||l>0n&&x===0n||x>j)throw new r("The minimum output must be positive and no larger than the simulated output.");return x}var qe=l=>{let c=l.clientFor(A),k=(e,o,n,s)=>l.unsignedTx({to:e,data:o,value:n.toString(),chainId:A,description:s}),H=e=>{throw new r(l.plainError(e))};async function G(){if(await c.getChainId()!==A)throw new r("pools.trade requires Robinhood Chain 4663.")}async function x(e,o,n){let s=await l.preview(e,o),t=s.changes.map(({token:a,amount:d})=>{let i=d.startsWith("-");return`${i?"-":""}${l.formatAmount(i?d.slice(1):d,a.decimals)} ${de(a.symbol)} (${a.address}, chain ${a.chainId})`});return{txs:e,summary:[n,s.summary,...t].join(" ")}}async function ee(){return(await c.getBlock()).timestamp+600n}function M(e,o,n,s,t,a){let d=[F,e,2500,25,F],i=[U(q("((address,address,uint24,int24,address),bool,uint128,uint128,uint256,bytes)"),[[d,o,n,s,0n,"0x"]]),U(q("address,uint256"),[o?F:e,n]),U(q("address,address,uint256"),[o?e:F,t,0n])],m=[U(q("bytes,bytes[]"),["0x060c0e",i])];return{inputs:m,encoded:U(q("bytes,bytes[],uint256"),["0x10",m,a])}}async function te(e,o){let n=await c.request({method:"eth_simulateV1",params:[{blockStateCalls:[{calls:e.map(i=>({from:o,gas:Be(Ae),to:i.to,data:i.data,value:Be(BigInt(i.value))}))}],validation:!1,traceTransfers:!1},"latest"]},{retryCount:0});if(!Array.isArray(n)||n.length!==1||!X(n[0])||!Array.isArray(n[0].calls)||n[0].calls.length!==e.length)throw new r("The output simulation returned a malformed response.");let s=n[0].calls;if(!s.slice(0,-1).every(i=>X(i)&&i.status==="0x1"&&!i.error))throw new r("A prerequisite failed during the output simulation.");let t=s.at(-1);if(!X(t)||t.status!=="0x0")throw new r("The output simulation did not return the expected minimum-output control.");let a=typeof t.returnData=="string"&&t.returnData!=="0x"?t.returnData:X(t.error)?t.error.data:void 0;if(typeof a!="string"||!/^0x[0-9a-fA-F]+$/.test(a))throw new r("The output simulation did not report an expected amount.");let d=Me({abi:h,data:a});if(d.errorName!=="V4TooLittleReceived"||d.args[0]!==j||d.args[1]<=0n||d.args[1]>=j)throw new r("The output simulation did not report a valid amount.");return d.args[1]}let _=new Map,ne=2e3;async function L(e,o,n,s=()=>!0){let t=await c.getBlockNumber(),a=t<D?0n:(t-D)/ae+1n,d=1n,i=(u=1n)=>{if(d+=u,d>Ue)throw new r("Pools.trade scan exceeds the 2000-request limit. Use launchTx for a specific launch; positions coverage is incomplete.")};i(a*BigInt(V.length+(e&&!n?1:0)));let m=new Map,b=new Set;for(let u=D;u<=t&&s();u+=ae){let f=u+ae-1n>t?t:u+ae-1n,y=(await Promise.all(V.map(T=>c.getLogs({address:T,event:K[0],...o?{args:{token:o}}:{},fromBlock:u,toBlock:f,strict:!0})))).flat(),$=[...new Set(y.map(T=>T.transactionHash))].filter(T=>!T||!m.has(T));for(let T=0;T<$.length&&s();T+=8)await Promise.all($.slice(T,T+8).map(async E=>{if(!E)throw new r("A launch log is missing its transaction hash.");let R=_.get(E);R||(i(),R=await c.getTransactionReceipt({hash:E}),_.size>=ne&&_.delete(_.keys().next().value),_.set(E,R)),m.set(E,R),s()&&await n?.(R)}));if(!s())break;if(e&&!n){let T=await c.getLogs({address:B,event:K[1],args:{to:e},fromBlock:u,toBlock:f,strict:!0});for(let E of T){let R=ce({abi:K,eventName:"Transfer",data:E.data,topics:E.topics}).args;b.add(R.tokenId.toString())}}}return{receipts:[...m.values()],feeIds:b}}async function O(e){let n=(e.launchTx!==void 0?[await c.getTransactionReceipt({hash:he(e.launchTx)})]:(await L(void 0,e.token===void 0?void 0:S(e.token))).receipts).flatMap(re).filter(s=>e.positionId!==void 0?s.positionId===P(e.positionId,"positionId").toString():p(s.token,S(e.token)));if(n.length!==1)throw new r("No unique current-strategy launch was found. Older strategy generations are unsupported.");return n[0]}async function Ee(e,o){if(typeof e.creatorFees!="boolean")throw new r("creatorFees must be an explicit boolean; the choice is permanent.");if(e.pair!==void 0&&!p(S(e.pair),F)&&!p(S(e.pair),ue))throw new r("Only the native ETH pair is supported.");if(e.decimals!==void 0&&e.decimals!==18)throw new r("Instant Launch requires 18 decimals.");if(e.supply!==void 0&&P(e.supply,"supply")!==ie)throw new r("Instant Launch requires a supply of one billion tokens.");let n=S(e.feeBeneficiary);if(p(n,F)||p(n,Y))throw new r("The fee beneficiary must be a wallet other than the launcher or zero address.");let s=Z(e.name,"name"),t=Z(e.symbol,"symbol"),a=e.initialBuy===void 0?0n:P(e.initialBuy,"initialBuy",!0);if(a>j)throw new r("The initial buy exceeds uint128.");if(a===0n&&e.minAmountOut!==void 0)throw new r("A minimum output requires an initial buy.");let d=await c.readContract({address:Y,abi:h,functionName:"getGraffiti",args:[o]}),i=S(await c.readContract({address:g.uerc20Factory.address,abi:h,functionName:"getUERC20Address",args:[s,t,18,Y,d]})),m=await c.getCode({address:i});if(m&&m!=="0x")throw new r("This wallet already launched that name and symbol.");let b=U(q("(string,string,string,bytes)"),[[Z(e.description,"description",!0),Z(e.website,"website",!0),Z(e.imageUri,"image URI",!0),"0x"]]),u=e.creatorFees?V[0]:V[1],f=[C({abi:h,functionName:"createToken",args:[g.uerc20Factory.address,s,t,18,ie,Y,b]}),C({abi:h,functionName:"distributeToken",args:[i,{strategy:u,amount:ie,configData:U(q("address"),[n])},Se]})],y=await ee(),v=T=>{let E=[...f];if(a>0n){let R=U(q("(address,address,bytes)"),[[fe,o,M(i,!0,a,T,o,y).encoded]]);E.push(C({abi:h,functionName:"distributeWithNative",args:[g.universalRouterStrategyApp.address,R,Se,a]}))}return k(Y,C({abi:h,functionName:"multicall",args:[E]}),a,`Atomic Instant Launch: creator fees ${e.creatorFees?"on":"off"} (permanent); beneficiary ${n}.`)},$=a>0n?ge(await te([v(j)],o),e):0n;return x([v($)],o,`Launch ${s} (${i}, chain 4663), supply 1000000000, decimals 18. Creator fees ${e.creatorFees?"on":"off"} are permanent; fee beneficiary ${n}. Creator ETH fees come from buys only (recorded 0.09996%); sells compound into locked liquidity. Initial-buy minimum ${$} token base units. Off-chain image/display unproven; no private metadata registration. No transaction sent.`)}async function Fe(e,o,n){let s=P(e.amountIn,"amountIn");if(s>j)throw new r("The trade amount exceeds uint128.");let t=S(e.token);await O(e);let a=await ee(),d=[];n||(await c.readContract({address:t,abi:J,functionName:"allowance",args:[o,g.permit2.address]})<s&&d.push(l.approval(t,g.permit2.address,s.toString(),A)),d.push(k(g.permit2.address,C({abi:h,functionName:"approve",args:[t,fe,s,Number(a)]}),0n,`Permit the exact ${s} token base units until ${a}.`)));let i=u=>[...d,k(fe,C({abi:h,functionName:"execute",args:["0x10",M(t,n,s,u,o,a).inputs,a]}),n?s:0n,`${n?"Buy":"Sell"} ${t} with minimum output ${u}.`)],m=await te(i(j),o),b=ge(m,e);return x(i(b),o,`${n?"Buy":"Sell"} token ${t} (chain 4663, 18 decimals), amountIn ${s}, minimum output ${b} ${n?"token":"ETH"} base units (18 decimals). Recorded swap fee 0.2899%; creator ETH fees from buys only, none from sells. No transaction sent.`)}async function we(e,o,n){let s=await O(e),t=BigInt(s.positionId),a=s.creatorFees?g.feeSplitterFeesOn.address:g.feeSplitterFeesOff.address,d=await c.readContract({address:g.v4PositionManager.address,abi:h,functionName:"ownerOf",args:[t]});if(!p(d,a))throw new r("The position is not locked in its current-strategy splitter.");if(!n)return x([k(a,C({abi:h,functionName:"collectFees",args:[[t]]}),0n,`Collect fees for position ${t}; permissionless.`)],o,"Collect fees for the entitled recipients; collection does not transfer creator fees to the collector. No transaction sent.");if(!s.creatorFees)throw new r("Creator fees are permanently disabled for this position.");let i=await c.readContract({address:B,abi:h,functionName:"ownerOf",args:[t]});if(!p(i,o))throw new r("Only the current fee NFT holder is entitled to claim.");let m=await c.readContract({address:B,abi:h,functionName:"amounts",args:[t]}),b=ge(m[0],e,"minEth");if(m[1]!==0n)throw new r("The current buy-only creator fee configuration returned unexpected token fees.");return x([k(B,C({abi:h,functionName:"claim",args:[t,b,0n]}),0n,`Claim collected ETH fees for position ${t} to ${o}.`)],o,`Claim collected fees: ${m[0]} ETH base units (18 decimals), minimum ${b}. Uncollected fees require poolstrade_collect first. No transaction sent.`)}async function Le(e,o){let n=await O(e),s=S(e.to);if(p(s,F))throw new r("The token recipient cannot be the zero address.");let t=P(e.amount,"amount"),a=await oe(n.token,await c.getBlockNumber());return x([k(a.address,C({abi:J,functionName:"transfer",args:[s,t]}),0n,`Transfer exactly ${t} ${de(a.symbol)} base units to ${s}.`)],o,`Transfer ${t} token base units (token ${a.address}, decimals ${a.decimals}, chain ${a.chainId}) to ${s}. No approval; no transaction sent.`)}async function Oe(e,o){if(!Array.isArray(e.positionIds)||e.positionIds.length<1||e.positionIds.length>20||!Array.isArray(e.launchTxs)||e.launchTxs.length!==e.positionIds.length)throw new r("Provide 1 to 20 positionIds and one matching launchTxs entry for each.");let n=e.positionIds.map(d=>P(d,"positionId").toString());if(new Set(n).size!==n.length)throw new r("Each position ID must appear once.");let s=e.launchTxs.map(he),t=new Map;for(let[d,i]of n.entries()){let b=(await O({positionId:i,launchTx:s[d]})).creatorFees?g.feeSplitterFeesOn.address:g.feeSplitterFeesOff.address,u=BigInt(i),f=await c.readContract({address:g.v4PositionManager.address,abi:h,functionName:"ownerOf",args:[u]});if(!p(f,b))throw new r("The position is not locked in its current-strategy splitter.");t.set(b,[...t.get(b)??[],u])}let a=[...t].map(([d,i])=>k(d,C({abi:h,functionName:"collectFees",args:[i]}),0n,`Collect fees for positions ${i.join(", ")}; permissionless.`));return x(a,o,"Collect fees in batches for the fixed entitled recipients. Collection does not pay the collector. No transaction sent.")}let Q="Current native ETH Instant Launch strategies only. Crowd Launch and older deployments are not covered.";async function oe(e,o){let[n,s]=await Promise.all([c.readContract({address:e,abi:J,functionName:"symbol",blockNumber:o}),c.readContract({address:e,abi:J,functionName:"decimals",blockNumber:o})]);if(typeof n!="string"||!n||n.length>256||s!==18)throw new r("The current launch token returned invalid metadata.");return{address:e,symbol:n,decimals:s,chainId:A}}async function be(e,o,n,s){let t=s??await oe(e.token,n),a=await c.readContract({address:t.address,abi:J,functionName:"balanceOf",args:[o],blockNumber:n});return{token:t,amount:a.toString(),humanAmount:l.formatAmount(a.toString(),t.decimals)}}async function Pe(e,o){let n=await O(e),s=await c.getBlockNumber();return{wallet:o,...await be(n,o,s),blockNumber:s.toString(),coverage:Q}}async function He(e,o){let n=he(e.launchTx),s=await c.getTransactionReceipt({hash:n}),t=re(s);if(e.token!==void 0&&(t=t.filter(i=>p(i.token,S(e.token)))),e.positionId!==void 0&&(t=t.filter(i=>i.positionId===P(e.positionId,"positionId").toString())),!t.length)throw new r("The receipt contains no matching current Instant Launch. Crowd Launch and older strategies are not covered.");let a=await c.getBlockNumber(),d=await Promise.all(t.map(async i=>{let m=i.creatorFees?g.feeSplitterFeesOn.address:g.feeSplitterFeesOff.address,b=await c.readContract({address:g.v4PositionManager.address,abi:h,functionName:"ownerOf",args:[BigInt(i.positionId)],blockNumber:a});if(!p(b,m))throw new r("The position is not locked in its current-strategy splitter.");let u=i.creatorFees?{owner:await c.readContract({address:B,abi:h,functionName:"ownerOf",args:[BigInt(i.positionId)],blockNumber:a}),approved:await c.readContract({address:B,abi:h,functionName:"getApproved",args:[BigInt(i.positionId)],blockNumber:a}),collected:await c.readContract({address:B,abi:h,functionName:"amounts",args:[BigInt(i.positionId)],blockNumber:a})}:void 0,f=await oe(i.token,a);return{...i,token:f,custodian:b,holding:await be(i,o,a,f),...u?{feeEntitlement:{owner:u.owner,approved:u.approved,collected:[{token:me,amount:u.collected[0].toString()},{token:f,amount:u.collected[1].toString()}],uncollectedFeesIncluded:!1}}:{}}}));return{launchTx:n,wallet:o,creator:s.from,blockNumber:a.toString(),launches:d,coverage:Q}}async function Re(e){let o=await c.getBlockNumber(),n=e.limit??20;if(typeof n!="number"||!Number.isInteger(n)||n<1||n>50)throw new r("limit must be an integer from 1 to 50.");let s=e.fromBlock===void 0?o>=D+pe?o-pe+1n:D:P(e.fromBlock,"fromBlock",!0),t=e.toBlock===void 0?o:P(e.toBlock,"toBlock",!0),a=0;if(e.cursor!==void 0){if(typeof e.cursor!="string"||!/^[0-9]{1,78}:[0-9]{1,78}:[0-9]{1,10}$/.test(e.cursor))throw new r("Provide the browse cursor exactly as returned.");let u=e.cursor.split(":"),f=BigInt(u[0]),y=BigInt(u[1]);if(e.fromBlock!==void 0&&s!==f||e.toBlock!==void 0&&t!==y)throw new r("The cursor does not match this block range.");s=f,t=y,a=Number(u[2])}if(o<D&&e.fromBlock===void 0&&e.toBlock===void 0&&e.cursor===void 0)return{launches:[],cursor:null,fromBlock:D.toString(),toBlock:o.toString(),coverage:Q,predeployment:!0};if(s<D||t<s||t>o||t-s>=pe)throw new r("Choose a deployed block range of at most 100000 blocks, ending no later than the current head.");let d=await c.getLogs({address:V,event:K[0],fromBlock:s,toBlock:t,strict:!0});if(d.some(u=>u.blockNumber===null||u.logIndex===null||!u.transactionHash))throw new r("The launch feed returned an incomplete log.");if(d.sort((u,f)=>u.blockNumber===f.blockNumber?f.logIndex-u.logIndex:u.blockNumber>f.blockNumber?-1:1),a>d.length)throw new r("The browse cursor is outside the launch feed.");let i=new Map,m=[];for(let u of d.slice(a,a+n)){let f=u.transactionHash,y=i.get(f);y||(y=await c.getTransactionReceipt({hash:f}),i.set(f,y));let v=ce({abi:K,eventName:"TokenLaunched",data:u.data,topics:u.topics}).args,$=re(y).filter(T=>p(T.token,v.token)&&p(T.poolId,v.poolId));if($.length!==1)throw new r("The launch feed log does not match one verified receipt launch.");m.push({...$[0],launchTx:f,blockNumber:u.blockNumber.toString(),token:await oe($[0].token,t),creator:y.from})}let b=a+n;return{launches:m,cursor:b<d.length?`${s}:${t}:${b}`:null,fromBlock:s.toString(),toBlock:t.toString(),coverage:Q,previousToBlock:s>D?(s-1n).toString():null,summary:"Newest launches first within this fixed block range. Empty does not establish absence outside the range or covered strategies."}}async function ye(e,o,n){let s=await O(e);if(!s.creatorFees)throw new r("Creator fees are permanently disabled for this position.");let t=BigInt(s.positionId),a=await c.readContract({address:g.v4PositionManager.address,abi:h,functionName:"ownerOf",args:[t]});if(!p(a,g.feeSplitterFeesOn.address))throw new r("The position is not locked in its current-strategy splitter.");let d=await c.readContract({address:B,abi:h,functionName:"ownerOf",args:[t]});if(!p(d,o))throw new r("Only the current fee NFT holder can change this entitlement.");let i=S(n?e.to:e.spender);if(p(i,B)||n&&p(i,F))throw new r("The fee NFT recipient cannot be the vault or zero address.");let m=n?C({abi:h,functionName:"safeTransferFrom",args:[o,i,t]}):C({abi:h,functionName:"approve",args:[i,t]});return x([k(B,m,0n,n?`Transfer fee NFT ${t} to ${i}, including accrued and future fees.`:`Approve ${i} for fee NFT ${t} only; zero address revokes approval.`)],o,n?`Transfer the entire fee entitlement for position ${t} to ${i}. This includes collected and future fees; locked LP remains in its splitter. No transaction sent.`:`Set the exact single-NFT approval for position ${t} to ${i}. This permits transfer of that fee entitlement; zero address revokes. No transaction sent.`)}async function De(){return{chainId:A,instant:{supported:!0,supply:ie.toString(),decimals:18,currency:me,permanentCreatorFeeChoice:!0},crowd:{status:"BLOCKED",strategy:"0xbf1aB81f7d534b2CC0Da76fcf4d541322bB0e000",factory:"0x000000001F26a0044BaA66024e7b6599c61963F8",missing:"A verified Pools-specific auction configuration (BlockNumberish timing, reserve allocation, Q96 floor/tick, USD FDV conversion, issuance steps, locked LP plan) and a bytecode-matched factory-created auction ABI with success/refund fixtures. Generic CCA parameters are not a verified Pools Crowd Launch.",source:"https://github.com/Uniswap/sdks/blob/main/sdks/liquidity-launcher-sdk/src/addresses.ts"},coverage:Q}}let w=e=>({type:"string",description:e}),I=e=>ve(e),se="Launched token contract address (0x + 40 hex digits).",z="Transaction hash (0x + 64 hex digits) of the token launch; lets the tool find the launch without scanning. Optional where the token or position is given.",W='Liquidity position NFT id for the launch, as a decimal string. Example: "1".',ke={chainId:{type:"integer",const:A,description:"Chain id; only 4663 (Robinhood Chain mainnet) is accepted. Optional."},slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage tolerance in basis points (50 = 0.5%) used to derive minimum outputs when none is given. Optional."}};function N(e,o,n,s){return{name:`poolstrade_${e}`,inputSchema:{type:"object",additionalProperties:!1,properties:{...ke,...o},required:n},execute:async(t,a)=>{try{let d=new Set([...Object.keys(ke),...Object.keys(o)]);if(Object.keys(t).some(i=>!d.has(i)))throw new r("Unsupported input for this pools.trade tool.");if(t.chainId!==void 0&&t.chainId!==A)throw new r("pools.trade requires chain 4663.");if(S(a),t.slippageBps!==void 0){if(typeof t.slippageBps!="number")throw new r("Slippage must be an integer in basis points.");le("10000",t.slippageBps)}return await G(),await s(t,a)}catch(d){H(d)}}}}return{tools:[N("launch",{name:w("Token name, shown in wallets and explorers."),symbol:w("Token ticker symbol."),creatorFees:{type:"boolean",description:"Permanent choice; must be explicit. true enables creator fees paid to feeBeneficiary from buys; false disables them forever."},feeBeneficiary:w("Address that receives creator fees; must not be the zero address or the launcher."),pair:w("Optional pair currency; only native ETH is supported (the zero address or the native ETH sentinel)."),decimals:{type:"integer",const:18,description:"Token decimals; must be 18 for an Instant Launch."},supply:I("Total token supply in base units (18 decimals); must be 1000000000000000000000000000 = one billion tokens."),initialBuy:I('ETH to spend on an initial buy in the same transaction, in wei base units (ETH has 18 decimals). Example: "1000000000000000" = 0.001 ETH.'),minAmountOut:I('Least new tokens to receive from the initial buy, in token base units (18 decimals). Requires initialBuy. Example: "1000000000000000000" = 1 token.'),description:w("Optional token description stored in token metadata."),website:w("Optional website URL stored in token metadata."),imageUri:w("Optional image URI stored in token metadata.")},["name","symbol","creatorFees","feeBeneficiary"],Ee),...["buy","sell"].map(e=>N(e,{token:w(se),amountIn:I(e==="buy"?'ETH to spend, in wei base units (ETH has 18 decimals). Example: "1000000000000000" = 0.001 ETH.':'Tokens to sell, in token base units (launched tokens have 18 decimals). Example: "1000000000000000000" = 1 token.'),minAmountOut:I(e==="buy"?'Least tokens to receive, in token base units (18 decimals). Example: "1000000000000000000" = 1 token. Defaults from slippageBps.':'Least ETH to receive, in wei base units (18 decimals). Example: "1000000000000000" = 0.001 ETH. Defaults from slippageBps.'),launchTx:w(z)},["token","amountIn"],(o,n)=>Fe(o,n,e==="buy"))),N("collect",{positionId:I(W),launchTx:w(z)},["positionId"],(e,o)=>we(e,o,!1)),N("claim",{positionId:I(W),launchTx:w(z),minEth:I('Least ETH you must receive from the claim, in wei base units (ETH has 18 decimals). Example: "1000000000000000" = 0.001 ETH.')},["positionId"],(e,o)=>we(e,o,!0)),N("browse",{fromBlock:I("First block number of the scan range, as a decimal string. Defaults to the most recent 100000 blocks."),toBlock:I("Last block number of the scan range, as a decimal string. Defaults to the latest block."),limit:{type:"integer",minimum:1,maximum:50,description:"Launches per page, 1 to 50 (default 20)."},cursor:w("Opaque pagination cursor exactly as returned by the previous browse call.")},[],Re),N("balance",{token:w(se),launchTx:w(z)},["token"],Pe),N("status",{launchTx:w("Transaction hash (0x + 64 hex digits) of the token launch to inspect."),token:w(se),positionId:I(W)},["launchTx"],He),N("launch_options",{},[],De),N("fee_transfer",{positionId:I(W),launchTx:w(z),to:w("Address that will become the new holder of the fee NFT and its future creator fees. Use the intended address.")},["positionId","to"],(e,o)=>ye(e,o,!0)),N("fee_approve",{positionId:I(W),launchTx:w(z),spender:w("Address approved to move the fee NFT. Use the intended address.")},["positionId","spender"],(e,o)=>ye(e,o,!1)),N("transfer",{token:w(se),amount:I('Tokens to send, in token base units (launched tokens have 18 decimals). Example: "1000000000000000000" = 1 token.'),to:w("Recipient address of the tokens; must not be the zero address. Use the intended address."),launchTx:w(z)},["token","amount","to"],Le),N("collect_many",{positionIds:{type:"array",items:I(W),minItems:1,maxItems:20,description:"Position NFT ids to collect fees for, decimal strings; same order as launchTxs."},launchTxs:{type:"array",items:w("Launch transaction hash (0x + 64 hex digits) matching the position id at the same index."),minItems:1,maxItems:20,description:"Launch transaction hashes, one per position id, in the same order."}},["positionIds","launchTxs"],Oe)],positions:async(e,o)=>{S(e);let n=[],s=0,t=!0,a=o?.deepScan?2e4:6e3,d=o?.signal,i,m,b=f=>({module:"poolstrade",id:"poolstrade-discovery-incomplete",chainId:A,assets:[],incomplete:!0,description:`${f} Checked ${s} launch receipts. Readable holdings are retained. Check a known launch with poolstrade_status {"launchTx":"<hash>"} or its token holding with poolstrade_balance {"token":"<address>","launchTx":"<hash>"}. Crowd Launch and older deployments are outside this reader's coverage.`}),u=async()=>{await G(),t&&await L(e,void 0,async f=>{s++;for(let y of re(f)){if(!t)return;let v=y.creatorFees&&p(await c.readContract({address:B,abi:h,functionName:"ownerOf",args:[BigInt(y.positionId)]}),e);if(!t)return;if(!v&&!p(f.from,e))continue;let $=v?[{token:me,amount:(await c.readContract({address:B,abi:h,functionName:"amounts",args:[BigInt(y.positionId)]}))[0].toString()}]:[];t&&n.push({module:"poolstrade",id:y.positionId,chainId:A,assets:$,description:`Current Instant Launch ${y.token} (18 decimals, supply 1000000000), pool ${y.poolId}; creator fees ${y.creatorFees?"on":"off"} (permanent). ${v?"Collected ETH fees only; uncollected fees excluded.":"Launch record; no fee entitlement held."} Liquidity is permanently locked.`})}},()=>t)};try{if(d?.aborted)return[b("Pools.trade discovery was cancelled; the historical scan is incomplete.")];let f=new Promise(v=>{i=()=>{t=!1,v("aborted")},d?.addEventListener("abort",i,{once:!0}),m=setTimeout(()=>{t=!1,v("budget")},a)}),y=await Promise.race([u().then(()=>"complete"),f]);return y==="complete"?n:[...n,b(y==="aborted"?"Pools.trade discovery was cancelled; the historical scan is incomplete.":`Pools.trade global launch discovery reached its ${a} ms read budget; the historical scan is incomplete.`)]}catch(f){return[...n,b(`Pools.trade discovery could not finish: ${l.plainError(f)}`)]}finally{t=!1,m!==void 0&&clearTimeout(m),i&&d?.removeEventListener("abort",i)}}}};function Ye(l){return Ne("poolstrade",[qe(l)])}export{re as a,qe as b,Ye as c};
@@ -1 +1 @@
1
- import{a as m}from"./DFM4T6ZE.js";import{a as p,e as y}from"./VXCGMALF.js";import{o as v}from"./QLFPAN6S.js";import{a as f}from"./66F5ZH34.js";import{b as l}from"./TI727O2H.js";import{a as u}from"./XSD5NL7J.js";import{encodeFunctionData as w,getAddress as a,parseAbi as I}from"viem";var P="(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks)",$="(address tokenIn,address tokenOut,uint24 fee,address recipient,uint256 amountIn,uint256 amountOutMinimum,uint160 sqrtPriceLimitX96)",g=I([`function swapExactIn(${P} key,bool zeroForOne,uint128 amountIn,uint256 minOut,uint160 sqrtPriceLimitX96,address to,uint256 deadline) returns (uint256 paid,uint256 out)`,`function exactInputSingle(${$} params) payable returns (uint256 amountOut)`,"function multicall(uint256 deadline,bytes[] data) payable returns (bytes[] results)"]),E=I(["function quoteExactInputSingle((address tokenIn,address tokenOut,uint256 amountIn,uint24 fee,uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut,uint160 sqrtPriceX96After,uint32 initializedTicksCrossed,uint256 gasEstimate)"]),_=I([`function quoteExactInputSingle((${P} poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountOut,uint256 gasEstimate)`]),C="0x0000000000000000000000000000000000000000",h={symbol:{type:"string",enum:m.tokens.map(e=>e.symbol),description:'Official stock ticker with a published Priors pool. Example: "TSLA".'},side:{type:"string",enum:["buy","sell"],description:'Choose "buy": pay USDG for the stock token; "sell": pay the stock token for USDG.'},amountIn:f('Input amount in base units: USDG (6 decimals) to buy, or the stock token (its decimals) to sell. Example: "1000000" = 1 USDG.')};async function O(e,o){let n=m.tokens.find(s=>s.symbol===e.symbol);if(!n||e.side!=="buy"&&e.side!=="sell")throw new u("Choose a published stock symbol and buy or sell.");let t=await v(String(e.symbol),{context:o});if(t.kind!=="official_stock"||t.address!==a(n.token))throw new u("Published Priors stock pool does not match the official stock contract address. Retry after the pool mapping is updated.");let r=y(e.amountIn,"amountIn",128);if(r===0n)throw new u("amountIn must be positive base units.");return{token:n,identity:t,amount:r,input:e.side==="buy"?p.usdg:a(n.token),output:e.side==="buy"?a(n.token):p.usdg}}function x(e,o,n){let[t,r]=BigInt(p.usdg)<BigInt(e)?[p.usdg,e]:[e,p.usdg];return{currency0:t,currency1:r,fee:o,tickSpacing:n,hooks:C}}function R(e){return{tools:[{name:"priors_stock_quote",inputSchema:{type:"object",properties:h,required:Object.keys(h),additionalProperties:!1},async execute(o,n){if(e.network==="testnet")throw new u("Priors stock swaps require mainnet chain 4663.");let t=await O(o,e),r=e.clientFor(l),s=await r.getBlockNumber({cacheTime:0}),k=await Promise.all(t.token.pools.map(async(i,d)=>{try{let c=x(a(t.token.token),i.fee,"tickSpacing"in i?i.tickSpacing:0),b=i.v===3?await r.simulateContract({address:a(m.v3.quoter),abi:E,functionName:"quoteExactInputSingle",args:[{tokenIn:t.input,tokenOut:t.output,amountIn:t.amount,fee:i.fee,sqrtPriceLimitX96:0n}],account:n,blockNumber:s}):await r.simulateContract({address:a(m.v4.quoter),abi:_,functionName:"quoteExactInputSingle",args:[{poolKey:c,zeroForOne:t.input===c.currency0,exactAmount:t.amount,hookData:"0x"}],account:n,blockNumber:s});return{poolIndex:d,version:i.v,amountOut:b.result[0].toString()}}catch(c){return{poolIndex:d,version:i.v,error:e.plainError(c)}}}));return{chainId:l,blockNumber:s.toString(),token:t.identity,quotes:k,warning:"Use explicit minimum output with priors_stock_swap and inspect its preview. Issuer restrictions can prevent sale. Quote is no promise of an exit; local regional eligibility remains required."}}},{name:"priors_stock_swap",inputSchema:{type:"object",properties:{...h,poolIndex:{type:"integer",minimum:0,maximum:2,description:"Index of the published pool to use, from priors_stock_quote (0 to 2)."},minOut:f("Minimum output in base units: the stock token when buying, USDG (6 decimals) when selling. Must be positive."),deadline:f("Deadline in Unix seconds, within the next 30 minutes. Example: 1800000000."),eligible:{type:"boolean",description:"Operator/user affirms eligibility for this stock-token trade in their jurisdiction."}},required:[...Object.keys(h),"poolIndex","minOut","deadline","eligible"],additionalProperties:!1},async execute(o,n){if(e.network==="testnet")throw new u("Priors stock swaps require mainnet chain 4663.");if(n=a(n),o.eligible!==!0)throw new u("Confirm local eligibility for Robinhood stock tokens before trading.");let t=await O(o,e),r=y(o.minOut,"minOut"),s=y(o.deadline,"deadline"),k=BigInt(Math.floor(Date.now()/1e3));if(r===0n||s<=k||s>k+1800n||!Number.isSafeInteger(o.poolIndex))throw new u("Provide positive minOut, poolIndex and a deadline within 30 minutes.");let i=t.token.pools[o.poolIndex];if(!i)throw new u("No published pool at that index. Read priors_stock_quote.");let d=x(a(t.token.token),i.fee,"tickSpacing"in i?i.tickSpacing:0),c=t.input===d.currency0,b=a(i.v===3?m.v3.router:m.v4.swapper),q=i.v===3?w({abi:g,functionName:"multicall",args:[s,[w({abi:g,functionName:"exactInputSingle",args:[{tokenIn:t.input,tokenOut:t.output,fee:i.fee,recipient:n,amountIn:t.amount,amountOutMinimum:r,sqrtPriceLimitX96:0n}]})]]}):w({abi:g,functionName:"swapExactIn",args:[d,c,t.amount,r,c?4295128740n:1461446703485210103287273052203988822378723970341n,n,s]}),S=[e.approval(t.input,b,t.amount.toString(),l),e.unsignedTx({to:b,data:q,value:"0",chainId:l,description:`Priors stock ${o.side}: ${t.amount} input base units; minimum ${r}; pinned V${i.v} pool.`})],A=await e.preview(S,n);return{txs:S,expiresAt:s.toString(),summary:`Stock ${o.side} ${o.symbol}: input ${t.amount} base units (${t.input}), minimum output ${r} (${t.output}), receiver ${n}, deadline ${s}. Issuer transfer/sale restrictions apply. Price impact is not measured by this builder; inspect minOut and the preview. ${A.summary}`}}}]}}export{g as a,R as b};
1
+ import{a as p,e as y}from"./VXCGMALF.js";import{a as m}from"./DFM4T6ZE.js";import{o as v}from"./W7QNSNOH.js";import{a as f}from"./66F5ZH34.js";import{b as l}from"./TI727O2H.js";import{a as u}from"./XSD5NL7J.js";import{encodeFunctionData as w,getAddress as a,parseAbi as I}from"viem";var P="(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks)",$="(address tokenIn,address tokenOut,uint24 fee,address recipient,uint256 amountIn,uint256 amountOutMinimum,uint160 sqrtPriceLimitX96)",g=I([`function swapExactIn(${P} key,bool zeroForOne,uint128 amountIn,uint256 minOut,uint160 sqrtPriceLimitX96,address to,uint256 deadline) returns (uint256 paid,uint256 out)`,`function exactInputSingle(${$} params) payable returns (uint256 amountOut)`,"function multicall(uint256 deadline,bytes[] data) payable returns (bytes[] results)"]),E=I(["function quoteExactInputSingle((address tokenIn,address tokenOut,uint256 amountIn,uint24 fee,uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut,uint160 sqrtPriceX96After,uint32 initializedTicksCrossed,uint256 gasEstimate)"]),_=I([`function quoteExactInputSingle((${P} poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountOut,uint256 gasEstimate)`]),C="0x0000000000000000000000000000000000000000",h={symbol:{type:"string",enum:m.tokens.map(e=>e.symbol),description:'Official stock ticker with a published Priors pool. Example: "TSLA".'},side:{type:"string",enum:["buy","sell"],description:'Choose "buy": pay USDG for the stock token; "sell": pay the stock token for USDG.'},amountIn:f('Input amount in base units: USDG (6 decimals) to buy, or the stock token (its decimals) to sell. Example: "1000000" = 1 USDG.')};async function O(e,o){let n=m.tokens.find(s=>s.symbol===e.symbol);if(!n||e.side!=="buy"&&e.side!=="sell")throw new u("Choose a published stock symbol and buy or sell.");let t=await v(String(e.symbol),{context:o});if(t.kind!=="official_stock"||t.address!==a(n.token))throw new u("Published Priors stock pool does not match the official stock contract address. Retry after the pool mapping is updated.");let r=y(e.amountIn,"amountIn",128);if(r===0n)throw new u("amountIn must be positive base units.");return{token:n,identity:t,amount:r,input:e.side==="buy"?p.usdg:a(n.token),output:e.side==="buy"?a(n.token):p.usdg}}function x(e,o,n){let[t,r]=BigInt(p.usdg)<BigInt(e)?[p.usdg,e]:[e,p.usdg];return{currency0:t,currency1:r,fee:o,tickSpacing:n,hooks:C}}function R(e){return{tools:[{name:"priors_stock_quote",inputSchema:{type:"object",properties:h,required:Object.keys(h),additionalProperties:!1},async execute(o,n){if(e.network==="testnet")throw new u("Priors stock swaps require mainnet chain 4663.");let t=await O(o,e),r=e.clientFor(l),s=await r.getBlockNumber({cacheTime:0}),k=await Promise.all(t.token.pools.map(async(i,d)=>{try{let c=x(a(t.token.token),i.fee,"tickSpacing"in i?i.tickSpacing:0),b=i.v===3?await r.simulateContract({address:a(m.v3.quoter),abi:E,functionName:"quoteExactInputSingle",args:[{tokenIn:t.input,tokenOut:t.output,amountIn:t.amount,fee:i.fee,sqrtPriceLimitX96:0n}],account:n,blockNumber:s}):await r.simulateContract({address:a(m.v4.quoter),abi:_,functionName:"quoteExactInputSingle",args:[{poolKey:c,zeroForOne:t.input===c.currency0,exactAmount:t.amount,hookData:"0x"}],account:n,blockNumber:s});return{poolIndex:d,version:i.v,amountOut:b.result[0].toString()}}catch(c){return{poolIndex:d,version:i.v,error:e.plainError(c)}}}));return{chainId:l,blockNumber:s.toString(),token:t.identity,quotes:k,warning:"Use explicit minimum output with priors_stock_swap and inspect its preview. Issuer restrictions can prevent sale. Quote is no promise of an exit; local regional eligibility remains required."}}},{name:"priors_stock_swap",inputSchema:{type:"object",properties:{...h,poolIndex:{type:"integer",minimum:0,maximum:2,description:"Index of the published pool to use, from priors_stock_quote (0 to 2)."},minOut:f("Minimum output in base units: the stock token when buying, USDG (6 decimals) when selling. Must be positive."),deadline:f("Deadline in Unix seconds, within the next 30 minutes. Example: 1800000000."),eligible:{type:"boolean",description:"Operator/user affirms eligibility for this stock-token trade in their jurisdiction."}},required:[...Object.keys(h),"poolIndex","minOut","deadline","eligible"],additionalProperties:!1},async execute(o,n){if(e.network==="testnet")throw new u("Priors stock swaps require mainnet chain 4663.");if(n=a(n),o.eligible!==!0)throw new u("Confirm local eligibility for Robinhood stock tokens before trading.");let t=await O(o,e),r=y(o.minOut,"minOut"),s=y(o.deadline,"deadline"),k=BigInt(Math.floor(Date.now()/1e3));if(r===0n||s<=k||s>k+1800n||!Number.isSafeInteger(o.poolIndex))throw new u("Provide positive minOut, poolIndex and a deadline within 30 minutes.");let i=t.token.pools[o.poolIndex];if(!i)throw new u("No published pool at that index. Read priors_stock_quote.");let d=x(a(t.token.token),i.fee,"tickSpacing"in i?i.tickSpacing:0),c=t.input===d.currency0,b=a(i.v===3?m.v3.router:m.v4.swapper),q=i.v===3?w({abi:g,functionName:"multicall",args:[s,[w({abi:g,functionName:"exactInputSingle",args:[{tokenIn:t.input,tokenOut:t.output,fee:i.fee,recipient:n,amountIn:t.amount,amountOutMinimum:r,sqrtPriceLimitX96:0n}]})]]}):w({abi:g,functionName:"swapExactIn",args:[d,c,t.amount,r,c?4295128740n:1461446703485210103287273052203988822378723970341n,n,s]}),S=[e.approval(t.input,b,t.amount.toString(),l),e.unsignedTx({to:b,data:q,value:"0",chainId:l,description:`Priors stock ${o.side}: ${t.amount} input base units; minimum ${r}; pinned V${i.v} pool.`})],A=await e.preview(S,n);return{txs:S,expiresAt:s.toString(),summary:`Stock ${o.side} ${o.symbol}: input ${t.amount} base units (${t.input}), minimum output ${r} (${t.output}), receiver ${n}, deadline ${s}. Issuer transfer/sale restrictions apply. Price impact is not measured by this builder; inspect minOut and the preview. ${A.summary}`}}}]}}export{g as a,R as b};