@oakagentkit/core 0.2.4 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (448) hide show
  1. package/build/dist/api/amounts.d.ts +2 -0
  2. package/build/dist/api/amounts.js +1 -1
  3. package/build/dist/api/args.js +1 -1
  4. package/build/dist/api/gas.js +1 -1
  5. package/build/dist/api/grandfather.js +1 -1
  6. package/build/dist/api/guards.js +1 -1
  7. package/build/dist/api/history.js +1 -1
  8. package/build/dist/api/http.js +1 -1
  9. package/build/dist/api/merkle.js +1 -1
  10. package/build/dist/api/module.js +1 -1
  11. package/build/dist/api/modules/beefy/boosts.js +1 -1
  12. package/build/dist/api/modules/beefy/clm.js +1 -1
  13. package/build/dist/api/modules/beefy/guard.js +1 -1
  14. package/build/dist/api/modules/beefy/index.js +1 -1
  15. package/build/dist/api/modules/beefy/liquidity.js +1 -1
  16. package/build/dist/api/modules/beefy/management.js +1 -1
  17. package/build/dist/api/modules/beefy/vaults.js +1 -1
  18. package/build/dist/api/modules/borro/abi.d.ts +149 -0
  19. package/build/dist/api/modules/borro/abi.js +1 -0
  20. package/build/dist/api/modules/borro/actions.d.ts +2 -0
  21. package/build/dist/api/modules/borro/actions.js +1 -0
  22. package/build/dist/api/modules/borro/checks.d.ts +151 -0
  23. package/build/dist/api/modules/borro/checks.js +1 -0
  24. package/build/dist/api/modules/borro/copy.d.ts +174 -0
  25. package/build/dist/api/modules/borro/copy.js +1 -0
  26. package/build/dist/api/modules/borro/index.d.ts +13 -0
  27. package/build/dist/api/modules/borro/index.js +1 -0
  28. package/build/dist/api/modules/borro/liquidity.d.ts +4 -0
  29. package/build/dist/api/modules/borro/liquidity.js +1 -0
  30. package/build/dist/api/modules/borro/pins.d.ts +264 -0
  31. package/build/dist/api/modules/borro/pins.js +1 -0
  32. package/build/dist/api/modules/borro/positions.d.ts +8 -0
  33. package/build/dist/api/modules/borro/positions.js +1 -0
  34. package/build/dist/api/modules/borro/rates.d.ts +20 -0
  35. package/build/dist/api/modules/borro/rates.js +1 -0
  36. package/build/dist/api/modules/borro/reader.d.ts +32 -0
  37. package/build/dist/api/modules/borro/reader.js +1 -0
  38. package/build/dist/api/modules/borro/types.d.ts +120 -0
  39. package/build/dist/api/modules/borro/types.js +0 -0
  40. package/build/dist/api/modules/clanker/extensions.js +1 -1
  41. package/build/dist/api/modules/clanker/index.js +1 -1
  42. package/build/dist/api/modules/clanker/manage.js +1 -1
  43. package/build/dist/api/modules/clanker/pool-config.js +1 -1
  44. package/build/dist/api/modules/clanker/protocol.js +1 -1
  45. package/build/dist/api/modules/clanker/state.js +1 -1
  46. package/build/dist/api/modules/earn/copy.d.ts +2 -2
  47. package/build/dist/api/modules/earn/copy.js +1 -1
  48. package/build/dist/api/modules/earn/index.js +1 -1
  49. package/build/dist/api/modules/earn/lp.js +1 -1
  50. package/build/dist/api/modules/earn/options.js +1 -1
  51. package/build/dist/api/modules/erc8004/common.js +1 -1
  52. package/build/dist/api/modules/erc8004/domain.js +1 -1
  53. package/build/dist/api/modules/erc8004/index.js +1 -1
  54. package/build/dist/api/modules/erc8004/management.js +1 -1
  55. package/build/dist/api/modules/erc8004/reputation.js +1 -1
  56. package/build/dist/api/modules/erc8004/services.js +1 -1
  57. package/build/dist/api/modules/erc8004/validation.js +1 -1
  58. package/build/dist/api/modules/grove/index.js +1 -1
  59. package/build/dist/api/modules/heyresearch/builder-feed.js +1 -1
  60. package/build/dist/api/modules/heyresearch/index.js +1 -1
  61. package/build/dist/api/modules/heyresearch/proof-reads.js +1 -1
  62. package/build/dist/api/modules/heyresearch/public-reads.js +1 -1
  63. package/build/dist/api/modules/heyresearch/scan.js +1 -1
  64. package/build/dist/api/modules/heyresearch/token-facts.js +1 -1
  65. package/build/dist/api/modules/hoodag/chain-reads.js +1 -1
  66. package/build/dist/api/modules/hoodag/index.js +1 -1
  67. package/build/dist/api/modules/hoodag/management.js +1 -1
  68. package/build/dist/api/modules/hoodag/public-reads.js +1 -1
  69. package/build/dist/api/modules/hoodag/reconstruct.js +1 -1
  70. package/build/dist/api/modules/hoodlock/airdrop.js +1 -1
  71. package/build/dist/api/modules/hoodlock/commerce.js +1 -1
  72. package/build/dist/api/modules/hoodlock/fee.js +1 -1
  73. package/build/dist/api/modules/hoodlock/guard.js +1 -1
  74. package/build/dist/api/modules/hoodlock/index.js +1 -1
  75. package/build/dist/api/modules/hoodlock/lifecycle.js +1 -1
  76. package/build/dist/api/modules/hoodlock/locks-burn.js +1 -1
  77. package/build/dist/api/modules/hoodlock/public.js +1 -1
  78. package/build/dist/api/modules/hookr/actions.js +1 -1
  79. package/build/dist/api/modules/hookr/addons.js +1 -1
  80. package/build/dist/api/modules/hookr/agent-gate.js +1 -1
  81. package/build/dist/api/modules/hookr/contracts.js +1 -1
  82. package/build/dist/api/modules/hookr/create-cancel.js +1 -1
  83. package/build/dist/api/modules/hookr/discovery.js +1 -1
  84. package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
  85. package/build/dist/api/modules/hookr/index.js +1 -1
  86. package/build/dist/api/modules/hookr/launch-options.js +1 -1
  87. package/build/dist/api/modules/hookr/launch-receipt.js +1 -1
  88. package/build/dist/api/modules/hookr/launch.js +1 -1
  89. package/build/dist/api/modules/hookr/liquidity.js +1 -1
  90. package/build/dist/api/modules/hookr/lp-positions.js +1 -1
  91. package/build/dist/api/modules/hookr/lp-reads.js +1 -1
  92. package/build/dist/api/modules/hookr/lp-receipt.js +1 -1
  93. package/build/dist/api/modules/hookr/lp-state.js +1 -1
  94. package/build/dist/api/modules/hookr/public-reads.js +1 -1
  95. package/build/dist/api/modules/hookr/read-utils.js +1 -1
  96. package/build/dist/api/modules/hookr/relay.js +1 -1
  97. package/build/dist/api/modules/hookr/revenue.js +1 -1
  98. package/build/dist/api/modules/kyberswap/index.js +1 -1
  99. package/build/dist/api/modules/kyberswap/source-pools.js +1 -1
  100. package/build/dist/api/modules/layerbank/actions.js +1 -1
  101. package/build/dist/api/modules/layerbank/checks.js +1 -1
  102. package/build/dist/api/modules/layerbank/index.js +1 -1
  103. package/build/dist/api/modules/layerbank/merkl.js +1 -1
  104. package/build/dist/api/modules/layerbank/reader.js +1 -1
  105. package/build/dist/api/modules/layerbank/reserve.js +1 -1
  106. package/build/dist/api/modules/lighter/index.js +1 -1
  107. package/build/dist/api/modules/longbow/administration.js +1 -1
  108. package/build/dist/api/modules/longbow/analytics.js +1 -1
  109. package/build/dist/api/modules/longbow/fixed.js +1 -1
  110. package/build/dist/api/modules/longbow/index.js +1 -1
  111. package/build/dist/api/modules/longbow/nft.js +1 -1
  112. package/build/dist/api/modules/longbow/rebates.js +1 -1
  113. package/build/dist/api/modules/longbow/staking.js +1 -1
  114. package/build/dist/api/modules/meridian/index.js +1 -1
  115. package/build/dist/api/modules/meridian/markets.js +1 -1
  116. package/build/dist/api/modules/meridian/perps-batch.js +1 -1
  117. package/build/dist/api/modules/meridian/perps-common.js +1 -1
  118. package/build/dist/api/modules/meridian/perps-guards.js +1 -1
  119. package/build/dist/api/modules/meridian/perps-intents.js +1 -1
  120. package/build/dist/api/modules/meridian/perps-stream.js +1 -1
  121. package/build/dist/api/modules/meridian/perps.d.ts +1 -0
  122. package/build/dist/api/modules/meridian/perps.js +1 -1
  123. package/build/dist/api/modules/meridian/predict-read.js +1 -1
  124. package/build/dist/api/modules/meridian/rfq.js +1 -1
  125. package/build/dist/api/modules/merkl/discovery.js +1 -1
  126. package/build/dist/api/modules/merkl/index.js +1 -1
  127. package/build/dist/api/modules/merkl/manage.js +1 -1
  128. package/build/dist/api/modules/merkl/protocol.js +1 -1
  129. package/build/dist/api/modules/morpho/allocator.js +1 -1
  130. package/build/dist/api/modules/morpho/bundles.js +1 -1
  131. package/build/dist/api/modules/morpho/in-kind.js +1 -1
  132. package/build/dist/api/modules/morpho/index.js +1 -1
  133. package/build/dist/api/modules/morpho/local-guard.js +1 -1
  134. package/build/dist/api/modules/morpho/midnight.js +1 -1
  135. package/build/dist/api/modules/morpho/protocol.js +1 -1
  136. package/build/dist/api/modules/morpho/vault-management.js +1 -1
  137. package/build/dist/api/modules/morpho/vault-tools.js +1 -1
  138. package/build/dist/api/modules/morpho/vault-v2.js +1 -1
  139. package/build/dist/api/modules/netnet/card-plan.js +1 -1
  140. package/build/dist/api/modules/netnet/card-read.js +1 -1
  141. package/build/dist/api/modules/netnet/card-recovery.js +1 -1
  142. package/build/dist/api/modules/netnet/desk-action.js +1 -1
  143. package/build/dist/api/modules/netnet/financial.js +1 -1
  144. package/build/dist/api/modules/netnet/index.js +1 -1
  145. package/build/dist/api/modules/netnet/staking.js +1 -1
  146. package/build/dist/api/modules/orbio/gateway.js +1 -1
  147. package/build/dist/api/modules/orbio/index.js +1 -1
  148. package/build/dist/api/modules/orbio/positions.js +1 -1
  149. package/build/dist/api/modules/pendle/convert.js +1 -1
  150. package/build/dist/api/modules/pendle/costs.js +1 -1
  151. package/build/dist/api/modules/pendle/index.js +1 -1
  152. package/build/dist/api/modules/pendle/markets.js +1 -1
  153. package/build/dist/api/modules/pendle/positions.js +1 -1
  154. package/build/dist/api/modules/pendle/pricecheck.js +1 -1
  155. package/build/dist/api/modules/pendle/reader.js +1 -1
  156. package/build/dist/api/modules/pendle/redeem.js +1 -1
  157. package/build/dist/api/modules/pendle/trade.js +1 -1
  158. package/build/dist/api/modules/pendle/types.d.ts +16 -1
  159. package/build/dist/api/modules/pendle/validate.js +1 -1
  160. package/build/dist/api/modules/pendle/verify.js +1 -1
  161. package/build/dist/api/modules/pons/claim.js +1 -1
  162. package/build/dist/api/modules/pons/holder-directory.js +1 -1
  163. package/build/dist/api/modules/pons/index.js +1 -1
  164. package/build/dist/api/modules/pons/launch-status.js +1 -1
  165. package/build/dist/api/modules/pons/prices.js +1 -1
  166. package/build/dist/api/modules/pons/reads.js +1 -1
  167. package/build/dist/api/modules/pons/swap-terms.js +1 -1
  168. package/build/dist/api/modules/pons/trade.js +1 -1
  169. package/build/dist/api/modules/poolstrade/index.js +1 -1
  170. package/build/dist/api/modules/priors/coverage.js +1 -1
  171. package/build/dist/api/modules/priors/discovery.js +1 -1
  172. package/build/dist/api/modules/priors/features.js +1 -1
  173. package/build/dist/api/modules/priors/holdings.js +1 -1
  174. package/build/dist/api/modules/priors/index.js +1 -1
  175. package/build/dist/api/modules/priors/integration.js +1 -1
  176. package/build/dist/api/modules/priors/market.js +1 -1
  177. package/build/dist/api/modules/priors/pt.js +1 -1
  178. package/build/dist/api/modules/priors/savings-exit.js +1 -1
  179. package/build/dist/api/modules/priors/starter-line.js +1 -1
  180. package/build/dist/api/modules/priors/stock-swap.js +1 -1
  181. package/build/dist/api/modules/relay/api.js +1 -1
  182. package/build/dist/api/modules/relay/bootstrap.js +1 -1
  183. package/build/dist/api/modules/relay/discovery.js +1 -1
  184. package/build/dist/api/modules/relay/inbound.d.ts +2 -0
  185. package/build/dist/api/modules/relay/inbound.js +1 -1
  186. package/build/dist/api/modules/relay/index.js +1 -1
  187. package/build/dist/api/modules/relay/order.js +1 -1
  188. package/build/dist/api/modules/relay/outbound-status.js +1 -1
  189. package/build/dist/api/modules/relay/readiness.js +1 -1
  190. package/build/dist/api/modules/relay/reads.js +1 -1
  191. package/build/dist/api/modules/relay/vaults.js +1 -1
  192. package/build/dist/api/modules/spark/actions.js +1 -1
  193. package/build/dist/api/modules/spark/details.js +1 -1
  194. package/build/dist/api/modules/spark/index.js +1 -1
  195. package/build/dist/api/modules/spark/management.js +1 -1
  196. package/build/dist/api/modules/steakhouse/analytics.js +1 -1
  197. package/build/dist/api/modules/steakhouse/erc4626.js +1 -1
  198. package/build/dist/api/modules/steakhouse/index.js +1 -1
  199. package/build/dist/api/modules/steakhouse/local-guard.js +1 -1
  200. package/build/dist/api/modules/steakhouse/management.js +1 -1
  201. package/build/dist/api/modules/steakhouse/v2-exit.js +1 -1
  202. package/build/dist/api/modules/tickerspring/basket-routes.js +1 -1
  203. package/build/dist/api/modules/tickerspring/contract-reads.js +1 -1
  204. package/build/dist/api/modules/tickerspring/exit-preview.js +1 -1
  205. package/build/dist/api/modules/tickerspring/guards.js +1 -1
  206. package/build/dist/api/modules/tickerspring/index.js +1 -1
  207. package/build/dist/api/modules/tickerspring/journeys.js +1 -1
  208. package/build/dist/api/modules/tickerspring/ladder.js +1 -1
  209. package/build/dist/api/modules/tickerspring/maker.js +1 -1
  210. package/build/dist/api/modules/tickerspring/order-accounting.js +1 -1
  211. package/build/dist/api/modules/tickerspring/research.js +1 -1
  212. package/build/dist/api/modules/tickerspring/strategies.js +1 -1
  213. package/build/dist/api/modules/uniswap/auction-create.js +1 -1
  214. package/build/dist/api/modules/uniswap/auction.js +1 -1
  215. package/build/dist/api/modules/uniswap/batch.js +1 -1
  216. package/build/dist/api/modules/uniswap/common.js +1 -1
  217. package/build/dist/api/modules/uniswap/fees.js +1 -1
  218. package/build/dist/api/modules/uniswap/index.js +1 -1
  219. package/build/dist/api/modules/uniswap/local-guard.js +1 -1
  220. package/build/dist/api/modules/uniswap/oracle.js +1 -1
  221. package/build/dist/api/modules/uniswap/pool-math.js +1 -1
  222. package/build/dist/api/modules/uniswap/pools.js +1 -1
  223. package/build/dist/api/modules/uniswap/position.js +1 -1
  224. package/build/dist/api/modules/uniswap/protocol.js +1 -1
  225. package/build/dist/api/modules/uniswap/token-jar.js +1 -1
  226. package/build/dist/api/modules/uniswap/trade-batch.js +1 -1
  227. package/build/dist/api/modules/uniswap/trade.js +1 -1
  228. package/build/dist/api/modules/uniswap/v2.js +1 -1
  229. package/build/dist/api/modules/uniswap/v3.d.ts +11 -1
  230. package/build/dist/api/modules/uniswap/v3.js +1 -1
  231. package/build/dist/api/modules/uniswap/v4.js +1 -1
  232. package/build/dist/api/modules/uniswap/wrap.js +1 -1
  233. package/build/dist/api/modules/velora/claims.js +1 -1
  234. package/build/dist/api/modules/velora/delta-reads.js +1 -1
  235. package/build/dist/api/modules/velora/index.js +1 -1
  236. package/build/dist/api/modules/wormhole/index.js +1 -1
  237. package/build/dist/api/modules/wormhole/scan-text.js +1 -1
  238. package/build/dist/api/modules/wormhole/token-check.js +1 -1
  239. package/build/dist/api/positions.js +1 -1
  240. package/build/dist/api/pricenote.js +1 -1
  241. package/build/dist/api/prices.js +1 -1
  242. package/build/dist/api/pricing.js +1 -1
  243. package/build/dist/api/routes.js +1 -1
  244. package/build/dist/api/send.js +1 -1
  245. package/build/dist/api/signing-registry.js +1 -1
  246. package/build/dist/api/simulate.js +1 -1
  247. package/build/dist/api/swap.js +1 -1
  248. package/build/dist/api/tokens.d.ts +1 -0
  249. package/build/dist/api/tokens.js +1 -1
  250. package/build/dist/api/tool-policy.js +1 -1
  251. package/build/dist/api/tx.js +1 -1
  252. package/build/dist/api/vendor-limits.js +1 -1
  253. package/build/dist/chunks/{BAAXGB4K.js → 2KYAMXTS.js} +1 -1
  254. package/build/dist/chunks/{WVONJOWN.js → 2MAMJJJC.js} +1 -1
  255. package/build/dist/chunks/{MKAPRRKF.js → 2TK3ETUO.js} +1 -1
  256. package/build/dist/chunks/{CTMA4BTM.js → 326QMOTR.js} +1 -1
  257. package/build/dist/chunks/{ALRRW7SF.js → 3FUVMSCF.js} +1 -1
  258. package/build/dist/chunks/{YPM2UITD.js → 3GOHSYHW.js} +1 -1
  259. package/build/dist/chunks/{HTXKERNS.js → 3MLUCYCB.js} +1 -1
  260. package/build/dist/chunks/{GHPREYQK.js → 3NJ5KQ3Q.js} +1 -1
  261. package/build/dist/chunks/{WPFAEBE7.js → 3XNZUIRU.js} +1 -1
  262. package/build/dist/chunks/3XXBLNEX.js +1 -0
  263. package/build/dist/chunks/{PBQSJSZO.js → 43LI5NKJ.js} +1 -1
  264. package/build/dist/chunks/{NZXQWDGF.js → 45BRW2ZF.js} +1 -1
  265. package/build/dist/chunks/{QVYCJ6WV.js → 46KWRAYK.js} +1 -1
  266. package/build/dist/chunks/{UHRCM7AG.js → 4HG6FRVH.js} +1 -1
  267. package/build/dist/chunks/{TBCSZDAF.js → 4MXM6Q4W.js} +1 -1
  268. package/build/dist/chunks/{ZCOFMGPS.js → 4PY3UFNR.js} +1 -1
  269. package/build/dist/chunks/{WIVYKLQM.js → 52ELWNXJ.js} +1 -1
  270. package/build/dist/chunks/{F3BSEE52.js → 553UE2ZQ.js} +1 -1
  271. package/build/dist/chunks/{S2TAJHHK.js → 57MEFFCU.js} +1 -1
  272. package/build/dist/chunks/{ENX72ARB.js → 5APS4T2D.js} +1 -1
  273. package/build/dist/chunks/{UA4O226F.js → 5SMVQCAP.js} +1 -1
  274. package/build/dist/chunks/{6PY3IRDS.js → 64GOINYS.js} +1 -1
  275. package/build/dist/chunks/{5ZLOCQA4.js → 66F5ZH34.js} +1 -1
  276. package/build/dist/chunks/{HVM2EEXB.js → 6B3VVISQ.js} +1 -1
  277. package/build/dist/chunks/{E6RRXNV2.js → 6D5DJA5B.js} +1 -1
  278. package/build/dist/chunks/{XDZRO5JQ.js → 6I4NTKB2.js} +1 -1
  279. package/build/dist/chunks/{MFCPL6LF.js → 6OGDTEGH.js} +1 -1
  280. package/build/dist/chunks/6PBGEPUK.js +20 -0
  281. package/build/dist/chunks/{43CSMYDO.js → 6WD4HHID.js} +1 -1
  282. package/build/dist/chunks/{XJEOEMDS.js → 6WZX7C4T.js} +1 -1
  283. package/build/dist/chunks/{NA7R6J5N.js → 74Y2KDNR.js} +1 -1
  284. package/build/dist/chunks/{IKEJCBYU.js → 7WSHW7KW.js} +1 -1
  285. package/build/dist/chunks/{UPMGGK34.js → AFBEZXNV.js} +1 -1
  286. package/build/dist/chunks/{AUOXDNUO.js → AKYF5264.js} +1 -1
  287. package/build/dist/chunks/{BXHNYCH2.js → APGLZXIW.js} +1 -1
  288. package/build/dist/chunks/{7UOOIDR3.js → AVG4W3Y7.js} +1 -1
  289. package/build/dist/chunks/{Y7PRJOIK.js → B3RXD5ET.js} +1 -1
  290. package/build/dist/chunks/{JPNYUEQP.js → BBS3ODWZ.js} +1 -1
  291. package/build/dist/chunks/{I4TGMF2C.js → BJ2VGRF4.js} +1 -1
  292. package/build/dist/chunks/{WD37MEMZ.js → BTD5SMOW.js} +1 -1
  293. package/build/dist/chunks/{57JFKIMK.js → BTPXJAUX.js} +1 -1
  294. package/build/dist/chunks/{BIRMUW7Z.js → C36BFZH6.js} +1 -1
  295. package/build/dist/chunks/{ZGKVXFM5.js → C7AXJHBT.js} +1 -1
  296. package/build/dist/chunks/{5U7TCKX2.js → CBG5HARQ.js} +1 -1
  297. package/build/dist/chunks/{ET23SES4.js → CCTXCMH4.js} +1 -1
  298. package/build/dist/chunks/{5N4A5XAW.js → CHXBOXOD.js} +1 -1
  299. package/build/dist/chunks/D3YLXQPW.js +1 -0
  300. package/build/dist/chunks/{L7OQUHM5.js → DJN3JAWB.js} +1 -1
  301. package/build/dist/chunks/{CERNEJ2F.js → DW4V5PUY.js} +1 -1
  302. package/build/dist/chunks/E3RACZUY.js +1 -0
  303. package/build/dist/chunks/{TPL4U3AQ.js → E674J2MD.js} +1 -1
  304. package/build/dist/chunks/EE64JSLY.js +1 -0
  305. package/build/dist/chunks/EJ7O75A7.js +1 -0
  306. package/build/dist/chunks/{3AXVB23N.js → ELSXLZN5.js} +1 -1
  307. package/build/dist/chunks/{IQGY5FW7.js → ER47KGRM.js} +1 -1
  308. package/build/dist/chunks/FQ6UZCM6.js +1 -0
  309. package/build/dist/chunks/{WPAF55SP.js → GEIFITAQ.js} +1 -1
  310. package/build/dist/chunks/{4ALMYJJV.js → GGSAKCND.js} +1 -1
  311. package/build/dist/chunks/{EKNSLLJK.js → GL4NCUMH.js} +1 -1
  312. package/build/dist/chunks/GNC6RXLT.js +1 -0
  313. package/build/dist/chunks/{VVA72C6O.js → GQ5GYUEH.js} +1 -1
  314. package/build/dist/chunks/{6AAARNZ3.js → GW626GG2.js} +1 -1
  315. package/build/dist/chunks/{LROVANUR.js → H2XDMFQQ.js} +1 -1
  316. package/build/dist/chunks/H43RNCX2.js +1 -0
  317. package/build/dist/chunks/{VHLINDDS.js → HAQPIBYR.js} +1 -1
  318. package/build/dist/chunks/{ZE7EU2CS.js → HCUHMCBW.js} +1 -1
  319. package/build/dist/chunks/{64WKYWZV.js → HKEMQBFA.js} +1 -1
  320. package/build/dist/chunks/{4YFVAYKR.js → HM72DH4V.js} +1 -1
  321. package/build/dist/chunks/HSCQZ66A.js +1 -0
  322. package/build/dist/chunks/{QRC4ZPDA.js → I26DMNJG.js} +1 -1
  323. package/build/dist/chunks/{S3FPF537.js → IMO3GDA5.js} +1 -1
  324. package/build/dist/chunks/{ECWGKLBW.js → INOZIE55.js} +1 -1
  325. package/build/dist/chunks/{BQICZFLR.js → IOYRL6AY.js} +1 -1
  326. package/build/dist/chunks/IX3GZMTM.js +1 -0
  327. package/build/dist/chunks/IY7BXLT4.js +1 -0
  328. package/build/dist/chunks/{NYNJITCM.js → J2OT4KAH.js} +1 -1
  329. package/build/dist/chunks/{Y7RPSDD2.js → JKD2B6OX.js} +1 -1
  330. package/build/dist/chunks/{PSVOVZH7.js → JUZ5JU6D.js} +5 -5
  331. package/build/dist/chunks/{YEXUSRIZ.js → JVLLVNF2.js} +1 -1
  332. package/build/dist/chunks/{SSIENQVU.js → K3RDPI5J.js} +1 -1
  333. package/build/dist/chunks/{PADWZX7J.js → K4DHHQBI.js} +1 -1
  334. package/build/dist/chunks/KIFSRO5K.js +1 -0
  335. package/build/dist/chunks/{NB3LYS3G.js → KIFZ5ZSK.js} +1 -1
  336. package/build/dist/chunks/{QSN6Y2K6.js → KPCY5V35.js} +1 -1
  337. package/build/dist/chunks/{3ESNHZT5.js → L4N2RSK2.js} +1 -1
  338. package/build/dist/chunks/{EYFBVQ46.js → L5BLHY34.js} +1 -1
  339. package/build/dist/chunks/{E6UU7DL2.js → LSXUAHOE.js} +1 -1
  340. package/build/dist/chunks/{BNG2IWZL.js → M37654RL.js} +1 -1
  341. package/build/dist/chunks/{XFKVU46U.js → MJ6WEWMI.js} +1 -1
  342. package/build/dist/chunks/{47YN4OUI.js → MR5L7V6Z.js} +1 -1
  343. package/build/dist/chunks/{DVVFT42J.js → MRMR4QHA.js} +1 -1
  344. package/build/dist/chunks/{WWHCEMNB.js → N4Q6GN65.js} +1 -1
  345. package/build/dist/chunks/{S5WICHIS.js → NAZPDRIF.js} +1 -1
  346. package/build/dist/chunks/{MKBNLGDD.js → NDCLTVIU.js} +1 -1
  347. package/build/dist/chunks/{5WUKOQIJ.js → NEEZBJBC.js} +1 -1
  348. package/build/dist/chunks/{HSFOWJ3Z.js → NKZKKCK2.js} +1 -1
  349. package/build/dist/chunks/{5KUWLUPM.js → NWNYJ26T.js} +1 -1
  350. package/build/dist/chunks/{KBXU7U6Q.js → O7HCEPQY.js} +1 -1
  351. package/build/dist/chunks/{LDT3QTSY.js → OJ4WJUPP.js} +1 -1
  352. package/build/dist/chunks/{QJFXLYZG.js → OJPG45AC.js} +1 -1
  353. package/build/dist/chunks/{5MQ5KSSV.js → OKUO3BVM.js} +1 -1
  354. package/build/dist/chunks/OTXSKFUD.js +1 -0
  355. package/build/dist/chunks/{4TQQH7N6.js → P3S4BR5G.js} +1 -1
  356. package/build/dist/chunks/P56RZC2M.js +1 -0
  357. package/build/dist/chunks/{BK23XJXE.js → P5PYFK7L.js} +1 -1
  358. package/build/dist/chunks/{ZYH4B2GR.js → P7I62KFR.js} +1 -1
  359. package/build/dist/chunks/{SQL6HD5E.js → PK66GCDT.js} +1 -1
  360. package/build/dist/chunks/{6FTYNYGF.js → PSBQWDYI.js} +1 -1
  361. package/build/dist/chunks/{W76QC2AW.js → PV5FDT6O.js} +1 -1
  362. package/build/dist/chunks/{42DQTKEO.js → PXT5YTWU.js} +1 -1
  363. package/build/dist/chunks/{IMRXZ7JB.js → Q42YI3EP.js} +1 -1
  364. package/build/dist/chunks/{ZBFKKUNP.js → QA3UHEO3.js} +1 -1
  365. package/build/dist/chunks/QC3HH5UD.js +3 -0
  366. package/build/dist/chunks/{MQYOG66Q.js → QF52OIBS.js} +1 -1
  367. package/build/dist/chunks/{7WQEPZJY.js → QO3KCJMP.js} +1 -1
  368. package/build/dist/chunks/QQECG3WP.js +1 -0
  369. package/build/dist/chunks/QSHCBASA.js +1 -0
  370. package/build/dist/chunks/{RVO3QK2B.js → QU5XKRGK.js} +1 -1
  371. package/build/dist/chunks/{GVPX5XCL.js → QZZ4O34L.js} +1 -1
  372. package/build/dist/chunks/{A6YQ5H24.js → RQ4GHJXE.js} +1 -1
  373. package/build/dist/chunks/{3WXK2FUA.js → RUC7KH7A.js} +1 -1
  374. package/build/dist/chunks/{MBTARLZQ.js → RUX3RY7Y.js} +1 -1
  375. package/build/dist/chunks/{3VAJW6TQ.js → RVDUSNWW.js} +1 -1
  376. package/build/dist/chunks/{SDHPFXRM.js → S47VUTHM.js} +1 -1
  377. package/build/dist/chunks/{OTIXQZ3X.js → S7IFAQPG.js} +1 -1
  378. package/build/dist/chunks/{WMNRP3YH.js → SIYUNOLI.js} +1 -1
  379. package/build/dist/chunks/{TNKVRVTH.js → SJJR4ZBZ.js} +1 -1
  380. package/build/dist/chunks/{UFVPMWPJ.js → SMYWWIE6.js} +1 -1
  381. package/build/dist/chunks/{Z4SRGAVL.js → SPJCSEKP.js} +1 -1
  382. package/build/dist/chunks/{IQIWASRD.js → SSHCD6RZ.js} +1 -1
  383. package/build/dist/chunks/{SGEZIYJW.js → T2WHOZXM.js} +1 -1
  384. package/build/dist/chunks/{WOEKXQAH.js → T3AJSQYT.js} +1 -1
  385. package/build/dist/chunks/{SKMPKAZI.js → TAEZTP4L.js} +1 -1
  386. package/build/dist/chunks/{E3UBHTJO.js → TEJ7W534.js} +1 -1
  387. package/build/dist/chunks/{AWXJV2YH.js → TFDPEAVZ.js} +1 -1
  388. package/build/dist/chunks/{MGPHD4VV.js → TM2XCRU7.js} +1 -1
  389. package/build/dist/chunks/{UOGHQLQX.js → TMVO2DAK.js} +1 -1
  390. package/build/dist/chunks/{MXW2TP5P.js → TVWMTMEF.js} +1 -1
  391. package/build/dist/chunks/{GRIGSPD4.js → TX2EOIRS.js} +1 -1
  392. package/build/dist/chunks/{VV2HEIFI.js → U5PMVP56.js} +1 -1
  393. package/build/dist/chunks/{K72EYD6R.js → U67J4BCH.js} +1 -1
  394. package/build/dist/chunks/{MDDHG34Y.js → UHTRW2R6.js} +1 -1
  395. package/build/dist/chunks/{PQC5635W.js → UHVSINR5.js} +1 -1
  396. package/build/dist/chunks/{MOPETB64.js → UMIZMJWW.js} +1 -1
  397. package/build/dist/chunks/{F26FK47J.js → UNJJRQIU.js} +1 -1
  398. package/build/dist/chunks/V74F6IDY.js +1 -0
  399. package/build/dist/chunks/{MYFAKCQI.js → VEQBHI6O.js} +1 -1
  400. package/build/dist/chunks/VHV6WQ5F.js +1 -0
  401. package/build/dist/chunks/{EOQYLFXA.js → VJS4DHQQ.js} +1 -1
  402. package/build/dist/chunks/{AG67Z3SC.js → VOMGT5SG.js} +1 -1
  403. package/build/dist/chunks/{D6ZJPNK7.js → VY7XRHZQ.js} +1 -1
  404. package/build/dist/chunks/{W2OJ57ZO.js → VYAJXLND.js} +1 -1
  405. package/build/dist/chunks/{LVLVP5KQ.js → VYN2NRAP.js} +1 -1
  406. package/build/dist/chunks/{MDV7GECM.js → VYYSL557.js} +1 -1
  407. package/build/dist/chunks/{KA7BPBCV.js → W2BYU5JQ.js} +1 -1
  408. package/build/dist/chunks/W6BS3T7S.js +1 -0
  409. package/build/dist/chunks/WCNHZYQQ.js +1 -0
  410. package/build/dist/chunks/{ALPYEM7B.js → WDK6VOG4.js} +1 -1
  411. package/build/dist/chunks/{K22EXPWN.js → WIRBCS4W.js} +1 -1
  412. package/build/dist/chunks/{YRXT3HTW.js → WLMWWEP7.js} +1 -1
  413. package/build/dist/chunks/{NDW5DAFL.js → WP6RHXGN.js} +1 -1
  414. package/build/dist/chunks/{PLZKXQ76.js → WTXC3XKW.js} +1 -1
  415. package/build/dist/chunks/{WGL46F3S.js → WU7XIAXB.js} +1 -1
  416. package/build/dist/chunks/{5OKJEGBH.js → WV3A3OUU.js} +1 -1
  417. package/build/dist/chunks/{4ISR2U72.js → X2KFXCVD.js} +1 -1
  418. package/build/dist/chunks/{RPNAFUM5.js → X3BYCOWS.js} +1 -1
  419. package/build/dist/chunks/{6L5KTE6Y.js → X3PQMS4N.js} +1 -1
  420. package/build/dist/chunks/{RNC463IM.js → XBE3B6Y2.js} +1 -1
  421. package/build/dist/chunks/XLOYBLFI.js +1 -0
  422. package/build/dist/chunks/{2ZUP7ZEV.js → XR7VK24E.js} +1 -1
  423. package/build/dist/chunks/{ZSQOMSOC.js → Y25EXZCO.js} +1 -1
  424. package/build/dist/chunks/{TJWVY4VO.js → YCZPSMZ5.js} +1 -1
  425. package/build/dist/chunks/{JZXYLHI7.js → YDNTY67T.js} +1 -1
  426. package/build/dist/chunks/{2DUCTO5C.js → YN56C7PN.js} +1 -1
  427. package/build/dist/chunks/{G7XSFUDL.js → YWRDZQI6.js} +1 -1
  428. package/build/dist/chunks/{DP2NIYBP.js → YXTSWRV5.js} +1 -1
  429. package/build/dist/chunks/{I6KUORFT.js → Z43BTOTE.js} +1 -1
  430. package/build/dist/chunks/{PWH464CJ.js → Z4FZVJ5Z.js} +1 -1
  431. package/build/dist/chunks/{YAJYDD6C.js → ZMFRMWHR.js} +1 -1
  432. package/build/dist/chunks/{OFI3Y55L.js → ZQAFFWDK.js} +1 -1
  433. package/build/dist/chunks/{TBIVTEP5.js → ZSN4IRI5.js} +1 -1
  434. package/build/dist/chunks/{ZET37EIG.js → ZV5HIQXC.js} +1 -1
  435. package/package.json +1 -1
  436. package/build/dist/chunks/24CQ2SPB.js +0 -1
  437. package/build/dist/chunks/2OJAOVMG.js +0 -1
  438. package/build/dist/chunks/65EQECL3.js +0 -1
  439. package/build/dist/chunks/6YYCGUCU.js +0 -1
  440. package/build/dist/chunks/EU3OAJU2.js +0 -1
  441. package/build/dist/chunks/H4NYYJ3Z.js +0 -1
  442. package/build/dist/chunks/JG27HM4P.js +0 -1
  443. package/build/dist/chunks/L6D26AMO.js +0 -1
  444. package/build/dist/chunks/O6L4BJP4.js +0 -1
  445. package/build/dist/chunks/SUFA2GKR.js +0 -1
  446. package/build/dist/chunks/UP7FBDMJ.js +0 -1
  447. package/build/dist/chunks/YHRUAQQK.js +0 -1
  448. package/build/dist/chunks/ZCUXM52B.js +0 -1
@@ -1 +1 @@
1
- import{i as Y}from"./S2TAJHHK.js";import{b as V,c as W,d as G}from"./65EQECL3.js";import{d as de,e as P}from"./GHPREYQK.js";import{a as B}from"./HTXKERNS.js";import{a as N}from"./PBQSJSZO.js";import{a as H,b as se,c as ae,d as j}from"./UP7FBDMJ.js";import{a as C,i as D}from"./FWD4L3CJ.js";import{a as o}from"./XSD5NL7J.js";import{a as S}from"./JXOEJPJ4.js";import{decodeEventLog as $e,encodeAbiParameters as pe,encodeFunctionData as ye,erc20Abi as Z,getAddress as l,isAddress as E,keccak256 as Ee,parseAbi as _e,parseAbiParameters as we,toEventSelector as ge}from"viem";var A=l(D[4663].hookr.HookrLimitOrders.address),ve=l(D[4663].hookr.HookrRoot.address),Ne=l(D[4663].hookr.HookrRouter.address),It=l(D[4663].hookr.HookrRegistry.address),Be=l(D[4663].hookr.HookrForwarder.address),Fe=l(D[4663].hookr.PoolManager.address),At=l(D[4663].hookr.HOOKR_Token.address),Me=l("0x000000000000000000000000000000000000dEaD"),ze=8388608,qe=200,ce=60n,Xe=604800n,ue=31536000n,ht=10,St=100,Ct="500000000000000",xt="10000000000000000",me=4096n,Q=32n,Ke=1e4,Ue=(1n<<127n)-1n,le=(1n<<128n)-1n,je=(1n<<160n)-1n,Ve=(1n<<40n)-1n,We=16777215,Ge=8388607,fe=1n<<192n,ee=0,M=1,Ye=2,Qe=3,Ze=ge("OrderCreated(uint256,address,bytes32,bool,uint128,uint128,uint128,uint40,address)"),Dt=ge("OrderCancelled(uint256,address,address,uint256,uint256)"),L=_e(["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 createOrder(((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, bool zeroForOne, uint128 amountIn, uint128 minAmountOut, uint160 sqrtPriceLimitX96, address recipient, uint40 expiry, uint128 bounty) params) payable returns (uint256 orderId)","function cancel(uint256 orderId, address to)","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 lastOrderId() view returns (uint256)","function liabilities(address currency) view returns (uint256)","function router() view returns (address)","function registry() view returns (address)","function poolManager() view returns (address)","function forwarder() view returns (address)","event OrderCreated(uint256 indexed orderId, address indexed owner, bytes32 indexed poolId, bool zeroForOne, uint128 amountIn, uint128 minAmountOut, uint128 bounty, uint40 expiry, address recipient)","event OrderCancelled(uint256 indexed orderId, address indexed owner, address indexed to, uint256 amountIn, uint256 bounty)"]);function F(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function be(e){let t=e.toLowerCase();return t===P.toLowerCase()||t===B.toLowerCase()||t===de.toLowerCase()}function $(e,t){if(typeof e!="string"||!e.trim())throw new o(`Provide a valid contract address for ${t}. Identify tokens by chain and address, never by symbol.`);let n=e.trim();if(!E(n,{strict:!1}))throw new o(`Invalid token address "${n}" for ${t}. Identify tokens by chain and address, never by symbol.`);return be(n)?P:l(n)}function ke(e){let t=e===void 0?C:Number(e);if(!Number.isSafeInteger(t)||t!==C)throw new o(`Hookr limit orders are only supported on Robinhood Chain (${C}).`);return C}function Je(e){switch(e){case ee:return"None";case M:return"Open";case Ye:return"Filled";case Qe:return"Cancelled";default:return"Unknown"}}function et(e,t,n=ae){if(typeof e!="string"||!/^-?\d+$/.test(e.trim()))throw new o("Signed amount must be an integer string in base units.");let r=e.trim();if(r.startsWith("-")){let i=r.slice(1),u=n(i,t);return u==="0"?"0":`-${u}`}return n(r,t)}function Lt(e,t,n="floor"){return se(e,t,n)}function Oe(e){return Ee(pe(we("address, address, uint24, int24, address"),[l(e.currency0),l(e.currency1),e.fee,e.tickSpacing,l(e.hooks)]))}function Ie(e,t){let n=e.toLowerCase();if(new Set([P.toLowerCase(),Me.toLowerCase(),A.toLowerCase(),Ne.toLowerCase(),Be.toLowerCase(),Fe.toLowerCase(),t.toLowerCase()]).has(n))throw new o(`Recipient ${e} is a reserved address and cannot receive Hookr limit order funds.`)}async function J(e,t,n,r){if(be(e))return{address:B,symbol:V.symbol,decimals:V.decimals,chainId:t};let i=l(e),u=i.toLowerCase();if(F(r)){let s=typeof r.decimals=="number"&&Number.isInteger(r.decimals)&&r.decimals>=0&&r.decimals<=255?r.decimals:void 0,a=typeof r.symbol=="string"&&r.symbol.trim()?r.symbol.trim():void 0;if(s!==void 0&&a!==void 0)return{address:i,symbol:a,decimals:s,chainId:t}}if(u===W.address.toLowerCase())return{...W,chainId:t};if(u===G.address.toLowerCase())return{...G,chainId:t};try{let[s,a]=await Promise.all([n.readContract({address:i,abi:Z,functionName:"symbol"}),n.readContract({address:i,abi:Z,functionName:"decimals"})]);if(typeof s!="string"||!s.trim()||typeof a!="number"||!Number.isInteger(a)||a<0||a>255)throw new o(`Invalid token metadata for ${i}.`);return{address:i,symbol:s.trim(),decimals:a,chainId:t}}catch{throw new o(`Could not read valid token metadata for ${i}. Refusing to guess token decimals.`)}}function tt(e){let t=F(e.key)?e.key:F(e.poolKey)?e.poolKey:void 0,n=t?.fee??e.fee??ze,r=(typeof n=="string"&&/^\d+$/.test(n),Number(n));if(!Number.isInteger(r)||r<0||r>We)throw new o("Pool fee must be a valid uint24 integer (default 8388608 for Hookr dynamic fee pools).");let i=t?.tickSpacing??e.tickSpacing??qe,u=(typeof i=="string"&&/^-?\d+$/.test(i),Number(i));if(!Number.isInteger(u)||u<=0||u>Ge)throw new o("Pool tickSpacing must be a positive int24 integer.");let s=t?.hooks??e.hooks??ve;if(typeof s!="string"||!E(s,{strict:!1}))throw new o("Provide a valid Hookr root contract address for hooks.");let a=l(s);if(t?.currency0!==void 0&&t?.currency1!==void 0||e.currency0!==void 0&&e.currency1!==void 0){let m=$(t?.currency0??e.currency0,"currency0"),I=$(t?.currency1??e.currency1,"currency1");if(m.toLowerCase()===I.toLowerCase())throw new o("Pool currency0 and currency1 must be distinct token addresses.");if(BigInt(m)>=BigInt(I))throw new o("Pool currency0 must sort strictly before currency1 by address.");let k;if(typeof e.zeroForOne=="boolean")k=e.zeroForOne;else if(e.tokenIn!==void 0||e.from!==void 0){let x=$(e.tokenIn??e.from,"tokenIn");if(x.toLowerCase()===m.toLowerCase())k=!0;else if(x.toLowerCase()===I.toLowerCase())k=!1;else throw new o("tokenIn does not match currency0 or currency1 of the pool key.")}else throw new o("Provide zeroForOne (boolean) or tokenIn when specifying a pool key.");return{key:{currency0:m,currency1:I,fee:r,tickSpacing:u,hooks:a},zeroForOne:k}}let w=e.tokenIn??e.from,f=e.tokenOut??e.to;if(w===void 0||f===void 0)throw new o("Provide either key ({ currency0, currency1, fee, tickSpacing, hooks }) with zeroForOne or tokenIn and tokenOut addresses.");let g=$(w,"tokenIn"),b=$(f,"tokenOut");if(g.toLowerCase()===b.toLowerCase())throw new o("Input and output tokens must have distinct addresses.");let p=BigInt(g)<BigInt(b),y=p?g:b,d=p?b:g;if(typeof e.zeroForOne=="boolean"&&e.zeroForOne!==p)throw new o("zeroForOne conflicts with the canonical sorting of tokenIn and tokenOut.");return{key:{currency0:y,currency1:d,fee:r,tickSpacing:u,hooks:a},zeroForOne:p}}function nt(e,t,n){let r=Y(t),i=r*r;if(n){let s=j(e.toString(),i.toString(),fe.toString(),"ceil");return BigInt(s)}let u=j(e.toString(),fe.toString(),i.toString(),"ceil");return BigInt(u)}function R(e,t){if(typeof e=="bigint"){if(e<0n)throw new o(`${t} must be a non-negative integer.`);return e}if(typeof e=="number"){if(!Number.isSafeInteger(e)||e<0)throw new o(`${t} must be a non-negative safe integer.`);return BigInt(e)}if(typeof e=="string")return H(e.trim());throw new o(`Provide ${t} as a decimal base-unit string.`)}async function ot(e,t){if(t!==void 0)return R(t,"now");if(typeof e.getBlock=="function"){let n=await e.getBlock().catch(()=>{throw new o("Could not read the chain timestamp for Hookr order expiry.")});return BigInt(n.timestamp)}throw new o("Could not read the chain timestamp for Hookr order expiry.")}function Ae(e,t){return!e.changes||e.changes.length===0?"no net ERC-20 transfer deltas":e.changes.map(n=>`${et(n.amount,n.token.decimals,t.formatAmount)} ${S(n.token.symbol)}`).join(", ")}function rt(e,t,n,r){if(!e||!Array.isArray(e.logs))throw new o("Provide a transaction receipt with a logs array.");for(let i of e.logs){if(!i||typeof i.address!="string"||!E(i.address,{strict:!1})||!Array.isArray(i.topics)||typeof i.data!="string"||i.topics.some(u=>typeof u!="string"||!/^0x[0-9a-fA-F]{64}$/.test(u)))throw new o(`Malformed Hookr ${t} receipt log.`);if(i.address.toLowerCase()===A.toLowerCase()&&i.topics[0]?.toLowerCase()===n.toLowerCase()){if(i.topics.length!==4||!/^0x0{24}/i.test(i.topics[2])||t==="OrderCancelled"&&!/^0x0{24}/i.test(i.topics[3])||!/^0x[0-9a-fA-F]*$/.test(i.data)||i.data.length!==2+r*64)throw new o(`Malformed Hookr ${t} receipt log.`);return{topics:i.topics,data:i.data}}}throw new o(`Could not find Hookr ${t} event in transaction receipt logs.`)}function he(e){if(e.receipt!==void 0){if(!F(e.receipt)||!Array.isArray(e.receipt.logs))throw new o("Provide a transaction receipt with a logs array.");return st({logs:e.receipt.logs})}if(e.logs!==void 0){if(!Array.isArray(e.logs))throw new o("Provide receipt logs as an array.");return it(e.logs)}}function Se(e){let t=rt(e,"OrderCreated",Ze,6);try{let n=$e({abi:L,eventName:"OrderCreated",...t,strict:!0});if(pe(we("bool, uint128, uint128, uint128, uint40, address"),[n.args.zeroForOne,n.args.amountIn,n.args.minAmountOut,n.args.bounty,n.args.expiry,n.args.recipient]).toLowerCase()!==t.data.toLowerCase())throw new o("Noncanonical Hookr OrderCreated event data.");return{orderId:n.args.orderId.toString(),owner:l(n.args.owner),poolId:n.args.poolId,zeroForOne:n.args.zeroForOne,amountIn:n.args.amountIn.toString(),minAmountOut:n.args.minAmountOut.toString(),bounty:n.args.bounty.toString(),expiry:n.args.expiry.toString(),recipient:l(n.args.recipient)}}catch{throw new o("Malformed Hookr OrderCreated receipt log.")}}function it(e){return Se({logs:e}).orderId}function st(e){return Se(e).orderId}function Ce(e){if(Array.isArray(e)){let[n,r,i,u,s,a,c,w,f,g,b]=e;return{key:Array.isArray(n)?{currency0:n[0],currency1:n[1],fee:Number(n[2]),tickSpacing:Number(n[3]),hooks:n[4]}:n,owner:r,createdAt:i,expiry:u,zeroForOne:s,status:a,recipient:c,amountIn:BigInt(w),minAmountOut:BigInt(f),bounty:BigInt(g),sqrtPriceLimitX96:BigInt(b)}}let t=e;return{key:{currency0:t.key.currency0,currency1:t.key.currency1,fee:Number(t.key.fee),tickSpacing:Number(t.key.tickSpacing),hooks:t.key.hooks},owner:t.owner,createdAt:t.createdAt,expiry:t.expiry,zeroForOne:!!t.zeroForOne,status:Number(t.status),recipient:t.recipient,amountIn:BigInt(t.amountIn),minAmountOut:BigInt(t.minAmountOut),bounty:BigInt(t.bounty),sqrtPriceLimitX96:BigInt(t.sqrtPriceLimitX96)}}async function xe(e,t,n){let r=R(t,"orderId");if(r<=0n)throw new o("Order ID must be a positive integer.");let i=e.clientFor(C),u=n?.order??await i.readContract({address:A,abi:L,functionName:"getOrder",args:[r]}).catch(()=>{throw new o(`Could not read Hookr order #${r}. Order coverage is incomplete.`)}),s=Ce(u),a=Number(s.status);if(s.owner.toLowerCase()===P.toLowerCase()||a===ee)throw new o(`Hookr order #${r} does not exist.`);let c={currency0:l(s.key.currency0),currency1:l(s.key.currency1),fee:Number(s.key.fee),tickSpacing:Number(s.key.tickSpacing),hooks:l(s.key.hooks)},w=s.zeroForOne?c.currency0:c.currency1,f=s.zeroForOne?c.currency1:c.currency0,g=m=>{let I=m.toLowerCase(),k=n?.tokens.get(I);if(k)return k;let x=J(m,C,i);return n?.tokens.set(I,x),x},[b,p]=await Promise.all([g(w),g(f)]),y=!1,d=0n;if(a===M)try{let m=await i.readContract({address:A,abi:L,functionName:"quoteFill",args:[r]});if(typeof m[0]!="boolean"||typeof m[1]!="bigint"||m[1]<0n)throw new o(`Invalid quote for Hookr order #${r}.`);y=m[0],d=m[1]}catch{throw new o(`Could not quote Hookr order #${r}. Fillability and output amount are unknown.`)}return{orderId:r.toString(),poolId:Oe(c),key:c,owner:l(s.owner),recipient:l(s.recipient),createdAt:BigInt(s.createdAt).toString(),expiry:BigInt(s.expiry).toString(),zeroForOne:s.zeroForOne,status:a,statusLabel:Je(a),amountIn:s.amountIn.toString(),minAmountOut:s.minAmountOut.toString(),bounty:s.bounty.toString(),sqrtPriceLimitX96:s.sqrtPriceLimitX96.toString(),tokenIn:b,tokenOut:p,fillable:y,quotedAmountOut:d.toString()}}function at(e){return{name:"hookr_create",inputSchema:{type:"object",properties:{key:{type:"object",properties:{currency0:{type:"string"},currency1:{type:"string"},fee:{type:"number"},tickSpacing:{type:"number"},hooks:{type:"string"}}},tokenIn:{type:"string",description:"Input token address on chain 4663."},tokenOut:{type:"string",description:"Output token address on chain 4663."},zeroForOne:{type:"boolean",description:"True when selling currency0 for currency1."},amountIn:{type:"string",description:"Input amount in base units (uint128)."},minAmountOut:{type:"string",description:"Minimum net output amount in base units (uint128)."},tick:{type:"number",description:"Optional limit tick in [-887272, 887272]."},expiry:{type:"string",description:"Order expiry unix timestamp in seconds (uint40)."},deadline:{type:"string",description:"Alias for expiry unix timestamp in seconds."},bounty:{type:"string",description:"Keeper bounty in native ETH wei (uint128)."},recipient:{type:"string",description:"Order output recipient address (must be the signing wallet)."},sqrtPriceLimitX96:{type:"string",description:"Optional sqrtPriceLimitX96 (defaults to 0)."},chainId:{type:"number",description:"Must be 4663 (Robinhood Chain)."}},required:["amountIn"]},async execute(t,n){N(n);let r=l(n),i=ke(t.chainId),u=e.clientFor(i),s=he(t),{key:a,zeroForOne:c}=tt(t),w=c?a.currency0:a.currency1,f=c?a.currency1:a.currency0,[g,b]=await Promise.all([J(w,i,u,t.tokenInMeta),J(f,i,u,t.tokenOutMeta)]),p=t.recipient??r;if(typeof p!="string"||!E(p,{strict:!1}))throw new o("Provide a valid recipient address for the Hookr limit order.");let y=l(p);if(Ie(y,a.hooks),y!==r)throw new o("Hookr recipient must be the signing wallet.");if(typeof t.amountIn!="string")throw new o("Provide amountIn as an integer string in base units.");let d=H(t.amountIn);if(d<=0n||d>Ue)throw new o("amountIn must be between 1 and int128.max base units.");if(t.tick!==void 0){let T=Number(t.tick);Y(T)}let m;if(t.minAmountOut!==void 0){if(typeof t.minAmountOut!="string")throw new o("Provide minAmountOut as an integer string in base units.");m=H(t.minAmountOut)}else if(t.tick!==void 0)m=nt(d,Number(t.tick),c);else throw new o("Provide minAmountOut in base units (or tick to derive minAmountOut).");if(m<=0n||m>le)throw new o("minAmountOut must be between 1 and uint128.max base units.");let I=t.sqrtPriceLimitX96!==void 0?R(t.sqrtPriceLimitX96,"sqrtPriceLimitX96"):0n;if(I>je)throw new o("sqrtPriceLimitX96 exceeds uint160 bounds.");let k=await ot(u,t.now),x=t.expiry??t.deadline,O;if(x!==void 0)O=R(x,"expiry");else if(t.lifetime!==void 0||t.ttlSeconds!==void 0){let T=R(t.lifetime??t.ttlSeconds,"lifetime");O=k+T}else O=k+Xe;if(O<k+ce)throw new o(`Order expiry (${O}) is expired or below the minimum lifetime of ${ce} seconds from block timestamp ${k}.`);if(O>k+ue||O>Ve)throw new o(`Order expiry (${O}) exceeds the maximum lifetime of ${ue} seconds (365 days).`);let z=await u.readContract({address:A,abi:L,functionName:"bountyBounds",args:[a,c,d,m]}).catch(()=>{throw new o("Could not read Hookr bounty bounds.")}),_=BigInt(z[0]),q=BigInt(z[1]),X=BigInt(z[2]);if(t.bounty!==void 0&&typeof t.bounty!="string")throw new o("Provide bounty as an integer string in base units.");let h=t.bounty!==void 0?H(t.bounty):q,K=_>0n?_:q;if(h<_||K>0n&&h<K)throw new o(`Order keeper bounty (${h} wei) is underbounty: must be at least ${K} wei (default keeper bounty floor).`);if(h>X||h>le)throw new o(`Order keeper bounty (${h} wei) exceeds the maximum allowed bounty of ${X} wei.`);let te=w.toLowerCase()===P.toLowerCase(),v=[];if(!te){let T;try{let U=await u.readContract({address:w,abi:Z,functionName:"allowance",args:[r,A]});if(typeof U!="bigint"||U<0n)throw new o("Invalid token allowance.");T=U}catch{throw new o(`Could not read token allowance for ${w}. No approval was prepared.`)}T<d&&v.push(e.approval(w,A,d.toString(),i))}let Le=te?d+h:h,Pe=ye({abi:L,functionName:"createOrder",args:[{key:a,zeroForOne:c,amountIn:d,minAmountOut:m,sqrtPriceLimitX96:I,recipient:y,expiry:Number(O),bounty:h}]}),ne=e.formatAmount(d.toString(),g.decimals),oe=e.formatAmount(m.toString(),b.decimals),re=e.formatAmount(h.toString(),18),Te=e.unsignedTx({to:A,data:Pe,value:Le.toString(),chainId:i,description:`Create Hookr limit order on ${A}: sell ${ne} ${S(g.symbol)} (${g.address}) for at least ${oe} ${S(b.symbol)} (${b.address}) with ${re} ETH keeper bounty (fee=${a.fee}, tickSpacing=${a.tickSpacing}, expiry=${O}).`});v.push(Te);let ie=await e.preview(v,r),Re=Ae(ie,e),He=Oe(a);return{txs:v,summary:`Hookr limit order prepared: sell ${ne} ${S(g.symbol)} for at least ${oe} ${S(b.symbol)} (bounty ${re} ETH, expiry ${O}; preview deltas: ${Re}).`,preview:ie,poolId:He,key:a,zeroForOne:c,amountIn:d.toString(),minAmountOut:m.toString(),bounty:h.toString(),bountyBounds:{minBounty:_.toString(),defaultBounty:q.toString(),maxBounty:X.toString()},expiry:O.toString(),recipient:y,sqrtPriceLimitX96:I.toString(),tokenIn:g,tokenOut:b,...s!==void 0?{orderId:s}:{}}}}}function dt(e){return{name:"hookr_cancel",inputSchema:{type:"object",properties:{orderId:{type:"string",description:"Hookr order ID to cancel (uint256 decimal string)."},to:{type:"string",description:"Recipient address for the refunded principal and bounty (must be the signing wallet)."},chainId:{type:"number",description:"Must be 4663 (Robinhood Chain)."}},required:["orderId"]},async execute(t,n){N(n);let r=l(n),i=ke(t.chainId),u=he(t),s=t.orderId??t.id??u;if(s===void 0)throw new o("Provide orderId to cancel a Hookr limit order.");let a=R(s,"orderId");if(a<=0n)throw new o("orderId must be a positive integer.");let c=await xe(e,a);if(c.owner.toLowerCase()!==r.toLowerCase())throw new o(`Unauthorized cancellation: only the order owner (${c.owner}) can cancel Hookr order #${a} (caller is ${r}).`);if(c.status!==M)throw new o(`Hookr order #${a} is not open (current status: ${c.statusLabel}).`);let w=t.to??r;if(typeof w!="string"||!E(w,{strict:!1}))throw new o("Provide a valid refund recipient address for cancel.");let f=l(w);if(Ie(f,c.key.hooks),f!==r)throw new o("Hookr refund recipient must be the signing wallet.");let g=ye({abi:L,functionName:"cancel",args:[a,f]}),b=e.formatAmount(c.amountIn,c.tokenIn.decimals),p=e.formatAmount(c.bounty,18),y=e.unsignedTx({to:A,data:g,value:"0",chainId:i,description:`Cancel Hookr limit order #${a} on ${A} and refund ${b} ${S(c.tokenIn.symbol)} plus ${p} ETH bounty to ${f}.`}),d=await e.preview([y],r),m=Ae(d,e);return{txs:[y],summary:`Cancel Hookr limit order #${a}: refund ${b} ${S(c.tokenIn.symbol)} and ${p} ETH bounty to ${f} (preview deltas: ${m}).`,preview:d,orderId:a.toString(),to:f,refundedAmountIn:c.amountIn,refundedBounty:c.bounty,tokenIn:c.tokenIn,tokenOut:c.tokenOut}}}}function ct(e){let t=performance.now()+Ke;return new Proxy(e,{get(n,r,i){return r!=="readContract"?Reflect.get(n,r,i):async(...u)=>{let s=t-performance.now(),a=()=>new o("Hookr scan deadline exceeded. Order coverage is incomplete; retry later.");if(s<=0)throw a();let c;try{return await Promise.race([n.readContract(...u),new Promise((w,f)=>{c=setTimeout(()=>f(a()),s)})])}finally{c!==void 0&&clearTimeout(c)}}}})}function ut(e){return async t=>{N(t);let n=l(t),r=ct(e.clientFor(C)),i={...e,clientFor:()=>r},u=await r.readContract({address:A,abi:L,functionName:"lastOrderId"}).catch(()=>{throw new o("Could not read the last Hookr order ID. Order coverage is incomplete.")});if(typeof u!="bigint"||u<0n)throw new o("Could not read a valid last Hookr order ID. Order coverage is incomplete.");let s=u,a=s>me?s-me+1n:1n;if(s<=0n)return[];let c=[],w=new Map;for(let f=a;f<=s;f+=Q){let g=Array.from({length:Number(s-f+1n<Q?s-f+1n:Q)},(p,y)=>f+BigInt(y)),b=await Promise.all(g.map(async p=>{let y=await r.readContract({address:A,abi:L,functionName:"getOrder",args:[p]}).catch(()=>{throw new o(`Could not read Hookr order #${p}. Order coverage is incomplete.`)}),d=Ce(y);if(d.owner.toLowerCase()===P||Number(d.status)===ee)throw new o(`Hookr order #${p} does not exist. Order coverage is incomplete.`);return{id:p,order:d}}));for(let{id:p,order:y}of b){if(y.owner.toLowerCase()!==n.toLowerCase()||Number(y.status)!==M)continue;let d=await xe(i,p,{order:y,tokens:w}),m=[{token:d.tokenIn,amount:d.amountIn}];BigInt(d.bounty)>0n&&m.push({token:{address:B,symbol:"ETH",decimals:18,chainId:C},amount:d.bounty});let I=e.formatAmount(d.amountIn,d.tokenIn.decimals),k=e.formatAmount(d.minAmountOut,d.tokenOut.decimals),x=e.formatAmount(d.bounty,18),O=e.formatAmount(d.quotedAmountOut,d.tokenOut.decimals);c.push({module:"hookr",id:d.orderId,chainId:C,assets:m,description:`Hookr open limit order #${d.orderId}: sell ${I} ${S(d.tokenIn.symbol)} (${d.tokenIn.address}) for at least ${k} ${S(d.tokenOut.symbol)} (${d.tokenOut.address}), bounty ${x} ETH, expiry ${d.expiry}, fillable=${d.fillable} (quoted output ${O} ${S(d.tokenOut.symbol)}).`})}}return a>1n&&c.push({module:"hookr",id:"coverage",chainId:C,assets:[],description:`Hookr order coverage is incomplete: scanned IDs ${a}-${s}. Older orders require an explicit order ID.`}),c}}var De=e=>{let t=[at(e),dt(e)],n=ut(e);return{tools:t,positions:n}},Pt=De,Tt=De;export{A as a,ve as b,Ne as c,It as d,Be as e,Fe as f,At as g,Me as h,ze as i,qe as j,ce as k,Xe as l,ue as m,ht as n,St as o,Ct as p,xt as q,me as r,Ke as s,ee as t,M as u,Ye as v,Qe as w,Ze as x,Dt as y,L as z,et as A,Lt as B,Oe as C,rt as D,Se as E,it as F,st as G,Ce as H,xe as I,at as J,dt as K,ct as L,ut as M,De as N,Pt as O,Tt as P};
1
+ import{i as Y}from"./57MEFFCU.js";import{b as V,c as W,d as G}from"./P56RZC2M.js";import{d as de,e as P}from"./3NJ5KQ3Q.js";import{a as B}from"./3MLUCYCB.js";import{a as N}from"./43LI5NKJ.js";import{b as H,c as se,d as ae,e as j}from"./IX3GZMTM.js";import{a as C,i as D}from"./FWD4L3CJ.js";import{a as o}from"./XSD5NL7J.js";import{a as S}from"./JXOEJPJ4.js";import{decodeEventLog as $e,encodeAbiParameters as pe,encodeFunctionData as ye,erc20Abi as Z,getAddress as l,isAddress as E,keccak256 as Ee,parseAbi as _e,parseAbiParameters as we,toEventSelector as ge}from"viem";var A=l(D[4663].hookr.HookrLimitOrders.address),ve=l(D[4663].hookr.HookrRoot.address),Ne=l(D[4663].hookr.HookrRouter.address),It=l(D[4663].hookr.HookrRegistry.address),Be=l(D[4663].hookr.HookrForwarder.address),Fe=l(D[4663].hookr.PoolManager.address),At=l(D[4663].hookr.HOOKR_Token.address),Me=l("0x000000000000000000000000000000000000dEaD"),ze=8388608,qe=200,ce=60n,Xe=604800n,ue=31536000n,ht=10,St=100,Ct="500000000000000",xt="10000000000000000",me=4096n,Q=32n,Ke=1e4,Ue=(1n<<127n)-1n,le=(1n<<128n)-1n,je=(1n<<160n)-1n,Ve=(1n<<40n)-1n,We=16777215,Ge=8388607,fe=1n<<192n,ee=0,M=1,Ye=2,Qe=3,Ze=ge("OrderCreated(uint256,address,bytes32,bool,uint128,uint128,uint128,uint40,address)"),Dt=ge("OrderCancelled(uint256,address,address,uint256,uint256)"),L=_e(["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 createOrder(((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, bool zeroForOne, uint128 amountIn, uint128 minAmountOut, uint160 sqrtPriceLimitX96, address recipient, uint40 expiry, uint128 bounty) params) payable returns (uint256 orderId)","function cancel(uint256 orderId, address to)","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 lastOrderId() view returns (uint256)","function liabilities(address currency) view returns (uint256)","function router() view returns (address)","function registry() view returns (address)","function poolManager() view returns (address)","function forwarder() view returns (address)","event OrderCreated(uint256 indexed orderId, address indexed owner, bytes32 indexed poolId, bool zeroForOne, uint128 amountIn, uint128 minAmountOut, uint128 bounty, uint40 expiry, address recipient)","event OrderCancelled(uint256 indexed orderId, address indexed owner, address indexed to, uint256 amountIn, uint256 bounty)"]);function F(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function be(e){let t=e.toLowerCase();return t===P.toLowerCase()||t===B.toLowerCase()||t===de.toLowerCase()}function $(e,t){if(typeof e!="string"||!e.trim())throw new o(`Provide a valid contract address for ${t}. Identify tokens by chain and address, never by symbol.`);let n=e.trim();if(!E(n,{strict:!1}))throw new o(`Invalid token address "${n}" for ${t}. Identify tokens by chain and address, never by symbol.`);return be(n)?P:l(n)}function ke(e){let t=e===void 0?C:Number(e);if(!Number.isSafeInteger(t)||t!==C)throw new o(`Hookr limit orders are only supported on Robinhood Chain (${C}).`);return C}function Je(e){switch(e){case ee:return"None";case M:return"Open";case Ye:return"Filled";case Qe:return"Cancelled";default:return"Unknown"}}function et(e,t,n=ae){if(typeof e!="string"||!/^-?\d+$/.test(e.trim()))throw new o("Signed amount must be an integer string in base units.");let r=e.trim();if(r.startsWith("-")){let i=r.slice(1),u=n(i,t);return u==="0"?"0":`-${u}`}return n(r,t)}function Lt(e,t,n="floor"){return se(e,t,n)}function Oe(e){return Ee(pe(we("address, address, uint24, int24, address"),[l(e.currency0),l(e.currency1),e.fee,e.tickSpacing,l(e.hooks)]))}function Ie(e,t){let n=e.toLowerCase();if(new Set([P.toLowerCase(),Me.toLowerCase(),A.toLowerCase(),Ne.toLowerCase(),Be.toLowerCase(),Fe.toLowerCase(),t.toLowerCase()]).has(n))throw new o(`Recipient ${e} is a reserved address and cannot receive Hookr limit order funds.`)}async function J(e,t,n,r){if(be(e))return{address:B,symbol:V.symbol,decimals:V.decimals,chainId:t};let i=l(e),u=i.toLowerCase();if(F(r)){let s=typeof r.decimals=="number"&&Number.isInteger(r.decimals)&&r.decimals>=0&&r.decimals<=255?r.decimals:void 0,a=typeof r.symbol=="string"&&r.symbol.trim()?r.symbol.trim():void 0;if(s!==void 0&&a!==void 0)return{address:i,symbol:a,decimals:s,chainId:t}}if(u===W.address.toLowerCase())return{...W,chainId:t};if(u===G.address.toLowerCase())return{...G,chainId:t};try{let[s,a]=await Promise.all([n.readContract({address:i,abi:Z,functionName:"symbol"}),n.readContract({address:i,abi:Z,functionName:"decimals"})]);if(typeof s!="string"||!s.trim()||typeof a!="number"||!Number.isInteger(a)||a<0||a>255)throw new o(`Invalid token metadata for ${i}.`);return{address:i,symbol:s.trim(),decimals:a,chainId:t}}catch{throw new o(`Could not read valid token metadata for ${i}. Refusing to guess token decimals.`)}}function tt(e){let t=F(e.key)?e.key:F(e.poolKey)?e.poolKey:void 0,n=t?.fee??e.fee??ze,r=(typeof n=="string"&&/^\d+$/.test(n),Number(n));if(!Number.isInteger(r)||r<0||r>We)throw new o("Pool fee must be a valid uint24 integer (default 8388608 for Hookr dynamic fee pools).");let i=t?.tickSpacing??e.tickSpacing??qe,u=(typeof i=="string"&&/^-?\d+$/.test(i),Number(i));if(!Number.isInteger(u)||u<=0||u>Ge)throw new o("Pool tickSpacing must be a positive int24 integer.");let s=t?.hooks??e.hooks??ve;if(typeof s!="string"||!E(s,{strict:!1}))throw new o("Provide a valid Hookr root contract address for hooks.");let a=l(s);if(t?.currency0!==void 0&&t?.currency1!==void 0||e.currency0!==void 0&&e.currency1!==void 0){let m=$(t?.currency0??e.currency0,"currency0"),I=$(t?.currency1??e.currency1,"currency1");if(m.toLowerCase()===I.toLowerCase())throw new o("Pool currency0 and currency1 must be distinct token addresses.");if(BigInt(m)>=BigInt(I))throw new o("Pool currency0 must sort strictly before currency1 by address.");let k;if(typeof e.zeroForOne=="boolean")k=e.zeroForOne;else if(e.tokenIn!==void 0||e.from!==void 0){let x=$(e.tokenIn??e.from,"tokenIn");if(x.toLowerCase()===m.toLowerCase())k=!0;else if(x.toLowerCase()===I.toLowerCase())k=!1;else throw new o("tokenIn does not match currency0 or currency1 of the pool key.")}else throw new o("Provide zeroForOne (boolean) or tokenIn when specifying a pool key.");return{key:{currency0:m,currency1:I,fee:r,tickSpacing:u,hooks:a},zeroForOne:k}}let w=e.tokenIn??e.from,f=e.tokenOut??e.to;if(w===void 0||f===void 0)throw new o("Provide either key ({ currency0, currency1, fee, tickSpacing, hooks }) with zeroForOne or tokenIn and tokenOut addresses.");let g=$(w,"tokenIn"),b=$(f,"tokenOut");if(g.toLowerCase()===b.toLowerCase())throw new o("Input and output tokens must have distinct addresses.");let p=BigInt(g)<BigInt(b),y=p?g:b,d=p?b:g;if(typeof e.zeroForOne=="boolean"&&e.zeroForOne!==p)throw new o("zeroForOne conflicts with the canonical sorting of tokenIn and tokenOut.");return{key:{currency0:y,currency1:d,fee:r,tickSpacing:u,hooks:a},zeroForOne:p}}function nt(e,t,n){let r=Y(t),i=r*r;if(n){let s=j(e.toString(),i.toString(),fe.toString(),"ceil");return BigInt(s)}let u=j(e.toString(),fe.toString(),i.toString(),"ceil");return BigInt(u)}function R(e,t){if(typeof e=="bigint"){if(e<0n)throw new o(`${t} must be a non-negative integer.`);return e}if(typeof e=="number"){if(!Number.isSafeInteger(e)||e<0)throw new o(`${t} must be a non-negative safe integer.`);return BigInt(e)}if(typeof e=="string")return H(e.trim());throw new o(`Provide ${t} as a decimal base-unit string.`)}async function ot(e,t){if(t!==void 0)return R(t,"now");if(typeof e.getBlock=="function"){let n=await e.getBlock().catch(()=>{throw new o("Could not read the chain timestamp for Hookr order expiry.")});return BigInt(n.timestamp)}throw new o("Could not read the chain timestamp for Hookr order expiry.")}function Ae(e,t){return!e.changes||e.changes.length===0?"no net ERC-20 transfer deltas":e.changes.map(n=>`${et(n.amount,n.token.decimals,t.formatAmount)} ${S(n.token.symbol)}`).join(", ")}function rt(e,t,n,r){if(!e||!Array.isArray(e.logs))throw new o("Provide a transaction receipt with a logs array.");for(let i of e.logs){if(!i||typeof i.address!="string"||!E(i.address,{strict:!1})||!Array.isArray(i.topics)||typeof i.data!="string"||i.topics.some(u=>typeof u!="string"||!/^0x[0-9a-fA-F]{64}$/.test(u)))throw new o(`Malformed Hookr ${t} receipt log.`);if(i.address.toLowerCase()===A.toLowerCase()&&i.topics[0]?.toLowerCase()===n.toLowerCase()){if(i.topics.length!==4||!/^0x0{24}/i.test(i.topics[2])||t==="OrderCancelled"&&!/^0x0{24}/i.test(i.topics[3])||!/^0x[0-9a-fA-F]*$/.test(i.data)||i.data.length!==2+r*64)throw new o(`Malformed Hookr ${t} receipt log.`);return{topics:i.topics,data:i.data}}}throw new o(`Could not find Hookr ${t} event in transaction receipt logs.`)}function he(e){if(e.receipt!==void 0){if(!F(e.receipt)||!Array.isArray(e.receipt.logs))throw new o("Provide a transaction receipt with a logs array.");return st({logs:e.receipt.logs})}if(e.logs!==void 0){if(!Array.isArray(e.logs))throw new o("Provide receipt logs as an array.");return it(e.logs)}}function Se(e){let t=rt(e,"OrderCreated",Ze,6);try{let n=$e({abi:L,eventName:"OrderCreated",...t,strict:!0});if(pe(we("bool, uint128, uint128, uint128, uint40, address"),[n.args.zeroForOne,n.args.amountIn,n.args.minAmountOut,n.args.bounty,n.args.expiry,n.args.recipient]).toLowerCase()!==t.data.toLowerCase())throw new o("Noncanonical Hookr OrderCreated event data.");return{orderId:n.args.orderId.toString(),owner:l(n.args.owner),poolId:n.args.poolId,zeroForOne:n.args.zeroForOne,amountIn:n.args.amountIn.toString(),minAmountOut:n.args.minAmountOut.toString(),bounty:n.args.bounty.toString(),expiry:n.args.expiry.toString(),recipient:l(n.args.recipient)}}catch{throw new o("Malformed Hookr OrderCreated receipt log.")}}function it(e){return Se({logs:e}).orderId}function st(e){return Se(e).orderId}function Ce(e){if(Array.isArray(e)){let[n,r,i,u,s,a,c,w,f,g,b]=e;return{key:Array.isArray(n)?{currency0:n[0],currency1:n[1],fee:Number(n[2]),tickSpacing:Number(n[3]),hooks:n[4]}:n,owner:r,createdAt:i,expiry:u,zeroForOne:s,status:a,recipient:c,amountIn:BigInt(w),minAmountOut:BigInt(f),bounty:BigInt(g),sqrtPriceLimitX96:BigInt(b)}}let t=e;return{key:{currency0:t.key.currency0,currency1:t.key.currency1,fee:Number(t.key.fee),tickSpacing:Number(t.key.tickSpacing),hooks:t.key.hooks},owner:t.owner,createdAt:t.createdAt,expiry:t.expiry,zeroForOne:!!t.zeroForOne,status:Number(t.status),recipient:t.recipient,amountIn:BigInt(t.amountIn),minAmountOut:BigInt(t.minAmountOut),bounty:BigInt(t.bounty),sqrtPriceLimitX96:BigInt(t.sqrtPriceLimitX96)}}async function xe(e,t,n){let r=R(t,"orderId");if(r<=0n)throw new o("Order ID must be a positive integer.");let i=e.clientFor(C),u=n?.order??await i.readContract({address:A,abi:L,functionName:"getOrder",args:[r]}).catch(()=>{throw new o(`Could not read Hookr order #${r}. Order coverage is incomplete.`)}),s=Ce(u),a=Number(s.status);if(s.owner.toLowerCase()===P.toLowerCase()||a===ee)throw new o(`Hookr order #${r} does not exist.`);let c={currency0:l(s.key.currency0),currency1:l(s.key.currency1),fee:Number(s.key.fee),tickSpacing:Number(s.key.tickSpacing),hooks:l(s.key.hooks)},w=s.zeroForOne?c.currency0:c.currency1,f=s.zeroForOne?c.currency1:c.currency0,g=m=>{let I=m.toLowerCase(),k=n?.tokens.get(I);if(k)return k;let x=J(m,C,i);return n?.tokens.set(I,x),x},[b,p]=await Promise.all([g(w),g(f)]),y=!1,d=0n;if(a===M)try{let m=await i.readContract({address:A,abi:L,functionName:"quoteFill",args:[r]});if(typeof m[0]!="boolean"||typeof m[1]!="bigint"||m[1]<0n)throw new o(`Invalid quote for Hookr order #${r}.`);y=m[0],d=m[1]}catch{throw new o(`Could not quote Hookr order #${r}. Fillability and output amount are unknown.`)}return{orderId:r.toString(),poolId:Oe(c),key:c,owner:l(s.owner),recipient:l(s.recipient),createdAt:BigInt(s.createdAt).toString(),expiry:BigInt(s.expiry).toString(),zeroForOne:s.zeroForOne,status:a,statusLabel:Je(a),amountIn:s.amountIn.toString(),minAmountOut:s.minAmountOut.toString(),bounty:s.bounty.toString(),sqrtPriceLimitX96:s.sqrtPriceLimitX96.toString(),tokenIn:b,tokenOut:p,fillable:y,quotedAmountOut:d.toString()}}function at(e){return{name:"hookr_create",inputSchema:{type:"object",properties:{key:{type:"object",properties:{currency0:{type:"string"},currency1:{type:"string"},fee:{type:"number"},tickSpacing:{type:"number"},hooks:{type:"string"}}},tokenIn:{type:"string",description:"Input token address on chain 4663."},tokenOut:{type:"string",description:"Output token address on chain 4663."},zeroForOne:{type:"boolean",description:"True when selling currency0 for currency1."},amountIn:{type:"string",description:"Input amount in base units (uint128)."},minAmountOut:{type:"string",description:"Minimum net output amount in base units (uint128)."},tick:{type:"number",description:"Optional limit tick in [-887272, 887272]."},expiry:{type:"string",description:"Order expiry unix timestamp in seconds (uint40)."},deadline:{type:"string",description:"Alias for expiry unix timestamp in seconds."},bounty:{type:"string",description:"Keeper bounty in native ETH wei (uint128)."},recipient:{type:"string",description:"Order output recipient address (must be the signing wallet)."},sqrtPriceLimitX96:{type:"string",description:"Optional sqrtPriceLimitX96 (defaults to 0)."},chainId:{type:"number",description:"Must be 4663 (Robinhood Chain)."}},required:["amountIn"]},async execute(t,n){N(n);let r=l(n),i=ke(t.chainId),u=e.clientFor(i),s=he(t),{key:a,zeroForOne:c}=tt(t),w=c?a.currency0:a.currency1,f=c?a.currency1:a.currency0,[g,b]=await Promise.all([J(w,i,u,t.tokenInMeta),J(f,i,u,t.tokenOutMeta)]),p=t.recipient??r;if(typeof p!="string"||!E(p,{strict:!1}))throw new o("Provide a valid recipient address for the Hookr limit order.");let y=l(p);if(Ie(y,a.hooks),y!==r)throw new o("Hookr recipient must be the signing wallet.");if(typeof t.amountIn!="string")throw new o("Provide amountIn as an integer string in base units.");let d=H(t.amountIn);if(d<=0n||d>Ue)throw new o("amountIn must be between 1 and int128.max base units.");if(t.tick!==void 0){let T=Number(t.tick);Y(T)}let m;if(t.minAmountOut!==void 0){if(typeof t.minAmountOut!="string")throw new o("Provide minAmountOut as an integer string in base units.");m=H(t.minAmountOut)}else if(t.tick!==void 0)m=nt(d,Number(t.tick),c);else throw new o("Provide minAmountOut in base units (or tick to derive minAmountOut).");if(m<=0n||m>le)throw new o("minAmountOut must be between 1 and uint128.max base units.");let I=t.sqrtPriceLimitX96!==void 0?R(t.sqrtPriceLimitX96,"sqrtPriceLimitX96"):0n;if(I>je)throw new o("sqrtPriceLimitX96 exceeds uint160 bounds.");let k=await ot(u,t.now),x=t.expiry??t.deadline,O;if(x!==void 0)O=R(x,"expiry");else if(t.lifetime!==void 0||t.ttlSeconds!==void 0){let T=R(t.lifetime??t.ttlSeconds,"lifetime");O=k+T}else O=k+Xe;if(O<k+ce)throw new o(`Order expiry (${O}) is expired or below the minimum lifetime of ${ce} seconds from block timestamp ${k}.`);if(O>k+ue||O>Ve)throw new o(`Order expiry (${O}) exceeds the maximum lifetime of ${ue} seconds (365 days).`);let z=await u.readContract({address:A,abi:L,functionName:"bountyBounds",args:[a,c,d,m]}).catch(()=>{throw new o("Could not read Hookr bounty bounds.")}),_=BigInt(z[0]),q=BigInt(z[1]),X=BigInt(z[2]);if(t.bounty!==void 0&&typeof t.bounty!="string")throw new o("Provide bounty as an integer string in base units.");let h=t.bounty!==void 0?H(t.bounty):q,K=_>0n?_:q;if(h<_||K>0n&&h<K)throw new o(`Order keeper bounty (${h} wei) is underbounty: must be at least ${K} wei (default keeper bounty floor).`);if(h>X||h>le)throw new o(`Order keeper bounty (${h} wei) exceeds the maximum allowed bounty of ${X} wei.`);let te=w.toLowerCase()===P.toLowerCase(),v=[];if(!te){let T;try{let U=await u.readContract({address:w,abi:Z,functionName:"allowance",args:[r,A]});if(typeof U!="bigint"||U<0n)throw new o("Invalid token allowance.");T=U}catch{throw new o(`Could not read token allowance for ${w}. No approval was prepared.`)}T<d&&v.push(e.approval(w,A,d.toString(),i))}let Le=te?d+h:h,Pe=ye({abi:L,functionName:"createOrder",args:[{key:a,zeroForOne:c,amountIn:d,minAmountOut:m,sqrtPriceLimitX96:I,recipient:y,expiry:Number(O),bounty:h}]}),ne=e.formatAmount(d.toString(),g.decimals),oe=e.formatAmount(m.toString(),b.decimals),re=e.formatAmount(h.toString(),18),Te=e.unsignedTx({to:A,data:Pe,value:Le.toString(),chainId:i,description:`Create Hookr limit order on ${A}: sell ${ne} ${S(g.symbol)} (${g.address}) for at least ${oe} ${S(b.symbol)} (${b.address}) with ${re} ETH keeper bounty (fee=${a.fee}, tickSpacing=${a.tickSpacing}, expiry=${O}).`});v.push(Te);let ie=await e.preview(v,r),Re=Ae(ie,e),He=Oe(a);return{txs:v,summary:`Hookr limit order prepared: sell ${ne} ${S(g.symbol)} for at least ${oe} ${S(b.symbol)} (bounty ${re} ETH, expiry ${O}; preview deltas: ${Re}).`,preview:ie,poolId:He,key:a,zeroForOne:c,amountIn:d.toString(),minAmountOut:m.toString(),bounty:h.toString(),bountyBounds:{minBounty:_.toString(),defaultBounty:q.toString(),maxBounty:X.toString()},expiry:O.toString(),recipient:y,sqrtPriceLimitX96:I.toString(),tokenIn:g,tokenOut:b,...s!==void 0?{orderId:s}:{}}}}}function dt(e){return{name:"hookr_cancel",inputSchema:{type:"object",properties:{orderId:{type:"string",description:"Hookr order ID to cancel (uint256 decimal string)."},to:{type:"string",description:"Recipient address for the refunded principal and bounty (must be the signing wallet)."},chainId:{type:"number",description:"Must be 4663 (Robinhood Chain)."}},required:["orderId"]},async execute(t,n){N(n);let r=l(n),i=ke(t.chainId),u=he(t),s=t.orderId??t.id??u;if(s===void 0)throw new o("Provide orderId to cancel a Hookr limit order.");let a=R(s,"orderId");if(a<=0n)throw new o("orderId must be a positive integer.");let c=await xe(e,a);if(c.owner.toLowerCase()!==r.toLowerCase())throw new o(`Unauthorized cancellation: only the order owner (${c.owner}) can cancel Hookr order #${a} (caller is ${r}).`);if(c.status!==M)throw new o(`Hookr order #${a} is not open (current status: ${c.statusLabel}).`);let w=t.to??r;if(typeof w!="string"||!E(w,{strict:!1}))throw new o("Provide a valid refund recipient address for cancel.");let f=l(w);if(Ie(f,c.key.hooks),f!==r)throw new o("Hookr refund recipient must be the signing wallet.");let g=ye({abi:L,functionName:"cancel",args:[a,f]}),b=e.formatAmount(c.amountIn,c.tokenIn.decimals),p=e.formatAmount(c.bounty,18),y=e.unsignedTx({to:A,data:g,value:"0",chainId:i,description:`Cancel Hookr limit order #${a} on ${A} and refund ${b} ${S(c.tokenIn.symbol)} plus ${p} ETH bounty to ${f}.`}),d=await e.preview([y],r),m=Ae(d,e);return{txs:[y],summary:`Cancel Hookr limit order #${a}: refund ${b} ${S(c.tokenIn.symbol)} and ${p} ETH bounty to ${f} (preview deltas: ${m}).`,preview:d,orderId:a.toString(),to:f,refundedAmountIn:c.amountIn,refundedBounty:c.bounty,tokenIn:c.tokenIn,tokenOut:c.tokenOut}}}}function ct(e){let t=performance.now()+Ke;return new Proxy(e,{get(n,r,i){return r!=="readContract"?Reflect.get(n,r,i):async(...u)=>{let s=t-performance.now(),a=()=>new o("Hookr scan deadline exceeded. Order coverage is incomplete; retry later.");if(s<=0)throw a();let c;try{return await Promise.race([n.readContract(...u),new Promise((w,f)=>{c=setTimeout(()=>f(a()),s)})])}finally{c!==void 0&&clearTimeout(c)}}}})}function ut(e){return async t=>{N(t);let n=l(t),r=ct(e.clientFor(C)),i={...e,clientFor:()=>r},u=await r.readContract({address:A,abi:L,functionName:"lastOrderId"}).catch(()=>{throw new o("Could not read the last Hookr order ID. Order coverage is incomplete.")});if(typeof u!="bigint"||u<0n)throw new o("Could not read a valid last Hookr order ID. Order coverage is incomplete.");let s=u,a=s>me?s-me+1n:1n;if(s<=0n)return[];let c=[],w=new Map;for(let f=a;f<=s;f+=Q){let g=Array.from({length:Number(s-f+1n<Q?s-f+1n:Q)},(p,y)=>f+BigInt(y)),b=await Promise.all(g.map(async p=>{let y=await r.readContract({address:A,abi:L,functionName:"getOrder",args:[p]}).catch(()=>{throw new o(`Could not read Hookr order #${p}. Order coverage is incomplete.`)}),d=Ce(y);if(d.owner.toLowerCase()===P||Number(d.status)===ee)throw new o(`Hookr order #${p} does not exist. Order coverage is incomplete.`);return{id:p,order:d}}));for(let{id:p,order:y}of b){if(y.owner.toLowerCase()!==n.toLowerCase()||Number(y.status)!==M)continue;let d=await xe(i,p,{order:y,tokens:w}),m=[{token:d.tokenIn,amount:d.amountIn}];BigInt(d.bounty)>0n&&m.push({token:{address:B,symbol:"ETH",decimals:18,chainId:C},amount:d.bounty});let I=e.formatAmount(d.amountIn,d.tokenIn.decimals),k=e.formatAmount(d.minAmountOut,d.tokenOut.decimals),x=e.formatAmount(d.bounty,18),O=e.formatAmount(d.quotedAmountOut,d.tokenOut.decimals);c.push({module:"hookr",id:d.orderId,chainId:C,assets:m,description:`Hookr open limit order #${d.orderId}: sell ${I} ${S(d.tokenIn.symbol)} (${d.tokenIn.address}) for at least ${k} ${S(d.tokenOut.symbol)} (${d.tokenOut.address}), bounty ${x} ETH, expiry ${d.expiry}, fillable=${d.fillable} (quoted output ${O} ${S(d.tokenOut.symbol)}).`})}}return a>1n&&c.push({module:"hookr",id:"coverage",chainId:C,assets:[],description:`Hookr order coverage is incomplete: scanned IDs ${a}-${s}. Older orders require an explicit order ID.`}),c}}var De=e=>{let t=[at(e),dt(e)],n=ut(e);return{tools:t,positions:n}},Pt=De,Tt=De;export{A as a,ve as b,Ne as c,It as d,Be as e,Fe as f,At as g,Me as h,ze as i,qe as j,ce as k,Xe as l,ue as m,ht as n,St as o,Ct as p,xt as q,me as r,Ke as s,ee as t,M as u,Ye as v,Qe as w,Ze as x,Dt as y,L as z,et as A,Lt as B,Oe as C,rt as D,Se as E,it as F,st as G,Ce as H,xe as I,at as J,dt as K,ct as L,ut as M,De as N,Pt as O,Tt as P};
@@ -1 +1 @@
1
- import{a as k}from"./5ZLOCQA4.js";import{c as l}from"./5KUWLUPM.js";import{a as p}from"./FWD4L3CJ.js";import{a as s}from"./XSD5NL7J.js";import{encodeFunctionData as H,getAddress as m,parseAbi as f,zeroAddress as w}from"viem";var x=f(["function tokenizations(address token) view returns ((address creator,address forwarder,bytes32 marketFamilyId,uint64 createdAt))"]),S=f(["function tokenizations(address token) view returns ((address creator,uint8 way,address forwarder,address adapter,address door,bytes32 familyId,bytes32 marketFamilyId,uint64 unlockBlock,uint16 legBps))"]),b=f(["function name() view returns (string)","function symbol() view returns (string)","function decimals() view returns (uint8)","function balanceOf(address account) view returns (uint256)","function totalSupply() view returns (uint256)","function assetCount() view returns (uint256)","function claimable(address account,uint256 asset) view returns (uint256)","function streamSeconds() view returns (uint32)","function tipBps() view returns (uint16)","function doorCount() view returns (uint256)","function dropBox() view returns (address)","function bridge() view returns (address)","function claim(uint256 asset,address to) returns (uint256 amount)","function claimAll(address to) returns (uint256[] amounts)","function sync() returns (uint256 tip)","function syncRange(uint256 start,uint256 count) returns (uint256 tip)","function syncSome(uint256[] doorIds) returns (uint256 tip)"]),C=f(["function dropCount() view returns (uint256)","function claimable(uint256 dropId,address holder) view returns (uint256)","function claim(uint256[] dropIds,address to) returns (uint256[] amounts)"]),y=["0x522723A7a09684515881568Ab8247f3846D66F43","0xfb3c1501c727f30883cd7B36Ec380381af7412Ef"].map(m),I={token:b,drops:C};function O(n){return{type:"object",properties:Object.fromEntries(n.inputs.map(t=>[t.name,t.type==="address"?l:t.type==="uint256[]"?{type:"array",items:k(),maxItems:128}:k()])),required:n.inputs.map(t=>t.name),additionalProperties:!1}}function h(n){return Object.entries(I).flatMap(([t,o])=>o.filter(r=>r.stateMutability==="view"===n).map(r=>({target:t,fn:r})))}function v(n){return{type:"object",oneOf:h(n).map(({target:t,fn:o})=>({type:"object",properties:{token:l,target:{const:t},function:{const:o.name},params:O(o)},required:["token","target","function","params"],additionalProperties:!1}))}}function A(n,t){if(Object.keys(n).length!==4||Object.keys(n).some(e=>!["token","target","function","params"].includes(e)))throw new s("Provide token, target, function and params for the Hookr revenue operation.");let o=h(t).find(e=>e.target===n.target&&e.fn.name===n.function);if(!o||!n.params||typeof n.params!="object"||Array.isArray(n.params))throw new s("Choose a documented Hookr revenue function and parameter object.");let r;try{r=m(String(n.token))}catch{throw new s("Provide a valid Hookr revenue token address.")}let i=n.params,a=o.fn;if(Object.keys(i).length!==a.inputs.length||Object.keys(i).some(e=>!a.inputs.some(u=>u.name===e)))throw new s("Provide exactly the documented Hookr revenue parameters.");let c=e=>{if(typeof e!="string"||!/^(0|[1-9][0-9]*)$/.test(e)||e.length>78||BigInt(e)>=1n<<256n)throw new s("Revenue token indices and amounts must be decimal base-unit strings.");return BigInt(e)},d=a.inputs.map(e=>{let u=i[e.name];if(e.type==="address")try{return m(String(u))}catch{throw new s("Provide a valid Hookr revenue address.")}if(e.type==="uint256[]"){if(!Array.isArray(u)||u.length>128)throw new s("Provide at most 128 Hookr revenue indices.");return u.map(c)}return c(u)});return{token:r,fn:a,values:d,operation:o}}async function g(n,t,o){let r=n.clientFor(p),i;for(let c of y){let d=c===y[0],e=await r.readContract({address:c,abi:d?x:S,functionName:"tokenizations",args:[t]});if(!e||typeof e.creator!="string"||d&&(!("createdAt"in e)||typeof e.createdAt!="bigint"||e.createdAt<0n||e.createdAt>=1n<<64n))throw new s("Hookr token provenance is unavailable.");if(m(e.creator)!==w&&(!d||"createdAt"in e&&e.createdAt>0n)){i=c;break}}if(!i)throw new s("This token has no record on a pinned Hookr tokenizer.");let a=o?m(await r.readContract({address:t,abi:b,functionName:"dropBox"})):t;if(a===w)throw new s("Hookr revenue drop box is unavailable.");return{to:a,tokenizer:i}}async function j(n,t,o){if(n.network==="testnet")throw new s("Hookr revenue actions require mainnet, chain 4663.");let{token:r,fn:i,values:a}=A(t,!1),{to:c}=await g(n,r,t.target==="drops"),d=i.inputs.findIndex(e=>e.name==="to");if(d>=0&&[w,r,c].includes(a[d]))throw new s("Choose a valid revenue claim recipient.");return{txs:[n.unsignedTx({chainId:p,to:c,value:"0",data:H({abi:[i],functionName:i.name,args:a}),description:`Hookr revenue ${t.target}.${i.name}: ${JSON.stringify(t.params)}. No token approval or principal deposit.`})],inputs:[]}}function T(n){return[{name:"hookr_revenue_read",inputSchema:{...v(!0),description:"Read a registered Hookr revenue token or its derived drop box: balance, claimable, terms and indices. Checks tokenizer provenance on chain."},execute:async t=>{let{token:o,fn:r,values:i}=A(t,!0),{to:a,tokenizer:c}=await g(n,o,t.target==="drops"),d=await n.clientFor(p).readContract({address:a,abi:[r],functionName:r.name,args:i});return{chainId:p,token:o,tokenizer:c,contract:a,function:r.name,result:JSON.parse(JSON.stringify(d,(e,u)=>typeof u=="bigint"?u.toString():u))}}},{name:"hookr_revenue_action",inputSchema:{...v(!1),description:"Preview holder income/drop claims or permissionless sync/syncRange/syncSome on a registered Hookr revenue token. No approvals; local human confirmation required. Claims and syncs are separate actions."},execute:async(t,o)=>{let{txs:r}=await j(n,t,o),i=await n.preview(r,o);return{txs:r,preview:i,summary:`Hookr revenue ${t.function}; verify receipt and holder balances after confirmation.`}}}]}export{y as a,j as b,T as c};
1
+ import{a as k}from"./66F5ZH34.js";import{c as l}from"./NWNYJ26T.js";import{a as p}from"./FWD4L3CJ.js";import{a as s}from"./XSD5NL7J.js";import{encodeFunctionData as H,getAddress as m,parseAbi as f,zeroAddress as w}from"viem";var x=f(["function tokenizations(address token) view returns ((address creator,address forwarder,bytes32 marketFamilyId,uint64 createdAt))"]),S=f(["function tokenizations(address token) view returns ((address creator,uint8 way,address forwarder,address adapter,address door,bytes32 familyId,bytes32 marketFamilyId,uint64 unlockBlock,uint16 legBps))"]),b=f(["function name() view returns (string)","function symbol() view returns (string)","function decimals() view returns (uint8)","function balanceOf(address account) view returns (uint256)","function totalSupply() view returns (uint256)","function assetCount() view returns (uint256)","function claimable(address account,uint256 asset) view returns (uint256)","function streamSeconds() view returns (uint32)","function tipBps() view returns (uint16)","function doorCount() view returns (uint256)","function dropBox() view returns (address)","function bridge() view returns (address)","function claim(uint256 asset,address to) returns (uint256 amount)","function claimAll(address to) returns (uint256[] amounts)","function sync() returns (uint256 tip)","function syncRange(uint256 start,uint256 count) returns (uint256 tip)","function syncSome(uint256[] doorIds) returns (uint256 tip)"]),C=f(["function dropCount() view returns (uint256)","function claimable(uint256 dropId,address holder) view returns (uint256)","function claim(uint256[] dropIds,address to) returns (uint256[] amounts)"]),y=["0x522723A7a09684515881568Ab8247f3846D66F43","0xfb3c1501c727f30883cd7B36Ec380381af7412Ef"].map(m),I={token:b,drops:C};function O(n){return{type:"object",properties:Object.fromEntries(n.inputs.map(t=>[t.name,t.type==="address"?l:t.type==="uint256[]"?{type:"array",items:k(),maxItems:128}:k()])),required:n.inputs.map(t=>t.name),additionalProperties:!1}}function h(n){return Object.entries(I).flatMap(([t,o])=>o.filter(r=>r.stateMutability==="view"===n).map(r=>({target:t,fn:r})))}function v(n){return{type:"object",oneOf:h(n).map(({target:t,fn:o})=>({type:"object",properties:{token:l,target:{const:t},function:{const:o.name},params:O(o)},required:["token","target","function","params"],additionalProperties:!1}))}}function A(n,t){if(Object.keys(n).length!==4||Object.keys(n).some(e=>!["token","target","function","params"].includes(e)))throw new s("Provide token, target, function and params for the Hookr revenue operation.");let o=h(t).find(e=>e.target===n.target&&e.fn.name===n.function);if(!o||!n.params||typeof n.params!="object"||Array.isArray(n.params))throw new s("Choose a documented Hookr revenue function and parameter object.");let r;try{r=m(String(n.token))}catch{throw new s("Provide a valid Hookr revenue token address.")}let i=n.params,a=o.fn;if(Object.keys(i).length!==a.inputs.length||Object.keys(i).some(e=>!a.inputs.some(u=>u.name===e)))throw new s("Provide exactly the documented Hookr revenue parameters.");let c=e=>{if(typeof e!="string"||!/^(0|[1-9][0-9]*)$/.test(e)||e.length>78||BigInt(e)>=1n<<256n)throw new s("Revenue token indices and amounts must be decimal base-unit strings.");return BigInt(e)},d=a.inputs.map(e=>{let u=i[e.name];if(e.type==="address")try{return m(String(u))}catch{throw new s("Provide a valid Hookr revenue address.")}if(e.type==="uint256[]"){if(!Array.isArray(u)||u.length>128)throw new s("Provide at most 128 Hookr revenue indices.");return u.map(c)}return c(u)});return{token:r,fn:a,values:d,operation:o}}async function g(n,t,o){let r=n.clientFor(p),i;for(let c of y){let d=c===y[0],e=await r.readContract({address:c,abi:d?x:S,functionName:"tokenizations",args:[t]});if(!e||typeof e.creator!="string"||d&&(!("createdAt"in e)||typeof e.createdAt!="bigint"||e.createdAt<0n||e.createdAt>=1n<<64n))throw new s("Hookr token provenance is unavailable.");if(m(e.creator)!==w&&(!d||"createdAt"in e&&e.createdAt>0n)){i=c;break}}if(!i)throw new s("This token has no record on a pinned Hookr tokenizer.");let a=o?m(await r.readContract({address:t,abi:b,functionName:"dropBox"})):t;if(a===w)throw new s("Hookr revenue drop box is unavailable.");return{to:a,tokenizer:i}}async function j(n,t,o){if(n.network==="testnet")throw new s("Hookr revenue actions require mainnet, chain 4663.");let{token:r,fn:i,values:a}=A(t,!1),{to:c}=await g(n,r,t.target==="drops"),d=i.inputs.findIndex(e=>e.name==="to");if(d>=0&&[w,r,c].includes(a[d]))throw new s("Choose a valid revenue claim recipient.");return{txs:[n.unsignedTx({chainId:p,to:c,value:"0",data:H({abi:[i],functionName:i.name,args:a}),description:`Hookr revenue ${t.target}.${i.name}: ${JSON.stringify(t.params)}. No token approval or principal deposit.`})],inputs:[]}}function T(n){return[{name:"hookr_revenue_read",inputSchema:{...v(!0),description:"Read a registered Hookr revenue token or its derived drop box: balance, claimable, terms and indices. Checks tokenizer provenance on chain."},execute:async t=>{let{token:o,fn:r,values:i}=A(t,!0),{to:a,tokenizer:c}=await g(n,o,t.target==="drops"),d=await n.clientFor(p).readContract({address:a,abi:[r],functionName:r.name,args:i});return{chainId:p,token:o,tokenizer:c,contract:a,function:r.name,result:JSON.parse(JSON.stringify(d,(e,u)=>typeof u=="bigint"?u.toString():u))}}},{name:"hookr_revenue_action",inputSchema:{...v(!1),description:"Preview holder income/drop claims or permissionless sync/syncRange/syncSome on a registered Hookr revenue token. No approvals; local human confirmation required. Claims and syncs are separate actions."},execute:async(t,o)=>{let{txs:r}=await j(n,t,o),i=await n.preview(r,o);return{txs:r,preview:i,summary:`Hookr revenue ${t.function}; verify receipt and holder balances after confirmation.`}}}]}export{y as a,j as b,T as c};
@@ -1 +1 @@
1
- import{a as d}from"./UP7FBDMJ.js";import{a as o}from"./XSD5NL7J.js";import{getAddress as w,isAddress as c,zeroAddress as g}from"viem";var u="^0x[0-9a-fA-F]{40}$",m=new RegExp(u),y={type:"string",pattern:u},R="Provide a valid contract or wallet address.";function a(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function h(n,t){if(!a(n))throw new o(t);return n}function A(n,t){return n.toLowerCase()===t.toLowerCase()}function S(n,t){return typeof n=="string"&&typeof t=="string"&&A(n,t)}function s(n,t,r){if(typeof n!="string")throw new o(t);if(!c(n,{strict:!1}))throw new o(r);return n}function E(n,t,r=t){return w(s(n,t,r))}function D(n,t,r=t){return s(n,t,r).toLowerCase()}function T(n,t,r=t){return s(n,t,r)}function L(n,t){if(n.toLowerCase()===g)throw new o(t);return n}function B(n,t){if(typeof n!="bigint"||n<0n||n>=1n<<256n)throw new o(t);return n}function C(n,t,r={}){let{notString:i,bits:f=256,positive:p=!1}=r;if(i!==void 0&&typeof n!="string")throw new o(i);let e=d(n);if(e>=1n<<BigInt(f)||p&&e===0n)throw new o(t);return e}export{u as a,m as b,y as c,R as d,a as e,h as f,A as g,S as h,E as i,D as j,T as k,L as l,B as m,C as n};
1
+ import{b as d}from"./IX3GZMTM.js";import{a as o}from"./XSD5NL7J.js";import{getAddress as w,isAddress as c,zeroAddress as g}from"viem";var u="^0x[0-9a-fA-F]{40}$",m=new RegExp(u),y={type:"string",pattern:u},R="Provide a valid contract or wallet address.";function a(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function h(n,t){if(!a(n))throw new o(t);return n}function A(n,t){return n.toLowerCase()===t.toLowerCase()}function S(n,t){return typeof n=="string"&&typeof t=="string"&&A(n,t)}function s(n,t,r){if(typeof n!="string")throw new o(t);if(!c(n,{strict:!1}))throw new o(r);return n}function E(n,t,r=t){return w(s(n,t,r))}function D(n,t,r=t){return s(n,t,r).toLowerCase()}function T(n,t,r=t){return s(n,t,r)}function L(n,t){if(n.toLowerCase()===g)throw new o(t);return n}function B(n,t){if(typeof n!="bigint"||n<0n||n>=1n<<256n)throw new o(t);return n}function C(n,t,r={}){let{notString:i,bits:f=256,positive:p=!1}=r;if(i!==void 0&&typeof n!="string")throw new o(i);let e=d(n);if(e>=1n<<BigInt(f)||p&&e===0n)throw new o(t);return e}export{u as a,m as b,y as c,R as d,a as e,h as f,A as g,S as h,E as i,D as j,T as k,L as l,B as m,C as n};
@@ -1 +1 @@
1
- import{e as P,f as o,g as S,h as f,i as g,k as h,l as q,o as I,r as R}from"./QVYCJ6WV.js";import{h as O}from"./5KUWLUPM.js";import{isDeepStrictEqual as D}from"node:util";import{pad as F,zeroHash as w}from"viem";var L=["order","cancel","withdraw","convert","signer","referral"],A={nonce:"uint64",signedAt:"uint64"},M={sender:"address",subaccount:"bytes32"},_=["type","side","onchainId","quantity","price","timeInForce","postOnly","reduceOnly","close","clientOrderId","stopPrice","stopType","expiresAt","groupId","groupContingencyType"],j={order:_,cancel:["all","orderIds","clientOrderIds"],withdraw:["token","tokenId","amount"],convert:["fromToken","toToken","amount"],signer:["mode","signer"],referral:["mode","code","cursor","limit"]};function G(n){let e=n.replace(/^meridian_perps_/,"");return L.includes(e)||o("Unsupported Meridian perps action."),e}function $(n,e){let d=[...j[n],"subaccount","subaccountId","continuation","signature"];Object.keys(e).some(s=>!d.includes(s))&&o("Unsupported Meridian perps arguments; use the tool schema."),q(e.subaccount),n!=="referral"&&!(n==="signer"&&e.mode==="extend")&&h(e.subaccountId)}function v(n,e=!1){(!Array.isArray(n)||n.length<1||n.length>200)&&o("Provide between 1 and 200 unique order identifiers.");let d=n.map(s=>e?C(s):h(s));return new Set(d).size!==d.length&&o("Do not repeat Meridian order identifiers."),d}function C(n){return(typeof n!="string"||!(/^[a-z0-9]{1,32}$/i.test(n)||/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(n)))&&o("Provide an alphanumeric clientOrderId of at most 32 characters or a UUID."),n}function b(n,e){return(typeof n!="number"||!Number.isSafeInteger(n)||n<0||n>e)&&o("Provide a valid integer Meridian order option."),n}function x(n,e=!1){return n===void 0?e:(typeof n!="boolean"&&o("Provide Meridian order flags as booleans."),n)}function z(n,e,d,s,c){$(n,e),f(s,"the signing nonce",!1,64),b(c,Number.MAX_SAFE_INTEGER);let m=q(e.subaccount),t={sender:d,subaccount:m,nonce:s,signedAt:c};if(n==="order"){e.type!=="MARKET"&&e.type!=="LIMIT"&&o("Choose a MARKET or LIMIT Meridian order.");let i=f(e.quantity,"the D9 order quantity",!1,128),u=x(e.reduceOnly),a=x(e.close);(a?i!=="0"||!u:i==="0")&&o('Close orders require quantity "0" and reduceOnly true; other orders require a positive quantity.'),a&&e.type!=="MARKET"&&o("A full Meridian position close requires a MARKET order.");let T=b(e.onchainId,4294967295);T||o("Choose a nonzero Meridian product onchainId.");let k=b(e.side,1);Object.assign(t,{type:e.type,quantity:I(i),reduceOnly:u,close:a,onchainId:T,side:k,engineType:0});let E=e.type==="LIMIT"?f(e.price,"the D9 limit price",!0,128):"0";if(e.type==="LIMIT"){["GTD","IOC","FOK"].includes(String(e.timeInForce))||o("Choose GTD, IOC or FOK for a limit order.");let p=x(e.postOnly);p&&e.timeInForce!=="GTD"&&o("Post-only requires GTD."),Object.assign(t,{price:I(E),timeInForce:e.timeInForce,postOnly:p})}else["price","timeInForce","postOnly"].some(p=>e[p]!==void 0)&&o("Market orders omit price, timeInForce and postOnly.");if(e.clientOrderId!==void 0&&(t.clientOrderId=C(e.clientOrderId)),(e.stopPrice!==void 0||e.stopType!==void 0)&&(t.stopPrice=I(f(e.stopPrice,"the D9 stop price",!0,128)),t.stopType=b(e.stopType,1)),e.expiresAt!==void 0){let p=Number(f(e.expiresAt,"the order expiry",!0,64));(!Number.isSafeInteger(p)||p<=c||p>c+6652800)&&o("Order expiry must be in the next 77 days."),t.expiresAt=p}return(e.groupId!==void 0||e.groupContingencyType!==void 0)&&(t.groupId=h(e.groupId),t.groupContingencyType=b(e.groupContingencyType,1)),{path:"/v1/order",method:"POST",data:t,primaryType:"TradeOrder",fields:{...M,quantity:"uint128",price:"uint128",reduceOnly:"bool",side:"uint8",engineType:"uint8",productId:"uint32",...A},message:{sender:d,subaccount:m,quantity:i,price:E,reduceOnly:u,side:k,engineType:0,productId:T,nonce:s,signedAt:c}}}if(n==="cancel"){delete t.signedAt;let i=x(e.all);return i&&(e.orderIds!==void 0||e.clientOrderIds!==void 0)&&o("Cancel-all omits order ID arrays."),i||(e.orderIds!==void 0&&(t.orderIds=v(e.orderIds)),e.clientOrderIds!==void 0&&(t.clientOrderIds=v(e.clientOrderIds,!0)),((t.orderIds??[]).length+(t.clientOrderIds??[]).length>200||!t.orderIds&&!t.clientOrderIds)&&o("Target between 1 and 200 order IDs, or choose all.")),{path:`/v1/order/${i?"cancel-all":"cancel"}`,method:"POST",data:t,primaryType:"CancelOrder",fields:{...M,nonce:"uint64"},message:{sender:d,subaccount:m,nonce:s}}}if(n==="withdraw"){let i=g(e.token),u=f(e.amount,"the D9 withdrawal amount",!0),a=F(d);return{path:`/v1/token/${h(e.tokenId)}/withdraw`,method:"POST",data:{account:d,subaccount:m,token:i,amount:I(u),lzDestinationAddress:a,lzDestinationEid:0,nonce:s,signedAt:c},primaryType:"InitiateWithdraw",fields:{account:"address",subaccount:"bytes32",token:"address",amount:"uint256",...A,destinationAddress:"bytes32",destinationEndpointId:"uint32"},message:{account:d,subaccount:m,token:i,amount:u,nonce:s,signedAt:c,destinationAddress:a,destinationEndpointId:0}}}if(n==="convert"){let i=g(e.fromToken),u=g(e.toToken);O(i,u)&&o("Choose two different compatible quote-token pools.");let a=f(e.amount,"the D9 conversion amount",!0,128);return Object.assign(t,{fromToken:i,toToken:u,amount:I(a)}),{path:"/v1/token/convert",method:"POST",data:t,primaryType:"ConvertToken",fields:{...M,fromToken:"address",toToken:"address",amount:"uint128",...A},message:{...t,amount:a}}}if(n==="signer"){["revoke","refresh","extend"].includes(String(e.mode))||o("Choose revoke, refresh or extend. Linking a new signer requires two local signatures and is not available in Oak.");let i=e.mode,u=i==="extend"?d:g(e.signer);i==="extend"&&e.signer!==void 0&&!O(e.signer,d)&&o("Only this local signer can extend itself.");let a=i==="revoke"?"RevokeLinkedSigner":i==="refresh"?"RefreshLinkedSigner":"ExtendLinkedSigner",T={sender:d,...i!=="extend"?{signer:u}:{},...i==="revoke"?{subaccount:m}:{},nonce:s,signedAt:c},k={sender:"address",...i!=="extend"?{signer:"address"}:{},...i==="revoke"?{subaccount:"bytes32"}:{},...A};return{path:`/v1/linked-signer/${i}`,method:i==="revoke"?"DELETE":"POST",data:i==="extend"?{sender:d,nonce:s,signedAt:c}:{...t,subaccountId:h(e.subaccountId),signer:u},primaryType:a,fields:k,message:T}}let r=e.mode;["activate","claim","summary","history"].includes(String(r))||o("Choose activate, claim, summary or history for Meridian referrals."),(r==="claim"?typeof e.code!="string"||!/^[A-Z0-9]{12}$/.test(e.code):e.code!==void 0)&&o("A referral claim needs a 12-character uppercase alphanumeric code; other referral modes omit code.");let l=r==="activate"?0:r==="claim"?1:2,y={sender:d,intent:l,signedAt:c};return{path:r==="history"?"/v1/referral":`/v1/referral/${r}`,method:l===2?"GET":"POST",data:r==="claim"?{...y,code:e.code}:y,primaryType:"EIP712Auth",fields:{sender:"address",intent:"uint8",signedAt:"uint64"},message:y}}function K(n,e){return{domain:{...P},primaryType:n.primaryType,types:R(e,n.primaryType,n.fields),message:n.message}}function H(n,e,d,s,c,m,t){let r=S(c);(m||r.stage!=="perps_sign"||!O(r.wallet,d)||r.chainId!==4663||typeof r.requestId!="string"||!r.requestId||typeof r.expiresAt!="number"||r.expiresAt<=t||r.expiresAt>t+120||typeof r.signedAt!="number"||r.signedAt>t+10||r.signedAt<t-120)&&o("Meridian perps signing round is invalid or expired.");let l=z(G(n),e,d,f(r.nonce,"the nonce",!1,64),r.signedAt),y=K(l,S(r.signatureTypes));(!D(r.request,y)||!D(s,[{kind:"typedData",request:y}]))&&o("Meridian perps signing terms differ from the local request."),(!D(r.data,l.data)||r.path!==l.path||r.method!==l.method)&&o("Meridian perps API terms differ from the local request.")}var W=w;export{L as a,j as b,G as c,$ as d,z as e,K as f,H as g,W as h};
1
+ import{e as P,f as o,g as S,h as f,i as g,k as h,l as q,o as I,r as R}from"./46KWRAYK.js";import{h as O}from"./NWNYJ26T.js";import{isDeepStrictEqual as D}from"node:util";import{pad as F,zeroHash as w}from"viem";var L=["order","cancel","withdraw","convert","signer","referral"],A={nonce:"uint64",signedAt:"uint64"},M={sender:"address",subaccount:"bytes32"},_=["type","side","onchainId","quantity","price","timeInForce","postOnly","reduceOnly","close","clientOrderId","stopPrice","stopType","expiresAt","groupId","groupContingencyType"],j={order:_,cancel:["all","orderIds","clientOrderIds"],withdraw:["token","tokenId","amount"],convert:["fromToken","toToken","amount"],signer:["mode","signer"],referral:["mode","code","cursor","limit"]};function G(n){let e=n.replace(/^meridian_perps_/,"");return L.includes(e)||o("Unsupported Meridian perps action."),e}function $(n,e){let d=[...j[n],"subaccount","subaccountId","continuation","signature"];Object.keys(e).some(s=>!d.includes(s))&&o("Unsupported Meridian perps arguments; use the tool schema."),q(e.subaccount),n!=="referral"&&!(n==="signer"&&e.mode==="extend")&&h(e.subaccountId)}function v(n,e=!1){(!Array.isArray(n)||n.length<1||n.length>200)&&o("Provide between 1 and 200 unique order identifiers.");let d=n.map(s=>e?C(s):h(s));return new Set(d).size!==d.length&&o("Do not repeat Meridian order identifiers."),d}function C(n){return(typeof n!="string"||!(/^[a-z0-9]{1,32}$/i.test(n)||/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(n)))&&o("Provide an alphanumeric clientOrderId of at most 32 characters or a UUID."),n}function b(n,e){return(typeof n!="number"||!Number.isSafeInteger(n)||n<0||n>e)&&o("Provide a valid integer Meridian order option."),n}function x(n,e=!1){return n===void 0?e:(typeof n!="boolean"&&o("Provide Meridian order flags as booleans."),n)}function z(n,e,d,s,c){$(n,e),f(s,"the signing nonce",!1,64),b(c,Number.MAX_SAFE_INTEGER);let m=q(e.subaccount),t={sender:d,subaccount:m,nonce:s,signedAt:c};if(n==="order"){e.type!=="MARKET"&&e.type!=="LIMIT"&&o("Choose a MARKET or LIMIT Meridian order.");let i=f(e.quantity,"the D9 order quantity",!1,128),u=x(e.reduceOnly),a=x(e.close);(a?i!=="0"||!u:i==="0")&&o('Close orders require quantity "0" and reduceOnly true; other orders require a positive quantity.'),a&&e.type!=="MARKET"&&o("A full Meridian position close requires a MARKET order.");let T=b(e.onchainId,4294967295);T||o("Choose a nonzero Meridian product onchainId.");let k=b(e.side,1);Object.assign(t,{type:e.type,quantity:I(i),reduceOnly:u,close:a,onchainId:T,side:k,engineType:0});let E=e.type==="LIMIT"?f(e.price,"the D9 limit price",!0,128):"0";if(e.type==="LIMIT"){["GTD","IOC","FOK"].includes(String(e.timeInForce))||o("Choose GTD, IOC or FOK for a limit order.");let p=x(e.postOnly);p&&e.timeInForce!=="GTD"&&o("Post-only requires GTD."),Object.assign(t,{price:I(E),timeInForce:e.timeInForce,postOnly:p})}else["price","timeInForce","postOnly"].some(p=>e[p]!==void 0)&&o("Market orders omit price, timeInForce and postOnly.");if(e.clientOrderId!==void 0&&(t.clientOrderId=C(e.clientOrderId)),(e.stopPrice!==void 0||e.stopType!==void 0)&&(t.stopPrice=I(f(e.stopPrice,"the D9 stop price",!0,128)),t.stopType=b(e.stopType,1)),e.expiresAt!==void 0){let p=Number(f(e.expiresAt,"the order expiry",!0,64));(!Number.isSafeInteger(p)||p<=c||p>c+6652800)&&o("Order expiry must be in the next 77 days."),t.expiresAt=p}return(e.groupId!==void 0||e.groupContingencyType!==void 0)&&(t.groupId=h(e.groupId),t.groupContingencyType=b(e.groupContingencyType,1)),{path:"/v1/order",method:"POST",data:t,primaryType:"TradeOrder",fields:{...M,quantity:"uint128",price:"uint128",reduceOnly:"bool",side:"uint8",engineType:"uint8",productId:"uint32",...A},message:{sender:d,subaccount:m,quantity:i,price:E,reduceOnly:u,side:k,engineType:0,productId:T,nonce:s,signedAt:c}}}if(n==="cancel"){delete t.signedAt;let i=x(e.all);return i&&(e.orderIds!==void 0||e.clientOrderIds!==void 0)&&o("Cancel-all omits order ID arrays."),i||(e.orderIds!==void 0&&(t.orderIds=v(e.orderIds)),e.clientOrderIds!==void 0&&(t.clientOrderIds=v(e.clientOrderIds,!0)),((t.orderIds??[]).length+(t.clientOrderIds??[]).length>200||!t.orderIds&&!t.clientOrderIds)&&o("Target between 1 and 200 order IDs, or choose all.")),{path:`/v1/order/${i?"cancel-all":"cancel"}`,method:"POST",data:t,primaryType:"CancelOrder",fields:{...M,nonce:"uint64"},message:{sender:d,subaccount:m,nonce:s}}}if(n==="withdraw"){let i=g(e.token),u=f(e.amount,"the D9 withdrawal amount",!0),a=F(d);return{path:`/v1/token/${h(e.tokenId)}/withdraw`,method:"POST",data:{account:d,subaccount:m,token:i,amount:I(u),lzDestinationAddress:a,lzDestinationEid:0,nonce:s,signedAt:c},primaryType:"InitiateWithdraw",fields:{account:"address",subaccount:"bytes32",token:"address",amount:"uint256",...A,destinationAddress:"bytes32",destinationEndpointId:"uint32"},message:{account:d,subaccount:m,token:i,amount:u,nonce:s,signedAt:c,destinationAddress:a,destinationEndpointId:0}}}if(n==="convert"){let i=g(e.fromToken),u=g(e.toToken);O(i,u)&&o("Choose two different compatible quote-token pools.");let a=f(e.amount,"the D9 conversion amount",!0,128);return Object.assign(t,{fromToken:i,toToken:u,amount:I(a)}),{path:"/v1/token/convert",method:"POST",data:t,primaryType:"ConvertToken",fields:{...M,fromToken:"address",toToken:"address",amount:"uint128",...A},message:{...t,amount:a}}}if(n==="signer"){["revoke","refresh","extend"].includes(String(e.mode))||o("Choose revoke, refresh or extend. Linking a new signer requires two local signatures and is not available in Oak.");let i=e.mode,u=i==="extend"?d:g(e.signer);i==="extend"&&e.signer!==void 0&&!O(e.signer,d)&&o("Only this local signer can extend itself.");let a=i==="revoke"?"RevokeLinkedSigner":i==="refresh"?"RefreshLinkedSigner":"ExtendLinkedSigner",T={sender:d,...i!=="extend"?{signer:u}:{},...i==="revoke"?{subaccount:m}:{},nonce:s,signedAt:c},k={sender:"address",...i!=="extend"?{signer:"address"}:{},...i==="revoke"?{subaccount:"bytes32"}:{},...A};return{path:`/v1/linked-signer/${i}`,method:i==="revoke"?"DELETE":"POST",data:i==="extend"?{sender:d,nonce:s,signedAt:c}:{...t,subaccountId:h(e.subaccountId),signer:u},primaryType:a,fields:k,message:T}}let r=e.mode;["activate","claim","summary","history"].includes(String(r))||o("Choose activate, claim, summary or history for Meridian referrals."),(r==="claim"?typeof e.code!="string"||!/^[A-Z0-9]{12}$/.test(e.code):e.code!==void 0)&&o("A referral claim needs a 12-character uppercase alphanumeric code; other referral modes omit code.");let l=r==="activate"?0:r==="claim"?1:2,y={sender:d,intent:l,signedAt:c};return{path:r==="history"?"/v1/referral":`/v1/referral/${r}`,method:l===2?"GET":"POST",data:r==="claim"?{...y,code:e.code}:y,primaryType:"EIP712Auth",fields:{sender:"address",intent:"uint8",signedAt:"uint64"},message:y}}function K(n,e){return{domain:{...P},primaryType:n.primaryType,types:R(e,n.primaryType,n.fields),message:n.message}}function H(n,e,d,s,c,m,t){let r=S(c);(m||r.stage!=="perps_sign"||!O(r.wallet,d)||r.chainId!==4663||typeof r.requestId!="string"||!r.requestId||typeof r.expiresAt!="number"||r.expiresAt<=t||r.expiresAt>t+120||typeof r.signedAt!="number"||r.signedAt>t+10||r.signedAt<t-120)&&o("Meridian perps signing round is invalid or expired.");let l=z(G(n),e,d,f(r.nonce,"the nonce",!1,64),r.signedAt),y=K(l,S(r.signatureTypes));(!D(r.request,y)||!D(s,[{kind:"typedData",request:y}]))&&o("Meridian perps signing terms differ from the local request."),(!D(r.data,l.data)||r.path!==l.path||r.method!==l.method)&&o("Meridian perps API terms differ from the local request.")}var W=w;export{L as a,j as b,G as c,$ as d,z as e,K as f,H as g,W as h};
@@ -1 +1 @@
1
- import{f as l,h as x,i as h}from"./6PY3IRDS.js";import{g}from"./5KUWLUPM.js";import{a as r}from"./XSD5NL7J.js";import{encodeFunctionData as y,erc20Abi as O,getAddress as f,parseAbi as R}from"viem";var P=[{chainId:1,vault:"0x57b68c4ea221ee8da6eb14ebdfccee5177567771",asset:"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",gateway:"0xed8a2a23bf9d6818651527daaf3bf4ffeb53945f"},{chainId:42161,vault:"0xc7273772b87860097373d91b3880fd4cc61fba2d",asset:"0x82af49447d8a07e3bd95bd0d56f35241523fbab1",gateway:"0x67defe8d90c8cd013fd527669e76e0be420f1208"}].map(t=>({chainId:t.chainId,vault:f(t.vault),asset:f(t.asset),gateway:f(t.gateway)})),T=R(["function balanceOf(address) view returns (uint256)","function asset() view returns (address)","function yieldPool() view returns (address)","function maxWithdraw(address) view returns (uint256)","function convertToAssets(uint256) view returns (uint256)","function previewRedeem(uint256) view returns (uint256)","function previewWithdraw(uint256) view returns (uint256)","function redeem(uint256,address,address) returns (uint256)","function withdraw(uint256,address,address) returns (uint256)"]),$=R(["function redeem(address,uint256,address,uint256) returns (uint256)","function withdraw(address,uint256,address,uint256) returns (uint256)"]),I={type:"string",pattern:"^[1-9][0-9]*$"},A={type:"integer",enum:[1,42161]};function S(t){let o=P.find(i=>i.chainId===x(t));if(!o)throw new r("Relay legacy vault exits support Ethereum (1) and Arbitrum (42161).");return o}function b(t){let o=h(t);if(o==="0")throw new r("Provide a positive Relay vault amount or limit.");return o}function E(t,o){let i=S(t.chainId),s=f(l(o));if(Object.keys(t).some(c=>!["chainId","mode","amount","native","minAssetsOut","maxSharesIn"].includes(c)))throw new r("Provide only the documented Relay vault exit arguments.");if(t.mode!=="redeem"&&t.mode!=="withdraw")throw new r("Choose redeem (shares) or withdraw (WETH amount).");if(t.native!==void 0&&typeof t.native!="boolean")throw new r("Provide native as a boolean.");let e=b(t.amount),n=t.native===!0,a=t.mode==="redeem";if(!a&&!n)throw new r("Direct WETH withdrawals cannot enforce maxSharesIn on-chain. Use native withdraw or redeem a fixed number of shares.");if(t.minAssetsOut!==void 0&&(!n||!a)||t.maxSharesIn!==void 0&&a)throw new r("minAssetsOut applies only to native redeem; maxSharesIn applies only to withdraw.");let d=n&&a?b(t.minAssetsOut):void 0,u=a?e:b(t.maxSharesIn),w=(c,v,p)=>({to:c,data:v,chainId:i.chainId,value:"0",description:p}),m=[];return n?(m.push(w(i.vault,y({abi:O,functionName:"approve",args:[i.gateway,BigInt(u)]}),`Approve exactly ${u} WETH-REL share base units for the Relay native gateway.`)),m.push(w(i.gateway,y({abi:$,functionName:t.mode,args:[i.vault,BigInt(e),s,BigInt(a?d:u)]}),`Relay legacy vault ${t.mode} to native ETH for ${s}.`))):m.push(w(i.vault,y({abi:T,functionName:t.mode,args:[BigInt(e),s,s]}),`Relay legacy vault ${t.mode} to WETH for ${s}.`)),{pin:i,txs:m,wallet:s,redeem:a,native:n,amount:e,maxSharesIn:u,minAssetsOut:d}}function C(t,o,i){let s=E(o,i).txs;if(t.length!==s.length||t.some((e,n)=>e.chainId!==s[n].chainId||l(e.to)!==l(s[n].to)||e.value!=="0"||!g(e.data,s[n].data)))throw new r("Relay vault transactions differ from the requested exit.")}var H=t=>{async function o(i,s){let e=S(i),n;try{n=t.clientFor(e.chainId)}catch(c){throw/No RPC URL configured for chain/.test(t.plainError(c))?new r(`Relay legacy vault reads and exits on chain ${e.chainId} need an RPC. Ask the operator to configure OAK_RPC_URL_${e.chainId} on the server. No vault balances were checked.`):c}if(await n.getChainId()!==e.chainId)throw new r("The RPC chain does not match the Relay vault chain.");let a=(c,v,p=[])=>n.readContract({address:c,abi:T,functionName:v,args:p});if(l(await a(e.vault,"asset"))!==l(e.asset))throw new r("Relay vault asset does not match the pinned WETH.");let d=h(String(await a(e.vault,"balanceOf",[s]))),u=f(l(await a(e.vault,"yieldPool"))),w=h(String(await a(e.vault,"convertToAssets",[BigInt(d)]))),m=h(String(await a(u,"maxWithdraw",[e.vault])));return{pin:e,shares:d,assets:w,liquidAssets:m,read:a}}return{tools:[{name:"relay_vault_status",inputSchema:{type:"object",description:"Read legacy vault shares and shared liquidity. Requires server OAK_RPC_URL_1 or OAK_RPC_URL_42161 for the selected chain; no API key. New deposits are unsupported.",additionalProperties:!1,required:["chainId"],properties:{chainId:A}},execute:async(i,s)=>{if(Object.keys(i).some(u=>u!=="chainId"))throw new r("Provide only the Relay vault chainId.");let{pin:e,shares:n,assets:a,liquidAssets:d}=await o(i.chainId,s);return{chainId:e.chainId,vault:e.vault,shares:{token:{address:e.vault,chainId:e.chainId,symbol:"WETH-REL",decimals:18},amount:n},assets:{token:{address:e.asset,chainId:e.chainId,symbol:"WETH",decimals:18},amount:a},liquidAssets:d,summary:"Relay legacy vault wind-down: new deposits are unsupported. Available yield-pool liquidity is shared by all LPs and may change. Withdraw with relay_vault_withdraw; gas is paid in ETH on the vault chain."}}},{name:"relay_vault_withdraw",inputSchema:{type:"object",additionalProperties:!1,required:["chainId","mode","amount"],properties:{chainId:A,mode:{type:"string",enum:["redeem","withdraw"]},amount:I,native:{type:"boolean"},minAssetsOut:I,maxSharesIn:I}},execute:async(i,s)=>{let e=E(i,s),n=await o(i.chainId,s),a=e.redeem?e.amount:h(String(await n.read(e.pin.vault,"previewWithdraw",[BigInt(e.amount)]))),d=e.redeem?h(String(await n.read(e.pin.vault,"previewRedeem",[BigInt(e.amount)]))):e.amount;if(BigInt(a)>BigInt(n.shares)||BigInt(a)>BigInt(e.maxSharesIn))throw new r("Relay vault exit exceeds your shares or maxSharesIn.");if(BigInt(d)>BigInt(n.liquidAssets))throw new r("Relay vault liquidity is insufficient. Withdraw less or retry when liquidity returns.");if(e.minAssetsOut!==void 0&&BigInt(d)<BigInt(e.minAssetsOut))throw new r("Relay vault output is below minAssetsOut.");let u=await t.preview(e.txs,s);return{txs:e.txs,preview:u,chainId:e.pin.chainId,expectedAssets:d,expectedShares:a,summary:`Relay legacy vault exit on chain ${e.pin.chainId}: ${a} share base units for about ${d} ${e.native?"ETH":"WETH"} base units (18 decimals), to ${e.wallet}. ${e.minAssetsOut?`Gateway minimum ${e.minAssetsOut}.`:e.redeem?"Direct ERC-4626 redeem has no calldata minimum output.":`Gateway maximum input ${e.maxSharesIn} share base units.`} Review the local preview and confirm before signing. No destination bridge or future yield is promised.`}}}]}};export{P as a,E as b,C as c,H as d};
1
+ import{f as l,h as x,i as h}from"./64GOINYS.js";import{g}from"./NWNYJ26T.js";import{a as r}from"./XSD5NL7J.js";import{encodeFunctionData as y,erc20Abi as O,getAddress as f,parseAbi as R}from"viem";var P=[{chainId:1,vault:"0x57b68c4ea221ee8da6eb14ebdfccee5177567771",asset:"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",gateway:"0xed8a2a23bf9d6818651527daaf3bf4ffeb53945f"},{chainId:42161,vault:"0xc7273772b87860097373d91b3880fd4cc61fba2d",asset:"0x82af49447d8a07e3bd95bd0d56f35241523fbab1",gateway:"0x67defe8d90c8cd013fd527669e76e0be420f1208"}].map(t=>({chainId:t.chainId,vault:f(t.vault),asset:f(t.asset),gateway:f(t.gateway)})),T=R(["function balanceOf(address) view returns (uint256)","function asset() view returns (address)","function yieldPool() view returns (address)","function maxWithdraw(address) view returns (uint256)","function convertToAssets(uint256) view returns (uint256)","function previewRedeem(uint256) view returns (uint256)","function previewWithdraw(uint256) view returns (uint256)","function redeem(uint256,address,address) returns (uint256)","function withdraw(uint256,address,address) returns (uint256)"]),$=R(["function redeem(address,uint256,address,uint256) returns (uint256)","function withdraw(address,uint256,address,uint256) returns (uint256)"]),I={type:"string",pattern:"^[1-9][0-9]*$"},A={type:"integer",enum:[1,42161]};function S(t){let o=P.find(i=>i.chainId===x(t));if(!o)throw new r("Relay legacy vault exits support Ethereum (1) and Arbitrum (42161).");return o}function b(t){let o=h(t);if(o==="0")throw new r("Provide a positive Relay vault amount or limit.");return o}function E(t,o){let i=S(t.chainId),s=f(l(o));if(Object.keys(t).some(c=>!["chainId","mode","amount","native","minAssetsOut","maxSharesIn"].includes(c)))throw new r("Provide only the documented Relay vault exit arguments.");if(t.mode!=="redeem"&&t.mode!=="withdraw")throw new r("Choose redeem (shares) or withdraw (WETH amount).");if(t.native!==void 0&&typeof t.native!="boolean")throw new r("Provide native as a boolean.");let e=b(t.amount),n=t.native===!0,a=t.mode==="redeem";if(!a&&!n)throw new r("Direct WETH withdrawals cannot enforce maxSharesIn on-chain. Use native withdraw or redeem a fixed number of shares.");if(t.minAssetsOut!==void 0&&(!n||!a)||t.maxSharesIn!==void 0&&a)throw new r("minAssetsOut applies only to native redeem; maxSharesIn applies only to withdraw.");let d=n&&a?b(t.minAssetsOut):void 0,u=a?e:b(t.maxSharesIn),w=(c,v,p)=>({to:c,data:v,chainId:i.chainId,value:"0",description:p}),m=[];return n?(m.push(w(i.vault,y({abi:O,functionName:"approve",args:[i.gateway,BigInt(u)]}),`Approve exactly ${u} WETH-REL share base units for the Relay native gateway.`)),m.push(w(i.gateway,y({abi:$,functionName:t.mode,args:[i.vault,BigInt(e),s,BigInt(a?d:u)]}),`Relay legacy vault ${t.mode} to native ETH for ${s}.`))):m.push(w(i.vault,y({abi:T,functionName:t.mode,args:[BigInt(e),s,s]}),`Relay legacy vault ${t.mode} to WETH for ${s}.`)),{pin:i,txs:m,wallet:s,redeem:a,native:n,amount:e,maxSharesIn:u,minAssetsOut:d}}function C(t,o,i){let s=E(o,i).txs;if(t.length!==s.length||t.some((e,n)=>e.chainId!==s[n].chainId||l(e.to)!==l(s[n].to)||e.value!=="0"||!g(e.data,s[n].data)))throw new r("Relay vault transactions differ from the requested exit.")}var H=t=>{async function o(i,s){let e=S(i),n;try{n=t.clientFor(e.chainId)}catch(c){throw/No RPC URL configured for chain/.test(t.plainError(c))?new r(`Relay legacy vault reads and exits on chain ${e.chainId} need an RPC. Ask the operator to configure OAK_RPC_URL_${e.chainId} on the server. No vault balances were checked.`):c}if(await n.getChainId()!==e.chainId)throw new r("The RPC chain does not match the Relay vault chain.");let a=(c,v,p=[])=>n.readContract({address:c,abi:T,functionName:v,args:p});if(l(await a(e.vault,"asset"))!==l(e.asset))throw new r("Relay vault asset does not match the pinned WETH.");let d=h(String(await a(e.vault,"balanceOf",[s]))),u=f(l(await a(e.vault,"yieldPool"))),w=h(String(await a(e.vault,"convertToAssets",[BigInt(d)]))),m=h(String(await a(u,"maxWithdraw",[e.vault])));return{pin:e,shares:d,assets:w,liquidAssets:m,read:a}}return{tools:[{name:"relay_vault_status",inputSchema:{type:"object",description:"Read legacy vault shares and shared liquidity. Requires server OAK_RPC_URL_1 or OAK_RPC_URL_42161 for the selected chain; no API key. New deposits are unsupported.",additionalProperties:!1,required:["chainId"],properties:{chainId:A}},execute:async(i,s)=>{if(Object.keys(i).some(u=>u!=="chainId"))throw new r("Provide only the Relay vault chainId.");let{pin:e,shares:n,assets:a,liquidAssets:d}=await o(i.chainId,s);return{chainId:e.chainId,vault:e.vault,shares:{token:{address:e.vault,chainId:e.chainId,symbol:"WETH-REL",decimals:18},amount:n},assets:{token:{address:e.asset,chainId:e.chainId,symbol:"WETH",decimals:18},amount:a},liquidAssets:d,summary:"Relay legacy vault wind-down: new deposits are unsupported. Available yield-pool liquidity is shared by all LPs and may change. Withdraw with relay_vault_withdraw; gas is paid in ETH on the vault chain."}}},{name:"relay_vault_withdraw",inputSchema:{type:"object",additionalProperties:!1,required:["chainId","mode","amount"],properties:{chainId:A,mode:{type:"string",enum:["redeem","withdraw"]},amount:I,native:{type:"boolean"},minAssetsOut:I,maxSharesIn:I}},execute:async(i,s)=>{let e=E(i,s),n=await o(i.chainId,s),a=e.redeem?e.amount:h(String(await n.read(e.pin.vault,"previewWithdraw",[BigInt(e.amount)]))),d=e.redeem?h(String(await n.read(e.pin.vault,"previewRedeem",[BigInt(e.amount)]))):e.amount;if(BigInt(a)>BigInt(n.shares)||BigInt(a)>BigInt(e.maxSharesIn))throw new r("Relay vault exit exceeds your shares or maxSharesIn.");if(BigInt(d)>BigInt(n.liquidAssets))throw new r("Relay vault liquidity is insufficient. Withdraw less or retry when liquidity returns.");if(e.minAssetsOut!==void 0&&BigInt(d)<BigInt(e.minAssetsOut))throw new r("Relay vault output is below minAssetsOut.");let u=await t.preview(e.txs,s);return{txs:e.txs,preview:u,chainId:e.pin.chainId,expectedAssets:d,expectedShares:a,summary:`Relay legacy vault exit on chain ${e.pin.chainId}: ${a} share base units for about ${d} ${e.native?"ETH":"WETH"} base units (18 decimals), to ${e.wallet}. ${e.minAssetsOut?`Gateway minimum ${e.minAssetsOut}.`:e.redeem?"Direct ERC-4626 redeem has no calldata minimum output.":`Gateway maximum input ${e.maxSharesIn} share base units.`} Review the local preview and confirm before signing. No destination bridge or future yield is promised.`}}}]}};export{P as a,E as b,C as c,H as d};
@@ -1 +1 @@
1
- import{a as H}from"./E3UBHTJO.js";import{a as L}from"./KA7BPBCV.js";import{b as z}from"./Z4SRGAVL.js";import{a as P}from"./PBQSJSZO.js";import{c as D}from"./MYFAKCQI.js";import{c as y,e as b,g as A,i as N,l as _}from"./5KUWLUPM.js";import{a as E}from"./UP7FBDMJ.js";import{a as l,i as I}from"./FWD4L3CJ.js";import{a as u}from"./XSD5NL7J.js";import{a as S}from"./JXOEJPJ4.js";import{encodeFunctionData as C,parseAbi as Y,zeroAddress as v}from"viem";import{encodeAbiParameters as B,encodeFunctionData as G,keccak256 as O,parseAbi as J}from"viem";var R=I[l].merkl.distributor.address,w="Claim rewards on Merkl (Powered by Merkl \u2014 https://app.merkl.xyz)",j=`${w}. No claimable rewards on Robinhood Chain. Pending rewards must settle into a Merkle root before they can be claimed.`,T=J(["function claimed(address user,address token) view returns (uint208 amount,uint48 timestamp,bytes32 merkleRoot)","function getMerkleRoot() view returns (bytes32)","function claim(address[] users,address[] tokens,uint256[] amounts,bytes32[][] proofs)"]);function W(o){return typeof o=="string"&&/^0x[0-9a-fA-F]{64}$/.test(o)}function p(){throw new u("Merkl returned an unexpected response. Please refetch rewards.")}function x(o){typeof o!="string"&&p();let d=E(o);if(d>=1n<<256n)throw new u("The Merkl reward amount exceeds the uint256 range.");return d.toString()}function K(o){let d=[],m=new Set;for(let c of o)if((!b(c)||!b(c.chain)||!Number.isSafeInteger(c.chain.id))&&p(),c.chain.id===l){Array.isArray(c.rewards)||p();for(let r of c.rewards){if((!b(r)||typeof r.distributionLayer!="string"||!b(r.token))&&p(),r.distributionLayer!=="TREE"||(Number.isSafeInteger(r.token.chainId)||p(),r.token.chainId!==l)||(Array.isArray(r.proofs)||p(),!r.proofs.length))continue;(!r.proofs.every(W)||typeof r.token.address!="string"||typeof r.token.symbol!="string"||!r.token.symbol.trim()||typeof r.token.decimals!="number"||!Number.isInteger(r.token.decimals)||r.token.decimals<0||r.token.decimals>255)&&p(),P(r.token.address);let t=x(r.amount),e=x(r.pending);if(BigInt(t)===0n)continue;let n=r.token.address.toLowerCase();if(m.has(n))throw new u("Merkl returned duplicate token leaves. Please refetch rewards.");m.add(n),d.push({token:{address:r.token.address,chainId:l,decimals:r.token.decimals,symbol:r.token.symbol},amount:t,pending:e,proofs:r.proofs})}}return d}function Q(o,d,m){let c=O(B([{type:"address"},{type:"address"},{type:"uint256"}],[o,d.token.address,BigInt(d.amount)]));for(let r of d.proofs){let t=BigInt(c)<BigInt(r)?[c,r]:[r,c];c=O(B([{type:"bytes32"},{type:"bytes32"}],t))}if(!A(c,m))throw new u("The Merkl proof does not match the active root. Please refetch rewards.")}function F(o){if(!b(o)||Object.keys(o).length)throw new u("This Merkl tool takes no arguments and uses the connected wallet.")}async function V(o,d){let m=await Z(o,d),c=[],r=new Set;for(let t of m)if((!b(t)||!b(t.chain)||!Number.isSafeInteger(t.chain.id))&&p(),t.chain.id===l){Array.isArray(t.rewards)||p();for(let e of t.rewards){if((!b(e)||typeof e.distributionLayer!="string"||!b(e.token)||!Number.isSafeInteger(e.token.chainId))&&p(),e.token.chainId!==l)continue;(typeof e.token.address!="string"||typeof e.token.symbol!="string"||!e.token.symbol.trim()||typeof e.token.decimals!="number"||!Number.isInteger(e.token.decimals)||e.token.decimals<0||e.token.decimals>255)&&p(),P(e.token.address);let n=x(e.amount),i=x(e.pending),s=`${e.distributionLayer}:${e.token.address.toLowerCase()}`;if(r.has(s))throw new u("Merkl returned duplicate earning rows. Please refetch rewards.");r.add(s);let a={address:e.token.address,symbol:e.token.symbol,decimals:e.token.decimals,chainId:l},k="0";if(e.distributionLayer==="TREE"){let h=await o.clientFor(l).readContract({address:R,abi:T,functionName:"claimed",args:[d,a.address]});(!Array.isArray(h)||typeof h[0]!="bigint"||h[0]<0n||h[0]>=1n<<208n)&&p(),k=h[0].toString()}c.push({token:a,amount:n,pending:i,claimed:k,claimable:"0",distributionLayer:e.distributionLayer,status:e.distributionLayer!=="TREE"?"unsupported_distribution_layer":BigInt(n)>BigInt(k)?"awaiting_verified_proof":BigInt(i)>0n?"pending_settlement":"settled"})}}return{body:m,earnings:c}}async function Z(o,d){return P(d),D(o.http,`https://api.merkl.xyz/v4/users/${d}/rewards/summary?chainId=${l}`,{method:"GET",headers:{"User-Agent":"oak-core/merkl"}},m=>Array.isArray(m))}async function $(o,d,m){P(d);let c=K(m??await Z(o,d)),r=o.clientFor(l),t=[];for(let n of c){let i=await r.readContract({address:R,abi:T,functionName:"claimed",args:[d,n.token.address]});if(!Array.isArray(i)||typeof i[0]!="bigint"||i[0]<0n||i[0]>=1n<<208n)throw new u("The Merkl claimed balance could not be read. Please try again.");BigInt(n.amount)<=i[0]||t.push({...n,claimed:i[0].toString(),claimable:(BigInt(n.amount)-i[0]).toString()})}if(!t.length)return[];let e=await r.readContract({address:R,abi:T,functionName:"getMerkleRoot"});if(!W(e))throw new u("The active Merkl root could not be read. Please try again.");for(let n of t)Q(d,n,e);return t}var X=o=>{async function d(t){try{return await t()}catch(e){throw new u(o.plainError(e))}}function m(t){let e=t.amount.startsWith("-"),n=e?t.amount.slice(1):t.amount;return`${e?"-":""}${o.formatAmount(n,t.token.decimals)} ${S(t.token.symbol)} (${t.token.address}, chain ${t.token.chainId}, ${t.token.decimals} decimals)`}let c=t=>$(o,t);return{tools:[{name:"merkl_rewards",description:"Read claimable rewards (Powered by Merkl \u2014 https://app.merkl.xyz).",inputSchema:{type:"object",properties:{},additionalProperties:!1,description:"Read rewards (Powered by Merkl \u2014 https://app.merkl.xyz)."},execute:(t,e)=>d(async()=>{F(t);let{body:n,earnings:i}=await V(o,e),s=await $(o,e,n);for(let a of i){let k=s.find(h=>A(h.token.address,a.token.address)&&a.distributionLayer==="TREE");k&&(a.claimed=k.claimed,a.claimable=k.claimable,a.status="claimable")}return{earnings:i,rewards:s.map(({proofs:a,...k})=>k),summary:s.length?`${w}. Claimable reward leaves: ${s.map(a=>m({token:a.token,amount:a.claimable})).join("; ")}. Wrapped leaves may transfer underlying tokens; claim preview shows the received assets. Pending rewards appear separately in earnings and are excluded from claimable amounts.`:`${j} Earnings include pending-only and unsupported distribution layers; an unverified amount is never presented as claimable.`}})},{name:"merkl_claim",description:w,inputSchema:{type:"object",properties:{},additionalProperties:!1,description:w},execute:(t,e)=>d(async()=>{F(t);let n=await c(e);if(!n.length)return{txs:[],summary:j};let i=[o.unsignedTx({to:R,chainId:l,value:"0",description:w,data:G({abi:T,functionName:"claim",args:[n.map(()=>e),n.map(a=>a.token.address),n.map(a=>BigInt(a.amount)),n.map(a=>a.proofs)]})})],s=await o.preview(i,e);return{txs:i,summary:`${w}. Prepared unsigned claim. Expected wallet changes: ${s.changes.length?s.changes.map(m).join("; "):"no token transfers in simulation"}. ${s.summary}`}})}],positions:t=>d(async()=>(await c(t)).map(e=>({module:"merkl",id:`${l}:${e.token.address.toLowerCase()}`,chainId:l,assets:[{token:e.token,amount:e.claimable}],description:`${w}. Unclaimed reward leaf; wrapped rewards may transfer underlying assets. Pending rewards are excluded.`})))}},ue=o=>z("merkl",[X(o),L(o),U(o),H(o)]);var M=I[l].merkl.distributor.address,g=Y(["function operators(address,address) view returns (uint256)","function claimRecipient(address,address) view returns (address)","function toggleOperator(address,address)","function setClaimRecipient(address,address)","function claim(address[],address[],uint256[],bytes32[][])","function claimWithRecipient(address[],address[],uint256[],bytes32[][],address[],bytes[])"]),q="Provide a valid address.";function f(o,d=!1){let m=N(o,q);return d?m:_(m,q)}var U=o=>{let d=()=>o.clientFor(l),m=async(r,t,e)=>{let n=[o.unsignedTx({to:M,chainId:l,value:"0",data:r,description:t})],i=await o.preview(n,e);return{txs:n,preview:i,summary:`Powered by Merkl \u2014 https://app.merkl.xyz. ${t} ${i.summary}`}},c=(r,t,e,n)=>({name:`merkl_${r}`,inputSchema:{type:"object",properties:t,required:e,additionalProperties:!1},execute:async(i,s)=>{try{let a=Object.keys(i).find(k=>!Object.hasOwn(t,k));if(a)throw new u(`Unsupported Merkl input: ${a}.`);return await n(i,f(s))}catch(a){throw new u(o.plainError(a))}}});return{tools:[c("claim_config",{token:y,operator:y},[],async(r,t)=>{let e=f(r.token??v,!0),n=f(await d().readContract({address:M,abi:g,functionName:"claimRecipient",args:[t,v]}),!0),i=f(await d().readContract({address:M,abi:g,functionName:"claimRecipient",args:[t,e]}),!0),s;if(r.operator!==void 0){let a=await d().readContract({address:M,abi:g,functionName:"operators",args:[t,f(r.operator,!0)]});if(a!==0n&&a!==1n)throw new u("Merkl returned invalid operator authorization.");s=a===1n}return{chainId:l,wallet:t,token:e,defaultRecipient:n,tokenRecipient:i,effectiveRecipient:i!==v?i:n!==v?n:t,...s===void 0?{}:{operatorEnabled:s},summary:"Powered by Merkl \u2014 https://app.merkl.xyz. Zero recipient restores self-claims. Token overrides take precedence over the global recipient."}}),c("set_operator",{operator:y,enabled:{type:"boolean"}},["operator","enabled"],async(r,t)=>{let e=f(r.operator,!0);if(typeof r.enabled!="boolean")throw new u("Provide enabled as boolean.");let n=await d().readContract({address:M,abi:g,functionName:"operators",args:[t,e]});if(n!==0n&&n!==1n)throw new u("Merkl returned invalid operator authorization.");return n===1n===r.enabled?{txs:[],summary:"Powered by Merkl \u2014 https://app.merkl.xyz. Operator already has the requested state; no transaction needed."}:m(C({abi:g,functionName:"toggleOperator",args:[t,e]}),`${r.enabled?"Authorize":"Revoke"} Merkl claims by ${e} for ${t}. Zero operator grants permissionless claiming; configured recipients still apply. The contract toggles the observed state; preview and confirmation must remain current.`,t)}),c("set_recipient",{recipient:y,token:y},["recipient"],async(r,t)=>{let e=f(r.recipient,!0),n=f(r.token??v,!0);return m(C({abi:g,functionName:"setClaimRecipient",args:[e,n]}),`Set Merkl reward recipient for ${n===v?"all tokens":n} to ${e===v?`self (${t})`:e}. This redirects future claims; token-specific overrides remain authoritative.`,t)}),c("claim_to",{recipient:y,token:y,data:{type:"string",pattern:"^0x([0-9a-fA-F]{2})*$",maxLength:16386}},["recipient"],async(r,t)=>{let e=f(r.recipient),n=r.token===void 0?void 0:f(r.token),i=r.data??"0x";if(typeof i!="string"||!/^0x([0-9a-fA-F]{2})*$/.test(i)||i.length>16386)throw new u("Provide callback data as at most 8192 hexadecimal bytes.");let s=(await $(o,t)).filter(a=>!n||A(a.token.address,n));return s.length?m(C({abi:g,functionName:"claimWithRecipient",args:[s.map(()=>t),s.map(a=>a.token.address),s.map(a=>BigInt(a.amount)),s.map(a=>a.proofs),s.map(()=>e),s.map(()=>i)]}),`Claim ${s.map(a=>`${a.claimable} ${a.token.symbol} base units (token ${a.token.address}, decimals ${a.token.decimals})`).join("; ")} to ${e}, overriding saved claim recipients for this claim only. Callback data for each leaf: ${i}. Inspect all callback effects in preview.`,t):{txs:[],summary:"Powered by Merkl \u2014 https://app.merkl.xyz. No verified claimable rewards for the selected token."}}),c("claim_for",{user:y,token:y},["user"],async(r,t)=>{let e=f(r.user),n=r.token===void 0?void 0:f(r.token),i=(await $(o,e)).filter(s=>!n||A(s.token.address,n));return i.length?m(C({abi:g,functionName:"claim",args:[i.map(()=>e),i.map(s=>s.token.address),i.map(s=>BigInt(s.amount)),i.map(s=>s.proofs)]}),`Claim Merkl rewards for ${e}; caller ${t} pays gas. The user's saved recipients control payment. Claim authorization and actual receipts must pass preview.`,t):{txs:[],summary:"Powered by Merkl \u2014 https://app.merkl.xyz. No verified claimable rewards for this user."}})]}};export{U as a,$ as b,X as c,ue as d};
1
+ import{a as L}from"./W2BYU5JQ.js";import{a as H}from"./TEJ7W534.js";import{b as z}from"./SPJCSEKP.js";import{a as P}from"./43LI5NKJ.js";import{c as D}from"./VEQBHI6O.js";import{c as y,e as b,g as A,i as N,l as _}from"./NWNYJ26T.js";import{b as E}from"./IX3GZMTM.js";import{a as l,i as I}from"./FWD4L3CJ.js";import{a as u}from"./XSD5NL7J.js";import{a as S}from"./JXOEJPJ4.js";import{encodeFunctionData as C,parseAbi as Y,zeroAddress as v}from"viem";import{encodeAbiParameters as B,encodeFunctionData as G,keccak256 as O,parseAbi as J}from"viem";var R=I[l].merkl.distributor.address,w="Claim rewards on Merkl (Powered by Merkl \u2014 https://app.merkl.xyz)",j=`${w}. No claimable rewards on Robinhood Chain. Pending rewards must settle into a Merkle root before they can be claimed.`,T=J(["function claimed(address user,address token) view returns (uint208 amount,uint48 timestamp,bytes32 merkleRoot)","function getMerkleRoot() view returns (bytes32)","function claim(address[] users,address[] tokens,uint256[] amounts,bytes32[][] proofs)"]);function W(o){return typeof o=="string"&&/^0x[0-9a-fA-F]{64}$/.test(o)}function p(){throw new u("Merkl returned an unexpected response. Please refetch rewards.")}function x(o){typeof o!="string"&&p();let d=E(o);if(d>=1n<<256n)throw new u("The Merkl reward amount exceeds the uint256 range.");return d.toString()}function K(o){let d=[],m=new Set;for(let c of o)if((!b(c)||!b(c.chain)||!Number.isSafeInteger(c.chain.id))&&p(),c.chain.id===l){Array.isArray(c.rewards)||p();for(let r of c.rewards){if((!b(r)||typeof r.distributionLayer!="string"||!b(r.token))&&p(),r.distributionLayer!=="TREE"||(Number.isSafeInteger(r.token.chainId)||p(),r.token.chainId!==l)||(Array.isArray(r.proofs)||p(),!r.proofs.length))continue;(!r.proofs.every(W)||typeof r.token.address!="string"||typeof r.token.symbol!="string"||!r.token.symbol.trim()||typeof r.token.decimals!="number"||!Number.isInteger(r.token.decimals)||r.token.decimals<0||r.token.decimals>255)&&p(),P(r.token.address);let t=x(r.amount),e=x(r.pending);if(BigInt(t)===0n)continue;let n=r.token.address.toLowerCase();if(m.has(n))throw new u("Merkl returned duplicate token leaves. Please refetch rewards.");m.add(n),d.push({token:{address:r.token.address,chainId:l,decimals:r.token.decimals,symbol:r.token.symbol},amount:t,pending:e,proofs:r.proofs})}}return d}function Q(o,d,m){let c=O(B([{type:"address"},{type:"address"},{type:"uint256"}],[o,d.token.address,BigInt(d.amount)]));for(let r of d.proofs){let t=BigInt(c)<BigInt(r)?[c,r]:[r,c];c=O(B([{type:"bytes32"},{type:"bytes32"}],t))}if(!A(c,m))throw new u("The Merkl proof does not match the active root. Please refetch rewards.")}function F(o){if(!b(o)||Object.keys(o).length)throw new u("This Merkl tool takes no arguments and uses the connected wallet.")}async function V(o,d){let m=await Z(o,d),c=[],r=new Set;for(let t of m)if((!b(t)||!b(t.chain)||!Number.isSafeInteger(t.chain.id))&&p(),t.chain.id===l){Array.isArray(t.rewards)||p();for(let e of t.rewards){if((!b(e)||typeof e.distributionLayer!="string"||!b(e.token)||!Number.isSafeInteger(e.token.chainId))&&p(),e.token.chainId!==l)continue;(typeof e.token.address!="string"||typeof e.token.symbol!="string"||!e.token.symbol.trim()||typeof e.token.decimals!="number"||!Number.isInteger(e.token.decimals)||e.token.decimals<0||e.token.decimals>255)&&p(),P(e.token.address);let n=x(e.amount),i=x(e.pending),s=`${e.distributionLayer}:${e.token.address.toLowerCase()}`;if(r.has(s))throw new u("Merkl returned duplicate earning rows. Please refetch rewards.");r.add(s);let a={address:e.token.address,symbol:e.token.symbol,decimals:e.token.decimals,chainId:l},k="0";if(e.distributionLayer==="TREE"){let h=await o.clientFor(l).readContract({address:R,abi:T,functionName:"claimed",args:[d,a.address]});(!Array.isArray(h)||typeof h[0]!="bigint"||h[0]<0n||h[0]>=1n<<208n)&&p(),k=h[0].toString()}c.push({token:a,amount:n,pending:i,claimed:k,claimable:"0",distributionLayer:e.distributionLayer,status:e.distributionLayer!=="TREE"?"unsupported_distribution_layer":BigInt(n)>BigInt(k)?"awaiting_verified_proof":BigInt(i)>0n?"pending_settlement":"settled"})}}return{body:m,earnings:c}}async function Z(o,d){return P(d),D(o.http,`https://api.merkl.xyz/v4/users/${d}/rewards/summary?chainId=${l}`,{method:"GET",headers:{"User-Agent":"oak-core/merkl"}},m=>Array.isArray(m))}async function $(o,d,m){P(d);let c=K(m??await Z(o,d)),r=o.clientFor(l),t=[];for(let n of c){let i=await r.readContract({address:R,abi:T,functionName:"claimed",args:[d,n.token.address]});if(!Array.isArray(i)||typeof i[0]!="bigint"||i[0]<0n||i[0]>=1n<<208n)throw new u("The Merkl claimed balance could not be read. Please try again.");BigInt(n.amount)<=i[0]||t.push({...n,claimed:i[0].toString(),claimable:(BigInt(n.amount)-i[0]).toString()})}if(!t.length)return[];let e=await r.readContract({address:R,abi:T,functionName:"getMerkleRoot"});if(!W(e))throw new u("The active Merkl root could not be read. Please try again.");for(let n of t)Q(d,n,e);return t}var X=o=>{async function d(t){try{return await t()}catch(e){throw new u(o.plainError(e))}}function m(t){let e=t.amount.startsWith("-"),n=e?t.amount.slice(1):t.amount;return`${e?"-":""}${o.formatAmount(n,t.token.decimals)} ${S(t.token.symbol)} (${t.token.address}, chain ${t.token.chainId}, ${t.token.decimals} decimals)`}let c=t=>$(o,t);return{tools:[{name:"merkl_rewards",description:"Read claimable rewards (Powered by Merkl \u2014 https://app.merkl.xyz).",inputSchema:{type:"object",properties:{},additionalProperties:!1,description:"Read rewards (Powered by Merkl \u2014 https://app.merkl.xyz)."},execute:(t,e)=>d(async()=>{F(t);let{body:n,earnings:i}=await V(o,e),s=await $(o,e,n);for(let a of i){let k=s.find(h=>A(h.token.address,a.token.address)&&a.distributionLayer==="TREE");k&&(a.claimed=k.claimed,a.claimable=k.claimable,a.status="claimable")}return{earnings:i,rewards:s.map(({proofs:a,...k})=>k),summary:s.length?`${w}. Claimable reward leaves: ${s.map(a=>m({token:a.token,amount:a.claimable})).join("; ")}. Wrapped leaves may transfer underlying tokens; claim preview shows the received assets. Pending rewards appear separately in earnings and are excluded from claimable amounts.`:`${j} Earnings include pending-only and unsupported distribution layers; an unverified amount is never presented as claimable.`}})},{name:"merkl_claim",description:w,inputSchema:{type:"object",properties:{},additionalProperties:!1,description:w},execute:(t,e)=>d(async()=>{F(t);let n=await c(e);if(!n.length)return{txs:[],summary:j};let i=[o.unsignedTx({to:R,chainId:l,value:"0",description:w,data:G({abi:T,functionName:"claim",args:[n.map(()=>e),n.map(a=>a.token.address),n.map(a=>BigInt(a.amount)),n.map(a=>a.proofs)]})})],s=await o.preview(i,e);return{txs:i,summary:`${w}. Prepared unsigned claim. Expected wallet changes: ${s.changes.length?s.changes.map(m).join("; "):"no token transfers in simulation"}. ${s.summary}`}})}],positions:t=>d(async()=>(await c(t)).map(e=>({module:"merkl",id:`${l}:${e.token.address.toLowerCase()}`,chainId:l,assets:[{token:e.token,amount:e.claimable}],description:`${w}. Unclaimed reward leaf; wrapped rewards may transfer underlying assets. Pending rewards are excluded.`})))}},ue=o=>z("merkl",[X(o),L(o),U(o),H(o)]);var M=I[l].merkl.distributor.address,g=Y(["function operators(address,address) view returns (uint256)","function claimRecipient(address,address) view returns (address)","function toggleOperator(address,address)","function setClaimRecipient(address,address)","function claim(address[],address[],uint256[],bytes32[][])","function claimWithRecipient(address[],address[],uint256[],bytes32[][],address[],bytes[])"]),q="Provide a valid address.";function f(o,d=!1){let m=N(o,q);return d?m:_(m,q)}var U=o=>{let d=()=>o.clientFor(l),m=async(r,t,e)=>{let n=[o.unsignedTx({to:M,chainId:l,value:"0",data:r,description:t})],i=await o.preview(n,e);return{txs:n,preview:i,summary:`Powered by Merkl \u2014 https://app.merkl.xyz. ${t} ${i.summary}`}},c=(r,t,e,n)=>({name:`merkl_${r}`,inputSchema:{type:"object",properties:t,required:e,additionalProperties:!1},execute:async(i,s)=>{try{let a=Object.keys(i).find(k=>!Object.hasOwn(t,k));if(a)throw new u(`Unsupported Merkl input: ${a}.`);return await n(i,f(s))}catch(a){throw new u(o.plainError(a))}}});return{tools:[c("claim_config",{token:y,operator:y},[],async(r,t)=>{let e=f(r.token??v,!0),n=f(await d().readContract({address:M,abi:g,functionName:"claimRecipient",args:[t,v]}),!0),i=f(await d().readContract({address:M,abi:g,functionName:"claimRecipient",args:[t,e]}),!0),s;if(r.operator!==void 0){let a=await d().readContract({address:M,abi:g,functionName:"operators",args:[t,f(r.operator,!0)]});if(a!==0n&&a!==1n)throw new u("Merkl returned invalid operator authorization.");s=a===1n}return{chainId:l,wallet:t,token:e,defaultRecipient:n,tokenRecipient:i,effectiveRecipient:i!==v?i:n!==v?n:t,...s===void 0?{}:{operatorEnabled:s},summary:"Powered by Merkl \u2014 https://app.merkl.xyz. Zero recipient restores self-claims. Token overrides take precedence over the global recipient."}}),c("set_operator",{operator:y,enabled:{type:"boolean"}},["operator","enabled"],async(r,t)=>{let e=f(r.operator,!0);if(typeof r.enabled!="boolean")throw new u("Provide enabled as boolean.");let n=await d().readContract({address:M,abi:g,functionName:"operators",args:[t,e]});if(n!==0n&&n!==1n)throw new u("Merkl returned invalid operator authorization.");return n===1n===r.enabled?{txs:[],summary:"Powered by Merkl \u2014 https://app.merkl.xyz. Operator already has the requested state; no transaction needed."}:m(C({abi:g,functionName:"toggleOperator",args:[t,e]}),`${r.enabled?"Authorize":"Revoke"} Merkl claims by ${e} for ${t}. Zero operator grants permissionless claiming; configured recipients still apply. The contract toggles the observed state; preview and confirmation must remain current.`,t)}),c("set_recipient",{recipient:y,token:y},["recipient"],async(r,t)=>{let e=f(r.recipient,!0),n=f(r.token??v,!0);return m(C({abi:g,functionName:"setClaimRecipient",args:[e,n]}),`Set Merkl reward recipient for ${n===v?"all tokens":n} to ${e===v?`self (${t})`:e}. This redirects future claims; token-specific overrides remain authoritative.`,t)}),c("claim_to",{recipient:y,token:y,data:{type:"string",pattern:"^0x([0-9a-fA-F]{2})*$",maxLength:16386}},["recipient"],async(r,t)=>{let e=f(r.recipient),n=r.token===void 0?void 0:f(r.token),i=r.data??"0x";if(typeof i!="string"||!/^0x([0-9a-fA-F]{2})*$/.test(i)||i.length>16386)throw new u("Provide callback data as at most 8192 hexadecimal bytes.");let s=(await $(o,t)).filter(a=>!n||A(a.token.address,n));return s.length?m(C({abi:g,functionName:"claimWithRecipient",args:[s.map(()=>t),s.map(a=>a.token.address),s.map(a=>BigInt(a.amount)),s.map(a=>a.proofs),s.map(()=>e),s.map(()=>i)]}),`Claim ${s.map(a=>`${a.claimable} ${a.token.symbol} base units (token ${a.token.address}, decimals ${a.token.decimals})`).join("; ")} to ${e}, overriding saved claim recipients for this claim only. Callback data for each leaf: ${i}. Inspect all callback effects in preview.`,t):{txs:[],summary:"Powered by Merkl \u2014 https://app.merkl.xyz. No verified claimable rewards for the selected token."}}),c("claim_for",{user:y,token:y},["user"],async(r,t)=>{let e=f(r.user),n=r.token===void 0?void 0:f(r.token),i=(await $(o,e)).filter(s=>!n||A(s.token.address,n));return i.length?m(C({abi:g,functionName:"claim",args:[i.map(()=>e),i.map(s=>s.token.address),i.map(s=>BigInt(s.amount)),i.map(s=>s.proofs)]}),`Claim Merkl rewards for ${e}; caller ${t} pays gas. The user's saved recipients control payment. Claim authorization and actual receipts must pass preview.`,t):{txs:[],summary:"Powered by Merkl \u2014 https://app.merkl.xyz. No verified claimable rewards for this user."}})]}};export{U as a,$ as b,X as c,ue as d};
@@ -1 +1 @@
1
- import{b as le,o as K}from"./GHPREYQK.js";import{b as x}from"./5ZLOCQA4.js";import{c as W,f as de,h as y,i as ce,l as ue}from"./5KUWLUPM.js";import{a as k,i as oe,j as G}from"./FWD4L3CJ.js";import{a as N}from"./XSD5NL7J.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"./3NJ5KQ3Q.js";import{b as x}from"./66F5ZH34.js";import{c as W,f as de,h as y,i as ce,l as ue}from"./NWNYJ26T.js";import{a as k,i as oe,j as G}from"./FWD4L3CJ.js";import{a as N}from"./XSD5NL7J.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};
@@ -0,0 +1 @@
1
+ import{a as d}from"./XSD5NL7J.js";var i=class extends d{constructor(r,n){super(`${r} is busy; retry in ${Math.max(1,Math.ceil(n))} seconds.`);this.vendor=r;this.retryAfterSeconds=n}vendor;retryAfterSeconds},y=new WeakMap,b={"aggregator-api.kyberswap.com":{label:"KyberSwap",spacing:350},"api.velora.xyz":{label:"Velora",spacing:1050,daily:5e3},"api.relay.link":{label:"Relay",spacing:1250},"borro.markets":{label:"Borro",spacing:2e3,daily:5e3},"api-v2.pendle.finance":{label:"Pendle",spacing:2e3,daily:5e3}};function u(t,c){let r=new URL(c).hostname,n=b[r];if(!n)return;let o=y.get(t);o||(o=new Map,y.set(t,o));let e=o.get(r);return e||(e={next:0,blockedUntil:0,lastSent:-1/0,daily:[]},o.set(r,e)),{label:n.label,reserve(){let a=Date.now();if(e.daily=e.daily.filter(s=>s>a-864e5),n.daily&&e.daily.length>=n.daily)throw new i(n.label,(e.daily[0]+864e5-a)/1e3);let l=Math.max(a,e.next,e.blockedUntil,e.lastSent+n.spacing);if(l-a>2e3)throw new i(n.label,(l-a)/1e3);return e.next=l+n.spacing,l-a},dispatchDelay(){let a=Date.now();if(e.daily=e.daily.filter(s=>s>a-864e5),n.daily&&e.daily.length>=n.daily)throw new i(n.label,(e.daily[0]+864e5-a)/1e3);if(e.blockedUntil>a)throw new i(n.label,(e.blockedUntil-a)/1e3);let l=Math.max(0,e.lastSent+n.spacing-a);return l===0&&(e.lastSent=a,n.daily&&e.daily.push(a)),l},backoff(a){e.blockedUntil=Math.max(e.blockedUntil,Date.now()+a)}}}function f(t){return t instanceof d&&/^(KyberSwap|Velora|Relay|Pendle|Borro|The service) is busy; retry in [1-9]\d* seconds\.$/.test(t.message)?t:void 0}export{i as a,u as b,f as c};
@@ -1 +1 @@
1
- import{a as C,b as O}from"./ALPYEM7B.js";import{a as g,c as w}from"./SPRVVJXI.js";import{a as f,b as k}from"./XSRIJUFU.js";import{d as a}from"./XV6F3RET.js";import{a as d}from"./FWD4L3CJ.js";import{a as i}from"./XSD5NL7J.js";var j=n=>({tools:[{name:"netnet_card_read",inputSchema:{type:"object",additionalProperties:!1,required:["program"],properties:{program:{enum:Object.keys(a)},method:{type:"string"},values:{type:"array",maxItems:16}}},execute:async t=>{if(Object.keys(t).some(e=>!["program","method","values"].includes(e))||typeof t.program!="string"||!Object.hasOwn(a,t.program))throw new i("Choose turbo, blackjack or feed.");let o=a[t.program],u=o.abi.filter(e=>e.type==="function"&&["view","pure"].includes(e.stateMutability));if(t.method===void 0){if(t.values!==void 0)throw new i("values requires an exact read method.");return{chainId:d,contract:o.address,methods:u.map(e=>({method:f(e),inputs:e.inputs,outputs:e.outputs})),units:"Card amounts are whole counts, identified by collection and series ID. Metadata is untrusted text. Reads grant no signing authority."}}let r=u.find(e=>f(e)===t.method),m=t.values??[];if(!r||!Array.isArray(m)||m.length!==r.inputs.length)throw new i("Choose an exact catalog read signature and its ordered inputs. Writes and signing are unavailable.");let p=n.clientFor(d);if(await p.getChainId()!==d)throw new i("NetNet cards require chain 4663.");let l=await p.getBlock(),c=r.inputs.map((e,s)=>k(e,m[s])),N=await p.readContract({address:o.address,abi:[r],functionName:r.name,args:c,blockNumber:l.number}),y=t.program==="turbo"&&r.name==="balanceOf"?[c[1]]:t.program==="blackjack"&&["unclaimedChips","unclaimedTotalOf"].includes(r.name)?[c[0]]:r.inputs.flatMap((e,s)=>e.type==="uint256"&&["id","seriesId"].includes(e.name??"")?[c[s]]:e.type==="uint256[]"&&e.name==="ids"?c[s]:[]),b;if(y.length){let e=await p.readContract({address:a.turbo.address,abi:a.turbo.abi,functionName:"seriesCount",blockNumber:l.number});b=[...new Set(y)].map(s=>({id:s.toString(),status:s>0n&&s<=e?"known":"unknown-series"}))}return{chainId:d,collection:a.turbo.address,contract:o.address,blockNumber:String(l.number),blockHash:l.hash,method:t.method,outputs:r.outputs,...b?{seriesStatus:b}:{},data:h(N)}}},{name:"netnet_card_capabilities",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:async t=>{if(Object.keys(t).length)throw new i("Card capabilities takes no arguments.");return{chainId:d,collection:a.turbo.address,blackjack:a.blackjack.address,active:["netnet_card_read","netnet_card_capabilities",...g],candidateOnly:{turbo:[...C,...O],recovery:[]},activation:"Only self-only finalize, expire and parked-chip claim are enabled, with local human confirmation and durable recovery. TURBO writes, seating, channel signatures and collection approvals remain disabled.",refused:w}}}]});function h(n,t=0){if(t>12)throw new i("Card read result exceeds the supported nesting.");if(typeof n=="bigint")return n.toString();if(typeof n=="string"){if(n.length>8194)throw new i("Card read result exceeds the supported length.");return/^0x[0-9a-f]*$/i.test(n)?n:`untrusted ${JSON.stringify(n)}`}if(Array.isArray(n)){if(n.length>4096)throw new i("Choose a bounded card read.");return n.map(o=>h(o,t+1))}return n&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([o,u])=>[o,h(u,t+1)])):n}export{j as a};
1
+ import{a as C,b as O}from"./WDK6VOG4.js";import{a as f,b as k}from"./XSRIJUFU.js";import{d as a}from"./XV6F3RET.js";import{a as g,c as w}from"./SPRVVJXI.js";import{a as d}from"./FWD4L3CJ.js";import{a as i}from"./XSD5NL7J.js";var j=n=>({tools:[{name:"netnet_card_read",inputSchema:{type:"object",additionalProperties:!1,required:["program"],properties:{program:{enum:Object.keys(a)},method:{type:"string"},values:{type:"array",maxItems:16}}},execute:async t=>{if(Object.keys(t).some(e=>!["program","method","values"].includes(e))||typeof t.program!="string"||!Object.hasOwn(a,t.program))throw new i("Choose turbo, blackjack or feed.");let o=a[t.program],u=o.abi.filter(e=>e.type==="function"&&["view","pure"].includes(e.stateMutability));if(t.method===void 0){if(t.values!==void 0)throw new i("values requires an exact read method.");return{chainId:d,contract:o.address,methods:u.map(e=>({method:f(e),inputs:e.inputs,outputs:e.outputs})),units:"Card amounts are whole counts, identified by collection and series ID. Metadata is untrusted text. Reads grant no signing authority."}}let r=u.find(e=>f(e)===t.method),m=t.values??[];if(!r||!Array.isArray(m)||m.length!==r.inputs.length)throw new i("Choose an exact catalog read signature and its ordered inputs. Writes and signing are unavailable.");let p=n.clientFor(d);if(await p.getChainId()!==d)throw new i("NetNet cards require chain 4663.");let l=await p.getBlock(),c=r.inputs.map((e,s)=>k(e,m[s])),N=await p.readContract({address:o.address,abi:[r],functionName:r.name,args:c,blockNumber:l.number}),y=t.program==="turbo"&&r.name==="balanceOf"?[c[1]]:t.program==="blackjack"&&["unclaimedChips","unclaimedTotalOf"].includes(r.name)?[c[0]]:r.inputs.flatMap((e,s)=>e.type==="uint256"&&["id","seriesId"].includes(e.name??"")?[c[s]]:e.type==="uint256[]"&&e.name==="ids"?c[s]:[]),b;if(y.length){let e=await p.readContract({address:a.turbo.address,abi:a.turbo.abi,functionName:"seriesCount",blockNumber:l.number});b=[...new Set(y)].map(s=>({id:s.toString(),status:s>0n&&s<=e?"known":"unknown-series"}))}return{chainId:d,collection:a.turbo.address,contract:o.address,blockNumber:String(l.number),blockHash:l.hash,method:t.method,outputs:r.outputs,...b?{seriesStatus:b}:{},data:h(N)}}},{name:"netnet_card_capabilities",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:async t=>{if(Object.keys(t).length)throw new i("Card capabilities takes no arguments.");return{chainId:d,collection:a.turbo.address,blackjack:a.blackjack.address,active:["netnet_card_read","netnet_card_capabilities",...g],candidateOnly:{turbo:[...C,...O],recovery:[]},activation:"Only self-only finalize, expire and parked-chip claim are enabled, with local human confirmation and durable recovery. TURBO writes, seating, channel signatures and collection approvals remain disabled.",refused:w}}}]});function h(n,t=0){if(t>12)throw new i("Card read result exceeds the supported nesting.");if(typeof n=="bigint")return n.toString();if(typeof n=="string"){if(n.length>8194)throw new i("Card read result exceeds the supported length.");return/^0x[0-9a-f]*$/i.test(n)?n:`untrusted ${JSON.stringify(n)}`}if(Array.isArray(n)){if(n.length>4096)throw new i("Choose a bounded card read.");return n.map(o=>h(o,t+1))}return n&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([o,u])=>[o,h(u,t+1)])):n}export{j as a};
@@ -0,0 +1 @@
1
+ import{a as fe}from"./TM2XCRU7.js";import{c as me}from"./MJ6WEWMI.js";import{a as Z}from"./L4N2RSK2.js";import{a as M,b as P}from"./3MLUCYCB.js";import{a as L}from"./U4JGEMKT.js";import{a as ue}from"./P4UQGWCP.js";import{a as x}from"./43LI5NKJ.js";import{b as de,c as le}from"./VEQBHI6O.js";import{a as re,b as X,c as j}from"./5HCXZWUH.js";import{l as ie,n as F,o as ce}from"./ABPL3ZZI.js";import{a as w,b as _,c as B,d as oe,i as E,j as ae,s as D}from"./FWD4L3CJ.js";import{a as k}from"./XSD5NL7J.js";import{a as p,b as V,c as se}from"./JXOEJPJ4.js";import{decodeFunctionResult as Ne,encodeFunctionData as ve,erc20Abi as Y,getAddress as b,isAddress as G,parseAbi as te}from"viem";var z="https://api.robinhood.com/rhj/assets",Pe={address:M,symbol:"ETH",decimals:18,chainId:w},Q={address:b(ae),symbol:"USDG",decimals:oe,chainId:w},J={address:b(E[4663].tokens.WETH.address),symbol:"WETH",decimals:18,chainId:w},we={address:b(E[4663].meridian.CollateralToken_USDe.address),symbol:"USDe",decimals:18,chainId:w};function K(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function $(e,t=w,s={}){let n=Array.isArray(e)?e:K(e)&&Array.isArray(e.assets)?e.assets:void 0;if(!n)throw new k("Official stock asset list response is malformed.");let a=new Map,d=new Map;if(n.length>1e4)throw new k("Official stock asset list exceeds the lookup limit.");for(let o of n){if(!K(o))continue;let r=o;if(typeof r.tokenSymbol!="string"||!r.tokenSymbol.trim()||!Array.isArray(r.deployments))continue;if(r.deployments.length>100)throw new k("Official stock deployment list exceeds the lookup limit.");let l=r.tokenSymbol;if(!/^[A-Za-z0-9.$_-]{1,32}$/.test(l))throw new k(`Invalid official stock ticker ${p(l)}.`);if(r.tokenDecimals!==void 0&&(typeof r.tokenDecimals!="number"||!Number.isInteger(r.tokenDecimals)||r.tokenDecimals<0||r.tokenDecimals>255))throw new k("Official stock asset has invalid token decimals.");let u=typeof r.tokenDecimals=="number"&&Number.isInteger(r.tokenDecimals)&&r.tokenDecimals>=0&&r.tokenDecimals<=255?r.tokenDecimals:18;for(let m of r.deployments){if(!K(m))continue;let h=m;if(h.chainId!==t)continue;if(typeof h.contractAddress!="string"||!G(h.contractAddress,{strict:!1}))throw new k("Official stock deployment has an invalid contract address.");let y=b(h.contractAddress),f=y.toLowerCase(),g=l.toUpperCase(),i=d.get(g);if(!s.allowAmbiguousSymbols&&i&&i!==f)throw new k(`Ambiguous official stock ticker ${p(l)} across multiple addresses.`);let c=a.get(f);if(c&&(c.symbol!==l||c.decimals!==u))throw new k(`Conflicting official stock identity at ${y}.`);d.set(g,f),a.set(f,{address:y,symbol:l,decimals:u,chainId:t,...s.includeNames&&typeof r.tokenName=="string"&&r.tokenName.trim()?{name:r.tokenName.trim()}:{}})}}return[...a.values()]}function Ee(e,t){if(typeof e.address!="string"||!G(e.address,{strict:!1}))return!1;let s=e.chainId??w,n=e.address.toLowerCase();return t.some(a=>a.chainId===s&&a.address.toLowerCase()===n&&a.symbol===e.symbol)}function W(e,t){x(e.address);let s=e.chainId??w,n=b(e.address),a=n.toLowerCase(),d=O(e.symbol),o=t.find(l=>l.chainId===s&&l.address.toLowerCase()===a),r=t.find(l=>l.chainId===s&&O(l.symbol)===d);if(o){if(e.symbol!==o.symbol)throw new k(`Token at ${n} does not match official stock ticker ${p(o.symbol)} (received ${p(e.symbol)}).`);if(e.decimals!==void 0&&e.decimals!==o.decimals)throw new k(`Token ${p(o.symbol)} at ${n} does not match official decimals ${o.decimals}.`);return o}if(r)throw new k(`Token symbol ${p(e.symbol)} at ${n} does not match the official stock contract address ${r.address}.`);return{address:n,symbol:e.symbol.trim(),decimals:e.decimals??18,chainId:s}}var xe=["AAOI","AAPL","ABCL","ADBE","AEHR","AEIS","ALAB","AMAT","AMBA","AMC","AMD","AMKR","AMZN","ANET","APLD","APP","ASML","ASTS","AUR","AVAV","AVGO","AXON","AXTI","BA","BABA","BB","BE","BMNR","BND","BULL","CBRS","CCL","CEG","CELH","CIEN","CLOV","CLS","CLSK","COHR","COIN","COST","CRCL","CRDO","CRM","CRWD","CRWV","CSCO","CTSH","CVNA","DDOG","DELL","DIS","DJT","DOCN","ELF","EWT","EWY","F","FICO","FIG","FISV","FIX","FLNC","FLY","FTNT","FUTU","GDX","GE","GEV","GLD","GLW","GLXY","GME","GOOGL","HII","HIMS","HPE","HWM","IBM","IBRX","INDA","INFQ","INOD","INTC","INTU","IONQ","IREN","JBL","JNJ","JOBY","JPM","KLAC","KSS","KTOS","LHX","LITE","LLY","LMT","LRCX","LULU","LUNR","MCD","MDB","META","MOD","MPWR","MRNA","MRVL","MSFT","MSTR","MTSI","MU","MXL","NAVN","NBIS","NET","NFLX","NNE","NOW","NU","NVDA","NVTS","OKLO","ON","ONTO","ORCL","OUST","P","PANW","PATH","PENG","PFE","PL","PLTR","POET","POWL","PR","PWR","PYPL","QBTS","QCOM","QQQ","QUBT","RBLX","RCAT","RDDT","RDW","RGTI","RIVN","RKLB","RUN","SATS","SCHD","SGOV","SHOP","SHY","SIMO","SKHY","SLS","SLV","SMCI","SMH","SMR","SNAP","SNDK","SNOW","SOFI","SOUN","SOXX","SPCX","SPMO","SPY","TE","TEAM","TEM","TER","TSEM","TSLA","TSM","TTD","TTWO","UBER","UMC","UNH","UPS","USAR","USO","V","VICR","VRT","VSAT","VST","VTI","WDAY","WDC","WULF","WYFI","XLK","XNDU","XOM","ZETA","ZM","ZS"],q=new WeakMap,ke=new WeakMap,ge=3e4,he=Object.freeze([]),N;function nn(){if(!N)return he;let e=Date.now()-N.started;return e>=0&&e<ge?N.tokens:he}var ee=new WeakMap;function H(e,t){return(ee.get(e)??F)(t)}async function Ae(e){let t=e?.http??de(),s=e?.url??z,n=e?.chainId??w,a=j(t),d=ke.get(a);d||(d=new re(ge),ke.set(a,d));let{value:o,started:r}=await H(t,()=>d.read(`${n}:${s}`,async()=>{let u=await F(h=>le(a,s,{method:"GET",signal:h},y=>K(y)||Array.isArray(y))),m=$(u,n,{allowAmbiguousSymbols:!0});if(n===w&&m.length===0)throw new k("Official stock asset list has no mainnet deployments; retry when the list is available.");return u})),l=$(o,n,e);if(n===w&&s===z&&(!N||r>=N.started||Date.now()<N.started)&&(N={started:r,tokens:Object.freeze($(o,n,{allowAmbiguousSymbols:!0}).map(u=>Object.freeze(u)))}),n===w){let u=q.get(a);u||(u=new Set,q.set(a,u));for(let m of l)u.add(O(m.symbol))}return l}var Me=te(["function aggregate3((address target, bool allowFailure, bytes callData)[] calls) payable returns ((bool success, bytes returnData)[] returnData)"]);function ye(e){let t=e,s=new Set;for(;t&&typeof t=="object"&&!s.has(t)&&s.size<10;){s.add(t);let n=t;if(n.name==="ContractFunctionZeroDataError"||n.name==="AbiDecodingZeroDataError")return!0;let a=`${typeof n.shortMessage=="string"?n.shortMessage:""} ${typeof n.message=="string"?n.message:""}`;if(/returned no data \("0x"\)|Cannot decode zero data/i.test(a))return!0;t=n.cause}return!1}function Re(e){return e instanceof k?/RPC endpoint|too many requests|malformed JSON/i.test(e.message):e instanceof Error?/fetch failed|network|ECONNREFUSED|ETIMEDOUT|HTTP \d{3}|rate limit|too many requests/i.test(e.message):!1}async function Ue(e,t,s){if(typeof e.getCode=="function")try{let n=await e.getCode({address:t});return!n||n==="0x"}catch{return ye(s)}return ye(s)}async function Te(e,t,s){if(t.length===0)return[];let n=await Promise.allSettled(t.map(a=>e.readContract({address:a.address,abi:Y,functionName:"balanceOf",args:[s]})));if(n.every(a=>a.status==="rejected")&&n[0]?.status==="rejected"&&Re(n[0].reason))throw n[0].reason;return n.map(a=>{if(a.status!=="fulfilled"||a.value===void 0||a.value===null)return{ok:!1};try{let d=typeof a.value=="bigint"?a.value:BigInt(a.value);return d>=0n?{ok:!0,amount:d}:{ok:!1}}catch{return{ok:!1}}})}async function Se(e,t,s,n){if(s.length===0)return[];let a=ie(t,e);if(!a)return Te(e,s,n);let d=s.map(r=>({target:r.address,allowFailure:!0,callData:ve({abi:Y,functionName:"balanceOf",args:[n]})})),o;try{o=await e.readContract({address:a,abi:Me,functionName:"aggregate3",args:[d]})}catch(r){if(await Ue(e,a,r))return Te(e,s,n);throw r}if(!Array.isArray(o)||o.length!==s.length)throw new k("Multicall3 aggregate3 returned an invalid result list.");return o.map(r=>{let l=r,u=Array.isArray(l)?l[0]:l?.success,m=Array.isArray(l)?l[1]:l?.returnData;if(!u||typeof m!="string"||m==="0x")return{ok:!1};try{let h=Ne({abi:Y,functionName:"balanceOf",data:m}),y=typeof h=="bigint"?h:BigInt(h);return y>=0n?{ok:!0,amount:y}:{ok:!1}}catch{return{ok:!1}}})}async function tn(e,t={}){x(e);let s=b(e),n=t.chainId??w,a=t.client??ce(t.rpcUrl,n),d=[];if(t.stockTokens?d=[...t.stockTokens]:t.stockAssetsPayload!==void 0?d=$(t.stockAssetsPayload,n):t.includeStockTokens!==!1&&n!==_&&(d=await Ae({http:t.http,url:t.stockAssetsUrl,chainId:n})),t.tokens)for(let i of t.tokens)W(i,d);let o=n===w?[Q,J,we,...t.oakTokenAddress||process.env.OAK_TOKEN_ADDRESS?[{address:b(t.oakTokenAddress??process.env.OAK_TOKEN_ADDRESS),symbol:"OAK",decimals:B,chainId:n}]:[]]:n===_?[{...Q,address:b(D.testnet.usdg),chainId:n},{...J,address:b(D.testnet.weth),chainId:n},...t.oakTokenAddress?[{address:b(t.oakTokenAddress),symbol:"OAK",decimals:B,chainId:n}]:[]]:[],r=n===w&&t.includePoolTokens!==!1?ue.vaults.flatMap(i=>[{address:b(i.tokenAddress),symbol:b(i.tokenAddress),decimals:i.tokenDecimals,chainId:n},{address:b(i.earnContractAddress),symbol:b(i.earnContractAddress),decimals:18,chainId:n}]):[],l=new Set(r.map(i=>i.address.toLowerCase())),u=[],m=new Set;for(let i of[...o,...d,...t.tokens??[],...r]){if(i.chainId!==n||P(i.address)===M)continue;let c=W(i,d),T=c.address.toLowerCase();m.has(T)||(m.add(T),u.push(c))}let[h,y]=await Promise.all([a.getBalance({address:s}),Se(a,n,u,s)]),f=[],g={address:M,symbol:"ETH",decimals:18,chainId:n};(h>0n||t.includeZero)&&f.push({token:g,amount:h.toString()});for(let i=0;i<u.length;i++){let c=u[i],T=o.some(S=>C(S.address,c.address))||d.some(S=>C(S.address,c.address))?c.symbol:p(c.symbol),I=y[i]??{ok:!1};if(!I.ok){f.push({token:{address:c.address,symbol:T,decimals:c.decimals,chainId:c.chainId},amount:"unavailable"});continue}let A=I.amount;if(A>0n&&l.has(c.address.toLowerCase()))try{let[S,R]=await Promise.all([L(a,n,c.address,"symbol"),L(a,n,c.address,"decimals")]);T=p(S),c.decimals=R}catch{}(A>0n||t.includeZero)&&f.push({token:{address:c.address,symbol:T,decimals:c.decimals,chainId:c.chainId},amount:A.toString()})}return f}async function sn(e,t,s){if(x(e),t.length>1e4)throw new k("Journal token discovery exceeds the balance lookup limit.");let n=[...new Set(t.map(o=>(x(o),b(o))))].filter(o=>P(o)!==M).map(o=>({address:o,symbol:o,decimals:0,chainId:s.chainId})),a=await Se(s.client,s.chainId,n,b(e)),d=n.flatMap((o,r)=>{let l=a[r];return l.ok&&l.amount===0n?[]:[{token:o,amount:l.ok?l.amount.toString():"unavailable"}]});return Promise.all(d.map(async({token:o,amount:r})=>{let[l,u]=await Promise.all([L(s.client,s.chainId,o.address,"symbol").catch(()=>o.address),L(s.client,s.chainId,o.address,"decimals").catch(()=>{throw new k(`Token decimals are unavailable for journal-received token ${o.address}; retry balances when RPC metadata is available.`)})]);return{token:{...o,symbol:p(l),decimals:u},amount:r}}))}var C=(e,t)=>e.toLowerCase()===t.toLowerCase(),O=e=>se(e.normalize("NFKC")).toLowerCase().replace(/[^\p{L}\p{N}]/gu,"");function Oe(e){let t=e.context.network??"mainnet",{chainId:s,usdg:n,weth:a}=D[t],d=(o,r,l)=>({...o,address:P(b(o.address)),name:r,kind:l,verified:!0,source:"Oak fixed addresses",warnings:[]});return[d({...Pe,chainId:s},"Ether","native"),d({...Q,address:n,chainId:s},"Global Dollar","stablecoin"),d({...J,address:a,chainId:s},"Wrapped Ether","wrapped"),...t==="mainnet"?[d(we,"USDe","stablecoin")]:[],...e.oakTokenAddress?[d({address:e.oakTokenAddress,symbol:"OAK",decimals:B,chainId:s},"Oak","oak")]:[]]}async function Ce(e){if(e.context.network==="testnet")return[];let t=e.officialStockTokens??await Ae({http:e.context.http,includeNames:!0,allowAmbiguousSymbols:!0});return t.filter(s=>Ee(s,t)).map(s=>({...s,name:s.name??s.symbol,kind:"official_stock",verified:!0,source:z,warnings:[]}))}async function ne(e,t,s=!0){let{chainId:n}=D[t.context.network??"mainnet"],a=t.context.clientFor(n);if(await a.getChainId()!==n)throw new k(`Token lookup requires Robinhood Chain ${n}.`);let[d,o,r]=await Promise.all([H(a,()=>L(a,n,e,"name",t.blockNumber)).catch(l=>{if(s)throw l;return""}),H(a,()=>L(a,n,e,"symbol",t.blockNumber)),H(a,()=>L(a,n,e,"decimals",t.blockNumber))]);if(typeof d!="string"||s&&!d.trim()||typeof o!="string"||!o.trim()||!Number.isInteger(r)||r<0||r>255)throw new k("The contract returned invalid token metadata.");return{address:b(e),name:d||o,symbol:o,decimals:r,chainId:n}}async function be(e,t){let s=await t.context.clientFor(w).readContract({address:E[w].clanker.factory.address,abi:te(["function tokenDeploymentInfo(address) view returns ((address,address,address,address[]))"]),functionName:"tokenDeploymentInfo",args:[e]});return Array.isArray(s)&&s.length===4&&typeof s[0]=="string"&&C(s[0],e)}async function _e(e,t){let s=t.context.clientFor(w),n=E[w].poolsTrade,a=[n.instantLaunchStrategyFeesOn.address,n.instantLaunchStrategyFeesOff.address],d=te(["event TokenLaunched(bytes32 indexed poolId,address indexed token,address indexed feeSplitter,(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey)"])[0],o=await s.getBlockNumber(),r=new Set,l=0,u=0;for(let m=63127652n;m<=o;m+=10000000n){if(++l>Ie)throw new k("Token origin scan limit reached.");let h=m+9999999n>o?o:m+9999999n,y=await s.getLogs({address:a,event:d,args:{token:e},fromBlock:m,toBlock:h,strict:!0});for(let f of y){if(f.removed||!a.some(i=>C(i,f.address))||!f.args.token||!C(f.args.token,e)||!f.transactionHash||r.has(f.transactionHash))continue;if(r.add(f.transactionHash),++u>20)throw new k("Token origin receipt limit reached.");let g=await s.getTransactionReceipt({hash:f.transactionHash});if(fe(g).some(i=>C(i.token,e)))return b(g.from)}}}var Ie=5,Be=100,Fe=500,Ke=3e4;function Le(e){let t=Date.now()+Ke,s=0,n=new Map,a=o=>{let r=t-Date.now();if(r<=0)throw new k("Token lookup time budget reached; results are partial.");return F(o,Math.min(1e4,r))},d=X((o,r)=>a(async l=>{let u=await e.context.http(o,{...r,signal:l});return new Proxy(u,{get(m,h){if(h==="json")return()=>a(()=>m.json());let y=Reflect.get(m,h,m);return typeof y=="function"?y.bind(m):y}})}),e.context.http);return ee.set(d,a),{...e,context:{...e.context,http:d,clientFor:o=>{if(!n.has(o)){let r=e.context.clientFor(o),l=u=>{if(++s>Fe)throw new k("Token lookup RPC budget reached; results are partial.");return a(u)};n.set(o,X(new Proxy(r,{get(u,m){let h=Reflect.get(u,m);return typeof h!="function"?h:(...y)=>l(()=>h.apply(u,y))}}),r)),ee.set(n.get(o),l)}return n.get(o)}}}}function pe(e){return e.source==="Oak fixed addresses"?e:{...e,symbol:p(e.symbol),name:p(e.name)}}async function on(e,t){if(t=Le(t),typeof e!="string"||e.length>256||!O(e))throw new k("Provide a token name, symbol or address to find_token.");let s=O(e),n=G(e.trim(),{strict:!1})?P(b(e.trim())):void 0,{chainId:a}=D[t.context.network??"mainnet"],d=[],o=Oe(t),r=!1;try{o.push(...await Ce(t))}catch{r=!0,d.push("The official stock list is unavailable; results are partial and stock identities and lookalikes could not be checked.")}let l=i=>n?C(i.address,n):O(i.symbol).includes(s)||O(i.name).includes(s),u=o.filter(l),m=[],h=(i,c)=>[i.symbol,i.name??""].some(T=>[c.symbol,c.name].some(I=>{let A=O(T),S=O(I);return!!A&&!!S&&(A.includes(S)||S.includes(A))})),y=(i,c={})=>{if(m.some(A=>C(A.address,i.address)))return;let T=[`Token ${p(i.symbol)} at ${i.address} is an unverified ${c.launchpad?"launchpad token":"token"}. Use its address, not its name or symbol.`];(V(i.symbol)||V(i.name)||o.some(A=>!C(A.address,i.address)&&h(i,A)))&&T.push(`Lookalike warning: ${p(i.symbol)} at ${i.address} resembles a verified token's name or symbol.`);let I={...i,...c,kind:c.launchpad?"launchpad":"erc20",verified:!1,source:c.launchpad?`${c.launchpad} origin and on-chain metadata; not a verified token`:"On-chain metadata only",warnings:T};m.push(I),d.push(...T)};if(n&&!u.length){let i=await ne(n,t),c={};if(a===w){try{await be(n,t)&&(c.launchpad="clanker")}catch{d.push("Clanker origin lookup was unavailable for this address.")}if(c.launchpad==="clanker")try{let I=(await Z(t.context,{q:n,limit:20})).tokens.find(A=>C(A.contract_address,n));I&&(c.creator=b(I.msg_sender),c.creatorSource="Clanker indexer msg_sender")}catch{d.push("Clanker creator lookup is unavailable.")}else try{let T=await me(t.context,n);c.launchpad="pons",c.creator=b(T.creator),c.creatorSource="Pons factory deployer"}catch{d.push("Pons launch origin could not be confirmed for this address.")}if(!c.launchpad)try{let T=await _e(n,t);T&&(c.launchpad="pools.trade",c.creator=T,c.creatorSource="Launch transaction sender; may be a relayer")}catch{r=!0,d.push("pools.trade launch receipt lookup is unavailable; origin results are partial.")}}y(i,c)}else if(!n&&a===w){let i=new Set,c=new Set,T,I=0,A=0;try{do{if(++I>Ie)throw new k("Token search page limit reached.");let S=await Z(t.context,{q:e.trim(),limit:20,...T?{cursor:T}:{}});for(let R of S.tokens){if(++A>Be)throw new k("Token candidate limit reached.");let v=b(R.contract_address);if(!(c.has(v)||o.some(U=>C(U.address,v)))){c.add(v);try{let U=await ne(v,t);if(!l(U))continue;let De=await be(v,t)?{launchpad:"clanker",creator:b(R.msg_sender),creatorSource:"Clanker indexer msg_sender"}:{};y(U,De)}catch{r=!0,d.push(`Could not read Clanker candidate ${v}; it was omitted from these partial results.`)}}}if(S.cursor&&i.has(S.cursor))throw new k("The Clanker indexer repeated a pagination cursor.");S.cursor&&i.add(S.cursor),T=S.cursor??void 0}while(T)}catch{r=!0,d.push("Clanker name search is unavailable, incomplete or reached its scan limit; results are partial.")}d.push("Pons and pools.trade require a token address; name search does not cover those launchpads.")}a===_&&d.push("Testnet lookup covers pinned tokens and explicit token addresses; stock and launchpad discovery are unavailable.");let f=i=>[...new Map(i.map(c=>[c.address.toLowerCase(),c])).values()],g=f([...u,...m]);for(let i of g)if(g.some(c=>!C(c.address,i.address)&&(O(i.symbol)===O(c.symbol)||O(i.name)===O(c.name)))){let c=`Duplicate warning: several tokens share the symbol or name of ${i.address}. Choose the intended address; do not guess from the name.`;i.warnings.push(c),d.push(c)}return u.length>1&&d.push("Several verified tokens match this search, including possible substring matches. Choose an exact address; the search does not select a quote token."),{query:p(e.trim()),chainId:a,partial:r,matches:f(u).map(pe),unverified:f(m).map(pe),warnings:d}}async function an(e,t){if(typeof e!="string"||!e.trim())throw new k("Provide a token address or verified symbol; use find_token to look it up.");if(!/^[A-Za-z0-9.$_-]{1,42}$/.test(e))throw new k("Use an exact ASCII verified symbol or token address; use find_token to look it up.");let s=e,n=G(s,{strict:!1})?P(b(s)):void 0,a=Oe(t),d=n&&a.find(y=>C(y.address,n));if(d)return d;let o=s.toUpperCase()==="$OAK"?"OAK":s.toUpperCase(),r=!n&&a.find(y=>y.symbol.toUpperCase()===o),l=[],u=!1;try{l=await Ce(t)}catch{if(r)return r;if(!n)throw new k("The official stock list is unavailable; stock symbols cannot be checked. Use find_token and try again when the list is reachable.");u=!0}if(n){let y=l.find(i=>C(i.address,n));if(y)return t.tokenMetadata&&W(t.tokenMetadata,l),{...y,name:p(y.name)};let f=t.tokenMetadata??await t.readMetadata?.(n);if(f&&(!C(f.address,n)||f.chainId!==D[t.context.network??"mainnet"].chainId))throw new k("Token metadata does not match the requested address and chain.");if(f&&(typeof f.symbol!="string"||!f.symbol.trim()||!Number.isInteger(f.decimals)||f.decimals<0||f.decimals>255))throw new k("The contract returned invalid token metadata.");let g=f?{...f,name:f.symbol}:await ne(n,Le(t),!1);if(u){let i=O(g.symbol),c=q.get(j(t.context.http));if(xe.some(T=>O(T)===i)||c?.has(i))throw new k("The official stock list is unavailable; this address claims a stock ticker that cannot be checked. Try again when the list is reachable.")}return W(g,l),{...g,symbol:p(g.symbol),name:p(g.name),kind:"erc20",verified:!1,source:"On-chain metadata only",warnings:["This token address is unverified. On-chain names and symbols do not prove identity.",...u?["The official stock list is unavailable; stock identity could not be verified."]:[]]}}let m=[...a,...l].filter(y=>y.symbol.toUpperCase()===o);if(m.length!==1)throw new k(`Token symbol ${p(s)} is ${m.length?"ambiguous":"unverified"}; use find_token and choose an explicit address.`);let h=m[0];if(h.kind==="official_stock"&&s!==h.symbol)throw new k(`Use the exact official stock ticker ${p(h.symbol)}; case variants are refused.`);return h.source==="Oak fixed addresses"?h:{...h,name:p(h.name)}}export{z as a,Pe as b,Q as c,J as d,we as e,$ as f,Ee as g,W as h,nn as i,Ae as j,Me as k,tn as l,sn as m,on as n,an as o};
@@ -1 +1 @@
1
- import{a as l,c as w}from"./MYFAKCQI.js";import{e as d}from"./5KUWLUPM.js";import{a as h}from"./5HCXZWUH.js";import{a as p}from"./XSD5NL7J.js";var m=new WeakMap;async function x(o,r,s){let n=new URL(r);if(!(n.origin==="https://aggregator-api.kyberswap.com"&&n.pathname==="/robinhood/api/v1/routes")&&!(n.origin==="https://api.velora.xyz"&&n.pathname==="/prices"))throw new Error("Only supported public price routes may be shared.");let e=m.get(o);e||(e=new h(3e3),m.set(o,e));let i=await e.read(r,()=>w(o,r,{method:"GET"},s));return{value:i.value,expiresAt:Math.floor(i.started/1e3)+60}}var y="No route through verified sources.",g=new WeakMap;function E(o){let r=g.get(o);return r||(r=async(s,n)=>{let e=new URL(s instanceof Request?s.url:String(s)),i=["aggregator-api.kyberswap.com","api.kyberswap.com"].includes(e.hostname)&&e.pathname.endsWith("/robinhood/api/v1/routes"),u=e.origin==="https://api.velora.xyz"&&e.pathname==="/prices",f=async a=>{if(!(i||u)||![200,400,404].includes(a.status))return!1;let t=await a.clone().json().catch(()=>{});return d(t)?i&&(t.code===4008&&t.message==="route not found"||t.code===40011&&t.message==="filtered liquidity sources")||u&&typeof t.error=="string"&&/^(No routes found|No liquidity|No price route found)/i.test(t.error):!1},c;try{c=await o(s,n)}catch(a){throw a instanceof l&&await f(a.response)?new p(y):a}if(await f(c))throw new p(y);return c},g.set(o,r)),r}export{x as a,y as b,E as c};
1
+ import{a as l,c as w}from"./VEQBHI6O.js";import{e as d}from"./NWNYJ26T.js";import{a as h}from"./5HCXZWUH.js";import{a as p}from"./XSD5NL7J.js";var m=new WeakMap;async function x(o,r,s){let n=new URL(r);if(!(n.origin==="https://aggregator-api.kyberswap.com"&&n.pathname==="/robinhood/api/v1/routes")&&!(n.origin==="https://api.velora.xyz"&&n.pathname==="/prices"))throw new Error("Only supported public price routes may be shared.");let e=m.get(o);e||(e=new h(3e3),m.set(o,e));let i=await e.read(r,()=>w(o,r,{method:"GET"},s));return{value:i.value,expiresAt:Math.floor(i.started/1e3)+60}}var y="No route through verified sources.",g=new WeakMap;function E(o){let r=g.get(o);return r||(r=async(s,n)=>{let e=new URL(s instanceof Request?s.url:String(s)),i=["aggregator-api.kyberswap.com","api.kyberswap.com"].includes(e.hostname)&&e.pathname.endsWith("/robinhood/api/v1/routes"),u=e.origin==="https://api.velora.xyz"&&e.pathname==="/prices",f=async a=>{if(!(i||u)||![200,400,404].includes(a.status))return!1;let t=await a.clone().json().catch(()=>{});return d(t)?i&&(t.code===4008&&t.message==="route not found"||t.code===40011&&t.message==="filtered liquidity sources")||u&&typeof t.error=="string"&&/^(No routes found|No liquidity|No price route found)/i.test(t.error):!1},c;try{c=await o(s,n)}catch(a){throw a instanceof l&&await f(a.response)?new p(y):a}if(await f(c))throw new p(y);return c},g.set(o,r)),r}export{x as a,y as b,E as c};
@@ -1 +1 @@
1
- import{a as b,b as w,e as R,f as N,g as S}from"./SGEZIYJW.js";import{a as h}from"./5ZLOCQA4.js";import{c as g,g as E}from"./5KUWLUPM.js";import{a as d}from"./FWD4L3CJ.js";import{a as r}from"./XSD5NL7J.js";import{encodeFunctionData as v,erc20Abi as I,getAddress as _,parseAbi as O,zeroAddress as C}from"viem";var k=_("0x2ac03e14cfe755426daaee0a4994184ce81482f8"),a=_("0x7a8f74c2585f84c781f951b7f2ff21337d5b630b"),o=O(["function RESOURCE() view returns (address)","function TOKEN_JAR() view returns (address)","function threshold() view returns (uint256)","function nonce() view returns (uint256)","function release(uint256 nonce,address[] assets,address recipient)"]),B={assets:{type:"array",minItems:1,maxItems:20,items:g},nonce:h(),maxResourceAmount:h()};function F(n){return{tools:[!1,!0].map(i=>({name:i?"uniswap_token_jar_release":"uniswap_token_jar",inputSchema:{type:"object",additionalProperties:!1,required:i?["assets","nonce","maxResourceAmount"]:["assets"],properties:B},async execute(t,m){if(S(t,i?["assets","nonce","maxResourceAmount"]:["assets"]),!Array.isArray(t.assets)||t.assets.length<1||t.assets.length>20)throw new r("Provide 1 to 20 unique assets to release.");let c=t.assets.map(w);if(new Set(c).size!==c.length)throw new r("Token Jar assets must be unique.");let s=n.clientFor(d),e=await s.getBlockNumber(),[x,P,u,f]=await Promise.all([s.readContract({address:a,abi:o,functionName:"RESOURCE",blockNumber:e}),s.readContract({address:a,abi:o,functionName:"TOKEN_JAR",blockNumber:e}),s.readContract({address:a,abi:o,functionName:"threshold",blockNumber:e}),s.readContract({address:a,abi:o,functionName:"nonce",blockNumber:e})]);if(!E(String(P),k)||x===C)throw new r("Releaser deployment does not match the pinned Token Jar and ERC-20 resource.");let p=await R(n,w(x),e),T=await Promise.all(c.map(async l=>({token:await R(n,l,e),amount:(l===C?await s.getBalance({address:k,blockNumber:e}):await s.readContract({address:l,abi:I,functionName:"balanceOf",args:[k],blockNumber:e})).toString()}))),y={payment:{token:p,amount:String(u)},nonce:String(f),assets:T,blockNumber:e.toString()};if(!i)return{...y,summary:"Resource payment buys the listed jar contents; no profit is promised. Release uses a nonce to refuse competing releases."};let J=b(t.maxResourceAmount,"maxResourceAmount"),A=b(t.nonce,"nonce",256,!0);if(A!==BigInt(f)||BigInt(u)>J)throw new r("Token Jar nonce or resource cost changed. Read uniswap_token_jar and confirm fresh terms.");let j=[n.approval(p.address,a,String(u),d),n.unsignedTx({to:a,data:v({abi:o,functionName:"release",args:[A,c,m]}),value:"0",chainId:d,description:`Pay ${u} base units of ${p.address} to release Token Jar assets to ${m}, nonce ${f}.`})];return{...await N(n,j,m,"Exchange resource tokens for Token Jar assets. Check the full payment, assets and recipient in the preview; gas is additional."),...y}}}))}}export{k as a,a as b,o as c,F as d};
1
+ import{a as b,b as w,e as R,f as N,g as S}from"./T2WHOZXM.js";import{a as h}from"./66F5ZH34.js";import{c as g,g as E}from"./NWNYJ26T.js";import{a as d}from"./FWD4L3CJ.js";import{a as r}from"./XSD5NL7J.js";import{encodeFunctionData as v,erc20Abi as I,getAddress as _,parseAbi as O,zeroAddress as C}from"viem";var k=_("0x2ac03e14cfe755426daaee0a4994184ce81482f8"),a=_("0x7a8f74c2585f84c781f951b7f2ff21337d5b630b"),o=O(["function RESOURCE() view returns (address)","function TOKEN_JAR() view returns (address)","function threshold() view returns (uint256)","function nonce() view returns (uint256)","function release(uint256 nonce,address[] assets,address recipient)"]),B={assets:{type:"array",minItems:1,maxItems:20,items:g},nonce:h(),maxResourceAmount:h()};function F(n){return{tools:[!1,!0].map(i=>({name:i?"uniswap_token_jar_release":"uniswap_token_jar",inputSchema:{type:"object",additionalProperties:!1,required:i?["assets","nonce","maxResourceAmount"]:["assets"],properties:B},async execute(t,m){if(S(t,i?["assets","nonce","maxResourceAmount"]:["assets"]),!Array.isArray(t.assets)||t.assets.length<1||t.assets.length>20)throw new r("Provide 1 to 20 unique assets to release.");let c=t.assets.map(w);if(new Set(c).size!==c.length)throw new r("Token Jar assets must be unique.");let s=n.clientFor(d),e=await s.getBlockNumber(),[x,P,u,f]=await Promise.all([s.readContract({address:a,abi:o,functionName:"RESOURCE",blockNumber:e}),s.readContract({address:a,abi:o,functionName:"TOKEN_JAR",blockNumber:e}),s.readContract({address:a,abi:o,functionName:"threshold",blockNumber:e}),s.readContract({address:a,abi:o,functionName:"nonce",blockNumber:e})]);if(!E(String(P),k)||x===C)throw new r("Releaser deployment does not match the pinned Token Jar and ERC-20 resource.");let p=await R(n,w(x),e),T=await Promise.all(c.map(async l=>({token:await R(n,l,e),amount:(l===C?await s.getBalance({address:k,blockNumber:e}):await s.readContract({address:l,abi:I,functionName:"balanceOf",args:[k],blockNumber:e})).toString()}))),y={payment:{token:p,amount:String(u)},nonce:String(f),assets:T,blockNumber:e.toString()};if(!i)return{...y,summary:"Resource payment buys the listed jar contents; no profit is promised. Release uses a nonce to refuse competing releases."};let J=b(t.maxResourceAmount,"maxResourceAmount"),A=b(t.nonce,"nonce",256,!0);if(A!==BigInt(f)||BigInt(u)>J)throw new r("Token Jar nonce or resource cost changed. Read uniswap_token_jar and confirm fresh terms.");let j=[n.approval(p.address,a,String(u),d),n.unsignedTx({to:a,data:v({abi:o,functionName:"release",args:[A,c,m]}),value:"0",chainId:d,description:`Pay ${u} base units of ${p.address} to release Token Jar assets to ${m}, nonce ${f}.`})];return{...await N(n,j,m,"Exchange resource tokens for Token Jar assets. Check the full payment, assets and recipient in the preview; gas is additional."),...y}}}))}}export{k as a,a as b,o as c,F as d};
@@ -1 +1 @@
1
- import{d as p}from"./M7U3A4EH.js";import{e as a}from"./5KUWLUPM.js";import{a as l}from"./XSD5NL7J.js";import{createHash as x}from"node:crypto";var c=32768,g="wormhole-x402@0.11.0/603aba277a626630d9b9463f713121dc4327325c";function w(s){if(!a(s)||Object.keys(s).length!==1||typeof s.text!="string")throw new l("Provide only text as a string for the local Wormhole scan.");let n=s.text,f=n.length>c||Buffer.byteLength(n,"utf8")>c,i={local:!0,scannerVersion:g,attribution:{provider:"Agent Wormhole",source:"https://github.com/runningoffcode/agent-wormhole"},limitation:"Evadable English instruction-shape rules. Allow is not proof of safety, intent, or coverage of unknown attacks."};if(f)return{...i,decision:"abstain",codes:[],findings:[],scannedPaths:[],charsScanned:0,inputHash:null,reason:"Text exceeds the 32768-byte local scan limit; no text was scanned or hashed."};let u=x("sha256").update(n,"utf8").digest("hex"),m={maxFieldChars:c,maxDecodeDepth:3,maxDepth:12},d=t=>{try{return p(t,m)}catch{return{decision:"abstain",findings:[],scanned:[],charsScanned:0}}},e=[{path:"text",verdict:d(n)}];try{let t=JSON.parse(n);(typeof t=="string"||a(t)||Array.isArray(t))&&e.push({path:"text.json",verdict:d(t)})}catch{}let r=e.flatMap(t=>t.verdict.findings.map(o=>({code:o.code,severity:o.severity,path:t.path,offset:o.offset}))),h=e.some(t=>t.verdict.decision==="refuse")?"refuse":e.some(t=>t.verdict.decision==="abstain")?"abstain":"allow";return{...i,decision:h,codes:[...new Set(r.map(t=>t.code))],findings:r.slice(0,64),findingsTruncated:r.length>64,scannedPaths:e.filter(t=>t.verdict.scanned.length).map(t=>t.path),charsScanned:e.reduce((t,o)=>t+o.verdict.charsScanned,0),inputHash:u,...h==="abstain"?{reason:"The local scanner could not cover all supplied text. Treat the result as unknown."}:{}}}export{c as a,g as b,w as c};
1
+ import{d as p}from"./M7U3A4EH.js";import{e as a}from"./NWNYJ26T.js";import{a as l}from"./XSD5NL7J.js";import{createHash as x}from"node:crypto";var c=32768,g="wormhole-x402@0.11.0/603aba277a626630d9b9463f713121dc4327325c";function w(s){if(!a(s)||Object.keys(s).length!==1||typeof s.text!="string")throw new l("Provide only text as a string for the local Wormhole scan.");let n=s.text,f=n.length>c||Buffer.byteLength(n,"utf8")>c,i={local:!0,scannerVersion:g,attribution:{provider:"Agent Wormhole",source:"https://github.com/runningoffcode/agent-wormhole"},limitation:"Evadable English instruction-shape rules. Allow is not proof of safety, intent, or coverage of unknown attacks."};if(f)return{...i,decision:"abstain",codes:[],findings:[],scannedPaths:[],charsScanned:0,inputHash:null,reason:"Text exceeds the 32768-byte local scan limit; no text was scanned or hashed."};let u=x("sha256").update(n,"utf8").digest("hex"),m={maxFieldChars:c,maxDecodeDepth:3,maxDepth:12},d=t=>{try{return p(t,m)}catch{return{decision:"abstain",findings:[],scanned:[],charsScanned:0}}},e=[{path:"text",verdict:d(n)}];try{let t=JSON.parse(n);(typeof t=="string"||a(t)||Array.isArray(t))&&e.push({path:"text.json",verdict:d(t)})}catch{}let r=e.flatMap(t=>t.verdict.findings.map(o=>({code:o.code,severity:o.severity,path:t.path,offset:o.offset}))),h=e.some(t=>t.verdict.decision==="refuse")?"refuse":e.some(t=>t.verdict.decision==="abstain")?"abstain":"allow";return{...i,decision:h,codes:[...new Set(r.map(t=>t.code))],findings:r.slice(0,64),findingsTruncated:r.length>64,scannedPaths:e.filter(t=>t.verdict.scanned.length).map(t=>t.path),charsScanned:e.reduce((t,o)=>t+o.verdict.charsScanned,0),inputHash:u,...h==="abstain"?{reason:"The local scanner could not cover all supplied text. Treat the result as unknown."}:{}}}export{c as a,g as b,w as c};