@oakagentkit/core 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (380) hide show
  1. package/build/dist/api/addresses.d.ts +93 -0
  2. package/build/dist/api/addresses.js +1 -1
  3. package/build/dist/api/chain.js +1 -1
  4. package/build/dist/api/history.js +1 -1
  5. package/build/dist/api/identity-link.js +1 -1
  6. package/build/dist/api/metadata.js +1 -1
  7. package/build/dist/api/modules/beefy/boosts.js +1 -1
  8. package/build/dist/api/modules/beefy/clm.js +1 -1
  9. package/build/dist/api/modules/beefy/guard.js +1 -1
  10. package/build/dist/api/modules/beefy/index.js +1 -1
  11. package/build/dist/api/modules/beefy/liquidity.js +1 -1
  12. package/build/dist/api/modules/beefy/management.js +1 -1
  13. package/build/dist/api/modules/beefy/vaults.js +1 -1
  14. package/build/dist/api/modules/clanker/extensions.js +1 -1
  15. package/build/dist/api/modules/clanker/index.js +1 -1
  16. package/build/dist/api/modules/clanker/manage.js +1 -1
  17. package/build/dist/api/modules/clanker/pool-config.js +1 -1
  18. package/build/dist/api/modules/clanker/protocol.js +1 -1
  19. package/build/dist/api/modules/clanker/state.js +1 -1
  20. package/build/dist/api/modules/erc8004/common.js +1 -1
  21. package/build/dist/api/modules/erc8004/domain.js +1 -1
  22. package/build/dist/api/modules/erc8004/index.js +1 -1
  23. package/build/dist/api/modules/erc8004/management.js +1 -1
  24. package/build/dist/api/modules/erc8004/reputation.js +1 -1
  25. package/build/dist/api/modules/erc8004/services.js +1 -1
  26. package/build/dist/api/modules/erc8004/validation.js +1 -1
  27. package/build/dist/api/modules/grove/index.js +1 -1
  28. package/build/dist/api/modules/heyresearch/backoff.d.ts +6 -0
  29. package/build/dist/api/modules/heyresearch/backoff.js +1 -0
  30. package/build/dist/api/modules/heyresearch/builder-feed.d.ts +62 -0
  31. package/build/dist/api/modules/heyresearch/builder-feed.js +1 -0
  32. package/build/dist/api/modules/heyresearch/index.d.ts +3 -0
  33. package/build/dist/api/modules/heyresearch/index.js +1 -1
  34. package/build/dist/api/modules/heyresearch/proof-reads.d.ts +7 -0
  35. package/build/dist/api/modules/heyresearch/proof-reads.js +1 -0
  36. package/build/dist/api/modules/heyresearch/public-reads.d.ts +1 -0
  37. package/build/dist/api/modules/heyresearch/public-reads.js +1 -1
  38. package/build/dist/api/modules/heyresearch/scan.d.ts +31 -0
  39. package/build/dist/api/modules/heyresearch/scan.js +1 -0
  40. package/build/dist/api/modules/heyresearch/status-labels.d.ts +5 -0
  41. package/build/dist/api/modules/heyresearch/status-labels.js +1 -0
  42. package/build/dist/api/modules/heyresearch/token-facts.d.ts +123 -0
  43. package/build/dist/api/modules/heyresearch/token-facts.js +1 -0
  44. package/build/dist/api/modules/hoodag/chain-reads.js +1 -1
  45. package/build/dist/api/modules/hoodag/index.js +1 -1
  46. package/build/dist/api/modules/hoodag/management.js +1 -1
  47. package/build/dist/api/modules/hoodag/public-reads.js +1 -1
  48. package/build/dist/api/modules/hoodag/reconstruct.js +1 -1
  49. package/build/dist/api/modules/hoodlock/airdrop.js +1 -1
  50. package/build/dist/api/modules/hoodlock/buyback.js +1 -1
  51. package/build/dist/api/modules/hoodlock/commerce.js +1 -1
  52. package/build/dist/api/modules/hoodlock/fee.js +1 -1
  53. package/build/dist/api/modules/hoodlock/guard.js +1 -1
  54. package/build/dist/api/modules/hoodlock/index.js +1 -1
  55. package/build/dist/api/modules/hoodlock/lifecycle.js +1 -1
  56. package/build/dist/api/modules/hoodlock/locks-burn.js +1 -1
  57. package/build/dist/api/modules/hoodlock/public.js +1 -1
  58. package/build/dist/api/modules/hookr/actions.d.ts +1 -1
  59. package/build/dist/api/modules/hookr/actions.js +1 -1
  60. package/build/dist/api/modules/hookr/addons.js +1 -1
  61. package/build/dist/api/modules/hookr/agent-gate.d.ts +63 -0
  62. package/build/dist/api/modules/hookr/agent-gate.js +1 -0
  63. package/build/dist/api/modules/hookr/contracts.js +1 -1
  64. package/build/dist/api/modules/hookr/create-cancel.js +1 -1
  65. package/build/dist/api/modules/hookr/discovery.js +1 -1
  66. package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
  67. package/build/dist/api/modules/hookr/index.d.ts +1 -0
  68. package/build/dist/api/modules/hookr/index.js +1 -1
  69. package/build/dist/api/modules/hookr/launch-options.d.ts +119 -0
  70. package/build/dist/api/modules/hookr/launch-options.js +1 -0
  71. package/build/dist/api/modules/hookr/launch-profile.d.ts +5 -0
  72. package/build/dist/api/modules/hookr/launch-profile.js +1 -0
  73. package/build/dist/api/modules/hookr/launch-receipt.d.ts +144 -0
  74. package/build/dist/api/modules/hookr/launch-receipt.js +1 -0
  75. package/build/dist/api/modules/hookr/launch.d.ts +58 -0
  76. package/build/dist/api/modules/hookr/launch.js +1 -0
  77. package/build/dist/api/modules/hookr/liquidity.d.ts +48 -0
  78. package/build/dist/api/modules/hookr/liquidity.js +1 -0
  79. package/build/dist/api/modules/hookr/lp-positions.d.ts +2 -0
  80. package/build/dist/api/modules/hookr/lp-positions.js +1 -0
  81. package/build/dist/api/modules/hookr/lp-reads.d.ts +52 -0
  82. package/build/dist/api/modules/hookr/lp-reads.js +1 -0
  83. package/build/dist/api/modules/hookr/lp-receipt.d.ts +136 -0
  84. package/build/dist/api/modules/hookr/lp-receipt.js +1 -0
  85. package/build/dist/api/modules/hookr/lp-state.d.ts +33 -0
  86. package/build/dist/api/modules/hookr/lp-state.js +1 -0
  87. package/build/dist/api/modules/hookr/pins.d.ts +43 -0
  88. package/build/dist/api/modules/hookr/pins.js +1 -0
  89. package/build/dist/api/modules/hookr/public-reads.js +1 -1
  90. package/build/dist/api/modules/hookr/read-utils.d.ts +59 -0
  91. package/build/dist/api/modules/hookr/read-utils.js +1 -0
  92. package/build/dist/api/modules/hookr/relay.js +1 -1
  93. package/build/dist/api/modules/hookr/revenue.js +1 -1
  94. package/build/dist/api/modules/kyberswap/index.js +1 -1
  95. package/build/dist/api/modules/kyberswap/source-pools.js +1 -1
  96. package/build/dist/api/modules/lighter/index.js +1 -1
  97. package/build/dist/api/modules/longbow/administration.js +1 -1
  98. package/build/dist/api/modules/longbow/analytics.js +1 -1
  99. package/build/dist/api/modules/longbow/fixed.js +1 -1
  100. package/build/dist/api/modules/longbow/index.js +1 -1
  101. package/build/dist/api/modules/longbow/nft.js +1 -1
  102. package/build/dist/api/modules/longbow/rebates.js +1 -1
  103. package/build/dist/api/modules/longbow/staking.js +1 -1
  104. package/build/dist/api/modules/meridian/index.js +1 -1
  105. package/build/dist/api/modules/meridian/markets.js +1 -1
  106. package/build/dist/api/modules/meridian/rfq.js +1 -1
  107. package/build/dist/api/modules/merkl/discovery.js +1 -1
  108. package/build/dist/api/modules/merkl/index.js +1 -1
  109. package/build/dist/api/modules/merkl/manage.js +1 -1
  110. package/build/dist/api/modules/merkl/protocol.js +1 -1
  111. package/build/dist/api/modules/morpho/allocator.js +1 -1
  112. package/build/dist/api/modules/morpho/bundles.js +1 -1
  113. package/build/dist/api/modules/morpho/in-kind.js +1 -1
  114. package/build/dist/api/modules/morpho/index.js +1 -1
  115. package/build/dist/api/modules/morpho/local-guard.js +1 -1
  116. package/build/dist/api/modules/morpho/midnight.js +1 -1
  117. package/build/dist/api/modules/morpho/protocol.js +1 -1
  118. package/build/dist/api/modules/morpho/vault-management.js +1 -1
  119. package/build/dist/api/modules/morpho/vault-tools.js +1 -1
  120. package/build/dist/api/modules/morpho/vault-v2.js +1 -1
  121. package/build/dist/api/modules/netnet/card-plan.js +1 -1
  122. package/build/dist/api/modules/netnet/card-read.js +1 -1
  123. package/build/dist/api/modules/netnet/card-recovery.js +1 -1
  124. package/build/dist/api/modules/netnet/desk-action.js +1 -1
  125. package/build/dist/api/modules/netnet/desk-read.js +1 -1
  126. package/build/dist/api/modules/netnet/financial.js +1 -1
  127. package/build/dist/api/modules/netnet/index.js +1 -1
  128. package/build/dist/api/modules/netnet/staking.js +1 -1
  129. package/build/dist/api/modules/orbio/index.js +1 -1
  130. package/build/dist/api/modules/pons/claim.js +1 -1
  131. package/build/dist/api/modules/pons/index.js +1 -1
  132. package/build/dist/api/modules/pons/launch-status.js +1 -1
  133. package/build/dist/api/modules/pons/prices.js +1 -1
  134. package/build/dist/api/modules/pons/reads.js +1 -1
  135. package/build/dist/api/modules/pons/swap-terms.js +1 -1
  136. package/build/dist/api/modules/pons/trade.js +1 -1
  137. package/build/dist/api/modules/poolstrade/index.js +1 -1
  138. package/build/dist/api/modules/priors/coverage.js +1 -1
  139. package/build/dist/api/modules/priors/discovery.js +1 -1
  140. package/build/dist/api/modules/priors/features.js +1 -1
  141. package/build/dist/api/modules/priors/index.js +1 -1
  142. package/build/dist/api/modules/priors/integration.js +1 -1
  143. package/build/dist/api/modules/priors/market.js +1 -1
  144. package/build/dist/api/modules/priors/pt.js +1 -1
  145. package/build/dist/api/modules/priors/savings-exit.js +1 -1
  146. package/build/dist/api/modules/priors/starter-line.js +1 -1
  147. package/build/dist/api/modules/priors/stock-swap.js +1 -1
  148. package/build/dist/api/modules/relay/bootstrap.js +1 -1
  149. package/build/dist/api/modules/relay/discovery.js +1 -1
  150. package/build/dist/api/modules/relay/inbound.js +1 -1
  151. package/build/dist/api/modules/relay/index.js +1 -1
  152. package/build/dist/api/modules/relay/outbound-status.js +1 -1
  153. package/build/dist/api/modules/relay/reads.js +1 -1
  154. package/build/dist/api/modules/spark/actions.js +1 -1
  155. package/build/dist/api/modules/spark/details.js +1 -1
  156. package/build/dist/api/modules/spark/index.js +1 -1
  157. package/build/dist/api/modules/spark/management.js +1 -1
  158. package/build/dist/api/modules/steakhouse/analytics.js +1 -1
  159. package/build/dist/api/modules/steakhouse/erc4626.js +1 -1
  160. package/build/dist/api/modules/steakhouse/index.js +1 -1
  161. package/build/dist/api/modules/steakhouse/local-guard.js +1 -1
  162. package/build/dist/api/modules/steakhouse/management.js +1 -1
  163. package/build/dist/api/modules/steakhouse/v2-exit.js +1 -1
  164. package/build/dist/api/modules/tickerspring/basket-routes.js +1 -1
  165. package/build/dist/api/modules/tickerspring/contract-reads.js +1 -1
  166. package/build/dist/api/modules/tickerspring/discovery.js +1 -1
  167. package/build/dist/api/modules/tickerspring/exit-preview.js +1 -1
  168. package/build/dist/api/modules/tickerspring/guards.js +1 -1
  169. package/build/dist/api/modules/tickerspring/index.js +1 -1
  170. package/build/dist/api/modules/tickerspring/journeys.js +1 -1
  171. package/build/dist/api/modules/tickerspring/ladder.js +1 -1
  172. package/build/dist/api/modules/tickerspring/maker.js +1 -1
  173. package/build/dist/api/modules/tickerspring/order-accounting.js +1 -1
  174. package/build/dist/api/modules/tickerspring/research.js +1 -1
  175. package/build/dist/api/modules/tickerspring/strategies.js +1 -1
  176. package/build/dist/api/modules/uniswap/auction-create.js +1 -1
  177. package/build/dist/api/modules/uniswap/auction.js +1 -1
  178. package/build/dist/api/modules/uniswap/batch.js +1 -1
  179. package/build/dist/api/modules/uniswap/common.js +1 -1
  180. package/build/dist/api/modules/uniswap/fees.js +1 -1
  181. package/build/dist/api/modules/uniswap/index.js +1 -1
  182. package/build/dist/api/modules/uniswap/local-guard.js +1 -1
  183. package/build/dist/api/modules/uniswap/oracle.js +1 -1
  184. package/build/dist/api/modules/uniswap/pool-math.js +1 -1
  185. package/build/dist/api/modules/uniswap/pools.js +1 -1
  186. package/build/dist/api/modules/uniswap/position.js +1 -1
  187. package/build/dist/api/modules/uniswap/protocol.js +1 -1
  188. package/build/dist/api/modules/uniswap/token-jar.js +1 -1
  189. package/build/dist/api/modules/uniswap/trade-batch.js +1 -1
  190. package/build/dist/api/modules/uniswap/trade.js +1 -1
  191. package/build/dist/api/modules/uniswap/v2.js +1 -1
  192. package/build/dist/api/modules/uniswap/v3.js +1 -1
  193. package/build/dist/api/modules/uniswap/v4.js +1 -1
  194. package/build/dist/api/modules/uniswap/wrap.js +1 -1
  195. package/build/dist/api/modules/velora/claims.js +1 -1
  196. package/build/dist/api/modules/velora/delta-reads.js +1 -1
  197. package/build/dist/api/modules/velora/index.js +1 -1
  198. package/build/dist/api/modules/wormhole/index.d.ts +5 -0
  199. package/build/dist/api/modules/wormhole/index.js +1 -0
  200. package/build/dist/api/modules/wormhole/license.d.ts +2 -0
  201. package/build/dist/api/modules/wormhole/license.js +1 -0
  202. package/build/dist/api/modules/wormhole/quotetext.d.ts +36 -0
  203. package/build/dist/api/modules/wormhole/quotetext.js +1 -0
  204. package/build/dist/api/modules/wormhole/scan-text.d.ts +40 -0
  205. package/build/dist/api/modules/wormhole/scan-text.js +1 -0
  206. package/build/dist/api/modules/wormhole/token-check.d.ts +54 -0
  207. package/build/dist/api/modules/wormhole/token-check.js +1 -0
  208. package/build/dist/api/positions.js +1 -1
  209. package/build/dist/api/pricenote.js +1 -1
  210. package/build/dist/api/prices.js +1 -1
  211. package/build/dist/api/pricing.js +1 -1
  212. package/build/dist/api/rpc.js +1 -1
  213. package/build/dist/api/send.js +1 -1
  214. package/build/dist/api/signing-registry.js +1 -1
  215. package/build/dist/api/signing.js +1 -1
  216. package/build/dist/api/simulate.js +1 -1
  217. package/build/dist/api/swap.js +1 -1
  218. package/build/dist/api/tokens.d.ts +4 -0
  219. package/build/dist/api/tokens.js +1 -1
  220. package/build/dist/api/tool-policy.js +1 -1
  221. package/build/dist/api/types.d.ts +7 -0
  222. package/build/dist/chunks/{QHHZDXRG.js → 2FSX7MMR.js} +1 -1
  223. package/build/dist/chunks/{RTBOMWCB.js → 2LM7U4S7.js} +1 -1
  224. package/build/dist/chunks/{XKRWJCYE.js → 2MSQ6JII.js} +1 -1
  225. package/build/dist/chunks/{T6MTTMLQ.js → 2UU5TBBB.js} +1 -1
  226. package/build/dist/chunks/{OW7GOYKA.js → 2W46IRX6.js} +1 -1
  227. package/build/dist/chunks/{6LLOTPH2.js → 3EFV4FQF.js} +1 -1
  228. package/build/dist/chunks/{64AF7ECA.js → 3NDVXEBR.js} +1 -1
  229. package/build/dist/chunks/3SC5UI35.js +1 -0
  230. package/build/dist/chunks/{TCS3ICNE.js → 3WBDHUV2.js} +1 -1
  231. package/build/dist/chunks/{UPPYXY74.js → 4AKIXLXH.js} +1 -1
  232. package/build/dist/chunks/{RRSODRGT.js → 4GAWMCQC.js} +1 -1
  233. package/build/dist/chunks/{ZGXNTWYG.js → 4GHVIBL5.js} +1 -1
  234. package/build/dist/chunks/{NHCRJC5X.js → 4KQZTPMS.js} +1 -1
  235. package/build/dist/chunks/{N77ANGBT.js → 4X2JOQ2L.js} +1 -1
  236. package/build/dist/chunks/{ZPM2MFXZ.js → 52DHGSG4.js} +1 -1
  237. package/build/dist/chunks/{ITV52TIE.js → 57HAXNQV.js} +1 -1
  238. package/build/dist/chunks/5IIR3GIN.js +1 -0
  239. package/build/dist/chunks/{CAU44UWP.js → 5O5ZE3ZV.js} +1 -1
  240. package/build/dist/chunks/5OEHZJ6X.js +1 -0
  241. package/build/dist/chunks/{CBA776XQ.js → 5VHH5PW3.js} +1 -1
  242. package/build/dist/chunks/{O5SU2I3G.js → 66VBACC2.js} +1 -1
  243. package/build/dist/chunks/{6HV5BR7P.js → 6AWTAE4Q.js} +1 -1
  244. package/build/dist/chunks/{JRVTSGAT.js → 6UPPUHCL.js} +1 -1
  245. package/build/dist/chunks/{3ACEWCKZ.js → 6ZYLNB2B.js} +1 -1
  246. package/build/dist/chunks/7XLEYOZH.js +1 -0
  247. package/build/dist/chunks/{QCD33HMD.js → AAGDMH54.js} +1 -1
  248. package/build/dist/chunks/ACN2BFMA.js +1 -0
  249. package/build/dist/chunks/{L24EOVLT.js → AJP5LDM2.js} +1 -1
  250. package/build/dist/chunks/{F2YH72GF.js → ALK6NKFP.js} +1 -1
  251. package/build/dist/chunks/{EC5W3UZD.js → AMICUXS6.js} +1 -1
  252. package/build/dist/chunks/{5FTSKYQH.js → BX7XQANB.js} +1 -1
  253. package/build/dist/chunks/{QNPEKNWM.js → CEIPDEXZ.js} +1 -1
  254. package/build/dist/chunks/{HFQS5344.js → CQCVFRQ5.js} +1 -1
  255. package/build/dist/chunks/{OJLMF5AR.js → CUNQ5RG5.js} +1 -1
  256. package/build/dist/chunks/{IWALIX7Q.js → CXLEQCP3.js} +1 -1
  257. package/build/dist/chunks/{VJ3W2V3B.js → CY75R4FK.js} +1 -1
  258. package/build/dist/chunks/{65QFM4JU.js → DCTUYDWF.js} +1 -1
  259. package/build/dist/chunks/DHOBTJRD.js +1 -0
  260. package/build/dist/chunks/{NO57NGRV.js → DRWWPBOQ.js} +1 -1
  261. package/build/dist/chunks/{7B5UH2VS.js → DZGEQBO7.js} +1 -1
  262. package/build/dist/chunks/{RFJCG4NA.js → E7R3J4H7.js} +1 -1
  263. package/build/dist/chunks/{7T4BYFD4.js → EGUMOD3A.js} +1 -1
  264. package/build/dist/chunks/ELZNT5Q3.js +1 -0
  265. package/build/dist/chunks/EPZ7SWKM.js +1 -0
  266. package/build/dist/chunks/{WDGPCPQJ.js → EXRKBBX2.js} +1 -1
  267. package/build/dist/chunks/{U3FMCX3L.js → FBSUTF3B.js} +1 -1
  268. package/build/dist/chunks/FUXT7GRK.js +1 -0
  269. package/build/dist/chunks/G6HCV67X.js +1 -0
  270. package/build/dist/chunks/{HNMOB76J.js → GGUEKSR4.js} +1 -1
  271. package/build/dist/chunks/{GZ5TW3WB.js → GIV5JMTE.js} +1 -1
  272. package/build/dist/chunks/{ZYR5LSVB.js → GJY3P6OG.js} +1 -1
  273. package/build/dist/chunks/HOEQVPY7.js +1 -0
  274. package/build/dist/chunks/{R7D256HG.js → IBXYIN7Q.js} +1 -1
  275. package/build/dist/chunks/{SXX52Y27.js → IUE6RASI.js} +1 -1
  276. package/build/dist/chunks/J2XAEVKC.js +1 -0
  277. package/build/dist/chunks/{AYM5L6L7.js → J3GFCBZZ.js} +1 -1
  278. package/build/dist/chunks/JNZZLA2A.js +1 -0
  279. package/build/dist/chunks/JPOYTTTW.js +1 -0
  280. package/build/dist/chunks/{4IPW5WZ4.js → JST5JGAP.js} +1 -1
  281. package/build/dist/chunks/{ZCGVBK5K.js → JVI26KQO.js} +1 -1
  282. package/build/dist/chunks/JWCOXLYA.js +1 -0
  283. package/build/dist/chunks/{G7UKNO2I.js → KHJFXJBU.js} +1 -1
  284. package/build/dist/chunks/{HQVC6X3T.js → KSZMMNXK.js} +1 -1
  285. package/build/dist/chunks/{JC4SYMBV.js → L3ZM77SJ.js} +1 -1
  286. package/build/dist/chunks/{QRUC7EFE.js → L62M7LOB.js} +1 -1
  287. package/build/dist/chunks/{5VXNQFYJ.js → L7YBCMZU.js} +1 -1
  288. package/build/dist/chunks/{H6ED3RHF.js → LMVB3B6T.js} +1 -1
  289. package/build/dist/chunks/{UIIJWIR6.js → LQGPMOD2.js} +1 -1
  290. package/build/dist/chunks/{BXN3MDS4.js → LQUDJCAR.js} +1 -1
  291. package/build/dist/chunks/LT5P6PZW.js +1 -0
  292. package/build/dist/chunks/M7U3A4EH.js +3 -0
  293. package/build/dist/chunks/MFNP4KOK.js +1 -0
  294. package/build/dist/chunks/MKQVS3IO.js +1 -0
  295. package/build/dist/chunks/{7US6PD56.js → MLPWQTBS.js} +1 -1
  296. package/build/dist/chunks/{5XFXH2JT.js → NATG6YA6.js} +1 -1
  297. package/build/dist/chunks/{O47JXRXN.js → NAYRD43N.js} +1 -1
  298. package/build/dist/chunks/NMYGNJIJ.js +1 -0
  299. package/build/dist/chunks/NRBIXV7V.js +1 -0
  300. package/build/dist/chunks/{D6VP3N27.js → NSOEDRBU.js} +1 -1
  301. package/build/dist/chunks/{HL2MLC3O.js → NU4K3TEZ.js} +1 -1
  302. package/build/dist/chunks/NWSPC3NH.js +1 -0
  303. package/build/dist/chunks/{SDICP7BT.js → OE3CLZHR.js} +1 -1
  304. package/build/dist/chunks/{2NA6JLEC.js → OQVZVR2S.js} +1 -1
  305. package/build/dist/chunks/{D3OWLDVB.js → OVK4EEOD.js} +1 -1
  306. package/build/dist/chunks/{Q2VMH2LB.js → PARWLWXW.js} +1 -1
  307. package/build/dist/chunks/{DHXVYHT4.js → PTAWEHKB.js} +1 -1
  308. package/build/dist/chunks/{KQFDLDHL.js → PWBL4WKB.js} +1 -1
  309. package/build/dist/chunks/{55NX776C.js → PZHR4ITH.js} +1 -1
  310. package/build/dist/chunks/{ANQ43XJA.js → Q356HHCL.js} +1 -1
  311. package/build/dist/chunks/{OG5HRQU4.js → QRDDKA4I.js} +1 -1
  312. package/build/dist/chunks/{YR3QJVJQ.js → QXNPPCOU.js} +1 -1
  313. package/build/dist/chunks/{6NR7SVRO.js → QYYFRAWY.js} +1 -1
  314. package/build/dist/chunks/{7BTELNNI.js → R53P2K3C.js} +1 -1
  315. package/build/dist/chunks/{5HW6JKME.js → R7FXNZRM.js} +1 -1
  316. package/build/dist/chunks/{CCEWSOBT.js → R7QPJQP6.js} +1 -1
  317. package/build/dist/chunks/{SLSPWXR6.js → R7SXC74O.js} +1 -1
  318. package/build/dist/chunks/{IHGVCPVA.js → RAKUK5VR.js} +1 -1
  319. package/build/dist/chunks/{7LDAJ6BM.js → S3HNPTXA.js} +1 -1
  320. package/build/dist/chunks/SI6GCOAS.js +1 -0
  321. package/build/dist/chunks/{WIDTTGSH.js → SJPM5ST4.js} +1 -1
  322. package/build/dist/chunks/{GHDDVBPK.js → SJPYXNOK.js} +1 -1
  323. package/build/dist/chunks/{VY3P34PY.js → SKQGLGES.js} +1 -1
  324. package/build/dist/chunks/{ZT67OMLW.js → SOYQOE5P.js} +1 -1
  325. package/build/dist/chunks/{BFVLBENV.js → SQZRVIVF.js} +1 -1
  326. package/build/dist/chunks/{N6RL3SUZ.js → SSTROLQM.js} +1 -1
  327. package/build/dist/chunks/{IUXOUKQN.js → SXAIXD56.js} +1 -1
  328. package/build/dist/chunks/{TNRDCBGO.js → SXX3VTBP.js} +1 -1
  329. package/build/dist/chunks/{UXG67LH3.js → TCPPYBGQ.js} +1 -1
  330. package/build/dist/chunks/TFVWAYHY.js +1 -0
  331. package/build/dist/chunks/{67TJOOBI.js → TLJPVYRJ.js} +1 -1
  332. package/build/dist/chunks/{HRG2VVPY.js → TMGWXDCZ.js} +1 -1
  333. package/build/dist/chunks/{NMFVXBTL.js → TNSKEHPC.js} +1 -1
  334. package/build/dist/chunks/{C2FEXLMA.js → TQL7UDFL.js} +1 -1
  335. package/build/dist/chunks/{SQH7A4O3.js → TWCSCRFS.js} +1 -1
  336. package/build/dist/chunks/{2EDXKJ3B.js → TWSTOFN3.js} +1 -1
  337. package/build/dist/chunks/{JREVERSC.js → U3F6DDML.js} +1 -1
  338. package/build/dist/chunks/{6PU2CMQZ.js → UFS2RVEZ.js} +1 -1
  339. package/build/dist/chunks/{Y2IWPNEW.js → UNZRE3YU.js} +1 -1
  340. package/build/dist/chunks/{K463HFGC.js → USSOVTD5.js} +1 -1
  341. package/build/dist/chunks/V2OOOV6B.js +1 -0
  342. package/build/dist/chunks/{WQZLYX64.js → V5LTA42G.js} +1 -1
  343. package/build/dist/chunks/{TAI63P6E.js → VC2RCYQE.js} +1 -1
  344. package/build/dist/chunks/{2SNQWKHA.js → VFSRRDLY.js} +1 -1
  345. package/build/dist/chunks/{XW7RH7YY.js → VVEUJ36E.js} +1 -1
  346. package/build/dist/chunks/{5EHQM6DM.js → WQ6H62DM.js} +1 -1
  347. package/build/dist/chunks/{FSPNOVKB.js → WQQJ7UPJ.js} +1 -1
  348. package/build/dist/chunks/{F3TJCOVV.js → WTSMPDT5.js} +1 -1
  349. package/build/dist/chunks/{BYXBS45D.js → WVXW6VL3.js} +1 -1
  350. package/build/dist/chunks/WWFOYZT2.js +1 -0
  351. package/build/dist/chunks/WWNAGOCD.js +1 -0
  352. package/build/dist/chunks/X2NJSQUY.js +203 -0
  353. package/build/dist/chunks/{PJ65ZOQ7.js → XMA25DXR.js} +1 -1
  354. package/build/dist/chunks/{C3ZZSGSP.js → XQUPZ3GU.js} +1 -1
  355. package/build/dist/chunks/XQXLFF7Y.js +1 -0
  356. package/build/dist/chunks/XV2HQKND.js +1 -0
  357. package/build/dist/chunks/{QZM7CWZW.js → XVFLT275.js} +1 -1
  358. package/build/dist/chunks/{BV3AHLH5.js → XWEFKXKA.js} +1 -1
  359. package/build/dist/chunks/{QZTUMSQY.js → Y2KH6DCE.js} +1 -1
  360. package/build/dist/chunks/{GSI5COTD.js → YA5WWDEW.js} +1 -1
  361. package/build/dist/chunks/YHB55C5T.js +1 -0
  362. package/build/dist/chunks/YQUKU2LS.js +1 -0
  363. package/build/dist/chunks/{A25P24G2.js → YZSTP2E6.js} +1 -1
  364. package/build/dist/chunks/{T3NPRRTY.js → Z7RL4NGX.js} +1 -1
  365. package/build/dist/chunks/{LI7FYINH.js → ZT47KN7A.js} +1 -1
  366. package/build/dist/chunks/{QQWF6A4P.js → ZUG6MG46.js} +1 -1
  367. package/package.json +2 -2
  368. package/build/dist/chunks/46ZA2R5L.js +0 -1
  369. package/build/dist/chunks/6SCCW74G.js +0 -1
  370. package/build/dist/chunks/74BPMUAG.js +0 -1
  371. package/build/dist/chunks/7Z5IM2QZ.js +0 -1
  372. package/build/dist/chunks/DLIOZCEG.js +0 -1
  373. package/build/dist/chunks/EYYUWFUR.js +0 -1
  374. package/build/dist/chunks/G4PDM3MX.js +0 -1
  375. package/build/dist/chunks/JRO6WTK4.js +0 -1
  376. package/build/dist/chunks/NBRMUFJP.js +0 -1
  377. package/build/dist/chunks/NIOBE2LK.js +0 -1
  378. package/build/dist/chunks/OJMYESQU.js +0 -1
  379. package/build/dist/chunks/UMK564HS.js +0 -1
  380. package/build/dist/chunks/XPFVT2EA.js +0 -1
@@ -1 +1 @@
1
- import{d as Z}from"./TAI63P6E.js";import{e as ne}from"./5XFXH2JT.js";import{a as te,k as ae}from"./CBA776XQ.js";import{b as O,c as D}from"./2NA6JLEC.js";import{e as ee}from"./C3ZZSGSP.js";import{b as X}from"./AXYOJBX6.js";import{a as C}from"./6IM6A5VA.js";import{c as $}from"./MYBDO5SA.js";import{b as K}from"./UWOFA6GV.js";import{c as k,d as G,e as b,g as F,j as z,m as J,n as Q}from"./73N3TOJL.js";import{a as l,i as N}from"./XPFVT2EA.js";import{a as d}from"./5YS5V2LK.js";import{encodeFunctionData as se,erc20Abi as R,parseAbi as oe}from"viem";var B="https://api.beefy.finance/vaults",re="https://api.beefy.finance/fees",de="https://api.beefy.finance/apy/breakdown",ue="https://api.beefy.finance/tvl",ce="https://databarn.beefy.finance/api/v1/price",j=N[l].vaults.beefyTestedLpVault,M=oe(["function want() view returns (address)","function balance() view returns (uint256)","function getPricePerFullShare() view returns (uint256)","function strategy() view returns (address)","function paused() view returns (bool)","function deposit(uint256 amount)","function withdraw(uint256 shares)"]),q=K("Positive integer string in base units. Send quoted digits, never a JSON number.");function v(s){return z(s,"Provide a valid contract or wallet address.",G)}function _(s){return J(s,"The contract returned an invalid integer.")}function T(s){return Q(s,"Amount must be positive and fit in uint256.",{notString:"Amount must be a positive integer string in base units.",positive:!0})}function ie(s){if(typeof s!="number"||!Number.isInteger(s)||s<0||s>255)throw new d("Invalid token decimals.");return s}function I(s){return F(s,j.address)}function U(s){return te.some(f=>F(f.vault,s))}function L(s){return U(s)?"Use beefy_withdraw to exchange vault shares for CLM shares, redeem them into pair tokens with beefy_clm_withdraw, then convert the tokens to USDG with beefy_clm_swap.":"Use beefy_withdraw to exchange vault shares for the want token. Redeem that want into its pair tokens through a qualified Oak route or the Beefy app, then swap the received tokens to USDG."}function le(s){return!b(s)||!b(s.performance)?!1:[s.deposit,s.withdraw,s.performance.total].every(f=>typeof f=="number"&&Number.isFinite(f)&&f>=0&&f<=1)&&typeof s.lastUpdated=="number"&&Number.isSafeInteger(s.lastUpdated)&&s.lastUpdated>=0}var me=s=>{async function f(a){try{return await a()}catch(o){throw new d(s.plainError(o))}}function A(a,o){if(a.chainId!==void 0&&a.chainId!==l)throw new d("Beefy requires chain 4663.");for(let i of Object.keys(a))if(!["chainId",...o].includes(i))throw new d(`Unsupported Beefy input: ${i}.`)}async function P(){let a=await $(s.http,B,{headers:{"User-Agent":"Oak-Beefy/1.0"}},e=>Array.isArray(e)&&e.every(t=>b(t)&&typeof t.chain=="string")),o=new Set,i=new Set;return a.filter(e=>e.chain==="robinhood").map(e=>{if(typeof e.id!="string"||!e.id||typeof e.name!="string"||!e.name||e.type!=="standard"||!["active","paused","eol"].includes(String(e.status)))throw new d("The Beefy API returned an unexpected vault record.");let t=v(e.earnContractAddress);if(o.has(e.id)||i.has(t))throw new d("The Beefy API returned duplicate vault records.");return o.add(e.id),i.add(t),{id:e.id,name:e.name,type:"standard",chain:"robinhood",status:e.status,tokenAddress:v(e.tokenAddress),tokenDecimals:ie(e.tokenDecimals),earnContractAddress:t,assets:Array.isArray(e.assets)&&e.assets.every(r=>typeof r=="string")?e.assets:[],strategyType:typeof e.strategyTypeId=="string"?e.strategyTypeId:null,risks:b(e.risks)?Object.fromEntries(Object.entries(e.risks).filter(r=>typeof r[1]=="boolean")):{},lastHarvest:typeof e.lastHarvest=="number"&&Number.isSafeInteger(e.lastHarvest)&&e.lastHarvest>=0?e.lastHarvest:null}})}async function E(){return $(s.http,re,{headers:{"User-Agent":"Oak-Beefy/1.0"}},b)}function H(a,o){let i=a[o.id];if(!le(i))throw new d(`Beefy fees are unavailable for ${o.id}.`);return i}async function g(){let a=s.clientFor(l);if(await a.getChainId()!==l)throw new d("The Beefy endpoint must report chain 4663.");let o=_(await a.getBlockNumber()),i=(n,u)=>a.readContract({address:n,abi:M,functionName:u,blockNumber:o}),e=async(n,u)=>_(await a.readContract({address:n,abi:R,functionName:"balanceOf",args:[u],blockNumber:o}));async function t(n){let[u,p]=await Promise.all([a.readContract({address:n,abi:R,functionName:"symbol",blockNumber:o}),a.readContract({address:n,abi:R,functionName:"decimals",blockNumber:o})]);if(typeof u!="string"||!u.trim())throw new d("The contract returned invalid token metadata.");return{address:n,chainId:l,symbol:u,decimals:ie(p)}}async function r(n){let u=n.earnContractAddress,p=v(await i(u,"want"));if(p!==n.tokenAddress)throw new d(`Beefy API token and want() disagree for ${n.id}.`);let[h,y,m,c,w]=await Promise.all([t(p),t(u),i(u,"strategy"),i(u,"balance"),i(u,"getPricePerFullShare")]);if(h.decimals!==n.tokenDecimals)throw new d(`Beefy API and want decimals disagree for ${n.id}.`);let S=v(m),W=await i(S,"paused");if(typeof W!="boolean")throw new d("The strategy returned an invalid pause flag.");let x=_(w);if(x===0n)throw new d("The Beefy share price is zero.");return{want:h,shares:y,strategy:S,paused:W,managed:_(c),pricePerFullShare:x}}return{blockNumber:o,balanceOf:e,vaultState:r}}async function V(a){let o=v(a.vault),i=O(o),t=(await P()).find(r=>r.earnContractAddress===o);if(!t)throw new d("The selected vault is missing from the current Beefy inventory.");if(t.id!==i.id||t.tokenAddress!==i.tokenAddress.toLowerCase()||t.tokenDecimals!==i.tokenDecimals||t.type!==i.type)throw new d("The Beefy API and pinned vault type or want disagree.");return t}async function Y(a,o,i,e){let t=H(await E(),e),r=await s.preview(a,o),n=r.changes.map(u=>{let p=u.amount.startsWith("-"),h=p?u.amount.slice(1):u.amount;return`${p?"-":"+"}${s.formatAmount(h,u.token.decimals)} ${u.token.symbol} (${u.token.address}, chain ${u.token.chainId})`}).join("; ");return{txs:a,preview:r,summary:`${i} ${e.name}. ${n}. ${r.summary} Beefy API fees: deposit ${t.deposit*100}%, withdrawal ${t.withdraw*100}%, performance ${t.performance.total*100}% (updated ${t.lastUpdated} ms). These calls have no on-chain minimum output parameter; preview is an estimate, not a guaranteed amount. LP acquisition and conversion to USDG are separate.`}}return{tools:[{name:"beefy_list",inputSchema:{type:"object",properties:{chainId:{const:l}},additionalProperties:!1},execute:a=>f(async()=>{A(a,[]);let[o,i,e]=await Promise.all([P(),E(),g()]),t=[];for(let r of o){let n=await e.vaultState(r);t.push({id:r.id,name:r.name,vault:r.earnContractAddress,chainId:l,want:n.want,shares:n.shares,balance:{token:n.want,amount:n.managed.toString()},pricePerFullShare:{token:n.want,amount:n.pricePerFullShare.toString(),scale:"1000000000000000000",source:"getPricePerFullShare()"},apiStatus:{value:r.status,source:B},strategyPaused:{value:n.paused,source:"strategy.paused()",address:n.strategy,block:e.blockNumber.toString()},fees:{...H(i,r),source:re},forkQualified:I(r.earnContractAddress),qualification:I(r.earnContractAddress)?{source:j.source,block:j.block}:null,depositAvailable:O(r.earnContractAddress,!1)!==void 0&&r.status==="active"&&!n.paused,underlyingRoute:U(r.earnContractAddress)?{kind:"clm",read:"beefy_lp",acquire:"beefy_clm_deposit",redeem:"beefy_clm_withdraw",swap:"beefy_clm_swap"}:null,exitPath:L(r.earnContractAddress),block:e.blockNumber.toString()})}return{vaults:t,summary:"Direct want/LP vaults, not ERC-4626 or direct USDG. All pinned standard vaults support direct want deposits and share withdrawals after local code/type checks. For the seven active pinned CLM wants, start with beefy_lp and use the CLM acquisition/redemption tools. Fork qualification, API status and strategy pause are separate observations."}})},{name:"beefy_vault_info",inputSchema:{type:"object",properties:{vault:k,chainId:{const:l},historyBucket:{enum:["1h_1d","1h_1w","1h_1M","1d_1M","1d_1Y","1d_all"]}},required:["vault"],additionalProperties:!1},execute:a=>f(async()=>{A(a,["vault","historyBucket"]);let o=a.historyBucket??"1d_1M";if(!["1h_1d","1h_1w","1h_1M","1d_1M","1d_1Y","1d_all"].includes(String(o)))throw new d("Provide a supported Beefy historyBucket.");let i=v(a.vault),e=(await P()).find(m=>m.earnContractAddress===i);if(!e)throw new d("The selected vault is missing from the current Beefy inventory.");let t=new URL(ce);t.searchParams.set("product_key",`beefy:vault:robinhood:${i}`),t.searchParams.set("price_type","share_to_underlying"),t.searchParams.set("time_bucket",String(o));async function r(m,c){try{let w=await $(s.http,m,{headers:{"User-Agent":"Oak-Beefy/1.0"}},S=>S!==void 0);return{status:"available",source:m,value:c(w)}}catch(w){return{status:"unavailable",source:m,error:s.plainError(w)}}}let[n,u,p,h]=await Promise.all([r(de,m=>{if(!b(m))throw new d("Beefy APY is unavailable for this vault.");let c=m[e.id];if(!b(c))throw new d("Beefy APY is unavailable for this vault.");if(!Object.hasOwn(c,"totalApy")||Object.values(c).some(w=>typeof w!="number"||!Number.isFinite(w)||w<0))throw new d("Beefy returned invalid APY data.");return c}),r(ue,m=>{let c=b(m)?m[e.id]:void 0;if(typeof c!="number"||!Number.isFinite(c)||c<0)throw new d("Beefy TVL is unavailable for this vault.");return c}),r(t.toString(),m=>{if(!Array.isArray(m)||m.some(c=>!Array.isArray(c)||c.length<2||typeof c[0]!="string"||!Number.isFinite(Date.parse(c[0]))||typeof c[1]!="string"||!/^\d+(\.\d+)?$/.test(c[1])))throw new d("Beefy returned invalid share-price history.");return m.map(c=>({timestamp:c[0],shareToUnderlying:c[1]}))}),g()]),y=await h.vaultState(e);return{id:e.id,name:e.name,vault:e.earnContractAddress,chainId:l,want:y.want,strategy:{address:y.strategy,type:e.strategyType,assets:e.assets,paused:y.paused,lastHarvest:e.lastHarvest,source:B},risk:{status:Object.keys(e.risks).length?"available":"unavailable",flags:e.risks,source:B,guide:"https://docs.beefy.finance/safety/risk-checklist",summary:"API risk flags are assessments, not guarantees. Uncorrelated LP assets can suffer impermanent loss; vaults also expose strategy, token and contract risks."},apy:n,tvl:{...u,currency:"USD"},history:p,forkQualified:I(e.earnContractAddress),block:h.blockNumber.toString(),app:`https://app.beefy.finance/vault/${encodeURIComponent(e.id)}`,summary:"APY is a fractional annual estimate, not a promised return. Share-price history is not a wallet profit calculation. Missing analytics remain unavailable."}})},{name:"beefy_deposit",inputSchema:{type:"object",properties:{vault:k,token:k,amount:q,minSharesOut:q,slippageBps:{type:"integer",minimum:0,maximum:9999},chainId:{const:l}},required:["vault","token","amount"],additionalProperties:!1},execute:(a,o)=>f(async()=>{if(A(a,["vault","token","amount","minSharesOut","slippageBps"]),C(o),a.slippageBps!==void 0&&(!Number.isInteger(a.slippageBps)||Number(a.slippageBps)<0||Number(a.slippageBps)>9999))throw new d("slippageBps must be an integer from 0 to 9999.");a.minSharesOut!==void 0&&T(a.minSharesOut);let i=T(a.amount),e=v(a.token),t=await V(a),r=await g();await D(s.clientFor(l),t.earnContractAddress,r.blockNumber);let n=await r.vaultState(t);if(t.status!=="active")throw new d(`The Beefy API marks this vault ${t.status}; deposits are unavailable. ${L(t.earnContractAddress)}`);if(n.paused)throw new d(`The Beefy strategy is paused; deposits are unavailable. ${L(t.earnContractAddress)}`);if(e!==n.want.address)throw new d(`This vault needs ${n.want.symbol} (${n.want.address}, chain 4663), not the supplied token. ${U(t.earnContractAddress)?"Read beefy_lp, acquire the pair tokens with beefy_clm_swap and mint the want with beefy_clm_deposit first.":"No USDG zap is provided."}`);if(await r.balanceOf(n.want.address,o)<i)throw new d(`Insufficient ${n.want.symbol} want balance.`);let u=[s.approval(n.want.address,t.earnContractAddress,i.toString(),l),s.unsignedTx({to:t.earnContractAddress,data:se({abi:M,functionName:"deposit",args:[i]}),value:"0",chainId:l,description:`Deposit ${i} want base units into ${t.name}.`})],p=await Y(u,o,"Deposit into",t),h=i*10n**18n/n.pricePerFullShare,y=a.minSharesOut===void 0?h*BigInt(1e4-Number(a.slippageBps??50))/10000n:T(a.minSharesOut);if(y<=0n||y>h)throw new d("Minimum shares must be positive and no greater than the current forecast.");let m={token:{address:N[l].tokens.WETH.address,symbol:"WETH",decimals:18,chainId:l},from:n.strategy,recipient:o,optional:!0,includedInMinimumShares:!1},c=`Share forecast ${h}; minimum ${y} share base units (local pre-sign simulation check only; deposit(uint256) has no on-chain minimum). Optional WETH harvest rewards from strategy ${n.strategy} may vary or be zero and are not part of that floor.`;return{...p,harvestReward:m,minimumShares:y.toString(),summary:`${p.summary} ${c}`,preview:{...p.preview,summary:`${p.preview.summary} ${c}`}}})},{name:"beefy_withdraw",inputSchema:{type:"object",properties:{vault:k,shares:{anyOf:[q,{const:"all"}]},chainId:{const:l}},required:["vault","shares"],additionalProperties:!1},execute:(a,o)=>f(async()=>{A(a,["vault","shares"]),C(o);let i=a.shares==="all"?void 0:T(a.shares),e=await V(a),t=await g();await D(s.clientFor(l),e.earnContractAddress,t.blockNumber),await t.vaultState(e);let r=await t.balanceOf(e.earnContractAddress,o),n=i??r;if(n===0n||n>r)throw new d("Provide a positive share amount no greater than your current Beefy share balance.");let u=[s.unsignedTx({to:e.earnContractAddress,data:se({abi:M,functionName:"withdraw",args:[n]}),value:"0",chainId:l,description:`Withdraw ${n} share base units from ${e.name} to the calling wallet.`})];return Y(u,o,"Withdraw from",e)})}],positions:a=>f(async()=>{C(a);let[o,i]=await Promise.all([P(),g()]),e=[];for(let t of o){let r=await i.balanceOf(t.earnContractAddress,a);if(r===0n)continue;let n=await i.vaultState(t);e.push({module:"beefy",id:t.earnContractAddress,chainId:l,assets:[{token:n.want,amount:(r*n.pricePerFullShare/10n**18n).toString()}],description:`${t.name}: ${s.formatAmount(r.toString(),n.shares.decimals)} ${n.shares.symbol} shares (${t.earnContractAddress}); want estimate before withdrawal fees at block ${i.blockNumber}. API ${t.status}; strategy paused ${n.paused}. ${I(t.earnContractAddress)?"Recorded fork-qualified vault.":U(t.earnContractAddress)?"Direct want/share writes supported; CLM acquisition and redemption have separate qualification.":"Direct want/share writes supported after code/type checks; no recorded fork round trip yet."}`})}return e})}};function Be(s){return X("beefy",[me(s),ne(s),ae(s),Z(s),ee(s)])}export{me as a,Be as b};
1
+ import{d as Z}from"./VC2RCYQE.js";import{e as ne}from"./NATG6YA6.js";import{a as te,k as ae}from"./5VHH5PW3.js";import{b as O,c as D}from"./OQVZVR2S.js";import{e as ee}from"./XQUPZ3GU.js";import{b as X}from"./AXYOJBX6.js";import{a as C}from"./6IM6A5VA.js";import{c as $}from"./MYBDO5SA.js";import{b as K}from"./UWOFA6GV.js";import{c as k,d as G,e as b,g as F,j as z,m as J,n as Q}from"./73N3TOJL.js";import{a as l,i as N}from"./G6HCV67X.js";import{a as d}from"./5YS5V2LK.js";import{encodeFunctionData as se,erc20Abi as R,parseAbi as oe}from"viem";var B="https://api.beefy.finance/vaults",re="https://api.beefy.finance/fees",de="https://api.beefy.finance/apy/breakdown",ue="https://api.beefy.finance/tvl",ce="https://databarn.beefy.finance/api/v1/price",j=N[l].vaults.beefyTestedLpVault,M=oe(["function want() view returns (address)","function balance() view returns (uint256)","function getPricePerFullShare() view returns (uint256)","function strategy() view returns (address)","function paused() view returns (bool)","function deposit(uint256 amount)","function withdraw(uint256 shares)"]),q=K("Positive integer string in base units. Send quoted digits, never a JSON number.");function v(s){return z(s,"Provide a valid contract or wallet address.",G)}function _(s){return J(s,"The contract returned an invalid integer.")}function T(s){return Q(s,"Amount must be positive and fit in uint256.",{notString:"Amount must be a positive integer string in base units.",positive:!0})}function ie(s){if(typeof s!="number"||!Number.isInteger(s)||s<0||s>255)throw new d("Invalid token decimals.");return s}function I(s){return F(s,j.address)}function U(s){return te.some(f=>F(f.vault,s))}function L(s){return U(s)?"Use beefy_withdraw to exchange vault shares for CLM shares, redeem them into pair tokens with beefy_clm_withdraw, then convert the tokens to USDG with beefy_clm_swap.":"Use beefy_withdraw to exchange vault shares for the want token. Redeem that want into its pair tokens through a qualified Oak route or the Beefy app, then swap the received tokens to USDG."}function le(s){return!b(s)||!b(s.performance)?!1:[s.deposit,s.withdraw,s.performance.total].every(f=>typeof f=="number"&&Number.isFinite(f)&&f>=0&&f<=1)&&typeof s.lastUpdated=="number"&&Number.isSafeInteger(s.lastUpdated)&&s.lastUpdated>=0}var me=s=>{async function f(a){try{return await a()}catch(o){throw new d(s.plainError(o))}}function A(a,o){if(a.chainId!==void 0&&a.chainId!==l)throw new d("Beefy requires chain 4663.");for(let i of Object.keys(a))if(!["chainId",...o].includes(i))throw new d(`Unsupported Beefy input: ${i}.`)}async function P(){let a=await $(s.http,B,{headers:{"User-Agent":"Oak-Beefy/1.0"}},e=>Array.isArray(e)&&e.every(t=>b(t)&&typeof t.chain=="string")),o=new Set,i=new Set;return a.filter(e=>e.chain==="robinhood").map(e=>{if(typeof e.id!="string"||!e.id||typeof e.name!="string"||!e.name||e.type!=="standard"||!["active","paused","eol"].includes(String(e.status)))throw new d("The Beefy API returned an unexpected vault record.");let t=v(e.earnContractAddress);if(o.has(e.id)||i.has(t))throw new d("The Beefy API returned duplicate vault records.");return o.add(e.id),i.add(t),{id:e.id,name:e.name,type:"standard",chain:"robinhood",status:e.status,tokenAddress:v(e.tokenAddress),tokenDecimals:ie(e.tokenDecimals),earnContractAddress:t,assets:Array.isArray(e.assets)&&e.assets.every(r=>typeof r=="string")?e.assets:[],strategyType:typeof e.strategyTypeId=="string"?e.strategyTypeId:null,risks:b(e.risks)?Object.fromEntries(Object.entries(e.risks).filter(r=>typeof r[1]=="boolean")):{},lastHarvest:typeof e.lastHarvest=="number"&&Number.isSafeInteger(e.lastHarvest)&&e.lastHarvest>=0?e.lastHarvest:null}})}async function E(){return $(s.http,re,{headers:{"User-Agent":"Oak-Beefy/1.0"}},b)}function H(a,o){let i=a[o.id];if(!le(i))throw new d(`Beefy fees are unavailable for ${o.id}.`);return i}async function g(){let a=s.clientFor(l);if(await a.getChainId()!==l)throw new d("The Beefy endpoint must report chain 4663.");let o=_(await a.getBlockNumber()),i=(n,u)=>a.readContract({address:n,abi:M,functionName:u,blockNumber:o}),e=async(n,u)=>_(await a.readContract({address:n,abi:R,functionName:"balanceOf",args:[u],blockNumber:o}));async function t(n){let[u,p]=await Promise.all([a.readContract({address:n,abi:R,functionName:"symbol",blockNumber:o}),a.readContract({address:n,abi:R,functionName:"decimals",blockNumber:o})]);if(typeof u!="string"||!u.trim())throw new d("The contract returned invalid token metadata.");return{address:n,chainId:l,symbol:u,decimals:ie(p)}}async function r(n){let u=n.earnContractAddress,p=v(await i(u,"want"));if(p!==n.tokenAddress)throw new d(`Beefy API token and want() disagree for ${n.id}.`);let[h,y,m,c,w]=await Promise.all([t(p),t(u),i(u,"strategy"),i(u,"balance"),i(u,"getPricePerFullShare")]);if(h.decimals!==n.tokenDecimals)throw new d(`Beefy API and want decimals disagree for ${n.id}.`);let S=v(m),W=await i(S,"paused");if(typeof W!="boolean")throw new d("The strategy returned an invalid pause flag.");let x=_(w);if(x===0n)throw new d("The Beefy share price is zero.");return{want:h,shares:y,strategy:S,paused:W,managed:_(c),pricePerFullShare:x}}return{blockNumber:o,balanceOf:e,vaultState:r}}async function V(a){let o=v(a.vault),i=O(o),t=(await P()).find(r=>r.earnContractAddress===o);if(!t)throw new d("The selected vault is missing from the current Beefy inventory.");if(t.id!==i.id||t.tokenAddress!==i.tokenAddress.toLowerCase()||t.tokenDecimals!==i.tokenDecimals||t.type!==i.type)throw new d("The Beefy API and pinned vault type or want disagree.");return t}async function Y(a,o,i,e){let t=H(await E(),e),r=await s.preview(a,o),n=r.changes.map(u=>{let p=u.amount.startsWith("-"),h=p?u.amount.slice(1):u.amount;return`${p?"-":"+"}${s.formatAmount(h,u.token.decimals)} ${u.token.symbol} (${u.token.address}, chain ${u.token.chainId})`}).join("; ");return{txs:a,preview:r,summary:`${i} ${e.name}. ${n}. ${r.summary} Beefy API fees: deposit ${t.deposit*100}%, withdrawal ${t.withdraw*100}%, performance ${t.performance.total*100}% (updated ${t.lastUpdated} ms). These calls have no on-chain minimum output parameter; preview is an estimate, not a guaranteed amount. LP acquisition and conversion to USDG are separate.`}}return{tools:[{name:"beefy_list",inputSchema:{type:"object",properties:{chainId:{const:l}},additionalProperties:!1},execute:a=>f(async()=>{A(a,[]);let[o,i,e]=await Promise.all([P(),E(),g()]),t=[];for(let r of o){let n=await e.vaultState(r);t.push({id:r.id,name:r.name,vault:r.earnContractAddress,chainId:l,want:n.want,shares:n.shares,balance:{token:n.want,amount:n.managed.toString()},pricePerFullShare:{token:n.want,amount:n.pricePerFullShare.toString(),scale:"1000000000000000000",source:"getPricePerFullShare()"},apiStatus:{value:r.status,source:B},strategyPaused:{value:n.paused,source:"strategy.paused()",address:n.strategy,block:e.blockNumber.toString()},fees:{...H(i,r),source:re},forkQualified:I(r.earnContractAddress),qualification:I(r.earnContractAddress)?{source:j.source,block:j.block}:null,depositAvailable:O(r.earnContractAddress,!1)!==void 0&&r.status==="active"&&!n.paused,underlyingRoute:U(r.earnContractAddress)?{kind:"clm",read:"beefy_lp",acquire:"beefy_clm_deposit",redeem:"beefy_clm_withdraw",swap:"beefy_clm_swap"}:null,exitPath:L(r.earnContractAddress),block:e.blockNumber.toString()})}return{vaults:t,summary:"Direct want/LP vaults, not ERC-4626 or direct USDG. All pinned standard vaults support direct want deposits and share withdrawals after local code/type checks. For the seven active pinned CLM wants, start with beefy_lp and use the CLM acquisition/redemption tools. Fork qualification, API status and strategy pause are separate observations."}})},{name:"beefy_vault_info",inputSchema:{type:"object",properties:{vault:k,chainId:{const:l},historyBucket:{enum:["1h_1d","1h_1w","1h_1M","1d_1M","1d_1Y","1d_all"]}},required:["vault"],additionalProperties:!1},execute:a=>f(async()=>{A(a,["vault","historyBucket"]);let o=a.historyBucket??"1d_1M";if(!["1h_1d","1h_1w","1h_1M","1d_1M","1d_1Y","1d_all"].includes(String(o)))throw new d("Provide a supported Beefy historyBucket.");let i=v(a.vault),e=(await P()).find(m=>m.earnContractAddress===i);if(!e)throw new d("The selected vault is missing from the current Beefy inventory.");let t=new URL(ce);t.searchParams.set("product_key",`beefy:vault:robinhood:${i}`),t.searchParams.set("price_type","share_to_underlying"),t.searchParams.set("time_bucket",String(o));async function r(m,c){try{let w=await $(s.http,m,{headers:{"User-Agent":"Oak-Beefy/1.0"}},S=>S!==void 0);return{status:"available",source:m,value:c(w)}}catch(w){return{status:"unavailable",source:m,error:s.plainError(w)}}}let[n,u,p,h]=await Promise.all([r(de,m=>{if(!b(m))throw new d("Beefy APY is unavailable for this vault.");let c=m[e.id];if(!b(c))throw new d("Beefy APY is unavailable for this vault.");if(!Object.hasOwn(c,"totalApy")||Object.values(c).some(w=>typeof w!="number"||!Number.isFinite(w)||w<0))throw new d("Beefy returned invalid APY data.");return c}),r(ue,m=>{let c=b(m)?m[e.id]:void 0;if(typeof c!="number"||!Number.isFinite(c)||c<0)throw new d("Beefy TVL is unavailable for this vault.");return c}),r(t.toString(),m=>{if(!Array.isArray(m)||m.some(c=>!Array.isArray(c)||c.length<2||typeof c[0]!="string"||!Number.isFinite(Date.parse(c[0]))||typeof c[1]!="string"||!/^\d+(\.\d+)?$/.test(c[1])))throw new d("Beefy returned invalid share-price history.");return m.map(c=>({timestamp:c[0],shareToUnderlying:c[1]}))}),g()]),y=await h.vaultState(e);return{id:e.id,name:e.name,vault:e.earnContractAddress,chainId:l,want:y.want,strategy:{address:y.strategy,type:e.strategyType,assets:e.assets,paused:y.paused,lastHarvest:e.lastHarvest,source:B},risk:{status:Object.keys(e.risks).length?"available":"unavailable",flags:e.risks,source:B,guide:"https://docs.beefy.finance/safety/risk-checklist",summary:"API risk flags are assessments, not guarantees. Uncorrelated LP assets can suffer impermanent loss; vaults also expose strategy, token and contract risks."},apy:n,tvl:{...u,currency:"USD"},history:p,forkQualified:I(e.earnContractAddress),block:h.blockNumber.toString(),app:`https://app.beefy.finance/vault/${encodeURIComponent(e.id)}`,summary:"APY is a fractional annual estimate, not a promised return. Share-price history is not a wallet profit calculation. Missing analytics remain unavailable."}})},{name:"beefy_deposit",inputSchema:{type:"object",properties:{vault:k,token:k,amount:q,minSharesOut:q,slippageBps:{type:"integer",minimum:0,maximum:9999},chainId:{const:l}},required:["vault","token","amount"],additionalProperties:!1},execute:(a,o)=>f(async()=>{if(A(a,["vault","token","amount","minSharesOut","slippageBps"]),C(o),a.slippageBps!==void 0&&(!Number.isInteger(a.slippageBps)||Number(a.slippageBps)<0||Number(a.slippageBps)>9999))throw new d("slippageBps must be an integer from 0 to 9999.");a.minSharesOut!==void 0&&T(a.minSharesOut);let i=T(a.amount),e=v(a.token),t=await V(a),r=await g();await D(s.clientFor(l),t.earnContractAddress,r.blockNumber);let n=await r.vaultState(t);if(t.status!=="active")throw new d(`The Beefy API marks this vault ${t.status}; deposits are unavailable. ${L(t.earnContractAddress)}`);if(n.paused)throw new d(`The Beefy strategy is paused; deposits are unavailable. ${L(t.earnContractAddress)}`);if(e!==n.want.address)throw new d(`This vault needs ${n.want.symbol} (${n.want.address}, chain 4663), not the supplied token. ${U(t.earnContractAddress)?"Read beefy_lp, acquire the pair tokens with beefy_clm_swap and mint the want with beefy_clm_deposit first.":"No USDG zap is provided."}`);if(await r.balanceOf(n.want.address,o)<i)throw new d(`Insufficient ${n.want.symbol} want balance.`);let u=[s.approval(n.want.address,t.earnContractAddress,i.toString(),l),s.unsignedTx({to:t.earnContractAddress,data:se({abi:M,functionName:"deposit",args:[i]}),value:"0",chainId:l,description:`Deposit ${i} want base units into ${t.name}.`})],p=await Y(u,o,"Deposit into",t),h=i*10n**18n/n.pricePerFullShare,y=a.minSharesOut===void 0?h*BigInt(1e4-Number(a.slippageBps??50))/10000n:T(a.minSharesOut);if(y<=0n||y>h)throw new d("Minimum shares must be positive and no greater than the current forecast.");let m={token:{address:N[l].tokens.WETH.address,symbol:"WETH",decimals:18,chainId:l},from:n.strategy,recipient:o,optional:!0,includedInMinimumShares:!1},c=`Share forecast ${h}; minimum ${y} share base units (local pre-sign simulation check only; deposit(uint256) has no on-chain minimum). Optional WETH harvest rewards from strategy ${n.strategy} may vary or be zero and are not part of that floor.`;return{...p,harvestReward:m,minimumShares:y.toString(),summary:`${p.summary} ${c}`,preview:{...p.preview,summary:`${p.preview.summary} ${c}`}}})},{name:"beefy_withdraw",inputSchema:{type:"object",properties:{vault:k,shares:{anyOf:[q,{const:"all"}]},chainId:{const:l}},required:["vault","shares"],additionalProperties:!1},execute:(a,o)=>f(async()=>{A(a,["vault","shares"]),C(o);let i=a.shares==="all"?void 0:T(a.shares),e=await V(a),t=await g();await D(s.clientFor(l),e.earnContractAddress,t.blockNumber),await t.vaultState(e);let r=await t.balanceOf(e.earnContractAddress,o),n=i??r;if(n===0n||n>r)throw new d("Provide a positive share amount no greater than your current Beefy share balance.");let u=[s.unsignedTx({to:e.earnContractAddress,data:se({abi:M,functionName:"withdraw",args:[n]}),value:"0",chainId:l,description:`Withdraw ${n} share base units from ${e.name} to the calling wallet.`})];return Y(u,o,"Withdraw from",e)})}],positions:a=>f(async()=>{C(a);let[o,i]=await Promise.all([P(),g()]),e=[];for(let t of o){let r=await i.balanceOf(t.earnContractAddress,a);if(r===0n)continue;let n=await i.vaultState(t);e.push({module:"beefy",id:t.earnContractAddress,chainId:l,assets:[{token:n.want,amount:(r*n.pricePerFullShare/10n**18n).toString()}],description:`${t.name}: ${s.formatAmount(r.toString(),n.shares.decimals)} ${n.shares.symbol} shares (${t.earnContractAddress}); want estimate before withdrawal fees at block ${i.blockNumber}. API ${t.status}; strategy paused ${n.paused}. ${I(t.earnContractAddress)?"Recorded fork-qualified vault.":U(t.earnContractAddress)?"Direct want/share writes supported; CLM acquisition and redemption have separate qualification.":"Direct want/share writes supported after code/type checks; no recorded fork round trip yet."}`})}return e})}};function Be(s){return X("beefy",[me(s),ne(s),ae(s),Z(s),ee(s)])}export{me as a,Be as b};
@@ -1,2 +1,2 @@
1
- import{b as Ne}from"./AXYOJBX6.js";import{a as _e}from"./MYBDO5SA.js";import{a as V}from"./UWOFA6GV.js";import{c as H,d as $e,e as G,i as Se,l as Te,m as Ae}from"./73N3TOJL.js";import{a as p,d as W,i as F,j as B}from"./XPFVT2EA.js";import{a as i}from"./5YS5V2LK.js";import{encodeFunctionData as $,getAddress as Z,keccak256 as cn,parseAbi as j,stringToHex as ln,zeroAddress as q,zeroHash as Le}from"viem";import{namehash as un}from"viem/ens";import{encodeFunctionData as Re,getAddress as en,keccak256 as nn,parseAbi as ne,stringToHex as tn,zeroAddress as Be,zeroHash as Ue}from"viem";import{normalize as rn}from"viem/ens";import{getAddress as Ce,keccak256 as Ie,namehash as De,parseAbi as Fe,parseAbiItem as se,stringToHex as ze}from"viem";var M=F[p].hoodag,Je=se("event Transfer(address indexed from,address indexed to,uint256 indexed tokenId)"),We=se("event NameRegistered(string name,bytes32 indexed label,address indexed owner,uint256 cost,uint256 expires)"),Ve=se("event NewOwner(bytes32 indexed node,bytes32 indexed label,address owner)"),ae=Fe(["function ownerOf(uint256) view returns (address)","function nameExpires(uint256) view returns (uint256)","function owner(bytes32) view returns (address)"]),ie=50000n,Ke=5000n,Xe=10000000n,xe=2e3,Qe=200,de={toBlock:V("Inclusive final block for this scan. Omit for latest. Owned names scan all history by default; an explicit cursor scans the preceding 50000-block window."),fromBlock:V("Optional inclusive first block for a narrower scan; at most 50000 blocks per call.")};async function K(a,s,f,h){if(--h.remaining<0)throw new i("hood.ag scan exceeded its 512-request budget. Use an archive RPC with wider log ranges, or provide fromBlock/toBlock windows. No empty holdings result was inferred.");try{let l=await a(s,f);if(l.length>xe)throw new i("hood.ag returned too many logs in one page. Narrow fromBlock/toBlock.");return l}catch(l){let u=l,d=!1,c=new Set;for(;u&&typeof u=="object"&&!c.has(u);){c.add(u);let o=u;d||=/block range|range cap|narrow the block range|query spans/i.test(String(o.message??"")),u=o.cause}if(f-s<1000n||l instanceof i||!d)throw l;let w=(s+f)/2n,t=[...await K(a,s,w,h),...await K(a,w+1n,f,h)];if(t.length>xe)throw new i("hood.ag returned too many logs in one page. Narrow fromBlock/toBlock.");return t}}async function Ye(a,s,f){for(let c of["fromBlock","toBlock"])if(s[c]!==void 0&&(typeof s[c]!="string"||!/^[0-9]{1,20}$/.test(s[c])))throw new i(`Provide ${c} as a decimal block-number string.`);if(await a.getChainId()!==p)throw new i("hood.ag chain reads require chain 4663.");let h=await a.getBlock({blockTag:"latest"});if(h.number===null)throw new i("hood.ag latest block is unavailable.");let l=s.toBlock,u=l===void 0?h.number:BigInt(l);if(u>h.number)throw new i("hood.ag toBlock cannot be in the future.");let d=f?0n:s.fromBlock===void 0?u>=ie?u-ie+1n:0n:BigInt(s.fromBlock);if(d>u||!f&&u-d>=ie)throw new i("hood.ag scans require an ordered range of at most 50000 blocks.");return{head:h,toBlock:u,fromBlock:d}}async function Ze(a,s,f){let h=f===void 0?void 0:b(f,"wallet"),l=a.clientFor(p),u=h!==void 0&&s.fromBlock===void 0&&s.toBlock===void 0,{head:d,fromBlock:c,toBlock:w}=await Ye(l,s,u),t=u?Xe:Ke,o=new Map,e=(m,y,S=null)=>{let k=m.toString();if(o.set(k,{tokenId:m,label:y,name:S??o.get(k)?.name??null}),o.size>Qe)throw new i("hood.ag scan found over 200 candidates. Narrow fromBlock/toBlock. No empty collection was inferred.")},n=0,r={remaining:512};for(let m=c;m<=w;m+=t){let y=m+t-1n<w?m+t-1n:w,S=[];for(let k of[M.registrarController.address,M.registrar.address])S.push(...await K((C,A)=>l.getLogs({address:k,event:We,...h?{args:{owner:h}}:{},fromBlock:C,toBlock:A,strict:!0}),m,y,r));for(let k of S){if(k.removed)continue;let{label:C,name:A}=U(k.args.name),T=Ie(ze(C));if(T!==k.args.label)throw new i("hood.ag registration name does not match its on-chain label hash.");e(BigInt(T),T,A),n++}if(h){let k=await K((A,T)=>l.getLogs({address:M.registrar.address,event:Je,args:{to:h},fromBlock:A,toBlock:T,strict:!0}),m,y,r);for(let A of k)A.removed||e(A.args.tokenId,`0x${A.args.tokenId.toString(16).padStart(64,"0")}`);let C=u?[]:await K((A,T)=>l.getLogs({address:M.registry.address,event:Ve,args:{node:De("hood")},fromBlock:A,toBlock:T,strict:!0}),m,y,r);for(let A of C)!A.removed&&Ce(A.args.owner)===h&&e(BigInt(A.args.label),A.args.label)}}let g=[];for(let m of o.values()){let y=P(await l.readContract({address:M.registrar.address,abi:ae,functionName:"nameExpires",args:[m.tokenId],blockNumber:d.number}),"name expiry");if(y<=d.timestamp)continue;let S=b(await l.readContract({address:M.registrar.address,abi:ae,functionName:"ownerOf",args:[m.tokenId],blockNumber:d.number}),"name owner");if(h&&S!==h)continue;let k=Ie(`0x${De("hood").slice(2)}${m.label.slice(2)}`),C=Ce(await l.readContract({address:M.registry.address,abi:ae,functionName:"owner",args:[k],blockNumber:d.number}));g.push({name:m.name,tokenId:m.tokenId.toString(),owner:S,registryOwner:C,expiresAt:y.toString()})}return g.sort((m,y)=>BigInt(m.tokenId)<BigInt(y.tokenId)?-1:1),{chainId:p,wallet:h??null,source:"on-chain registry, registrar NFT Transfer and registrar/controller NameRegistered events",snapshotBlock:d.number.toString(),names:g,registrationEvents:n,ownershipComplete:h!==void 0&&c===0n,labelsComplete:g.every(m=>m.name!==null),scan:{fromBlock:c.toString(),toBlock:w.toString(),logPageBlocks:t.toString(),nextToBlock:c>0n?(c-1n).toString():null},incomplete:c>0n,warning:`${c>0n?"Only names discovered in this event window are shown, with current ownership and expiry. An empty page is not proof of no owned names. Continue with nextToBlock; merge by tokenId.":h?"Ownership discovery covers registrar history from genesis, with current ownership and expiry.":"Discovery covers the stated registrar/controller history, with current ownership and expiry."} A null name means no plaintext registration was found at the pinned registrar/controller addresses; it does not make ownership discovery incomplete. Look up the tokenId in the registrar explorer or original registration transaction; a label hash cannot be reversed. No global count, market volume or complete catalogue is inferred.`}}async function ce(a,s,f){try{return await Ze(a,s,f)}catch(h){throw h instanceof i?h:new i("hood.ag chain discovery is unavailable. Retry with a working archive RPC or configured OAK_RPC_FALLBACK_URLS. No empty holdings result was inferred.")}}async function le(a){let s=a.body?.getReader();if(!s)throw new i("hood.ag returned an empty response.");let f=new TextDecoder,h=0,l="";try{for(;;){let{value:u,done:d}=await s.read();if(d)break;if(h+=u.byteLength,h>2e6)throw await s.cancel(),new i("hood.ag returned too much data. Narrow the request.");l+=f.decode(u,{stream:!0})}return l+f.decode()}finally{s.releaseLock()}}function Pe(a){let s=l=>{let u=l.limit===void 0?20:l.limit,d=l.offset===void 0?0:l.offset;if(typeof u!="number"||!Number.isInteger(u)||u<1||u>50||typeof d!="number"||!Number.isSafeInteger(d)||d<0||d>1e4)throw new i("Provide limit 1..50 and offset 0..10000 as whole numbers.");return{limit:u,offset:d}},f={limit:{type:"integer",minimum:1,maximum:50,default:20},offset:{type:"integer",minimum:0,maximum:1e4,default:0}};async function h(l){let u=await a.http(l,{method:"GET",credentials:"omit",redirect:"error",signal:AbortSignal.timeout(1e4),headers:{accept:"application/json"}});if(u.status===410)throw new i("The published hood.ag index route is retired (HTTP 410). Read known names on-chain and ask HoodAG for its replacement index interface.");if(!u.ok)throw new i(`hood.ag discovery returned HTTP ${u.status}. Please try again.`);let d;try{d=JSON.parse(await le(u))}catch(c){throw c instanceof i?c:new i("hood.ag returned malformed discovery JSON.")}if(G(d)&&(d.error||d.stale===!0))throw new i("The hood.ag index is stale or unavailable. Do not treat this response as an empty catalogue.");return d}return[v(a,"browse",{operation:{type:"string",enum:["names","listings","activity","stats","ethusd","buybacks","leaderboard","traders"]},metric:{type:"string",enum:["realized","buyvol"],description:"Required only for traders; historical ETH-denominated data, never a return promise."},...f,...de},["operation"],async l=>{let{offset:u,limit:d}=s(l),c=l.operation;if(typeof c!="string"||!["names","listings","activity","stats","ethusd","buybacks","leaderboard","traders"].includes(c))throw new i("Choose a published hood.ag discovery operation.");if(c==="traders"?!["realized","buyvol"].includes(String(l.metric)):l.metric!==void 0)throw new i("Use metric realized or buyvol only with the traders operation.");if((l.toBlock!==void 0||l.fromBlock!==void 0)&&c!=="names"&&c!=="stats")throw new i("toBlock is available only for chain names/stats discovery.");let w=`https://www.hood.ag/api/${c}${c==="traders"?`?by=${l.metric}`:""}`,t;try{if(l.toBlock!==void 0||l.fromBlock!==void 0)throw new i("Requested a chain event window.");t=await h(w)}catch(n){if(c!=="names"&&c!=="stats")throw n;let r=await ce(a,l),{names:g,...m}=r;return{...m,operation:c,data:c==="names"?{names:g.slice(u,u+d)}:{observedActiveNames:g.length,registrationEventsInWindow:r.registrationEvents},incomplete:r.incomplete||c==="names"&&(u>0||u+d<g.length),page:{offset:u,limit:d,windowRows:g.length,nextOffset:u+d<g.length?u+d:null},providerWarning:l.toBlock===void 0&&l.fromBlock===void 0?"The hood.ag vendor index is stale or unavailable; showing chain observations for the stated window.":"Showing the requested chain window."}}if(!G(t)||!Object.keys(t).length)throw new i("hood.ag returned an unexpected discovery response.");let o={names:"names",listings:"listings",activity:"items",leaderboard:"rows",traders:"rows"}[c];if(o&&!Array.isArray(t[o]))throw new i("hood.ag returned an invalid discovery list.");let e=o?t[o]:void 0;return{chainId:p,operation:c,data:e?{...t,[o]:e.slice(u,u+d)}:t,source:w,untrusted:!0,...e?{page:{offset:u,limit:d,providerRows:e.length,nextOffset:u+d<e.length?u+d:null}}:{},warning:"This is a provider index, with unverified chain completeness. Re-read name ownership, availability, rent and listing terms on-chain before acting. Historical market data is not a prediction or a recommendation."}}),v(a,"owned_names",{address:{type:"string",description:"Wallet to inspect; defaults to the connected wallet."},...f,...de},[],async(l,u)=>{let{offset:d,limit:c}=s(l),w=await ce(a,l,l.address===void 0?u:String(l.address));return{...w,names:w.names.slice(d,d+c),incomplete:w.incomplete||d>0||d+c<w.names.length,page:{offset:d,limit:c,windowRows:w.names.length,nextOffset:d+c<w.names.length?d+c:null}}}),v(a,"registration_quote",{name:{type:"string"},years:{type:"integer",minimum:1,maximum:100,default:1}},["name"],async l=>{let{label:u,name:d}=U(l.name),c=l.years??1;if(typeof c!="number"||!Number.isInteger(c)||c<1||c>100)throw new i("Provide years as an integer from 1 to 100.");let w=`https://agents.hood.ag/quote?name=${encodeURIComponent(u)}&years=${c}`,t=await a.http(w,{method:"GET",credentials:"omit",redirect:"error",signal:AbortSignal.timeout(1e4),headers:{accept:"application/json"}});if(!t.ok)throw new i(`hood.ag registration quoting returned HTTP ${t.status}. Please try again.`);let o;try{o=JSON.parse(await le(t))}catch(e){throw e instanceof i?e:new i("hood.ag returned malformed quote JSON.")}if(!G(o)||!G(o.rails)||!Object.keys(o.rails).length)throw new i("hood.ag returned an unexpected registration quote.");return{chainId:p,name:d,years:c,data:o,source:w,untrusted:!0,warning:"Indicative x402 quote only. No HTTP registration or payment is made. Direct USDG registration remains available through hoodag_register."}}),v(a,"social_read",{operation:{type:"string",enum:["get_feed","get_profile","get_thread","search"]},parameters:{type:"object",description:"get_feed: type latest/trending and limit 1..50; get_profile: user; get_thread: post_id; search: query."}},["operation"],async l=>{let u=l.operation,d=l.parameters??{};if(typeof u!="string"||!["get_feed","get_profile","get_thread","search"].includes(u)||!G(d))throw new i("Choose a documented public social read and its parameters.");let c={get_feed:["type","limit"],get_profile:["user"],get_thread:["post_id"],search:["query"]};if(Object.keys(d).some(n=>!c[u].includes(n)))throw new i("Unsupported hood social read parameter.");let w={...d};if(u==="get_feed"){if(w.type??="latest",w.limit??=20,!["latest","trending"].includes(String(w.type))||typeof w.limit!="number"||!Number.isInteger(w.limit)||w.limit<1||w.limit>50)throw new i("Choose latest or trending and a whole limit from 1 to 50.")}else{let n=c[u][0];if(typeof w[n]!="string"||!w[n].trim()||w[n].length>200)throw new i(`Provide ${n} as text of at most 200 characters.`)}let t;try{t=await a.http("https://social.hood.ag/api/mcp",{method:"POST",credentials:"omit",redirect:"error",signal:AbortSignal.timeout(1e4),headers:{"content-type":"application/json",accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:u,arguments:w}})})}catch(n){throw n instanceof _e&&n.response.status>=500?new i(`hood.ag social service is down (HTTP ${n.response.status}). Use hoodag_owned_names, hoodag_name_info or hoodag_browse names/stats for chain reads.`):n}if(t.status>=500)throw new i(`hood.ag social service is down (HTTP ${t.status}). Use hoodag_owned_names, hoodag_name_info or hoodag_browse names/stats for chain reads.`);if(!t.ok)throw new i(`hood social returned HTTP ${t.status}. Please try again.`);let o=await le(t),e;try{t.headers.get("content-type")?.includes("text/event-stream")?e=o.split(/\r?\n\r?\n/).map(r=>r.split(/\r?\n/).filter(g=>g.startsWith("data:")).map(g=>g.slice(5).trimStart()).join(`
1
+ import{b as Ne}from"./AXYOJBX6.js";import{a as _e}from"./MYBDO5SA.js";import{a as V}from"./UWOFA6GV.js";import{c as H,d as $e,e as G,i as Se,l as Te,m as Ae}from"./73N3TOJL.js";import{a as p,d as W,i as F,j as B}from"./G6HCV67X.js";import{a as i}from"./5YS5V2LK.js";import{encodeFunctionData as $,getAddress as Z,keccak256 as cn,parseAbi as j,stringToHex as ln,zeroAddress as q,zeroHash as Le}from"viem";import{namehash as un}from"viem/ens";import{encodeFunctionData as Re,getAddress as en,keccak256 as nn,parseAbi as ne,stringToHex as tn,zeroAddress as Be,zeroHash as Ue}from"viem";import{normalize as rn}from"viem/ens";import{getAddress as Ce,keccak256 as Ie,namehash as De,parseAbi as Fe,parseAbiItem as se,stringToHex as ze}from"viem";var M=F[p].hoodag,Je=se("event Transfer(address indexed from,address indexed to,uint256 indexed tokenId)"),We=se("event NameRegistered(string name,bytes32 indexed label,address indexed owner,uint256 cost,uint256 expires)"),Ve=se("event NewOwner(bytes32 indexed node,bytes32 indexed label,address owner)"),ae=Fe(["function ownerOf(uint256) view returns (address)","function nameExpires(uint256) view returns (uint256)","function owner(bytes32) view returns (address)"]),ie=50000n,Ke=5000n,Xe=10000000n,xe=2e3,Qe=200,de={toBlock:V("Inclusive final block for this scan. Omit for latest. Owned names scan all history by default; an explicit cursor scans the preceding 50000-block window."),fromBlock:V("Optional inclusive first block for a narrower scan; at most 50000 blocks per call.")};async function K(a,s,f,h){if(--h.remaining<0)throw new i("hood.ag scan exceeded its 512-request budget. Use an archive RPC with wider log ranges, or provide fromBlock/toBlock windows. No empty holdings result was inferred.");try{let l=await a(s,f);if(l.length>xe)throw new i("hood.ag returned too many logs in one page. Narrow fromBlock/toBlock.");return l}catch(l){let u=l,d=!1,c=new Set;for(;u&&typeof u=="object"&&!c.has(u);){c.add(u);let o=u;d||=/block range|range cap|narrow the block range|query spans/i.test(String(o.message??"")),u=o.cause}if(f-s<1000n||l instanceof i||!d)throw l;let w=(s+f)/2n,t=[...await K(a,s,w,h),...await K(a,w+1n,f,h)];if(t.length>xe)throw new i("hood.ag returned too many logs in one page. Narrow fromBlock/toBlock.");return t}}async function Ye(a,s,f){for(let c of["fromBlock","toBlock"])if(s[c]!==void 0&&(typeof s[c]!="string"||!/^[0-9]{1,20}$/.test(s[c])))throw new i(`Provide ${c} as a decimal block-number string.`);if(await a.getChainId()!==p)throw new i("hood.ag chain reads require chain 4663.");let h=await a.getBlock({blockTag:"latest"});if(h.number===null)throw new i("hood.ag latest block is unavailable.");let l=s.toBlock,u=l===void 0?h.number:BigInt(l);if(u>h.number)throw new i("hood.ag toBlock cannot be in the future.");let d=f?0n:s.fromBlock===void 0?u>=ie?u-ie+1n:0n:BigInt(s.fromBlock);if(d>u||!f&&u-d>=ie)throw new i("hood.ag scans require an ordered range of at most 50000 blocks.");return{head:h,toBlock:u,fromBlock:d}}async function Ze(a,s,f){let h=f===void 0?void 0:b(f,"wallet"),l=a.clientFor(p),u=h!==void 0&&s.fromBlock===void 0&&s.toBlock===void 0,{head:d,fromBlock:c,toBlock:w}=await Ye(l,s,u),t=u?Xe:Ke,o=new Map,e=(m,y,S=null)=>{let k=m.toString();if(o.set(k,{tokenId:m,label:y,name:S??o.get(k)?.name??null}),o.size>Qe)throw new i("hood.ag scan found over 200 candidates. Narrow fromBlock/toBlock. No empty collection was inferred.")},n=0,r={remaining:512};for(let m=c;m<=w;m+=t){let y=m+t-1n<w?m+t-1n:w,S=[];for(let k of[M.registrarController.address,M.registrar.address])S.push(...await K((C,A)=>l.getLogs({address:k,event:We,...h?{args:{owner:h}}:{},fromBlock:C,toBlock:A,strict:!0}),m,y,r));for(let k of S){if(k.removed)continue;let{label:C,name:A}=U(k.args.name),T=Ie(ze(C));if(T!==k.args.label)throw new i("hood.ag registration name does not match its on-chain label hash.");e(BigInt(T),T,A),n++}if(h){let k=await K((A,T)=>l.getLogs({address:M.registrar.address,event:Je,args:{to:h},fromBlock:A,toBlock:T,strict:!0}),m,y,r);for(let A of k)A.removed||e(A.args.tokenId,`0x${A.args.tokenId.toString(16).padStart(64,"0")}`);let C=u?[]:await K((A,T)=>l.getLogs({address:M.registry.address,event:Ve,args:{node:De("hood")},fromBlock:A,toBlock:T,strict:!0}),m,y,r);for(let A of C)!A.removed&&Ce(A.args.owner)===h&&e(BigInt(A.args.label),A.args.label)}}let g=[];for(let m of o.values()){let y=P(await l.readContract({address:M.registrar.address,abi:ae,functionName:"nameExpires",args:[m.tokenId],blockNumber:d.number}),"name expiry");if(y<=d.timestamp)continue;let S=b(await l.readContract({address:M.registrar.address,abi:ae,functionName:"ownerOf",args:[m.tokenId],blockNumber:d.number}),"name owner");if(h&&S!==h)continue;let k=Ie(`0x${De("hood").slice(2)}${m.label.slice(2)}`),C=Ce(await l.readContract({address:M.registry.address,abi:ae,functionName:"owner",args:[k],blockNumber:d.number}));g.push({name:m.name,tokenId:m.tokenId.toString(),owner:S,registryOwner:C,expiresAt:y.toString()})}return g.sort((m,y)=>BigInt(m.tokenId)<BigInt(y.tokenId)?-1:1),{chainId:p,wallet:h??null,source:"on-chain registry, registrar NFT Transfer and registrar/controller NameRegistered events",snapshotBlock:d.number.toString(),names:g,registrationEvents:n,ownershipComplete:h!==void 0&&c===0n,labelsComplete:g.every(m=>m.name!==null),scan:{fromBlock:c.toString(),toBlock:w.toString(),logPageBlocks:t.toString(),nextToBlock:c>0n?(c-1n).toString():null},incomplete:c>0n,warning:`${c>0n?"Only names discovered in this event window are shown, with current ownership and expiry. An empty page is not proof of no owned names. Continue with nextToBlock; merge by tokenId.":h?"Ownership discovery covers registrar history from genesis, with current ownership and expiry.":"Discovery covers the stated registrar/controller history, with current ownership and expiry."} A null name means no plaintext registration was found at the pinned registrar/controller addresses; it does not make ownership discovery incomplete. Look up the tokenId in the registrar explorer or original registration transaction; a label hash cannot be reversed. No global count, market volume or complete catalogue is inferred.`}}async function ce(a,s,f){try{return await Ze(a,s,f)}catch(h){throw h instanceof i?h:new i("hood.ag chain discovery is unavailable. Retry with a working archive RPC or configured OAK_RPC_FALLBACK_URLS. No empty holdings result was inferred.")}}async function le(a){let s=a.body?.getReader();if(!s)throw new i("hood.ag returned an empty response.");let f=new TextDecoder,h=0,l="";try{for(;;){let{value:u,done:d}=await s.read();if(d)break;if(h+=u.byteLength,h>2e6)throw await s.cancel(),new i("hood.ag returned too much data. Narrow the request.");l+=f.decode(u,{stream:!0})}return l+f.decode()}finally{s.releaseLock()}}function Pe(a){let s=l=>{let u=l.limit===void 0?20:l.limit,d=l.offset===void 0?0:l.offset;if(typeof u!="number"||!Number.isInteger(u)||u<1||u>50||typeof d!="number"||!Number.isSafeInteger(d)||d<0||d>1e4)throw new i("Provide limit 1..50 and offset 0..10000 as whole numbers.");return{limit:u,offset:d}},f={limit:{type:"integer",minimum:1,maximum:50,default:20},offset:{type:"integer",minimum:0,maximum:1e4,default:0}};async function h(l){let u=await a.http(l,{method:"GET",credentials:"omit",redirect:"error",signal:AbortSignal.timeout(1e4),headers:{accept:"application/json"}});if(u.status===410)throw new i("The published hood.ag index route is retired (HTTP 410). Read known names on-chain and ask HoodAG for its replacement index interface.");if(!u.ok)throw new i(`hood.ag discovery returned HTTP ${u.status}. Please try again.`);let d;try{d=JSON.parse(await le(u))}catch(c){throw c instanceof i?c:new i("hood.ag returned malformed discovery JSON.")}if(G(d)&&(d.error||d.stale===!0))throw new i("The hood.ag index is stale or unavailable. Do not treat this response as an empty catalogue.");return d}return[v(a,"browse",{operation:{type:"string",enum:["names","listings","activity","stats","ethusd","buybacks","leaderboard","traders"]},metric:{type:"string",enum:["realized","buyvol"],description:"Required only for traders; historical ETH-denominated data, never a return promise."},...f,...de},["operation"],async l=>{let{offset:u,limit:d}=s(l),c=l.operation;if(typeof c!="string"||!["names","listings","activity","stats","ethusd","buybacks","leaderboard","traders"].includes(c))throw new i("Choose a published hood.ag discovery operation.");if(c==="traders"?!["realized","buyvol"].includes(String(l.metric)):l.metric!==void 0)throw new i("Use metric realized or buyvol only with the traders operation.");if((l.toBlock!==void 0||l.fromBlock!==void 0)&&c!=="names"&&c!=="stats")throw new i("toBlock is available only for chain names/stats discovery.");let w=`https://www.hood.ag/api/${c}${c==="traders"?`?by=${l.metric}`:""}`,t;try{if(l.toBlock!==void 0||l.fromBlock!==void 0)throw new i("Requested a chain event window.");t=await h(w)}catch(n){if(c!=="names"&&c!=="stats")throw n;let r=await ce(a,l),{names:g,...m}=r;return{...m,operation:c,data:c==="names"?{names:g.slice(u,u+d)}:{observedActiveNames:g.length,registrationEventsInWindow:r.registrationEvents},incomplete:r.incomplete||c==="names"&&(u>0||u+d<g.length),page:{offset:u,limit:d,windowRows:g.length,nextOffset:u+d<g.length?u+d:null},providerWarning:l.toBlock===void 0&&l.fromBlock===void 0?"The hood.ag vendor index is stale or unavailable; showing chain observations for the stated window.":"Showing the requested chain window."}}if(!G(t)||!Object.keys(t).length)throw new i("hood.ag returned an unexpected discovery response.");let o={names:"names",listings:"listings",activity:"items",leaderboard:"rows",traders:"rows"}[c];if(o&&!Array.isArray(t[o]))throw new i("hood.ag returned an invalid discovery list.");let e=o?t[o]:void 0;return{chainId:p,operation:c,data:e?{...t,[o]:e.slice(u,u+d)}:t,source:w,untrusted:!0,...e?{page:{offset:u,limit:d,providerRows:e.length,nextOffset:u+d<e.length?u+d:null}}:{},warning:"This is a provider index, with unverified chain completeness. Re-read name ownership, availability, rent and listing terms on-chain before acting. Historical market data is not a prediction or a recommendation."}}),v(a,"owned_names",{address:{type:"string",description:"Wallet to inspect; defaults to the connected wallet."},...f,...de},[],async(l,u)=>{let{offset:d,limit:c}=s(l),w=await ce(a,l,l.address===void 0?u:String(l.address));return{...w,names:w.names.slice(d,d+c),incomplete:w.incomplete||d>0||d+c<w.names.length,page:{offset:d,limit:c,windowRows:w.names.length,nextOffset:d+c<w.names.length?d+c:null}}}),v(a,"registration_quote",{name:{type:"string"},years:{type:"integer",minimum:1,maximum:100,default:1}},["name"],async l=>{let{label:u,name:d}=U(l.name),c=l.years??1;if(typeof c!="number"||!Number.isInteger(c)||c<1||c>100)throw new i("Provide years as an integer from 1 to 100.");let w=`https://agents.hood.ag/quote?name=${encodeURIComponent(u)}&years=${c}`,t=await a.http(w,{method:"GET",credentials:"omit",redirect:"error",signal:AbortSignal.timeout(1e4),headers:{accept:"application/json"}});if(!t.ok)throw new i(`hood.ag registration quoting returned HTTP ${t.status}. Please try again.`);let o;try{o=JSON.parse(await le(t))}catch(e){throw e instanceof i?e:new i("hood.ag returned malformed quote JSON.")}if(!G(o)||!G(o.rails)||!Object.keys(o.rails).length)throw new i("hood.ag returned an unexpected registration quote.");return{chainId:p,name:d,years:c,data:o,source:w,untrusted:!0,warning:"Indicative x402 quote only. No HTTP registration or payment is made. Direct USDG registration remains available through hoodag_register."}}),v(a,"social_read",{operation:{type:"string",enum:["get_feed","get_profile","get_thread","search"]},parameters:{type:"object",description:"get_feed: type latest/trending and limit 1..50; get_profile: user; get_thread: post_id; search: query."}},["operation"],async l=>{let u=l.operation,d=l.parameters??{};if(typeof u!="string"||!["get_feed","get_profile","get_thread","search"].includes(u)||!G(d))throw new i("Choose a documented public social read and its parameters.");let c={get_feed:["type","limit"],get_profile:["user"],get_thread:["post_id"],search:["query"]};if(Object.keys(d).some(n=>!c[u].includes(n)))throw new i("Unsupported hood social read parameter.");let w={...d};if(u==="get_feed"){if(w.type??="latest",w.limit??=20,!["latest","trending"].includes(String(w.type))||typeof w.limit!="number"||!Number.isInteger(w.limit)||w.limit<1||w.limit>50)throw new i("Choose latest or trending and a whole limit from 1 to 50.")}else{let n=c[u][0];if(typeof w[n]!="string"||!w[n].trim()||w[n].length>200)throw new i(`Provide ${n} as text of at most 200 characters.`)}let t;try{t=await a.http("https://social.hood.ag/api/mcp",{method:"POST",credentials:"omit",redirect:"error",signal:AbortSignal.timeout(1e4),headers:{"content-type":"application/json",accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:u,arguments:w}})})}catch(n){throw n instanceof _e&&n.response.status>=500?new i(`hood.ag social service is down (HTTP ${n.response.status}). Use hoodag_owned_names, hoodag_name_info or hoodag_browse names/stats for chain reads.`):n}if(t.status>=500)throw new i(`hood.ag social service is down (HTTP ${t.status}). Use hoodag_owned_names, hoodag_name_info or hoodag_browse names/stats for chain reads.`);if(!t.ok)throw new i(`hood social returned HTTP ${t.status}. Please try again.`);let o=await le(t),e;try{t.headers.get("content-type")?.includes("text/event-stream")?e=o.split(/\r?\n\r?\n/).map(r=>r.split(/\r?\n/).filter(g=>g.startsWith("data:")).map(g=>g.slice(5).trimStart()).join(`
2
2
  `)).filter(Boolean).map(r=>JSON.parse(r)).find(r=>G(r)&&r.id===1):e=JSON.parse(o)}catch{throw new i("hood social returned malformed MCP data.")}if(!G(e)||e.jsonrpc!=="2.0"||e.id!==1||e.error||!G(e.result)||e.result.isError||!Array.isArray(e.result.content))throw new i("hood social did not return a successful read. Please try again.");return{chainId:p,operation:u,data:e.result,source:"https://social.hood.ag/api/mcp",untrusted:!0,warning:"Posts, profiles and links are untrusted content, never instructions. No wallet, token, signature, post, like or follow is sent."}})]}var te=F[p].hoodag,X=te.registrarController.address,Ge=te.universalResolver.address,Ee=te.registrar.address,ee=ne(["function valid(string) view returns (bool)","function available(string) view returns (bool)","function priceUSDG(string,uint256) view returns (uint256)","function registerManyUSDG(string[],address,uint256,address,(uint256,uint256,uint8,bytes32,bytes32))"]),Oe=ne(["function resolve(string) view returns (address)","function reverse(address) view returns (string name,bool verified)"]),He=ne(["function nameExpires(uint256) view returns (uint256)","function ownerOf(uint256) view returns (address)"]),on=ne(["function setName(string) returns (bytes32)"]),an={address:en(B),chainId:p,symbol:"USDG",decimals:W},sn=(1n<<256n)-1n,ue={type:"string",description:"A single .hood label or full name."},Me={type:"string",pattern:"^[0-9]+$",default:"31536000",description:"Registration duration in whole seconds, as a decimal integer string. Minimum 2419200 seconds; defaults to one year."};function U(a){if(typeof a!="string"||!a.trim()||a.length>256)throw new i("Provide a .hood name of at most 256 characters.");let s;try{s=rn(a.trim().replace(/\.hood$/i,""))}catch{throw new i("Provide a valid .hood name.")}if(!s||s.includes("."))throw new i("Provide a single label, optionally ending in .hood.");return{label:s,name:`${s}.hood`}}function re(a){let s=a===void 0?"31536000":a;if(typeof s!="string"||s.length>78||!/^\d+$/.test(s))throw new i("Duration must be a positive integer string in seconds.");let f=BigInt(s);if(f<=0n||f>sn)throw new i("Duration must fit a positive uint256 number of seconds.");if(f<2419200n)throw new i("Duration must be at least 2419200 seconds.");return f}function b(a,s){let f=Se(a,`Invalid ${s} address.`,$e);return Te(f,`Provide a non-zero ${s} address.`)}function me(a,s){if(typeof a!="boolean")throw new i(`The ${s} read returned an invalid response.`);return a}function P(a,s){return Ae(a,`The ${s} read returned an invalid response.`)}function v(a,s,f,h,l,u={}){return{name:`hoodag_${s}`,inputSchema:{type:"object",properties:f,required:h,additionalProperties:!1,...u},execute:async(d,c)=>{try{if(!d||typeof d!="object"||Array.isArray(d))throw new i("Provide tool arguments as an object.");if(Object.keys(d).some(w=>!Object.hasOwn(f,w)))throw new i("Unsupported hood.ag argument.");return await l(d,c)}catch(w){throw new i(a.plainError(w))}}}}var dn=a=>{async function s(d){let{label:c,name:w}=U(d.name),t=re(d.duration),o=a.clientFor(p);if(!me(await o.readContract({address:X,abi:ee,functionName:"valid",args:[c]}),"label validity"))throw new i("This .hood label is not valid.");let n=me(await o.readContract({address:X,abi:ee,functionName:"available",args:[c]}),"availability");return{label:c,name:w,duration:t,client:o,available:n}}async function f(d,c){let w=P(await a.clientFor(p).readContract({address:X,abi:ee,functionName:"priceUSDG",args:[d,c]}),"USDG rent");if(w===0n)throw new i("The current USDG rent is zero; a registration quote is unavailable.");return{token:{...an},amount:w.toString()}}let h=v(a,"register",{name:ue,duration:Me},["name"],async(d,c)=>{let w=b(c,"wallet"),{label:t,name:o,duration:e,available:n}=await s(d);if(!n)throw new i(`${o} is not available.`);let r=await f(t,e),g=[a.approval(B,X,r.amount,p),a.unsignedTx({to:X,chainId:p,value:"0",data:Re({abi:ee,functionName:"registerManyUSDG",args:[[t],w,e,Be,[0n,0n,0,Ue,Ue]]}),description:`Register ${o} for ${e} seconds using ${r.amount} USDG base units (6 decimals).`}),a.unsignedTx({to:te.reverseRegistrar.address,chainId:p,value:"0",data:Re({abi:on,functionName:"setName",args:[o]}),description:`Set ${o} as the wallet's primary reverse name.`})],m=await a.preview(g,w),y=m.changes.map(({token:S,amount:k})=>{let C=k.startsWith("-"),A=a.formatAmount(C?k.slice(1):k,S.decimals);return`${C?"-":"+"}${A} ${S.symbol} (${S.address}, chain ${S.chainId}, ${S.decimals} decimals)`});return{txs:g,rent:r,duration:e.toString(),preview:m,summary:`Prepare registration of ${o} for ${e} seconds, then set its primary reverse name. Quoted rent: ${r.amount} USDG base units (${B}, chain ${p}, ${W} decimals). ${m.summary}${y.length?` Token changes: ${y.join("; ")}.`:""}`}}),l=v(a,"resolve",{name:ue,address:{type:"string",description:"Wallet address for reverse resolution."}},[],async d=>{if(d.name!==void 0==(d.address!==void 0))throw new i("Provide exactly one name or wallet address to resolve.");if(d.name!==void 0){let{name:o}=U(d.name),e=await a.clientFor(p).readContract({address:Ge,abi:Oe,functionName:"resolve",args:[o]});if(typeof e=="string"&&e.toLowerCase()===Be)throw new i(`No address is set for ${o}.`);return{name:o,address:b(e,"resolved"),chainId:p}}let c=b(d.address,"wallet"),w=await a.clientFor(p).readContract({address:Ge,abi:Oe,functionName:"reverse",args:[c]});if(!Array.isArray(w)||w.length!==2||typeof w[0]!="string")throw new i("The reverse read returned an invalid response.");let t=me(w[1],"reverse verification");if(!w[0])throw new i("No reverse name is set for this wallet.");return{address:c,name:w[0],verified:t,chainId:p}},{oneOf:[{required:["name"]},{required:["address"]}]}),u=v(a,"name_info",{name:ue,duration:Me},["name"],async d=>{let{label:c,name:w,duration:t,available:o,client:e}=await s(d),n=await f(c,t),r=BigInt(nn(tn(c))),g=P(await e.readContract({address:Ee,abi:He,functionName:"nameExpires",args:[r]}),"name expiry"),m=o?null:b(await e.readContract({address:Ee,abi:He,functionName:"ownerOf",args:[r]}),"name owner");return{name:w,label:c,chainId:p,available:o,tokenId:r.toString(),owner:m,expiresAt:g.toString(),duration:t.toString(),rent:n}});return{tools:[h,l,u,...qe(a),...Pe(a)]}},Rn=a=>Ne("hoodag",[dn(a)]);var x=F[p].hoodag,_=x.registrarController.address,E=x.registrar.address,L=x.publicResolver.address,I="0xd37C9f7D1a59bceB2BDa47325f14f5789f1176a1",D=j(["function valid(string) view returns (bool)","function available(string) view returns (bool)","function priceUSDG(string,uint256) view returns (uint256)","function renewUSDG(string,uint256,(uint256,uint256,uint8,bytes32,bytes32))","function price(string,uint256) view returns (uint256)","function renew(string,uint256) payable","function minCommitAge() view returns (uint256)","function makeCommitment(string,address,bytes32) pure returns (bytes32)","function commit(bytes32)","function register(string,address,uint256,bytes32) payable","function registerMany(string[],address,uint256,address) payable","function registerManyUSDG(string[],address,uint256,address,(uint256,uint256,uint8,bytes32,bytes32))","function refDiscountBps() view returns (uint256)","function refRewardBps() view returns (uint256)"]),O=j(["function ownerOf(uint256) view returns (address)","function getApproved(uint256) view returns (address)","function nameExpires(uint256) view returns (uint256)","function reclaim(uint256,address)","function approve(address,uint256)","function safeTransferFrom(address,address,uint256)"]),fe=j(["function owner(bytes32) view returns (address)","function resolver(bytes32) view returns (address)"]),we=j(["function resolve(string) view returns (address)","function reverse(address) view returns (string,bool)","function resolveText(string,string) view returns (string)"]),Q=j(["function setAddr(bytes32,address)","function setText(bytes32,string,string)","function contenthash(bytes32) view returns (bytes)","function setContenthash(bytes32,bytes)"]),ge=j(["function setName(string) returns (bytes32)"]),R=j(["function getListing(uint256) view returns (address seller,uint256 price,bool active)","function listingCurrency(uint256) view returns (uint8)","function usdg() view returns (address)","function feeBps() view returns (uint256)","function refDiscountBps() view returns (uint256)","function refRewardBps() view returns (uint256)","function list(uint256,uint256)","function listUSDG(uint256,uint256)","function setPrice(uint256,uint256)","function unlist(uint256)","function buy(uint256,uint256) payable","function buy(uint256,uint256,address) payable","function buyUSDG(uint256,uint256,address,(uint256,uint256,uint8,bytes32,bytes32))"]),N={type:"string",description:"One label or full .hood name."},he={type:"string",pattern:"^[0-9]+$",default:"31536000",description:"Whole seconds, minimum 2419200."},je={type:"string",minLength:1,maxLength:128,description:"Text key, e.g. avatar, url, com.twitter."},pe=V("Positive base-unit integer string; ETH has 18 decimals, USDG 6."),ye=[0n,0n,0,Le,Le],be={address:Z(B),chainId:p,symbol:"USDG",decimals:W},oe={address:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",chainId:p,symbol:"ETH",decimals:18};function ve(a,s,f,h=!1){if(typeof a!="string"||!h&&!a.trim()||a.length>f||[...a].some(l=>l.charCodeAt(0)<32||l.charCodeAt(0)===127))throw new i(`Provide ${s} as text of at most ${f} characters.`);return a}function ke(a){if(typeof a!="string"||!/^\d+$/.test(a)||a.length>78)throw new i("Provide a positive base-unit integer string.");let s=BigInt(a);if(s===0n||s>=1n<<256n)throw new i("Amount must fit a positive uint256.");return s}function Y(a,s){if(typeof a!="string"||!/^0x(?:[a-fA-F0-9]{2})*$/.test(a)||a.length>8194||s!==void 0&&a.length!==2+s*2)throw new i("Provide valid hex bytes of the required length.");return a}function z(a){let s=U(a);return{...s,tokenId:BigInt(cn(ln(s.label))),node:un(s.name)}}function qe(a){let s=()=>a.clientFor(p),f=(t,o,e,n="0")=>a.unsignedTx({to:t,data:o,description:e,value:n,chainId:p});async function h(t,o,e,n={}){let r=await a.preview(t,o);return{txs:t,preview:r,...n,summary:`${e} ${r.summary}`}}async function l(t,o){let e=b(o,"wallet"),n=z(t);if(b(await s().readContract({address:E,abi:O,functionName:"ownerOf",args:[n.tokenId]}),"name owner")!==e)throw new i("This wallet does not own this .hood name. Ask its current owner to manage it.");return{...n,owner:e}}async function u(t,o){let e=await l(t,o);if(b(await s().readContract({address:x.registry.address,abi:fe,functionName:"owner",args:[e.node]}),"registry owner")!==e.owner)throw new i("The registry owner differs from this wallet. Run hoodag_reclaim before editing records.");if(b(await s().readContract({address:x.registry.address,abi:fe,functionName:"resolver",args:[e.node]}),"resolver")!==Z(L))throw new i("This name uses another resolver. Its record-writing interface is not configured in Oak.");return e}async function d(t,o,e,n){let r=z(t),g=re(o);if(e!=="USDG"&&e!=="ETH")throw new i("Choose USDG or ETH.");if(await s().readContract({address:_,abi:D,functionName:"valid",args:[r.label]})!==!0)throw new i("This .hood label is not valid.");let y=await s().readContract({address:_,abi:D,functionName:"available",args:[r.label]});if(typeof y!="boolean")throw new i("The availability read returned an invalid response.");if(n&&y)throw new i("This name is available for registration; it cannot be renewed.");if(!n&&!y)throw new i(`${r.name} is not available.`);let S=P(await s().readContract({address:_,abi:D,functionName:e==="USDG"?"priceUSDG":"price",args:[r.label,g]}),"rent");if(!S)throw new i("The current rent is zero; a quote is unavailable.");return{...r,duration:g,cost:S,token:e==="USDG"?be:oe}}async function c(t){let o=z(t),e=await s().readContract({address:I,abi:R,functionName:"getListing",args:[o.tokenId]});if(!Array.isArray(e)||e.length!==3||typeof e[2]!="boolean")throw new i("The marketplace listing read returned an invalid response.");let n=P(e[1],"listing price"),r=typeof e[0]=="string"?Z(e[0]):null;if(!r||e[2]&&(r===q||n===0n))throw new i("The marketplace listing read returned an invalid seller or price.");let g=await s().readContract({address:I,abi:R,functionName:"listingCurrency",args:[o.tokenId]});if(g!==0&&g!==1)throw new i("This marketplace currency is not configured in Oak.");if(g===1&&b(await s().readContract({address:I,abi:R,functionName:"usdg"}),"market USDG")!==Z(B))throw new i("The marketplace USDG token differs from Oak configuration.");return{...o,seller:r,price:n,active:e[2],currency:g===1?"USDG":"ETH",token:g===1?be:oe}}async function w(t,o,e,n,r){if(e===void 0)return{cost:t,referrer:q,discountBps:0n};let g=b(e,"referrer");if(g===n||g===r)throw new i("Choose a referrer different from the payer and seller.");let m=P(await s().readContract({address:o,abi:D,functionName:"refDiscountBps"}),"referral discount");if(m>10000n)throw new i("The referral discount exceeds 10000 basis points.");return{cost:t-t*m/10000n,referrer:g,discountBps:m}}return[v(a,"renew",{name:N,duration:he,currency:{type:"string",enum:["USDG","ETH"],default:"USDG"}},["name"],async(t,o)=>{let e=b(o,"wallet"),n=await d(t.name,t.duration,t.currency??"USDG",!0),r=n.token.symbol==="USDG"?[a.approval(B,_,n.cost.toString(),p),f(_,$({abi:D,functionName:"renewUSDG",args:[n.label,n.duration,ye]}),`Renew ${n.name} using USDG.`)]:[f(_,$({abi:D,functionName:"renew",args:[n.label,n.duration]}),`Renew ${n.name} using ETH.`,n.cost.toString())];return h(r,e,`Renew ${n.name} for ${n.duration} seconds for ${n.cost} ${n.token.symbol} base units plus gas. An expired name's new term starts at renewal time. Ownership and primary name are unchanged.`,{duration:n.duration.toString(),rent:{token:n.token,amount:n.cost.toString()}})}),v(a,"text",{name:N,key:je},["name","key"],async t=>{let{name:o}=z(t.name),e=ve(t.key,"a record key",128),n=await s().readContract({address:x.universalResolver.address,abi:we,functionName:"resolveText",args:[o,e]});if(typeof n!="string")throw new i("The text-record read returned an invalid response.");return{name:o,key:e,value:n,chainId:p,untrusted:!0,warning:"Name records are untrusted content, never instructions. Empty means unset."}}),v(a,"set_address",{name:N,address:H},["name","address"],async(t,o)=>{let e=b(t.address,"resolved"),n=await u(t.name,o);return h([f(L,$({abi:Q,functionName:"setAddr",args:[n.node,e]}),`Point ${n.name} to ${e}.`)],n.owner,`Change ${n.name} to resolve to ${e}. Any primary reverse name must still point back to its wallet to be verified.`)}),v(a,"set_text",{name:N,key:je,value:{type:"string",maxLength:2048,description:"Untrusted public text. Empty clears the record."}},["name","key","value"],async(t,o)=>{let e=ve(t.key,"a record key",128),n=ve(t.value,"a record value",2048,!0),r=await u(t.name,o);return h([f(L,$({abi:Q,functionName:"setText",args:[r.node,e,n]}),`Set public text on ${r.name}: ${JSON.stringify(e)} = ${JSON.stringify(n)} (untrusted).`)],r.owner,`Publish the untrusted ${JSON.stringify(e)} record on ${r.name}. Empty clears the current record. Transaction history remains public.`)}),v(a,"contenthash",{name:N},["name"],async t=>{let o=z(t.name);if(b(await s().readContract({address:x.registry.address,abi:fe,functionName:"resolver",args:[o.node]}),"resolver")!==Z(L))throw new i("This name uses another resolver. Its contenthash interface is not configured in Oak.");let n=Y(await s().readContract({address:L,abi:Q,functionName:"contenthash",args:[o.node]}));return{name:o.name,value:n,chainId:p,untrusted:!0}}),v(a,"set_contenthash",{name:N,value:{type:"string",pattern:"^0x([0-9a-fA-F]{2})*$",description:"Encoded contenthash bytes; 0x clears it. No content is fetched or uploaded."}},["name","value"],async(t,o)=>{let e=Y(t.value),n=await u(t.name,o);return h([f(L,$({abi:Q,functionName:"setContenthash",args:[n.node,e]}),`Set public contenthash on ${n.name} to ${e}.`)],n.owner,`Update ${n.name}'s public contenthash. The content is untrusted; no URL is fetched. History remains public.`)}),v(a,"set_primary",{name:N},["name"],async(t,o)=>{let e=await l(t.name,o);if(b(await s().readContract({address:x.universalResolver.address,abi:we,functionName:"resolve",args:[e.name]}),"resolved")!==e.owner)throw new i("Set this name to resolve to this wallet with hoodag_set_address before making it primary.");return h([f(x.reverseRegistrar.address,$({abi:ge,functionName:"setName",args:[e.name]}),`Make ${e.name} the primary name for ${e.owner}.`)],e.owner,`Replace this wallet's primary reverse name with ${e.name}.`)}),v(a,"clear_primary",{},[],async(t,o)=>{let e=b(o,"wallet");return h([f(x.reverseRegistrar.address,$({abi:ge,functionName:"setName",args:[""]}),`Clear the primary name for ${e}.`)],e,"Clear this wallet's primary reverse record. Names remain owned and rent is not refunded.")}),v(a,"reclaim",{name:N},["name"],async(t,o)=>{let e=await l(t.name,o);return h([f(E,$({abi:O,functionName:"reclaim",args:[e.tokenId,e.owner]}),`Reclaim registry control of ${e.name} for its NFT owner.`)],e.owner,`Restore registry control of ${e.name} to ${e.owner}. Existing address and text records remain public.`)}),v(a,"transfer",{name:N,to:H},["name","to"],async(t,o)=>{let e=b(t.to,"recipient"),n=await u(t.name,o);if(e===n.owner)throw new i("Choose a recipient different from this wallet.");let r=await s().readContract({address:x.universalResolver.address,abi:we,functionName:"reverse",args:[n.owner]});if(!Array.isArray(r)||r.length!==2||typeof r[0]!="string"||typeof r[1]!="boolean")throw new i("The reverse read returned an invalid response.");let g=[f(L,$({abi:Q,functionName:"setAddr",args:[n.node,e]}),`Point transferred ${n.name} to ${e}.`)],m=!1;try{m=!!r[0]&&U(r[0]).name===n.name}catch{}return m&&g.push(f(x.reverseRegistrar.address,$({abi:ge,functionName:"setName",args:[""]}),`Clear the sender's primary ${n.name}.`)),g.push(f(E,$({abi:O,functionName:"reclaim",args:[n.tokenId,e]}),`Give registry control of ${n.name} to ${e}.`),f(E,$({abi:O,functionName:"safeTransferFrom",args:[n.owner,e,n.tokenId]}),`Transfer the ${n.name} NFT to ${e}.`)),h(g,n.owner,`Transfer ${n.name} and registry control to ${e}; set its address to the recipient and clear the sender's matching primary name. Existing text/contenthash records travel with it; the recipient must review them and set its own primary name. Partial execution can leave earlier record changes mined.`,{name:n.name,tokenId:n.tokenId.toString(),recipient:e})}),v(a,"approve_transfer",{name:N,operator:H},["name","operator"],async(t,o)=>{if(typeof t.operator!="string")throw new i("Provide an operator address, or the zero address to revoke.");let e=t.operator.toLowerCase()===q?q:b(t.operator,"operator"),n=await l(t.name,o);return h([f(E,$({abi:O,functionName:"approve",args:[e,n.tokenId]}),`Approve ${e} for only the ${n.name} NFT.`)],n.owner,`${e===q?"Revoke":"Grant"} transfer approval for only ${n.name} to ${e}. An approved operator can move this name; no collection-wide approval is built.`)}),v(a,"market_listing",{name:N},["name"],async t=>{let o=await c(t.name),e=P(await s().readContract({address:I,abi:R,functionName:"feeBps"}),"marketplace fee");if(e>10000n)throw new i("The marketplace fee is invalid.");return{name:o.name,tokenId:o.tokenId.toString(),chainId:p,market:I,seller:o.seller,active:o.active,price:{token:o.token,amount:o.price.toString()},feeBps:e.toString()}}),v(a,"market_list",{name:N,price:pe,currency:{type:"string",enum:["ETH","USDG"]}},["name","price","currency"],async(t,o)=>{let e=ke(t.price);if(t.currency!=="USDG"&&t.currency!=="ETH")throw new i("Choose USDG or ETH.");let n=await l(t.name,o),r=[f(E,$({abi:O,functionName:"approve",args:[I,n.tokenId]}),`Approve only ${n.name} for marketplace transfer.`),f(I,$({abi:R,functionName:t.currency==="USDG"?"listUSDG":"list",args:[n.tokenId,e]}),`List ${n.name} for ${e} ${t.currency} base units.`)];return h(r,n.owner,`List ${n.name} for ${e} ${t.currency} base units. Buyers can transfer this name immediately; the marketplace deducts its live fee. Use hoodag_market_unlist to cancel. If interrupted after the individual NFT approval, revoke it explicitly with hoodag_approve_transfer and the zero operator address.`)}),...["set_price","unlist"].map(t=>v(a,`market_${t}`,{name:N,...t==="set_price"?{price:pe}:{}},t==="set_price"?["name","price"]:["name"],async(o,e)=>{let n=t==="set_price"?ke(o.price):void 0,r=await l(o.name,e),g=await c(o.name);if(!g.active||g.seller!==r.owner)throw new i("This wallet has no active listing for this name.");let m=n===void 0?$({abi:R,functionName:"unlist",args:[r.tokenId]}):$({abi:R,functionName:"setPrice",args:[r.tokenId,n]}),y=[f(I,m,`${t==="unlist"?"Unlist":"Reprice"} ${r.name}.`)];return t==="unlist"&&y.push(f(E,$({abi:O,functionName:"approve",args:[q,r.tokenId]}),`Revoke the transfer approval for ${r.name}.`)),h(y,r.owner,n===void 0?`Cancel ${r.name}'s listing and revoke its individual transfer approval.`:`Set ${r.name}'s listing to ${n} ${g.currency} base units.`)})),v(a,"market_buy",{name:N,maxPrice:pe,currency:{type:"string",enum:["ETH","USDG"]},referrer:H},["name","maxPrice","currency"],async(t,o)=>{let e=ke(t.maxPrice),n=b(o,"wallet"),r=await c(t.name);if(!r.active)throw new i("This name has no active marketplace listing.");if(r.currency!==t.currency)throw new i("The listing currency changed. Read hoodag_market_listing and confirm a fresh purchase.");if(r.price>e)throw new i("The listing exceeds maxPrice. Read hoodag_market_listing and confirm a fresh purchase.");if(n===r.seller)throw new i("This wallet already owns this listing.");if(b(await s().readContract({address:E,abi:O,functionName:"ownerOf",args:[r.tokenId]}),"name owner")!==r.seller)throw new i("The marketplace listing is stale; its seller no longer owns the name.");let m=await w(r.price,I,t.referrer,n,r.seller),y=r.currency==="USDG"?[a.approval(B,I,m.cost.toString(),p),f(I,$({abi:R,functionName:"buyUSDG",args:[r.tokenId,r.price,m.referrer,ye]}),`Buy ${r.name} for ${m.cost} USDG base units.`)]:[f(I,m.referrer===q?$({abi:R,functionName:"buy",args:[r.tokenId,r.price]}):$({abi:R,functionName:"buy",args:[r.tokenId,r.price,m.referrer]}),`Buy ${r.name} for ${m.cost} ETH base units.`,m.cost.toString())];return h(y,n,`Buy ${r.name} for ${m.cost} ${r.currency} base units plus gas, capped in calldata at the quoted listing price ${r.price}. Referrer ${m.referrer}; discount ${m.discountBps} basis points. Existing records may still point to the seller. After mining, run hoodag_reclaim, hoodag_set_address, review public records, then hoodag_set_primary.`,{price:{token:r.token,amount:m.cost.toString()}})}),v(a,"commit",{name:N,salt:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$",description:"Random 32-byte registration salt; never a wallet key. Reuse it only for this reveal."}},["name","salt"],async(t,o)=>{let e=Y(t.salt,32),n=b(o,"wallet"),r=z(t.name),g=Y(await s().readContract({address:_,abi:D,functionName:"makeCommitment",args:[r.label,n,e]}),32),m=P(await s().readContract({address:_,abi:D,functionName:"minCommitAge"}),"minimum commit age");return h([f(_,$({abi:D,functionName:"commit",args:[g]}),`Commit to registering ${r.name} with native ETH later.`)],n,`Commit to ${r.name}; this does not register it. After mining, wait at least ${m} seconds, then use hoodag_register_eth with the same name and salt. Gas is spent even if no reveal follows. A numeric price quote does not establish oracle freshness; the reveal can still fail with stale oracle.`,{commitment:g,waitSeconds:m.toString()})}),v(a,"register_eth",{name:N,duration:he,salt:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$"}},["name","salt"],async(t,o)=>{let e=Y(t.salt,32),n=b(o,"wallet"),r=await d(t.name,t.duration,"ETH",!1);return h([f(_,$({abi:D,functionName:"register",args:[r.label,n,r.duration,e]}),`Reveal and register ${r.name} with native ETH.`,r.cost.toString())],n,`Register ${r.name} for ${r.duration} seconds with ${r.cost} ETH base units plus gas. Requires the earlier matching commitment to have matured. Primary reverse name is set separately with hoodag_set_primary. A stale oracle or expired commitment must be resolved before retrying.`,{rent:{token:oe,amount:r.cost.toString()},duration:r.duration.toString()})}),v(a,"register_many",{names:{type:"array",minItems:1,maxItems:20,items:N},owner:H,duration:he,referrer:H,currency:{type:"string",enum:["USDG","ETH"],default:"USDG"}},["names"],async(t,o)=>{if(!Array.isArray(t.names)||!t.names.length||t.names.length>20)throw new i("Provide one to twenty .hood names.");let e=b(o,"wallet"),n=t.owner===void 0?e:b(t.owner,"name owner"),r=t.currency??"USDG",g=re(t.duration),m=t.names.map(U);if(new Set(m.map(T=>T.name)).size!==m.length)throw new i("Provide distinct names after normalization.");let y=0n,S=[];for(let T of m){let J=(await d(T.name,g.toString(),r,!1)).cost;S.push(J),y+=J}if(y>=1n<<256n)throw new i("The total rent exceeds uint256.");let k=await w(y,_,t.referrer,e);k.cost=S.reduce((T,J)=>T+J-J*k.discountBps/10000n,0n);let C=m.map(T=>T.label),A=r==="USDG"?[a.approval(B,_,k.cost.toString(),p),f(_,$({abi:D,functionName:"registerManyUSDG",args:[C,n,g,k.referrer,ye]}),`Register ${m.map(T=>T.name).join(", ")} to ${n}.`)]:[f(_,$({abi:D,functionName:"registerMany",args:[C,n,g,k.referrer]}),`Register ${m.map(T=>T.name).join(", ")} to ${n}.`,k.cost.toString())];return h(A,e,`Register ${m.map(T=>T.name).join(", ")} to ${n} for ${g} seconds each, for ${k.cost} ${r} base units plus gas. Referrer ${k.referrer}; discount ${k.discountBps} basis points. All names go to that owner; no primary reverse name is changed. Renewals and transfers are separate actions.`,{rent:{token:r==="USDG"?be:oe,amount:k.cost.toString()},duration:g.toString()})}),v(a,"referral_info",{},[],async(t,o)=>{let e=b(o,"wallet"),n={};for(let[r,g,m]of[["registration",_,D],["market",I,R]])for(let y of["refDiscountBps","refRewardBps"]){let S=P(await s().readContract({address:g,abi:m,functionName:y}),"referral basis points");if(S>10000n)throw new i("The referral rate exceeds 10000 basis points.");n[`${r}_${y}`]=S.toString()}return{address:e,chainId:p,referralLink:`https://www.hood.ag/?ref=${e}`,rates:n,warning:"Referral payouts occur in the qualifying transaction; there is no reward claim action. Pass a distinct referrer to hoodag_register_many or hoodag_market_buy. Exact discounted spending is quoted and previewed; no fallback silently removes the referral."}})]}export{qe as a,Pe as b,U as c,re as d,b as e,P as f,v as g,dn as h,Rn as i,de as j,ce as k};
@@ -1 +1 @@
1
- import{b as R}from"./UXG67LH3.js";import{a as w}from"./6IM6A5VA.js";import{g as S}from"./73N3TOJL.js";import{a as o,i as k,j as v}from"./XPFVT2EA.js";import{a as t}from"./5YS5V2LK.js";import{encodeFunctionData as x,getAddress as h,keccak256 as A,parseAbi as O,parseAbiItem as T,toHex as C,zeroHash as E}from"viem";var i=h(k[o].vaults.spark.address),g={admin:E,setter:A(C("SETTER_ROLE")),taker:A(C("TAKER_ROLE"))},D=[["drip()","any"],["setVsr(uint256 rate)","setter"],["setVsrBounds(uint256 minimum,uint256 maximum)","admin"],["setDepositCap(uint256 cap)","admin"],["take(uint256 assets)","taker"],["grantRole(bytes32 role,address account)","admin"],["revokeRole(bytes32 role,address account)","admin"],["renounceRole(bytes32 role,address account)","any"],["upgradeToAndCall(address implementation,bytes data)","admin"]],N=D.map(([r,a])=>({abi:T(`function ${r}`),authority:a})),p=O(["function asset() view returns (address)","function hasRole(bytes32,address) view returns (bool)","function getRoleMemberCount(bytes32) view returns (uint256)","function getRoleMember(bytes32,uint256) view returns (address)"]);function _(r){return[{name:"spark_roles",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:async(a,s)=>{try{if(w(s),Object.keys(a).length)throw new t("Spark roles takes no arguments.");let e=r.clientFor(o);if(await e.getChainId()!==o)throw new t("Spark requires chain 4663.");let u=await e.getBlockNumber({cacheTime:0}),c=await Promise.all(Object.entries(g).map(async([f,d])=>{let l=await e.readContract({address:i,abi:p,functionName:"getRoleMemberCount",args:[d],blockNumber:u});if(l>256n)throw new t("Spark role membership exceeds this reader\u2019s supported size.");let[b,n]=await Promise.all([e.readContract({address:i,abi:p,functionName:"hasRole",args:[d,s],blockNumber:u}),Promise.all(Array.from({length:Number(l)},(y,m)=>e.readContract({address:i,abi:p,functionName:"getRoleMember",args:[d,BigInt(m)],blockNumber:u})))]);return{name:f,role:d,heldByWallet:b,members:n.map(y=>h(y))}}));return{vault:i,chainId:o,blockNumber:u.toString(),roles:c}}catch(e){throw new t(r.plainError(e))}}},{name:"spark_manage",inputSchema:{type:"object",additionalProperties:!1,required:["operation","values"],properties:{operation:{type:"string",enum:N.map(a=>a.abi.name)},values:{type:"array",maxItems:2,items:{type:"string"},description:"Ordered contract inputs; all integers are decimal base-unit strings."}}},execute:async(a,s)=>{try{if(w(s),Object.keys(a).some(n=>!["operation","values"].includes(n)))throw new t("Unexpected Spark management argument.");let e=N.find(n=>n.abi.name===a.operation);if(!e||!Array.isArray(a.values)||a.values.length!==e.abi.inputs.length)throw new t("Provide a supported Spark operation and its exact ordered values.");let u=e.abi.inputs.map((n,y)=>{let m=a.values[y];if(n.type==="bytes32"){if(typeof m!="string"||!Object.values(g).includes(m))throw new t("Provide a documented Spark role identifier.");return m}return R(n.type,m)});if(e.abi.name==="renounceRole"&&!S(String(u[1]),s))throw new t("Role renunciation must name this wallet.");let c=r.clientFor(o);if(await c.getChainId()!==o)throw new t("Spark requires chain 4663.");let f=await c.readContract({address:i,abi:p,functionName:"asset"});if(h(f)!==h(v))throw new t("Spark does not use canonical USDG.");if(e.authority!=="any"&&await c.readContract({address:i,abi:p,functionName:"hasRole",args:[g[e.authority],s]})!==!0)throw new t("This wallet does not hold the required Spark role. No transaction was built.");let d=`${e.abi.name} on Spark ${i}; ordered values ${JSON.stringify(a.values)}. ${e.abi.name==="upgradeToAndCall"?"Replaces vault implementation; Oak must review and re-pin upgraded code before subsequent use.":e.abi.name==="take"?"Pulls vault liquidity to this role-authorized wallet; it mints no savings shares.":""}`,l=[r.unsignedTx({to:i,data:x({abi:[e.abi],functionName:e.abi.name,args:u}),value:"0",chainId:o,description:d})],b=await r.preview(l,s);return{txs:l,preview:b,summary:`${d} ${b.summary} Role and rate bounds are enforced again by the contract at execution.`}}catch(e){throw new t(r.plainError(e))}}}]}export{N as a,_ as b};
1
+ import{b as R}from"./TCPPYBGQ.js";import{a as w}from"./6IM6A5VA.js";import{g as S}from"./73N3TOJL.js";import{a as o,i as k,j as v}from"./G6HCV67X.js";import{a as t}from"./5YS5V2LK.js";import{encodeFunctionData as x,getAddress as h,keccak256 as A,parseAbi as O,parseAbiItem as T,toHex as C,zeroHash as E}from"viem";var i=h(k[o].vaults.spark.address),g={admin:E,setter:A(C("SETTER_ROLE")),taker:A(C("TAKER_ROLE"))},D=[["drip()","any"],["setVsr(uint256 rate)","setter"],["setVsrBounds(uint256 minimum,uint256 maximum)","admin"],["setDepositCap(uint256 cap)","admin"],["take(uint256 assets)","taker"],["grantRole(bytes32 role,address account)","admin"],["revokeRole(bytes32 role,address account)","admin"],["renounceRole(bytes32 role,address account)","any"],["upgradeToAndCall(address implementation,bytes data)","admin"]],N=D.map(([r,a])=>({abi:T(`function ${r}`),authority:a})),p=O(["function asset() view returns (address)","function hasRole(bytes32,address) view returns (bool)","function getRoleMemberCount(bytes32) view returns (uint256)","function getRoleMember(bytes32,uint256) view returns (address)"]);function _(r){return[{name:"spark_roles",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:async(a,s)=>{try{if(w(s),Object.keys(a).length)throw new t("Spark roles takes no arguments.");let e=r.clientFor(o);if(await e.getChainId()!==o)throw new t("Spark requires chain 4663.");let u=await e.getBlockNumber({cacheTime:0}),c=await Promise.all(Object.entries(g).map(async([f,d])=>{let l=await e.readContract({address:i,abi:p,functionName:"getRoleMemberCount",args:[d],blockNumber:u});if(l>256n)throw new t("Spark role membership exceeds this reader\u2019s supported size.");let[b,n]=await Promise.all([e.readContract({address:i,abi:p,functionName:"hasRole",args:[d,s],blockNumber:u}),Promise.all(Array.from({length:Number(l)},(y,m)=>e.readContract({address:i,abi:p,functionName:"getRoleMember",args:[d,BigInt(m)],blockNumber:u})))]);return{name:f,role:d,heldByWallet:b,members:n.map(y=>h(y))}}));return{vault:i,chainId:o,blockNumber:u.toString(),roles:c}}catch(e){throw new t(r.plainError(e))}}},{name:"spark_manage",inputSchema:{type:"object",additionalProperties:!1,required:["operation","values"],properties:{operation:{type:"string",enum:N.map(a=>a.abi.name)},values:{type:"array",maxItems:2,items:{type:"string"},description:"Ordered contract inputs; all integers are decimal base-unit strings."}}},execute:async(a,s)=>{try{if(w(s),Object.keys(a).some(n=>!["operation","values"].includes(n)))throw new t("Unexpected Spark management argument.");let e=N.find(n=>n.abi.name===a.operation);if(!e||!Array.isArray(a.values)||a.values.length!==e.abi.inputs.length)throw new t("Provide a supported Spark operation and its exact ordered values.");let u=e.abi.inputs.map((n,y)=>{let m=a.values[y];if(n.type==="bytes32"){if(typeof m!="string"||!Object.values(g).includes(m))throw new t("Provide a documented Spark role identifier.");return m}return R(n.type,m)});if(e.abi.name==="renounceRole"&&!S(String(u[1]),s))throw new t("Role renunciation must name this wallet.");let c=r.clientFor(o);if(await c.getChainId()!==o)throw new t("Spark requires chain 4663.");let f=await c.readContract({address:i,abi:p,functionName:"asset"});if(h(f)!==h(v))throw new t("Spark does not use canonical USDG.");if(e.authority!=="any"&&await c.readContract({address:i,abi:p,functionName:"hasRole",args:[g[e.authority],s]})!==!0)throw new t("This wallet does not hold the required Spark role. No transaction was built.");let d=`${e.abi.name} on Spark ${i}; ordered values ${JSON.stringify(a.values)}. ${e.abi.name==="upgradeToAndCall"?"Replaces vault implementation; Oak must review and re-pin upgraded code before subsequent use.":e.abi.name==="take"?"Pulls vault liquidity to this role-authorized wallet; it mints no savings shares.":""}`,l=[r.unsignedTx({to:i,data:x({abi:[e.abi],functionName:e.abi.name,args:u}),value:"0",chainId:o,description:d})],b=await r.preview(l,s);return{txs:l,preview:b,summary:`${d} ${b.summary} Role and rate bounds are enforced again by the contract at execution.`}}catch(e){throw new t(r.plainError(e))}}}]}export{N as a,_ as b};
@@ -0,0 +1 @@
1
+ import{a as p,f as u,g as c}from"./3NDVXEBR.js";import{f as a}from"./Q356HHCL.js";import{a as e}from"./UWOFA6GV.js";import{a as r}from"./G6HCV67X.js";import{a as n}from"./5YS5V2LK.js";import{encodeFunctionData as d,parseAbi as f}from"viem";var m=f(["function deposit() payable","function withdraw(uint256)"]);function H(i){return{tools:[{name:"uniswap_wrap",inputSchema:{type:"object",additionalProperties:!1,required:["direction","amount"],properties:{direction:{type:"string",enum:["wrap","unwrap"]},amount:e()}},async execute(t,w){if(c(t,["direction","amount"]),t.direction!=="wrap"&&t.direction!=="unwrap")throw new n("Choose direction wrap or unwrap.");let o=p(t.amount,"amount"),s=t.direction==="wrap"?d({abi:m,functionName:"deposit"}):d({abi:m,functionName:"withdraw",args:[o]});return u(i,[i.unsignedTx({to:a,data:s,value:t.direction==="wrap"?o.toString():"0",chainId:r,description:`${t.direction} ${o} ETH/WETH base units to the signing wallet.`})],w,"Wrap or unwrap native ETH at the pinned WETH contract. Ratio 1:1; network gas is additional.")}}]}}export{m as a,H as b};
@@ -1 +1 @@
1
- import{d as s,e as h,f as y,h as O,i as q,k as T,m as L,q as w,t as D}from"./53N7PNJH.js";import{b as E,c as I,e as x,g as S}from"./73N3TOJL.js";import{a as P}from"./XPFVT2EA.js";import{a as d}from"./5YS5V2LK.js";import{a as $}from"./JXOEJPJ4.js";import{getAddress as k}from"viem";var u={type:"integer",minimum:1},l={type:"string",minLength:1,maxLength:512},_={type:"string",pattern:"^0x[0-9a-fA-F]{64}$"},g={type:"integer",minimum:1,maximum:100},v={limit:g,cursor:l},j={relay_chain_health:"Read Relay service health. chainId is required.",relay_requests:"Page this wallet\u2019s requests. Requires server OAK_RELAY_API_KEY; the wallet filter is automatic. Optional id, chain and status filters narrow results.",relay_balance_events:"Page this wallet\u2019s balance events. Requires server OAK_RELAY_API_KEY with access to this resource.",relay_exchange_rates:"Read reference rates without a freshness guarantee. Relay may be unavailable; use relay_token_price for an individual token."};function C(n,r){if(r.type==="string"){if(typeof n!="string"||n.length<Number(r.minLength??0)||n.length>Number(r.maxLength??1024)||typeof r.pattern=="string"&&!new RegExp(r.pattern).test(n))throw new d("Provide a valid Relay search, address or cursor.")}else if(r.type==="integer"){if(typeof n!="number"||!Number.isSafeInteger(n)||n<Number(r.minimum??0)||n>Number(r.maximum??Number.MAX_SAFE_INTEGER))throw new d("Provide an integer within the Relay parameter bounds.")}else{if(r.type==="boolean"&&typeof n!="boolean")throw new d("Provide a boolean Relay filter.");if(r.type==="array"){if(!Array.isArray(n)||n.length>100)throw new d("Provide at most 100 Relay search values.");for(let a of n)C(a,s(r.items))}}if(Array.isArray(r.enum)&&!r.enum.includes(n))throw new d("Choose a supported Relay filter.")}function m(n){return new URLSearchParams(Object.entries(n).map(([r,a])=>[r==="cursor"?"continuation":r,String(a)])).toString()}function R(n){if(n!=null)return C(n,l),n}function p(n){return typeof n=="string"?E.test(n)?k(n.toLowerCase()):/^(?:0x[0-9a-fA-F]{64}|-?\d+(?:\.\d+)?)$/.test(n)?n:$(n):Array.isArray(n)?n.map(p):x(n)?Object.fromEntries(Object.entries(n).filter(([r])=>!/api.?key|signature|authorization|secret/i.test(r)).map(([r,a])=>[r,p(a)])):n}function A(n){return h(n).map(r=>{let a=s(r),e=a.decimals;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>255||typeof a.address!="string")throw new d("Relay returned invalid currency metadata.");let t=a.vmType===void 0||a.vmType==="evm";return{chainId:O(a.chainId),address:t?k(y(a.address)):$(a.address),symbol:w(a.symbol)??"unknown",decimals:e,vmType:w(a.vmType),verified:x(a.metadata)&&a.metadata.verified===!0}})}var F=["relay_vault_status","relay_currencies","relay_token_price","relay_currency_classifications","relay_liquidity","relay_swap_sources","relay_requests","relay_app_fee_balance","relay_app_fee_claims","relay_balance_events","relay_deposit_address","relay_recovery_balances","relay_withdrawal_status","relay_chain_health","relay_token_details","relay_token_chart","relay_trending","relay_exchange_rates","relay_protocol_execution"],X=n=>{let r=D(n);function a(e,t,i,o){return{name:e,inputSchema:{type:"object",...j[e]?{description:j[e]}:{},additionalProperties:!1,properties:t,required:i},execute:async(c,b)=>{for(let f of i)if(c[f]===void 0)throw new d(`Provide ${f} for ${e}.`);for(let[f,N]of Object.entries(c)){if(!Object.hasOwn(t,f))throw new d(`Unsupported ${e} parameter ${f}.`);C(N,t[f])}return o(c,y(b))}}}return{tools:[a("relay_chain_health",{chainId:u},["chainId"],async e=>{let t=s(await r(`/chains/health?${m(e)}`));if(typeof t.healthy!="boolean")throw new d("Relay returned invalid chain health.");return{healthy:t.healthy,chainId:e.chainId}}),a("relay_token_details",{chainId:u,address:I},["chainId","address"],async e=>{let t=s(await r(`/chains/${e.chainId}/currencies/${y(e.address)}`));if(t.chainId!==e.chainId||y(t.address)!==y(e.address))throw new d("Relay returned another token.");return{token:A([t])[0],data:p(t)}}),a("relay_token_chart",{chainId:u,address:I,timeframe:{type:"string",enum:["5M","1H","4H","24H","7D","30D","MAX"]}},["chainId","address"],async e=>{let t=s(await r(`/chains/${e.chainId}/currencies/${y(e.address)}/chart?${m(e.timeframe===void 0?{}:{timeframe:e.timeframe})}`));return{chainId:e.chainId,address:k(y(e.address)),data:p(t),summary:"Relay historical market data. Chart prices and volumes are not token base-unit balances."}}),a("relay_trending",{chainId:u,limit:{...g,maximum:20},sortBy:{type:"string",enum:["relay24hBuyTxCount","relay24hBuyUsdVolume","coingecko6hTrending"]}},[],async e=>({currencies:A(await r(`/currencies/trending?${m(e)}`))})),a("relay_exchange_rates",{},[],async()=>({rates:p(s(await r("/prices/rates"))),summary:"Relay reference rates; timestamps are not supplied. These are prices, not token base-unit amounts."})),a("relay_protocol_execution",{id:_},["id"],async e=>{let t=s(await r(`/protocol/executions/${e.id}`)),i=s(t.execution);if(!S(T(i.idempotencyKey),String(e.id)))throw new d("Relay returned another protocol execution.");return{data:p(t),summary:"Oracle execution status only; this does not prove a destination bridge fill."}}),a("relay_currencies",{chainIds:{type:"array",items:u},term:{...l,maxLength:256},address:l,currencyId:l,symbol:l,groupID:l,tokens:{type:"array",items:l},verified:{type:"boolean"},defaultList:{type:"boolean"},includeAllChains:{type:"boolean"},useExternalSearch:{type:"boolean"},depositAddressOnly:{type:"boolean"},limit:g},[],async e=>({currencies:A(await r("/currencies/v2",{chainIds:[P],...e})),summary:"Relay currency search. Provider verification is not an Oak token endorsement; obtain a quote to check route availability."})),a("relay_token_price",{chainId:u,address:I},["chainId","address"],async e=>{let t=s(await r(`/currencies/token/price/v2?${m(e)}`));if(typeof t.price!="string"||!/^\d+(?:\.\d+)?$/.test(t.price))throw new d("Relay returned an invalid USD price.");return{chainId:e.chainId,address:k(y(e.address)),priceUsd:t.price,summary:"Relay USD price; freshness is not supplied by this endpoint."}}),a("relay_currency_classifications",{},[],async()=>{let e=s(await r("/currencies/classifications"));return{major:h(e.major).map(t=>w(t)??"unknown"),stable:h(e.stable).map(t=>w(t)??"unknown")}}),a("relay_liquidity",{chainId:u},["chainId"],async e=>{let t=s(await r(`/chains/liquidity?${m(e)}`));return{liquidity:h(t.liquidity).map(i=>{let o=s(i);if(o.chainId!==e.chainId)throw new d("Relay liquidity chain does not match the request.");return{...A([o])[0],amount:q(o.balance)}}),summary:"Relay solver balances are indicative capacity, not a reserved route or user funds."}}),a("relay_swap_sources",{chainId:u},[],async e=>({sources:h(s(await r(`/swap-sources?${m(e)}`)).sources).map(t=>w(t,"name")??"unknown")})),a("relay_requests",{...v,originChainId:u,destinationChainId:u,chainId:u,id:_,orderId:_,depositTxHash:_,fillTxHash:_,refundTxHash:_,status:{type:"string",enum:["success","failure","refund","pending","depositing"]},includeChildRequests:{type:"boolean"}},[],async(e,t)=>{let i=s(await r(`/requests/v3?${m({...e,user:t,includePendingRequests:!0})}`)),o=h(i.requests).map(s);for(let c of o){let b=x(c.depositAddress)?c.depositAddress.depositor:void 0;if(![c.user,c.sender,b].some(f=>typeof f=="string"&&f.toLowerCase()===t))throw new d("Relay returned a request for another wallet.");T(c.id)}return{requests:p(o),nextCursor:R(i.continuation),summary:"One page of this wallet\u2019s Relay requests, including pending requests. Pass nextCursor as cursor to resume; provider success is not destination receipt verification."}}),a("relay_app_fee_balance",{},[],async(e,t)=>{let i=s(await r(`/app-fees/${t}/balances`));return{balances:h(i.balances).map(o=>{let c=L(o);return{...c,token:{...c.token,address:k(c.token.address),symbol:w(c.token.symbol)??"unknown"}}}),summary:"Off-chain Relay app fee credits for this wallet. Claiming requires separate local signature integration."}}),a("relay_app_fee_claims",v,[],async(e,t)=>{let i=s(await r(`/app-fees/${t}/claims?${m(e)}`)),o=h(i.claims).map(s);for(let c of o)if(y(c.wallet)!==t)throw new d("Relay returned a fee claim for another wallet.");return{claims:p(o),nextCursor:R(i.continuation)}}),a("relay_balance_events",{...v,limit:{...g,maximum:50},requestId:_,chainId:u,currency:I,startTimestamp:{type:"integer",minimum:0},endTimestamp:{type:"integer",minimum:0},type:l},[],async(e,t)=>{let i=s(await r(`/balance/${t}/events?${m(e)}`));if(y(i.wallet)!==t)throw new d("Relay returned balance events for another wallet.");let o=h(i.events).map(s);for(let c of o)if(y(c.wallet)!==t)throw new d("Relay returned a balance event for another wallet.");return{events:p(o),nextCursor:R(i.continuation)}}),a("relay_deposit_address",{address:l,depositAddressId:l,pageSize:{...g,maximum:50},pageToken:l},[],async e=>{if(e.address===void 0==(e.depositAddressId===void 0))throw new d("Provide exactly one deposit address or depositAddressId.");let t=s(await r(`/deposit-addresses/v2?${m(e)}`)),i=s(t.data),o=s(i.depositAddress);if(e.address!==void 0&&o.address!==e.address||e.depositAddressId!==void 0&&o.id!==e.depositAddressId)throw new d("Relay returned another deposit address.");return{data:p(i),nextPageToken:R(i.nextPageToken),summary:"Deposit address monitoring only. Reading an address does not create, change, fund or recover it."}}),a("relay_recovery_balances",{...v,limit:{...g,maximum:50},ownerChainId:u},["ownerChainId"],async(e,t)=>{let i=s(await r(`/withdrawals/balances?${m({...e,recoveryAddress:t})}`)),o=h(i.balances).map(c=>{let b=s(c);return q(b.amount),b});return{balances:p(o),nextCursor:R(i.continuation),summary:"Credited recovery balances only. Empty balances do not prove that an unattested deposit has no recoverable funds. Withdrawal signing remains a separate action."}}),a("relay_withdrawal_status",{id:l},["id"],async e=>{let t=s(await r(`/withdrawals/status?${m(e)}`));if(typeof t.status!="string")throw new d("Relay returned an invalid withdrawal status.");return{status:w(t.status)??"unknown",data:p(t),summary:"Relay withdrawal job status; verify any reported transaction on its chain before treating funds as received."}})]}};export{F as a,X as b};
1
+ import{d as s,e as h,f as y,h as O,i as q,k as T,m as L,q as w,t as D}from"./53N7PNJH.js";import{b as E,c as I,e as x,g as S}from"./73N3TOJL.js";import{a as P}from"./G6HCV67X.js";import{a as d}from"./5YS5V2LK.js";import{a as $}from"./JXOEJPJ4.js";import{getAddress as k}from"viem";var u={type:"integer",minimum:1},l={type:"string",minLength:1,maxLength:512},_={type:"string",pattern:"^0x[0-9a-fA-F]{64}$"},g={type:"integer",minimum:1,maximum:100},v={limit:g,cursor:l},j={relay_chain_health:"Read Relay service health. chainId is required.",relay_requests:"Page this wallet\u2019s requests. Requires server OAK_RELAY_API_KEY; the wallet filter is automatic. Optional id, chain and status filters narrow results.",relay_balance_events:"Page this wallet\u2019s balance events. Requires server OAK_RELAY_API_KEY with access to this resource.",relay_exchange_rates:"Read reference rates without a freshness guarantee. Relay may be unavailable; use relay_token_price for an individual token."};function C(n,r){if(r.type==="string"){if(typeof n!="string"||n.length<Number(r.minLength??0)||n.length>Number(r.maxLength??1024)||typeof r.pattern=="string"&&!new RegExp(r.pattern).test(n))throw new d("Provide a valid Relay search, address or cursor.")}else if(r.type==="integer"){if(typeof n!="number"||!Number.isSafeInteger(n)||n<Number(r.minimum??0)||n>Number(r.maximum??Number.MAX_SAFE_INTEGER))throw new d("Provide an integer within the Relay parameter bounds.")}else{if(r.type==="boolean"&&typeof n!="boolean")throw new d("Provide a boolean Relay filter.");if(r.type==="array"){if(!Array.isArray(n)||n.length>100)throw new d("Provide at most 100 Relay search values.");for(let a of n)C(a,s(r.items))}}if(Array.isArray(r.enum)&&!r.enum.includes(n))throw new d("Choose a supported Relay filter.")}function m(n){return new URLSearchParams(Object.entries(n).map(([r,a])=>[r==="cursor"?"continuation":r,String(a)])).toString()}function R(n){if(n!=null)return C(n,l),n}function p(n){return typeof n=="string"?E.test(n)?k(n.toLowerCase()):/^(?:0x[0-9a-fA-F]{64}|-?\d+(?:\.\d+)?)$/.test(n)?n:$(n):Array.isArray(n)?n.map(p):x(n)?Object.fromEntries(Object.entries(n).filter(([r])=>!/api.?key|signature|authorization|secret/i.test(r)).map(([r,a])=>[r,p(a)])):n}function A(n){return h(n).map(r=>{let a=s(r),e=a.decimals;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>255||typeof a.address!="string")throw new d("Relay returned invalid currency metadata.");let t=a.vmType===void 0||a.vmType==="evm";return{chainId:O(a.chainId),address:t?k(y(a.address)):$(a.address),symbol:w(a.symbol)??"unknown",decimals:e,vmType:w(a.vmType),verified:x(a.metadata)&&a.metadata.verified===!0}})}var F=["relay_vault_status","relay_currencies","relay_token_price","relay_currency_classifications","relay_liquidity","relay_swap_sources","relay_requests","relay_app_fee_balance","relay_app_fee_claims","relay_balance_events","relay_deposit_address","relay_recovery_balances","relay_withdrawal_status","relay_chain_health","relay_token_details","relay_token_chart","relay_trending","relay_exchange_rates","relay_protocol_execution"],X=n=>{let r=D(n);function a(e,t,i,o){return{name:e,inputSchema:{type:"object",...j[e]?{description:j[e]}:{},additionalProperties:!1,properties:t,required:i},execute:async(c,b)=>{for(let f of i)if(c[f]===void 0)throw new d(`Provide ${f} for ${e}.`);for(let[f,N]of Object.entries(c)){if(!Object.hasOwn(t,f))throw new d(`Unsupported ${e} parameter ${f}.`);C(N,t[f])}return o(c,y(b))}}}return{tools:[a("relay_chain_health",{chainId:u},["chainId"],async e=>{let t=s(await r(`/chains/health?${m(e)}`));if(typeof t.healthy!="boolean")throw new d("Relay returned invalid chain health.");return{healthy:t.healthy,chainId:e.chainId}}),a("relay_token_details",{chainId:u,address:I},["chainId","address"],async e=>{let t=s(await r(`/chains/${e.chainId}/currencies/${y(e.address)}`));if(t.chainId!==e.chainId||y(t.address)!==y(e.address))throw new d("Relay returned another token.");return{token:A([t])[0],data:p(t)}}),a("relay_token_chart",{chainId:u,address:I,timeframe:{type:"string",enum:["5M","1H","4H","24H","7D","30D","MAX"]}},["chainId","address"],async e=>{let t=s(await r(`/chains/${e.chainId}/currencies/${y(e.address)}/chart?${m(e.timeframe===void 0?{}:{timeframe:e.timeframe})}`));return{chainId:e.chainId,address:k(y(e.address)),data:p(t),summary:"Relay historical market data. Chart prices and volumes are not token base-unit balances."}}),a("relay_trending",{chainId:u,limit:{...g,maximum:20},sortBy:{type:"string",enum:["relay24hBuyTxCount","relay24hBuyUsdVolume","coingecko6hTrending"]}},[],async e=>({currencies:A(await r(`/currencies/trending?${m(e)}`))})),a("relay_exchange_rates",{},[],async()=>({rates:p(s(await r("/prices/rates"))),summary:"Relay reference rates; timestamps are not supplied. These are prices, not token base-unit amounts."})),a("relay_protocol_execution",{id:_},["id"],async e=>{let t=s(await r(`/protocol/executions/${e.id}`)),i=s(t.execution);if(!S(T(i.idempotencyKey),String(e.id)))throw new d("Relay returned another protocol execution.");return{data:p(t),summary:"Oracle execution status only; this does not prove a destination bridge fill."}}),a("relay_currencies",{chainIds:{type:"array",items:u},term:{...l,maxLength:256},address:l,currencyId:l,symbol:l,groupID:l,tokens:{type:"array",items:l},verified:{type:"boolean"},defaultList:{type:"boolean"},includeAllChains:{type:"boolean"},useExternalSearch:{type:"boolean"},depositAddressOnly:{type:"boolean"},limit:g},[],async e=>({currencies:A(await r("/currencies/v2",{chainIds:[P],...e})),summary:"Relay currency search. Provider verification is not an Oak token endorsement; obtain a quote to check route availability."})),a("relay_token_price",{chainId:u,address:I},["chainId","address"],async e=>{let t=s(await r(`/currencies/token/price/v2?${m(e)}`));if(typeof t.price!="string"||!/^\d+(?:\.\d+)?$/.test(t.price))throw new d("Relay returned an invalid USD price.");return{chainId:e.chainId,address:k(y(e.address)),priceUsd:t.price,summary:"Relay USD price; freshness is not supplied by this endpoint."}}),a("relay_currency_classifications",{},[],async()=>{let e=s(await r("/currencies/classifications"));return{major:h(e.major).map(t=>w(t)??"unknown"),stable:h(e.stable).map(t=>w(t)??"unknown")}}),a("relay_liquidity",{chainId:u},["chainId"],async e=>{let t=s(await r(`/chains/liquidity?${m(e)}`));return{liquidity:h(t.liquidity).map(i=>{let o=s(i);if(o.chainId!==e.chainId)throw new d("Relay liquidity chain does not match the request.");return{...A([o])[0],amount:q(o.balance)}}),summary:"Relay solver balances are indicative capacity, not a reserved route or user funds."}}),a("relay_swap_sources",{chainId:u},[],async e=>({sources:h(s(await r(`/swap-sources?${m(e)}`)).sources).map(t=>w(t,"name")??"unknown")})),a("relay_requests",{...v,originChainId:u,destinationChainId:u,chainId:u,id:_,orderId:_,depositTxHash:_,fillTxHash:_,refundTxHash:_,status:{type:"string",enum:["success","failure","refund","pending","depositing"]},includeChildRequests:{type:"boolean"}},[],async(e,t)=>{let i=s(await r(`/requests/v3?${m({...e,user:t,includePendingRequests:!0})}`)),o=h(i.requests).map(s);for(let c of o){let b=x(c.depositAddress)?c.depositAddress.depositor:void 0;if(![c.user,c.sender,b].some(f=>typeof f=="string"&&f.toLowerCase()===t))throw new d("Relay returned a request for another wallet.");T(c.id)}return{requests:p(o),nextCursor:R(i.continuation),summary:"One page of this wallet\u2019s Relay requests, including pending requests. Pass nextCursor as cursor to resume; provider success is not destination receipt verification."}}),a("relay_app_fee_balance",{},[],async(e,t)=>{let i=s(await r(`/app-fees/${t}/balances`));return{balances:h(i.balances).map(o=>{let c=L(o);return{...c,token:{...c.token,address:k(c.token.address),symbol:w(c.token.symbol)??"unknown"}}}),summary:"Off-chain Relay app fee credits for this wallet. Claiming requires separate local signature integration."}}),a("relay_app_fee_claims",v,[],async(e,t)=>{let i=s(await r(`/app-fees/${t}/claims?${m(e)}`)),o=h(i.claims).map(s);for(let c of o)if(y(c.wallet)!==t)throw new d("Relay returned a fee claim for another wallet.");return{claims:p(o),nextCursor:R(i.continuation)}}),a("relay_balance_events",{...v,limit:{...g,maximum:50},requestId:_,chainId:u,currency:I,startTimestamp:{type:"integer",minimum:0},endTimestamp:{type:"integer",minimum:0},type:l},[],async(e,t)=>{let i=s(await r(`/balance/${t}/events?${m(e)}`));if(y(i.wallet)!==t)throw new d("Relay returned balance events for another wallet.");let o=h(i.events).map(s);for(let c of o)if(y(c.wallet)!==t)throw new d("Relay returned a balance event for another wallet.");return{events:p(o),nextCursor:R(i.continuation)}}),a("relay_deposit_address",{address:l,depositAddressId:l,pageSize:{...g,maximum:50},pageToken:l},[],async e=>{if(e.address===void 0==(e.depositAddressId===void 0))throw new d("Provide exactly one deposit address or depositAddressId.");let t=s(await r(`/deposit-addresses/v2?${m(e)}`)),i=s(t.data),o=s(i.depositAddress);if(e.address!==void 0&&o.address!==e.address||e.depositAddressId!==void 0&&o.id!==e.depositAddressId)throw new d("Relay returned another deposit address.");return{data:p(i),nextPageToken:R(i.nextPageToken),summary:"Deposit address monitoring only. Reading an address does not create, change, fund or recover it."}}),a("relay_recovery_balances",{...v,limit:{...g,maximum:50},ownerChainId:u},["ownerChainId"],async(e,t)=>{let i=s(await r(`/withdrawals/balances?${m({...e,recoveryAddress:t})}`)),o=h(i.balances).map(c=>{let b=s(c);return q(b.amount),b});return{balances:p(o),nextCursor:R(i.continuation),summary:"Credited recovery balances only. Empty balances do not prove that an unattested deposit has no recoverable funds. Withdrawal signing remains a separate action."}}),a("relay_withdrawal_status",{id:l},["id"],async e=>{let t=s(await r(`/withdrawals/status?${m(e)}`));if(typeof t.status!="string")throw new d("Relay returned an invalid withdrawal status.");return{status:w(t.status)??"unknown",data:p(t),summary:"Relay withdrawal job status; verify any reported transaction on its chain before treating funds as received."}})]}};export{F as a,X as b};
@@ -1 +1 @@
1
- import{b as k,c as D,d as x}from"./46ZA2R5L.js";import{a as Q}from"./VJ3W2V3B.js";import{a as T}from"./6IM6A5VA.js";import{g as V,i as G}from"./73N3TOJL.js";import{a as X,b as W}from"./RETS2ZEK.js";import{a as c,d as j,i as O}from"./XPFVT2EA.js";import{a as u}from"./5YS5V2LK.js";import{encodeFunctionData as tt,erc20Abi as Z,getAddress as a,parseAbi as kt}from"viem";var gt="hookr",y=a(O[4663].hookr.HookrLimitOrders.address),At=a(O[4663].hookr.HookrRoot.address),wt=a(O[4663].hookr.HookrRouter.address),Ot=a(O[4663].hookr.HookrForwarder.address),Bt=a(O[4663].hookr.PoolManager.address),ht=a(O[4663].hookr.HOOKR_Token.address),L="0x0000000000000000000000000000000000000000",It="0x000000000000000000000000000000000000dEaD",J=(1n<<128n)-1n,St=new Set([L.toLowerCase(),It.toLowerCase(),y.toLowerCase(),wt.toLowerCase(),Ot.toLowerCase(),Bt.toLowerCase(),At.toLowerCase()]),B=kt(["function getOrder(uint256 orderId) view returns (((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, address owner, uint40 createdAt, uint40 expiry, bool zeroForOne, uint8 status, address recipient, uint128 amountIn, uint128 minAmountOut, uint128 bounty, uint160 sqrtPriceLimitX96))","function quoteFill(uint256 orderId) view returns (bool fillable, uint256 amountOut)","function bountyBounds((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, bool zeroForOne, uint128 amountIn, uint128 minAmountOut) view returns (uint128 minBounty, uint128 defaultBounty, uint128 maxBounty)","function fill(uint256 orderId) returns (uint256 amountOut)","function claimBounty(address to) returns (uint256 amount)","function bountyOf(address keeper) view returns (uint256)","function lastOrderId() view returns (uint256)","function liabilities(address currency) view returns (uint256)"]);function Tt(t){let n=t.toLowerCase();return n===L.toLowerCase()||n===Q.toLowerCase()}function Ht(t,n,i){let o=n.trim();if(o.startsWith("-")){let s=o.slice(1),r=t(s,i);return r==="0"?"0":`-${r}`}return t(o,i)}function jt(t,n,i){return W(t,n,i)}function nt(t,n){return!t.changes||t.changes.length===0?"no net ERC-20/native transfer delta on caller":t.changes.map(i=>`${Ht(n,i.amount,i.token.decimals)} ${i.token.symbol} (${i.token.address})`).join(", ")}function $t(t){if(typeof t=="bigint"){if(t<=0n)throw new u("Hookr orderId must be a positive integer.");return t}if(typeof t=="number"){if(!Number.isSafeInteger(t)||t<=0)throw new u("Hookr orderId must be a positive integer.");return BigInt(t)}if(typeof t=="string"&&/^\d+$/.test(t.trim())){let n=BigInt(t.trim());if(n<=0n)throw new u("Hookr orderId must be a positive integer.");return n}throw new u("Provide a positive integer Hookr orderId.")}function et(t){if(t==null)return c;if(typeof t!="number"||!Number.isSafeInteger(t)||t!==c)throw new u(`Hookr limit orders are only supported on chain ${c}.`);return c}function xt(t){switch(t){case 0:return"None";case 1:return"Open";case 2:return"Filled";case 3:return"Cancelled";default:return"Unknown"}}function Rt(t){if(Array.isArray(t)){let[n,i,o,s,r,d,g,m,b,e,l]=t;return{key:Array.isArray(n)?{currency0:n[0],currency1:n[1],fee:Number(n[2]),tickSpacing:Number(n[3]),hooks:n[4]}:n,owner:i,createdAt:o,expiry:s,zeroForOne:!!r,status:d,recipient:g,amountIn:BigInt(m),minAmountOut:BigInt(b),bounty:BigInt(e),sqrtPriceLimitX96:BigInt(l)}}if(t&&typeof t=="object"){let n=t;if(n.key&&typeof n.key=="object")return{key:{currency0:n.key.currency0,currency1:n.key.currency1,fee:Number(n.key.fee),tickSpacing:Number(n.key.tickSpacing),hooks:n.key.hooks},owner:n.owner,createdAt:n.createdAt,expiry:n.expiry,zeroForOne:!!n.zeroForOne,status:n.status,recipient:n.recipient,amountIn:BigInt(n.amountIn),minAmountOut:BigInt(n.minAmountOut),bounty:BigInt(n.bounty),sqrtPriceLimitX96:BigInt(n.sqrtPriceLimitX96)}}throw new u("HookrLimitOrders returned a malformed order tuple.")}function Ct(t){if(Array.isArray(t)&&t.length>=2)return{fillable:!!t[0],amountOut:BigInt(t[1])};if(t&&typeof t=="object"&&"fillable"in t&&"amountOut"in t){let n=t;return{fillable:!!n.fillable,amountOut:BigInt(n.amountOut)}}throw new u("HookrLimitOrders returned a malformed quoteFill response.")}function Dt(t){if(Array.isArray(t)&&t.length>=3)return{minBounty:BigInt(t[0]),defaultBounty:BigInt(t[1]),maxBounty:BigInt(t[2])};if(t&&typeof t=="object"&&"minBounty"in t&&"defaultBounty"in t&&"maxBounty"in t){let n=t;return{minBounty:BigInt(n.minBounty),defaultBounty:BigInt(n.defaultBounty),maxBounty:BigInt(n.maxBounty)}}throw new u("HookrLimitOrders returned a malformed bountyBounds response.")}async function Y(t,n,i=c){if(i!==c)throw new u(`Unsupported token chain ${i}; Hookr requires chain ${c}.`);if(Tt(n))return{...k,chainId:i};T(n);let o=a(n),s=o.toLowerCase();if(s===D.address.toLowerCase())return{address:o,symbol:D.symbol,decimals:j,chainId:i};if(s===x.address.toLowerCase())return{address:o,symbol:x.symbol,decimals:x.decimals,chainId:i};if(s===ht.toLowerCase())return{address:o,symbol:"HOOKR",decimals:18,chainId:i};let[r,d]=await Promise.all([t.readContract({address:o,abi:Z,functionName:"symbol"}),t.readContract({address:o,abi:Z,functionName:"decimals"})]),g=typeof r=="string"&&r.trim()?r.trim():o,m=Number(d);if(!Number.isInteger(m)||m<0||m>255)throw new u(`Invalid token decimals for ${o} on chain ${i}.`);return{address:o,symbol:g,decimals:m,chainId:i}}async function Pt(t){if(typeof t.getBlock!="function")throw new u("Cannot read the latest block timestamp for Hookr order expiry.");let n=await t.getBlock().catch(()=>{throw new u("Cannot read the latest block timestamp for Hookr order expiry.")});if(!n||typeof n.timestamp!="bigint"||n.timestamp<=0n)throw new u("Hookr requires a usable latest block timestamp to check order expiry.");return n.timestamp}function P(t,n=[]){let i=G(t,"Provide a valid recipient wallet address."),o=i.toLowerCase();if(St.has(o)||n.some(s=>s.toLowerCase()===o))throw new u(`Recipient ${i} is a reserved protocol or zero address (invalid recipient).`);return i}function ot(t){if(t.minBountyEth!==void 0||t.minAmountOutDecimal!==void 0||t.rounding!==void 0)throw new u("Use minBounty and minAmountOut as base-unit integer strings.")}function E(t,n){if(t!==void 0){if(typeof t!="string"||!/^\d+$/.test(t))throw new u(`Provide ${n} as a base-unit integer string.`);return X(t)}}function Et(t){return{name:"hookr_fill",inputSchema:{type:"object",properties:{orderId:{type:"string",description:"HookrLimitOrders orderId as a positive integer string."},minBounty:{type:"string",description:"Optional minimum keeper bounty in wei (decimal base-unit string)."},minAmountOut:{type:"string",description:"Optional quote pre-check only, in token base-unit integer strings. Not enforced on chain: fill(uint256) enforces only the order minAmountOut."},chainId:{type:"number",description:"Target chain ID (must be 4663)."}},required:["orderId"],additionalProperties:!1},async execute(n,i){try{ot(n),T(i);let o=a(i),s=et(n.chainId),r=$t(n.orderId),d=t.clientFor(s),[g,m,b]=await Promise.all([d.readContract({address:y,abi:B,functionName:"getOrder",args:[r]}),d.readContract({address:y,abi:B,functionName:"quoteFill",args:[r]}),Pt(d)]),e=Rt(g),l=Number(e.status),h=xt(l);if(l===0||V(e.owner,L))throw new u(`Hookr order #${r} does not exist.`);if(l!==1)throw new u(`Hookr order #${r} is not open (current status: ${h}).`);let A=BigInt(e.expiry);if(A<b)throw new u(`Hookr order #${r} is expired (expiry ${A} < current timestamp ${b}).`);let f=Number(e.key.tickSpacing),H=Number(e.key.fee);if(!Number.isInteger(f)||f<=0)throw new u(`Hookr order #${r} has an invalid pool tickSpacing (${f}).`);if(e.amountIn<=0n||e.amountIn>J)throw new u(`Hookr order #${r} has an invalid amountIn (${e.amountIn}).`);if(e.minAmountOut<=0n||e.minAmountOut>J)throw new u(`Hookr order #${r} has an invalid minAmountOut (${e.minAmountOut}).`);let R=a(e.key.hooks);P(e.recipient,[R]);let rt=await d.readContract({address:y,abi:B,functionName:"bountyBounds",args:[{currency0:a(e.key.currency0),currency1:a(e.key.currency1),fee:H,tickSpacing:f,hooks:R},e.zeroForOne,e.amountIn,e.minAmountOut]}),w=Dt(rt),C=E(n.minBounty,"minBounty"),_=C!==void 0&&C>w.minBounty?C:w.minBounty;if(e.bounty<_)throw new u(`Hookr order #${r} is underbounty: order bounty (${e.bounty} wei) is below the required keeper bounty (${_} wei).`);if(e.bounty>w.maxBounty)throw new u(`Hookr order #${r} bounty (${e.bounty} wei) exceeds maximum bounty bound (${w.maxBounty} wei).`);let I=Ct(m),it=e.zeroForOne?e.key.currency0:e.key.currency1,ut=e.zeroForOne?e.key.currency1:e.key.currency0,[$,p]=await Promise.all([Y(d,it,s),Y(d,ut,s)]),S=E(n.minAmountOut,"minAmountOut"),F=S!==void 0&&S>e.minAmountOut?S:e.minAmountOut;if(!I.fillable||I.amountOut<=0n||I.amountOut<F)throw new u(`Hookr order #${r} is not executable: quoted output (${I.amountOut} base units of ${p.address}) does not meet minimum output (${F} base units).`);let st=tt({abi:B,functionName:"fill",args:[r]}),at=t.formatAmount(e.amountIn.toString(),$.decimals),mt=t.formatAmount(I.amountOut.toString(),p.decimals),dt=t.formatAmount(e.minAmountOut.toString(),p.decimals),ct=t.formatAmount(e.bounty.toString(),18),lt=S===void 0?"":` Caller minAmountOut ${S} base units is a quote pre-check only, not enforced on chain; fill(uint256) enforces the order minimum of ${e.minAmountOut} base units.`,v=`Fill Hookr order #${r}: maker's escrow pays ${at} ${$.symbol} (${e.amountIn} base units of ${$.address}); net output goes to ${a(e.recipient)} (quoted ${mt} ${p.symbol}, order minimum ${dt} ${p.symbol}, ${e.minAmountOut} base units of ${p.address}). The filler sends no tokens or ETH (value 0), pays gas, and accrues ${ct} ETH (${e.bounty} wei) bounty to ${o}, payable only via claimBounty. Pool tickSpacing ${f}; expiry ${A} inclusive.${lt}`,q=t.unsignedTx({to:y,data:st,value:"0",chainId:s,description:v}),M=await t.preview([q],o),yt=nt(M,t.formatAmount),z={token:$,amount:e.amountIn.toString()},K={token:p,amount:e.minAmountOut.toString()},bt={token:p,amount:I.amountOut.toString()},U={token:{...k,chainId:s},amount:e.bounty.toString()},ft={orderId:r.toString(),key:{currency0:a(e.key.currency0),currency1:a(e.key.currency1),fee:H,tickSpacing:f,hooks:R},owner:a(e.owner),recipient:a(e.recipient),createdAt:BigInt(e.createdAt).toString(),expiry:A.toString(),zeroForOne:e.zeroForOne,status:l,statusLabel:h,amountIn:z,minAmountOut:K,bounty:U,sqrtPriceLimitX96:e.sqrtPriceLimitX96.toString()},pt={minBounty:{token:{...k,chainId:s},amount:w.minBounty.toString()},defaultBounty:{token:{...k,chainId:s},amount:w.defaultBounty.toString()},maxBounty:{token:{...k,chainId:s},amount:w.maxBounty.toString()}};return{txs:[q],summary:`${v} Preview deltas: ${yt}.`,preview:M,orderId:r.toString(),fillable:!0,amountIn:z,minAmountOut:K,quotedAmountOut:bt,bounty:U,bountyBounds:pt,order:ft}}catch(o){throw new u(t.plainError(o))}}}}function Lt(t){return{name:"hookr_claim_bounty",inputSchema:{type:"object",properties:{to:{type:"string",description:"Optional recipient address for the claimed native ETH bounty (must be the signing wallet)."},minBounty:{type:"string",description:"Optional minimum claimable bounty in wei (decimal base-unit string)."},chainId:{type:"number",description:"Target chain ID (must be 4663)."}},additionalProperties:!1},async execute(n,i){try{ot(n),T(i);let o=a(i),s=et(n.chainId),r=n.to!==void 0&&n.to!==null?P(String(n.to)):P(o);if(r!==o)throw new u("Hookr bounty recipient must be the signing wallet.");let g=await t.clientFor(s).readContract({address:y,abi:B,functionName:"bountyOf",args:[o]}),m=BigInt(g);if(m<=0n)throw new u(`No claimable Hookr keeper bounty for ${o}.`);let b=E(n.minBounty,"minBounty");if(b!==void 0&&m<b)throw new u(`Claimable Hookr bounty (${m} wei) is below the requested minimum (${b} wei).`);let e=tt({abi:B,functionName:"claimBounty",args:[r]}),l=t.formatAmount(m.toString(),18),h=t.unsignedTx({to:y,data:e,value:"0",chainId:s,description:`Claim ${l} ETH (${m} wei) of accrued Hookr keeper bounty from ${y} to ${r}.`}),A=await t.preview([h],o),f=nt(A,t.formatAmount),H={token:{...k,chainId:s},amount:m.toString()};return{txs:[h],summary:`Claim ${l} ETH (${m} wei) Hookr keeper bounty to ${r}. Preview deltas: ${f}.`,preview:A,recipient:r,claimableBounty:H}}catch(o){throw new u(t.plainError(o))}}}}async function Nt(t,n){T(n);let i=a(n),o=t.clientFor(c);try{let s=await o.readContract({address:y,abi:B,functionName:"bountyOf",args:[i]}),r=BigInt(s);if(r<=0n)return[];let d=t.formatAmount(r.toString(),18);return[{module:gt,id:`hookr:bounty:${i.toLowerCase()}`,chainId:c,assets:[{token:{...k,chainId:c},amount:r.toString()}],description:`Hookr claimable keeper bounty (${d} ETH)`}]}catch(s){throw new u(t.plainError(s))}}var N=t=>({tools:[Et(t),Lt(t)],positions:n=>Nt(t,n)}),Xt=N,Wt=N,Vt=N;export{gt as a,y as b,At as c,wt as d,Ot as e,Bt as f,ht as g,B as h,Ht as i,jt as j,Et as k,Lt as l,Nt as m,N as n,Xt as o,Wt as p,Vt as q};
1
+ import{b as k,c as D,d as x}from"./JPOYTTTW.js";import{a as Q}from"./CY75R4FK.js";import{a as T}from"./6IM6A5VA.js";import{g as V,i as G}from"./73N3TOJL.js";import{a as X,b as W}from"./RETS2ZEK.js";import{a as c,d as j,i as O}from"./G6HCV67X.js";import{a as u}from"./5YS5V2LK.js";import{encodeFunctionData as tt,erc20Abi as Z,getAddress as a,parseAbi as kt}from"viem";var gt="hookr",y=a(O[4663].hookr.HookrLimitOrders.address),At=a(O[4663].hookr.HookrRoot.address),wt=a(O[4663].hookr.HookrRouter.address),Ot=a(O[4663].hookr.HookrForwarder.address),Bt=a(O[4663].hookr.PoolManager.address),ht=a(O[4663].hookr.HOOKR_Token.address),L="0x0000000000000000000000000000000000000000",It="0x000000000000000000000000000000000000dEaD",J=(1n<<128n)-1n,St=new Set([L.toLowerCase(),It.toLowerCase(),y.toLowerCase(),wt.toLowerCase(),Ot.toLowerCase(),Bt.toLowerCase(),At.toLowerCase()]),B=kt(["function getOrder(uint256 orderId) view returns (((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, address owner, uint40 createdAt, uint40 expiry, bool zeroForOne, uint8 status, address recipient, uint128 amountIn, uint128 minAmountOut, uint128 bounty, uint160 sqrtPriceLimitX96))","function quoteFill(uint256 orderId) view returns (bool fillable, uint256 amountOut)","function bountyBounds((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, bool zeroForOne, uint128 amountIn, uint128 minAmountOut) view returns (uint128 minBounty, uint128 defaultBounty, uint128 maxBounty)","function fill(uint256 orderId) returns (uint256 amountOut)","function claimBounty(address to) returns (uint256 amount)","function bountyOf(address keeper) view returns (uint256)","function lastOrderId() view returns (uint256)","function liabilities(address currency) view returns (uint256)"]);function Tt(t){let n=t.toLowerCase();return n===L.toLowerCase()||n===Q.toLowerCase()}function Ht(t,n,i){let o=n.trim();if(o.startsWith("-")){let s=o.slice(1),r=t(s,i);return r==="0"?"0":`-${r}`}return t(o,i)}function jt(t,n,i){return W(t,n,i)}function nt(t,n){return!t.changes||t.changes.length===0?"no net ERC-20/native transfer delta on caller":t.changes.map(i=>`${Ht(n,i.amount,i.token.decimals)} ${i.token.symbol} (${i.token.address})`).join(", ")}function $t(t){if(typeof t=="bigint"){if(t<=0n)throw new u("Hookr orderId must be a positive integer.");return t}if(typeof t=="number"){if(!Number.isSafeInteger(t)||t<=0)throw new u("Hookr orderId must be a positive integer.");return BigInt(t)}if(typeof t=="string"&&/^\d+$/.test(t.trim())){let n=BigInt(t.trim());if(n<=0n)throw new u("Hookr orderId must be a positive integer.");return n}throw new u("Provide a positive integer Hookr orderId.")}function et(t){if(t==null)return c;if(typeof t!="number"||!Number.isSafeInteger(t)||t!==c)throw new u(`Hookr limit orders are only supported on chain ${c}.`);return c}function xt(t){switch(t){case 0:return"None";case 1:return"Open";case 2:return"Filled";case 3:return"Cancelled";default:return"Unknown"}}function Rt(t){if(Array.isArray(t)){let[n,i,o,s,r,d,g,m,b,e,l]=t;return{key:Array.isArray(n)?{currency0:n[0],currency1:n[1],fee:Number(n[2]),tickSpacing:Number(n[3]),hooks:n[4]}:n,owner:i,createdAt:o,expiry:s,zeroForOne:!!r,status:d,recipient:g,amountIn:BigInt(m),minAmountOut:BigInt(b),bounty:BigInt(e),sqrtPriceLimitX96:BigInt(l)}}if(t&&typeof t=="object"){let n=t;if(n.key&&typeof n.key=="object")return{key:{currency0:n.key.currency0,currency1:n.key.currency1,fee:Number(n.key.fee),tickSpacing:Number(n.key.tickSpacing),hooks:n.key.hooks},owner:n.owner,createdAt:n.createdAt,expiry:n.expiry,zeroForOne:!!n.zeroForOne,status:n.status,recipient:n.recipient,amountIn:BigInt(n.amountIn),minAmountOut:BigInt(n.minAmountOut),bounty:BigInt(n.bounty),sqrtPriceLimitX96:BigInt(n.sqrtPriceLimitX96)}}throw new u("HookrLimitOrders returned a malformed order tuple.")}function Ct(t){if(Array.isArray(t)&&t.length>=2)return{fillable:!!t[0],amountOut:BigInt(t[1])};if(t&&typeof t=="object"&&"fillable"in t&&"amountOut"in t){let n=t;return{fillable:!!n.fillable,amountOut:BigInt(n.amountOut)}}throw new u("HookrLimitOrders returned a malformed quoteFill response.")}function Dt(t){if(Array.isArray(t)&&t.length>=3)return{minBounty:BigInt(t[0]),defaultBounty:BigInt(t[1]),maxBounty:BigInt(t[2])};if(t&&typeof t=="object"&&"minBounty"in t&&"defaultBounty"in t&&"maxBounty"in t){let n=t;return{minBounty:BigInt(n.minBounty),defaultBounty:BigInt(n.defaultBounty),maxBounty:BigInt(n.maxBounty)}}throw new u("HookrLimitOrders returned a malformed bountyBounds response.")}async function Y(t,n,i=c){if(i!==c)throw new u(`Unsupported token chain ${i}; Hookr requires chain ${c}.`);if(Tt(n))return{...k,chainId:i};T(n);let o=a(n),s=o.toLowerCase();if(s===D.address.toLowerCase())return{address:o,symbol:D.symbol,decimals:j,chainId:i};if(s===x.address.toLowerCase())return{address:o,symbol:x.symbol,decimals:x.decimals,chainId:i};if(s===ht.toLowerCase())return{address:o,symbol:"HOOKR",decimals:18,chainId:i};let[r,d]=await Promise.all([t.readContract({address:o,abi:Z,functionName:"symbol"}),t.readContract({address:o,abi:Z,functionName:"decimals"})]),g=typeof r=="string"&&r.trim()?r.trim():o,m=Number(d);if(!Number.isInteger(m)||m<0||m>255)throw new u(`Invalid token decimals for ${o} on chain ${i}.`);return{address:o,symbol:g,decimals:m,chainId:i}}async function Pt(t){if(typeof t.getBlock!="function")throw new u("Cannot read the latest block timestamp for Hookr order expiry.");let n=await t.getBlock().catch(()=>{throw new u("Cannot read the latest block timestamp for Hookr order expiry.")});if(!n||typeof n.timestamp!="bigint"||n.timestamp<=0n)throw new u("Hookr requires a usable latest block timestamp to check order expiry.");return n.timestamp}function P(t,n=[]){let i=G(t,"Provide a valid recipient wallet address."),o=i.toLowerCase();if(St.has(o)||n.some(s=>s.toLowerCase()===o))throw new u(`Recipient ${i} is a reserved protocol or zero address (invalid recipient).`);return i}function ot(t){if(t.minBountyEth!==void 0||t.minAmountOutDecimal!==void 0||t.rounding!==void 0)throw new u("Use minBounty and minAmountOut as base-unit integer strings.")}function E(t,n){if(t!==void 0){if(typeof t!="string"||!/^\d+$/.test(t))throw new u(`Provide ${n} as a base-unit integer string.`);return X(t)}}function Et(t){return{name:"hookr_fill",inputSchema:{type:"object",properties:{orderId:{type:"string",description:"HookrLimitOrders orderId as a positive integer string."},minBounty:{type:"string",description:"Optional minimum keeper bounty in wei (decimal base-unit string)."},minAmountOut:{type:"string",description:"Optional quote pre-check only, in token base-unit integer strings. Not enforced on chain: fill(uint256) enforces only the order minAmountOut."},chainId:{type:"number",description:"Target chain ID (must be 4663)."}},required:["orderId"],additionalProperties:!1},async execute(n,i){try{ot(n),T(i);let o=a(i),s=et(n.chainId),r=$t(n.orderId),d=t.clientFor(s),[g,m,b]=await Promise.all([d.readContract({address:y,abi:B,functionName:"getOrder",args:[r]}),d.readContract({address:y,abi:B,functionName:"quoteFill",args:[r]}),Pt(d)]),e=Rt(g),l=Number(e.status),h=xt(l);if(l===0||V(e.owner,L))throw new u(`Hookr order #${r} does not exist.`);if(l!==1)throw new u(`Hookr order #${r} is not open (current status: ${h}).`);let A=BigInt(e.expiry);if(A<b)throw new u(`Hookr order #${r} is expired (expiry ${A} < current timestamp ${b}).`);let f=Number(e.key.tickSpacing),H=Number(e.key.fee);if(!Number.isInteger(f)||f<=0)throw new u(`Hookr order #${r} has an invalid pool tickSpacing (${f}).`);if(e.amountIn<=0n||e.amountIn>J)throw new u(`Hookr order #${r} has an invalid amountIn (${e.amountIn}).`);if(e.minAmountOut<=0n||e.minAmountOut>J)throw new u(`Hookr order #${r} has an invalid minAmountOut (${e.minAmountOut}).`);let R=a(e.key.hooks);P(e.recipient,[R]);let rt=await d.readContract({address:y,abi:B,functionName:"bountyBounds",args:[{currency0:a(e.key.currency0),currency1:a(e.key.currency1),fee:H,tickSpacing:f,hooks:R},e.zeroForOne,e.amountIn,e.minAmountOut]}),w=Dt(rt),C=E(n.minBounty,"minBounty"),_=C!==void 0&&C>w.minBounty?C:w.minBounty;if(e.bounty<_)throw new u(`Hookr order #${r} is underbounty: order bounty (${e.bounty} wei) is below the required keeper bounty (${_} wei).`);if(e.bounty>w.maxBounty)throw new u(`Hookr order #${r} bounty (${e.bounty} wei) exceeds maximum bounty bound (${w.maxBounty} wei).`);let I=Ct(m),it=e.zeroForOne?e.key.currency0:e.key.currency1,ut=e.zeroForOne?e.key.currency1:e.key.currency0,[$,p]=await Promise.all([Y(d,it,s),Y(d,ut,s)]),S=E(n.minAmountOut,"minAmountOut"),F=S!==void 0&&S>e.minAmountOut?S:e.minAmountOut;if(!I.fillable||I.amountOut<=0n||I.amountOut<F)throw new u(`Hookr order #${r} is not executable: quoted output (${I.amountOut} base units of ${p.address}) does not meet minimum output (${F} base units).`);let st=tt({abi:B,functionName:"fill",args:[r]}),at=t.formatAmount(e.amountIn.toString(),$.decimals),mt=t.formatAmount(I.amountOut.toString(),p.decimals),dt=t.formatAmount(e.minAmountOut.toString(),p.decimals),ct=t.formatAmount(e.bounty.toString(),18),lt=S===void 0?"":` Caller minAmountOut ${S} base units is a quote pre-check only, not enforced on chain; fill(uint256) enforces the order minimum of ${e.minAmountOut} base units.`,v=`Fill Hookr order #${r}: maker's escrow pays ${at} ${$.symbol} (${e.amountIn} base units of ${$.address}); net output goes to ${a(e.recipient)} (quoted ${mt} ${p.symbol}, order minimum ${dt} ${p.symbol}, ${e.minAmountOut} base units of ${p.address}). The filler sends no tokens or ETH (value 0), pays gas, and accrues ${ct} ETH (${e.bounty} wei) bounty to ${o}, payable only via claimBounty. Pool tickSpacing ${f}; expiry ${A} inclusive.${lt}`,q=t.unsignedTx({to:y,data:st,value:"0",chainId:s,description:v}),M=await t.preview([q],o),yt=nt(M,t.formatAmount),z={token:$,amount:e.amountIn.toString()},K={token:p,amount:e.minAmountOut.toString()},bt={token:p,amount:I.amountOut.toString()},U={token:{...k,chainId:s},amount:e.bounty.toString()},ft={orderId:r.toString(),key:{currency0:a(e.key.currency0),currency1:a(e.key.currency1),fee:H,tickSpacing:f,hooks:R},owner:a(e.owner),recipient:a(e.recipient),createdAt:BigInt(e.createdAt).toString(),expiry:A.toString(),zeroForOne:e.zeroForOne,status:l,statusLabel:h,amountIn:z,minAmountOut:K,bounty:U,sqrtPriceLimitX96:e.sqrtPriceLimitX96.toString()},pt={minBounty:{token:{...k,chainId:s},amount:w.minBounty.toString()},defaultBounty:{token:{...k,chainId:s},amount:w.defaultBounty.toString()},maxBounty:{token:{...k,chainId:s},amount:w.maxBounty.toString()}};return{txs:[q],summary:`${v} Preview deltas: ${yt}.`,preview:M,orderId:r.toString(),fillable:!0,amountIn:z,minAmountOut:K,quotedAmountOut:bt,bounty:U,bountyBounds:pt,order:ft}}catch(o){throw new u(t.plainError(o))}}}}function Lt(t){return{name:"hookr_claim_bounty",inputSchema:{type:"object",properties:{to:{type:"string",description:"Optional recipient address for the claimed native ETH bounty (must be the signing wallet)."},minBounty:{type:"string",description:"Optional minimum claimable bounty in wei (decimal base-unit string)."},chainId:{type:"number",description:"Target chain ID (must be 4663)."}},additionalProperties:!1},async execute(n,i){try{ot(n),T(i);let o=a(i),s=et(n.chainId),r=n.to!==void 0&&n.to!==null?P(String(n.to)):P(o);if(r!==o)throw new u("Hookr bounty recipient must be the signing wallet.");let g=await t.clientFor(s).readContract({address:y,abi:B,functionName:"bountyOf",args:[o]}),m=BigInt(g);if(m<=0n)throw new u(`No claimable Hookr keeper bounty for ${o}.`);let b=E(n.minBounty,"minBounty");if(b!==void 0&&m<b)throw new u(`Claimable Hookr bounty (${m} wei) is below the requested minimum (${b} wei).`);let e=tt({abi:B,functionName:"claimBounty",args:[r]}),l=t.formatAmount(m.toString(),18),h=t.unsignedTx({to:y,data:e,value:"0",chainId:s,description:`Claim ${l} ETH (${m} wei) of accrued Hookr keeper bounty from ${y} to ${r}.`}),A=await t.preview([h],o),f=nt(A,t.formatAmount),H={token:{...k,chainId:s},amount:m.toString()};return{txs:[h],summary:`Claim ${l} ETH (${m} wei) Hookr keeper bounty to ${r}. Preview deltas: ${f}.`,preview:A,recipient:r,claimableBounty:H}}catch(o){throw new u(t.plainError(o))}}}}async function Nt(t,n){T(n);let i=a(n),o=t.clientFor(c);try{let s=await o.readContract({address:y,abi:B,functionName:"bountyOf",args:[i]}),r=BigInt(s);if(r<=0n)return[];let d=t.formatAmount(r.toString(),18);return[{module:gt,id:`hookr:bounty:${i.toLowerCase()}`,chainId:c,assets:[{token:{...k,chainId:c},amount:r.toString()}],description:`Hookr claimable keeper bounty (${d} ETH)`}]}catch(s){throw new u(t.plainError(s))}}var N=t=>({tools:[Et(t),Lt(t)],positions:n=>Nt(t,n)}),Xt=N,Wt=N,Vt=N;export{gt as a,y as b,At as c,wt as d,Ot as e,Bt as f,ht as g,B as h,Ht as i,jt as j,Et as k,Lt as l,Nt as m,N as n,Xt as o,Wt as p,Vt as q};
@@ -1 +1 @@
1
- import{b as le,o as K}from"./CAU44UWP.js";import{b as x}from"./UWOFA6GV.js";import{c as W,f as de,h as y,i as ce,l as ue}from"./73N3TOJL.js";import{a as k,i as oe,j as G}from"./XPFVT2EA.js";import{a as N}from"./5YS5V2LK.js";import{a as O}from"./JXOEJPJ4.js";import{randomBytes as ge,randomUUID as he}from"node:crypto";import{isDeepStrictEqual as pe}from"node:util";import{decodeFunctionData as me,encodeAbiParameters as ne,erc20Abi as J,keccak256 as ie,parseAbi as re,parseAbiParameters as ae,toEventSelector as be,zeroAddress as L}from"viem";var se=oe[k].meridian,Q=se.PredictionMarketEscrow.address,V=se.SecondaryMarketEscrow.address,$={address:se.CollateralToken_USDe.address,chainId:k,symbol:"USDe",decimals:18},we="wss://relayer.predict.meridian.xyz/auction",ke=ae("(address conditionResolver,bytes conditionId,uint8 predictedOutcome)[]"),Ie=ae("bytes32,uint256,uint256,address,address,address,bytes"),Se=ae("address,address,address,address,uint256,uint256"),X=re(["function isNonceUsed(address,uint256) view returns (bool)"]),Be=re(["function mint(((address conditionResolver,bytes conditionId,uint8 predictedOutcome)[] picks,uint256 predictorCollateral,uint256 counterpartyCollateral,address predictor,address counterparty,uint256 predictorNonce,uint256 counterpartyNonce,uint256 predictorDeadline,uint256 counterpartyDeadline,bytes predictorSignature,bytes counterpartySignature,bytes32 refCode,bytes predictorSessionKeyData,bytes counterpartySessionKeyData,address predictorSponsor,bytes predictorSponsorData) request)"]),Me=re(["function executeTrade((address token,address collateral,address seller,address buyer,uint256 tokenAmount,uint256 price,uint256 sellerNonce,uint256 buyerNonce,uint256 sellerDeadline,uint256 buyerDeadline,bytes sellerSignature,bytes buyerSignature,bytes32 refCode,bytes sellerSessionKeyData,bytes buyerSessionKeyData) request)"]),$e=be("Transfer(address,address,uint256)"),Ae=[{name:"predictionHash",type:"bytes32"},{name:"signer",type:"address"},{name:"collateral",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}],Ce=[{name:"tradeHash",type:"bytes32"},{name:"signer",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}];function i(n){throw new N(n)}function _(n){return de(n,"Meridian returned an invalid exchange object.")}function M(n,t,d=!1){return d&&typeof n=="number"&&Number.isSafeInteger(n)&&n>=0&&(n=String(n)),(typeof n!="string"||!/^\d+$/.test(n)||BigInt(n)>=1n<<256n)&&i(`Provide ${t} as a decimal base-unit integer string.`),n}function F(n){let t=Number(n);return(!Number.isSafeInteger(t)||t<0||BigInt(t)!==BigInt(n))&&i("Meridian signing terms cannot be represented exactly as JSON numbers."),t}function R(n){let t="Provide a nonzero token, resolver or wallet address.";return ue(ce(n,t),t)}function Z(n,t){return(typeof n!="string"||!/^0x(?:[0-9a-fA-F]{2})+$/.test(n)||t!==void 0&&n.length!==2+t*2)&&i("Meridian returned invalid hexadecimal data."),n}function v(n){return(typeof n!="string"||n.length===0||n.length>256)&&i("Meridian returned an invalid exchange identifier."),n}function j(){return BigInt(Math.floor(Date.now()/1e3))}function ve(n,t){let d=n==="buy"?["picks","stake","minCounterpartyCollateral","usdgAmountIn","slippageBps","continuation","signature"]:["token","amount","minPrice","slippageBps","continuation","signature"];Object.keys(t).some(S=>!d.includes(S))&&i("Unsupported Meridian arguments; use the tool input schema."),t.slippageBps!==void 0&&(typeof t.slippageBps!="number"||!Number.isInteger(t.slippageBps)||t.slippageBps<0||t.slippageBps>=1e4)&&i("Slippage must be an integer from 0 to 9999 basis points.");let c=t.slippageBps;if(n==="sell"){let S=M(t.amount,"the position amount");BigInt(S)===0n&&i("The position amount must be positive.");let B=R(t.token);(y(B,$.address)||y(B,G))&&i("Choose a Meridian position token to sell.");let A;if(t.minPrice!==void 0){let e=M(t.minPrice,"the minimum sale price");BigInt(e)<=1n&&i("The minimum sale price must be greater than 1 base unit."),A=e}else{let e=BigInt(S)/100n>10n**18n?BigInt(S)/100n:10n**18n;A=c===void 0?e.toString():K(e.toString(),c)}return{side:n,token:B,amount:S,minPrice:A,priceFloorSource:t.minPrice===void 0?"default":"explicit",...c===void 0?{}:{slippageBps:c}}}(!Array.isArray(t.picks)||t.picks.length<1||t.picks.length>10)&&i("Provide between one and ten Meridian picks.");let m=t.picks.map(S=>{let B=_(S);return(Object.keys(B).some(A=>!["conditionResolver","conditionId","predictedOutcome"].includes(A))||B.predictedOutcome!==0&&B.predictedOutcome!==1)&&i("Each pick needs a resolver, condition ID and outcome 0 or 1."),{conditionResolver:R(B.conditionResolver),conditionId:Z(B.conditionId),predictedOutcome:B.predictedOutcome}}).sort((S,B)=>{let A=`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}:${S.predictedOutcome}`,e=`${B.conditionResolver.toLowerCase()}:${B.conditionId.toLowerCase()}:${B.predictedOutcome}`;return A<e?-1:A>e?1:0}),g=m.map(S=>`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}`);new Set(g).size!==m.length&&i("Do not repeat a condition in the same prediction.");let l=M(t.stake,"the USDe stake");BigInt(l)<10n**18n&&i("Meridian requires a stake of at least 1 USDe.");let I=t.usdgAmountIn===void 0?void 0:M(t.usdgAmountIn,"the USDG swap amount");I!==void 0&&BigInt(I)===0n&&i("The USDG swap amount must be positive.");let D=t.minCounterpartyCollateral!==void 0?M(t.minCounterpartyCollateral,"the minimum counterparty collateral"):K(l,c??le);return BigInt(D)<=1n&&i("The minimum counterparty collateral must be greater than 1 base unit."),{side:n,picks:m,stake:l,minCounterpartyCollateral:D,...I===void 0?{}:{usdgAmountIn:I},...c===void 0?{}:{slippageBps:c}}}var ee=class{constructor(t,d){this.id=t;this.prefix=d;this.socket=new globalThis.WebSocket(we),this.socket.addEventListener("open",()=>{this.opened=!0,this.notify?.()}),this.socket.addEventListener("close",()=>this.stop("Meridian exchange socket was lost. Start a fresh auction.")),this.socket.addEventListener("error",()=>this.stop("Meridian exchange socket failed. Start a fresh auction.")),this.socket.addEventListener("message",c=>{try{(typeof c.data!="string"||c.data.length>65536)&&i("Meridian returned a malformed exchange message.");let m=_(JSON.parse(c.data));if(m.type==="pong")return;let g=v(m.type),l=_(m.payload);if(g==="error"&&i("Meridian rejected or failed the exchange. Start a fresh auction."),g===`${d}.ack`){this.auctionId===void 0?((l.id!==t||this.accepting||l.accepted!==void 0)&&i("Meridian acknowledged a different exchange."),l.error!==void 0&&i(`Meridian rejected the exchange: ${O(v(l.error))}.`),this.auctionId=v(l.auctionId)):((!this.accepting||l.auctionId!==this.auctionId||l.id!==void 0&&l.id!==t)&&i("Meridian acknowledged a different exchange."),l.error!==void 0&&i(`Meridian rejected acceptance: ${O(v(l.error))}.`),l.accepted!==!0&&i("Meridian rejected acceptance of the exchange."));return}if((!g.startsWith(`${d}.`)||l.auctionId!==this.auctionId||!this.auctionId)&&i("Meridian returned a message for a different exchange."),["error","rejected","failed","expired"].some(I=>g===`${d}.${I}`)){let I=["reason","makerReason"].flatMap(D=>l[D]===void 0?[]:[`${D}=${O(v(l[D]))}`]);i(`Meridian exchange ${g.slice(d.length+1)}${I.length?`: ${I.join("; ")}`:""}. Start a fresh auction.`)}if((g===`${d}.pending`||g===`${d}.filled`)&&!this.accepting&&i("Meridian returned settlement before acceptance."),g===`${d}.pending`)return;this.queue.length>=16&&i("Meridian returned too many exchange messages."),this.queue.push({type:g,payload:l}),this.notify?.()}catch(m){this.stop(m instanceof N?m.message:"Meridian rejected or returned an invalid exchange message. Start a fresh auction.")}})}id;prefix;socket;queue=[];notify;error;auctionId;accepting=!1;opened=!1;check(){if(this.error)throw this.error;this.socket.readyState>1&&i("Meridian exchange socket was lost. Start a fresh auction.")}stop(t){this.error??=new N(t),this.notify?.(),this.socket.readyState<2&&this.socket.close()}async wait(t,d=3e4){return new Promise((c,m)=>{let g=setTimeout(()=>this.stop("Meridian exchange timed out. Start a fresh auction."),d),l=()=>{try{if(this.check(),t===void 0?!this.opened:!this.queue.length)return;let I=t===void 0?void 0:this.queue.shift();I&&I.type!==`${this.prefix}.${t}`&&i("Meridian returned an unexpected exchange stage."),clearTimeout(g),this.notify=void 0,c(I?.payload??{})}catch(I){clearTimeout(g),this.notify=void 0,m(I)}};this.notify=l,l()})}send(t,d){this.check(),this.socket.readyState!==1&&i("Meridian exchange socket is not open."),t==="accept"&&(this.accepting=!0),this.socket.send(JSON.stringify({...t==="start"?{id:this.id}:{},type:`${this.prefix}.${t}`,payload:d}))}};function te(n){return ie(ne(ke,[n]))}function De(n,t,d){return ie(ne(Ie,[te(n.picks),BigInt(n.stake),BigInt(d.counterpartyCollateral),t,d.counterparty,L,"0x"]))}function qe(n,t,d,c){return ie(ne(Se,[n.token,$.address,t,d,BigInt(n.amount),BigInt(c)]))}function Y(n,t){let{input:d,wallet:c,nonce:m,deadline:g}=n,l={name:d.side==="buy"?"PredictionMarketEscrow":"SecondaryMarketEscrow",version:"1",chainId:k,verifyingContract:n.continuation.escrowContract};return(!m||!g)&&i("Meridian exchange is missing its signing terms."),d.side==="buy"?(t||i("Meridian has not returned a winning bid."),{domain:l,primaryType:"MintApproval",types:{MintApproval:Ae},message:{predictionHash:De(d,c,t),signer:c,collateral:d.stake,nonce:m,deadline:g}}):{domain:l,primaryType:"TradeApproval",types:{TradeApproval:Ce},message:{tradeHash:qe(d,c,t?t.buyer:L,t?t.price:"0"),signer:c,nonce:m,deadline:g}}}function fe(n){let t=[BigInt(n.deadline)],d=n.continuation;if(d.stage==="primary_accept"||d.stage==="secondary_accept"){t.push(BigInt(d.acceptDeadline));let c=d.winningBid;d.stage==="primary_accept"&&t.push(BigInt(c.counterpartyDeadline)),c.buyerDeadline!==void 0&&t.push(BigInt(M(c.buyerDeadline,"the buyer deadline",!0)))}return t.reduce((c,m)=>c<m?c:m)}function H(n){n.channel?.check(),n.deadline&&j()>=fe(n)&&i("Meridian exchange expired. Start a fresh auction.")}var Oe=n=>{let t=new Map;function d(e){clearTimeout(e.timer),t.delete(e.continuation.requestId),e.channel?.stop("Meridian exchange is closed or expired. Start a fresh auction.")}function c(e,a){clearTimeout(e.timer),e.timer=setTimeout(()=>d(e),a),e.timer.unref?.()}function m(e){let{wallet:a,chainId:s,escrowContract:f,requestId:u}=e.continuation;return{wallet:a,chainId:s,escrowContract:f,requestId:u}}function g(e){return e.side!=="sell"?"":` Effective minimum sale proceeds: ${e.minPrice} USDe base units (${$.address}, 18 decimals). ${e.priceFloorSource==="explicit"?"Caller minPrice is unchanged; slippageBps does not reduce this floor.":`Default floor with ${e.slippageBps??0} bps slippage applied.`}`}async function l(e){let{input:a,wallet:s}=e,f=n.clientFor(k),u=a.side==="buy"?$.address:a.token,r=a.side==="buy"?a.stake:a.amount,[h,w]=await Promise.all([f.readContract({address:u,abi:J,functionName:"balanceOf",args:[s]}),f.readContract({address:u,abi:J,functionName:"allowance",args:[s,e.continuation.escrowContract]})]);if(a.side==="sell"&&await f.readContract({address:u,abi:J,functionName:"decimals"})!==18&&i("Meridian position tokens must have 18 decimals."),h>=BigInt(r)&&w>=BigInt(r))return;(e.continuation.stage==="primary_accept"||e.continuation.stage==="secondary_accept")&&i("Meridian prerequisites changed during the auction. Start a fresh auction after funding and approval.");let p,C;if(h<BigInt(r)){a.side==="sell"&&i("The wallet does not have enough position tokens to sell."),a.usdgAmountIn||i("Not enough USDe. Provide usdgAmountIn in USDG base units to quote a swap before the auction.");let b=await n.quoteSwap({from:G,to:$.address,amountIn:a.usdgAmountIn,...a.slippageBps===void 0?{}:{slippageBps:a.slippageBps}},s);(j()>=BigInt(M(b.expiresAt,"the swap expiry"))||BigInt(M(b.minAmountOut,"the swap minimum"))+h<BigInt(r))&&i("The USDG swap minimum does not cover the USDe stake, or the quote expired. Request a fresh quote with sufficient input.");let o=await n.buildSwap(b.quoteId,s);(!("txs"in o)||!o.txs.length)&&i("The swap coordinator did not return prerequisite transactions."),p=o.txs,C=`${o.summary} Minimum USDe output: ${b.minAmountOut} base units (18 decimals).`}else p=[n.approval(u,e.continuation.escrowContract,r,k)],C=`Approve exactly ${r} base units (18 decimals) of ${u} for ${e.continuation.escrowContract} on chain ${k}.`;p.some(b=>b.chainId!==k)&&i("Meridian prerequisite transactions must use chain 4663.");let q=await n.preview(p,s),T=q.changes.map(b=>{let o=b.amount.startsWith("-");return`${o?"-":"+"}${n.formatAmount(o?b.amount.slice(1):b.amount,b.token.decimals)} ${b.token.symbol} (${b.token.address}, chain ${b.token.chainId}, ${b.token.decimals} decimals)`}).join("; ");return e.channel?.stop("Meridian prerequisites must be mined before the auction."),e.channel=void 0,e.deadline=void 0,e.nonce=void 0,e.continuation={...m(e),stage:"prerequisites"},{steps:p.map(b=>({kind:"tx",tx:b})),continuation:structuredClone(e.continuation),summary:`${C}${g(a)} ${q.summary} ${T}. Mine these prerequisites before continuing; no RFQ has started.`}}function I(e){let a=e.continuation;a.stage==="prerequisites"&&i("Meridian prerequisites need to finish before signing."),H(e),c(e,Number(fe(e)-j())*1e3);let s=e.input,f=s.side==="buy"?`Stake ${s.stake} base units of USDe (${$.address}, 18 decimals)`:`Sell ${s.amount} base units of position ${s.token} (18 decimals)`,u=a.stage==="secondary_start"?"Initial buyer-zero, price-zero intent only.":a.stage==="primary_accept"?`Counterparty ${a.winningBid.counterparty}; counterparty collateral ${a.winningBid.counterpartyCollateral} USDe base units; counterparty deadline ${a.winningBid.counterpartyDeadline}.`:`Buyer ${a.winningBid.buyer}; receive ${a.winningBid.price} USDe base units (${$.address}, 18 decimals).`;return{steps:[{kind:"typedData",request:structuredClone(a.request)}],continuation:structuredClone(a),summary:`${f} on chain ${k}.${g(s)} Approval was checked on chain. ${u} Sign locally for domain ${a.request.domain.name}, version 1, escrow ${a.escrowContract}, signature deadline ${e.deadline}${"acceptDeadline"in a?`, acceptance deadline ${a.acceptDeadline}`:""}. External relayer settlement is pending; a signature is not a fill.`}}async function D(e){let a=await e.channel.wait("result"),s=_(a.winningBid),f=v(a.auctionId);s.auctionId!==f&&i("Meridian winning bid belongs to another auction.");let u=M(a.acceptDeadline,"the acceptance deadline",!0);if(e.input.side==="buy"){let r={auctionId:f,counterparty:v(s.counterparty),counterpartyCollateral:M(s.counterpartyCollateral,"the counterparty collateral"),counterpartyNonce:M(s.counterpartyNonce,"the counterparty nonce",!0),counterpartyDeadline:M(s.counterpartyDeadline,"the counterparty deadline",!0),receivedAt:v(s.receivedAt)};R(r.counterparty),(!Number.isFinite(Date.parse(r.receivedAt))||BigInt(r.counterpartyCollateral)<=1n||BigInt(r.counterpartyCollateral)<BigInt(e.input.minCounterpartyCollateral))&&i("Meridian winning bid counterparty collateral is below the caller minimum."),e.continuation={...m(e),stage:"primary_accept",auctionId:f,winningBid:r,acceptDeadline:u,request:Y(e,r)}}else{let r={auctionId:f,buyer:v(s.buyer),price:M(s.price,"the sale price"),...s.buyerDeadline!==void 0?{buyerDeadline:M(s.buyerDeadline,"the buyer deadline",!0)}:{},...s.buyerNonce!==void 0?{buyerNonce:M(s.buyerNonce,"the buyer nonce",!0)}:{},...s.receivedAt!==void 0?{receivedAt:v(s.receivedAt)}:{}};R(r.buyer),(BigInt(r.price)<=1n||BigInt(r.price)<BigInt(e.input.minPrice))&&i("Meridian winning bid sale price is below the caller minimum."),e.continuation={...m(e),stage:"secondary_accept",auctionId:f,winningBid:r,acceptDeadline:u,request:Y(e,r)}}return I(e)}async function S(e,a){let s=e.continuation;s.stage!=="primary_accept"&&s.stage!=="secondary_accept"&&i("Meridian exchange is not ready for acceptance."),H(e),e.channel.send("accept",{auctionId:s.auctionId,[e.input.side==="buy"?"predictorSignature":"sellerSignature"]:a}),c(e,15e4);let f=await e.channel.wait("filled",12e4),u=Z(f.transactionHash,32),r=n.clientFor(k),[h,w]=await Promise.all([r.waitForTransactionReceipt({hash:u,timeout:12e4}),r.getTransaction({hash:u})]);(h.status!=="success"||!y(h.transactionHash,u)||!y(w.hash,u)||!y(h.to,s.escrowContract)||!y(w.to,s.escrowContract)||w.chainId!==k)&&i("Meridian fill has no matching successful receipt on chain 4663.");let{input:p,wallet:C}=e;if(p.side==="buy"&&s.stage==="primary_accept"){let o=me({abi:Be,data:w.input}).args[0];(!y(te([...o.picks]),te(p.picks))||o.predictorCollateral!==BigInt(p.stake)||o.counterpartyCollateral!==BigInt(s.winningBid.counterpartyCollateral)||!y(o.predictor,C)||!y(o.counterparty,s.winningBid.counterparty)||o.predictorNonce!==BigInt(e.nonce)||o.predictorDeadline!==BigInt(e.deadline)||!y(o.predictorSponsor,L)||o.predictorSponsorData!=="0x"||!y(o.predictorSignature,a))&&i("Meridian mint receipt does not match the accepted prediction.")}else if(p.side==="sell"&&s.stage==="secondary_accept"){let o=me({abi:Me,data:w.input}).args[0];(!y(o.token,p.token)||!y(o.collateral,$.address)||!y(o.seller,C)||!y(o.buyer,s.winningBid.buyer)||o.tokenAmount!==BigInt(p.amount)||o.price!==BigInt(s.winningBid.price)||o.sellerNonce!==BigInt(e.nonce)||o.sellerDeadline!==BigInt(e.deadline)||!y(o.sellerSignature,a))&&i("Meridian sale receipt does not match the accepted trade.")}let q=new Map,T=new Map;for(let o of h.logs){if(o.topics[0]!==$e||o.topics.length!==3)continue;(!/^0x[0-9a-fA-F]{64}$/.test(o.data)||!o.topics.slice(1).every(ye=>/^0x0{24}[0-9a-fA-F]{40}$/.test(ye)))&&i("Meridian receipt has malformed transfer logs.");let E=`0x${o.topics[1].slice(-40)}`,U=`0x${o.topics[2].slice(-40)}`,P=o.address.toLowerCase(),z=BigInt(o.data);q.set(P,(q.get(P)??0n)+(y(U,C)?z:0n)-(y(E,C)?z:0n)),y(E,L)&&y(U,C)&&T.set(P,(T.get(P)??0n)+z)}let b;if(p.side==="buy"&&s.stage==="primary_accept"){let o=BigInt(p.stake)+BigInt(s.winningBid.counterpartyCollateral),E=[...T].filter(([U,P])=>!y(U,$.address)&&P===o&&q.get(U)===o);(E.length!==1||q.get($.address.toLowerCase())!==-BigInt(p.stake))&&i("Meridian mint receipt does not prove the expected collateral and position delta."),b=`${o} base units received in position ${E[0][0]}`}else p.side==="sell"&&s.stage==="secondary_accept"?((q.get(p.token.toLowerCase())!==-BigInt(p.amount)||q.get($.address.toLowerCase())!==BigInt(s.winningBid.price))&&i("Meridian sale receipt does not prove the expected collateral and position delta."),b=`${p.amount} base units sold from position ${p.token}; ${s.winningBid.price} USDe base units received`):i("Meridian fill has a different exchange stage.");return{txs:[],hashes:[u],status:"mined",summary:`Mined: ${u}. Status: mined. Meridian ${p.side} filled by the external relayer. Successful receipt and transfer deltas verified on chain ${k}: ${b} (18 decimals); collateral USDe ${$.address} (18 decimals).`}}async function B(e,a,s){let f=R(s),u=ve(e,a),r;if(a.continuation!==void 0){let h=_(a.continuation),w=t.get(v(h.requestId));w||i("Meridian exchange is lost or expired. Start a fresh auction."),(!y(w.wallet,f)||!pe(w.input,u)||!pe(w.continuation,h))&&i("Meridian continuation or arguments do not match the active wallet exchange."),w.busy&&i("Meridian exchange is already processing this continuation."),r=w}else{a.signature!==void 0&&i("A signature requires an active Meridian continuation."),t.size>=1e3&&i("Too many active Meridian exchanges. Please try again later.");let h=he(),w=setTimeout(()=>{let p=t.get(h);p&&d(p)},9e5);w.unref?.(),r={input:u,wallet:f,continuation:{stage:"prerequisites",wallet:f,chainId:k,escrowContract:e==="buy"?Q:V,requestId:h},busy:!1,timer:w},t.set(h,r)}r.busy=!0;try{H(r),await n.clientFor(k).getChainId()!==k&&i("Meridian requires an RPC on chain 4663.");let h=r.continuation.stage;h==="prerequisites"&&a.signature!==void 0&&i("Do not sign before Meridian prerequisites have mined.");let w=await l(r);if(w)return w;if(h==="prerequisites")return r.nonce=(ge(4).readUInt32BE()+1).toString(),r.deadline=(j()+300n).toString(),await n.clientFor(k).readContract({address:r.continuation.escrowContract,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i(`Meridian ${e==="buy"?"predictor":"seller"} nonce is already used. Start a fresh auction.`),r.channel=new ee(r.continuation.requestId,e==="buy"?"auction":"secondary.auction"),await r.channel.wait(),u.side==="buy"?(r.channel.send("start",{id:r.continuation.requestId,picks:u.picks,predictorCollateral:u.stake,predictor:f,predictorNonce:F(r.nonce),predictorDeadline:F(r.deadline),chainId:k,escrowContract:Q,mode:"blind"}),await D(r)):(r.continuation={...m(r),stage:"secondary_start",request:Y(r)},I(r));let p=Z(a.signature);if(e==="sell"&&await n.clientFor(k).readContract({address:V,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i("Meridian seller nonce is already used. Start a fresh auction."),e==="buy"&&await n.clientFor(k).readContract({address:Q,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i("Meridian predictor nonce is already used. Start a fresh auction."),H(r),h==="secondary_start"&&u.side==="sell")return r.channel.send("start",{id:r.continuation.requestId,token:u.token,collateral:$.address,tokenAmount:u.amount,seller:f,sellerNonce:F(r.nonce),sellerDeadline:F(r.deadline),chainId:k,escrowContract:V,mode:"blind",sellerSignature:p}),await D(r);let C=await S(r,p);return d(r),C}catch(h){throw d(r),new N(n.plainError(h))}finally{r.busy=!1}}let A={continuation:{type:"object"},signature:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"}};return{tools:[{name:"meridian_buy",inputSchema:{type:"object",additionalProperties:!1,required:["picks","stake"],properties:{...A,stake:x("USDe stake in base units, 18 decimals, chain 4663."),minCounterpartyCollateral:x("Optional caller minimum counterparty collateral in USDe base units, 18 decimals."),usdgAmountIn:x("Optional exact USDG swap input in base units, 6 decimals, if USDe balance is insufficient."),slippageBps:{type:"integer",minimum:0,maximum:9999},picks:{type:"array",minItems:1,maxItems:10,items:{type:"object",additionalProperties:!1,required:["conditionResolver","conditionId","predictedOutcome"],properties:{conditionResolver:W,conditionId:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"},predictedOutcome:{type:"integer",enum:[0,1]}}}}}},execute:(e,a)=>B("buy",e,a)},{name:"meridian_sell",inputSchema:{type:"object",additionalProperties:!1,required:["token","amount"],properties:{...A,token:{...W,description:"Position token address on chain 4663."},amount:x("Position amount in base units, 18 decimals."),minPrice:x("Optional minimum total sale proceeds in USDe base units, 18 decimals. Explicit minPrice is never reduced by slippageBps."),slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Applied only to the default sale floor when minPrice is omitted."}}},execute:(e,a)=>B("sell",e,a)}]}};export{Ae as a,Ce as b,Oe as c};
1
+ import{b as le,o as K}from"./5O5ZE3ZV.js";import{b as x}from"./UWOFA6GV.js";import{c as W,f as de,h as y,i as ce,l as ue}from"./73N3TOJL.js";import{a as k,i as oe,j as G}from"./G6HCV67X.js";import{a as N}from"./5YS5V2LK.js";import{a as O}from"./JXOEJPJ4.js";import{randomBytes as ge,randomUUID as he}from"node:crypto";import{isDeepStrictEqual as pe}from"node:util";import{decodeFunctionData as me,encodeAbiParameters as ne,erc20Abi as J,keccak256 as ie,parseAbi as re,parseAbiParameters as ae,toEventSelector as be,zeroAddress as L}from"viem";var se=oe[k].meridian,Q=se.PredictionMarketEscrow.address,V=se.SecondaryMarketEscrow.address,$={address:se.CollateralToken_USDe.address,chainId:k,symbol:"USDe",decimals:18},we="wss://relayer.predict.meridian.xyz/auction",ke=ae("(address conditionResolver,bytes conditionId,uint8 predictedOutcome)[]"),Ie=ae("bytes32,uint256,uint256,address,address,address,bytes"),Se=ae("address,address,address,address,uint256,uint256"),X=re(["function isNonceUsed(address,uint256) view returns (bool)"]),Be=re(["function mint(((address conditionResolver,bytes conditionId,uint8 predictedOutcome)[] picks,uint256 predictorCollateral,uint256 counterpartyCollateral,address predictor,address counterparty,uint256 predictorNonce,uint256 counterpartyNonce,uint256 predictorDeadline,uint256 counterpartyDeadline,bytes predictorSignature,bytes counterpartySignature,bytes32 refCode,bytes predictorSessionKeyData,bytes counterpartySessionKeyData,address predictorSponsor,bytes predictorSponsorData) request)"]),Me=re(["function executeTrade((address token,address collateral,address seller,address buyer,uint256 tokenAmount,uint256 price,uint256 sellerNonce,uint256 buyerNonce,uint256 sellerDeadline,uint256 buyerDeadline,bytes sellerSignature,bytes buyerSignature,bytes32 refCode,bytes sellerSessionKeyData,bytes buyerSessionKeyData) request)"]),$e=be("Transfer(address,address,uint256)"),Ae=[{name:"predictionHash",type:"bytes32"},{name:"signer",type:"address"},{name:"collateral",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}],Ce=[{name:"tradeHash",type:"bytes32"},{name:"signer",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}];function i(n){throw new N(n)}function _(n){return de(n,"Meridian returned an invalid exchange object.")}function M(n,t,d=!1){return d&&typeof n=="number"&&Number.isSafeInteger(n)&&n>=0&&(n=String(n)),(typeof n!="string"||!/^\d+$/.test(n)||BigInt(n)>=1n<<256n)&&i(`Provide ${t} as a decimal base-unit integer string.`),n}function F(n){let t=Number(n);return(!Number.isSafeInteger(t)||t<0||BigInt(t)!==BigInt(n))&&i("Meridian signing terms cannot be represented exactly as JSON numbers."),t}function R(n){let t="Provide a nonzero token, resolver or wallet address.";return ue(ce(n,t),t)}function Z(n,t){return(typeof n!="string"||!/^0x(?:[0-9a-fA-F]{2})+$/.test(n)||t!==void 0&&n.length!==2+t*2)&&i("Meridian returned invalid hexadecimal data."),n}function v(n){return(typeof n!="string"||n.length===0||n.length>256)&&i("Meridian returned an invalid exchange identifier."),n}function j(){return BigInt(Math.floor(Date.now()/1e3))}function ve(n,t){let d=n==="buy"?["picks","stake","minCounterpartyCollateral","usdgAmountIn","slippageBps","continuation","signature"]:["token","amount","minPrice","slippageBps","continuation","signature"];Object.keys(t).some(S=>!d.includes(S))&&i("Unsupported Meridian arguments; use the tool input schema."),t.slippageBps!==void 0&&(typeof t.slippageBps!="number"||!Number.isInteger(t.slippageBps)||t.slippageBps<0||t.slippageBps>=1e4)&&i("Slippage must be an integer from 0 to 9999 basis points.");let c=t.slippageBps;if(n==="sell"){let S=M(t.amount,"the position amount");BigInt(S)===0n&&i("The position amount must be positive.");let B=R(t.token);(y(B,$.address)||y(B,G))&&i("Choose a Meridian position token to sell.");let A;if(t.minPrice!==void 0){let e=M(t.minPrice,"the minimum sale price");BigInt(e)<=1n&&i("The minimum sale price must be greater than 1 base unit."),A=e}else{let e=BigInt(S)/100n>10n**18n?BigInt(S)/100n:10n**18n;A=c===void 0?e.toString():K(e.toString(),c)}return{side:n,token:B,amount:S,minPrice:A,priceFloorSource:t.minPrice===void 0?"default":"explicit",...c===void 0?{}:{slippageBps:c}}}(!Array.isArray(t.picks)||t.picks.length<1||t.picks.length>10)&&i("Provide between one and ten Meridian picks.");let m=t.picks.map(S=>{let B=_(S);return(Object.keys(B).some(A=>!["conditionResolver","conditionId","predictedOutcome"].includes(A))||B.predictedOutcome!==0&&B.predictedOutcome!==1)&&i("Each pick needs a resolver, condition ID and outcome 0 or 1."),{conditionResolver:R(B.conditionResolver),conditionId:Z(B.conditionId),predictedOutcome:B.predictedOutcome}}).sort((S,B)=>{let A=`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}:${S.predictedOutcome}`,e=`${B.conditionResolver.toLowerCase()}:${B.conditionId.toLowerCase()}:${B.predictedOutcome}`;return A<e?-1:A>e?1:0}),g=m.map(S=>`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}`);new Set(g).size!==m.length&&i("Do not repeat a condition in the same prediction.");let l=M(t.stake,"the USDe stake");BigInt(l)<10n**18n&&i("Meridian requires a stake of at least 1 USDe.");let I=t.usdgAmountIn===void 0?void 0:M(t.usdgAmountIn,"the USDG swap amount");I!==void 0&&BigInt(I)===0n&&i("The USDG swap amount must be positive.");let D=t.minCounterpartyCollateral!==void 0?M(t.minCounterpartyCollateral,"the minimum counterparty collateral"):K(l,c??le);return BigInt(D)<=1n&&i("The minimum counterparty collateral must be greater than 1 base unit."),{side:n,picks:m,stake:l,minCounterpartyCollateral:D,...I===void 0?{}:{usdgAmountIn:I},...c===void 0?{}:{slippageBps:c}}}var ee=class{constructor(t,d){this.id=t;this.prefix=d;this.socket=new globalThis.WebSocket(we),this.socket.addEventListener("open",()=>{this.opened=!0,this.notify?.()}),this.socket.addEventListener("close",()=>this.stop("Meridian exchange socket was lost. Start a fresh auction.")),this.socket.addEventListener("error",()=>this.stop("Meridian exchange socket failed. Start a fresh auction.")),this.socket.addEventListener("message",c=>{try{(typeof c.data!="string"||c.data.length>65536)&&i("Meridian returned a malformed exchange message.");let m=_(JSON.parse(c.data));if(m.type==="pong")return;let g=v(m.type),l=_(m.payload);if(g==="error"&&i("Meridian rejected or failed the exchange. Start a fresh auction."),g===`${d}.ack`){this.auctionId===void 0?((l.id!==t||this.accepting||l.accepted!==void 0)&&i("Meridian acknowledged a different exchange."),l.error!==void 0&&i(`Meridian rejected the exchange: ${O(v(l.error))}.`),this.auctionId=v(l.auctionId)):((!this.accepting||l.auctionId!==this.auctionId||l.id!==void 0&&l.id!==t)&&i("Meridian acknowledged a different exchange."),l.error!==void 0&&i(`Meridian rejected acceptance: ${O(v(l.error))}.`),l.accepted!==!0&&i("Meridian rejected acceptance of the exchange."));return}if((!g.startsWith(`${d}.`)||l.auctionId!==this.auctionId||!this.auctionId)&&i("Meridian returned a message for a different exchange."),["error","rejected","failed","expired"].some(I=>g===`${d}.${I}`)){let I=["reason","makerReason"].flatMap(D=>l[D]===void 0?[]:[`${D}=${O(v(l[D]))}`]);i(`Meridian exchange ${g.slice(d.length+1)}${I.length?`: ${I.join("; ")}`:""}. Start a fresh auction.`)}if((g===`${d}.pending`||g===`${d}.filled`)&&!this.accepting&&i("Meridian returned settlement before acceptance."),g===`${d}.pending`)return;this.queue.length>=16&&i("Meridian returned too many exchange messages."),this.queue.push({type:g,payload:l}),this.notify?.()}catch(m){this.stop(m instanceof N?m.message:"Meridian rejected or returned an invalid exchange message. Start a fresh auction.")}})}id;prefix;socket;queue=[];notify;error;auctionId;accepting=!1;opened=!1;check(){if(this.error)throw this.error;this.socket.readyState>1&&i("Meridian exchange socket was lost. Start a fresh auction.")}stop(t){this.error??=new N(t),this.notify?.(),this.socket.readyState<2&&this.socket.close()}async wait(t,d=3e4){return new Promise((c,m)=>{let g=setTimeout(()=>this.stop("Meridian exchange timed out. Start a fresh auction."),d),l=()=>{try{if(this.check(),t===void 0?!this.opened:!this.queue.length)return;let I=t===void 0?void 0:this.queue.shift();I&&I.type!==`${this.prefix}.${t}`&&i("Meridian returned an unexpected exchange stage."),clearTimeout(g),this.notify=void 0,c(I?.payload??{})}catch(I){clearTimeout(g),this.notify=void 0,m(I)}};this.notify=l,l()})}send(t,d){this.check(),this.socket.readyState!==1&&i("Meridian exchange socket is not open."),t==="accept"&&(this.accepting=!0),this.socket.send(JSON.stringify({...t==="start"?{id:this.id}:{},type:`${this.prefix}.${t}`,payload:d}))}};function te(n){return ie(ne(ke,[n]))}function De(n,t,d){return ie(ne(Ie,[te(n.picks),BigInt(n.stake),BigInt(d.counterpartyCollateral),t,d.counterparty,L,"0x"]))}function qe(n,t,d,c){return ie(ne(Se,[n.token,$.address,t,d,BigInt(n.amount),BigInt(c)]))}function Y(n,t){let{input:d,wallet:c,nonce:m,deadline:g}=n,l={name:d.side==="buy"?"PredictionMarketEscrow":"SecondaryMarketEscrow",version:"1",chainId:k,verifyingContract:n.continuation.escrowContract};return(!m||!g)&&i("Meridian exchange is missing its signing terms."),d.side==="buy"?(t||i("Meridian has not returned a winning bid."),{domain:l,primaryType:"MintApproval",types:{MintApproval:Ae},message:{predictionHash:De(d,c,t),signer:c,collateral:d.stake,nonce:m,deadline:g}}):{domain:l,primaryType:"TradeApproval",types:{TradeApproval:Ce},message:{tradeHash:qe(d,c,t?t.buyer:L,t?t.price:"0"),signer:c,nonce:m,deadline:g}}}function fe(n){let t=[BigInt(n.deadline)],d=n.continuation;if(d.stage==="primary_accept"||d.stage==="secondary_accept"){t.push(BigInt(d.acceptDeadline));let c=d.winningBid;d.stage==="primary_accept"&&t.push(BigInt(c.counterpartyDeadline)),c.buyerDeadline!==void 0&&t.push(BigInt(M(c.buyerDeadline,"the buyer deadline",!0)))}return t.reduce((c,m)=>c<m?c:m)}function H(n){n.channel?.check(),n.deadline&&j()>=fe(n)&&i("Meridian exchange expired. Start a fresh auction.")}var Oe=n=>{let t=new Map;function d(e){clearTimeout(e.timer),t.delete(e.continuation.requestId),e.channel?.stop("Meridian exchange is closed or expired. Start a fresh auction.")}function c(e,a){clearTimeout(e.timer),e.timer=setTimeout(()=>d(e),a),e.timer.unref?.()}function m(e){let{wallet:a,chainId:s,escrowContract:f,requestId:u}=e.continuation;return{wallet:a,chainId:s,escrowContract:f,requestId:u}}function g(e){return e.side!=="sell"?"":` Effective minimum sale proceeds: ${e.minPrice} USDe base units (${$.address}, 18 decimals). ${e.priceFloorSource==="explicit"?"Caller minPrice is unchanged; slippageBps does not reduce this floor.":`Default floor with ${e.slippageBps??0} bps slippage applied.`}`}async function l(e){let{input:a,wallet:s}=e,f=n.clientFor(k),u=a.side==="buy"?$.address:a.token,r=a.side==="buy"?a.stake:a.amount,[h,w]=await Promise.all([f.readContract({address:u,abi:J,functionName:"balanceOf",args:[s]}),f.readContract({address:u,abi:J,functionName:"allowance",args:[s,e.continuation.escrowContract]})]);if(a.side==="sell"&&await f.readContract({address:u,abi:J,functionName:"decimals"})!==18&&i("Meridian position tokens must have 18 decimals."),h>=BigInt(r)&&w>=BigInt(r))return;(e.continuation.stage==="primary_accept"||e.continuation.stage==="secondary_accept")&&i("Meridian prerequisites changed during the auction. Start a fresh auction after funding and approval.");let p,C;if(h<BigInt(r)){a.side==="sell"&&i("The wallet does not have enough position tokens to sell."),a.usdgAmountIn||i("Not enough USDe. Provide usdgAmountIn in USDG base units to quote a swap before the auction.");let b=await n.quoteSwap({from:G,to:$.address,amountIn:a.usdgAmountIn,...a.slippageBps===void 0?{}:{slippageBps:a.slippageBps}},s);(j()>=BigInt(M(b.expiresAt,"the swap expiry"))||BigInt(M(b.minAmountOut,"the swap minimum"))+h<BigInt(r))&&i("The USDG swap minimum does not cover the USDe stake, or the quote expired. Request a fresh quote with sufficient input.");let o=await n.buildSwap(b.quoteId,s);(!("txs"in o)||!o.txs.length)&&i("The swap coordinator did not return prerequisite transactions."),p=o.txs,C=`${o.summary} Minimum USDe output: ${b.minAmountOut} base units (18 decimals).`}else p=[n.approval(u,e.continuation.escrowContract,r,k)],C=`Approve exactly ${r} base units (18 decimals) of ${u} for ${e.continuation.escrowContract} on chain ${k}.`;p.some(b=>b.chainId!==k)&&i("Meridian prerequisite transactions must use chain 4663.");let q=await n.preview(p,s),T=q.changes.map(b=>{let o=b.amount.startsWith("-");return`${o?"-":"+"}${n.formatAmount(o?b.amount.slice(1):b.amount,b.token.decimals)} ${b.token.symbol} (${b.token.address}, chain ${b.token.chainId}, ${b.token.decimals} decimals)`}).join("; ");return e.channel?.stop("Meridian prerequisites must be mined before the auction."),e.channel=void 0,e.deadline=void 0,e.nonce=void 0,e.continuation={...m(e),stage:"prerequisites"},{steps:p.map(b=>({kind:"tx",tx:b})),continuation:structuredClone(e.continuation),summary:`${C}${g(a)} ${q.summary} ${T}. Mine these prerequisites before continuing; no RFQ has started.`}}function I(e){let a=e.continuation;a.stage==="prerequisites"&&i("Meridian prerequisites need to finish before signing."),H(e),c(e,Number(fe(e)-j())*1e3);let s=e.input,f=s.side==="buy"?`Stake ${s.stake} base units of USDe (${$.address}, 18 decimals)`:`Sell ${s.amount} base units of position ${s.token} (18 decimals)`,u=a.stage==="secondary_start"?"Initial buyer-zero, price-zero intent only.":a.stage==="primary_accept"?`Counterparty ${a.winningBid.counterparty}; counterparty collateral ${a.winningBid.counterpartyCollateral} USDe base units; counterparty deadline ${a.winningBid.counterpartyDeadline}.`:`Buyer ${a.winningBid.buyer}; receive ${a.winningBid.price} USDe base units (${$.address}, 18 decimals).`;return{steps:[{kind:"typedData",request:structuredClone(a.request)}],continuation:structuredClone(a),summary:`${f} on chain ${k}.${g(s)} Approval was checked on chain. ${u} Sign locally for domain ${a.request.domain.name}, version 1, escrow ${a.escrowContract}, signature deadline ${e.deadline}${"acceptDeadline"in a?`, acceptance deadline ${a.acceptDeadline}`:""}. External relayer settlement is pending; a signature is not a fill.`}}async function D(e){let a=await e.channel.wait("result"),s=_(a.winningBid),f=v(a.auctionId);s.auctionId!==f&&i("Meridian winning bid belongs to another auction.");let u=M(a.acceptDeadline,"the acceptance deadline",!0);if(e.input.side==="buy"){let r={auctionId:f,counterparty:v(s.counterparty),counterpartyCollateral:M(s.counterpartyCollateral,"the counterparty collateral"),counterpartyNonce:M(s.counterpartyNonce,"the counterparty nonce",!0),counterpartyDeadline:M(s.counterpartyDeadline,"the counterparty deadline",!0),receivedAt:v(s.receivedAt)};R(r.counterparty),(!Number.isFinite(Date.parse(r.receivedAt))||BigInt(r.counterpartyCollateral)<=1n||BigInt(r.counterpartyCollateral)<BigInt(e.input.minCounterpartyCollateral))&&i("Meridian winning bid counterparty collateral is below the caller minimum."),e.continuation={...m(e),stage:"primary_accept",auctionId:f,winningBid:r,acceptDeadline:u,request:Y(e,r)}}else{let r={auctionId:f,buyer:v(s.buyer),price:M(s.price,"the sale price"),...s.buyerDeadline!==void 0?{buyerDeadline:M(s.buyerDeadline,"the buyer deadline",!0)}:{},...s.buyerNonce!==void 0?{buyerNonce:M(s.buyerNonce,"the buyer nonce",!0)}:{},...s.receivedAt!==void 0?{receivedAt:v(s.receivedAt)}:{}};R(r.buyer),(BigInt(r.price)<=1n||BigInt(r.price)<BigInt(e.input.minPrice))&&i("Meridian winning bid sale price is below the caller minimum."),e.continuation={...m(e),stage:"secondary_accept",auctionId:f,winningBid:r,acceptDeadline:u,request:Y(e,r)}}return I(e)}async function S(e,a){let s=e.continuation;s.stage!=="primary_accept"&&s.stage!=="secondary_accept"&&i("Meridian exchange is not ready for acceptance."),H(e),e.channel.send("accept",{auctionId:s.auctionId,[e.input.side==="buy"?"predictorSignature":"sellerSignature"]:a}),c(e,15e4);let f=await e.channel.wait("filled",12e4),u=Z(f.transactionHash,32),r=n.clientFor(k),[h,w]=await Promise.all([r.waitForTransactionReceipt({hash:u,timeout:12e4}),r.getTransaction({hash:u})]);(h.status!=="success"||!y(h.transactionHash,u)||!y(w.hash,u)||!y(h.to,s.escrowContract)||!y(w.to,s.escrowContract)||w.chainId!==k)&&i("Meridian fill has no matching successful receipt on chain 4663.");let{input:p,wallet:C}=e;if(p.side==="buy"&&s.stage==="primary_accept"){let o=me({abi:Be,data:w.input}).args[0];(!y(te([...o.picks]),te(p.picks))||o.predictorCollateral!==BigInt(p.stake)||o.counterpartyCollateral!==BigInt(s.winningBid.counterpartyCollateral)||!y(o.predictor,C)||!y(o.counterparty,s.winningBid.counterparty)||o.predictorNonce!==BigInt(e.nonce)||o.predictorDeadline!==BigInt(e.deadline)||!y(o.predictorSponsor,L)||o.predictorSponsorData!=="0x"||!y(o.predictorSignature,a))&&i("Meridian mint receipt does not match the accepted prediction.")}else if(p.side==="sell"&&s.stage==="secondary_accept"){let o=me({abi:Me,data:w.input}).args[0];(!y(o.token,p.token)||!y(o.collateral,$.address)||!y(o.seller,C)||!y(o.buyer,s.winningBid.buyer)||o.tokenAmount!==BigInt(p.amount)||o.price!==BigInt(s.winningBid.price)||o.sellerNonce!==BigInt(e.nonce)||o.sellerDeadline!==BigInt(e.deadline)||!y(o.sellerSignature,a))&&i("Meridian sale receipt does not match the accepted trade.")}let q=new Map,T=new Map;for(let o of h.logs){if(o.topics[0]!==$e||o.topics.length!==3)continue;(!/^0x[0-9a-fA-F]{64}$/.test(o.data)||!o.topics.slice(1).every(ye=>/^0x0{24}[0-9a-fA-F]{40}$/.test(ye)))&&i("Meridian receipt has malformed transfer logs.");let E=`0x${o.topics[1].slice(-40)}`,U=`0x${o.topics[2].slice(-40)}`,P=o.address.toLowerCase(),z=BigInt(o.data);q.set(P,(q.get(P)??0n)+(y(U,C)?z:0n)-(y(E,C)?z:0n)),y(E,L)&&y(U,C)&&T.set(P,(T.get(P)??0n)+z)}let b;if(p.side==="buy"&&s.stage==="primary_accept"){let o=BigInt(p.stake)+BigInt(s.winningBid.counterpartyCollateral),E=[...T].filter(([U,P])=>!y(U,$.address)&&P===o&&q.get(U)===o);(E.length!==1||q.get($.address.toLowerCase())!==-BigInt(p.stake))&&i("Meridian mint receipt does not prove the expected collateral and position delta."),b=`${o} base units received in position ${E[0][0]}`}else p.side==="sell"&&s.stage==="secondary_accept"?((q.get(p.token.toLowerCase())!==-BigInt(p.amount)||q.get($.address.toLowerCase())!==BigInt(s.winningBid.price))&&i("Meridian sale receipt does not prove the expected collateral and position delta."),b=`${p.amount} base units sold from position ${p.token}; ${s.winningBid.price} USDe base units received`):i("Meridian fill has a different exchange stage.");return{txs:[],hashes:[u],status:"mined",summary:`Mined: ${u}. Status: mined. Meridian ${p.side} filled by the external relayer. Successful receipt and transfer deltas verified on chain ${k}: ${b} (18 decimals); collateral USDe ${$.address} (18 decimals).`}}async function B(e,a,s){let f=R(s),u=ve(e,a),r;if(a.continuation!==void 0){let h=_(a.continuation),w=t.get(v(h.requestId));w||i("Meridian exchange is lost or expired. Start a fresh auction."),(!y(w.wallet,f)||!pe(w.input,u)||!pe(w.continuation,h))&&i("Meridian continuation or arguments do not match the active wallet exchange."),w.busy&&i("Meridian exchange is already processing this continuation."),r=w}else{a.signature!==void 0&&i("A signature requires an active Meridian continuation."),t.size>=1e3&&i("Too many active Meridian exchanges. Please try again later.");let h=he(),w=setTimeout(()=>{let p=t.get(h);p&&d(p)},9e5);w.unref?.(),r={input:u,wallet:f,continuation:{stage:"prerequisites",wallet:f,chainId:k,escrowContract:e==="buy"?Q:V,requestId:h},busy:!1,timer:w},t.set(h,r)}r.busy=!0;try{H(r),await n.clientFor(k).getChainId()!==k&&i("Meridian requires an RPC on chain 4663.");let h=r.continuation.stage;h==="prerequisites"&&a.signature!==void 0&&i("Do not sign before Meridian prerequisites have mined.");let w=await l(r);if(w)return w;if(h==="prerequisites")return r.nonce=(ge(4).readUInt32BE()+1).toString(),r.deadline=(j()+300n).toString(),await n.clientFor(k).readContract({address:r.continuation.escrowContract,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i(`Meridian ${e==="buy"?"predictor":"seller"} nonce is already used. Start a fresh auction.`),r.channel=new ee(r.continuation.requestId,e==="buy"?"auction":"secondary.auction"),await r.channel.wait(),u.side==="buy"?(r.channel.send("start",{id:r.continuation.requestId,picks:u.picks,predictorCollateral:u.stake,predictor:f,predictorNonce:F(r.nonce),predictorDeadline:F(r.deadline),chainId:k,escrowContract:Q,mode:"blind"}),await D(r)):(r.continuation={...m(r),stage:"secondary_start",request:Y(r)},I(r));let p=Z(a.signature);if(e==="sell"&&await n.clientFor(k).readContract({address:V,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i("Meridian seller nonce is already used. Start a fresh auction."),e==="buy"&&await n.clientFor(k).readContract({address:Q,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i("Meridian predictor nonce is already used. Start a fresh auction."),H(r),h==="secondary_start"&&u.side==="sell")return r.channel.send("start",{id:r.continuation.requestId,token:u.token,collateral:$.address,tokenAmount:u.amount,seller:f,sellerNonce:F(r.nonce),sellerDeadline:F(r.deadline),chainId:k,escrowContract:V,mode:"blind",sellerSignature:p}),await D(r);let C=await S(r,p);return d(r),C}catch(h){throw d(r),new N(n.plainError(h))}finally{r.busy=!1}}let A={continuation:{type:"object"},signature:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"}};return{tools:[{name:"meridian_buy",inputSchema:{type:"object",additionalProperties:!1,required:["picks","stake"],properties:{...A,stake:x("USDe stake in base units, 18 decimals, chain 4663."),minCounterpartyCollateral:x("Optional caller minimum counterparty collateral in USDe base units, 18 decimals."),usdgAmountIn:x("Optional exact USDG swap input in base units, 6 decimals, if USDe balance is insufficient."),slippageBps:{type:"integer",minimum:0,maximum:9999},picks:{type:"array",minItems:1,maxItems:10,items:{type:"object",additionalProperties:!1,required:["conditionResolver","conditionId","predictedOutcome"],properties:{conditionResolver:W,conditionId:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"},predictedOutcome:{type:"integer",enum:[0,1]}}}}}},execute:(e,a)=>B("buy",e,a)},{name:"meridian_sell",inputSchema:{type:"object",additionalProperties:!1,required:["token","amount"],properties:{...A,token:{...W,description:"Position token address on chain 4663."},amount:x("Position amount in base units, 18 decimals."),minPrice:x("Optional minimum total sale proceeds in USDe base units, 18 decimals. Explicit minPrice is never reduced by slippageBps."),slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Applied only to the default sale floor when minPrice is omitted."}}},execute:(e,a)=>B("sell",e,a)}]}};export{Ae as a,Ce as b,Oe as c};
@@ -1 +1 @@
1
- import{a as e,i as r}from"./XPFVT2EA.js";var t='Use query (token name, symbol or address) or category to narrow tickerspring_tokens. Unfiltered requests and sort:"volume" alone can return an incomplete or inconsistent provider response; retry with a query or category filter.';function i(){return{summary:"Minimums: limit orders 10 USDG; independent ladder levels 10 USDG each; grids 11 USDG; ladder planner 55 USDG. Vaults use current minDepositUnits from tickerspring_vaults (not a fixed 25 USDG). Basket creation first deposit 25 USDG; check current basket quote for trade minimums.",minimums:{denomination:{address:r[e].tokens.USDG.address,symbol:"USDG",decimals:6,chainId:e},limitOrderNotional:"10000000",independentLadderLevelNotional:"10000000",gridBudget:"11000000",ladderPlannerBudget:"55000000",vaultDeposit:{source:"tickerspring_vaults",field:"minDepositUnits",policy:"Per-vault current minimum; do not assume the 25 USDG example is a minimum."},basketCreationFirstDepositNotional:"25000000",basketTrade:{source:"tickerspring_baskets and current prepare quote",policy:"Check current provider minimum for the selected basket and payment token."}},tokenFilterGuidance:t}}export{t as a,i as b};
1
+ import{a as e,i as r}from"./G6HCV67X.js";var t='Use query (token name, symbol or address) or category to narrow tickerspring_tokens. Unfiltered requests and sort:"volume" alone can return an incomplete or inconsistent provider response; retry with a query or category filter.';function i(){return{summary:"Minimums: limit orders 10 USDG; independent ladder levels 10 USDG each; grids 11 USDG; ladder planner 55 USDG. Vaults use current minDepositUnits from tickerspring_vaults (not a fixed 25 USDG). Basket creation first deposit 25 USDG; check current basket quote for trade minimums.",minimums:{denomination:{address:r[e].tokens.USDG.address,symbol:"USDG",decimals:6,chainId:e},limitOrderNotional:"10000000",independentLadderLevelNotional:"10000000",gridBudget:"11000000",ladderPlannerBudget:"55000000",vaultDeposit:{source:"tickerspring_vaults",field:"minDepositUnits",policy:"Per-vault current minimum; do not assume the 25 USDG example is a minimum."},basketCreationFirstDepositNotional:"25000000",basketTrade:{source:"tickerspring_baskets and current prepare quote",policy:"Check current provider minimum for the selected basket and payment token."}},tokenFilterGuidance:t}}export{t as a,i as b};
@@ -1 +1 @@
1
- import{a as j}from"./XW7RH7YY.js";import{a as V}from"./G4PDM3MX.js";import{b as H,c as Z,d as z,e as J}from"./KQFDLDHL.js";import{a as L}from"./JRVTSGAT.js";import{c as W}from"./EC5W3UZD.js";import{b as $,o as q}from"./CAU44UWP.js";import{b as _}from"./AXYOJBX6.js";import{a as x,d as B,e as E}from"./6IM6A5VA.js";import{a as D}from"./UWOFA6GV.js";import{g as A,m as R,n as U}from"./73N3TOJL.js";import{a as h,d as N,i as I,j as S}from"./XPFVT2EA.js";import{a as o}from"./5YS5V2LK.js";import{getAddress as F,parseAbi as ee}from"viem";var a=F(I[4663].vaults.groveAlm.address),te="0x29626c2d8ca49a51e4deceec5499e52983c42bd5",d=ee(["function asset() view returns (address)","function decimals() view returns (uint8)","function totalAssets() view returns (uint256)","function totalSupply() view returns (uint256)","function balanceOf(address) view returns (uint256)","function maxDeposit(address) view returns (uint256)","function maxWithdraw(address) view returns (uint256)","function previewDeposit(uint256) view returns (uint256)","function previewRedeem(uint256) view returns (uint256)","function performanceFee() view returns (uint256)","function managementFee() view returns (uint256)"]),T=D("Positive integer in token base units."),M={type:"string",description:`Public Grove vault only: ${a}. Defaults to this vault.`},K={type:"integer",minimum:0,maximum:9999,default:$};function C(t){return U(t,"Amount must be positive and within the uint256 range.",{notString:"Amount must be a positive integer string in base units.",positive:!0})}function v(t){return R(t,"Grove returned an invalid integer read.")}function O(t,m,l){if(x(m),Object.keys(t).some(u=>!["vault",...l].includes(u)))throw new o("Unsupported Grove argument.");if(t.vault!==void 0){if(typeof t.vault!="string")throw new o("Provide the public Grove vault address.");if(t.vault.toLowerCase()===te)throw new o("The Grove ALM proxy is allocator infrastructure, not the public ERC-4626 vault.");if(x(t.vault),!A(t.vault,a))throw new o("Only the public Grove ERC-4626 vault is supported.")}}function Q(t,m,l){let u=l===void 0?$:l;if(typeof u!="number")throw new o("Slippage must be an integer from 0 to 9999 bps.");let e=BigInt(q(t.toString(),u)),n=m===void 0?e:C(m);if(n<=0n||n>t)throw new o("The minimum output must be positive and no greater than the quoted output.");return n}function X(t,m){let l=0n;for(let u of t.changes)if(!(u.token.chainId!==m.chainId||!A(u.token.address,m.address))){if(u.token.decimals!==m.decimals||typeof u.amount!="string"||!/^-?\d+$/.test(u.amount))throw new o("Grove preview returned invalid token metadata or amounts.");l+=BigInt(u.amount)}return l}var ne=t=>{async function m(e){try{return await e()}catch(n){throw new o(t.plainError(n))}}async function l(){let e=t.clientFor(h);if(await e.getChainId()!==h)throw new o("Grove requires an RPC endpoint on chain 4663.");let n=await e.readContract({address:a,abi:d,functionName:"asset"});if(typeof n!="string"||!A(n,S))throw new o("The public Grove vault must use canonical USDG on chain 4663.");let[i,s]=await Promise.all([e.readContract({address:F(S),abi:d,functionName:"decimals"}),e.readContract({address:a,abi:d,functionName:"decimals"})]);if(i!==N||s!==18)throw new o("Grove token decimals differ from the evidenced USDG/share interface.");let r={address:F(S),chainId:h,decimals:i,symbol:"USDG"};return{client:e,asset:r,shareToken:{address:a,chainId:h,decimals:s,symbol:"Grove shares"}}}async function u(e,n,i,s,r,p){let f=await t.preview(e,n);if(X(f,i)!==-s)throw new o("Grove simulation did not show the exact requested token outflow.");if(X(f,r)<p)throw new o("Grove simulated output is below the minimum.");let g=f.changes.map(({token:w,amount:b})=>{let y=b.startsWith("-");return`${y?"-":"+"}${t.formatAmount(y?b.slice(1):b,w.decimals)} ${w.symbol} (${w.address}, chain ${w.chainId})`}).join("; ");return{txs:e,summary:`${f.summary} ${g}. Minimum ${p} base units of ${r.address} is a preview check, not enforced on-chain by standard ERC-4626. Re-preview before signing; execution output can change.`}}return{tools:[Z(t,"grove_details",a),L(t,"grove_analytics",a),V(t,"grove_manage",a),...j(t,"grove",a),{name:"grove_list",inputSchema:{type:"object",properties:{vault:M},additionalProperties:!1},execute:(e,n)=>m(async()=>{O(e,n,[]);let{client:i,asset:s,shareToken:r}=await l(),[p,f,c,g,w,b]=await Promise.all([i.readContract({address:a,abi:d,functionName:"totalAssets"}),i.readContract({address:a,abi:d,functionName:"totalSupply"}),i.readContract({address:a,abi:d,functionName:"maxDeposit",args:[n]}),i.readContract({address:a,abi:d,functionName:"maxWithdraw",args:[n]}),i.readContract({address:a,abi:d,functionName:"performanceFee"}),i.readContract({address:a,abi:d,functionName:"managementFee"})]);return[{vault:a,chainId:h,name:"Grove x Steakhouse USDG",asset:s,shareToken:r,totalAssets:{token:s,amount:v(p).toString()},totalSupply:{token:r,amount:v(f).toString()},maxDeposit:v(c)===0n?null:c.toString(),maxWithdraw:v(g)===0n?null:g.toString(),maxViewCaveat:"Zero Morpho V2 maximum views mean unknown capacity. Simulate the requested action; full exits use the fresh share balance.",fees:{performanceFeeRaw:v(w).toString(),managementFeeRaw:v(b).toString(),scale:"1000000000000000000",managementFeeTimeUnit:"second",performanceFeeBasis:"accrued interest"}}]})},{name:"grove_deposit",inputSchema:{type:"object",properties:{vault:M,amount:T,minSharesOut:T,slippageBps:K},required:["amount"],additionalProperties:!1},execute:(e,n)=>m(async()=>{O(e,n,["amount","minSharesOut","slippageBps"]);let i=C(e.amount),{client:s,asset:r,shareToken:p}=await l(),f=v(await s.readContract({address:a,abi:d,functionName:"previewDeposit",args:[i]})),c=Q(f,e.minSharesOut,e.slippageBps),g=B(a,r.address,i.toString(),n,h),w=[t.approval(r.address,a,i.toString(),h),t.unsignedTx(g.txs[1])];return u(w,n,r,i,p,c)})},{name:"grove_withdraw",inputSchema:{type:"object",properties:{vault:M,shares:{oneOf:[T,{const:"all",description:"Redeem the fresh full share balance."}]},minAmountOut:T,slippageBps:K,force:{type:"boolean"},maxPenaltyAssets:D()},required:["shares"],additionalProperties:!1},execute:(e,n)=>m(async()=>{O(e,n,["shares","minAmountOut","slippageBps","force","maxPenaltyAssets"]);let i=e.shares==="all"?void 0:C(e.shares),{client:s,asset:r,shareToken:p}=await l(),f=v(await s.readContract({address:a,abi:d,functionName:"balanceOf",args:[n]})),c=i??f;if(c===0n||c>f)throw new o("The Grove share balance is insufficient for this withdrawal.");if(e.force!==void 0&&typeof e.force!="boolean")throw new o("force must be a boolean.");if(e.force===!0){if(e.shares!=="all"||e.slippageBps!==void 0)throw new o("Force exit requires shares all and an explicit minAmountOut; omit slippageBps.");let k=W(e.maxPenaltyAssets),Y=C(e.minAmountOut),G=await H(t,s,a,n,c,k),P=await t.preview([G.tx],n);return J(P.changes,a,c,Y),{txs:[G.tx],preview:P,summary:`${z(G.plan)} ${P.summary}`}}if(e.maxPenaltyAssets!==void 0)throw new o("maxPenaltyAssets requires force true.");let g=v(await s.readContract({address:a,abi:d,functionName:"previewRedeem",args:[c]})),w=Q(g,e.minAmountOut,e.slippageBps),y=E(a,c.toString(),n,h).txs.map(k=>t.unsignedTx({...k,description:`Redeem ${c} Grove share base units to the wallet.`}));return u(y,n,p,c,r,w)})}],positions:e=>m(async()=>{x(e);let{client:n,asset:i,shareToken:s}=await l(),r=v(await n.readContract({address:a,abi:d,functionName:"balanceOf",args:[e]}));if(r===0n)return[];let p=v(await n.readContract({address:a,abi:d,functionName:"previewRedeem",args:[r]}));return[{module:"grove",id:`${h}:${a.toLowerCase()}`,chainId:h,assets:[{token:i,amount:p.toString()}],description:`${t.formatAmount(r.toString(),s.decimals)} Grove shares (${r} base units, ${s.decimals} decimals, ${a}); estimated USDG redemption, subject to simulation.`}]})}},he=t=>_("grove",[ne(t)]);export{ne as a,he as b};
1
+ import{a as V}from"./YHB55C5T.js";import{b as H,c as Z,d as z,e as J}from"./PWBL4WKB.js";import{a as j}from"./VVEUJ36E.js";import{a as L}from"./6UPPUHCL.js";import{c as W}from"./AMICUXS6.js";import{b as $,o as q}from"./5O5ZE3ZV.js";import{b as _}from"./AXYOJBX6.js";import{a as x,d as B,e as E}from"./6IM6A5VA.js";import{a as D}from"./UWOFA6GV.js";import{g as A,m as R,n as U}from"./73N3TOJL.js";import{a as h,d as N,i as I,j as S}from"./G6HCV67X.js";import{a as o}from"./5YS5V2LK.js";import{getAddress as F,parseAbi as ee}from"viem";var a=F(I[4663].vaults.groveAlm.address),te="0x29626c2d8ca49a51e4deceec5499e52983c42bd5",d=ee(["function asset() view returns (address)","function decimals() view returns (uint8)","function totalAssets() view returns (uint256)","function totalSupply() view returns (uint256)","function balanceOf(address) view returns (uint256)","function maxDeposit(address) view returns (uint256)","function maxWithdraw(address) view returns (uint256)","function previewDeposit(uint256) view returns (uint256)","function previewRedeem(uint256) view returns (uint256)","function performanceFee() view returns (uint256)","function managementFee() view returns (uint256)"]),T=D("Positive integer in token base units."),M={type:"string",description:`Public Grove vault only: ${a}. Defaults to this vault.`},K={type:"integer",minimum:0,maximum:9999,default:$};function C(t){return U(t,"Amount must be positive and within the uint256 range.",{notString:"Amount must be a positive integer string in base units.",positive:!0})}function v(t){return R(t,"Grove returned an invalid integer read.")}function O(t,m,l){if(x(m),Object.keys(t).some(u=>!["vault",...l].includes(u)))throw new o("Unsupported Grove argument.");if(t.vault!==void 0){if(typeof t.vault!="string")throw new o("Provide the public Grove vault address.");if(t.vault.toLowerCase()===te)throw new o("The Grove ALM proxy is allocator infrastructure, not the public ERC-4626 vault.");if(x(t.vault),!A(t.vault,a))throw new o("Only the public Grove ERC-4626 vault is supported.")}}function Q(t,m,l){let u=l===void 0?$:l;if(typeof u!="number")throw new o("Slippage must be an integer from 0 to 9999 bps.");let e=BigInt(q(t.toString(),u)),n=m===void 0?e:C(m);if(n<=0n||n>t)throw new o("The minimum output must be positive and no greater than the quoted output.");return n}function X(t,m){let l=0n;for(let u of t.changes)if(!(u.token.chainId!==m.chainId||!A(u.token.address,m.address))){if(u.token.decimals!==m.decimals||typeof u.amount!="string"||!/^-?\d+$/.test(u.amount))throw new o("Grove preview returned invalid token metadata or amounts.");l+=BigInt(u.amount)}return l}var ne=t=>{async function m(e){try{return await e()}catch(n){throw new o(t.plainError(n))}}async function l(){let e=t.clientFor(h);if(await e.getChainId()!==h)throw new o("Grove requires an RPC endpoint on chain 4663.");let n=await e.readContract({address:a,abi:d,functionName:"asset"});if(typeof n!="string"||!A(n,S))throw new o("The public Grove vault must use canonical USDG on chain 4663.");let[i,s]=await Promise.all([e.readContract({address:F(S),abi:d,functionName:"decimals"}),e.readContract({address:a,abi:d,functionName:"decimals"})]);if(i!==N||s!==18)throw new o("Grove token decimals differ from the evidenced USDG/share interface.");let r={address:F(S),chainId:h,decimals:i,symbol:"USDG"};return{client:e,asset:r,shareToken:{address:a,chainId:h,decimals:s,symbol:"Grove shares"}}}async function u(e,n,i,s,r,p){let f=await t.preview(e,n);if(X(f,i)!==-s)throw new o("Grove simulation did not show the exact requested token outflow.");if(X(f,r)<p)throw new o("Grove simulated output is below the minimum.");let g=f.changes.map(({token:w,amount:b})=>{let y=b.startsWith("-");return`${y?"-":"+"}${t.formatAmount(y?b.slice(1):b,w.decimals)} ${w.symbol} (${w.address}, chain ${w.chainId})`}).join("; ");return{txs:e,summary:`${f.summary} ${g}. Minimum ${p} base units of ${r.address} is a preview check, not enforced on-chain by standard ERC-4626. Re-preview before signing; execution output can change.`}}return{tools:[Z(t,"grove_details",a),L(t,"grove_analytics",a),V(t,"grove_manage",a),...j(t,"grove",a),{name:"grove_list",inputSchema:{type:"object",properties:{vault:M},additionalProperties:!1},execute:(e,n)=>m(async()=>{O(e,n,[]);let{client:i,asset:s,shareToken:r}=await l(),[p,f,c,g,w,b]=await Promise.all([i.readContract({address:a,abi:d,functionName:"totalAssets"}),i.readContract({address:a,abi:d,functionName:"totalSupply"}),i.readContract({address:a,abi:d,functionName:"maxDeposit",args:[n]}),i.readContract({address:a,abi:d,functionName:"maxWithdraw",args:[n]}),i.readContract({address:a,abi:d,functionName:"performanceFee"}),i.readContract({address:a,abi:d,functionName:"managementFee"})]);return[{vault:a,chainId:h,name:"Grove x Steakhouse USDG",asset:s,shareToken:r,totalAssets:{token:s,amount:v(p).toString()},totalSupply:{token:r,amount:v(f).toString()},maxDeposit:v(c)===0n?null:c.toString(),maxWithdraw:v(g)===0n?null:g.toString(),maxViewCaveat:"Zero Morpho V2 maximum views mean unknown capacity. Simulate the requested action; full exits use the fresh share balance.",fees:{performanceFeeRaw:v(w).toString(),managementFeeRaw:v(b).toString(),scale:"1000000000000000000",managementFeeTimeUnit:"second",performanceFeeBasis:"accrued interest"}}]})},{name:"grove_deposit",inputSchema:{type:"object",properties:{vault:M,amount:T,minSharesOut:T,slippageBps:K},required:["amount"],additionalProperties:!1},execute:(e,n)=>m(async()=>{O(e,n,["amount","minSharesOut","slippageBps"]);let i=C(e.amount),{client:s,asset:r,shareToken:p}=await l(),f=v(await s.readContract({address:a,abi:d,functionName:"previewDeposit",args:[i]})),c=Q(f,e.minSharesOut,e.slippageBps),g=B(a,r.address,i.toString(),n,h),w=[t.approval(r.address,a,i.toString(),h),t.unsignedTx(g.txs[1])];return u(w,n,r,i,p,c)})},{name:"grove_withdraw",inputSchema:{type:"object",properties:{vault:M,shares:{oneOf:[T,{const:"all",description:"Redeem the fresh full share balance."}]},minAmountOut:T,slippageBps:K,force:{type:"boolean"},maxPenaltyAssets:D()},required:["shares"],additionalProperties:!1},execute:(e,n)=>m(async()=>{O(e,n,["shares","minAmountOut","slippageBps","force","maxPenaltyAssets"]);let i=e.shares==="all"?void 0:C(e.shares),{client:s,asset:r,shareToken:p}=await l(),f=v(await s.readContract({address:a,abi:d,functionName:"balanceOf",args:[n]})),c=i??f;if(c===0n||c>f)throw new o("The Grove share balance is insufficient for this withdrawal.");if(e.force!==void 0&&typeof e.force!="boolean")throw new o("force must be a boolean.");if(e.force===!0){if(e.shares!=="all"||e.slippageBps!==void 0)throw new o("Force exit requires shares all and an explicit minAmountOut; omit slippageBps.");let k=W(e.maxPenaltyAssets),Y=C(e.minAmountOut),G=await H(t,s,a,n,c,k),P=await t.preview([G.tx],n);return J(P.changes,a,c,Y),{txs:[G.tx],preview:P,summary:`${z(G.plan)} ${P.summary}`}}if(e.maxPenaltyAssets!==void 0)throw new o("maxPenaltyAssets requires force true.");let g=v(await s.readContract({address:a,abi:d,functionName:"previewRedeem",args:[c]})),w=Q(g,e.minAmountOut,e.slippageBps),y=E(a,c.toString(),n,h).txs.map(k=>t.unsignedTx({...k,description:`Redeem ${c} Grove share base units to the wallet.`}));return u(y,n,p,c,r,w)})}],positions:e=>m(async()=>{x(e);let{client:n,asset:i,shareToken:s}=await l(),r=v(await n.readContract({address:a,abi:d,functionName:"balanceOf",args:[e]}));if(r===0n)return[];let p=v(await n.readContract({address:a,abi:d,functionName:"previewRedeem",args:[r]}));return[{module:"grove",id:`${h}:${a.toLowerCase()}`,chainId:h,assets:[{token:i,amount:p.toString()}],description:`${t.formatAmount(r.toString(),s.decimals)} Grove shares (${r} base units, ${s.decimals} decimals, ${a}); estimated USDG redemption, subject to simulation.`}]})}},he=t=>_("grove",[ne(t)]);export{ne as a,he as b};