@oakagentkit/core 0.3.0 → 0.3.2

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 (266) 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.d.ts +2 -1
  76. package/build/dist/api/modules/morpho/index.js +1 -1
  77. package/build/dist/api/modules/morpho/local-guard.d.ts +3 -2
  78. package/build/dist/api/modules/morpho/local-guard.js +1 -1
  79. package/build/dist/api/modules/morpho/midnight.js +1 -1
  80. package/build/dist/api/modules/morpho/protocol.js +1 -1
  81. package/build/dist/api/modules/morpho/surface.js +1 -1
  82. package/build/dist/api/modules/morpho/vault-tools.js +1 -1
  83. package/build/dist/api/modules/netnet/card-plan.js +1 -1
  84. package/build/dist/api/modules/netnet/card-read.js +1 -1
  85. package/build/dist/api/modules/netnet/card-recovery.js +1 -1
  86. package/build/dist/api/modules/netnet/desk-action.js +1 -1
  87. package/build/dist/api/modules/netnet/financial.js +1 -1
  88. package/build/dist/api/modules/netnet/index.js +1 -1
  89. package/build/dist/api/modules/orbio/index.js +1 -1
  90. package/build/dist/api/modules/pendle/index.js +1 -1
  91. package/build/dist/api/modules/pendle/reader.js +1 -1
  92. package/build/dist/api/modules/pons/claim.js +1 -1
  93. package/build/dist/api/modules/pons/index.js +1 -1
  94. package/build/dist/api/modules/pons/launch-status.js +1 -1
  95. package/build/dist/api/modules/pons/reads.js +1 -1
  96. package/build/dist/api/modules/pons/swap-terms.d.ts +2 -8
  97. package/build/dist/api/modules/pons/swap-terms.js +1 -1
  98. package/build/dist/api/modules/pons/trade.js +1 -1
  99. package/build/dist/api/modules/poolstrade/index.js +1 -1
  100. package/build/dist/api/modules/priors/coverage.js +1 -1
  101. package/build/dist/api/modules/priors/discovery.js +1 -1
  102. package/build/dist/api/modules/priors/holdings.js +1 -1
  103. package/build/dist/api/modules/priors/index.js +1 -1
  104. package/build/dist/api/modules/priors/integration.js +1 -1
  105. package/build/dist/api/modules/priors/stock-swap.js +1 -1
  106. package/build/dist/api/modules/raeto/index.js +1 -1
  107. package/build/dist/api/modules/relay/discovery.js +1 -1
  108. package/build/dist/api/modules/relay/inbound.js +1 -1
  109. package/build/dist/api/modules/relay/index.js +1 -1
  110. package/build/dist/api/modules/relay/outbound-status.js +1 -1
  111. package/build/dist/api/modules/spark/index.js +1 -1
  112. package/build/dist/api/modules/steakhouse/analytics.js +1 -1
  113. package/build/dist/api/modules/steakhouse/index.js +1 -1
  114. package/build/dist/api/modules/steakhouse/local-guard.js +1 -1
  115. package/build/dist/api/modules/steakhouse/management.js +1 -1
  116. package/build/dist/api/modules/steakhouse/v2-exit.js +1 -1
  117. package/build/dist/api/modules/tickerspring/basket-routes.js +1 -1
  118. package/build/dist/api/modules/tickerspring/contract-reads.js +1 -1
  119. package/build/dist/api/modules/tickerspring/exit-preview.js +1 -1
  120. package/build/dist/api/modules/tickerspring/guards.js +1 -1
  121. package/build/dist/api/modules/tickerspring/index.js +1 -1
  122. package/build/dist/api/modules/tickerspring/journeys.js +1 -1
  123. package/build/dist/api/modules/tickerspring/ladder.js +1 -1
  124. package/build/dist/api/modules/tickerspring/maker.js +1 -1
  125. package/build/dist/api/modules/tickerspring/order-accounting.js +1 -1
  126. package/build/dist/api/modules/tickerspring/research.js +1 -1
  127. package/build/dist/api/modules/tickerspring/strategies.js +1 -1
  128. package/build/dist/api/modules/uniswap/auction-create.js +1 -1
  129. package/build/dist/api/modules/uniswap/auction.js +1 -1
  130. package/build/dist/api/modules/uniswap/batch.js +1 -1
  131. package/build/dist/api/modules/uniswap/common.js +1 -1
  132. package/build/dist/api/modules/uniswap/fees.js +1 -1
  133. package/build/dist/api/modules/uniswap/index.js +1 -1
  134. package/build/dist/api/modules/uniswap/local-guard.js +1 -1
  135. package/build/dist/api/modules/uniswap/oracle.js +1 -1
  136. package/build/dist/api/modules/uniswap/pool-math.js +1 -1
  137. package/build/dist/api/modules/uniswap/pools.js +1 -1
  138. package/build/dist/api/modules/uniswap/position.js +1 -1
  139. package/build/dist/api/modules/uniswap/protocol.js +1 -1
  140. package/build/dist/api/modules/uniswap/quote-guard.js +1 -1
  141. package/build/dist/api/modules/uniswap/token-jar.js +1 -1
  142. package/build/dist/api/modules/uniswap/trade-batch.js +1 -1
  143. package/build/dist/api/modules/uniswap/trade.js +1 -1
  144. package/build/dist/api/modules/uniswap/v2.js +1 -1
  145. package/build/dist/api/modules/uniswap/v3.js +1 -1
  146. package/build/dist/api/modules/uniswap/v4.js +1 -1
  147. package/build/dist/api/modules/uniswap/wrap.js +1 -1
  148. package/build/dist/api/modules/velora/claims.js +1 -1
  149. package/build/dist/api/modules/velora/index.js +1 -1
  150. package/build/dist/api/modules/wormhole/index.js +1 -1
  151. package/build/dist/api/prices.d.ts +5 -0
  152. package/build/dist/api/prices.js +1 -1
  153. package/build/dist/api/signing-registry.js +1 -1
  154. package/build/dist/api/swap.d.ts +1 -0
  155. package/build/dist/api/swap.js +1 -1
  156. package/build/dist/api/tokens.js +1 -1
  157. package/build/dist/api/universal-router.d.ts +45 -0
  158. package/build/dist/api/universal-router.js +1 -0
  159. package/build/dist/api/usd-estimate.js +1 -1
  160. package/build/dist/chunks/{ROQQ62LP.js → 22TU5PFT.js} +1 -1
  161. package/build/dist/chunks/{2WRXH6BL.js → 257N7343.js} +1 -1
  162. package/build/dist/chunks/{B2HSLY5F.js → 27PVS6BU.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/{TMRAF2L2.js → 3UQXTZ5R.js} +1 -1
  168. package/build/dist/chunks/43BG2JRB.js +1 -0
  169. package/build/dist/chunks/{KMSAUFYV.js → 47HSRR7G.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/{6OCLWSMZ.js → 5CPB33XA.js} +1 -1
  173. package/build/dist/chunks/{X5AL3DUK.js → 6D3XNCOX.js} +1 -1
  174. package/build/dist/chunks/{W4RYRLL5.js → 6GWXPQZ6.js} +1 -1
  175. package/build/dist/chunks/{D2IYA4LP.js → 72EV7TGI.js} +1 -1
  176. package/build/dist/chunks/{KBU3PYP7.js → 73BZPPRS.js} +1 -1
  177. package/build/dist/chunks/{XV3YJ4P6.js → 7FIEBJOZ.js} +1 -1
  178. package/build/dist/chunks/{CI5ENLYA.js → 7FZXSYFD.js} +1 -1
  179. package/build/dist/chunks/{K4P5VYDP.js → 7TSIF3F4.js} +1 -1
  180. package/build/dist/chunks/{KZA5GYZR.js → AWV24X7F.js} +1 -1
  181. package/build/dist/chunks/{WOGWLFAL.js → BGVC5NI6.js} +1 -1
  182. package/build/dist/chunks/BJK75C7G.js +1 -0
  183. package/build/dist/chunks/BSX4LFYI.js +1 -0
  184. package/build/dist/chunks/{OTYB6BHK.js → BZPFPQ2I.js} +1 -1
  185. package/build/dist/chunks/{XBNZ7GTY.js → CXH46MHJ.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/{GP6YO24Z.js → FSYYD3OM.js} +1 -1
  192. package/build/dist/chunks/{XEBMS5KU.js → GGMVT5A6.js} +1 -1
  193. package/build/dist/chunks/GK3D7OKG.js +1 -0
  194. package/build/dist/chunks/GYPMUYB5.js +1 -0
  195. package/build/dist/chunks/{U7UPLF4F.js → H64QC4QR.js} +1 -1
  196. package/build/dist/chunks/{HS5HWBMU.js → HIG7JY3J.js} +1 -1
  197. package/build/dist/chunks/{65356YKW.js → HPY2ONAS.js} +1 -1
  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/{QMEGAKLI.js → I3ZBOSSH.js} +1 -1
  201. package/build/dist/chunks/{YARZE7SJ.js → I4473OC6.js} +1 -1
  202. package/build/dist/chunks/{DMB64UIN.js → IJ4HZIDG.js} +1 -1
  203. package/build/dist/chunks/{YBLJ75U5.js → IPU656WB.js} +1 -1
  204. package/build/dist/chunks/{QLAOBULN.js → JTPHZCO3.js} +1 -1
  205. package/build/dist/chunks/{CSOO4SW7.js → K4GUZ5QS.js} +1 -1
  206. package/build/dist/chunks/{WBNFRPAT.js → KLEJ3W4T.js} +1 -1
  207. package/build/dist/chunks/{ACH4BSME.js → KOKLM63Q.js} +1 -1
  208. package/build/dist/chunks/{VB36EHIR.js → KVVBT43U.js} +1 -1
  209. package/build/dist/chunks/{6MDYKE2O.js → KXX7ZBFY.js} +1 -1
  210. package/build/dist/chunks/{I6PQW2JI.js → L2AE32SL.js} +1 -1
  211. package/build/dist/chunks/{KOTGFD2V.js → LGLWEGPY.js} +1 -1
  212. package/build/dist/chunks/{2HN3U6OG.js → LQSPWRHN.js} +1 -1
  213. package/build/dist/chunks/{C3WBHFLX.js → LTDF2LNP.js} +1 -1
  214. package/build/dist/chunks/{RNCMXKKS.js → M4AGEGWW.js} +1 -1
  215. package/build/dist/chunks/{OODSXDIH.js → MGVX5EUH.js} +1 -1
  216. package/build/dist/chunks/NCAV7Q4C.js +6 -0
  217. package/build/dist/chunks/{CZQ2CGYV.js → NUERUFH7.js} +1 -1
  218. package/build/dist/chunks/NV6FDIYT.js +1 -0
  219. package/build/dist/chunks/{A2V4NFVA.js → O3CC5SRM.js} +1 -1
  220. package/build/dist/chunks/{JI5DXDMY.js → ODV3XT5U.js} +1 -1
  221. package/build/dist/chunks/{HVFMIURK.js → OFWTO4N6.js} +1 -1
  222. package/build/dist/chunks/{B7BNDW35.js → OY5W7ZSL.js} +1 -1
  223. package/build/dist/chunks/{CD2JQ32C.js → PDGYM2WG.js} +1 -1
  224. package/build/dist/chunks/PHGHJ7SN.js +1 -0
  225. package/build/dist/chunks/{5R576SDB.js → PKYQ3XVA.js} +1 -1
  226. package/build/dist/chunks/{FN6GNTPR.js → PWJVC2FV.js} +1 -1
  227. package/build/dist/chunks/{PSGRZWES.js → QN45T4N3.js} +1 -1
  228. package/build/dist/chunks/{LJJYYUEG.js → QPY6UTLU.js} +1 -1
  229. package/build/dist/chunks/{ATEVAJ5Y.js → RA7DOR7F.js} +1 -1
  230. package/build/dist/chunks/{U762746N.js → RUSXMQSJ.js} +1 -1
  231. package/build/dist/chunks/{UPKVD7WG.js → RXP7ZUPY.js} +1 -1
  232. package/build/dist/chunks/{2QGLPY2D.js → SMKO7GKX.js} +1 -1
  233. package/build/dist/chunks/{EHK7CDTU.js → SNCV6HV7.js} +1 -1
  234. package/build/dist/chunks/{Q7L3BX6U.js → SO6O7JK2.js} +1 -1
  235. package/build/dist/chunks/{2ZQ7X223.js → SOJHYMD7.js} +1 -1
  236. package/build/dist/chunks/SVKG4JOY.js +3 -0
  237. package/build/dist/chunks/{ORG6LVKJ.js → UBI3HBXD.js} +1 -1
  238. package/build/dist/chunks/{NWPAQER2.js → UCHJYWGU.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/{MMCM3GSM.js → V4UJMUIB.js} +1 -1
  243. package/build/dist/chunks/{ZNPVBNC5.js → VC5ZCQYZ.js} +1 -1
  244. package/build/dist/chunks/{FGEGJOAA.js → VDJPDIBV.js} +1 -1
  245. package/build/dist/chunks/{TGFQQCRY.js → VFM2BICB.js} +1 -1
  246. package/build/dist/chunks/{MSMHS456.js → VOJULRNU.js} +1 -1
  247. package/build/dist/chunks/{5W74Z4WZ.js → W3DGFMQE.js} +1 -1
  248. package/build/dist/chunks/{QLFPAN6S.js → W7QNSNOH.js} +1 -1
  249. package/build/dist/chunks/{2ZBSE2LD.js → WCI3FHWT.js} +1 -1
  250. package/build/dist/chunks/X5I5EJ5T.js +6 -0
  251. package/build/dist/chunks/{JPPQDELB.js → XKLXVTSE.js} +3 -3
  252. package/build/dist/chunks/{OQFNUDMQ.js → XVOW6UCI.js} +1 -1
  253. package/build/dist/chunks/{P6OB2AFW.js → Y7HBFQYG.js} +1 -1
  254. package/build/dist/chunks/{25C4DTVA.js → YAVWSW3G.js} +1 -1
  255. package/build/dist/chunks/{LDJI2JAL.js → YGW4ODAP.js} +1 -1
  256. package/build/dist/chunks/{U243AWCH.js → YW4W3LPQ.js} +1 -1
  257. package/build/dist/chunks/{S4UJDZGN.js → ZDCCFEVL.js} +1 -1
  258. package/build/dist/chunks/{D7QXZM3S.js → ZOLHVZDK.js} +1 -1
  259. package/build/dist/chunks/{SMSXZ3FN.js → ZSVAGOF2.js} +1 -1
  260. package/package.json +1 -1
  261. package/build/dist/chunks/4R3G3H42.js +0 -1
  262. package/build/dist/chunks/LKX5WDOQ.js +0 -1
  263. package/build/dist/chunks/ND32LJWI.js +0 -1
  264. package/build/dist/chunks/URBEK2VV.js +0 -1
  265. package/build/dist/chunks/UVAR6BHU.js +0 -1
  266. 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 Ge}from"./7MR37STI.js";import{a as oe}from"./3CCBUYUM.js";import{a as Ze,b as Ee,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 Ne,g as R,i as Oe}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 Xo,getAddress as ao,parseAbi as pt,zeroAddress as Yo}from"viem";import{decodeAbiParameters as mo,encodeFunctionData as po,getAddress as le,parseAbiParameters as fo,zeroAddress as he,zeroHash as Dt}from"viem";import{decodeAbiParameters as no,encodeFunctionData as so,erc20Abi as io,getAddress as Ct,parseAbi as lo,parseAbiParameters as co,zeroHash as Mt}from"viem";var et=Ct("0xCE29862924756584BBD0D75CA1249d22007E2813"),Lt="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",uo="(uint256 value,uint256 nonce,uint256 deadline,uint8 v,bytes32 r,bytes32 s)",vt=lo(["function BLUE() view returns (address)",`function vaultExitBundlesV1InKindRedemptionVaultV2(address vault,address adapter,${Lt}[] marketParamsList,uint256 exitAssets,${uo} sharesPermit,uint256 deadline)`]);function O(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 la(e,t,s,r,n){q(n);let l=O(r.amount),o=O(r.maxShares),a=O(r.maxPenaltyAssets,!0),u=O(r.deadline),c=e.clientFor(f),m=await At(c,t,s),d=(S,N,Ce,ee=[])=>c.readContract({address:S,abi:N,functionName:Ce,args:ee,blockNumber:m.blockNumber}),[p,h,b,w]=await Promise.all([c.getBlock({blockNumber:m.blockNumber}),d(et,vt,"BLUE"),d(t,io,"balanceOf",[n]),d(t,Ze,"previewRedeem",[o])]);if(typeof h!="string"||Ct(h)!==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(o>Ee(b))throw new i("maxShares exceeds the wallet share balance.");let k=Pt(m.idle,l),y=m.markets.filter(S=>S.supplied>0n&&j(S.id)),g=l-k,I=y[0]?.penalty??0n,x=g*10n**18n/(10n**18n+I);if(g>0n&&x===0n)throw new i("The penalty-adjusted in-kind amount rounds to zero.");let T=[];for(let S of y){if(x===0n)break;let N=Pt(S.supplied,x);T.push({marketId:S.id,assets:N,penalty:(N*S.penalty+10n**18n-1n)/10n**18n}),x-=N}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(T.length)>Ee(w))throw new i("maxShares cannot cover the exit and per-market rounding buffer.");if(T.some(S=>S.assets>m.blueCash))throw new i("Morpho Blue cannot fund the largest in-kind callback. Reduce the amount.");let P=T.reduce((S,N)=>S+N.penalty,0n);if(P>a)throw new i("In-kind penalty exceeds maxPenaltyAssets.");let C=[...k?[k]:[],...T.flatMap(S=>[S.assets,S.penalty].filter(N=>N>0n))],v=(await Promise.all(C.map(S=>d(t,Ze,"previewWithdraw",[S])))).reduce((S,N)=>S+Ee(N),0n);if(v===0n||v>o)throw new i("Separately rounded burns exceed maxShares.");let Z=T.map(S=>no(co(Lt),m.markets.find(N=>N.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 ${v} share base units; receive ${k} ${s.symbol} base units and Morpho Blue supply positions ${T.map(S=>`${S.marketId}: ${S.assets} ${s.symbol} base units`).join(", ")||"none"}. Penalty ${P} ${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.`,M=so({abi:vt,functionName:"vaultExitBundlesV1InKindRedemptionVaultV2",args:[t,H,Z,l,{value:0n,nonce:0n,deadline:0n,v:0,r:Mt,s:Mt},u]}),$=[e.approval(t,et,v.toString(),f),e.unsignedTx({to:et,data:M,value:"0",chainId:f,description:F})],U=await e.preview($,n),V=-U.changes.filter(S=>S.token.chainId===f&&R(S.token.address,t)).reduce((S,N)=>{if(N.token.decimals!==18||!/^-?\d+$/.test(N.amount))throw new i("Invalid in-kind share preview.");return S+BigInt(N.amount)},0n);if(V<=0n||V>v)throw new i("In-kind preview exceeds the exact share authorization or burns no shares.");return{txs:$,preview:U,summary:F,receipt:{idleAssets:k.toString(),positions:T.map(S=>({marketId:S.marketId,asset:s,assets:S.assets.toString()})),penaltyAssets:P.toString()}}}var we=le("0x53A1eB6589861F686af7c531211E35Aefe30210f"),Ut=["supply","withdraw","supplyCollateralAndBorrow","repayAndWithdrawCollateral","migrateBorrowPosition"],tt={kind:0,data:"0x"},Re={nonce:0n,deadline:0n,signature:{v:0,r:Dt,s:Dt}},bo=fo("(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(M=>!l.includes(M)))throw new i("Unexpected argument for this Blue bundle.");let o=await n.getBlock(),a=O(t.deadline);if(a<o.timestamp||a>o.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:Ge,functionName:"BLUE",blockNumber:o.number}),n.readContract({address:we,abi:Ge,functionName:"PUBLIC_ALLOCATOR",blockNumber:o.number})]);if(le(u)!==B||le(c)!==xt)throw new i("BlueBundlesV1 deployment does not match Oak\u2019s pinned Blue and Public Allocator.");let m=async M=>{if(typeof M!="string"||!j(M))throw new i("Choose a verified Morpho market with a supported exit.");let $=await n.readContract({address:B,abi:E,functionName:"idToMarketParams",args:[M],blockNumber:o.number}),U={loanToken:le($[0]),collateralToken:le($[1]),oracle:le($[2]),irm:le($[3]),lltv:$[4]};if(!R(ke({...U,lltv:String(U.lltv)}),M))throw new i("Blue bundle market identity mismatch.");return U},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:B,abi:E,functionName:"isAuthorized",args:[s,we],blockNumber:o.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 h=t.assets===void 0?0n:O(t.assets,!0),b=t.shares===void 0?0n:O(t.shares,!0),w=t.collateralAssets===void 0?0n:O(t.collateralAssets,!0),k=r==="supply"||r==="withdraw"?0n:O(t.maxLtv,!0);if(k>p.lltv)throw new i("maxLtv cannot exceed the verified destination market LLTV.");if(r==="supply"&&h===0n||r==="withdraw"&&h===0n==(b===0n)||r==="supplyCollateralAndBorrow"&&w===0n&&h===0n||r==="repayAndWithdrawCollateral"&&(h>0n&&b>0n||h===0n&&b===0n&&w===0n))throw new i("Choose a nonzero amount; assets and shares are mutually exclusive for repayment/withdrawal.");let y=t.allocations??[];if(!Array.isArray(y)||y.length>4||y.length&&r==="supplyCollateralAndBorrow"&&h===0n)throw new i("Provide at most four explicit allocations, only with a borrow or withdrawal.");let g=new Set,I=[],x=0n;for(let M of y){if(!M||typeof M!="object"||Array.isArray(M)||Object.keys(M).some(Xe=>!["vault","sourceMarketId","assets","maxPenaltyAssets"].includes(Xe)))throw new i("Unsupported bundled allocation input.");let $=M,U=await It(e,{vault:$.vault,marketId:r==="migrateBorrowPosition"?t.destinationMarketId:t.marketId});if(g.has(U.definition.vault.toLowerCase()))throw new i("Use each source vault at most once per bundle.");g.add(U.definition.vault.toLowerCase());let V=O($.assets),S=O($.maxPenaltyAssets,!0);if(!U.permission||V>=1n<<128n||V>U.headroom||U.penalty>10n**18n||U.asset.address!==p.loanToken)throw new i("Bundled allocation is disabled, unqualified or exceeds target capacity.");let N=(V*U.penalty+10n**18n-1n)/10n**18n;if(N>S)throw new i("Bundled allocation exceeds maxPenaltyAssets.");x+=N;let Ce=$.sourceMarketId===void 0,ee=Ce?void 0:U.sources.find(Xe=>R(Xe.id,String($.sourceMarketId)));if(Ce?!U.canIdle||V>U.data.idle:!ee||!ee.canPull||V>ee.capacity||V>U.data.blueCash)throw new i("Bundled allocation source cannot cover the requested amount.");I.push({vault:U.definition.vault,adapter:U.target.adapter,marketParams:U.params,sourceAdapter:ee?.adapter??he,sourceMarketParams:ee?mo(bo,ee.data)[0]:U.params,assets:V,penalty:U.penalty,fromIdle:Ce})}let T,P,C,L=0n;if(r==="supply")T="blueBundlesV1Supply",C=d.loanToken,L=h,P=[d,h,tt,0n,he,a];else if(r==="withdraw")T="blueBundlesV1Withdraw",P=[d,h,b,Re,I,0n,he,a];else if(r==="supplyCollateralAndBorrow"){if(T="blueBundlesV1SupplyCollateralAndBorrow",C=d.collateralToken,L=w,x>=h&&x>0n)throw new i("Allocation penalties would consume the borrow proceeds.");P=[d,w,h,k,tt,Re,I,0n,he,a]}else if(r==="repayAndWithdrawCollateral"){if(T="blueBundlesV1RepayAndWithdrawCollateral",C=d.loanToken,L=O(t.maxRepayAssets,!0),h>L||b>0n&&L===0n)throw new i("Repayment requires a sufficient maxRepayAssets budget.");P=[d,h,b,L,w,k,tt,Re,0n,he,a]}else T="blueBundlesV1MigrateBorrowPosition",P=[d,p,k,Re,I,0n,he,a];let v=`Morpho Blue atomic ${r}: ${JSON.stringify(t)}. Allocation penalties ${x} loan-token base units; zero referral fee. Max LTV ${k}; absolute deadline ${a}. Migration adds allocation penalties to destination debt; borrowing deducts them from proceeds. Exact input approval ${L}. Existing Blue bundle authorization remains until explicitly revoked with morpho_manage. No opaque callback, permit or signature is accepted.`,Z=[...C&&L?[e.approval(C,we,L.toString(),f)]:[],e.unsignedTx({to:we,data:po({abi:Ge,functionName:T,args:P}),value:"0",chainId:f,description:v})],H=await e.preview(Z,s),F=new Map;for(let M of H.changes)if(BigInt(M.amount)<0n){let $=M.token.address.toLowerCase();F.set($,(F.get($)??0n)-BigInt(M.amount))}if([...F].some(([M,$])=>!C||M!==C.toLowerCase()||$>L))throw new i("Bundle preview spends outside the exact input budget.");return{txs:Z,preview:H,summary:v}}catch(r){throw new i(e.plainError(r))}}}]});import{concatHex as Bt,decodeAbiParameters as ho,encodeAbiParameters as Rt,encodeFunctionData as ot,erc20Abi as Nt,getAddress as K,keccak256 as rt,zeroAddress as ye,zeroHash as wo}from"viem";var Y=K("0x6120765Ba5336150BbdDdD0Cd9108B5bFD369632"),ko=["0x90B800999e4ACd1bD20283BD450bBd2e06D91F7C","0x708d6Bf6F847202a0755bb5636bE663B174242ea"].map(e=>K(e)),nt=oe.find(e=>e.name==="take"),Ot=[nt.inputs[0]],yo=[nt.inputs[0].components[0]];function Et(e){let t=rt(Bt(["0x600b380380600b5f395ff3",Rt(yo,[e])]));return rt(Bt(["0xff",e.midnight,wo,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 go(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 _e(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 at(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 So=e=>JSON.parse(JSON.stringify(e,(t,s)=>typeof s=="bigint"?s.toString():s)),Ht=e=>{async function t(n,l){let o=_e(n,32),a=e.clientFor(f);if(await a.getChainId()!==f)throw new i("Midnight requires chain 4663.");let u=await a.getBlock(),c=(y,g=[])=>a.readContract({address:Y,abi:oe,functionName:y,args:g,blockNumber:u.number}),m=await c("toMarket",[o]);if(m.chainId!==BigInt(f)||K(m.midnight)!==Y||!R(Et(m),o))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(y=>R(y,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,h,b,w]=await Promise.all([c("position",[o,l]),c("updatePositionView",[m,o,l]),c("marketState",[o]),c("isHealthy",[m,o,l])]),k=async y=>{let[g,I]=await Promise.all([a.readContract({address:y,abi:Nt,functionName:"decimals",blockNumber:u.number}),a.readContract({address:y,abi:Nt,functionName:"symbol",blockNumber:u.number})]);if(!Number.isInteger(g)||g>36||typeof I!="string")throw new i("Invalid Midnight token metadata.");return{address:K(y),decimals:g,symbol:I.replace(/[^a-zA-Z0-9.$_-]/g,"").slice(0,32),chainId:f}};return{id:o,rpc:a,block:u,market:m,read:c,token:k,loan:await k(m.loanToken),position:at(p,6),updated:at(h,3),state:at(b,13),healthy:w}}let s=(n,l,o,a)=>({name:n,inputSchema:{type:"object",properties:l,required:o,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 a(u,c)}catch(m){throw new i(e.plainError(m))}}});async function r(n,l,o){return{txs:n,preview:await e.preview(n,l),summary:o}}return{tools:[s("morpho_midnight_status",{marketId:{type:"string",description:"Midnight market id: 0x + 64 hex digits (bytes32)."}},["marketId"],async(n,l)=>{let o=await t(n.marketId,l),a=await Promise.all(o.market.collateralParams.map(async(m,d)=>({token:await o.token(m.token),lltvWad:m.lltv.toString(),oracle:m.oracle,assets:String(await o.read("collateral",[o.id,l,BigInt(d)]))}))),u=["configurator","feeSetter","feeClaimer","tickSpacingSetter"],c=await Promise.all(u.map(m=>o.read(m)));return{protocol:Object.fromEntries(u.map((m,d)=>[m,K(String(c[d]))])),continuousFeePerSecondWad:String(o.state[11]),tickSpacing:String(o.state[12]),settlementFeeCbps:o.state.slice(4,11).map(String),settlementFeeCbpWadScale:"1000000000000",chainId:f,midnight:Y,marketId:o.id,blockNumber:String(o.block.number),market:So(o.market),loanToken:o.loan,collaterals:a,debtUnits:String(o.position[4]),creditUnits:String(o.updated[0]),pendingFeeUnits:String(o.updated[1]),withdrawableUnits:String(o.state[2]),healthy:o.healthy,maturity:String(o.market.maturity),matured:o.block.timestamp>o.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 o=_e(n.offer),[a]=ho(Ot,o);if(!R(Rt(Ot,[a]),o))throw new i("Offer encoding is not canonical.");let u=await t(Et(a.market),l),c=O(n.units),m=O(n.maxAssets,!0),d=O(n.minAssets,!0),p=_e(n.ratifierData);if(c>=1n<<128n||R(a.maker,l)||a.callback!==ye||a.callbackData!=="0x"||!ko.includes(K(a.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<a.start||u.block.timestamp>a.expiry||a.expiry<a.start)throw new i("The Midnight offer is not currently live.");if(a.buy&&a.receiverIfMakerIsSeller!==ye||!a.buy&&a.receiverIfMakerIsSeller===ye)throw new i("Invalid offer seller receiver.");if(a.buy&&u.block.timestamp>u.market.maturity&&c>u.updated[0])throw new i("Post-maturity sales cannot increase this wallet\u2019s debt.");let h=await u.read("settlementFee",[u.id,u.market.maturity>u.block.timestamp?u.market.maturity-u.block.timestamp:0n]),b=go(a.tick);if(h>b&&a.buy)throw new i("Settlement fee exceeds the offer price.");let w=a.buy?b-h:b,k=w+h,y=M=>a.buy?M/de:(M+de-1n)/de,g=y(c*k),I=y(c*w);if(a.buy?I<d||I===0n:g>m||g===0n)throw new i("Midnight proceeds/spend do not fit the requested bounds.");let x=await u.read("consumed",[a.maker,a.group]);if(a.maxAssets===0n==(a.maxUnits===0n)||x+(a.maxAssets?a.buy?g:I:c)>(a.maxAssets||a.maxUnits))throw new i("Midnight offer capacity is exhausted or invalid.");if(u.state[11]>a.continuousFeeCap||a.tick%u.state[12]!==0n)throw new i("Offer fee cap or market tick spacing no longer permits execution.");let T=await u.read("isAuthorized",[a.maker,a.ratifier]),P=[{type:"function",name:"isRatified",stateMutability:"view",inputs:[nt.inputs[0],{type:"bytes"},{type:"address"}],outputs:[{type:"bytes32"}]}],C=await u.rpc.readContract({address:a.ratifier,abi:P,functionName:"isRatified",args:[a,p,l],blockNumber:u.block.number});if(T!==!0||C!==rt(new TextEncoder().encode("morpho.midnight.callbackSuccess")))throw new i("The maker has not authorized and ratified this exact offer.");let L=ot({abi:oe,functionName:"take",args:[a,p,c,l,a.buy?l:ye,ye,"0x"]}),v=`Midnight ${a.buy?"sell credit or borrow":"buy credit or reduce debt"}: ${c} fixed debt units; ${a.buy?`receive ${I}`:`spend ${g}`} ${u.loan.symbol} base units (token ${u.loan.address}, decimals ${u.loan.decimals}). Maturity ${u.market.maturity} Unix seconds; offer expiry ${a.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=[...a.buy?[]:[e.approval(u.loan.address,Y,g.toString(),f)],e.unsignedTx({to:Y,data:L,value:"0",chainId:f,description:v})],H=await r(Z,l,v),F=H.preview.changes.filter(M=>M.token.chainId===f&&R(M.token.address,u.loan.address)).reduce((M,$)=>M+BigInt($.amount),0n);if(a.buy?F<I: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 o=await t(n.marketId,l),a=n.operation;if(!["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"].includes(String(a)))throw new i("Choose a finite Midnight position operation.");let u,c,m=o.loan,d=0n;if(a==="updatePosition"){if(n.amount!==void 0||n.collateralIndex!==void 0)throw new i("Position update takes no amount or collateral index.");u=[o.market,l]}else if(a==="claimContinuousFee"){if(d=O(n.amount),n.collateralIndex!==void 0||K(String(await o.read("feeClaimer")))!==K(l))throw new i("This wallet lacks the Midnight fee claimer role or supplied an unused collateral index.");u=[o.market,d,l]}else{if(d=O(n.amount),d>=1n<<128n)throw new i("Midnight position amount exceeds uint128.");if(a==="supplyCollateral"||a==="withdrawCollateral"){if(!Number.isInteger(n.collateralIndex)||Number(n.collateralIndex)<0||Number(n.collateralIndex)>=o.market.collateralParams.length)throw new i("Choose a current collateral index.");let b=BigInt(String(n.collateralIndex)),w=await o.token(o.market.collateralParams[Number(b)].token);if(m=w,a==="withdrawCollateral"&&d>await o.read("collateral",[o.id,l,b]))throw new i("Insufficient Midnight collateral.");u=a==="supplyCollateral"?[o.market,b,d,l]:[o.market,b,d,l,l],a==="supplyCollateral"&&(c=w)}else{if(n.collateralIndex!==void 0)throw new i("This operation takes no collateral index.");if(a==="repay"&&d>o.position[4]||a==="withdraw"&&(d>o.updated[0]||d>o.state[2]))throw new i("Amount exceeds current debt, credit or available repayment liquidity.");u=a==="repay"?[o.market,d,l,ye,"0x"]:[o.market,d,l,l],a==="repay"&&(c=o.loan)}}let p=`Midnight ${a}: ${d} ${m.symbol} base units (token ${m.address}, decimals ${m.decimals}) on ${o.id}; beneficiary ${l}; maturity ${o.market.maturity} Unix seconds. No callbacks or delegation. Withdrawal can fail if collateral health or lender liquidity changes.`,h=[...c?[e.approval(c.address,Y,d.toString(),f)]:[],e.unsignedTx({to:Y,data:ot({abi:oe,functionName:String(a),args:u}),value:"0",chainId:f,description:p})];return r(h,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 o={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(o)].includes(n.operation)||!Array.isArray(n.values))throw new i("Choose a finite Midnight management operation and ordered values.");let a=n.operation,u=oe.find(p=>p.name===a);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,h)=>{let b=n.values[h];if(p.type==="bool"){if(typeof b!="boolean")throw new i("Use boolean management values.");return b}if(p.type==="address")return Oe(b,"Use explicit management addresses.",Ne);if(p.type==="bytes32")return _e(b,32);if(/^uint/.test(p.type)){let w=O(b,!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(a==="setConsumed"||a==="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:oe,functionName:o[a]});if(typeof p!="string"||K(p)!==K(l))throw new i("This wallet lacks the Midnight configuration, fee or tick role.")}let d=`Midnight ${a}, ordered values ${JSON.stringify(n.values)}. ${a==="setIsAuthorized"&&m[1]?"This grants authority over all Midnight positions, cancellations and further delegation, without an amount cap. Revoke with false when done.":""}${a==="setConsumed"?"Consumption only increases; setting uint128 maximum permanently cancels this offer group.":""}`;return r([e.unsignedTx({to:Y,data:ot({abi:oe,functionName:a,args:m}),value:"0",chainId:f,description:d})],l,d)})]}};import{decodeAbiParameters as re,encodeAbiParameters as Ao,encodeFunctionData as G,erc20Abi as it,getAddress as D,isAddress as Fe,keccak256 as xo,parseAbi as Ve,parseAbiParameters as J}from"viem";var De="morpho",Io="https://api.morpho.org/graphql",B=D(z[f].morpho.morpho_blue.address),To=D(z[f].morpho.adaptive_curve_irm.address),Mo=D(z[f].morpho.USDG.address),me=D(z[f].morpho.WETH.address),vo=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],Po={"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"}],Co=new Map(lt.map(e=>[e.marketId.toLowerCase(),e]));function j(e){return Co.get(e.toLowerCase())}function ct(e){let t=j(e);return t?{actions:"enabled",label:t.label,source:Po[t.source]}:{actions:"read-only",reason:"Not in Oak's verified Morpho market registry; Oak builds no transactions for it."}}var qt=20,qe=120n,ze=1000000n,We=1n,Se=10n**18n,Lo=10n**36n,jt=(1n<<128n)-1n,Do=(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)"]),Uo=Ve(["function price() view returns (uint256)"]),$o=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 Ue(e,t){return e===0n?0n:(e+t-1n)/t}function Bo(e,t,s){return e*(s+ze)/(t+We)}function No(e,t,s){return Ue(e*(s+ze),t+We)}function ut(e,t,s){return e*(t+We)/(s+ze)}function se(e,t,s){return Ue(e*(t+We),s+ze)}function Ae(e,t,s){return e*t/Lo*s/Se}function Oo(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=Oo(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 o of[e.loanToken,e.collateralToken,e.oracle,e.irm])if(typeof o!="string"||!Fe(o,{strict:!1}))throw new i("Morpho marketParams contains an invalid address.");let t=D(e.loanToken),s=D(e.collateralToken),r=D(e.oracle),n=D(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=Ao(J("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return xo(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),D(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=D(t),n=r.toLowerCase();if(s===f){if(n===Mo.toLowerCase())return yt;if(n===me.toLowerCase())return gt}let[l,o]=await Promise.all([ne(e,r,G({abi:it,functionName:"symbol"})),ne(e,r,G({abi:it,functionName:"decimals"}))]),[a]=re(J("string"),l),[u]=re(J("uint8"),o);return{address:r,symbol:Xt(a),decimals:Number(u),chainId:s}}async function Yt(e,t){let s=await ne(e,B,G({abi:X,functionName:"idToMarketParams",args:[t]})),[r,n,l,o,a]=re(J("address, address, address, address, uint256"),s);return{loanToken:D(r),collateralToken:D(n),oracle:D(l),irm:D(o),lltv:a}}async function Jt(e,t){let s=await ne(e,B,G({abi:X,functionName:"market",args:[t]})),[r,n,l,o,a,u]=re(J("uint128, uint128, uint128, uint128, uint128, uint128"),s);return{totalSupplyAssets:r,totalSupplyShares:n,totalBorrowAssets:l,totalBorrowShares:o,lastUpdate:a,fee:u}}async function Te(e,t,s){let r=await ne(e,B,G({abi:X,functionName:"position",args:[t,D(s)]})),[n,l,o]=re(J("uint256, uint128, uint128"),r);return{supplyShares:n,borrowShares:l,collateral:o}}async function Ke(e,t){let s=await ne(e,D(t),G({abi:Uo,functionName:"price"})),[r]=re(J("uint256"),s);return r}async function Eo(e,t,s){if(t.irm===te)return 0n;let r=await ne(e,D(t.irm),G({abi:$o,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=Ue(n*n,2n*Se),o=Ue(l*n,3n*Se);return e.totalBorrowAssets+Ue(e.totalBorrowAssets*(n+l+o),Se)}async function $e(e,t,s,r=0n){let[n,l]=await Promise.all([e.getBlock({blockTag:"latest"}),Eo(e,t,s)]),o=BigInt(Math.ceil(Date.now()/1e3)),a=(n.timestamp>o?n.timestamp:o)+r;return{totalBorrowAssets:Qe(s,l,a),accruedThrough:a,rate:l}}async function Zt(e,t,s){let r=await ne(e,D(t),G({abi:it,functionName:"balanceOf",args:[D(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,o=l?ke(l):void 0,a=r!==void 0?Qt(r):void 0;if(a&&o&&a!==o.toLowerCase())throw new i(`MarketParams tuple hash (${o}) does not match marketId (${a}).`);let u=(a??o).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 Go(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=e.clientFor(f),{marketId:o,marketParams:a}=await fe(l,t,!0),u=await Q(l,a.collateralToken,f),c=a.collateralToken.toLowerCase()===me.toLowerCase(),m=typeof t.collateralToken=="string"?(q(t.collateralToken),D(t.collateralToken)):void 0,d=W("wrapNative",t.wrapNative)===!0||m!==void 0&&dt(m);if(m&&!dt(m)&&m.toLowerCase()!==a.collateralToken.toLowerCase())throw new i(`Collateral token ${m} does not match market collateral ${a.collateralToken}.`);if(d&&!c)throw new i("Native ETH wrapping is only supported when market collateralToken is WETH.");let p=Me(t),h=p.toString(),b=e.formatAmount(h,u.decimals),w=[];d&&w.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:h,description:`Wrap ${b} ETH into WETH at ${me}.`})),w.push(e.approval(a.collateralToken,B,h,f)),w.push(e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"supplyCollateral",args:[a,p,n,"0x"]}),value:"0",description:`Supply ${b} ${u.symbol} (${h} base units) collateral to Morpho market ${o}.`}));let k=await e.preview(w,r),{formattedChanges:y,formattedNetOutflows:g}=xe(e,k);return{action:"morpho_supply_collateral",chainId:f,marketId:o,marketParams:pe(a),collateralToken:u,assets:h,formattedAssets:b,onBehalf:n,txs:w,summary:`${d?`Send ${b} ETH to wrap into WETH. `:""}Supply ${b} ${u.symbol} collateral to Morpho Blue market ${o}.`,preview:k,formattedChanges:y,formattedNetOutflows:g}}async function Ro(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,o=e.clientFor(f),{marketId:a,marketParams:u,marketState:c}=await fe(o,t,!0),[m,d,p,h]=await Promise.all([Q(o,u.loanToken,f),Te(o,a,n),Ke(o,u.oracle),$e(o,u,c,qe)]),b=Me(t),w=b.toString(),k=e.formatAmount(w,m.decimals),y=c.totalSupplyAssets>c.totalBorrowAssets?c.totalSupplyAssets-c.totalBorrowAssets:0n;if(b>y)throw new i(`Insufficient market liquidity: requested ${w} base units, available ${y.toString()} base units.`);let g=Ae(d.collateral,p,u.lltv),I=se(d.borrowShares,h.totalBorrowAssets,c.totalBorrowShares);if(d.collateral===0n||I+b>g)throw new i(`Insufficient collateral or unhealthy borrow: total debt ${(I+b).toString()} exceeds max borrow ${g.toString()} base units.`);let x=No(b,h.totalBorrowAssets,c.totalBorrowShares),P=[e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"borrow",args:[u,b,0n,n,l]}),value:"0",description:`Borrow ${k} ${m.symbol} (${w} base units) from Morpho market ${a}.`})],C=await e.preview(P,r),{formattedChanges:L,formattedNetOutflows:v}=xe(e,C);return{action:"morpho_borrow",chainId:f,marketId:a,marketParams:pe(u),loanToken:m,assets:w,formattedAssets:k,borrowShares:x.toString(),onBehalf:n,receiver:l,txs:P,summary:`Borrow ${k} ${m.symbol} from Morpho Blue market ${a}.`,preview:C,formattedChanges:L,formattedNetOutflows:v}}async function eo(e,t,s,r=qe){let n=Ie(t,s);ve(t,n);let l=n,o=e.clientFor(f);if(t.shares!==void 0){let v=Le(t.shares);if(v<=0n||v===Do||v>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:u,marketState:c}=await fe(o,t,!0),[m,d,p]=await Promise.all([Q(o,u.loanToken,f),Te(o,a,l),Zt(o,u.loanToken,n)]);if(d.borrowShares===0n)throw new i(`Position has no active borrow debt on Morpho market ${a}.`);let h=0n,b=0n;if(W("repayAll",t.repayAll)===!0)b=d.borrowShares;else if(t.shares!==void 0){let v=Le(t.shares);if(v>d.borrowShares)throw new i(`Repay shares (${v.toString()}) exceed current position borrowShares (${d.borrowShares.toString()}).`);b=v}else h=Me(t);let w=b>0n?await $e(o,u,c,r):void 0,k=b>0n?se(b,w.totalBorrowAssets,c.totalBorrowShares):h;if(p<k)throw new i(`Insufficient loan token balance for repayment: wallet holds ${p.toString()} base units, but ${k.toString()} base units are required (including accrued interest).`);let y=k.toString(),g=e.formatAmount(y,m.decimals),I=e.approval(u.loanToken,B,y,f),x=e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"repay",args:[u,h,b,l,"0x"]}),value:"0",description:b>0n?`Repay ${b.toString()} borrow shares (${g} ${m.symbol}) on Morpho market ${a}.`:`Repay ${g} ${m.symbol} (${h.toString()} base units) on Morpho market ${a}.`}),T=[I,x],P=await e.preview(T,n),{formattedChanges:C,formattedNetOutflows:L}=xe(e,P);return{action:"morpho_repay",chainId:f,marketId:a,marketParams:pe(u),loanToken:m,repayAssets:h.toString(),repayShares:b.toString(),requiredAssets:y,...w?{accruedThrough:w.accruedThrough.toString(),borrowRatePerSecond:w.rate.toString(),inclusionSeconds:r.toString()}:{},formattedRequiredAssets:g,onBehalf:l,txs:T,summary:b>0n?`Repay ${b.toString()} borrow shares (approval up to ${g} ${m.symbol}) on Morpho Blue market ${a}. Refresh if signing/inclusion takes more than ${qe} seconds.`:`Repay ${g} ${m.symbol} on Morpho Blue market ${a}.`,preview:P,formattedChanges:C,formattedNetOutflows:L}}function Ka(e,t,s){if(t.repayAll!==!0)throw new i("Reviewed debt reconstruction requires repayAll.");return eo(e,t,s,0n)}async function _o(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,o=e.clientFor(f),{marketId:a,marketParams:u,marketState:c}=await fe(o,t,!0),[m,d,p,h]=await Promise.all([Q(o,u.collateralToken,f),Te(o,a,n),Ke(o,u.oracle),$e(o,u,c,qe)]),b=W("withdrawAll",t.withdrawAll)===!0?d.collateral:Me(t);if(b<=0n||b>d.collateral)throw new i(`Insufficient collateral to withdraw: requested ${b.toString()} base units, position holds ${d.collateral.toString()} base units.`);if(d.borrowShares>0n){let P=d.collateral-b,C=Ae(P,p,u.lltv),L=se(d.borrowShares,h.totalBorrowAssets,c.totalBorrowShares);if(L>C)throw new i(`Unhealthy collateral withdrawal: remaining max borrow ${C.toString()} would fall below current debt ${L.toString()} base units.`)}let w=b.toString(),k=e.formatAmount(w,m.decimals),g=[e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"withdrawCollateral",args:[u,b,n,l]}),value:"0",description:`Withdraw ${k} ${m.symbol} (${w} base units) collateral from Morpho market ${a}.`})],I=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:T}=xe(e,I);return{action:"morpho_withdraw_collateral",chainId:f,marketId:a,marketParams:pe(u),collateralToken:m,assets:w,formattedAssets:k,onBehalf:n,receiver:l,txs:g,summary:`Withdraw ${k} ${m.symbol} collateral from Morpho Blue market ${a}.`,preview:I,formattedChanges:x,formattedNetOutflows:T}}async function Ho(e,t,s){let r=Ie(t,s);ve(t,r);let n=e.clientFor(f),{marketId:l,marketParams:o,marketState:a}=await fe(n,t,!0),u=W("wrapNative",t.wrapNative)===!0;if(u&&o.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,o.loanToken,f),u?Promise.resolve(c):Zt(n,o.loanToken,r)]);if(p<c)throw new i(`Insufficient ${d.symbol} balance to lend: wallet holds ${p.toString()} base units, requested ${m}.`);let h=e.formatAmount(m,d.decimals),b=[];u&&b.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:m,description:`Wrap ${h} ETH into WETH at ${me}.`})),b.push(e.approval(o.loanToken,B,m,f)),b.push(e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"supply",args:[o,c,0n,r,"0x"]}),value:"0",description:`Lend ${h} ${d.symbol} (${m} base units) to Morpho market ${l}.`}));let w=Bo(c,a.totalSupplyAssets,a.totalSupplyShares),k=await e.preview(b,r),{formattedChanges:y,formattedNetOutflows:g}=xe(e,k);return{action:"morpho_supply",chainId:f,marketId:l,marketParams:pe(o),loanToken:d,assets:m,formattedAssets:h,supplySharesEstimated:w.toString(),onBehalf:r,oak:ct(l),txs:b,summary:`${u?`Send ${h} ETH to wrap into WETH. `:""}Lend ${h} ${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:k,formattedChanges:y,formattedNetOutflows:g}}async function qo(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:o,marketParams:a,marketState:u}=await fe(n,t,!0),[c,m]=await Promise.all([Q(n,a.loanToken,f),Te(n,o,r)]);if(m.supplyShares===0n)throw new i(`This wallet has no lent ${c.symbol} on Morpho market ${o}.`);let d=ut(m.supplyShares,u.totalSupplyAssets,u.totalSupplyShares),p=l?0n:Me(t),h=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 b=u.totalSupplyAssets>u.totalBorrowAssets?u.totalSupplyAssets-u.totalBorrowAssets:0n,w=l?d:p;if(w>b)throw new i(`Insufficient market liquidity: withdrawing ${w.toString()} base units needs idle assets, but only ${b.toString()} are available until borrowers repay. Withdraw at most that amount, or retry later.`);let k=e.formatAmount(w.toString(),c.decimals),g=[e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"withdraw",args:[a,p,h,r,r]}),value:"0",description:l?`Withdraw all ${m.supplyShares.toString()} supply shares (about ${k} ${c.symbol}) from Morpho market ${o}.`:`Withdraw ${k} ${c.symbol} (${p.toString()} base units) of lent assets from Morpho market ${o}.`})],I=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:T}=xe(e,I);return{action:"morpho_withdraw",chainId:f,marketId:o,marketParams:pe(a),loanToken:c,withdrawAssets:p.toString(),withdrawShares:h.toString(),estimatedAssets:w.toString(),formattedAssets:k,receiver:r,txs:g,summary:l?`Withdraw all lent ${c.symbol} (about ${k}, including interest) from Morpho Blue market ${o}.`:`Withdraw ${k} lent ${c.symbol} from Morpho Blue market ${o}.`,preview:I,formattedChanges:x,formattedNetOutflows:T}}async function to(e,t,s){let r=await e.http(Io,{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 oo(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
@@ -10,9 +10,9 @@ import{a as ae}from"./3CCBUYUM.js";import{a as xt,d as It,e as Tt}from"./ZTKT3ZQ
10
10
  }
11
11
  pageInfo { count countTotal }
12
12
  }
13
- }`;try{let r=(await ea(e,t,{chainId:f})).markets;if(!Array.isArray(r?.items)||typeof r.pageInfo?.countTotal!="number"||r.pageInfo.countTotal!==r.items.length||r.items.some(n=>!n||typeof n.marketId!="string"||!/^0x[0-9a-fA-F]{64}$/.test(n.marketId)))throw new i("Morpho GraphQL returned an incomplete or invalid market inventory.");return r.items}catch(s){throw new i(`Morpho GraphQL read failed: ${ie(s)}`)}}async function qa(e,t){return(await ta(e)).find(r=>r.marketId.toLowerCase()===t)??null}async function Fa(e,t){let r=await ea(e,`query Positions($chainId: Int!, $wallet: String!) {
13
+ }`;try{let r=(await to(e,t,{chainId:f})).markets;if(!Array.isArray(r?.items)||typeof r.pageInfo?.countTotal!="number"||r.pageInfo.countTotal!==r.items.length||r.items.some(n=>!n||typeof n.marketId!="string"||!/^0x[0-9a-fA-F]{64}$/.test(n.marketId)))throw new i("Morpho GraphQL returned an incomplete or invalid market inventory.");return r.items}catch(s){throw new i(`Morpho GraphQL read failed: ${ie(s)}`)}}async function Fo(e,t){return(await oo(e)).find(r=>r.marketId.toLowerCase()===t)??null}async function Vo(e,t){let r=await to(e,`query Positions($chainId: Int!, $wallet: String!) {
14
14
  marketPositions(first: 1000, where: { chainId_in: [$chainId], userAddress_in: [$wallet] }) {
15
15
  items { market { marketId } }
16
16
  pageInfo { countTotal }
17
17
  }
18
- }`,{chainId:f,wallet:t}),n=r.marketPositions?.items;if(!Array.isArray(n)||r.marketPositions?.pageInfo?.countTotal!==n.length)throw new i("Morpho GraphQL returned an incomplete wallet position list.");return n.map(l=>Qt(l.market?.marketId))}function Ft(e){let t=e;return!t||typeof t.address!="string"||!Fe(t.address,{strict:!1})?null:{address:L(t.address),symbol:Xt(t.symbol),decimals:typeof t.decimals=="number"?t.decimals:null}}function Vt(e){return typeof e=="string"&&Fe(e,{strict:!1})?L(e):null}function zt(e,t){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw new i(`Morpho ${t} filter must be a token address or symbol.`);let s=e.trim().toLowerCase();return r=>!!r&&(String(r.address).toLowerCase()===s||typeof r.symbol=="string"&&r.symbol.toLowerCase()===s.replace(/^\$/,""))}async function Va(e,t){if(t.marketId!==void 0||t.marketParams!==void 0||t.includeGraphql!==void 0)throw new i("Use discover without marketId, marketParams or includeGraphql.");let s=t.limit===void 0?20:Number(t.limit);if(!Number.isSafeInteger(s)||s<1||s>100)throw new i("Morpho discover limit must be an integer from 1 to 100.");let r=zt(t.loanToken,"loanToken"),n=zt(t.collateralToken,"collateralToken"),l=W("verifiedOnly",t.verifiedOnly)===!0,a=await ta(e),o=a.map(c=>{let m=c.marketId.toLowerCase(),d=c.state??{},p=Ft(c.loanAsset),b=Ft(c.collateralAsset),h=Array.isArray(c.warnings)?c.warnings.map(w=>({type:String(w?.type??"").slice(0,64),level:String(w?.level??"").slice(0,16)})):[];return{marketId:m,listed:c.listed===!0,warnings:h,loanToken:p,collateralToken:b,lltv:typeof c.lltv=="string"||typeof c.lltv=="number"?String(c.lltv):null,oracle:Vt(c.oracle?.address),irm:Vt(c.irmAddress),state:{supplyAssets:d.supplyAssets===void 0?null:String(d.supplyAssets),borrowAssets:d.borrowAssets===void 0?null:String(d.borrowAssets),liquidityAssets:d.liquidityAssets===void 0?null:String(d.liquidityAssets),supplyApy:typeof d.supplyApy=="number"?d.supplyApy:null,borrowApy:typeof d.borrowApy=="number"?d.borrowApy:null},oak:ct(m)}}).filter(c=>(!l||c.oak.actions==="enabled")&&(!r||r(c.loanToken))&&(!n||n(c.collateralToken))),u=c=>{try{return BigInt(c.state.liquidityAssets??"0")}catch{return 0n}};return o.sort((c,m)=>{let d=+(m.oak.actions==="enabled")-+(c.oak.actions==="enabled");if(d)return d;let p=u(m)-u(c);return p>0n?1:p<0n?-1:0}),{chainId:f,morphoBlue:$,source:"Morpho API market inventory; token symbols, rates and liquidity are indexer data, not chain reads.",totalMatching:o.length,inventoryTotal:a.length,markets:o.slice(0,s),next:'Re-read a market with morpho_status {"marketId":"<id>"} before acting. Only oak.actions "enabled" markets accept Oak transactions.'}}async function za(e,t,s){let r=e.clientFor(f),n=s??t.wallet,l=n&&Fe(n,{strict:!1})?L(n):void 0;if(W("discover",t.discover)===!0)return Va(e,t);for(let c of["loanToken","collateralToken","verifiedOnly","limit"])if(t[c]!==void 0)throw new i(`Morpho ${c} is a discover filter; pass discover:true with it.`);let a=W("includeGraphql",t.includeGraphql)===!0,o=t.marketId||t.marketParams?[t]:Ta.map(c=>({marketId:c})),u=await Promise.all(o.map(async c=>{let{marketId:m,marketParams:d,marketState:p}=await fe(r,c),[b,h,w,y,k,g]=await Promise.all([Q(r,d.loanToken,f),Q(r,d.collateralToken,f),Ke(r,d.oracle),Be(r,d,p),l?Te(r,m,l):Promise.resolve(void 0),a?qa(e,m):Promise.resolve(void 0)]),T=p.totalSupplyAssets>p.totalBorrowAssets?p.totalSupplyAssets-p.totalBorrowAssets:0n,x;if(k){let M=k.borrowShares>0n?se(k.borrowShares,y.totalBorrowAssets,p.totalBorrowShares):0n,C=k.supplyShares>0n?ut(k.supplyShares,p.totalSupplyAssets,p.totalSupplyShares):0n,P=Ae(k.collateral,w,d.lltv),I=M>0n?e.formatAmount((P*Se/M).toString(),18):null;x={supplyShares:k.supplyShares.toString(),supplyAssets:C.toString(),borrowShares:k.borrowShares.toString(),borrowAssets:M.toString(),collateralAssets:k.collateral.toString(),maxBorrowAssets:P.toString(),healthFactor:I}}return{marketId:m,marketParams:pe(d),loanToken:b,collateralToken:h,state:{totalSupplyAssets:p.totalSupplyAssets.toString(),totalSupplyShares:p.totalSupplyShares.toString(),totalBorrowAssets:p.totalBorrowAssets.toString(),totalBorrowShares:p.totalBorrowShares.toString(),availableLiquidity:T.toString(),lastUpdate:p.lastUpdate.toString(),fee:p.fee.toString()},oraclePrice:w.toString(),borrowRatePerSecond:y.rate.toString(),oak:ct(m),...x?{position:x}:{},...a?{graphql:g??null}:{}}}));return{chainId:f,morphoBlue:$,adaptiveCurveIrm:xa,markets:u}}async function Wa(e,t,s,r){let[n,l]=await Promise.all([Yt(t,s),Jt(t,s)]),[a,o,u,c]=await Promise.all([Q(t,n.loanToken,f),Q(t,n.collateralToken,f),Ke(t,n.oracle),Be(t,n,l)]),m=[];r.collateral>0n&&m.push({token:o,amount:r.collateral.toString()});let d=r.supplyShares>0n?ut(r.supplyShares,l.totalSupplyAssets,l.totalSupplyShares):0n;d>0n&&m.push({token:a,amount:d.toString()});let p=r.borrowShares>0n?se(r.borrowShares,c.totalBorrowAssets,l.totalBorrowShares):0n,b=Ae(r.collateral,u,n.lltv),h=e.formatAmount(r.collateral.toString(),o.decimals),w=e.formatAmount(p.toString(),a.decimals);return{module:De,id:s,chainId:f,assets:m,economics:{principal:[...r.collateral>0n?[Je("collateral",{token:o,amount:r.collateral.toString(),source:"morpho.collateral"})]:[],...d>0n?[Je("redeemable",{token:a,amount:d.toString(),source:"morpho.supplyAssets"})]:[]],debt:p>0n?[St({token:a,amount:p.toString(),source:"morpho.borrowAssets"})]:[],rewards:[],backing:[],coverage:{complete:!0}},description:`Morpho Blue market ${s}: collateral=${h} ${o.symbol} (${r.collateral.toString()}), debt=${w} ${a.symbol} (${p.toString()}, shares=${r.borrowShares.toString()}), maxBorrow=${b.toString()}${r.supplyShares>0n?`, lent=${e.formatAmount(d.toString(),a.decimals)} ${a.symbol} (supplyShares=${r.supplyShares.toString()})`:""}.${j(s)?"":" Read-only: not in Oak's verified market registry, so Oak cannot build exits here."}`}}async function ja(e,t){q(t);let s=L(t),r=e.clientFor(f),n=[],l=new Set(lt.map(d=>d.marketId)),a;try{for(let d of await Fa(e,s))l.add(d)}catch(d){a=ie(d)}let o=[...l],u=[],c=[];if(typeof r.multicall=="function")try{let d=await r.multicall({multicallAddress:ft,batchSize:0,allowFailure:!0,contracts:o.map(p=>({address:$,abi:X,functionName:"position",args:[p,s]}))});if(d.length!==o.length)throw new i("Morpho multicall returned an incomplete position list.");d.forEach((p,b)=>{let h=o[b];if(p.status!=="success"){c.push({marketId:h,reason:ie(p.error)});return}let[w,y,k]=p.result;u.push({marketId:h,position:{supplyShares:w,borrowShares:y,collateral:k}})})}catch(d){c.push(...o.map(p=>({marketId:p,reason:ie(d)})))}else for(let d=0;d<o.length;d+=qt)u.push(...await Promise.all(o.slice(d,d+qt).map(async p=>({marketId:p,position:await Te(r,p,s).catch(b=>{c.push({marketId:p,reason:ie(b)})})}))));c.length&&n.push({module:De,id:"morpho-market-reads-incomplete",chainId:f,assets:[],incomplete:!0,description:`Morpho could not read ${c.length} of ${o.length} markets. ${[...new Set(c.map(d=>d.reason))].slice(0,3).join(" ")} Example market IDs: ${c.slice(0,3).map(d=>d.marketId).join(", ")}. Retry positions or check a known market with morpho_status {"marketId":"<id>"}; other readable markets are retained.`});let m=u.filter(d=>d.position!==void 0&&(d.position.supplyShares>0n||d.position.borrowShares>0n||d.position.collateral>0n));for(let{marketId:d,position:p}of m)try{n.push(await Wa(e,r,d,p))}catch(b){let h=j(d)!==void 0;n.push({module:De,id:d,chainId:f,assets:[],incomplete:!0,description:`Unreadable ${h?"verified":"unverified"} Morpho market ${d}: the wallet holds supplyShares=${p.supplyShares.toString()}, borrowShares=${p.borrowShares.toString()}, collateral=${p.collateral.toString()} base units, but its token or oracle reads failed (${ie(b)}). Retry morpho_status {"marketId":"${d}"}.${h?"":" Read-only in Oak."}`})}return a!==void 0&&n.push({module:De,id:"morpho-discovery-unavailable",incomplete:!0,chainId:f,assets:[],description:`Incomplete: Morpho API position discovery failed (${a}). Only Oak's ${lt.length} verified markets were checked on chain; check any other market with morpho_status {"marketId":"<id>"}.`}),n}var ce="Morpho Blue market id: 0x followed by 64 hex digits (bytes32). Provide this or marketParams.",ue="Market parameters object with loanToken, collateralToken, oracle, irm (addresses) and lltv (decimal string, 18 decimals). Provide this or marketId.",ge="Position owner address. Must be the Oak wallet; any other address is refused. Omit to use the wallet.",st="Address receiving the tokens. Must be the Oak wallet; any other address is refused. Omit to use the wallet.",oe=()=>`Amount of the market's loan token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`,qe=`Amount of the market's collateral token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`,Ka=e=>({tools:[{name:"morpho_supply_collateral",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(qe),amount:A(qe),collateralToken:{type:"string",pattern:"^0x[0-9a-fA-F]{40}$",description:"Optional collateral token address (0x + 40 hex); must match the market collateral token, or be the native ETH sentinel to wrap."},wrapNative:{type:"boolean",description:"true wraps native ETH into WETH first; only valid when the token supplied is WETH."},onBehalf:{type:"string",description:ge}}},execute:(s,r)=>Oa(e,s,r)},{name:"morpho_withdraw_collateral",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(qe),amount:A(qe),withdrawAll:{type:"boolean",description:"true withdraws the full collateral balance; do not combine with assets or amount."},onBehalf:{type:"string",description:ge},receiver:{type:"string",description:st}}},execute:(s,r)=>Ra(e,s,r)},{name:"morpho_borrow",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(oe()),amount:A(oe()),onBehalf:{type:"string",description:ge},receiver:{type:"string",description:st}}},execute:(s,r)=>Ea(e,s,r)},{name:"morpho_repay",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(oe()),amount:A(oe()),shares:A("Borrow shares to repay, in share base units exactly as your position reports them (not loan-token units). Use instead of assets or amount."),repayAll:{type:"boolean",description:"true repays the entire debt; do not combine with assets, amount or shares."},onBehalf:{type:"string",description:ge}}},execute:(s,r)=>Ga(e,s,r)},{name:"morpho_supply",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(oe()),amount:A(oe()),wrapNative:{type:"boolean",description:"true wraps native ETH into WETH first; only valid when the market loan token is WETH."},onBehalf:{type:"string",description:ge}}},execute:(s,r)=>_a(e,s,r)},{name:"morpho_withdraw",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(oe()),amount:A(oe()),withdrawAll:{type:"boolean",description:"true withdraws the full supplied balance; do not combine with assets or amount."},onBehalf:{type:"string",description:ge},receiver:{type:"string",description:st}}},execute:(s,r)=>Ha(e,s,r)},{name:"morpho_status",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},includeGraphql:{type:"boolean",description:"true also fetches Morpho API (GraphQL) market data alongside on-chain reads."},discover:{type:"boolean",description:"List the Morpho API market inventory with Oak action eligibility instead of reading markets on chain."},loanToken:{type:"string",description:"discover filter: loan token address or symbol."},collateralToken:{type:"string",description:"discover filter: collateral token address or symbol."},verifiedOnly:{type:"boolean",description:"discover filter: only markets Oak can act on."},limit:{type:"integer",minimum:1,maximum:100,description:"discover page size, default 20."}}},execute:(s,r)=>za(e,s,r)}].map(s=>{let r=new Set(Object.keys(s.inputSchema.properties));if(r.add("wallet"),s.name!=="morpho_status")for(let l of["onBehalf","receiver","data"])r.add(l);let n=new Set(["loanToken","collateralToken","oracle","irm","lltv"]);return{...s,execute:async(l,a)=>{for(let o of Object.keys(l))if(!r.has(o))throw new i(`Unknown argument ${Ye(o)} for ${s.name}; remove it and retry.`);if(l.marketParams&&typeof l.marketParams=="object"){for(let o of Object.keys(l.marketParams))if(!n.has(o))throw new i(`Unknown Morpho marketParams field ${Ye(o)}; remove it and retry.`)}return s.execute(l,a)}}}),positions:s=>ja(e,s)}),Ko=e=>bt(De,[Ka(e),Tt(e),Wt(e),Ht(e),$t(e)]);var _=z[f].morpho.morpho_blue.address,Pe="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",O=pt(["function owner() view returns (address)","function feeRecipient() view returns (address)","function isIrmEnabled(address) view returns (bool)","function isLltvEnabled(uint256) view returns (bool)","function isAuthorized(address,address) view returns (bool)","function nonce(address) view returns (uint256)",`function idToMarketParams(bytes32) view returns ${Pe}`,"function market(bytes32) view returns (uint128,uint128,uint128,uint128,uint128,uint128)","function position(bytes32,address) view returns (uint256 supplyShares,uint128 borrowShares,uint128 collateral)",`function createMarket(${Pe} marketParams)`,`function accrueInterest(${Pe} marketParams)`,`function setFee(${Pe} marketParams,uint256 newFee)`,"function setAuthorization(address authorized,bool newIsAuthorized)","function setOwner(address newOwner)","function setFeeRecipient(address newFeeRecipient)","function enableIrm(address irm)","function enableLltv(uint256 lltv)",`function liquidate(${Pe} marketParams,address borrower,uint256 seizedAssets,uint256 repaidShares,bytes data) returns (uint256,uint256)`]),Ya=pt(["function price() view returns (uint256)"]),Ja=pt([`function borrowRateView(${Pe} marketParams,(uint128 totalSupplyAssets,uint128 totalSupplyShares,uint128 totalBorrowAssets,uint128 totalBorrowShares,uint128 lastUpdate,uint128 fee) market) view returns (uint256)`]),oa=["createMarket","accrueInterest","setAuthorization","setOwner","setFeeRecipient","enableIrm","enableLltv","setFee"],Za=new Set(["setOwner","setFeeRecipient","enableIrm","enableLltv","setFee"]);function Ne(e){if(typeof e!="string"||!/^\d+$/.test(e)||e.length>78||BigInt(e)>=1n<<256n)throw new i("Provide a uint256 decimal base-unit string.");return BigInt(e)}function mt(e){return Ee(e,"Provide an explicit account address.",Oe)}var Wt=e=>{async function t(){let n=e.clientFor(f);if(await n.getChainId()!==f)throw new i("Morpho protocol tools require chain 4663.");return n}async function s(n){if(typeof n!="string"||!j(n))throw new i("Choose a market in Oak\u2019s verified registry.");let l=await t(),a=await l.readContract({address:_,abi:O,functionName:"idToMarketParams",args:[n]}),o={loanToken:a[0],collateralToken:a[1],oracle:a[2],irm:a[3],lltv:a[4]};if(!R(ke({...o,lltv:o.lltv.toString()}),n))throw new i("On-chain Morpho parameters do not match the selected market.");return{rpc:l,params:o,marketId:n}}let r=(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 Morpho protocol argument.");return await o(u,c)}catch(m){throw new i(e.plainError(m))}}});return{tools:[r("morpho_protocol",{authorized:{type:"string",description:"Optional address to check whether it is authorized to manage the Oak wallet's Morpho positions."}},[],async(n,l)=>{let a=await t(),[o,u,c]=await Promise.all([a.readContract({address:_,abi:O,functionName:"owner"}),a.readContract({address:_,abi:O,functionName:"feeRecipient"}),a.readContract({address:_,abi:O,functionName:"nonce",args:[l]})]),m=n.authorized===void 0?void 0:mt(n.authorized);return{chainId:f,morpho:_,owner:o,feeRecipient:u,nonce:c.toString(),...m?{authorized:m,isAuthorized:await a.readContract({address:_,abi:O,functionName:"isAuthorized",args:[l,m]})}:{}}}),r("morpho_manage",{operation:{enum:oa,description:"Protocol action: createMarket, accrueInterest, setAuthorization, setOwner, setFeeRecipient, enableIrm, enableLltv or setFee. Owner-only except accrueInterest, setAuthorization and createMarket."},marketId:{type:"string",description:"Verified market id (0x + 64 hex digits). Used by accrueInterest and setFee."},marketParams:{type:"object",description:"For createMarket only: loanToken, collateralToken, oracle, irm addresses and lltv as a decimal string (18 decimals)."},account:{type:"string",description:"Address argument: authorized account for setAuthorization, new owner, new fee recipient, or IRM to enable."},enabled:{type:"boolean",description:"For setAuthorization: true grants the account control of all your Morpho positions, false revokes it."},value:A("18-decimal wad in base units: for setFee the fee (max 0.25e18 = 25 percent), for enableLltv the LLTV (below 1e18; 0.8e18 = 80 percent).")},["operation"],async(n,l)=>{if(typeof n.operation!="string"||!oa.includes(n.operation))throw new i("Choose a documented Morpho protocol operation.");let a=n.operation,o=await t(),u=a==="createMarket"?["operation","marketParams"]:a==="accrueInterest"?["operation","marketId"]:a==="setFee"?["operation","marketId","value"]:a==="enableLltv"?["operation","value"]:a==="setAuthorization"?["operation","account","enabled"]:["operation","account"];if(Object.keys(n).some(p=>!u.includes(p)))throw new i("Unexpected fields for this Morpho operation.");if(Za.has(a)){let p=await o.readContract({address:_,abi:O,functionName:"owner"});if(aa(p)!==aa(l))throw new i("This wallet does not hold the Morpho owner role.")}let c;if(a==="createMarket"){if(!n.marketParams||typeof n.marketParams!="object"||Array.isArray(n.marketParams)||Object.keys(n.marketParams).some(w=>!["loanToken","collateralToken","oracle","irm","lltv"].includes(w)))throw new i("Provide only the five documented market parameter fields.");let p=je(n.marketParams),[b,h]=await Promise.all([o.readContract({address:_,abi:O,functionName:"isIrmEnabled",args:[p.irm]}),o.readContract({address:_,abi:O,functionName:"isLltvEnabled",args:[p.lltv]})]);if(!b||!h)throw new i("The new market\u2019s IRM and LLTV must first be enabled by the Morpho owner.");c=be({abi:O,functionName:"createMarket",args:[p]})}else if(a==="accrueInterest"||a==="setFee"){let{params:p}=await s(n.marketId);if(a==="setFee"){let b=Ne(n.value);if(b>250000000000000000n)throw new i("Morpho market fee cannot exceed 25% (0.25e18).");c=be({abi:O,functionName:"setFee",args:[p,b]})}else c=be({abi:O,functionName:"accrueInterest",args:[p]})}else if(a==="enableLltv"){let p=Ne(n.value);if(p>=10n**18n)throw new i("Morpho LLTV must be below 1e18.");c=be({abi:O,functionName:"enableLltv",args:[p]})}else{let p=mt(n.account);if(a==="setAuthorization"){if(typeof n.enabled!="boolean")throw new i("Provide enabled as a boolean.");c=be({abi:O,functionName:"setAuthorization",args:[p,n.enabled]})}else if(a==="setOwner"||a==="enableIrm"||a==="setFeeRecipient")c=be({abi:O,functionName:a,args:[p]});else throw new i("Unsupported Morpho operation.")}let m=`Morpho ${a}: ${JSON.stringify(n)}. ${a==="setAuthorization"&&n.enabled?"This account can manage all your Morpho positions, including borrowing and withdrawals. There is no amount cap.":""}${a==="setOwner"&&n.account===Xa?"Setting the owner to zero permanently relinquishes protocol administration.":""}${a==="createMarket"?"New market creation does not add it to Oak\u2019s verified action registry.":""}`,d=[e.unsignedTx({to:_,data:c,value:"0",chainId:f,description:m})];return{txs:d,preview:await e.preview(d,l),summary:m}}),r("morpho_liquidate",{marketId:{type:"string",description:"Verified Morpho Blue market id (0x + 64 hex digits) holding the unhealthy position."},borrower:{type:"string",description:"Address of the unhealthy borrower to liquidate."},repaidShares:A("Borrow shares to repay, in share base units (read the borrower position); cannot exceed their debt shares."),maxAssets:A('Most loan token you will pay, in base units of the market loan token (read its decimals). Example: "1000000" = 1 USDG.'),minCollateral:A("Least collateral you must receive, in collateral token units (base units, read its decimals); checked in simulation only.")},["marketId","borrower","repaidShares","maxAssets","minCollateral"],async(n,l)=>{let{rpc:a,params:o,marketId:u}=await s(n.marketId),c=mt(n.borrower),m=Ne(n.repaidShares),d=Ne(n.maxAssets),p=Ne(n.minCollateral),[b,h,w,y]=await Promise.all([a.readContract({address:_,abi:O,functionName:"market",args:[u]}),a.readContract({address:_,abi:O,functionName:"position",args:[u,c]}),a.readContract({address:o.oracle,abi:Ya,functionName:"price"}),a.getBlock()]);if(m===0n||m>h[1]||w===0n)throw new i("Liquidation shares must fit the current debt and the oracle must be valid.");let k={totalSupplyAssets:b[0],totalSupplyShares:b[1],totalBorrowAssets:b[2],totalBorrowShares:b[3],lastUpdate:b[4],fee:b[5]},g=await a.readContract({address:o.irm,abi:Ja,functionName:"borrowRateView",args:[o,k]}),T=Qe(k,g,y.timestamp);if(se(h[1],T,b[3])<=Ae(h[2],w,o.lltv))throw new i("This borrower is healthy; liquidation is unavailable.");let x=se(m,Qe(k,g,y.timestamp+120n),b[3]);if(x>d)throw new i("Liquidation funding exceeds maxAssets.");if(await a.readContract({address:o.loanToken,abi:Qa,functionName:"balanceOf",args:[l]})<x)throw new i("Top up the loan token before liquidating.");let C=`Liquidate ${m} debt shares of ${c} on ${u}; exact approval ${x} loan-token base units; preview minimum ${p} collateral units. No callbacks; the wallet funds repayment. Approval can leave interest-buffer dust; revoke it afterward.`,P=[e.approval(o.loanToken,_,x.toString(),f),e.unsignedTx({to:_,data:be({abi:O,functionName:"liquidate",args:[o,c,0n,m,"0x"]}),value:"0",chainId:f,description:C})],I=await e.preview(P,l),E=Z=>I.changes.filter(H=>H.token.chainId===f&&R(H.token.address,Z)).reduce((H,F)=>H+BigInt(F.amount),0n);if(-E(o.loanToken)<=0n||-E(o.loanToken)>x||E(o.collateralToken)<p||E(o.collateralToken)<=0n)throw new i("Liquidation preview does not match the funding limit and collateral minimum.");return{txs:P,preview:I,requiredAssets:x.toString(),summary:`${C} MinCollateral is a local simulation check, not an on-chain floor.`}})]}};export{O as a,Wt as b,we as c,$t as d,Y as e,ha as f,Ot as g,wa as h,Et as i,ka as j,Ht as k,De as l,Aa as m,$ as n,xa as o,Ia as p,me as q,Ta as r,Ma as s,lt as t,j as u,Ue as v,Ua as w,$a as x,ut as y,se as z,Ae as A,Ba as B,je as C,ke as D,Xt as E,Qe as F,Ka as G,Ko as H,et as I,vt as J,N as K,io as L};
18
+ }`,{chainId:f,wallet:t}),n=r.marketPositions?.items;if(!Array.isArray(n)||r.marketPositions?.pageInfo?.countTotal!==n.length)throw new i("Morpho GraphQL returned an incomplete wallet position list.");return n.map(l=>Qt(l.market?.marketId))}function Ft(e){let t=e;return!t||typeof t.address!="string"||!Fe(t.address,{strict:!1})?null:{address:D(t.address),symbol:Xt(t.symbol),decimals:typeof t.decimals=="number"?t.decimals:null}}function Vt(e){return typeof e=="string"&&Fe(e,{strict:!1})?D(e):null}function zt(e,t){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw new i(`Morpho ${t} filter must be a token address or symbol.`);let s=e.trim().toLowerCase();return r=>!!r&&(String(r.address).toLowerCase()===s||typeof r.symbol=="string"&&r.symbol.toLowerCase()===s.replace(/^\$/,""))}async function zo(e,t){if(t.marketId!==void 0||t.marketParams!==void 0||t.includeGraphql!==void 0)throw new i("Use discover without marketId, marketParams or includeGraphql.");let s=t.limit===void 0?20:Number(t.limit);if(!Number.isSafeInteger(s)||s<1||s>100)throw new i("Morpho discover limit must be an integer from 1 to 100.");let r=zt(t.loanToken,"loanToken"),n=zt(t.collateralToken,"collateralToken"),l=W("verifiedOnly",t.verifiedOnly)===!0,o=await oo(e),a=o.map(c=>{let m=c.marketId.toLowerCase(),d=c.state??{},p=Ft(c.loanAsset),h=Ft(c.collateralAsset),b=Array.isArray(c.warnings)?c.warnings.map(w=>({type:String(w?.type??"").slice(0,64),level:String(w?.level??"").slice(0,16)})):[];return{marketId:m,listed:c.listed===!0,warnings:b,loanToken:p,collateralToken:h,lltv:typeof c.lltv=="string"||typeof c.lltv=="number"?String(c.lltv):null,oracle:Vt(c.oracle?.address),irm:Vt(c.irmAddress),state:{supplyAssets:d.supplyAssets===void 0?null:String(d.supplyAssets),borrowAssets:d.borrowAssets===void 0?null:String(d.borrowAssets),liquidityAssets:d.liquidityAssets===void 0?null:String(d.liquidityAssets),supplyApy:typeof d.supplyApy=="number"?d.supplyApy:null,borrowApy:typeof d.borrowApy=="number"?d.borrowApy:null},oak:ct(m)}}).filter(c=>(!l||c.oak.actions==="enabled")&&(!r||r(c.loanToken))&&(!n||n(c.collateralToken))),u=c=>{try{return BigInt(c.state.liquidityAssets??"0")}catch{return 0n}};return a.sort((c,m)=>{let d=+(m.oak.actions==="enabled")-+(c.oak.actions==="enabled");if(d)return d;let p=u(m)-u(c);return p>0n?1:p<0n?-1:0}),{chainId:f,morphoBlue:B,source:"Morpho API market inventory; token symbols, rates and liquidity are indexer data, not chain reads.",totalMatching:a.length,inventoryTotal:o.length,markets:a.slice(0,s),next:'Re-read a market with morpho_status {"marketId":"<id>"} before acting. Only oak.actions "enabled" markets accept Oak transactions.'}}async function Wo(e,t,s){let r=e.clientFor(f),n=s??t.wallet,l=n&&Fe(n,{strict:!1})?D(n):void 0;if(W("discover",t.discover)===!0)return zo(e,t);for(let c of["loanToken","collateralToken","verifiedOnly","limit"])if(t[c]!==void 0)throw new i(`Morpho ${c} is a discover filter; pass discover:true with it.`);let o=W("includeGraphql",t.includeGraphql)===!0,a=t.marketId||t.marketParams?[t]:vo.map(c=>({marketId:c})),u=await Promise.all(a.map(async c=>{let{marketId:m,marketParams:d,marketState:p}=await fe(r,c),[h,b,w,k,y,g]=await Promise.all([Q(r,d.loanToken,f),Q(r,d.collateralToken,f),Ke(r,d.oracle),$e(r,d,p),l?Te(r,m,l):Promise.resolve(void 0),o?Fo(e,m):Promise.resolve(void 0)]),I=p.totalSupplyAssets>p.totalBorrowAssets?p.totalSupplyAssets-p.totalBorrowAssets:0n,x;if(y){let T=y.borrowShares>0n?se(y.borrowShares,k.totalBorrowAssets,p.totalBorrowShares):0n,P=y.supplyShares>0n?ut(y.supplyShares,p.totalSupplyAssets,p.totalSupplyShares):0n,C=Ae(y.collateral,w,d.lltv),L=T>0n?e.formatAmount((C*Se/T).toString(),18):null;x={supplyShares:y.supplyShares.toString(),supplyAssets:P.toString(),borrowShares:y.borrowShares.toString(),borrowAssets:T.toString(),collateralAssets:y.collateral.toString(),maxBorrowAssets:C.toString(),healthFactor:L}}return{marketId:m,marketParams:pe(d),loanToken:h,collateralToken:b,state:{totalSupplyAssets:p.totalSupplyAssets.toString(),totalSupplyShares:p.totalSupplyShares.toString(),totalBorrowAssets:p.totalBorrowAssets.toString(),totalBorrowShares:p.totalBorrowShares.toString(),availableLiquidity:I.toString(),lastUpdate:p.lastUpdate.toString(),fee:p.fee.toString()},oraclePrice:w.toString(),borrowRatePerSecond:k.rate.toString(),oak:ct(m),...x?{position:x}:{},...o?{graphql:g??null}:{}}}));return{chainId:f,morphoBlue:B,adaptiveCurveIrm:To,markets:u}}async function jo(e,t,s,r){let[n,l]=await Promise.all([Yt(t,s),Jt(t,s)]),[o,a,u,c]=await Promise.all([Q(t,n.loanToken,f),Q(t,n.collateralToken,f),Ke(t,n.oracle),$e(t,n,l)]),m=[];r.collateral>0n&&m.push({token:a,amount:r.collateral.toString()});let d=r.supplyShares>0n?ut(r.supplyShares,l.totalSupplyAssets,l.totalSupplyShares):0n;d>0n&&m.push({token:o,amount:d.toString()});let p=r.borrowShares>0n?se(r.borrowShares,c.totalBorrowAssets,l.totalBorrowShares):0n,h=Ae(r.collateral,u,n.lltv),b=e.formatAmount(r.collateral.toString(),a.decimals),w=e.formatAmount(p.toString(),o.decimals);return{module:De,id:s,chainId:f,assets:m,economics:{principal:[...r.collateral>0n?[Je("collateral",{token:a,amount:r.collateral.toString(),source:"morpho.collateral"})]:[],...d>0n?[Je("redeemable",{token:o,amount:d.toString(),source:"morpho.supplyAssets"})]:[]],debt:p>0n?[St({token:o,amount:p.toString(),source:"morpho.borrowAssets"})]:[],rewards:[],backing:[],coverage:{complete:!0}},description:`Morpho Blue market ${s}: collateral=${b} ${a.symbol} (${r.collateral.toString()}), debt=${w} ${o.symbol} (${p.toString()}, shares=${r.borrowShares.toString()}), maxBorrow=${h.toString()}${r.supplyShares>0n?`, lent=${e.formatAmount(d.toString(),o.decimals)} ${o.symbol} (supplyShares=${r.supplyShares.toString()})`:""}.${j(s)?"":" Read-only: not in Oak's verified market registry, so Oak cannot build exits here."}`}}async function Ko(e,t){q(t);let s=D(t),r=e.clientFor(f),n=[],l=new Set(lt.map(d=>d.marketId)),o;try{for(let d of await Vo(e,s))l.add(d)}catch(d){o=ie(d)}let a=[...l],u=[],c=[];if(typeof r.multicall=="function")try{let d=await r.multicall({multicallAddress:ft,batchSize:0,allowFailure:!0,contracts:a.map(p=>({address:B,abi:X,functionName:"position",args:[p,s]}))});if(d.length!==a.length)throw new i("Morpho multicall returned an incomplete position list.");d.forEach((p,h)=>{let b=a[h];if(p.status!=="success"){c.push({marketId:b,reason:ie(p.error)});return}let[w,k,y]=p.result;u.push({marketId:b,position:{supplyShares:w,borrowShares:k,collateral:y}})})}catch(d){c.push(...a.map(p=>({marketId:p,reason:ie(d)})))}else for(let d=0;d<a.length;d+=qt)u.push(...await Promise.all(a.slice(d,d+qt).map(async p=>({marketId:p,position:await Te(r,p,s).catch(h=>{c.push({marketId:p,reason:ie(h)})})}))));c.length&&n.push({module:De,id:"morpho-market-reads-incomplete",chainId:f,assets:[],incomplete:!0,description:`Morpho could not read ${c.length} of ${a.length} markets. ${[...new Set(c.map(d=>d.reason))].slice(0,3).join(" ")} Example market IDs: ${c.slice(0,3).map(d=>d.marketId).join(", ")}. Retry positions or check a known market with morpho_status {"marketId":"<id>"}; other readable markets are retained.`});let m=u.filter(d=>d.position!==void 0&&(d.position.supplyShares>0n||d.position.borrowShares>0n||d.position.collateral>0n));for(let{marketId:d,position:p}of m)try{n.push(await jo(e,r,d,p))}catch(h){let b=j(d)!==void 0;n.push({module:De,id:d,chainId:f,assets:[],incomplete:!0,description:`Unreadable ${b?"verified":"unverified"} Morpho market ${d}: the wallet holds supplyShares=${p.supplyShares.toString()}, borrowShares=${p.borrowShares.toString()}, collateral=${p.collateral.toString()} base units, but its token or oracle reads failed (${ie(h)}). Retry morpho_status {"marketId":"${d}"}.${b?"":" Read-only in Oak."}`})}return o!==void 0&&n.push({module:De,id:"morpho-discovery-unavailable",incomplete:!0,chainId:f,assets:[],description:`Incomplete: Morpho API position discovery failed (${o}). Only Oak's ${lt.length} verified markets were checked on chain; check any other market with morpho_status {"marketId":"<id>"}.`}),n}var ce="Morpho Blue market id: 0x followed by 64 hex digits (bytes32). Provide this or marketParams.",ue="Market parameters object with loanToken, collateralToken, oracle, irm (addresses) and lltv (decimal string, 18 decimals). Provide this or marketId.",ge="Position owner address. Must be the Oak wallet; any other address is refused. Omit to use the wallet.",st="Address receiving the tokens. Must be the Oak wallet; any other address is refused. Omit to use the wallet.",ae=()=>`Amount of the market's loan token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`,He=`Amount of the market's collateral token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`,Qo=e=>({tools:[{name:"morpho_supply_collateral",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(He),amount:A(He),collateralToken:{type:"string",pattern:"^0x[0-9a-fA-F]{40}$",description:"Optional collateral token address (0x + 40 hex); must match the market collateral token, or be the native ETH sentinel to wrap."},wrapNative:{type:"boolean",description:"true wraps native ETH into WETH first; only valid when the token supplied is WETH."},onBehalf:{type:"string",description:ge}}},execute:(s,r)=>Go(e,s,r)},{name:"morpho_withdraw_collateral",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(He),amount:A(He),withdrawAll:{type:"boolean",description:"true withdraws the full collateral balance; do not combine with assets or amount."},onBehalf:{type:"string",description:ge},receiver:{type:"string",description:st}}},execute:(s,r)=>_o(e,s,r)},{name:"morpho_borrow",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(ae()),amount:A(ae()),onBehalf:{type:"string",description:ge},receiver:{type:"string",description:st}}},execute:(s,r)=>Ro(e,s,r)},{name:"morpho_repay",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(ae()),amount:A(ae()),shares:A("Borrow shares to repay, in share base units exactly as your position reports them (not loan-token units). Use instead of assets or amount."),repayAll:{type:"boolean",description:"true repays the entire debt; do not combine with assets, amount or shares."},onBehalf:{type:"string",description:ge}}},execute:(s,r)=>eo(e,s,r)},{name:"morpho_supply",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(ae()),amount:A(ae()),wrapNative:{type:"boolean",description:"true wraps native ETH into WETH first; only valid when the market loan token is WETH."},onBehalf:{type:"string",description:ge}}},execute:(s,r)=>Ho(e,s,r)},{name:"morpho_withdraw",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},assets:A(ae()),amount:A(ae()),withdrawAll:{type:"boolean",description:"true withdraws the full supplied balance; do not combine with assets or amount."},onBehalf:{type:"string",description:ge},receiver:{type:"string",description:st}}},execute:(s,r)=>qo(e,s,r)},{name:"morpho_status",inputSchema:{type:"object",properties:{marketId:{type:"string",description:ce},marketParams:{type:"object",description:ue},includeGraphql:{type:"boolean",description:"true also fetches Morpho API (GraphQL) market data alongside on-chain reads."},discover:{type:"boolean",description:"List the Morpho API market inventory with Oak action eligibility instead of reading markets on chain."},loanToken:{type:"string",description:"discover filter: loan token address or symbol."},collateralToken:{type:"string",description:"discover filter: collateral token address or symbol."},verifiedOnly:{type:"boolean",description:"discover filter: only markets Oak can act on."},limit:{type:"integer",minimum:1,maximum:100,description:"discover page size, default 20."}}},execute:(s,r)=>Wo(e,s,r)}].map(s=>{let r=new Set(Object.keys(s.inputSchema.properties));if(r.add("wallet"),s.name!=="morpho_status")for(let l of["onBehalf","receiver","data"])r.add(l);let n=new Set(["loanToken","collateralToken","oracle","irm","lltv"]);return{...s,execute:async(l,o)=>{for(let a of Object.keys(l))if(!r.has(a))throw new i(`Unknown argument ${Ye(a)} for ${s.name}; remove it and retry.`);if(l.marketParams&&typeof l.marketParams=="object"){for(let a of Object.keys(l.marketParams))if(!n.has(a))throw new i(`Unknown Morpho marketParams field ${Ye(a)}; remove it and retry.`)}return s.execute(l,o)}}}),positions:s=>Ko(e,s)}),Qa=e=>bt(De,[Qo(e),Tt(e),Wt(e),Ht(e),$t(e)]);var _=z[f].morpho.morpho_blue.address,Pe="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",E=pt(["function owner() view returns (address)","function feeRecipient() view returns (address)","function isIrmEnabled(address) view returns (bool)","function isLltvEnabled(uint256) view returns (bool)","function isAuthorized(address,address) view returns (bool)","function nonce(address) view returns (uint256)",`function idToMarketParams(bytes32) view returns ${Pe}`,"function market(bytes32) view returns (uint128,uint128,uint128,uint128,uint128,uint128)","function position(bytes32,address) view returns (uint256 supplyShares,uint128 borrowShares,uint128 collateral)",`function createMarket(${Pe} marketParams)`,`function accrueInterest(${Pe} marketParams)`,`function setFee(${Pe} marketParams,uint256 newFee)`,"function setAuthorization(address authorized,bool newIsAuthorized)","function setOwner(address newOwner)","function setFeeRecipient(address newFeeRecipient)","function enableIrm(address irm)","function enableLltv(uint256 lltv)",`function liquidate(${Pe} marketParams,address borrower,uint256 seizedAssets,uint256 repaidShares,bytes data) returns (uint256,uint256)`]),Jo=pt(["function price() view returns (uint256)"]),Zo=pt([`function borrowRateView(${Pe} marketParams,(uint128 totalSupplyAssets,uint128 totalSupplyShares,uint128 totalBorrowAssets,uint128 totalBorrowShares,uint128 lastUpdate,uint128 fee) market) view returns (uint256)`]),ro=["createMarket","accrueInterest","setAuthorization","setOwner","setFeeRecipient","enableIrm","enableLltv","setFee"],ea=new Set(["setOwner","setFeeRecipient","enableIrm","enableLltv","setFee"]);function Be(e){if(typeof e!="string"||!/^\d+$/.test(e)||e.length>78||BigInt(e)>=1n<<256n)throw new i("Provide a uint256 decimal base-unit string.");return BigInt(e)}function mt(e){return Oe(e,"Provide an explicit account address.",Ne)}var Wt=e=>{async function t(){let n=e.clientFor(f);if(await n.getChainId()!==f)throw new i("Morpho protocol tools require chain 4663.");return n}async function s(n){if(typeof n!="string"||!j(n))throw new i("Choose a market in Oak\u2019s verified registry.");let l=await t(),o=await l.readContract({address:_,abi:E,functionName:"idToMarketParams",args:[n]}),a={loanToken:o[0],collateralToken:o[1],oracle:o[2],irm:o[3],lltv:o[4]};if(!R(ke({...a,lltv:a.lltv.toString()}),n))throw new i("On-chain Morpho parameters do not match the selected market.");return{rpc:l,params:a,marketId:n}}let r=(n,l,o,a)=>({name:n,inputSchema:{type:"object",properties:l,required:o,additionalProperties:!1},execute:async(u,c)=>{try{if(q(c),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Morpho protocol argument.");return await a(u,c)}catch(m){throw new i(e.plainError(m))}}});return{tools:[r("morpho_protocol",{authorized:{type:"string",description:"Optional address to check whether it is authorized to manage the Oak wallet's Morpho positions."}},[],async(n,l)=>{let o=await t(),[a,u,c]=await Promise.all([o.readContract({address:_,abi:E,functionName:"owner"}),o.readContract({address:_,abi:E,functionName:"feeRecipient"}),o.readContract({address:_,abi:E,functionName:"nonce",args:[l]})]),m=n.authorized===void 0?void 0:mt(n.authorized);return{chainId:f,morpho:_,owner:a,feeRecipient:u,nonce:c.toString(),...m?{authorized:m,isAuthorized:await o.readContract({address:_,abi:E,functionName:"isAuthorized",args:[l,m]})}:{}}}),r("morpho_manage",{operation:{enum:ro,description:"Protocol action: createMarket, accrueInterest, setAuthorization, setOwner, setFeeRecipient, enableIrm, enableLltv or setFee. Owner-only except accrueInterest, setAuthorization and createMarket."},marketId:{type:"string",description:"Verified market id (0x + 64 hex digits). Used by accrueInterest and setFee."},marketParams:{type:"object",description:"For createMarket only: loanToken, collateralToken, oracle, irm addresses and lltv as a decimal string (18 decimals)."},account:{type:"string",description:"Address argument: authorized account for setAuthorization, new owner, new fee recipient, or IRM to enable."},enabled:{type:"boolean",description:"For setAuthorization: true grants the account control of all your Morpho positions, false revokes it."},value:A("18-decimal wad in base units: for setFee the fee (max 0.25e18 = 25 percent), for enableLltv the LLTV (below 1e18; 0.8e18 = 80 percent).")},["operation"],async(n,l)=>{if(typeof n.operation!="string"||!ro.includes(n.operation))throw new i("Choose a documented Morpho protocol operation.");let o=n.operation,a=await t(),u=o==="createMarket"?["operation","marketParams"]:o==="accrueInterest"?["operation","marketId"]:o==="setFee"?["operation","marketId","value"]:o==="enableLltv"?["operation","value"]:o==="setAuthorization"?["operation","account","enabled"]:["operation","account"];if(Object.keys(n).some(p=>!u.includes(p)))throw new i("Unexpected fields for this Morpho operation.");if(ea.has(o)){let p=await a.readContract({address:_,abi:E,functionName:"owner"});if(ao(p)!==ao(l))throw new i("This wallet does not hold the Morpho owner role.")}let c;if(o==="createMarket"){if(!n.marketParams||typeof n.marketParams!="object"||Array.isArray(n.marketParams)||Object.keys(n.marketParams).some(w=>!["loanToken","collateralToken","oracle","irm","lltv"].includes(w)))throw new i("Provide only the five documented market parameter fields.");let p=je(n.marketParams),[h,b]=await Promise.all([a.readContract({address:_,abi:E,functionName:"isIrmEnabled",args:[p.irm]}),a.readContract({address:_,abi:E,functionName:"isLltvEnabled",args:[p.lltv]})]);if(!h||!b)throw new i("The new market\u2019s IRM and LLTV must first be enabled by the Morpho owner.");c=be({abi:E,functionName:"createMarket",args:[p]})}else if(o==="accrueInterest"||o==="setFee"){let{params:p}=await s(n.marketId);if(o==="setFee"){let h=Be(n.value);if(h>250000000000000000n)throw new i("Morpho market fee cannot exceed 25% (0.25e18).");c=be({abi:E,functionName:"setFee",args:[p,h]})}else c=be({abi:E,functionName:"accrueInterest",args:[p]})}else if(o==="enableLltv"){let p=Be(n.value);if(p>=10n**18n)throw new i("Morpho LLTV must be below 1e18.");c=be({abi:E,functionName:"enableLltv",args:[p]})}else{let p=mt(n.account);if(o==="setAuthorization"){if(typeof n.enabled!="boolean")throw new i("Provide enabled as a boolean.");c=be({abi:E,functionName:"setAuthorization",args:[p,n.enabled]})}else if(o==="setOwner"||o==="enableIrm"||o==="setFeeRecipient")c=be({abi:E,functionName:o,args:[p]});else throw new i("Unsupported Morpho operation.")}let m=`Morpho ${o}: ${JSON.stringify(n)}. ${o==="setAuthorization"&&n.enabled?"This account can manage all your Morpho positions, including borrowing and withdrawals. There is no amount cap.":""}${o==="setOwner"&&n.account===Yo?"Setting the owner to zero permanently relinquishes protocol administration.":""}${o==="createMarket"?"New market creation does not add it to Oak\u2019s verified action registry.":""}`,d=[e.unsignedTx({to:_,data:c,value:"0",chainId:f,description:m})];return{txs:d,preview:await e.preview(d,l),summary:m}}),r("morpho_liquidate",{marketId:{type:"string",description:"Verified Morpho Blue market id (0x + 64 hex digits) holding the unhealthy position."},borrower:{type:"string",description:"Address of the unhealthy borrower to liquidate."},repaidShares:A("Borrow shares to repay, in share base units (read the borrower position); cannot exceed their debt shares."),maxAssets:A('Most loan token you will pay, in base units of the market loan token (read its decimals). Example: "1000000" = 1 USDG.'),minCollateral:A("Least collateral you must receive, in collateral token units (base units, read its decimals); checked in simulation only.")},["marketId","borrower","repaidShares","maxAssets","minCollateral"],async(n,l)=>{let{rpc:o,params:a,marketId:u}=await s(n.marketId),c=mt(n.borrower),m=Be(n.repaidShares),d=Be(n.maxAssets),p=Be(n.minCollateral),[h,b,w,k]=await Promise.all([o.readContract({address:_,abi:E,functionName:"market",args:[u]}),o.readContract({address:_,abi:E,functionName:"position",args:[u,c]}),o.readContract({address:a.oracle,abi:Jo,functionName:"price"}),o.getBlock()]);if(m===0n||m>b[1]||w===0n)throw new i("Liquidation shares must fit the current debt and the oracle must be valid.");let y={totalSupplyAssets:h[0],totalSupplyShares:h[1],totalBorrowAssets:h[2],totalBorrowShares:h[3],lastUpdate:h[4],fee:h[5]},g=await o.readContract({address:a.irm,abi:Zo,functionName:"borrowRateView",args:[a,y]}),I=Qe(y,g,k.timestamp);if(se(b[1],I,h[3])<=Ae(b[2],w,a.lltv))throw new i("This borrower is healthy; liquidation is unavailable.");let x=se(m,Qe(y,g,k.timestamp+120n),h[3]);if(x>d)throw new i("Liquidation funding exceeds maxAssets.");if(await o.readContract({address:a.loanToken,abi:Xo,functionName:"balanceOf",args:[l]})<x)throw new i("Top up the loan token before liquidating.");let P=`Liquidate ${m} debt shares of ${c} on ${u}; exact approval ${x} loan-token base units; preview minimum ${p} collateral units. No callbacks; the wallet funds repayment. Approval can leave interest-buffer dust; revoke it afterward.`,C=[e.approval(a.loanToken,_,x.toString(),f),e.unsignedTx({to:_,data:be({abi:E,functionName:"liquidate",args:[a,c,0n,m,"0x"]}),value:"0",chainId:f,description:P})],L=await e.preview(C,l),v=Z=>L.changes.filter(H=>H.token.chainId===f&&R(H.token.address,Z)).reduce((H,F)=>H+BigInt(F.amount),0n);if(-v(a.loanToken)<=0n||-v(a.loanToken)>x||v(a.collateralToken)<p||v(a.collateralToken)<=0n)throw new i("Liquidation preview does not match the funding limit and collateral minimum.");return{txs:C,preview:L,requiredAssets:x.toString(),summary:`${P} MinCollateral is a local simulation check, not an on-chain floor.`}})]}};export{E as a,Wt as b,we as c,$t as d,Y as e,ko as f,Ot as g,yo as h,Et as i,go as j,Ht as k,De as l,Io as m,B as n,To as o,Mo as p,me as q,vo as r,Po as s,lt as t,j as u,qe as v,Bo as w,No as x,ut as y,se as z,Ae as A,Oo as B,je as C,ke as D,Xt as E,Qe as F,Ka as G,Qo as H,Qa as I,et as J,vt as K,O as L,la as M};
@@ -1 +1 @@
1
- import{b as s}from"./ORG6LVKJ.js";import{a as o,c as t}from"./VXCGMALF.js";import{getAddress as i}from"viem";var f=new Set(["priors_status",...s,...t.filter(r=>r.read).map(r=>r.name),"priors_ethos_status","priors_request_borrow","priors_request_repay","priors_request_stock","priors_request_backing","priors_pt_quote","priors_pt_position","priors_stock_quote","priors_savings_liquidity","priors_market_origin","priors_market_pins","priors_capabilities"]),p=new Set(["priors_sign_consent",...t.filter(r=>r.consentRoot).map(r=>r.name)]),u=new Set([...p,"priors_starter_line"]),R=new Set([...t.filter(r=>!r.read).map(r=>r.name),"priors_root_offer","priors_autopay_on","priors_autopay_off","priors_pt_buy","priors_pt_sell","priors_pt_redeem","priors_savings_force_withdraw","priors_stock_swap","priors_market_clear_bid_budget","priors_market_revoke_nft","priors_x_link"]),S=["priors_lend","priors_withdraw","priors_borrow","priors_repay","priors_starter_line","priors_close_line","priors_release_bond"];function c(r){let _=t.find(e=>e.name===r);return _?[o[_.contract],..._.approval==="bid"?[o.bidSpender]:[]]:r==="priors_root_offer"?[o.pool]:r==="priors_autopay_on"||r==="priors_autopay_off"?[o.autopay]:r==="priors_savings_force_withdraw"?[o.savings]:r==="priors_stock_swap"?[i("0xCaf681a66D020601342297493863E78C959E5cb2"),i("0x7Cd4E04E433E69e588728c86A3832753B5F846d4")]:r==="priors_pt_buy"||r==="priors_pt_sell"||r==="priors_pt_redeem"?[i("0x888888888889758F76e7103c6CbF23ABbF58F946")]:r==="priors_market_clear_bid_budget"?[o.bidSpender]:r==="priors_market_revoke_nft"?[o.registry,"0x0000000000000000000000000000000000000000"]:r==="priors_x_link"?[o.registry]:[]}export{f as a,p as b,u as c,R as d,S as e,c as f};
1
+ import{b as s}from"./UBI3HBXD.js";import{a as o,c as t}from"./VXCGMALF.js";import{getAddress as i}from"viem";var f=new Set(["priors_status",...s,...t.filter(r=>r.read).map(r=>r.name),"priors_ethos_status","priors_request_borrow","priors_request_repay","priors_request_stock","priors_request_backing","priors_pt_quote","priors_pt_position","priors_stock_quote","priors_savings_liquidity","priors_market_origin","priors_market_pins","priors_capabilities"]),p=new Set(["priors_sign_consent",...t.filter(r=>r.consentRoot).map(r=>r.name)]),u=new Set([...p,"priors_starter_line"]),R=new Set([...t.filter(r=>!r.read).map(r=>r.name),"priors_root_offer","priors_autopay_on","priors_autopay_off","priors_pt_buy","priors_pt_sell","priors_pt_redeem","priors_savings_force_withdraw","priors_stock_swap","priors_market_clear_bid_budget","priors_market_revoke_nft","priors_x_link"]),S=["priors_lend","priors_withdraw","priors_borrow","priors_repay","priors_starter_line","priors_close_line","priors_release_bond"];function c(r){let _=t.find(e=>e.name===r);return _?[o[_.contract],..._.approval==="bid"?[o.bidSpender]:[]]:r==="priors_root_offer"?[o.pool]:r==="priors_autopay_on"||r==="priors_autopay_off"?[o.autopay]:r==="priors_savings_force_withdraw"?[o.savings]:r==="priors_stock_swap"?[i("0xCaf681a66D020601342297493863E78C959E5cb2"),i("0x7Cd4E04E433E69e588728c86A3832753B5F846d4")]:r==="priors_pt_buy"||r==="priors_pt_sell"||r==="priors_pt_redeem"?[i("0x888888888889758F76e7103c6CbF23ABbF58F946")]:r==="priors_market_clear_bid_budget"?[o.bidSpender]:r==="priors_market_revoke_nft"?[o.registry,"0x0000000000000000000000000000000000000000"]:r==="priors_x_link"?[o.registry]:[]}export{f as a,p as b,u as c,R as d,S as e,c as f};
@@ -1 +1 @@
1
- import{a as k}from"./ROQQ62LP.js";import{e as P,i as O}from"./X5AL3DUK.js";import{a as g,b as f,f as E,g as S}from"./LJJYYUEG.js";import{a as h,w as M}from"./WBNFRPAT.js";import{a as y}from"./66F5ZH34.js";import{c as v,g as C}from"./NWNYJ26T.js";import{b}from"./TI727O2H.js";import{a as l}from"./XSD5NL7J.js";import{encodeFunctionData as c,parseAbi as H,zeroAddress as R}from"viem";var r=H(["function owner() view returns (address)","function feeTo() view returns (address)","function feeToSetter() view returns (address)","function protocolFeeController() view returns (address)","function setFeeTo(address)","function setFeeToSetter(address)","function setOwner(address)","function enableFeeAmount(uint24,int24)","function setFeeProtocol(uint8,uint8)","function collectProtocol(address,uint128,uint128) returns (uint128,uint128)","function transferOwnership(address)","function setProtocolFeeController(address)","function setProtocolFee((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks),uint24)","function collectProtocolFees(address recipient,address currency,uint256 amount) returns (uint256)"]),K=["set_fee_recipient","set_fee_setter","set_owner","enable_fee","set_pool_fee","collect_protocol","set_controller"],V={version:{description:'Uniswap version: "v2" for pairs, "v3" for concentrated liquidity or "v4" for PoolManager.',type:"string",enum:["v2","v3","v4"]},operation:{description:"set_fee_recipient/set_fee_setter: v2 roles; set_owner: owner; enable_fee: v3 tier; set_pool_fee: protocol fees; collect_protocol: collect fees; set_controller: v4 controller.",type:"string",enum:K},target:{...v,description:"Intended fee recipient, fee setter, owner or controller address for the selected administrative operation."},token0:{...v,description:"Lower sorted ERC-20 token address; use WETH for native ETH in v3."},token1:{...v,description:"Higher sorted ERC-20 token address."},fee:{description:"Pool fee in pips, hundredths of a basis point (3000 = 0.3%; 950000 = 95%).",type:"integer"},tickSpacing:{description:"Spacing between usable pool ticks, as an integer.",type:"integer"},fee0:{description:"Token0 or zero-for-one protocol fee: v3 divisor 0 (off) or 4\u201310; v4 pips, hundredths of a basis point, from 0 to 1000 (1000 = 0.1%).",type:"integer"},fee1:{description:"Token1 or one-for-zero protocol fee: v3 divisor 0 (off) or 4\u201310; v4 pips, hundredths of a basis point, from 0 to 1000 (1000 = 0.1%).",type:"integer"},currency:{...v,description:"Address of the currency whose protocol fees are collected; the zero address means native ETH."},amount:y('Amount of currency in base units; use currency decimals. Example: "1000000" = 1 currency at 6 decimals.'),amount0Max:y('Maximum amount of token0 in base units; use token0 decimals. Example: "1000000" = 1 token0 at 6 decimals.'),amount1Max:y('Maximum amount of token1 in base units; use token1 decimals. Example: "1000000" = 1 token1 at 6 decimals.'),poolKey:{description:"V4 pool key: sorted currencies, fee in pips, tick spacing and hook address.",type:"object"}};function G(_){let x=async e=>{let i=_.clientFor(b);if(e==="v2"){let[t,o]=await Promise.all([i.readContract({address:k,abi:r,functionName:"feeToSetter"}),i.readContract({address:k,abi:r,functionName:"feeTo"})]);return{version:e,contract:k,owner:t,feeRecipient:o}}if(e==="v3")return{version:e,contract:P.factory,owner:await i.readContract({address:P.factory,abi:r,functionName:"owner"})};if(e==="v4"){let[t,o]=await Promise.all([i.readContract({address:h,abi:r,functionName:"owner"}),i.readContract({address:h,abi:r,functionName:"protocolFeeController"})]);return{version:e,contract:h,owner:t,controller:o}}throw new l("Provide protocol version v2, v3 or v4.")};return{tools:[{name:"uniswap_protocol_status",inputSchema:{type:"object",additionalProperties:!1,required:["version"],properties:{version:V.version}},async execute(e){return S(e,["version"]),x(e.version)}},{name:"uniswap_protocol_admin",inputSchema:{type:"object",additionalProperties:!1,required:["version","operation"],properties:V},async execute(e,i){let{version:t,operation:o}=e,w=await x(t),I=_.clientFor(b),T=t==="v4"&&["set_pool_fee","collect_protocol"].includes(String(o))?"controller"in w?w.controller:void 0:w.owner;if(!T||!C(T,i))throw new l("The signing wallet does not hold the required Uniswap owner/controller role.");let N=w.contract,s,a,A=()=>{let n=f(e.target);if(n===R)throw new l("Administration target must be nonzero.");return n},d=(n,p,u,m)=>{if(typeof n!="number"||!Number.isInteger(n)||n<u||n>m)throw new l(`${p} must be an integer from ${u} to ${m}.`);return n};if(t==="v2"&&o==="set_fee_recipient")a=["target"],s=c({abi:r,functionName:"setFeeTo",args:[f(e.target)]});else if(t==="v2"&&o==="set_fee_setter")a=["target"],s=c({abi:r,functionName:"setFeeToSetter",args:[A()]});else if(t==="v3"&&o==="set_owner")a=["target"],s=c({abi:r,functionName:"setOwner",args:[A()]});else if(t==="v3"&&o==="enable_fee")a=["fee","tickSpacing"],s=c({abi:r,functionName:"enableFeeAmount",args:[d(e.fee,"fee",0,999999),d(e.tickSpacing,"tickSpacing",1,16383)]});else if(t==="v3"&&["set_pool_fee","collect_protocol"].includes(String(o))){a=["token0","token1","fee",...o==="set_pool_fee"?["fee0","fee1"]:["amount0Max","amount1Max"]];let n=f(e.token0),p=f(e.token1),u=d(e.fee,"fee",0,999999);if(N=await I.readContract({address:P.factory,abi:O,functionName:"getPool",args:[n,p,u]}),N===R)throw new l("No factory-verified v3 pool exists for these tokens and fee.");if(o==="set_pool_fee"){let m=z=>{let F=d(z,"fee divisor",0,10);if(F!==0&&F<4)throw new l("V3 protocol fee divisors must be zero or 4 through 10.");return F};s=c({abi:r,functionName:"setFeeProtocol",args:[m(e.fee0),m(e.fee1)]})}else s=c({abi:r,functionName:"collectProtocol",args:[i,g(e.amount0Max,"amount0Max",128,!0),g(e.amount1Max,"amount1Max",128,!0)]})}else if(t==="v4"&&o==="set_owner")a=["target"],s=c({abi:r,functionName:"transferOwnership",args:[A()]});else if(t==="v4"&&o==="set_controller")a=["target"],s=c({abi:r,functionName:"setProtocolFeeController",args:[f(e.target)]});else if(t==="v4"&&o==="set_pool_fee"){a=["poolKey","fee0","fee1"];let n=M(e.poolKey),p=d(e.fee0,"fee0 pips",0,1e3),u=d(e.fee1,"fee1 pips",0,1e3);s=c({abi:r,functionName:"setProtocolFee",args:[n,p+(u<<12)]})}else if(t==="v4"&&o==="collect_protocol")a=["currency","amount"],s=c({abi:r,functionName:"collectProtocolFees",args:[i,f(e.currency),g(e.amount,"amount",256,!0)]});else throw new l("This operation is not supported by the selected Uniswap protocol version.");return S(e,["version","operation",...a]),E(_,[_.unsignedTx({to:N,data:s,value:"0",chainId:b,description:`Uniswap ${t} protocol administration: ${o}. Role holder ${i}.`})],i,"Privileged protocol operation. Review the exact role/recipient/fee changes. Protocol fee collections pay the signing wallet; no wallet token approval is required.")}}]}}export{r as a,G as b};
1
+ import{a as k}from"./22TU5PFT.js";import{e as P,i as O}from"./6D3XNCOX.js";import{a as g,b as f,f as E,g as S}from"./QPY6UTLU.js";import{a as h,w as M}from"./KLEJ3W4T.js";import{a as y}from"./66F5ZH34.js";import{c as v,g as C}from"./NWNYJ26T.js";import{b}from"./TI727O2H.js";import{a as l}from"./XSD5NL7J.js";import{encodeFunctionData as c,parseAbi as H,zeroAddress as R}from"viem";var r=H(["function owner() view returns (address)","function feeTo() view returns (address)","function feeToSetter() view returns (address)","function protocolFeeController() view returns (address)","function setFeeTo(address)","function setFeeToSetter(address)","function setOwner(address)","function enableFeeAmount(uint24,int24)","function setFeeProtocol(uint8,uint8)","function collectProtocol(address,uint128,uint128) returns (uint128,uint128)","function transferOwnership(address)","function setProtocolFeeController(address)","function setProtocolFee((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks),uint24)","function collectProtocolFees(address recipient,address currency,uint256 amount) returns (uint256)"]),K=["set_fee_recipient","set_fee_setter","set_owner","enable_fee","set_pool_fee","collect_protocol","set_controller"],V={version:{description:'Uniswap version: "v2" for pairs, "v3" for concentrated liquidity or "v4" for PoolManager.',type:"string",enum:["v2","v3","v4"]},operation:{description:"set_fee_recipient/set_fee_setter: v2 roles; set_owner: owner; enable_fee: v3 tier; set_pool_fee: protocol fees; collect_protocol: collect fees; set_controller: v4 controller.",type:"string",enum:K},target:{...v,description:"Intended fee recipient, fee setter, owner or controller address for the selected administrative operation."},token0:{...v,description:"Lower sorted ERC-20 token address; use WETH for native ETH in v3."},token1:{...v,description:"Higher sorted ERC-20 token address."},fee:{description:"Pool fee in pips, hundredths of a basis point (3000 = 0.3%; 950000 = 95%).",type:"integer"},tickSpacing:{description:"Spacing between usable pool ticks, as an integer.",type:"integer"},fee0:{description:"Token0 or zero-for-one protocol fee: v3 divisor 0 (off) or 4\u201310; v4 pips, hundredths of a basis point, from 0 to 1000 (1000 = 0.1%).",type:"integer"},fee1:{description:"Token1 or one-for-zero protocol fee: v3 divisor 0 (off) or 4\u201310; v4 pips, hundredths of a basis point, from 0 to 1000 (1000 = 0.1%).",type:"integer"},currency:{...v,description:"Address of the currency whose protocol fees are collected; the zero address means native ETH."},amount:y('Amount of currency in base units; use currency decimals. Example: "1000000" = 1 currency at 6 decimals.'),amount0Max:y('Maximum amount of token0 in base units; use token0 decimals. Example: "1000000" = 1 token0 at 6 decimals.'),amount1Max:y('Maximum amount of token1 in base units; use token1 decimals. Example: "1000000" = 1 token1 at 6 decimals.'),poolKey:{description:"V4 pool key: sorted currencies, fee in pips, tick spacing and hook address.",type:"object"}};function G(_){let x=async e=>{let i=_.clientFor(b);if(e==="v2"){let[t,o]=await Promise.all([i.readContract({address:k,abi:r,functionName:"feeToSetter"}),i.readContract({address:k,abi:r,functionName:"feeTo"})]);return{version:e,contract:k,owner:t,feeRecipient:o}}if(e==="v3")return{version:e,contract:P.factory,owner:await i.readContract({address:P.factory,abi:r,functionName:"owner"})};if(e==="v4"){let[t,o]=await Promise.all([i.readContract({address:h,abi:r,functionName:"owner"}),i.readContract({address:h,abi:r,functionName:"protocolFeeController"})]);return{version:e,contract:h,owner:t,controller:o}}throw new l("Provide protocol version v2, v3 or v4.")};return{tools:[{name:"uniswap_protocol_status",inputSchema:{type:"object",additionalProperties:!1,required:["version"],properties:{version:V.version}},async execute(e){return S(e,["version"]),x(e.version)}},{name:"uniswap_protocol_admin",inputSchema:{type:"object",additionalProperties:!1,required:["version","operation"],properties:V},async execute(e,i){let{version:t,operation:o}=e,w=await x(t),I=_.clientFor(b),T=t==="v4"&&["set_pool_fee","collect_protocol"].includes(String(o))?"controller"in w?w.controller:void 0:w.owner;if(!T||!C(T,i))throw new l("The signing wallet does not hold the required Uniswap owner/controller role.");let N=w.contract,s,a,A=()=>{let n=f(e.target);if(n===R)throw new l("Administration target must be nonzero.");return n},d=(n,p,u,m)=>{if(typeof n!="number"||!Number.isInteger(n)||n<u||n>m)throw new l(`${p} must be an integer from ${u} to ${m}.`);return n};if(t==="v2"&&o==="set_fee_recipient")a=["target"],s=c({abi:r,functionName:"setFeeTo",args:[f(e.target)]});else if(t==="v2"&&o==="set_fee_setter")a=["target"],s=c({abi:r,functionName:"setFeeToSetter",args:[A()]});else if(t==="v3"&&o==="set_owner")a=["target"],s=c({abi:r,functionName:"setOwner",args:[A()]});else if(t==="v3"&&o==="enable_fee")a=["fee","tickSpacing"],s=c({abi:r,functionName:"enableFeeAmount",args:[d(e.fee,"fee",0,999999),d(e.tickSpacing,"tickSpacing",1,16383)]});else if(t==="v3"&&["set_pool_fee","collect_protocol"].includes(String(o))){a=["token0","token1","fee",...o==="set_pool_fee"?["fee0","fee1"]:["amount0Max","amount1Max"]];let n=f(e.token0),p=f(e.token1),u=d(e.fee,"fee",0,999999);if(N=await I.readContract({address:P.factory,abi:O,functionName:"getPool",args:[n,p,u]}),N===R)throw new l("No factory-verified v3 pool exists for these tokens and fee.");if(o==="set_pool_fee"){let m=z=>{let F=d(z,"fee divisor",0,10);if(F!==0&&F<4)throw new l("V3 protocol fee divisors must be zero or 4 through 10.");return F};s=c({abi:r,functionName:"setFeeProtocol",args:[m(e.fee0),m(e.fee1)]})}else s=c({abi:r,functionName:"collectProtocol",args:[i,g(e.amount0Max,"amount0Max",128,!0),g(e.amount1Max,"amount1Max",128,!0)]})}else if(t==="v4"&&o==="set_owner")a=["target"],s=c({abi:r,functionName:"transferOwnership",args:[A()]});else if(t==="v4"&&o==="set_controller")a=["target"],s=c({abi:r,functionName:"setProtocolFeeController",args:[f(e.target)]});else if(t==="v4"&&o==="set_pool_fee"){a=["poolKey","fee0","fee1"];let n=M(e.poolKey),p=d(e.fee0,"fee0 pips",0,1e3),u=d(e.fee1,"fee1 pips",0,1e3);s=c({abi:r,functionName:"setProtocolFee",args:[n,p+(u<<12)]})}else if(t==="v4"&&o==="collect_protocol")a=["currency","amount"],s=c({abi:r,functionName:"collectProtocolFees",args:[i,f(e.currency),g(e.amount,"amount",256,!0)]});else throw new l("This operation is not supported by the selected Uniswap protocol version.");return S(e,["version","operation",...a]),E(_,[_.unsignedTx({to:N,data:s,value:"0",chainId:b,description:`Uniswap ${t} protocol administration: ${o}. Role holder ${i}.`})],i,"Privileged protocol operation. Review the exact role/recipient/fee changes. Protocol fee collections pay the signing wallet; no wallet token approval is required.")}}]}}export{r as a,G as b};
@@ -1 +1 @@
1
- import{L as z}from"./JPPQDELB.js";import{b as W,c as K}from"./A3BJSQ23.js";import{a as D}from"./YBLJ75U5.js";import{c as C}from"./LCH6F5HT.js";import{c as B,f as R,i as F,j as L,k as H}from"./X24YTJST.js";import{a as V}from"./43LI5NKJ.js";import{a as u}from"./66F5ZH34.js";import{g as O}from"./NWNYJ26T.js";import{b as A}from"./TI727O2H.js";import{a as o}from"./XSD5NL7J.js";import{encodeFunctionData as I,erc20Abi as j,getAddress as P,parseAbi as k}from"viem";var f=k(["function asset() view returns (address)","function decimals() view returns (uint8)","function balanceOf(address) view returns (uint256)","function previewMint(uint256) view returns (uint256)","function previewRedeem(uint256) view returns (uint256)","function previewWithdraw(uint256) view returns (uint256)","function mint(uint256 shares,address receiver) returns (uint256)","function redeem(uint256 shares,address receiver,address owner) returns (uint256)","function withdraw(uint256 assets,address receiver,address owner) returns (uint256)"]);function U(t,n=!1){if(typeof t!="string"||!/^\d+$/.test(t)||t.length>78||BigInt(t)>=1n<<256n||!n&&BigInt(t)===0n)throw new o("Provide a positive uint256 decimal base-unit string.");return BigInt(t)}function ce(t,n,y){return["details","analytics","manage","mint",n==="netnet"?"redeem":"withdraw_assets","force_exit","in_kind_exit"].map(e=>{let $=[...n==="longbow"?["vault"]:[],...e==="mint"?["shares","maxAssets"]:e==="redeem"?["shares"]:e==="withdraw_assets"?["amount"]:e==="force_exit"?["maxPenaltyAssets","minAmountOut"]:[]],m={...n==="longbow"?{vault:{type:"string",enum:y.map(i=>i.vault),description:"Pinned vault address on chain 4663; use longbow_list to compare vault names."}}:{}};e==="in_kind_exit"&&(Object.assign(m,{amount:u(`Assets to receive, in base units of the vault's asset (read its decimals; USDG has 6). Example: "1000000" = 1 USDG.`),maxShares:u('Most vault shares you will burn, in share base units (shares have 18 decimals). Example: "1000000000000000000" = 1 share.'),maxPenaltyAssets:u(`Highest exit penalty you accept, in base units of the vault's asset (read its decimals). Example: "10000" = 0.01 USDG for a 6-decimal asset.`),deadline:u("Absolute Unix seconds deadline, no more than five minutes ahead. Example: 1800000000.")}),$.push("amount","maxShares","maxPenaltyAssets","deadline")),e==="mint"&&Object.assign(m,{shares:u('Vault shares to mint, in base units (shares have 18 decimals). Example: "1000000000000000000" = 1 share.'),maxAssets:u(`Most of the vault's asset you will pay, in base units (read its decimals; USDG has 6). Example: "1000000" = 1 USDG.`)}),e==="redeem"&&(m.shares=u('Vault shares to redeem, in base units (shares have 18 decimals). Example: "1000000000000000000" = 1 share.')),e==="withdraw_assets"&&(m.amount=u(`Assets to withdraw, in base units of the vault's asset (read its decimals; USDG has 6). Example: "1000000" = 1 USDG.`)),e==="force_exit"&&Object.assign(m,{maxPenaltyAssets:u(`Highest exit penalty you accept, in base units of the vault's asset (read its decimals). Example: "10000" = 0.01 USDG for a 6-decimal asset.`),minAmountOut:u(`Least of the vault's asset you must receive, in base units (read its decimals). Example: "1000000" = 1 USDG.`)});let J=C(t,`${n}_manage`,y[0].vault,y[0].asset),N=D(t,`${n}_analytics`,y[0].vault);if(e==="manage"||e==="analytics"){let i=e==="manage"?J.inputSchema:N.inputSchema;Object.assign(m,i.properties),e==="analytics"&&n==="longbow"&&(m.view={type:"string",enum:["apy","published_apy"],description:"Report: apy (realized yield from share price) or published_apy (yield published by the project)."}),$.push(...i.required)}return{name:`${n}_${e}`,inputSchema:{type:"object",properties:m,required:$,additionalProperties:!1,...e==="analytics"&&n==="netnet"?{allOf:N.inputSchema.allOf}:{}},execute:async(i,r)=>{try{if(V(r),Object.keys(i).some(c=>!Object.hasOwn(m,c)))throw new o("Unsupported vault feature argument.");let _=n==="netnet"?y[0]:y.find(c=>typeof i.vault=="string"&&O(c.vault,i.vault));if(!_)throw new o("Choose a current vault returned by the project list tool.");let{vault:s,asset:a}=_,b={...i};if(delete b.vault,e==="details")return F(t,`${n}_details`,s,a).execute(b,r);if(e==="manage")return C(t,`${n}_manage`,s,a).execute(b,r);if(e==="analytics"){if(n==="longbow"&&i.view==="published_apy")return K(t,s,a,b);if(n==="longbow"&&i.view==="apy")return W(t,s,a,b);if(n==="longbow")throw new o("Choose apy or published_apy; the Longbow vault is not indexed by Morpho for other analytics views.");return{...await D(t,`${n}_analytics`,s).execute(b,r),asset:{...a,address:P(a.address)}}}if(e==="in_kind_exit")return z(t,s,a,i,r);let h=t.clientFor(A);if(await h.getChainId()!==A)throw new o("Vault actions require chain 4663.");let[Q,X,Y]=await Promise.all([h.readContract({address:s,abi:f,functionName:"asset"}),h.readContract({address:s,abi:f,functionName:"decimals"}),h.readContract({address:a.address,abi:j,functionName:"decimals"})]);if(P(Q)!==P(a.address)||X!==18||Y!==a.decimals)throw new o("Vault metadata does not match the pinned asset and shares.");let T=e==="force_exit"?await h.readContract({address:s,abi:f,functionName:"balanceOf",args:[r]}):void 0;if(e==="force_exit"){let c=await R(t,h,s,r,T,B(i.maxPenaltyAssets),a),E=U(i.minAmountOut),w=[c.tx],v=await t.preview(w,r);return H(v.changes,s,T,E,a),{txs:w,preview:v,summary:`${L(c.plan,a.symbol)} ${v.summary}`}}let d=e==="mint",g=e==="redeem",l=U(d||g?i.shares:i.amount),x=await h.readContract({address:s,abi:f,functionName:d?"previewMint":g?"previewRedeem":"previewWithdraw",args:[l]});if(x<=0n||d&&x>U(i.maxAssets))throw new o("Vault quote is zero or exceeds maxAssets.");let q=d?void 0:await h.readContract({address:s,abi:f,functionName:"balanceOf",args:[r]});if(!d&&(g?l:x)>q)throw new o("The wallet share balance cannot cover this exit.");let Z=d?I({abi:f,functionName:"mint",args:[l,r]}):g?I({abi:f,functionName:"redeem",args:[l,r,r]}):I({abi:f,functionName:"withdraw",args:[l,r,r]}),G=`${e} ${l} ${d||g?"18-decimal share":`${a.decimals}-decimal ${a.symbol}`} base units on ${s}; beneficiary ${r}.`,M=[...d?[t.approval(a.address,s,x.toString(),A)]:[],t.unsignedTx({to:s,data:Z,value:"0",chainId:A,description:G})],S=await t.preview(M,r),p=(c,E)=>S.changes.filter(w=>w.token.chainId===A&&O(w.token.address,c)).reduce((w,v)=>{if(v.token.decimals!==E||!/^-?\d+$/.test(v.amount))throw new o("Invalid vault preview metadata.");return w+BigInt(v.amount)},0n);if(d?p(a.address,a.decimals)!==-x||p(s,18)!==l:g?p(s,18)!==-l||p(a.address,a.decimals)<=0n:p(a.address,a.decimals)!==l||-p(s,18)<=0n||-p(s,18)>q)throw new o("Vault preview does not match the requested amount and beneficiary.");return{txs:M,preview:S,summary:`${G} Counterpart quote ${x} base units. Mint approval is exact; accrual may require a fresh quote. Standard ERC-4626 calls encode no minimum receipt. ${S.summary}`}}catch(_){throw new o(t.plainError(_))}}}})}export{ce as a};
1
+ import{b as W,c as K}from"./A3BJSQ23.js";import{M as z}from"./XKLXVTSE.js";import{a as D}from"./IPU656WB.js";import{c as C}from"./LCH6F5HT.js";import{c as B,f as R,i as F,j as L,k as H}from"./X24YTJST.js";import{a as V}from"./43LI5NKJ.js";import{a as u}from"./66F5ZH34.js";import{g as O}from"./NWNYJ26T.js";import{b as A}from"./TI727O2H.js";import{a as o}from"./XSD5NL7J.js";import{encodeFunctionData as I,erc20Abi as j,getAddress as P,parseAbi as k}from"viem";var f=k(["function asset() view returns (address)","function decimals() view returns (uint8)","function balanceOf(address) view returns (uint256)","function previewMint(uint256) view returns (uint256)","function previewRedeem(uint256) view returns (uint256)","function previewWithdraw(uint256) view returns (uint256)","function mint(uint256 shares,address receiver) returns (uint256)","function redeem(uint256 shares,address receiver,address owner) returns (uint256)","function withdraw(uint256 assets,address receiver,address owner) returns (uint256)"]);function U(t,n=!1){if(typeof t!="string"||!/^\d+$/.test(t)||t.length>78||BigInt(t)>=1n<<256n||!n&&BigInt(t)===0n)throw new o("Provide a positive uint256 decimal base-unit string.");return BigInt(t)}function ce(t,n,y){return["details","analytics","manage","mint",n==="netnet"?"redeem":"withdraw_assets","force_exit","in_kind_exit"].map(e=>{let $=[...n==="longbow"?["vault"]:[],...e==="mint"?["shares","maxAssets"]:e==="redeem"?["shares"]:e==="withdraw_assets"?["amount"]:e==="force_exit"?["maxPenaltyAssets","minAmountOut"]:[]],m={...n==="longbow"?{vault:{type:"string",enum:y.map(i=>i.vault),description:"Pinned vault address on chain 4663; use longbow_list to compare vault names."}}:{}};e==="in_kind_exit"&&(Object.assign(m,{amount:u(`Assets to receive, in base units of the vault's asset (read its decimals; USDG has 6). Example: "1000000" = 1 USDG.`),maxShares:u('Most vault shares you will burn, in share base units (shares have 18 decimals). Example: "1000000000000000000" = 1 share.'),maxPenaltyAssets:u(`Highest exit penalty you accept, in base units of the vault's asset (read its decimals). Example: "10000" = 0.01 USDG for a 6-decimal asset.`),deadline:u("Absolute Unix seconds deadline, no more than five minutes ahead. Example: 1800000000.")}),$.push("amount","maxShares","maxPenaltyAssets","deadline")),e==="mint"&&Object.assign(m,{shares:u('Vault shares to mint, in base units (shares have 18 decimals). Example: "1000000000000000000" = 1 share.'),maxAssets:u(`Most of the vault's asset you will pay, in base units (read its decimals; USDG has 6). Example: "1000000" = 1 USDG.`)}),e==="redeem"&&(m.shares=u('Vault shares to redeem, in base units (shares have 18 decimals). Example: "1000000000000000000" = 1 share.')),e==="withdraw_assets"&&(m.amount=u(`Assets to withdraw, in base units of the vault's asset (read its decimals; USDG has 6). Example: "1000000" = 1 USDG.`)),e==="force_exit"&&Object.assign(m,{maxPenaltyAssets:u(`Highest exit penalty you accept, in base units of the vault's asset (read its decimals). Example: "10000" = 0.01 USDG for a 6-decimal asset.`),minAmountOut:u(`Least of the vault's asset you must receive, in base units (read its decimals). Example: "1000000" = 1 USDG.`)});let J=C(t,`${n}_manage`,y[0].vault,y[0].asset),N=D(t,`${n}_analytics`,y[0].vault);if(e==="manage"||e==="analytics"){let i=e==="manage"?J.inputSchema:N.inputSchema;Object.assign(m,i.properties),e==="analytics"&&n==="longbow"&&(m.view={type:"string",enum:["apy","published_apy"],description:"Report: apy (realized yield from share price) or published_apy (yield published by the project)."}),$.push(...i.required)}return{name:`${n}_${e}`,inputSchema:{type:"object",properties:m,required:$,additionalProperties:!1,...e==="analytics"&&n==="netnet"?{allOf:N.inputSchema.allOf}:{}},execute:async(i,r)=>{try{if(V(r),Object.keys(i).some(c=>!Object.hasOwn(m,c)))throw new o("Unsupported vault feature argument.");let _=n==="netnet"?y[0]:y.find(c=>typeof i.vault=="string"&&O(c.vault,i.vault));if(!_)throw new o("Choose a current vault returned by the project list tool.");let{vault:s,asset:a}=_,b={...i};if(delete b.vault,e==="details")return F(t,`${n}_details`,s,a).execute(b,r);if(e==="manage")return C(t,`${n}_manage`,s,a).execute(b,r);if(e==="analytics"){if(n==="longbow"&&i.view==="published_apy")return K(t,s,a,b);if(n==="longbow"&&i.view==="apy")return W(t,s,a,b);if(n==="longbow")throw new o("Choose apy or published_apy; the Longbow vault is not indexed by Morpho for other analytics views.");return{...await D(t,`${n}_analytics`,s).execute(b,r),asset:{...a,address:P(a.address)}}}if(e==="in_kind_exit")return z(t,s,a,i,r);let h=t.clientFor(A);if(await h.getChainId()!==A)throw new o("Vault actions require chain 4663.");let[Q,X,Y]=await Promise.all([h.readContract({address:s,abi:f,functionName:"asset"}),h.readContract({address:s,abi:f,functionName:"decimals"}),h.readContract({address:a.address,abi:j,functionName:"decimals"})]);if(P(Q)!==P(a.address)||X!==18||Y!==a.decimals)throw new o("Vault metadata does not match the pinned asset and shares.");let T=e==="force_exit"?await h.readContract({address:s,abi:f,functionName:"balanceOf",args:[r]}):void 0;if(e==="force_exit"){let c=await R(t,h,s,r,T,B(i.maxPenaltyAssets),a),E=U(i.minAmountOut),w=[c.tx],v=await t.preview(w,r);return H(v.changes,s,T,E,a),{txs:w,preview:v,summary:`${L(c.plan,a.symbol)} ${v.summary}`}}let d=e==="mint",g=e==="redeem",l=U(d||g?i.shares:i.amount),x=await h.readContract({address:s,abi:f,functionName:d?"previewMint":g?"previewRedeem":"previewWithdraw",args:[l]});if(x<=0n||d&&x>U(i.maxAssets))throw new o("Vault quote is zero or exceeds maxAssets.");let q=d?void 0:await h.readContract({address:s,abi:f,functionName:"balanceOf",args:[r]});if(!d&&(g?l:x)>q)throw new o("The wallet share balance cannot cover this exit.");let Z=d?I({abi:f,functionName:"mint",args:[l,r]}):g?I({abi:f,functionName:"redeem",args:[l,r,r]}):I({abi:f,functionName:"withdraw",args:[l,r,r]}),G=`${e} ${l} ${d||g?"18-decimal share":`${a.decimals}-decimal ${a.symbol}`} base units on ${s}; beneficiary ${r}.`,M=[...d?[t.approval(a.address,s,x.toString(),A)]:[],t.unsignedTx({to:s,data:Z,value:"0",chainId:A,description:G})],S=await t.preview(M,r),p=(c,E)=>S.changes.filter(w=>w.token.chainId===A&&O(w.token.address,c)).reduce((w,v)=>{if(v.token.decimals!==E||!/^-?\d+$/.test(v.amount))throw new o("Invalid vault preview metadata.");return w+BigInt(v.amount)},0n);if(d?p(a.address,a.decimals)!==-x||p(s,18)!==l:g?p(s,18)!==-l||p(a.address,a.decimals)<=0n:p(a.address,a.decimals)!==l||-p(s,18)<=0n||-p(s,18)>q)throw new o("Vault preview does not match the requested amount and beneficiary.");return{txs:M,preview:S,summary:`${G} Counterpart quote ${x} base units. Mint approval is exact; accrual may require a fresh quote. Standard ERC-4626 calls encode no minimum receipt. ${S.summary}`}}catch(_){throw new o(t.plainError(_))}}}})}export{ce as a};
@@ -1 +1 @@
1
- import{c as D}from"./VMZYFO6I.js";import{b as O,g as M,i as A,j as B,k as T,l as P,m as I,n as U,r as k,s as F,v as f,x as z}from"./Y64GFBTA.js";import{a as w,e as _}from"./NWNYJ26T.js";import{b as y}from"./TI727O2H.js";import{a as d}from"./XSD5NL7J.js";function $(u){return{...u,token:{...u.token,symbol:f(u.token.symbol)??"unknown"}}}var Q=u=>{let N=z(u);async function G(t,r){let g=T(r),i=I(t.originChainId),e=I(t.destinationChainId);if(i!==y&&e!==y)throw new d(`A Relay quote must start or end on chain ${y}.`);let h=P(t.originCurrency??O),b=P(t.destinationCurrency??O),c=T(t.recipient??g),a=U(t.amount);if(a==="0")throw new d("Provide a positive bridge amount.");let n=t.tradeType??"EXACT_INPUT";if(!["EXACT_INPUT","EXACT_OUTPUT","EXPECTED_OUTPUT"].includes(String(n)))throw new d("Choose EXACT_INPUT, EXACT_OUTPUT or EXPECTED_OUTPUT.");let m={};for(let E of["includedSwapSources","excludedSwapSources","includedOriginSwapSources","includedDestinationSwapSources"]){let p=t[E];if(p!==void 0){if(!Array.isArray(p)||p.length>100||p.some(j=>typeof j!="string"||!/^[A-Za-z0-9._ -]{1,128}$/.test(j)))throw new d("Provide valid Relay swap source names.");m[E]=p}}let S=await N("/quote/v2",{user:g,recipient:c,originChainId:i,destinationChainId:e,originCurrency:h,destinationCurrency:b,amount:a,tradeType:n,...m}),o=A(S.details),l=$(k(o.currencyIn)),s=$(k(o.currencyOut)),C=U(A(o.currencyOut).minimumAmount);F(T(o.sender)===g&&T(o.recipient)===c&&l.token.chainId===i&&l.token.address===h&&(n==="EXACT_INPUT"?l.amount===a:s.amount===a)&&s.token.chainId===e&&s.token.address===b&&BigInt(C)<=BigInt(s.amount));let H=Object.fromEntries(Object.entries(A(S.fees)).map(([E,p])=>[E,$(k(p))])),R=typeof o.timeEstimate=="number"&&Number.isFinite(o.timeEstimate)&&o.timeEstimate>=0?o.timeEstimate:void 0,v=M(S.fees),X=e===y,x=X?"relay_bridge_in":"relay_bridge_out",q=n==="EXACT_INPUT"&&Object.keys(m).length===0&&i!==e&&(!X||D(i)!==void 0);return{executable:!1,nextAction:q?x:void 0,originChainId:i,destinationChainId:e,recipient:c,tradeType:n,amountIn:l,amountOut:s,minAmountOut:{token:s.token,amount:C},fees:H,...v,slippage:{source:"provider",minimumAmount:C},...R===void 0?{}:{timeEstimateSeconds:R},summary:`${v.feeDisclosure} Read-only Relay estimate: ${l.amount} base units of ${l.token.symbol} (${l.token.decimals} decimals) on chain ${i} for about ${s.amount}, minimum ${C}, base units of ${s.token.symbol} (${s.token.decimals} decimals) on chain ${e} for ${c}. Slippage: selected by Relay; Oak sent no slippage setting. The returned minimum above is the quote floor. Relay fees are already deducted from the output; origin gas is separate. Nothing was built or signed, and this estimate cannot be executed. ${q?`To bridge, call ${x}; it fetches a fresh quote and shows its own preview for human confirmation.`:"This estimate shape has no matching Oak execution path. No action will preserve these trade type or routing options."}`}}async function Z(t){let r=t.chainId===void 0?void 0:I(t.chainId),i=B((await N("/chains")).chains).map(A).flatMap(e=>{if(typeof e.id!="number"||!Number.isSafeInteger(e.id)||e.id<=0)return[];if(r!==void 0&&e.id!==r)return[];let h=e.disabled===!1,b=_(e.currency)?e.currency:{},c={chainId:e.id,name:f(e.displayName,"name")??f(e.name,"name")??String(e.id),vmType:f(e.vmType),nativeCurrency:{symbol:f(b.symbol),decimals:typeof b.decimals=="number"?b.decimals:void 0},bridgeIn:e.id!==y&&h&&D(e.id)!==void 0,bridgeOut:e.id!==y&&h&&e.vmType==="evm"};if(r===void 0)return[c];let a=new Map;for(let n of[...Array.isArray(e.featuredTokens)?e.featuredTokens:[],...Array.isArray(e.erc20Currencies)?e.erc20Currencies:[]]){if(!_(n)||typeof n.address!="string"||!new RegExp(w).test(n.address)||typeof n.decimals!="number"||!Number.isInteger(n.decimals)||n.decimals<0||n.decimals>255)continue;let m=T(n.address);a.has(m)||a.set(m,{address:m,symbol:f(n.symbol)??"unknown",decimals:n.decimals,bridgeable:n.supportsBridging===!0})}return[{...c,currencies:[...a.values()]}]});if(r!==void 0&&!i.length)throw new d(`Relay does not list chain ${r}.`);return{chains:i,summary:`${i.length} Relay chain${i.length===1?"":"s"}. bridgeIn marks origins relay_bridge_in can build from; bridgeOut marks destinations relay_bridge_out can reach. Currency lists are Relay-reported display data; bridgeable false means Relay does not bridge that token. Confirm token addresses before bridging.`}}return{tools:[{name:"relay_quote",inputSchema:{type:"object",additionalProperties:!1,required:["originChainId","destinationChainId","amount"],properties:{originChainId:{type:"integer",minimum:1,description:"Origin chain ID."},destinationChainId:{type:"integer",minimum:1,description:"Destination chain ID."},originCurrency:{type:"string",pattern:w,description:"Origin token address; defaults to the origin chain\u2019s native token."},destinationCurrency:{type:"string",pattern:w,description:"Destination token address; defaults to the destination chain\u2019s native token."},amount:{type:"string",pattern:"^[1-9][0-9]*$",description:'Input token amount for EXACT_INPUT, otherwise output token amount, in base units using that token\u2019s decimals (USDG has 6: "1000000" = 1 USDG).'},recipient:{type:"string",pattern:w,description:"Destination recipient address; defaults to your wallet."},tradeType:{type:"string",enum:["EXACT_INPUT","EXACT_OUTPUT","EXPECTED_OUTPUT"],description:"EXACT_INPUT fixes input; EXACT_OUTPUT fixes output; EXPECTED_OUTPUT targets output."},...Object.fromEntries(["includedSwapSources","excludedSwapSources","includedOriginSwapSources","includedDestinationSwapSources"].map(t=>[t,{type:"array",description:t==="excludedSwapSources"?"Swap sources to exclude.":t==="includedOriginSwapSources"?"Origin swap sources to include.":t==="includedDestinationSwapSources"?"Destination swap sources to include.":"Swap sources to include.",maxItems:100,items:{type:"string",pattern:"^[A-Za-z0-9._ -]{1,128}$"}}]))}},execute:async(t,r)=>{try{return await G(t,r)}catch(g){throw new d(u.plainError(g))}}},{name:"relay_chains",inputSchema:{type:"object",additionalProperties:!1,properties:{chainId:{type:"integer",minimum:1,description:"Filter by chain ID."}}},execute:async t=>{try{return await Z(t)}catch(r){throw new d(u.plainError(r))}}}]}};export{Q as a};
1
+ import{c as D}from"./DXAPKN7H.js";import{b as O,g as M,i as A,j as B,k as T,l as P,m as I,n as U,r as k,s as F,v as f,x as z}from"./Y64GFBTA.js";import{a as w,e as _}from"./NWNYJ26T.js";import{b as y}from"./TI727O2H.js";import{a as d}from"./XSD5NL7J.js";function $(u){return{...u,token:{...u.token,symbol:f(u.token.symbol)??"unknown"}}}var Q=u=>{let N=z(u);async function G(t,r){let g=T(r),i=I(t.originChainId),e=I(t.destinationChainId);if(i!==y&&e!==y)throw new d(`A Relay quote must start or end on chain ${y}.`);let h=P(t.originCurrency??O),b=P(t.destinationCurrency??O),c=T(t.recipient??g),a=U(t.amount);if(a==="0")throw new d("Provide a positive bridge amount.");let n=t.tradeType??"EXACT_INPUT";if(!["EXACT_INPUT","EXACT_OUTPUT","EXPECTED_OUTPUT"].includes(String(n)))throw new d("Choose EXACT_INPUT, EXACT_OUTPUT or EXPECTED_OUTPUT.");let m={};for(let E of["includedSwapSources","excludedSwapSources","includedOriginSwapSources","includedDestinationSwapSources"]){let p=t[E];if(p!==void 0){if(!Array.isArray(p)||p.length>100||p.some(j=>typeof j!="string"||!/^[A-Za-z0-9._ -]{1,128}$/.test(j)))throw new d("Provide valid Relay swap source names.");m[E]=p}}let S=await N("/quote/v2",{user:g,recipient:c,originChainId:i,destinationChainId:e,originCurrency:h,destinationCurrency:b,amount:a,tradeType:n,...m}),o=A(S.details),l=$(k(o.currencyIn)),s=$(k(o.currencyOut)),C=U(A(o.currencyOut).minimumAmount);F(T(o.sender)===g&&T(o.recipient)===c&&l.token.chainId===i&&l.token.address===h&&(n==="EXACT_INPUT"?l.amount===a:s.amount===a)&&s.token.chainId===e&&s.token.address===b&&BigInt(C)<=BigInt(s.amount));let H=Object.fromEntries(Object.entries(A(S.fees)).map(([E,p])=>[E,$(k(p))])),R=typeof o.timeEstimate=="number"&&Number.isFinite(o.timeEstimate)&&o.timeEstimate>=0?o.timeEstimate:void 0,v=M(S.fees),X=e===y,x=X?"relay_bridge_in":"relay_bridge_out",q=n==="EXACT_INPUT"&&Object.keys(m).length===0&&i!==e&&(!X||D(i)!==void 0);return{executable:!1,nextAction:q?x:void 0,originChainId:i,destinationChainId:e,recipient:c,tradeType:n,amountIn:l,amountOut:s,minAmountOut:{token:s.token,amount:C},fees:H,...v,slippage:{source:"provider",minimumAmount:C},...R===void 0?{}:{timeEstimateSeconds:R},summary:`${v.feeDisclosure} Read-only Relay estimate: ${l.amount} base units of ${l.token.symbol} (${l.token.decimals} decimals) on chain ${i} for about ${s.amount}, minimum ${C}, base units of ${s.token.symbol} (${s.token.decimals} decimals) on chain ${e} for ${c}. Slippage: selected by Relay; Oak sent no slippage setting. The returned minimum above is the quote floor. Relay fees are already deducted from the output; origin gas is separate. Nothing was built or signed, and this estimate cannot be executed. ${q?`To bridge, call ${x}; it fetches a fresh quote and shows its own preview for human confirmation.`:"This estimate shape has no matching Oak execution path. No action will preserve these trade type or routing options."}`}}async function Z(t){let r=t.chainId===void 0?void 0:I(t.chainId),i=B((await N("/chains")).chains).map(A).flatMap(e=>{if(typeof e.id!="number"||!Number.isSafeInteger(e.id)||e.id<=0)return[];if(r!==void 0&&e.id!==r)return[];let h=e.disabled===!1,b=_(e.currency)?e.currency:{},c={chainId:e.id,name:f(e.displayName,"name")??f(e.name,"name")??String(e.id),vmType:f(e.vmType),nativeCurrency:{symbol:f(b.symbol),decimals:typeof b.decimals=="number"?b.decimals:void 0},bridgeIn:e.id!==y&&h&&D(e.id)!==void 0,bridgeOut:e.id!==y&&h&&e.vmType==="evm"};if(r===void 0)return[c];let a=new Map;for(let n of[...Array.isArray(e.featuredTokens)?e.featuredTokens:[],...Array.isArray(e.erc20Currencies)?e.erc20Currencies:[]]){if(!_(n)||typeof n.address!="string"||!new RegExp(w).test(n.address)||typeof n.decimals!="number"||!Number.isInteger(n.decimals)||n.decimals<0||n.decimals>255)continue;let m=T(n.address);a.has(m)||a.set(m,{address:m,symbol:f(n.symbol)??"unknown",decimals:n.decimals,bridgeable:n.supportsBridging===!0})}return[{...c,currencies:[...a.values()]}]});if(r!==void 0&&!i.length)throw new d(`Relay does not list chain ${r}.`);return{chains:i,summary:`${i.length} Relay chain${i.length===1?"":"s"}. bridgeIn marks origins relay_bridge_in can build from; bridgeOut marks destinations relay_bridge_out can reach. Currency lists are Relay-reported display data; bridgeable false means Relay does not bridge that token. Confirm token addresses before bridging.`}}return{tools:[{name:"relay_quote",inputSchema:{type:"object",additionalProperties:!1,required:["originChainId","destinationChainId","amount"],properties:{originChainId:{type:"integer",minimum:1,description:"Origin chain ID."},destinationChainId:{type:"integer",minimum:1,description:"Destination chain ID."},originCurrency:{type:"string",pattern:w,description:"Origin token address; defaults to the origin chain\u2019s native token."},destinationCurrency:{type:"string",pattern:w,description:"Destination token address; defaults to the destination chain\u2019s native token."},amount:{type:"string",pattern:"^[1-9][0-9]*$",description:'Input token amount for EXACT_INPUT, otherwise output token amount, in base units using that token\u2019s decimals (USDG has 6: "1000000" = 1 USDG).'},recipient:{type:"string",pattern:w,description:"Destination recipient address; defaults to your wallet."},tradeType:{type:"string",enum:["EXACT_INPUT","EXACT_OUTPUT","EXPECTED_OUTPUT"],description:"EXACT_INPUT fixes input; EXACT_OUTPUT fixes output; EXPECTED_OUTPUT targets output."},...Object.fromEntries(["includedSwapSources","excludedSwapSources","includedOriginSwapSources","includedDestinationSwapSources"].map(t=>[t,{type:"array",description:t==="excludedSwapSources"?"Swap sources to exclude.":t==="includedOriginSwapSources"?"Origin swap sources to include.":t==="includedDestinationSwapSources"?"Destination swap sources to include.":"Swap sources to include.",maxItems:100,items:{type:"string",pattern:"^[A-Za-z0-9._ -]{1,128}$"}}]))}},execute:async(t,r)=>{try{return await G(t,r)}catch(g){throw new d(u.plainError(g))}}},{name:"relay_chains",inputSchema:{type:"object",additionalProperties:!1,properties:{chainId:{type:"integer",minimum:1,description:"Filter by chain ID."}}},execute:async t=>{try{return await Z(t)}catch(r){throw new d(u.plainError(r))}}}]}};export{Q as a};