@oakagentkit/core 0.3.4 → 0.3.5

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 (247) hide show
  1. package/build/dist/api/history.js +1 -1
  2. package/build/dist/api/modules/borro/index.js +1 -1
  3. package/build/dist/api/modules/borro/positions.js +1 -1
  4. package/build/dist/api/modules/borro/reader.js +1 -1
  5. package/build/dist/api/modules/chop/actions.d.ts +13 -1
  6. package/build/dist/api/modules/chop/actions.js +1 -1
  7. package/build/dist/api/modules/chop/checks.js +1 -1
  8. package/build/dist/api/modules/chop/copy.d.ts +1 -0
  9. package/build/dist/api/modules/chop/copy.js +1 -1
  10. package/build/dist/api/modules/chop/display.d.ts +36 -0
  11. package/build/dist/api/modules/chop/display.js +1 -0
  12. package/build/dist/api/modules/chop/guard.js +1 -1
  13. package/build/dist/api/modules/chop/index.js +1 -1
  14. package/build/dist/api/modules/chop/pins.d.ts +1 -0
  15. package/build/dist/api/modules/chop/pins.js +1 -1
  16. package/build/dist/api/modules/chop/positions.js +1 -1
  17. package/build/dist/api/modules/chop/reader.d.ts +6 -1
  18. package/build/dist/api/modules/chop/reader.js +1 -1
  19. package/build/dist/api/modules/chop/types.d.ts +7 -0
  20. package/build/dist/api/modules/chop/unfarm.d.ts +16 -0
  21. package/build/dist/api/modules/chop/unfarm.js +1 -0
  22. package/build/dist/api/modules/clanker/index.js +1 -1
  23. package/build/dist/api/modules/earn/index.js +1 -1
  24. package/build/dist/api/modules/erc8004/index.js +1 -1
  25. package/build/dist/api/modules/factor/actions.js +1 -1
  26. package/build/dist/api/modules/factor/api.js +1 -1
  27. package/build/dist/api/modules/factor/checks.js +1 -1
  28. package/build/dist/api/modules/factor/copy.d.ts +11 -11
  29. package/build/dist/api/modules/factor/copy.js +1 -1
  30. package/build/dist/api/modules/factor/guard.js +1 -1
  31. package/build/dist/api/modules/factor/index.js +1 -1
  32. package/build/dist/api/modules/factor/reader.js +1 -1
  33. package/build/dist/api/modules/fobo/client.js +1 -1
  34. package/build/dist/api/modules/fobo/index.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/builder-feed.js +1 -1
  38. package/build/dist/api/modules/heyresearch/index.js +1 -1
  39. package/build/dist/api/modules/heyresearch/public-reads.js +1 -1
  40. package/build/dist/api/modules/heyresearch/scan.js +1 -1
  41. package/build/dist/api/modules/heyresearch/token-facts.js +1 -1
  42. package/build/dist/api/modules/hoodlock/airdrop.js +1 -1
  43. package/build/dist/api/modules/hoodlock/fee.js +1 -1
  44. package/build/dist/api/modules/hoodlock/guard.js +1 -1
  45. package/build/dist/api/modules/hoodlock/index.js +1 -1
  46. package/build/dist/api/modules/hoodlock/lifecycle.js +1 -1
  47. package/build/dist/api/modules/hoodlock/locks-burn.js +1 -1
  48. package/build/dist/api/modules/hoodlock/public.js +1 -1
  49. package/build/dist/api/modules/hookr/actions.js +1 -1
  50. package/build/dist/api/modules/hookr/create-cancel.js +1 -1
  51. package/build/dist/api/modules/hookr/discovery.js +1 -1
  52. package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
  53. package/build/dist/api/modules/hookr/index.js +1 -1
  54. package/build/dist/api/modules/hookr/launch-receipt.js +1 -1
  55. package/build/dist/api/modules/hookr/launch.js +1 -1
  56. package/build/dist/api/modules/hookr/liquidity.js +1 -1
  57. package/build/dist/api/modules/hookr/lp-positions.js +1 -1
  58. package/build/dist/api/modules/hookr/lp-reads.js +1 -1
  59. package/build/dist/api/modules/hookr/lp-receipt.js +1 -1
  60. package/build/dist/api/modules/hookr/lp-state.js +1 -1
  61. package/build/dist/api/modules/hookr/public-reads.js +1 -1
  62. package/build/dist/api/modules/hookr/relay.js +1 -1
  63. package/build/dist/api/modules/layerbank/actions.js +1 -1
  64. package/build/dist/api/modules/layerbank/index.js +1 -1
  65. package/build/dist/api/modules/layerbank/reader.js +1 -1
  66. package/build/dist/api/modules/longbow/administration.js +1 -1
  67. package/build/dist/api/modules/longbow/fixed.js +1 -1
  68. package/build/dist/api/modules/longbow/index.js +1 -1
  69. package/build/dist/api/modules/meridian/index.js +1 -1
  70. package/build/dist/api/modules/merkl/discovery.js +1 -1
  71. package/build/dist/api/modules/merkl/index.js +1 -1
  72. package/build/dist/api/modules/merkl/manage.js +1 -1
  73. package/build/dist/api/modules/morpho/bundles.js +1 -1
  74. package/build/dist/api/modules/morpho/in-kind.js +1 -1
  75. package/build/dist/api/modules/morpho/index.js +1 -1
  76. package/build/dist/api/modules/morpho/local-guard.js +1 -1
  77. package/build/dist/api/modules/morpho/midnight.js +1 -1
  78. package/build/dist/api/modules/morpho/protocol.js +1 -1
  79. package/build/dist/api/modules/morpho/vault-tools.js +1 -1
  80. package/build/dist/api/modules/netnet/card-plan.js +1 -1
  81. package/build/dist/api/modules/netnet/card-read.js +1 -1
  82. package/build/dist/api/modules/netnet/card-recovery.js +1 -1
  83. package/build/dist/api/modules/netnet/desk-action.js +1 -1
  84. package/build/dist/api/modules/netnet/financial.js +1 -1
  85. package/build/dist/api/modules/netnet/index.js +1 -1
  86. package/build/dist/api/modules/pendle/index.js +1 -1
  87. package/build/dist/api/modules/pendle/reader.js +1 -1
  88. package/build/dist/api/modules/pendle/trade.js +1 -1
  89. package/build/dist/api/modules/pons/index.js +1 -1
  90. package/build/dist/api/modules/priors/coverage.js +1 -1
  91. package/build/dist/api/modules/priors/discovery.js +1 -1
  92. package/build/dist/api/modules/priors/index.js +1 -1
  93. package/build/dist/api/modules/priors/integration.js +1 -1
  94. package/build/dist/api/modules/priors/stock-swap.js +1 -1
  95. package/build/dist/api/modules/raeto/index.js +1 -1
  96. package/build/dist/api/modules/relay/index.js +1 -1
  97. package/build/dist/api/modules/relay/outbound-status.js +1 -1
  98. package/build/dist/api/modules/spark/index.js +1 -1
  99. package/build/dist/api/modules/steakhouse/index.js +1 -1
  100. package/build/dist/api/modules/steakhouse/local-guard.js +1 -1
  101. package/build/dist/api/modules/steakhouse/management.js +1 -1
  102. package/build/dist/api/modules/steakhouse/v2-exit.js +1 -1
  103. package/build/dist/api/modules/tickerspring/basket-routes.js +1 -1
  104. package/build/dist/api/modules/tickerspring/contract-reads.js +1 -1
  105. package/build/dist/api/modules/tickerspring/exit-preview.js +1 -1
  106. package/build/dist/api/modules/tickerspring/guards.js +1 -1
  107. package/build/dist/api/modules/tickerspring/index.js +1 -1
  108. package/build/dist/api/modules/tickerspring/journeys.js +1 -1
  109. package/build/dist/api/modules/tickerspring/ladder.js +1 -1
  110. package/build/dist/api/modules/tickerspring/maker.js +1 -1
  111. package/build/dist/api/modules/tickerspring/order-accounting.js +1 -1
  112. package/build/dist/api/modules/tickerspring/research.js +1 -1
  113. package/build/dist/api/modules/tickerspring/strategies.js +1 -1
  114. package/build/dist/api/modules/uniswap/auction-create.js +1 -1
  115. package/build/dist/api/modules/uniswap/auction.js +1 -1
  116. package/build/dist/api/modules/uniswap/batch.js +1 -1
  117. package/build/dist/api/modules/uniswap/common.js +1 -1
  118. package/build/dist/api/modules/uniswap/fees.js +1 -1
  119. package/build/dist/api/modules/uniswap/index.js +1 -1
  120. package/build/dist/api/modules/uniswap/local-guard.js +1 -1
  121. package/build/dist/api/modules/uniswap/oracle.js +1 -1
  122. package/build/dist/api/modules/uniswap/pool-math.js +1 -1
  123. package/build/dist/api/modules/uniswap/pools.js +1 -1
  124. package/build/dist/api/modules/uniswap/position.js +1 -1
  125. package/build/dist/api/modules/uniswap/protocol.js +1 -1
  126. package/build/dist/api/modules/uniswap/quote-guard.js +1 -1
  127. package/build/dist/api/modules/uniswap/token-jar.js +1 -1
  128. package/build/dist/api/modules/uniswap/trade-batch.js +1 -1
  129. package/build/dist/api/modules/uniswap/trade.js +1 -1
  130. package/build/dist/api/modules/uniswap/v2.js +1 -1
  131. package/build/dist/api/modules/uniswap/v3.js +1 -1
  132. package/build/dist/api/modules/uniswap/v4.js +1 -1
  133. package/build/dist/api/modules/uniswap/wrap.js +1 -1
  134. package/build/dist/api/modules/upoch/index.js +1 -1
  135. package/build/dist/api/modules/upoch/reads.js +1 -1
  136. package/build/dist/api/modules/wormhole/index.js +1 -1
  137. package/build/dist/api/prices.d.ts +5 -0
  138. package/build/dist/api/prices.js +1 -1
  139. package/build/dist/api/send.js +1 -1
  140. package/build/dist/api/signing-registry.js +1 -1
  141. package/build/dist/api/tokens.d.ts +1 -0
  142. package/build/dist/api/tokens.js +1 -1
  143. package/build/dist/api/usd-estimate.d.ts +2 -0
  144. package/build/dist/api/usd-estimate.js +1 -1
  145. package/build/dist/chunks/{UBVE2U6X.js → 2FOI2625.js} +1 -1
  146. package/build/dist/chunks/{5OTQCE2E.js → 2I7XHRTI.js} +1 -1
  147. package/build/dist/chunks/{SGHSCK22.js → 2PS4GCOZ.js} +1 -1
  148. package/build/dist/chunks/3BQ5XHDJ.js +1 -0
  149. package/build/dist/chunks/{PRBIC3UK.js → 3YH5B5NQ.js} +1 -1
  150. package/build/dist/chunks/{RUSXMQSJ.js → 4HQEJHCD.js} +1 -1
  151. package/build/dist/chunks/{ZFRTBBIW.js → 4IOHSX3Z.js} +1 -1
  152. package/build/dist/chunks/5H7NVE6O.js +1 -0
  153. package/build/dist/chunks/{JJGZ7W3V.js → 6AS3TGOX.js} +1 -1
  154. package/build/dist/chunks/{RK3PPFRX.js → 6CKCZJ3F.js} +1 -1
  155. package/build/dist/chunks/{HU2JXDLH.js → 6LVHN33V.js} +1 -1
  156. package/build/dist/chunks/7OOCAZBE.js +1 -0
  157. package/build/dist/chunks/{O3XWE4FO.js → 7TRO6MBQ.js} +1 -1
  158. package/build/dist/chunks/{WX7OYCNS.js → A4FLWHLP.js} +1 -1
  159. package/build/dist/chunks/{FP7DHVK2.js → A4K5GXVO.js} +1 -1
  160. package/build/dist/chunks/{AOX6DKYU.js → AL6UXNGH.js} +1 -1
  161. package/build/dist/chunks/{FQTO7VJG.js → C57DITTF.js} +1 -1
  162. package/build/dist/chunks/{ZTX4WT62.js → CFPJDLTZ.js} +1 -1
  163. package/build/dist/chunks/{SRHVSNPX.js → CNDIAF3P.js} +1 -1
  164. package/build/dist/chunks/{LEHBRAZX.js → CW37EGPL.js} +1 -1
  165. package/build/dist/chunks/{PQG3ULRT.js → DBOGRUPS.js} +1 -1
  166. package/build/dist/chunks/{T3QEN3S6.js → E47UYYK4.js} +1 -1
  167. package/build/dist/chunks/EPOIAXCV.js +3 -0
  168. package/build/dist/chunks/{DWQJ7NSX.js → FCVH4FYH.js} +1 -1
  169. package/build/dist/chunks/{V6EVQWAL.js → FHB7QYJO.js} +1 -1
  170. package/build/dist/chunks/FRT6AC6M.js +1 -0
  171. package/build/dist/chunks/{Z5YI6KLN.js → FRVCSDKU.js} +1 -1
  172. package/build/dist/chunks/{EIE2U4OX.js → G5AMH4IP.js} +1 -1
  173. package/build/dist/chunks/{EQEMI54U.js → GDUKZYE2.js} +1 -1
  174. package/build/dist/chunks/{GNOHIL4Q.js → GKUPC4DO.js} +1 -1
  175. package/build/dist/chunks/{K7HTDKAT.js → GMMTHTCP.js} +1 -1
  176. package/build/dist/chunks/{XHFAF5PZ.js → HDBZZOHJ.js} +1 -1
  177. package/build/dist/chunks/{Q4HSQL65.js → HPS4KOU4.js} +1 -1
  178. package/build/dist/chunks/IZP3EKKS.js +1 -0
  179. package/build/dist/chunks/{P6MPKIU2.js → J7OZLXSG.js} +1 -1
  180. package/build/dist/chunks/{PXUML7HJ.js → JDHPMS7X.js} +1 -1
  181. package/build/dist/chunks/{MOZBDCVV.js → JJSCDDQO.js} +1 -1
  182. package/build/dist/chunks/{EFESPGA2.js → KCZUJ57H.js} +1 -1
  183. package/build/dist/chunks/{2ILYVUFA.js → KKTOBXIT.js} +1 -1
  184. package/build/dist/chunks/{L6CVMDWQ.js → KO7ANIKY.js} +1 -1
  185. package/build/dist/chunks/{2T6O77QZ.js → LKUZAJPZ.js} +1 -1
  186. package/build/dist/chunks/{5GQJVKVY.js → LZM3DO5Q.js} +1 -1
  187. package/build/dist/chunks/M6JNGU4E.js +1 -0
  188. package/build/dist/chunks/{MEB727X5.js → M7OVMIIE.js} +1 -1
  189. package/build/dist/chunks/{RKM62HC5.js → MJGEGNDU.js} +1 -1
  190. package/build/dist/chunks/{SYERFEJ4.js → MQXSCNUL.js} +1 -1
  191. package/build/dist/chunks/N624NR7Y.js +1 -0
  192. package/build/dist/chunks/{X3YEDVRN.js → N65J3L2H.js} +1 -1
  193. package/build/dist/chunks/{2TX7HP6M.js → N742W5KX.js} +1 -1
  194. package/build/dist/chunks/{365B4YEV.js → NIWAVMDR.js} +1 -1
  195. package/build/dist/chunks/O2QBSINK.js +1 -0
  196. package/build/dist/chunks/{FA3GBXQP.js → O4P5IQCP.js} +1 -1
  197. package/build/dist/chunks/{HUKDISRE.js → OB3YMTDI.js} +1 -1
  198. package/build/dist/chunks/{WXZ4LAKO.js → PV7FEVBD.js} +1 -1
  199. package/build/dist/chunks/{4M6XBG6X.js → Q3Q3YHEX.js} +1 -1
  200. package/build/dist/chunks/QA6Z2CYP.js +2 -0
  201. package/build/dist/chunks/{BDLV42SD.js → QBNASL3T.js} +1 -1
  202. package/build/dist/chunks/{AHUCYDBC.js → QKIQ7ZKD.js} +1 -1
  203. package/build/dist/chunks/{7FYM7FJA.js → QMIH6HXH.js} +1 -1
  204. package/build/dist/chunks/{2QP6WGKZ.js → QQD4PV64.js} +1 -1
  205. package/build/dist/chunks/{KNBNKG7P.js → R66NSNNQ.js} +1 -1
  206. package/build/dist/chunks/{VQJXQLFW.js → RP5VCG54.js} +1 -1
  207. package/build/dist/chunks/{OKXKDDBX.js → RUHNLNVX.js} +1 -1
  208. package/build/dist/chunks/{VKNKVUAA.js → S37D7HOK.js} +1 -1
  209. package/build/dist/chunks/S47M3IPR.js +1 -0
  210. package/build/dist/chunks/S65KXMZ7.js +3 -0
  211. package/build/dist/chunks/{NYHKIXJR.js → SX5YNFHG.js} +1 -1
  212. package/build/dist/chunks/{MHONMLF6.js → TGXEKBLV.js} +1 -1
  213. package/build/dist/chunks/{VHK5AYC2.js → TJU644I7.js} +1 -1
  214. package/build/dist/chunks/{O56EZB5Y.js → TOIKOIY6.js} +1 -1
  215. package/build/dist/chunks/{YR44GQG4.js → TZ7S5KRB.js} +1 -1
  216. package/build/dist/chunks/UEOS6SHR.js +1 -0
  217. package/build/dist/chunks/{USZCTSPI.js → USGMGKAG.js} +1 -1
  218. package/build/dist/chunks/{W5FM2OVB.js → UUF4Z6K6.js} +1 -1
  219. package/build/dist/chunks/{PMFR47H3.js → VREGY7E6.js} +1 -1
  220. package/build/dist/chunks/{2YYKQGJZ.js → W7BFM6CK.js} +1 -1
  221. package/build/dist/chunks/{3D7FXI6G.js → WQ2XTDHO.js} +1 -1
  222. package/build/dist/chunks/WRA3ZC6W.js +1 -0
  223. package/build/dist/chunks/{K3TZYPSV.js → XADHV2DT.js} +1 -1
  224. package/build/dist/chunks/{LVFI74ST.js → XNJ6NDQQ.js} +1 -1
  225. package/build/dist/chunks/{DD47RZFU.js → XTXXWRN2.js} +1 -1
  226. package/build/dist/chunks/{CZ66MYKR.js → XWC6IC5E.js} +1 -1
  227. package/build/dist/chunks/{DMB64UIN.js → YWVPK3DV.js} +1 -1
  228. package/build/dist/chunks/{WNWRF4HE.js → YZHJ4BAP.js} +1 -1
  229. package/build/dist/chunks/{4PB6MSGZ.js → ZKBOPZH5.js} +1 -1
  230. package/build/dist/chunks/{5ZVIAGLX.js → ZQPC54J5.js} +1 -1
  231. package/build/dist/chunks/{HDBDBKEA.js → ZVY7GGSP.js} +1 -1
  232. package/build/dist/chunks/{LQSPWRHN.js → ZX43P4BK.js} +1 -1
  233. package/build/dist/chunks/{PQOWIRKQ.js → ZXFJKW6H.js} +1 -1
  234. package/build/dist/chunks/{N6PHSHBE.js → ZXRIJG6H.js} +1 -1
  235. package/package.json +1 -1
  236. package/build/dist/chunks/3AOTYJPX.js +0 -1
  237. package/build/dist/chunks/4E7FJQLL.js +0 -1
  238. package/build/dist/chunks/4J245N3F.js +0 -1
  239. package/build/dist/chunks/BA66J5YQ.js +0 -1
  240. package/build/dist/chunks/BIY2F6MO.js +0 -1
  241. package/build/dist/chunks/DGCJZ3HO.js +0 -1
  242. package/build/dist/chunks/DHX3Q5RV.js +0 -2
  243. package/build/dist/chunks/EFUACKDK.js +0 -1
  244. package/build/dist/chunks/JW7GLNLB.js +0 -3
  245. package/build/dist/chunks/MIKQWF6Q.js +0 -3
  246. package/build/dist/chunks/P7C3TYI4.js +0 -1
  247. package/build/dist/chunks/ZNX3YVF2.js +0 -1
@@ -1,4 +1,4 @@
1
- import{a as oe}from"./3CCBUYUM.js";import{a as xt,d as It,e as Tt}from"./ZTKT3ZQK.js";import{a as Ge}from"./7MR37STI.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"./4J245N3F.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!) {
1
+ import{a as oe}from"./3CCBUYUM.js";import{a as xt,d as It,e as Tt}from"./ZTKT3ZQK.js";import{a as Ge}from"./7MR37STI.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"./N624NR7Y.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
@@ -0,0 +1 @@
1
+ import{a as be}from"./DCGNVMKG.js";import{c as ye}from"./3PHJUFU2.js";import{a as J}from"./ZX43P4BK.js";import{a as _,b as E}from"./Z7FGEWO2.js";import{a as Q,b as ke}from"./CFPJDLTZ.js";import{a as N}from"./VVAM3EAK.js";import{a as he}from"./P4UQGWCP.js";import{a as R}from"./43LI5NKJ.js";import{b as me,c as fe}from"./SCG5HWMN.js";import{a as de,b as z,c as Y}from"./5HCXZWUH.js";import{q as le,s as P,t as ue}from"./MQ5F2VOK.js";import{b as T,c as U,d as F,e as ie,j as M,k as ce,t as D}from"./TI727O2H.js";import{a as h}from"./XSD5NL7J.js";import{a as w,b as j,c as Z}from"./JXOEJPJ4.js";import{decodeFunctionResult as Ee,encodeFunctionData as Me,erc20Abi as q,getAddress as p,isAddress as V,parseAbi as X}from"viem";var ee="https://api.robinhood.com/rhj/assets",_e={address:_,symbol:"ETH",decimals:18,chainId:T},te={address:p(ce),symbol:"USDG",decimals:ie,chainId:T},ne={address:p(M[4663].tokens.WETH.address),symbol:"WETH",decimals:18,chainId:T},Ce={address:p(M[4663].meridian.CollateralToken_USDe.address),symbol:"USDe",decimals:18,chainId:T},re=[{address:p(Q.chop),symbol:"CHOP",decimals:18,chainId:T},{address:p(Q.oakLog.address),symbol:"chOAK",decimals:18,chainId:T},{address:p(ke),symbol:"schOAK",decimals:18,chainId:T}],K=(e,n)=>re.find(s=>s.chainId===n&&s.address.toLowerCase()===e.toLowerCase());function $(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function H(e,n=T,s={}){let t=Array.isArray(e)?e:$(e)&&Array.isArray(e.assets)?e.assets:void 0;if(!t)throw new h("Official stock asset list response is malformed.");let a=new Map,c=new Map;if(t.length>1e4)throw new h("Official stock asset list exceeds the lookup limit.");for(let o of t){if(!$(o))continue;let r=o;if(typeof r.tokenSymbol!="string"||!r.tokenSymbol.trim()||!Array.isArray(r.deployments))continue;if(r.deployments.length>100)throw new h("Official stock deployment list exceeds the lookup limit.");let d=r.tokenSymbol;if(!/^[A-Za-z0-9.$_-]{1,32}$/.test(d))throw new h(`Invalid official stock ticker ${w(d)}.`);if(r.tokenDecimals!==void 0&&(typeof r.tokenDecimals!="number"||!Number.isInteger(r.tokenDecimals)||r.tokenDecimals<0||r.tokenDecimals>255))throw new h("Official stock asset has invalid token decimals.");let l=typeof r.tokenDecimals=="number"&&Number.isInteger(r.tokenDecimals)&&r.tokenDecimals>=0&&r.tokenDecimals<=255?r.tokenDecimals:18;for(let f of r.deployments){if(!$(f))continue;let y=f;if(y.chainId!==n)continue;if(typeof y.contractAddress!="string"||!V(y.contractAddress,{strict:!1}))throw new h("Official stock deployment has an invalid contract address.");let b=p(y.contractAddress),k=b.toLowerCase(),S=d.toUpperCase(),u=c.get(S);if(!s.allowAmbiguousSymbols&&u&&u!==k)throw new h(`Ambiguous official stock ticker ${w(d)} across multiple addresses.`);let i=a.get(k);if(i&&(i.symbol!==d||i.decimals!==l))throw new h(`Conflicting official stock identity at ${b}.`);c.set(S,k),a.set(k,{address:b,symbol:d,decimals:l,chainId:n,...s.includeNames&&typeof r.tokenName=="string"&&r.tokenName.trim()?{name:r.tokenName.trim()}:{}})}}return[...a.values()]}function Be(e,n){if(typeof e.address!="string"||!V(e.address,{strict:!1}))return!1;let s=e.chainId??T,t=e.address.toLowerCase();return n.some(a=>a.chainId===s&&a.address.toLowerCase()===t&&a.symbol===e.symbol)}function G(e,n){R(e.address);let s=e.chainId??T,t=p(e.address),a=t.toLowerCase(),c=C(e.symbol),o=n.find(d=>d.chainId===s&&d.address.toLowerCase()===a),r=n.find(d=>d.chainId===s&&C(d.symbol)===c);if(o){if(e.symbol!==o.symbol)throw new h(`Token at ${t} does not match official stock ticker ${w(o.symbol)} (received ${w(e.symbol)}).`);if(e.decimals!==void 0&&e.decimals!==o.decimals)throw new h(`Token ${w(o.symbol)} at ${t} does not match official decimals ${o.decimals}.`);return o}if(r)throw new h(`Token symbol ${w(e.symbol)} at ${t} does not match the official stock contract address ${r.address}.`);return{address:t,symbol:e.symbol.trim(),decimals:e.decimals??18,chainId:s}}var Ue=["AAOI","AAPL","ABCL","ADBE","AEHR","AEIS","ALAB","AMAT","AMBA","AMC","AMD","AMKR","AMZN","ANET","APLD","APP","ASML","ASTS","AUR","AVAV","AVGO","AXON","AXTI","BA","BABA","BB","BE","BMNR","BND","BULL","CBRS","CCL","CEG","CELH","CIEN","CLOV","CLS","CLSK","COHR","COIN","COST","CRCL","CRDO","CRM","CRWD","CRWV","CSCO","CTSH","CVNA","DDOG","DELL","DIS","DJT","DOCN","ELF","EWT","EWY","F","FICO","FIG","FISV","FIX","FLNC","FLY","FTNT","FUTU","GDX","GE","GEV","GLD","GLW","GLXY","GME","GOOGL","HII","HIMS","HPE","HWM","IBM","IBRX","INDA","INFQ","INOD","INTC","INTU","IONQ","IREN","JBL","JNJ","JOBY","JPM","KLAC","KSS","KTOS","LHX","LITE","LLY","LMT","LRCX","LULU","LUNR","MCD","MDB","META","MOD","MPWR","MRNA","MRVL","MSFT","MSTR","MTSI","MU","MXL","NAVN","NBIS","NET","NFLX","NNE","NOW","NU","NVDA","NVTS","OKLO","ON","ONTO","ORCL","OUST","P","PANW","PATH","PENG","PFE","PL","PLTR","POET","POWL","PR","PWR","PYPL","QBTS","QCOM","QQQ","QUBT","RBLX","RCAT","RDDT","RDW","RGTI","RIVN","RKLB","RUN","SATS","SCHD","SGOV","SHOP","SHY","SIMO","SKHY","SLS","SLV","SMCI","SMH","SMR","SNAP","SNDK","SNOW","SOFI","SOUN","SOXX","SPCX","SPMO","SPY","TE","TEAM","TEM","TER","TSEM","TSLA","TSM","TTD","TTWO","UBER","UMC","UNH","UPS","USAR","USO","V","VICR","VRT","VSAT","VST","VTI","WDAY","WDC","WULF","WYFI","XLK","XNDU","XOM","ZETA","ZM","ZS"],se=new WeakMap,pe=new WeakMap,ve=3e4,Te=Object.freeze([]),x;function dt(){if(!x)return Te;let e=Date.now()-x.started;return e>=0&&e<ve?x.tokens:Te}var oe=new WeakMap;function W(e,n){return(oe.get(e)??P)(n)}async function Ie(e){let n=e?.http??me(),s=e?.url??ee,t=e?.chainId??T,a=Y(n),c=pe.get(a);c||(c=new de(ve),pe.set(a,c));let{value:o,started:r}=await W(n,()=>c.read(`${t}:${s}`,async()=>{let l=await P(y=>fe(a,s,{method:"GET",signal:y},b=>$(b)||Array.isArray(b))),f=H(l,t,{allowAmbiguousSymbols:!0});if(t===T&&f.length===0)throw new h("Official stock asset list has no mainnet deployments; retry when the list is available.");return l})),d=H(o,t,e);if(t===T&&s===ee&&(!x||r>=x.started||Date.now()<x.started)&&(x={started:r,tokens:Object.freeze(H(o,t,{allowAmbiguousSymbols:!0}).map(l=>Object.freeze(l)))}),t===T){let l=se.get(a);l||(l=new Set,se.set(a,l));for(let f of d)l.add(C(f.symbol))}return d}var Fe=X(["function aggregate3((address target, bool allowFailure, bytes callData)[] calls) payable returns ((bool success, bytes returnData)[] returnData)"]);function we(e){let n=e,s=new Set;for(;n&&typeof n=="object"&&!s.has(n)&&s.size<10;){s.add(n);let t=n;if(t.name==="ContractFunctionZeroDataError"||t.name==="AbiDecodingZeroDataError")return!0;let a=`${typeof t.shortMessage=="string"?t.shortMessage:""} ${typeof t.message=="string"?t.message:""}`;if(/returned no data \("0x"\)|Cannot decode zero data/i.test(a))return!0;n=t.cause}return!1}function Ke(e){return e instanceof h?/RPC endpoint|too many requests|malformed JSON/i.test(e.message):e instanceof Error?/fetch failed|network|ECONNREFUSED|ETIMEDOUT|HTTP \d{3}|rate limit|too many requests/i.test(e.message):!1}async function $e(e,n,s){if(typeof e.getCode=="function")try{let t=await e.getCode({address:n});return!t||t==="0x"}catch{return we(s)}return we(s)}async function ge(e,n,s){if(n.length===0)return[];let t=await Promise.allSettled(n.map(a=>e.readContract({address:a.address,abi:q,functionName:"balanceOf",args:[s]})));if(t.every(a=>a.status==="rejected")&&t[0]?.status==="rejected"&&Ke(t[0].reason))throw t[0].reason;return t.map(a=>{if(a.status!=="fulfilled"||a.value===void 0||a.value===null)return{ok:!1};try{let c=typeof a.value=="bigint"?a.value:BigInt(a.value);return c>=0n?{ok:!0,amount:c}:{ok:!1}}catch{return{ok:!1}}})}async function Le(e,n,s,t){if(s.length===0)return[];let a=le(n,e);if(!a)return ge(e,s,t);let c=s.map(r=>({target:r.address,allowFailure:!0,callData:Me({abi:q,functionName:"balanceOf",args:[t]})})),o;try{o=await e.readContract({address:a,abi:Fe,functionName:"aggregate3",args:[c]})}catch(r){if(await $e(e,a,r))return ge(e,s,t);throw r}if(!Array.isArray(o)||o.length!==s.length)throw new h("Multicall3 aggregate3 returned an invalid result list.");return o.map(r=>{let d=r,l=Array.isArray(d)?d[0]:d?.success,f=Array.isArray(d)?d[1]:d?.returnData;if(!l||typeof f!="string"||f==="0x")return{ok:!1};try{let y=Ee({abi:q,functionName:"balanceOf",data:f}),b=typeof y=="bigint"?y:BigInt(y);return b>=0n?{ok:!0,amount:b}:{ok:!1}}catch{return{ok:!1}}})}async function lt(e,n={}){R(e);let s=p(e),t=n.chainId??T,a=n.client??ue(n.rpcUrl,t),c=[];if(n.stockTokens?c=[...n.stockTokens]:n.stockAssetsPayload!==void 0?c=H(n.stockAssetsPayload,t):n.includeStockTokens!==!1&&t!==U&&(c=await Ie({http:n.http,url:n.stockAssetsUrl,chainId:t})),n.tokens)for(let i of n.tokens)G(i,c);let o=t===T?[te,ne,Ce,...n.oakTokenAddress||process.env.OAK_TOKEN_ADDRESS?[{address:p(n.oakTokenAddress??process.env.OAK_TOKEN_ADDRESS),symbol:"OAK",decimals:F,chainId:t}]:[]]:t===U?[{...te,address:p(D.testnet.usdg),chainId:t},{...ne,address:p(D.testnet.weth),chainId:t},...n.oakTokenAddress?[{address:p(n.oakTokenAddress),symbol:"OAK",decimals:F,chainId:t}]:[]]:[],r=t===T&&n.includePoolTokens!==!1?[...re,...he.vaults.flatMap(i=>[{address:p(i.tokenAddress),symbol:p(i.tokenAddress),decimals:i.tokenDecimals,chainId:t},{address:p(i.earnContractAddress),symbol:p(i.earnContractAddress),decimals:18,chainId:t}])]:[],d=new Set(r.map(i=>i.address.toLowerCase())),l=[],f=new Set;for(let i of[...o,...c,...n.tokens??[],...r]){if(i.chainId!==t||E(i.address)===_)continue;let m=K(i.address,t)??G(i,c),A=m.address.toLowerCase();f.has(A)||(f.add(A),l.push(m))}let[y,b]=await Promise.all([a.getBalance({address:s}),Le(a,t,l,s)]),k=[],S={address:_,symbol:"ETH",decimals:18,chainId:t};(y>0n||n.includeZero)&&k.push({token:S,amount:y.toString()});for(let i=0;i<l.length;i++){let m=l[i],A=o.some(I=>v(I.address,m.address))||c.some(I=>v(I.address,m.address))||K(m.address,t)?m.symbol:w(m.symbol),g=b[i]??{ok:!1};if(!g.ok){k.push({token:{address:m.address,symbol:A,decimals:m.decimals,chainId:m.chainId},amount:"unavailable"});continue}let O=g.amount;if(O>0n&&d.has(m.address.toLowerCase())&&!K(m.address,t))try{let[I,L]=await Promise.all([N(a,t,m.address,"symbol"),N(a,t,m.address,"decimals")]);A=w(I),m.decimals=L}catch{}(O>0n||n.includeZero)&&k.push({token:{address:m.address,symbol:A,decimals:m.decimals,chainId:m.chainId},amount:O.toString()})}let u="Outside token discovery is disabled; no receipt time window was scanned. The local journal can include older receipts.";if(n.includeReceivedTokens===!0){let i=await He(s,{client:a});if(u=i.notice,!i.incomplete)try{let m=i.addresses.filter(g=>!f.has(g.toLowerCase())),A=await We(s,m,{client:a,chainId:t});k.push(...A.map(g=>({...g,verified:!1,note:"Received from outside Oak's lists; not verified."})))}catch{u+=" Discovery is incomplete: outside balances or token metadata are unavailable; known balances are retained."}}return k.length||k.push({token:S,amount:y.toString()}),k[0]={...k[0],discoveryNotice:u},k}async function He(e,n){R(e);let s,t,a="the last 10,000 blocks (approximately 17 minutes at 100 ms per block; UTC boundaries unavailable)",c=()=>`Outside token discovery covers only ERC-20 receipts in ${a}; older holdings may be missing. The local journal can include older receipts.`;try{if(t=await P(()=>n.client.getBlockNumber({cacheTime:0}),3e3),s=t>9999n?t-9999n:0n,typeof n.client.getBlock=="function")try{let l=await Promise.all([s,t].map(f=>P(()=>n.client.getBlock({blockNumber:f}),3e3)));a=`blocks ${s}\u2013${t}, from ${new Date(Number(l[0].timestamp)*1e3).toISOString()} to ${new Date(Number(l[1].timestamp)*1e3).toISOString()} (UTC)`}catch{}let o=X(["event Transfer(address indexed from,address indexed to,uint256 value)"])[0],r=await P(()=>n.client.getLogs({event:o,args:{to:p(e)},fromBlock:s,toBlock:t,strict:!0}),3e3),d=[...new Set(r.filter(l=>!l.removed&&typeof l.args.value=="bigint"&&l.args.value>0n).map(l=>p(l.address)))];return d.length>200?{addresses:[],fromBlock:s,toBlock:t,incomplete:!0,notice:`${c()} Discovery is incomplete: the 200-contract limit was exceeded; known balances are retained.`}:{addresses:d,fromBlock:s,toBlock:t,incomplete:!1,notice:c()}}catch{return{addresses:[],fromBlock:s,toBlock:t,incomplete:!0,notice:`${c()} Discovery is incomplete: RPC receipt reads are unavailable; known balances are retained. Retry balances when RPC logs are available.`}}}async function We(e,n,s){if(R(e),n.length>1e4)throw new h("Journal token discovery exceeds the balance lookup limit.");let t=[...new Set(n.map(o=>(R(o),p(o))))].filter(o=>E(o)!==_).map(o=>({address:o,symbol:o,decimals:0,chainId:s.chainId})),a=await Le(s.client,s.chainId,t,p(e)),c=t.flatMap((o,r)=>{let d=a[r];return d.ok&&d.amount===0n?[]:[{token:o,amount:d.ok?d.amount.toString():"unavailable"}]});return Promise.all(c.map(async({token:o,amount:r})=>{let d=K(o.address,s.chainId);if(d)return{token:{...d},amount:r};let[l,f]=await Promise.all([N(s.client,s.chainId,o.address,"symbol"),N(s.client,s.chainId,o.address,"decimals").catch(()=>{throw new h(`Token decimals are unavailable for journal-received token ${o.address}; retry balances when RPC metadata is available.`)})]);return{token:{...o,symbol:w(l),decimals:f},amount:r}}))}var v=(e,n)=>e.toLowerCase()===n.toLowerCase(),C=e=>Z(e.normalize("NFKC")).toLowerCase().replace(/[^\p{L}\p{N}]/gu,""),Ae=e=>Z(e.normalize("NFKC")).toLowerCase().match(/[\p{L}\p{N}]+/gu)?.join(" ")??"";function Ne(e){let n=e.context.network??"mainnet",{chainId:s,usdg:t,weth:a}=D[n],c=(o,r,d)=>({...o,address:E(p(o.address)),name:r,kind:d,verified:!0,source:"Oak fixed addresses",warnings:[]});return[c({..._e,chainId:s},"Ether","native"),c({...te,address:t,chainId:s},"Global Dollar","stablecoin"),c({...ne,address:a,chainId:s},"Wrapped Ether","wrapped"),...n==="mainnet"?[c(Ce,"USDe","stablecoin")]:[],...n==="mainnet"?re.map(o=>c(o,o.symbol==="CHOP"?"Chop":o.symbol==="chOAK"?"Chop OAK log":"Chop OAK staked LP",o.symbol==="CHOP"?"erc20":"wrapped")):[],...e.oakTokenAddress?[c({address:e.oakTokenAddress,symbol:"OAK",decimals:F,chainId:s},"Oak","oak")]:[]]}async function De(e){if(e.context.network==="testnet")return[];let n=e.officialStockTokens??await Ie({http:e.context.http,includeNames:!0,allowAmbiguousSymbols:!0});return n.filter(s=>Be(s,n)).map(s=>({...s,name:s.name??s.symbol,kind:"official_stock",verified:!0,source:ee,warnings:[],identityNote:"Official Robinhood stock token: this address matches Robinhood's published list. The quoted name is text from that list."}))}async function ae(e,n,s=!0){let{chainId:t}=D[n.context.network??"mainnet"],a=n.context.clientFor(t);if(await a.getChainId()!==t)throw new h(`Token lookup requires Robinhood Chain ${t}.`);let[c,o,r]=await Promise.all([W(a,()=>N(a,t,e,"name",n.blockNumber)).catch(d=>{if(s)throw d;return""}),W(a,()=>N(a,t,e,"symbol",n.blockNumber)),W(a,()=>N(a,t,e,"decimals",n.blockNumber))]);if(typeof c!="string"||s&&!c.trim()||typeof o!="string"||!o.trim()||!Number.isInteger(r)||r<0||r>255)throw new h("The contract returned invalid token metadata.");return{address:p(e),name:c||o,symbol:o,decimals:r,chainId:t}}async function Se(e,n){let s=await n.context.clientFor(T).readContract({address:M[T].clanker.factory.address,abi:X(["function tokenDeploymentInfo(address) view returns ((address,address,address,address[]))"]),functionName:"tokenDeploymentInfo",args:[e]});return Array.isArray(s)&&s.length===4&&typeof s[0]=="string"&&v(s[0],e)}async function Ge(e,n){let s=n.context.clientFor(T),t=M[T].poolsTrade,a=[t.instantLaunchStrategyFeesOn.address,t.instantLaunchStrategyFeesOff.address],c=X(["event TokenLaunched(bytes32 indexed poolId,address indexed token,address indexed feeSplitter,(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey)"])[0],o=await s.getBlockNumber(),r=new Set,d=0,l=0;for(let f=63127652n;f<=o;f+=10000000n){if(++d>Pe)throw new h("Token origin scan limit reached.");let y=f+9999999n>o?o:f+9999999n,b=await s.getLogs({address:a,event:c,args:{token:e},fromBlock:f,toBlock:y,strict:!0});for(let k of b){if(k.removed||!a.some(u=>v(u,k.address))||!k.args.token||!v(k.args.token,e)||!k.transactionHash||r.has(k.transactionHash))continue;if(r.add(k.transactionHash),++l>20)throw new h("Token origin receipt limit reached.");let S=await s.getTransactionReceipt({hash:k.transactionHash});if(be(S).some(u=>v(u.token,e)))return p(S.from)}}}var Pe=5,Ve=100,Xe=500,je=3e4;function xe(e){let n=Date.now()+je,s=0,t=new Map,a=o=>{let r=n-Date.now();if(r<=0)throw new h("Token lookup time budget reached; results are partial.");return P(o,Math.min(1e4,r))},c=z((o,r)=>a(async d=>{let l=await e.context.http(o,{...r,signal:d});return new Proxy(l,{get(f,y){if(y==="json")return()=>a(()=>f.json());let b=Reflect.get(f,y,f);return typeof b=="function"?b.bind(f):b}})}),e.context.http);return oe.set(c,a),{...e,context:{...e.context,http:c,clientFor:o=>{if(!t.has(o)){let r=e.context.clientFor(o),d=l=>{if(++s>Xe)throw new h("Token lookup RPC budget reached; results are partial.");return a(l)};t.set(o,z(new Proxy(r,{get(l,f){let y=Reflect.get(l,f);return typeof y!="function"?y:(...b)=>d(()=>y.apply(l,b))}}),r)),oe.set(t.get(o),d)}return t.get(o)}}}}function Oe(e){return e.source==="Oak fixed addresses"?e:{...e,symbol:w(e.symbol),name:w(e.name)}}async function ut(e,n){if(n=xe(n),typeof e!="string"||e.length>256||!C(e))throw new h("Provide a token name, symbol or address to find_token.");let s=C(e),t=V(e.trim(),{strict:!1})?E(p(e.trim())):void 0,{chainId:a}=D[n.context.network??"mainnet"],c=[],o=Ne(n),r=!1;try{o.push(...await De(n))}catch{r=!0,c.push("The official stock list is unavailable; results are partial and stock identities and lookalikes could not be checked.")}let d=u=>t?v(u.address,t):C(u.symbol).includes(s)||C(u.name).includes(s),l=o.filter(d),f=[],y=(u,i)=>[u.symbol,u.name??""].some(m=>[i.symbol,i.name].some(A=>{let g=C(m),O=C(A),I=Ae(m),L=Ae(A);return!!g&&!!O&&(g===O||(O.length>=3?g.includes(O):` ${I} `.includes(` ${L} `)))})),b=(u,i={})=>{if(f.some(g=>v(g.address,u.address)))return;let m=[`Token ${w(u.symbol)} at ${u.address} is an unverified ${i.launchpad?"launchpad token":"token"}. Use its address, not its name or symbol.`];(j(u.symbol)||j(u.name)||o.some(g=>!v(g.address,u.address)&&y(u,g)))&&m.push(`Lookalike warning: ${w(u.symbol)} at ${u.address} resembles a verified token's name or symbol.`);let A={...u,...i,kind:i.launchpad?"launchpad":"erc20",verified:!1,source:i.launchpad?`${i.launchpad} origin and on-chain metadata; not a verified token`:"On-chain metadata only",warnings:m};f.push(A),c.push(...m)};if(t&&!l.length){let u=await ae(t,n),i={};if(a===T){try{await Se(t,n)&&(i.launchpad="clanker")}catch{c.push("Clanker origin lookup was unavailable for this address.")}if(i.launchpad==="clanker")try{let A=(await J(n.context,{q:t,limit:20})).tokens.find(g=>v(g.contract_address,t));A&&(i.creator=p(A.msg_sender),i.creatorSource="Clanker indexer msg_sender")}catch{c.push("Clanker creator lookup is unavailable.")}else try{let m=await ye(n.context,t);i.launchpad="pons",i.creator=p(m.creator),i.creatorSource="Pons factory deployer"}catch{c.push("Pons launch origin could not be confirmed for this address.")}if(!i.launchpad)try{let m=await Ge(t,n);m&&(i.launchpad="pools.trade",i.creator=m,i.creatorSource="Launch transaction sender; may be a relayer")}catch{r=!0,c.push("pools.trade launch receipt lookup is unavailable; origin results are partial.")}}b(u,i)}else if(!t&&a===T){let u=new Set,i=new Set,m,A=0,g=0;try{do{if(++A>Pe)throw new h("Token search page limit reached.");let O=await J(n.context,{q:e.trim(),limit:20,...m?{cursor:m}:{}});for(let I of O.tokens){if(++g>Ve)throw new h("Token candidate limit reached.");let L=p(I.contract_address);if(!(i.has(L)||o.some(B=>v(B.address,L)))){i.add(L);try{let B=await ae(L,n);if(!d(B))continue;let Re=await Se(L,n)?{launchpad:"clanker",creator:p(I.msg_sender),creatorSource:"Clanker indexer msg_sender"}:{};b(B,Re)}catch{r=!0,c.push(`Could not read Clanker candidate ${L}; it was omitted from these partial results.`)}}}if(O.cursor&&u.has(O.cursor))throw new h("The Clanker indexer repeated a pagination cursor.");O.cursor&&u.add(O.cursor),m=O.cursor??void 0}while(m)}catch{r=!0,c.push("Clanker name search is unavailable, incomplete or reached its scan limit; results are partial.")}c.push("Pons and pools.trade require a token address; name search does not cover those launchpads.")}a===U&&c.push("Testnet lookup covers pinned tokens and explicit token addresses; stock and launchpad discovery are unavailable.");let k=u=>[...new Map(u.map(i=>[i.address.toLowerCase(),i])).values()],S=k([...l,...f]);for(let u of S)if(S.some(i=>!v(i.address,u.address)&&(C(u.symbol)===C(i.symbol)||C(u.name)===C(i.name)))){let i=`Duplicate warning: several tokens share the symbol or name of ${u.address}. Choose the intended address; do not guess from the name.`;u.warnings.push(i),c.push(i)}return l.length>1&&c.push("Several verified tokens match this search, including possible substring matches. Choose an exact address; the search does not select a quote token."),{query:w(e.trim()),chainId:a,partial:r,matches:k(l).map(Oe),unverified:k(f).map(Oe),warnings:c}}async function mt(e,n){if(typeof e!="string"||!e.trim())throw new h("Provide a token address or verified symbol; use find_token to look it up.");if(!/^[A-Za-z0-9.$_-]{1,42}$/.test(e))throw new h("Use an exact ASCII verified symbol or token address; use find_token to look it up.");let s=e,t=V(s,{strict:!1})?E(p(s)):void 0,a=Ne(n),c=t&&a.find(b=>v(b.address,t));if(c)return c;let o=s.toUpperCase()==="$OAK"?"OAK":s.toUpperCase(),r=!t&&a.find(b=>b.symbol.toUpperCase()===o),d=[],l=!1;try{d=await De(n)}catch{if(r)return r;if(!t)throw new h("The official stock list is unavailable; stock symbols cannot be checked. Use find_token and try again when the list is reachable.");l=!0}if(t){let b=d.find(u=>v(u.address,t));if(b)return n.tokenMetadata&&G(n.tokenMetadata,d),{...b,name:w(b.name)};let k=n.tokenMetadata??await n.readMetadata?.(t);if(k&&(!v(k.address,t)||k.chainId!==D[n.context.network??"mainnet"].chainId))throw new h("Token metadata does not match the requested address and chain.");if(k&&(typeof k.symbol!="string"||!k.symbol.trim()||!Number.isInteger(k.decimals)||k.decimals<0||k.decimals>255))throw new h("The contract returned invalid token metadata.");let S=k?{...k,name:k.symbol}:await ae(t,xe(n),!1);if(l){let u=C(S.symbol),i=se.get(Y(n.context.http));if(Ue.some(m=>C(m)===u)||i?.has(u))throw new h("The official stock list is unavailable; this address claims a stock ticker that cannot be checked. Try again when the list is reachable.")}return G(S,d),{...S,symbol:w(S.symbol),name:w(S.name),kind:"erc20",verified:!1,source:"On-chain metadata only",warnings:["This token address is unverified. On-chain names and symbols do not prove identity.",...l?["The official stock list is unavailable; stock identity could not be verified."]:[]]}}let f=[...a,...d].filter(b=>b.symbol.toUpperCase()===o);if(f.length!==1)throw new h(`Token symbol ${w(s)} is ${f.length?"ambiguous":"unverified"}; use find_token and choose an explicit address.`);let y=f[0];if(y.kind==="official_stock"&&s!==y.symbol)throw new h(`Use the exact official stock ticker ${w(y.symbol)}; case variants are refused.`);return y.source==="Oak fixed addresses"?y:{...y,name:w(y.name)}}export{ee as a,_e as b,te as c,ne as d,Ce as e,re as f,H as g,Be as h,G as i,dt as j,Ie as k,Fe as l,lt as m,He as n,We as o,ut as p,mt as q};
@@ -1 +1 @@
1
- import{c as A,d as M,m as $}from"./HU2JXDLH.js";import{f as C,g as H}from"./N6PHSHBE.js";import{d as m,e as s,z as k}from"./4E7FJQLL.js";import{g as b}from"./NWNYJ26T.js";import{b as x}from"./TI727O2H.js";import{a as e}from"./XSD5NL7J.js";import{decodeFunctionData as v,encodeFunctionData as B,erc20Abi as q,getAddress as F}from"viem";function Q(u){return{tools:[{name:"uniswap_swap_batch",inputSchema:{type:"object",additionalProperties:!1,required:["routes"],properties:{routes:{description:"One to twenty complete uniswap_swap argument objects, each with its own minAmountOut or maxAmountIn bound.",type:"array",minItems:1,maxItems:20,items:{type:"object",description:"Complete uniswap_swap arguments, including an absolute minAmountOut or maxAmountIn."}}}},async execute(n,y){if(H(n,["routes"]),!Array.isArray(n.routes)||n.routes.length<1||n.routes.length>20)throw new e("Provide 1 to 20 explicit bounded Uniswap routes.");let p=[],I=[],l=new Map,i="0x",E=0n,a,w=[],P=new Set;for(let t of n.routes){if(!t||typeof t!="object"||Array.isArray(t))throw new e("Each route must contain uniswap_swap arguments.");let c=await $(u,t,y,!1);if(!("txs"in c))throw new e("Route did not build swap transactions.");p.push(...c.warnings??[]),I.push(...c.confirmationWarnings??[]);let R=c.txs;for(let r of R.slice(0,-1))if(b(r.to,m)){let[o,N,O,U]=v({abi:M,data:r.data}).args;if(N!==s)throw new e("Unexpected route approval spender.");let _=o.toLowerCase(),d=l.get(_),j=(d?.amount??0n)+O;if(j>=1n<<160n)throw new e("Combined input approvals exceed uint160.");l.set(_,{token:o,amount:j,expiration:d&&d.expiration<BigInt(U)?d.expiration:BigInt(U)})}else{let o=v({abi:q,data:r.data});if(o.functionName!=="approve"||!b(o.args[0],m))throw new e("Unexpected route prerequisite.")}let g=R.at(-1);if(g.to!==s)throw new e("Route does not use the pinned Universal Router.");E+=BigInt(g.value);let[D,h,S]=v({abi:A,data:g.data}).args,T=D.slice(2).match(/../g)??[];if(T.length!==h.length)throw new e("Unexpected route command/parameter count.");T.forEach((r,o)=>{r==="04"?P.add(h[o]):(i=`${i}${r}`,w.push(h[o]))}),a=a===void 0||S<a?S:a}for(let t of P)i=`${i}04`,w.push(t);let f=[];for(let t of l.values())f.push(u.approval(F(t.token),m,t.amount.toString(),x),k(t.token,s,t.amount.toString(),t.expiration.toString()));return f.push(u.unsignedTx({to:s,data:B({abi:A,functionName:"execute",args:[i,w,a]}),value:E.toString(),chainId:x,description:`Atomically execute ${n.routes.length} caller-selected v2/v3/v4 routes, preserving each route's trade bound.`})),{...await C(u,f,y,`${p.join(" ")}${p.length?" ":""}Explicit mixed-version/split routes; every route must meet its own bound. No automatic best-route search or allow-revert branch. The wallet must fund each independently previewed route.`),warnings:p,confirmationWarnings:I}}}]}}export{Q as a};
1
+ import{c as A,d as M,m as $}from"./6LVHN33V.js";import{f as C,g as H}from"./ZXRIJG6H.js";import{d as m,e as s,z as k}from"./FRT6AC6M.js";import{g as b}from"./NWNYJ26T.js";import{b as x}from"./TI727O2H.js";import{a as e}from"./XSD5NL7J.js";import{decodeFunctionData as v,encodeFunctionData as B,erc20Abi as q,getAddress as F}from"viem";function Q(u){return{tools:[{name:"uniswap_swap_batch",inputSchema:{type:"object",additionalProperties:!1,required:["routes"],properties:{routes:{description:"One to twenty complete uniswap_swap argument objects, each with its own minAmountOut or maxAmountIn bound.",type:"array",minItems:1,maxItems:20,items:{type:"object",description:"Complete uniswap_swap arguments, including an absolute minAmountOut or maxAmountIn."}}}},async execute(n,y){if(H(n,["routes"]),!Array.isArray(n.routes)||n.routes.length<1||n.routes.length>20)throw new e("Provide 1 to 20 explicit bounded Uniswap routes.");let p=[],I=[],l=new Map,i="0x",E=0n,a,w=[],P=new Set;for(let t of n.routes){if(!t||typeof t!="object"||Array.isArray(t))throw new e("Each route must contain uniswap_swap arguments.");let c=await $(u,t,y,!1);if(!("txs"in c))throw new e("Route did not build swap transactions.");p.push(...c.warnings??[]),I.push(...c.confirmationWarnings??[]);let R=c.txs;for(let r of R.slice(0,-1))if(b(r.to,m)){let[o,N,O,U]=v({abi:M,data:r.data}).args;if(N!==s)throw new e("Unexpected route approval spender.");let _=o.toLowerCase(),d=l.get(_),j=(d?.amount??0n)+O;if(j>=1n<<160n)throw new e("Combined input approvals exceed uint160.");l.set(_,{token:o,amount:j,expiration:d&&d.expiration<BigInt(U)?d.expiration:BigInt(U)})}else{let o=v({abi:q,data:r.data});if(o.functionName!=="approve"||!b(o.args[0],m))throw new e("Unexpected route prerequisite.")}let g=R.at(-1);if(g.to!==s)throw new e("Route does not use the pinned Universal Router.");E+=BigInt(g.value);let[D,h,S]=v({abi:A,data:g.data}).args,T=D.slice(2).match(/../g)??[];if(T.length!==h.length)throw new e("Unexpected route command/parameter count.");T.forEach((r,o)=>{r==="04"?P.add(h[o]):(i=`${i}${r}`,w.push(h[o]))}),a=a===void 0||S<a?S:a}for(let t of P)i=`${i}04`,w.push(t);let f=[];for(let t of l.values())f.push(u.approval(F(t.token),m,t.amount.toString(),x),k(t.token,s,t.amount.toString(),t.expiration.toString()));return f.push(u.unsignedTx({to:s,data:B({abi:A,functionName:"execute",args:[i,w,a]}),value:E.toString(),chainId:x,description:`Atomically execute ${n.routes.length} caller-selected v2/v3/v4 routes, preserving each route's trade bound.`})),{...await C(u,f,y,`${p.join(" ")}${p.length?" ":""}Explicit mixed-version/split routes; every route must meet its own bound. No automatic best-route search or allow-revert branch. The wallet must fund each independently previewed route.`),warnings:p,confirmationWarnings:I}}}]}}export{Q as a};
@@ -1 +1 @@
1
- import{a as k}from"./EIE2U4OX.js";import{a as E}from"./YR44GQG4.js";import{b as I}from"./L6CVMDWQ.js";import{c as $}from"./SRHVSNPX.js";import{g as w}from"./RUTSEGGD.js";import{c as C}from"./DMDOSHV7.js";import{a as b}from"./PQOWIRKQ.js";import{b as U}from"./SPJCSEKP.js";import{a as h}from"./43LI5NKJ.js";import{a as G}from"./66F5ZH34.js";import{g as P,n as y}from"./NWNYJ26T.js";import{b as s,e as T,j as S}from"./TI727O2H.js";import{a as m}from"./XSD5NL7J.js";import{encodeFunctionData as v,parseAbi as j}from"viem";var a=S[s].vaults.netnet.address,d={address:S[s].tokens.USDG.address,chainId:s,decimals:T,symbol:"USDG"},N={address:a,chainId:s,decimals:18,symbol:"nnUSDG"},o=j(["function asset() view returns (address)","function decimals() view returns (uint8)","function totalAssets() view returns (uint256)","function balanceOf(address owner) view returns (uint256)","function convertToAssets(uint256 shares) view returns (uint256)","function deposit(uint256 assets,address receiver) returns (uint256 shares)","function withdraw(uint256 assets,address receiver,address owner) returns (uint256 shares)","function redeem(uint256 shares,address receiver,address owner) returns (uint256 assets)"]),_=G("Positive USDG amount in integer base units (6 decimals)."),O="Preview amounts are estimates; these ERC-4626 calls have no on-chain minimum output argument. No transaction was sent.";function M(e){return y(e,"Amount must be positive and fit in uint256.",{notString:"Provide an integer amount string in base units.",positive:!0})}function g(e,f){if(Object.keys(e).some(l=>!f.includes(l)))throw new m("Unsupported NetNet argument.")}var q=e=>{async function f(t){try{return await t()}catch(n){throw new m(e.plainError(n))}}async function l(){let t=e.clientFor(s);if(await t.getChainId()!==s)throw new m("NetNet requires chain 4663.");let[n,r]=await Promise.all([t.readContract({address:a,abi:o,functionName:"asset"}),t.readContract({address:a,abi:o,functionName:"decimals"})]);if(!P(n,d.address))throw new m("NetNet does not report the pinned USDG asset.");if(r!==N.decimals)throw new m("NetNet share decimals do not match the pinned metadata.");return t}async function D(t,n,r){let i=await e.preview(t,n),p=i.changes.map(({token:c,amount:u})=>{let A=u.startsWith("-");return`${A?"-":"+"}${e.formatAmount(A?u.slice(1):u,c.decimals)} ${c.symbol}`}).join(", ");return{txs:t,preview:i,summary:`${r} ${i.summary} ${p?`Estimated changes: ${p}. `:""}${O}`}}async function R(t){return f(async()=>{h(t);let n=await l(),r=await n.readContract({address:a,abi:o,functionName:"balanceOf",args:[t]});if(r===0n)return[];let i=await n.readContract({address:a,abi:o,functionName:"convertToAssets",args:[r]});return[{module:"netnet",id:`${s}:${a}`,chainId:s,assets:[{token:{...d},amount:i.toString()}],description:`${e.formatAmount(r.toString(),N.decimals)} nnUSDG shares in NetNet Credit (${a}); underlying USDG is an estimate, not a liquidity guarantee.`}]})}return{positions:R,tools:[{name:"netnet_list",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:t=>f(async()=>{g(t,[]);let r=await(await l()).readContract({address:a,abi:o,functionName:"totalAssets"});return[{address:a,name:"NetNet Credit",chainId:s,asset:{...d},shares:{...N},totalAssets:{token:{...d},amount:r.toString()}}]})},{name:"netnet_deposit",inputSchema:{type:"object",description:"Deposit USDG in base units (1 USDG = 1000000) for nnUSDG vault shares. Exit with netnet_withdraw; check positions after confirmation.",properties:{amount:_},required:["amount"],additionalProperties:!1},execute:(t,n)=>f(async()=>{g(t,["amount"]),h(n);let r=M(t.amount);await l();let i=[e.approval(d.address,a,r.toString(),s),e.unsignedTx({to:a,data:v({abi:o,functionName:"deposit",args:[r,n]}),value:"0",chainId:s,description:`Deposit ${e.formatAmount(r.toString(),d.decimals)} USDG into NetNet Credit.`})];return D(i,n,"Approve the exact USDG amount, then deposit into NetNet Credit.")})},{name:"netnet_withdraw",inputSchema:{type:"object",description:"Withdraw USDG in 6-decimal base units, or amount max to redeem every nnUSDG share for USDG. Check positions after confirmation.",properties:{amount:{description:'USDG to withdraw in base units (USDG has 6 decimals; "1000000" = 1 USDG), or "max" to redeem every nnUSDG share.',anyOf:[_,{const:"max",description:"Redeem the fresh full nnUSDG share balance."}]}},required:["amount"],additionalProperties:!1},execute:(t,n)=>f(async()=>{g(t,["amount"]),h(n);let r=t.amount==="max"?void 0:M(t.amount),i=await l(),p,c;if(r===void 0){let u=await i.readContract({address:a,abi:o,functionName:"balanceOf",args:[n]});if(u===0n)throw new m("This wallet has no NetNet shares to redeem.");p=v({abi:o,functionName:"redeem",args:[u,n,n]}),c=`Redeem all ${e.formatAmount(u.toString(),N.decimals)} nnUSDG shares for USDG.`}else p=v({abi:o,functionName:"withdraw",args:[r,n,n]}),c=`Withdraw ${e.formatAmount(r.toString(),d.decimals)} USDG from NetNet Credit (unmeasured on the recorded fork; full exit uses amount "max" redeem).`;return D([e.unsignedTx({to:a,data:p,value:"0",chainId:s,description:c})],n,c)})}]}};function ie(e){return U("netnet",[q(e),w(e),$(e),C(e),k(e),E(e),I(e),{tools:b(e,"netnet",[{vault:a,asset:d}])}])}export{q as a,ie as b};
1
+ import{b as I}from"./KO7ANIKY.js";import{c as $}from"./CNDIAF3P.js";import{g as w}from"./RUTSEGGD.js";import{a as k}from"./G5AMH4IP.js";import{a as E}from"./TZ7S5KRB.js";import{c as C}from"./DMDOSHV7.js";import{a as b}from"./ZXFJKW6H.js";import{b as U}from"./SPJCSEKP.js";import{a as h}from"./43LI5NKJ.js";import{a as G}from"./66F5ZH34.js";import{g as P,n as y}from"./NWNYJ26T.js";import{b as s,e as T,j as S}from"./TI727O2H.js";import{a as m}from"./XSD5NL7J.js";import{encodeFunctionData as v,parseAbi as j}from"viem";var a=S[s].vaults.netnet.address,d={address:S[s].tokens.USDG.address,chainId:s,decimals:T,symbol:"USDG"},N={address:a,chainId:s,decimals:18,symbol:"nnUSDG"},o=j(["function asset() view returns (address)","function decimals() view returns (uint8)","function totalAssets() view returns (uint256)","function balanceOf(address owner) view returns (uint256)","function convertToAssets(uint256 shares) view returns (uint256)","function deposit(uint256 assets,address receiver) returns (uint256 shares)","function withdraw(uint256 assets,address receiver,address owner) returns (uint256 shares)","function redeem(uint256 shares,address receiver,address owner) returns (uint256 assets)"]),_=G("Positive USDG amount in integer base units (6 decimals)."),O="Preview amounts are estimates; these ERC-4626 calls have no on-chain minimum output argument. No transaction was sent.";function M(e){return y(e,"Amount must be positive and fit in uint256.",{notString:"Provide an integer amount string in base units.",positive:!0})}function g(e,f){if(Object.keys(e).some(l=>!f.includes(l)))throw new m("Unsupported NetNet argument.")}var q=e=>{async function f(t){try{return await t()}catch(n){throw new m(e.plainError(n))}}async function l(){let t=e.clientFor(s);if(await t.getChainId()!==s)throw new m("NetNet requires chain 4663.");let[n,r]=await Promise.all([t.readContract({address:a,abi:o,functionName:"asset"}),t.readContract({address:a,abi:o,functionName:"decimals"})]);if(!P(n,d.address))throw new m("NetNet does not report the pinned USDG asset.");if(r!==N.decimals)throw new m("NetNet share decimals do not match the pinned metadata.");return t}async function D(t,n,r){let i=await e.preview(t,n),p=i.changes.map(({token:c,amount:u})=>{let A=u.startsWith("-");return`${A?"-":"+"}${e.formatAmount(A?u.slice(1):u,c.decimals)} ${c.symbol}`}).join(", ");return{txs:t,preview:i,summary:`${r} ${i.summary} ${p?`Estimated changes: ${p}. `:""}${O}`}}async function R(t){return f(async()=>{h(t);let n=await l(),r=await n.readContract({address:a,abi:o,functionName:"balanceOf",args:[t]});if(r===0n)return[];let i=await n.readContract({address:a,abi:o,functionName:"convertToAssets",args:[r]});return[{module:"netnet",id:`${s}:${a}`,chainId:s,assets:[{token:{...d},amount:i.toString()}],description:`${e.formatAmount(r.toString(),N.decimals)} nnUSDG shares in NetNet Credit (${a}); underlying USDG is an estimate, not a liquidity guarantee.`}]})}return{positions:R,tools:[{name:"netnet_list",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:t=>f(async()=>{g(t,[]);let r=await(await l()).readContract({address:a,abi:o,functionName:"totalAssets"});return[{address:a,name:"NetNet Credit",chainId:s,asset:{...d},shares:{...N},totalAssets:{token:{...d},amount:r.toString()}}]})},{name:"netnet_deposit",inputSchema:{type:"object",description:"Deposit USDG in base units (1 USDG = 1000000) for nnUSDG vault shares. Exit with netnet_withdraw; check positions after confirmation.",properties:{amount:_},required:["amount"],additionalProperties:!1},execute:(t,n)=>f(async()=>{g(t,["amount"]),h(n);let r=M(t.amount);await l();let i=[e.approval(d.address,a,r.toString(),s),e.unsignedTx({to:a,data:v({abi:o,functionName:"deposit",args:[r,n]}),value:"0",chainId:s,description:`Deposit ${e.formatAmount(r.toString(),d.decimals)} USDG into NetNet Credit.`})];return D(i,n,"Approve the exact USDG amount, then deposit into NetNet Credit.")})},{name:"netnet_withdraw",inputSchema:{type:"object",description:"Withdraw USDG in 6-decimal base units, or amount max to redeem every nnUSDG share for USDG. Check positions after confirmation.",properties:{amount:{description:'USDG to withdraw in base units (USDG has 6 decimals; "1000000" = 1 USDG), or "max" to redeem every nnUSDG share.',anyOf:[_,{const:"max",description:"Redeem the fresh full nnUSDG share balance."}]}},required:["amount"],additionalProperties:!1},execute:(t,n)=>f(async()=>{g(t,["amount"]),h(n);let r=t.amount==="max"?void 0:M(t.amount),i=await l(),p,c;if(r===void 0){let u=await i.readContract({address:a,abi:o,functionName:"balanceOf",args:[n]});if(u===0n)throw new m("This wallet has no NetNet shares to redeem.");p=v({abi:o,functionName:"redeem",args:[u,n,n]}),c=`Redeem all ${e.formatAmount(u.toString(),N.decimals)} nnUSDG shares for USDG.`}else p=v({abi:o,functionName:"withdraw",args:[r,n,n]}),c=`Withdraw ${e.formatAmount(r.toString(),d.decimals)} USDG from NetNet Credit (unmeasured on the recorded fork; full exit uses amount "max" redeem).`;return D([e.unsignedTx({to:a,data:p,value:"0",chainId:s,description:c})],n,c)})}]}};function ie(e){return U("netnet",[q(e),w(e),$(e),C(e),k(e),E(e),I(e),{tools:b(e,"netnet",[{vault:a,asset:d}])}])}export{q as a,ie as b};
@@ -1 +1 @@
1
- import{a as c,f as d,g as s}from"./N6PHSHBE.js";import{f as a}from"./4E7FJQLL.js";import{a as p}from"./66F5ZH34.js";import{b as i}from"./TI727O2H.js";import{a as e}from"./XSD5NL7J.js";import{encodeFunctionData as m,erc20Abi as h,parseAbi as E}from"viem";var w=E(["function deposit() payable","function withdraw(uint256)"]);function y(n){return{tools:[{name:"uniswap_wrap",inputSchema:{type:"object",additionalProperties:!1,required:["direction","amount"],properties:{direction:{description:'Choose "wrap" to exchange ETH for WETH, or "unwrap" to exchange WETH for ETH.',type:"string",enum:["wrap","unwrap"]},amount:p('Amount of ETH or WETH in base units (18 decimals). Example: "1000000000000000000" = 1 ETH or WETH.')}},async execute(t,u){if(s(t,["direction","amount"]),t.direction!=="wrap"&&t.direction!=="unwrap")throw new e("Choose direction wrap or unwrap.");let o=c(t.amount,"amount");if(t.direction==="unwrap"){let r=await n.clientFor(i).readContract({address:a,abi:h,functionName:"balanceOf",args:[u]});if(r===0n)throw new e("You have no WETH to unwrap. Wrap ETH or receive WETH first.");if(r<o)throw new e(`You do not have enough WETH to unwrap this amount. Request ${r} base units or less.`)}let f=t.direction==="wrap"?m({abi:w,functionName:"deposit"}):m({abi:w,functionName:"withdraw",args:[o]});return d(n,[n.unsignedTx({to:a,data:f,value:t.direction==="wrap"?o.toString():"0",chainId:i,description:`${t.direction} ${o} ETH/WETH base units to the signing wallet.`})],u,"Wrap or unwrap native ETH at the pinned WETH contract. Ratio 1:1; network gas is additional.")}}]}}export{w as a,y as b};
1
+ import{a as c,f as d,g as s}from"./ZXRIJG6H.js";import{f as a}from"./FRT6AC6M.js";import{a as p}from"./66F5ZH34.js";import{b as i}from"./TI727O2H.js";import{a as e}from"./XSD5NL7J.js";import{encodeFunctionData as m,erc20Abi as h,parseAbi as E}from"viem";var w=E(["function deposit() payable","function withdraw(uint256)"]);function y(n){return{tools:[{name:"uniswap_wrap",inputSchema:{type:"object",additionalProperties:!1,required:["direction","amount"],properties:{direction:{description:'Choose "wrap" to exchange ETH for WETH, or "unwrap" to exchange WETH for ETH.',type:"string",enum:["wrap","unwrap"]},amount:p('Amount of ETH or WETH in base units (18 decimals). Example: "1000000000000000000" = 1 ETH or WETH.')}},async execute(t,u){if(s(t,["direction","amount"]),t.direction!=="wrap"&&t.direction!=="unwrap")throw new e("Choose direction wrap or unwrap.");let o=c(t.amount,"amount");if(t.direction==="unwrap"){let r=await n.clientFor(i).readContract({address:a,abi:h,functionName:"balanceOf",args:[u]});if(r===0n)throw new e("You have no WETH to unwrap. Wrap ETH or receive WETH first.");if(r<o)throw new e(`You do not have enough WETH to unwrap this amount. Request ${r} base units or less.`)}let f=t.direction==="wrap"?m({abi:w,functionName:"deposit"}):m({abi:w,functionName:"withdraw",args:[o]});return d(n,[n.unsignedTx({to:a,data:f,value:t.direction==="wrap"?o.toString():"0",chainId:i,description:`${t.direction} ${o} ETH/WETH base units to the signing wallet.`})],u,"Wrap or unwrap native ETH at the pinned WETH contract. Ratio 1:1; network gas is additional.")}}]}}export{w as a,y as b};
@@ -0,0 +1 @@
1
+ import{e as T,f as de,g as B,i as ce,j as O}from"./JDHPMS7X.js";import{F as I,a as te,b as se,c as _,f as L,h as S,m as ne,n as y,r as z,s as ie,t as re,v as ae}from"./FRT6AC6M.js";import{f as W,g as oe}from"./3BQ5XHDJ.js";import{a as U}from"./YEIM6BZQ.js";import{a as K}from"./Z7FGEWO2.js";import{h as ee}from"./QA6Z2CYP.js";import{c as Q}from"./CFPJDLTZ.js";import{a as J}from"./43LI5NKJ.js";import{g as E}from"./NWNYJ26T.js";import{b as k,n as Z}from"./TI727O2H.js";import{a as b,b as F,e as Y}from"./XSD5NL7J.js";import{decodeAbiParameters as be,getAddress as v,pad as le,parseAbi as me,parseAbiParameters as ke,toEventSelector as ye,toHex as ue,zeroAddress as he}from"viem";var Ae=ye("Initialize(bytes32,address,address,uint24,int24,address,uint160,int24)"),Ie=ke("uint24 fee, int24 tickSpacing, address hooks, uint160 sqrtPriceX96, int24 tick"),ve=10000000n,Ce=10000n,ge=25,X=200,q=16,Se=3e3,_e=500,Le=500n,R=100,$=me(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),Ne=me(["function poolKeys(bytes25 poolId) view returns (address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks)"]);function Ee(o){let e=o.trim().toLowerCase();return e==="eth"||e==="native"||e===he||e===K.toLowerCase()}function fe(o,e){if(o!=null){if(typeof o!="string")throw new b(`${e} must be a token address, or "eth" for native ETH.`);return Ee(o)?{eth:!0}:(J(o),{eth:!1,address:v(o)})}}var we=(o,e)=>BigInt(o)<BigInt(e)?-1:BigInt(o)>BigInt(e)?1:0;function H(o){return{address:o.address,symbol:o.symbol,decimals:o.decimals}}async function Pe(o,e,r,i,a){let[t,s,f]=await Promise.all([o.readContract({address:e,abi:O,functionName:"slot0"}),o.readContract({address:e,abi:O,functionName:"liquidity"}),o.readContract({address:e,abi:O,functionName:"tickSpacing"})]),n=BigInt(t[0]);return{version:"v3",id:e,feePercent:U(a),highFee:a>=5e4,token0:H(r),token1:H(i),fee:a,tickSpacing:Number(f),initialized:n>0n,liquidity:BigInt(s).toString(),sqrtPriceX96:n.toString(),tick:Number(t[1]),price:n>0n?W(n,r.decimals,i.decimals):"0",addSupported:!0}}async function x(o,e,r){let i=r??re(e),[a,t]=await Promise.all([I(o,e.currency0,k),I(o,e.currency1,k)]),[s,f]=await Promise.all([o.readContract({address:_,abi:$,functionName:"getSlot0",args:[i]}),o.readContract({address:_,abi:$,functionName:"getLiquidity",args:[i]})]),n=BigInt(s[0]),w=ae(e,Number(s[3]));return{version:"v4",id:i,feePercent:U((e.fee&8388608)!==0?Number(s[3]):e.fee),highFee:((e.fee&8388608)!==0?Number(s[3]):e.fee)>=5e4,token0:H(a),token1:H(t),fee:e.fee,tickSpacing:e.tickSpacing,hooks:v(e.hooks),initialized:n>0n,liquidity:BigInt(f).toString(),sqrtPriceX96:n.toString(),tick:Number(s[1]),price:n>0n?W(n,a.decimals,t.decimals):"0",addSupported:z.has(e.hooks.toLowerCase()),feeNote:w.feeNote,...z.has(e.hooks.toLowerCase())?{}:{note:i.toLowerCase()===Q.poolId?ee:e.hooks.toLowerCase()===Z.toLowerCase()?new ne(ie(e.currency0)?e.currency1:void 0).message:`Hook ${v(e.hooks)} is not one Oak has measured, so uniswap_add will refuse this pool.`}}}async function Te(o,e,r,i){let a=await o.getBlockNumber(),t=[],s=new Set,f=!1,n=ve;for(let d=a;;){let u=d+1n>n?d-n+1n:0n,l;try{l=await o.request({method:"eth_getLogs",params:[{address:te.toLowerCase(),topics:[Ae,null,e?le(e):null,r?le(r):null],fromBlock:ue(u),toBlock:ue(d)}]})}catch(p){if(F(p,-32601)||n<=Ce)throw p;n/=2n;continue}if(!Array.isArray(l))throw new b("Invalid v4 Initialize log response.");let P=[];for(let p of l){if(!Array.isArray(p.topics)||p.topics.length!==4||typeof p.data!="string")throw new b("Invalid v4 Initialize log.");let[A,C,N]=be(Ie,p.data),D={currency0:v(`0x${p.topics[2].slice(-40)}`),currency1:v(`0x${p.topics[3].slice(-40)}`),fee:Number(A),tickSpacing:Number(C),hooks:v(N)};P.push({key:D,id:p.topics[1]}),s.add(p.topics[1].toLowerCase())}if(t.push(P),u===0n)break;if(s.size>=i){f=!0;break}d=u-1n}let w=new Map;for(let d of t.reverse())for(let u of d)w.set(u.id.toLowerCase(),u);return{pools:[...w.values()],cut:f}}async function Be(o,e,r){let i=e.eth?T.weth:e.address,a=r.eth?T.weth:r.address;if(i===a)return[];let[t,s]=we(i,a)<0?[i,a]:[a,i],[f,n]=await Promise.all([I(o,t,k),I(o,s,k)]),w=[];for(let d of Object.keys(de).map(Number)){let u=v(String(await o.readContract({address:T.factory,abi:ce,functionName:"getPool",args:[t,s,d]})));u!==he&&w.push(await Pe(o,u,f,n,d))}return w}function pe(o){return o?o.eth?[S,L]:o.address===L?[L,S]:[o.address]:null}async function Oe(o,e){let r=new Map;if(e.length===0)return r;if(typeof o.multicall=="function"&&o.chain?.contracts?.multicall3)try{return(await o.multicall({allowFailure:!0,contracts:e.map(a=>({address:_,abi:$,functionName:"getLiquidity",args:[a]}))})).forEach((a,t)=>r.set(e[t].toLowerCase(),a.status==="success"?BigInt(a.result):0n)),r}catch{}for(let i=0;i<e.length;i+=q)(await Promise.allSettled(e.slice(i,i+q).map(async t=>BigInt(await o.readContract({address:_,abi:$,functionName:"getLiquidity",args:[t]}))))).forEach((t,s)=>r.set(e[i+s].toLowerCase(),t.status==="fulfilled"?t.value:0n));return r}async function Re(o,e,r,i){let a=pe(e),t=pe(r),s=new Map,f=(c,h)=>{if(c&&h){if(c===h)return;let[m,g]=we(c,h)<0?[c,h]:[h,c];s.set(`${m}/${g}`,[m,g])}else if(c||h){let m=c??h;s.set(`${m}/*0`,[m,null]),s.set(`${m}/*1`,[null,m])}};for(let c of a??[null])for(let h of t??[null])f(c,h);let n=new Map;for(let c of y)[...s.values()].some(([m,g])=>(!m||E(c.key.currency0,m))&&(!g||E(c.key.currency1,g)))&&n.set(c.poolId.toLowerCase(),{key:c.key,id:c.poolId});let d=typeof o.multicall=="function"&&!!o.chain?.contracts?.multicall3?Se:_e,u=!1;for(let[c,h]of s.values()){let m=await Te(o,c,h,d+y.length);u||=m.cut;for(let g of m.pools)n.set(g.id.toLowerCase(),g)}let l=new Set(y.map(c=>c.poolId.toLowerCase())),P=[...n.values()],p=P.filter(c=>l.has(c.id.toLowerCase())),A=P.filter(c=>!l.has(c.id.toLowerCase())).reverse();(A.length>d||u)&&i.push(`${u?"At least ":""}${A.length} v4 pools match; only the newest ${d} non-measured ones were considered. Pass both tokens, or a poolId, to narrow.`);let C=A.slice(0,d),N=await Oe(o,C.map(c=>c.id)),D=C.sort((c,h)=>{let m=N.get(c.id.toLowerCase())??0n,g=N.get(h.id.toLowerCase())??0n;return m===g?0:m<g?1:-1}),V=[...p,...D];V.length>X&&i.push(`${V.length} v4 pools match; full state was read for Oak's measured pools plus the deepest of the rest (${X} total). Pass both tokens, or a poolId, to narrow.`);let G=[],M=0,j=V.slice(0,X);for(let c=0;c<j.length;c+=q){let h=await Promise.allSettled(j.slice(c,c+q).map(({key:m,id:g})=>x(o,m,g)));for(let m of h)m.status==="fulfilled"?G.push(m.value):M++}return M>0&&i.push(`${M} pool(s) were skipped because a token or pool state could not be read.`),G}async function qe(o,e){let r=y.find(n=>E(n.poolId,e));if(r)return x(o,r.key,r.poolId);let[i,a,t,s,f]=await o.readContract({address:se,abi:Ne,functionName:"poolKeys",args:[e.slice(0,52)]});if(i===S&&a===S&&Number(s)===0)throw new b(`No Uniswap v4 pool ${e} is known to the PositionManager (no position was ever minted in it, or it is not initialized). Search by token pair instead.`);return x(o,{currency0:i,currency1:a,fee:Number(t),tickSpacing:Number(s),hooks:f},e)}function $e(o){let e=new Set([...y.map(t=>t.poolId.toLowerCase()),...B.map(t=>t.address.toLowerCase())]),r=new Set([S,K.toLowerCase(),L.toLowerCase()]),i=t=>r.has(t.address.toLowerCase())?"ETH":t.address.toLowerCase(),a=new Map;for(let t of o.filter(s=>s.initialized&&BigInt(s.liquidity)>0n)){let s=`${i(t.token0)}/${i(t.token1)}`;a.set(s,[...a.get(s)??[],t])}for(let t of a.values()){let s=t.filter(d=>e.has(d.id.toLowerCase()));if(s.length===0&&t.length<3)continue;let n=(s.length>0?s:t).map(d=>BigInt(d.sqrtPriceX96)).sort((d,u)=>d<u?-1:d>u?1:0),w=n[Math.floor(n.length/2)];for(let d of t){if(e.has(d.id.toLowerCase()))continue;let u=oe(BigInt(d.sqrtPriceX96),w);u>Le&&(d.priceOutlierBps=Number(u),d.note=`${d.note?`${d.note} `:""}Price differs ${u} bps from the ${s.length>0?"Oak-measured":"median"} price for this pair; do not treat this pool as the market price.`)}}}async function He(o,e){let r=e.version;if(r!==void 0&&r!=="v3"&&r!=="v4")throw new b('version must be "v3" or "v4"; omit it to search both.');let i=e.limit===void 0?ge:Number(e.limit);if(!Number.isInteger(i)||i<1||i>R)throw new b(`limit must be an integer from 1 to ${R}.`);let a=fe(e.tokenA,"tokenA"),t=fe(e.tokenB,"tokenB");if(!a&&t)throw new b("Provide tokenA when searching by token; tokenB narrows the search to a pair.");let s=o.clientFor(k),f=[],n=[];if(e.poolId!==void 0){if(typeof e.poolId!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.poolId))throw new b("poolId must be a 32-byte hex v4 poolId. For v3 search by tokenA/tokenB.");n=[await qe(s,e.poolId)]}else if(a){if(r!=="v4"&&(t?n.push(...await Be(s,a,t)):f.push("v3 pools are looked up per pair; pass tokenB to include them.")),r!=="v3")try{n.push(...await Re(s,a,t,f))}catch(l){throw F(l,-32601)?l:new b(`Could not search v4 pools. ${Y(l)}`)}}else{f.push("No token filter given: showing the pools Oak has measured. Pass tokenA (and tokenB) to search the chain for every pool of a pair.");let l=await Promise.all(B.map(async p=>{let[A,C]=await Promise.all([I(s,p.token0,k),I(s,p.token1,k)]);return Pe(s,p.address,A,C,p.fee)})),P=await Promise.all(y.map(p=>x(s,p.key,p.poolId)));n=[...r==="v4"?[]:l,...r==="v3"?[]:P]}$e(n);let w=new Set([...y.map(l=>l.poolId.toLowerCase()),...B.map(l=>l.address.toLowerCase())]),d=0;n=n.filter(l=>!l.highFee||w.has(l.id.toLowerCase())?!0:e.includeHighFeePools===!0?(l.note=`Do not trade here: ${l.feePercent} fee.${l.note?` ${l.note}`:""}`,!0):(d++,!1)),d&&f.push(`${d} pools with fees of 5% or more were left out. To see them, pass includeHighFeePools: true.`),n.sort((l,P)=>BigInt(P.liquidity)>BigInt(l.liquidity)?1:BigInt(P.liquidity)<BigInt(l.liquidity)?-1:0),n.length>i&&f.push(`Showing the ${i} deepest of ${n.length} pools found; raise limit (max ${R}) to see more.`),n=n.slice(0,i);let u=n.filter(l=>l.initialized&&BigInt(l.liquidity)>0n).length;return n.length===0&&d===0&&f.push("No pool exists for this pair. Create one with uniswap_create_pool, or create it and add the first liquidity together with uniswap_add plus initialPrice."),{pools:n,notes:f,summary:`Found ${n.length} Uniswap pool(s), ${u} with active liquidity. price is token1 per 1 token0.`}}function Ye(o){return{tools:[{name:"uniswap_pools",inputSchema:{type:"object",description:"Read-only pool discovery on Robinhood Chain (4663): every Uniswap v3 and v4 pool for a token pair with fee, tick spacing, hook, liquidity and price, or one v4 pool by poolId. No tokens given: the measured pools.",properties:{version:{type:"string",enum:["v3","v4"],description:"Limit to one version; omit to search both."},tokenA:{type:"string",description:'Token address, or "eth" for native ETH (searches v3 WETH and v4 native/WETH pools).'},tokenB:{type:"string",description:"Second token of the pair. Required for v3 lookups."},poolId:{type:"string",description:"32-byte v4 poolId to inspect."},includeHighFeePools:{description:"Include pools above the usual fee threshold in discovery.",type:"boolean"},limit:{description:"Maximum number of results to return, within the stated bounds.",type:"integer",minimum:1,maximum:R,default:ge}}},execute:async r=>He(o,r)}]}}export{He as a,Ye as b};