@oakagentkit/core 0.2.7 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (508) hide show
  1. package/build/dist/api/addresses.d.ts +9 -0
  2. package/build/dist/api/addresses.js +1 -1
  3. package/build/dist/api/chain.d.ts +4 -0
  4. package/build/dist/api/chain.js +1 -1
  5. package/build/dist/api/history.js +1 -1
  6. package/build/dist/api/identity-link.js +1 -1
  7. package/build/dist/api/metadata.js +1 -1
  8. package/build/dist/api/modules/beefy/boosts.js +1 -1
  9. package/build/dist/api/modules/beefy/clm.d.ts +9 -0
  10. package/build/dist/api/modules/beefy/clm.js +1 -1
  11. package/build/dist/api/modules/beefy/guard.js +1 -1
  12. package/build/dist/api/modules/beefy/index.js +1 -1
  13. package/build/dist/api/modules/beefy/liquidity.js +1 -1
  14. package/build/dist/api/modules/beefy/management.js +1 -1
  15. package/build/dist/api/modules/beefy/vaults.js +1 -1
  16. package/build/dist/api/modules/borro/abi.d.ts +54 -0
  17. package/build/dist/api/modules/borro/abi.js +1 -1
  18. package/build/dist/api/modules/borro/actions.d.ts +14 -1
  19. package/build/dist/api/modules/borro/actions.js +1 -1
  20. package/build/dist/api/modules/borro/checks.js +1 -1
  21. package/build/dist/api/modules/borro/copy.d.ts +10 -2
  22. package/build/dist/api/modules/borro/copy.js +1 -1
  23. package/build/dist/api/modules/borro/index.js +1 -1
  24. package/build/dist/api/modules/borro/liquidity.js +1 -1
  25. package/build/dist/api/modules/borro/pins.d.ts +30 -14
  26. package/build/dist/api/modules/borro/pins.js +1 -1
  27. package/build/dist/api/modules/borro/positions.js +1 -1
  28. package/build/dist/api/modules/borro/reader.js +1 -1
  29. package/build/dist/api/modules/borro/types.d.ts +1 -0
  30. package/build/dist/api/modules/chop/actions.js +1 -1
  31. package/build/dist/api/modules/chop/checks.js +1 -1
  32. package/build/dist/api/modules/chop/copy.js +1 -1
  33. package/build/dist/api/modules/chop/guard.js +1 -1
  34. package/build/dist/api/modules/chop/index.js +1 -1
  35. package/build/dist/api/modules/chop/pins.d.ts +13 -0
  36. package/build/dist/api/modules/chop/pins.js +1 -1
  37. package/build/dist/api/modules/chop/positions.js +1 -1
  38. package/build/dist/api/modules/chop/reader.js +1 -1
  39. package/build/dist/api/modules/clanker/extensions.js +1 -1
  40. package/build/dist/api/modules/clanker/index.js +1 -1
  41. package/build/dist/api/modules/clanker/manage.js +1 -1
  42. package/build/dist/api/modules/clanker/pool-config.js +1 -1
  43. package/build/dist/api/modules/clanker/protocol.js +1 -1
  44. package/build/dist/api/modules/clanker/state.js +1 -1
  45. package/build/dist/api/modules/earn/copy.d.ts +6 -6
  46. package/build/dist/api/modules/earn/copy.js +1 -1
  47. package/build/dist/api/modules/earn/cost.d.ts +1 -1
  48. package/build/dist/api/modules/earn/cost.js +1 -1
  49. package/build/dist/api/modules/earn/index.js +1 -1
  50. package/build/dist/api/modules/earn/lp.js +1 -1
  51. package/build/dist/api/modules/earn/options.js +1 -1
  52. package/build/dist/api/modules/erc8004/common.js +1 -1
  53. package/build/dist/api/modules/erc8004/domain.js +1 -1
  54. package/build/dist/api/modules/erc8004/index.js +1 -1
  55. package/build/dist/api/modules/erc8004/management.js +1 -1
  56. package/build/dist/api/modules/erc8004/reputation.js +1 -1
  57. package/build/dist/api/modules/erc8004/services.js +1 -1
  58. package/build/dist/api/modules/erc8004/thesis.d.ts +61 -0
  59. package/build/dist/api/modules/erc8004/thesis.js +1 -0
  60. package/build/dist/api/modules/erc8004/validation.js +1 -1
  61. package/build/dist/api/modules/fobo/client.d.ts +9 -0
  62. package/build/dist/api/modules/fobo/client.js +1 -0
  63. package/build/dist/api/modules/fobo/index.d.ts +16 -0
  64. package/build/dist/api/modules/fobo/index.js +1 -0
  65. package/build/dist/api/modules/fobo/intent.d.ts +243 -0
  66. package/build/dist/api/modules/fobo/intent.js +1 -0
  67. package/build/dist/api/modules/fobo/pins.d.ts +178 -0
  68. package/build/dist/api/modules/fobo/pins.js +1 -0
  69. package/build/dist/api/modules/fobo/steps.d.ts +25 -0
  70. package/build/dist/api/modules/fobo/steps.js +1 -0
  71. package/build/dist/api/modules/fobo/verify.d.ts +89 -0
  72. package/build/dist/api/modules/fobo/verify.js +1 -0
  73. package/build/dist/api/modules/gloam/copy.d.ts +1 -1
  74. package/build/dist/api/modules/gloam/copy.js +1 -1
  75. package/build/dist/api/modules/gloam/index.js +1 -1
  76. package/build/dist/api/modules/grove/index.js +1 -1
  77. package/build/dist/api/modules/heyresearch/builder-feed.js +1 -1
  78. package/build/dist/api/modules/heyresearch/index.js +1 -1
  79. package/build/dist/api/modules/heyresearch/public-reads.js +1 -1
  80. package/build/dist/api/modules/heyresearch/token-facts.js +1 -1
  81. package/build/dist/api/modules/hoodag/chain-reads.js +1 -1
  82. package/build/dist/api/modules/hoodag/index.d.ts +12 -1
  83. package/build/dist/api/modules/hoodag/index.js +1 -1
  84. package/build/dist/api/modules/hoodag/management.js +1 -1
  85. package/build/dist/api/modules/hoodag/public-reads.js +1 -1
  86. package/build/dist/api/modules/hoodag/reconstruct.d.ts +14 -0
  87. package/build/dist/api/modules/hoodag/reconstruct.js +1 -1
  88. package/build/dist/api/modules/hoodlock/airdrop.js +1 -1
  89. package/build/dist/api/modules/hoodlock/buyback.js +1 -1
  90. package/build/dist/api/modules/hoodlock/commerce.js +1 -1
  91. package/build/dist/api/modules/hoodlock/fee.js +1 -1
  92. package/build/dist/api/modules/hoodlock/guard.js +1 -1
  93. package/build/dist/api/modules/hoodlock/index.js +1 -1
  94. package/build/dist/api/modules/hoodlock/lifecycle.js +1 -1
  95. package/build/dist/api/modules/hoodlock/locks-burn.js +1 -1
  96. package/build/dist/api/modules/hoodlock/public.js +1 -1
  97. package/build/dist/api/modules/hookr/actions.js +1 -1
  98. package/build/dist/api/modules/hookr/addons.js +1 -1
  99. package/build/dist/api/modules/hookr/agent-gate.js +1 -1
  100. package/build/dist/api/modules/hookr/contracts.js +1 -1
  101. package/build/dist/api/modules/hookr/create-cancel.js +1 -1
  102. package/build/dist/api/modules/hookr/discovery.js +1 -1
  103. package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
  104. package/build/dist/api/modules/hookr/index.js +1 -1
  105. package/build/dist/api/modules/hookr/launch-options.js +1 -1
  106. package/build/dist/api/modules/hookr/launch-receipt.js +1 -1
  107. package/build/dist/api/modules/hookr/launch.js +1 -1
  108. package/build/dist/api/modules/hookr/liquidity.js +1 -1
  109. package/build/dist/api/modules/hookr/lp-positions.js +1 -1
  110. package/build/dist/api/modules/hookr/lp-reads.js +1 -1
  111. package/build/dist/api/modules/hookr/lp-receipt.js +1 -1
  112. package/build/dist/api/modules/hookr/lp-state.js +1 -1
  113. package/build/dist/api/modules/hookr/public-reads.js +1 -1
  114. package/build/dist/api/modules/hookr/read-utils.js +1 -1
  115. package/build/dist/api/modules/hookr/relay.js +1 -1
  116. package/build/dist/api/modules/hookr/revenue.js +1 -1
  117. package/build/dist/api/modules/kyberswap/index.d.ts +2 -1
  118. package/build/dist/api/modules/kyberswap/index.js +1 -1
  119. package/build/dist/api/modules/kyberswap/source-pools.js +1 -1
  120. package/build/dist/api/modules/layerbank/abi.js +1 -1
  121. package/build/dist/api/modules/layerbank/actions.js +1 -1
  122. package/build/dist/api/modules/layerbank/checks.js +1 -1
  123. package/build/dist/api/modules/layerbank/index.js +1 -1
  124. package/build/dist/api/modules/layerbank/merkl.js +1 -1
  125. package/build/dist/api/modules/layerbank/reader.js +1 -1
  126. package/build/dist/api/modules/layerbank/reserve.js +1 -1
  127. package/build/dist/api/modules/lighter/index.js +1 -1
  128. package/build/dist/api/modules/longbow/administration.js +1 -1
  129. package/build/dist/api/modules/longbow/analytics.js +1 -1
  130. package/build/dist/api/modules/longbow/fixed.js +1 -1
  131. package/build/dist/api/modules/longbow/index.js +1 -1
  132. package/build/dist/api/modules/longbow/nft.js +1 -1
  133. package/build/dist/api/modules/longbow/rebates.js +1 -1
  134. package/build/dist/api/modules/longbow/staking.js +1 -1
  135. package/build/dist/api/modules/meridian/index.js +1 -1
  136. package/build/dist/api/modules/meridian/markets.js +1 -1
  137. package/build/dist/api/modules/meridian/predict-read.js +1 -1
  138. package/build/dist/api/modules/meridian/rfq.js +1 -1
  139. package/build/dist/api/modules/merkl/discovery.js +1 -1
  140. package/build/dist/api/modules/merkl/index.js +1 -1
  141. package/build/dist/api/modules/merkl/manage.js +1 -1
  142. package/build/dist/api/modules/merkl/protocol.js +1 -1
  143. package/build/dist/api/modules/morpho/allocator.js +1 -1
  144. package/build/dist/api/modules/morpho/bundles.js +1 -1
  145. package/build/dist/api/modules/morpho/in-kind.js +1 -1
  146. package/build/dist/api/modules/morpho/index.js +1 -1
  147. package/build/dist/api/modules/morpho/local-guard.d.ts +2 -1
  148. package/build/dist/api/modules/morpho/local-guard.js +1 -1
  149. package/build/dist/api/modules/morpho/midnight.js +1 -1
  150. package/build/dist/api/modules/morpho/protocol.js +1 -1
  151. package/build/dist/api/modules/morpho/surface.js +1 -1
  152. package/build/dist/api/modules/morpho/vault-management.js +1 -1
  153. package/build/dist/api/modules/morpho/vault-tools.js +1 -1
  154. package/build/dist/api/modules/morpho/vault-v2.js +1 -1
  155. package/build/dist/api/modules/netnet/card-plan.js +1 -1
  156. package/build/dist/api/modules/netnet/card-policy.d.ts +1 -0
  157. package/build/dist/api/modules/netnet/card-policy.js +1 -1
  158. package/build/dist/api/modules/netnet/card-read.js +1 -1
  159. package/build/dist/api/modules/netnet/card-recovery.js +1 -1
  160. package/build/dist/api/modules/netnet/desk-action.js +1 -1
  161. package/build/dist/api/modules/netnet/desk-read.js +1 -1
  162. package/build/dist/api/modules/netnet/financial.js +1 -1
  163. package/build/dist/api/modules/netnet/index.js +1 -1
  164. package/build/dist/api/modules/netnet/staking.js +1 -1
  165. package/build/dist/api/modules/orbio/index.d.ts +6 -0
  166. package/build/dist/api/modules/orbio/index.js +1 -1
  167. package/build/dist/api/modules/orbio/positions.js +1 -1
  168. package/build/dist/api/modules/pendle/costs.js +1 -1
  169. package/build/dist/api/modules/pendle/index.js +1 -1
  170. package/build/dist/api/modules/pendle/markets.js +1 -1
  171. package/build/dist/api/modules/pendle/positions.js +1 -1
  172. package/build/dist/api/modules/pendle/pricecheck.js +1 -1
  173. package/build/dist/api/modules/pendle/reader.js +1 -1
  174. package/build/dist/api/modules/pendle/redeem.js +1 -1
  175. package/build/dist/api/modules/pendle/trade.js +1 -1
  176. package/build/dist/api/modules/pendle/validate.js +1 -1
  177. package/build/dist/api/modules/pendle/verify.js +1 -1
  178. package/build/dist/api/modules/pons/claim.js +1 -1
  179. package/build/dist/api/modules/pons/index.js +1 -1
  180. package/build/dist/api/modules/pons/launch-status.js +1 -1
  181. package/build/dist/api/modules/pons/prices.js +1 -1
  182. package/build/dist/api/modules/pons/reads.js +1 -1
  183. package/build/dist/api/modules/pons/swap-terms.d.ts +2 -8
  184. package/build/dist/api/modules/pons/swap-terms.js +1 -1
  185. package/build/dist/api/modules/pons/trade.js +1 -1
  186. package/build/dist/api/modules/poolstrade/index.js +1 -1
  187. package/build/dist/api/modules/priors/coverage.js +1 -1
  188. package/build/dist/api/modules/priors/discovery.js +1 -1
  189. package/build/dist/api/modules/priors/features.js +1 -1
  190. package/build/dist/api/modules/priors/holdings.js +1 -1
  191. package/build/dist/api/modules/priors/index.js +1 -1
  192. package/build/dist/api/modules/priors/integration.js +1 -1
  193. package/build/dist/api/modules/priors/market.js +1 -1
  194. package/build/dist/api/modules/priors/pt.js +1 -1
  195. package/build/dist/api/modules/priors/savings-exit.js +1 -1
  196. package/build/dist/api/modules/priors/starter-line.js +1 -1
  197. package/build/dist/api/modules/priors/stock-swap.js +1 -1
  198. package/build/dist/api/modules/relay/api.js +1 -1
  199. package/build/dist/api/modules/relay/bootstrap.js +1 -1
  200. package/build/dist/api/modules/relay/discovery.js +1 -1
  201. package/build/dist/api/modules/relay/inbound.js +1 -1
  202. package/build/dist/api/modules/relay/index.js +1 -1
  203. package/build/dist/api/modules/relay/order.js +1 -1
  204. package/build/dist/api/modules/relay/outbound-status.js +1 -1
  205. package/build/dist/api/modules/relay/readiness.js +1 -1
  206. package/build/dist/api/modules/relay/reads.js +1 -1
  207. package/build/dist/api/modules/relay/vaults.js +1 -1
  208. package/build/dist/api/modules/spark/actions.js +1 -1
  209. package/build/dist/api/modules/spark/details.js +1 -1
  210. package/build/dist/api/modules/spark/index.js +1 -1
  211. package/build/dist/api/modules/spark/management.js +1 -1
  212. package/build/dist/api/modules/steakhouse/analytics.js +1 -1
  213. package/build/dist/api/modules/steakhouse/erc4626.js +1 -1
  214. package/build/dist/api/modules/steakhouse/index.js +1 -1
  215. package/build/dist/api/modules/steakhouse/local-guard.js +1 -1
  216. package/build/dist/api/modules/steakhouse/management.js +1 -1
  217. package/build/dist/api/modules/steakhouse/v2-exit.js +1 -1
  218. package/build/dist/api/modules/tickerspring/basket-routes.js +1 -1
  219. package/build/dist/api/modules/tickerspring/contract-reads.js +1 -1
  220. package/build/dist/api/modules/tickerspring/discovery.js +1 -1
  221. package/build/dist/api/modules/tickerspring/exit-preview.js +1 -1
  222. package/build/dist/api/modules/tickerspring/guards.js +1 -1
  223. package/build/dist/api/modules/tickerspring/index.js +1 -1
  224. package/build/dist/api/modules/tickerspring/journeys.js +1 -1
  225. package/build/dist/api/modules/tickerspring/ladder.js +1 -1
  226. package/build/dist/api/modules/tickerspring/maker.js +1 -1
  227. package/build/dist/api/modules/tickerspring/order-accounting.js +1 -1
  228. package/build/dist/api/modules/tickerspring/research.js +1 -1
  229. package/build/dist/api/modules/tickerspring/strategies.js +1 -1
  230. package/build/dist/api/modules/uniswap/auction-create.js +1 -1
  231. package/build/dist/api/modules/uniswap/auction.js +1 -1
  232. package/build/dist/api/modules/uniswap/batch.js +1 -1
  233. package/build/dist/api/modules/uniswap/common.js +1 -1
  234. package/build/dist/api/modules/uniswap/fees.js +1 -1
  235. package/build/dist/api/modules/uniswap/index.js +1 -1
  236. package/build/dist/api/modules/uniswap/local-guard.js +1 -1
  237. package/build/dist/api/modules/uniswap/oracle.js +1 -1
  238. package/build/dist/api/modules/uniswap/pool-math.js +1 -1
  239. package/build/dist/api/modules/uniswap/pools.js +1 -1
  240. package/build/dist/api/modules/uniswap/position.js +1 -1
  241. package/build/dist/api/modules/uniswap/protocol.js +1 -1
  242. package/build/dist/api/modules/uniswap/quote-guard.js +1 -1
  243. package/build/dist/api/modules/uniswap/token-jar.js +1 -1
  244. package/build/dist/api/modules/uniswap/trade-batch.js +1 -1
  245. package/build/dist/api/modules/uniswap/trade.js +1 -1
  246. package/build/dist/api/modules/uniswap/v2.js +1 -1
  247. package/build/dist/api/modules/uniswap/v3.js +1 -1
  248. package/build/dist/api/modules/uniswap/v4.js +1 -1
  249. package/build/dist/api/modules/uniswap/wrap.js +1 -1
  250. package/build/dist/api/modules/upoch/copy.d.ts +5 -0
  251. package/build/dist/api/modules/upoch/copy.js +1 -0
  252. package/build/dist/api/modules/upoch/index.d.ts +8 -0
  253. package/build/dist/api/modules/upoch/index.js +1 -0
  254. package/build/dist/api/modules/upoch/pins.d.ts +8 -0
  255. package/build/dist/api/modules/upoch/pins.js +1 -0
  256. package/build/dist/api/modules/upoch/reads.d.ts +509 -0
  257. package/build/dist/api/modules/upoch/reads.js +1 -0
  258. package/build/dist/api/modules/velora/claims.js +1 -1
  259. package/build/dist/api/modules/velora/delta-reads.js +1 -1
  260. package/build/dist/api/modules/velora/index.js +1 -1
  261. package/build/dist/api/modules/wormhole/index.js +1 -1
  262. package/build/dist/api/modules/wormhole/x402-client.d.ts +17 -1
  263. package/build/dist/api/modules/wormhole/x402-client.js +1 -1
  264. package/build/dist/api/positions.js +1 -1
  265. package/build/dist/api/pricenote.js +1 -1
  266. package/build/dist/api/prices.d.ts +5 -0
  267. package/build/dist/api/prices.js +1 -1
  268. package/build/dist/api/pricing.js +1 -1
  269. package/build/dist/api/rpc.js +1 -1
  270. package/build/dist/api/secret-fields.d.ts +2 -0
  271. package/build/dist/api/secret-fields.js +1 -1
  272. package/build/dist/api/send.js +1 -1
  273. package/build/dist/api/signing-registry.js +1 -1
  274. package/build/dist/api/signing.js +1 -1
  275. package/build/dist/api/simulate.js +1 -1
  276. package/build/dist/api/swap.d.ts +1 -0
  277. package/build/dist/api/swap.js +1 -1
  278. package/build/dist/api/tokens.js +1 -1
  279. package/build/dist/api/tool-policy.d.ts +1 -0
  280. package/build/dist/api/tool-policy.js +1 -1
  281. package/build/dist/api/universal-router.d.ts +45 -0
  282. package/build/dist/api/universal-router.js +1 -0
  283. package/build/dist/api/usd-estimate.js +1 -1
  284. package/build/dist/chunks/{ZOMFHTB2.js → 22TU5PFT.js} +1 -1
  285. package/build/dist/chunks/23HNDJ76.js +2 -0
  286. package/build/dist/chunks/{ZFU65MB4.js → 257N7343.js} +1 -1
  287. package/build/dist/chunks/{F3VDVTMS.js → 27PVS6BU.js} +1 -1
  288. package/build/dist/chunks/{N245WC5R.js → 2JWAFLJU.js} +1 -1
  289. package/build/dist/chunks/{GQYV4TFO.js → 2OVJ2BTJ.js} +1 -1
  290. package/build/dist/chunks/{JS53DQVT.js → 35LXCSHY.js} +1 -1
  291. package/build/dist/chunks/{V37L4DU4.js → 3A2IKFTV.js} +1 -1
  292. package/build/dist/chunks/{OYPAVXGQ.js → 3BMM3V4P.js} +1 -1
  293. package/build/dist/chunks/{ZKZUS3QU.js → 3FU6XP6S.js} +1 -1
  294. package/build/dist/chunks/{BB765L75.js → 3PHJUFU2.js} +1 -1
  295. package/build/dist/chunks/{FWIFTPSE.js → 3PU2SD3U.js} +1 -1
  296. package/build/dist/chunks/{SBY4RJ7I.js → 3ZH5SOC2.js} +1 -1
  297. package/build/dist/chunks/43BG2JRB.js +1 -0
  298. package/build/dist/chunks/{YTLH4M4Y.js → 47HSRR7G.js} +1 -1
  299. package/build/dist/chunks/4NBXBKOX.js +2 -0
  300. package/build/dist/chunks/{EZZM2GQT.js → 4NDIYRH5.js} +1 -1
  301. package/build/dist/chunks/{FOKEFXGP.js → 4PLLS6CT.js} +1 -1
  302. package/build/dist/chunks/4RCYYN6O.js +1 -0
  303. package/build/dist/chunks/{XHYFISVV.js → 4Z3IGMU6.js} +1 -1
  304. package/build/dist/chunks/4ZD5D2UP.js +1 -0
  305. package/build/dist/chunks/{CSDN4MYP.js → 5GQJVKVY.js} +1 -1
  306. package/build/dist/chunks/{QFSBDPLN.js → 65OITTDL.js} +1 -1
  307. package/build/dist/chunks/{4FPV4CRC.js → 6D3XNCOX.js} +1 -1
  308. package/build/dist/chunks/{DSTMEY5F.js → 6F527FLN.js} +1 -1
  309. package/build/dist/chunks/{O3JWCJIF.js → 6GWXPQZ6.js} +1 -1
  310. package/build/dist/chunks/{32RXFUOH.js → 73BZPPRS.js} +1 -1
  311. package/build/dist/chunks/75SULXNT.js +1 -0
  312. package/build/dist/chunks/{WU7XIAXB.js → 7EACRKFV.js} +1 -1
  313. package/build/dist/chunks/{SKEKXEUU.js → 7FIEBJOZ.js} +1 -1
  314. package/build/dist/chunks/{4GNUXN4K.js → 7FZXSYFD.js} +1 -1
  315. package/build/dist/chunks/{ZP36DSOD.js → 7TSIF3F4.js} +1 -1
  316. package/build/dist/chunks/{AMTRDPVO.js → 7U62MMUQ.js} +1 -1
  317. package/build/dist/chunks/{DW4V5PUY.js → 7VH6JQ2H.js} +1 -1
  318. package/build/dist/chunks/A3BJSQ23.js +1 -0
  319. package/build/dist/chunks/{YSMWCKIX.js → ADIPEGNN.js} +1 -1
  320. package/build/dist/chunks/AG2G7BHH.js +6 -0
  321. package/build/dist/chunks/AIYNFIG6.js +1 -0
  322. package/build/dist/chunks/ANIF3JMV.js +4 -0
  323. package/build/dist/chunks/{4JTTA3BX.js → AWV24X7F.js} +1 -1
  324. package/build/dist/chunks/{7QKYDNF6.js → AXHFNE6L.js} +1 -1
  325. package/build/dist/chunks/{WOGWLFAL.js → BGVC5NI6.js} +1 -1
  326. package/build/dist/chunks/BJK75C7G.js +1 -0
  327. package/build/dist/chunks/BSX4LFYI.js +1 -0
  328. package/build/dist/chunks/{OYJFXEDU.js → BZPFPQ2I.js} +1 -1
  329. package/build/dist/chunks/{5PI57UC2.js → C76D54YG.js} +1 -1
  330. package/build/dist/chunks/{TDZTC5WR.js → DBOGRUPS.js} +1 -1
  331. package/build/dist/chunks/{HHO5ISMM.js → DCGNVMKG.js} +1 -1
  332. package/build/dist/chunks/{Y77EVVT4.js → DGDMRATN.js} +1 -1
  333. package/build/dist/chunks/{EGZREEG2.js → DLNA5272.js} +1 -1
  334. package/build/dist/chunks/{TM7Z5SA4.js → DMDOSHV7.js} +1 -1
  335. package/build/dist/chunks/{WHVZ372B.js → DRLBTB4E.js} +1 -1
  336. package/build/dist/chunks/DXAPKN7H.js +1 -0
  337. package/build/dist/chunks/{FZ6IJZZM.js → E76Z2TT4.js} +1 -1
  338. package/build/dist/chunks/{67BWOVET.js → EHGH646D.js} +1 -1
  339. package/build/dist/chunks/{KKPMOAVI.js → ELHRXA5U.js} +1 -1
  340. package/build/dist/chunks/{PZEF5LBL.js → ETMD747Y.js} +1 -1
  341. package/build/dist/chunks/{XCKTE4ON.js → F7MGYRPU.js} +1 -1
  342. package/build/dist/chunks/{MRMR4QHA.js → FAH7FKUT.js} +1 -1
  343. package/build/dist/chunks/FXOFR432.js +1 -0
  344. package/build/dist/chunks/{VHV6WQ5F.js → G2AA73ZE.js} +1 -1
  345. package/build/dist/chunks/{JWR5XVP2.js → GBIBRYOV.js} +1 -1
  346. package/build/dist/chunks/{FNGIJKMZ.js → GDOHHXNH.js} +1 -1
  347. package/build/dist/chunks/{BZ34ZR65.js → GGMVT5A6.js} +1 -1
  348. package/build/dist/chunks/GK3D7OKG.js +1 -0
  349. package/build/dist/chunks/{2OKYXT25.js → GQITAJVF.js} +1 -1
  350. package/build/dist/chunks/GYPMUYB5.js +1 -0
  351. package/build/dist/chunks/H3E7UD2X.js +1 -0
  352. package/build/dist/chunks/{GDRQ2ANN.js → H64QC4QR.js} +1 -1
  353. package/build/dist/chunks/HFVXNKA5.js +1 -0
  354. package/build/dist/chunks/HHYE42JG.js +21 -0
  355. package/build/dist/chunks/{U363GQTF.js → HIG7JY3J.js} +1 -1
  356. package/build/dist/chunks/{XWKK75TO.js → HOBIXKGO.js} +1 -1
  357. package/build/dist/chunks/HQIS3QI7.js +3 -0
  358. package/build/dist/chunks/{UOCRYXAB.js → HRAHGYNK.js} +1 -1
  359. package/build/dist/chunks/{GLF7WEY2.js → HUKDISRE.js} +1 -1
  360. package/build/dist/chunks/{GSFHM5L3.js → HZSYMGJ2.js} +1 -1
  361. package/build/dist/chunks/{FJLJ7ZQ5.js → I4473OC6.js} +1 -1
  362. package/build/dist/chunks/IBL6TL2Q.js +1 -0
  363. package/build/dist/chunks/{3DNJTJ2X.js → IJ4HZIDG.js} +1 -1
  364. package/build/dist/chunks/{OARVU3RC.js → IPU656WB.js} +1 -1
  365. package/build/dist/chunks/{HCBX4NFM.js → IT2JLILU.js} +1 -1
  366. package/build/dist/chunks/{REWXG6X6.js → JDSSYT6R.js} +1 -1
  367. package/build/dist/chunks/{XRDXFHIK.js → JFWJBZ7M.js} +1 -1
  368. package/build/dist/chunks/{TPEKCXVE.js → JTPHZCO3.js} +1 -1
  369. package/build/dist/chunks/{CSOO4SW7.js → K4GUZ5QS.js} +1 -1
  370. package/build/dist/chunks/{BAIY32AV.js → KLEJ3W4T.js} +1 -1
  371. package/build/dist/chunks/{ACH4BSME.js → KOKLM63Q.js} +1 -1
  372. package/build/dist/chunks/{7D73A6KS.js → KVVBT43U.js} +1 -1
  373. package/build/dist/chunks/{CO4GCF4L.js → KXX7ZBFY.js} +1 -1
  374. package/build/dist/chunks/{I6PQW2JI.js → L2AE32SL.js} +1 -1
  375. package/build/dist/chunks/{WUT7TZYM.js → LCH6F5HT.js} +1 -1
  376. package/build/dist/chunks/LEV5SNNC.js +3 -0
  377. package/build/dist/chunks/{SPRVVJXI.js → LFSJDFMY.js} +1 -1
  378. package/build/dist/chunks/{6UVGQYZ3.js → LGLWEGPY.js} +1 -1
  379. package/build/dist/chunks/{PV4AK32X.js → LQSPWRHN.js} +1 -1
  380. package/build/dist/chunks/{C3WBHFLX.js → LTDF2LNP.js} +1 -1
  381. package/build/dist/chunks/{5HIHUYA4.js → M4AGEGWW.js} +1 -1
  382. package/build/dist/chunks/{ARI72OYT.js → M6SQPOOL.js} +1 -1
  383. package/build/dist/chunks/{SOTYQGPT.js → M7CQPTRK.js} +1 -1
  384. package/build/dist/chunks/{XPEDQBLI.js → MGVX5EUH.js} +1 -1
  385. package/build/dist/chunks/{C5ZZAYXD.js → MI5HZDMH.js} +1 -1
  386. package/build/dist/chunks/{APHNOGNS.js → MQ37QX6U.js} +1 -1
  387. package/build/dist/chunks/MQ5F2VOK.js +1 -0
  388. package/build/dist/chunks/{JKD2B6OX.js → MSRCJ2BS.js} +1 -1
  389. package/build/dist/chunks/{JKRBGAX2.js → NAO7VWZF.js} +1 -1
  390. package/build/dist/chunks/{RLMVA575.js → NDSNE6PS.js} +1 -1
  391. package/build/dist/chunks/{RT7IU6TI.js → NMJVQX5M.js} +1 -1
  392. package/build/dist/chunks/NQ4MTIU3.js +1 -0
  393. package/build/dist/chunks/{IEG6GLFR.js → NTUXDIY6.js} +1 -1
  394. package/build/dist/chunks/{F4UQEPJT.js → NUERUFH7.js} +1 -1
  395. package/build/dist/chunks/NV6FDIYT.js +1 -0
  396. package/build/dist/chunks/O2J5I4VA.js +1 -0
  397. package/build/dist/chunks/{XVJ7ILKK.js → O3CC5SRM.js} +1 -1
  398. package/build/dist/chunks/{2SUHQWND.js → O4S6XAYV.js} +1 -1
  399. package/build/dist/chunks/{TAEZTP4L.js → O5QTITN6.js} +1 -1
  400. package/build/dist/chunks/{NA424YAL.js → OB7BFDOV.js} +1 -1
  401. package/build/dist/chunks/{523ZIR3J.js → ODV3XT5U.js} +1 -1
  402. package/build/dist/chunks/{GW5IXLKU.js → OI3N4EW4.js} +1 -1
  403. package/build/dist/chunks/{FL5SSHUL.js → OIQTZOBN.js} +1 -1
  404. package/build/dist/chunks/OLDQV43V.js +1 -0
  405. package/build/dist/chunks/OOPMZIG7.js +1 -0
  406. package/build/dist/chunks/{XYPGLG6A.js → OSMOBKRQ.js} +1 -1
  407. package/build/dist/chunks/{OZ5MDUD2.js → OVM4QIET.js} +1 -1
  408. package/build/dist/chunks/{N4XNNXOJ.js → OY5W7ZSL.js} +1 -1
  409. package/build/dist/chunks/{GRSXWQWD.js → PDGYM2WG.js} +1 -1
  410. package/build/dist/chunks/{UQEEF5W5.js → PDPTJMTJ.js} +1 -1
  411. package/build/dist/chunks/PEHXHQVA.js +1 -0
  412. package/build/dist/chunks/{JOKL5L6X.js → PKYQ3XVA.js} +1 -1
  413. package/build/dist/chunks/PMFR47H3.js +1 -0
  414. package/build/dist/chunks/{N6GIC7HJ.js → PWJVC2FV.js} +1 -1
  415. package/build/dist/chunks/{753HZZTY.js → QBYV7NXH.js} +1 -1
  416. package/build/dist/chunks/QHV5GORV.js +1 -0
  417. package/build/dist/chunks/{2LWBN35N.js → QIB6OMQV.js} +1 -1
  418. package/build/dist/chunks/{TK55VASJ.js → QMNUB2GM.js} +1 -1
  419. package/build/dist/chunks/{HKVQ646Q.js → QN45T4N3.js} +1 -1
  420. package/build/dist/chunks/{J73ATSEQ.js → QPY6UTLU.js} +1 -1
  421. package/build/dist/chunks/{YUHNPUNK.js → R73R4KN3.js} +1 -1
  422. package/build/dist/chunks/{RLI4JDOL.js → RA7DOR7F.js} +1 -1
  423. package/build/dist/chunks/{VR344DAZ.js → RN3WUJIO.js} +1 -1
  424. package/build/dist/chunks/RUSXMQSJ.js +1 -0
  425. package/build/dist/chunks/{D742AYEV.js → RUTSEGGD.js} +1 -1
  426. package/build/dist/chunks/{4Q2ZBZXM.js → RXP7ZUPY.js} +1 -1
  427. package/build/dist/chunks/{TFDPEAVZ.js → S4JUFCT4.js} +1 -1
  428. package/build/dist/chunks/{DYYEA5HB.js → SMKO7GKX.js} +1 -1
  429. package/build/dist/chunks/{C75MT5SD.js → SNCV6HV7.js} +1 -1
  430. package/build/dist/chunks/{HIX5N25Z.js → SOJHYMD7.js} +1 -1
  431. package/build/dist/chunks/{JLRHM2DQ.js → SUNTJ6IU.js} +1 -1
  432. package/build/dist/chunks/{4JRXEN7C.js → THL4TMQW.js} +2 -2
  433. package/build/dist/chunks/TI727O2H.js +1 -0
  434. package/build/dist/chunks/{PV5FDT6O.js → TXGZ6NWN.js} +1 -1
  435. package/build/dist/chunks/{Q2ACLVWR.js → UBI3HBXD.js} +1 -1
  436. package/build/dist/chunks/{YMV5TL5C.js → UEHN2IDF.js} +1 -1
  437. package/build/dist/chunks/{ZF2VPDRQ.js → UHIJMDD2.js} +1 -1
  438. package/build/dist/chunks/UJQYOTO5.js +1 -0
  439. package/build/dist/chunks/{VTPT5544.js → USEF3QKG.js} +1 -1
  440. package/build/dist/chunks/{LR4XTZ37.js → UYULQHZJ.js} +1 -1
  441. package/build/dist/chunks/{YWZQJJYY.js → V4UJMUIB.js} +1 -1
  442. package/build/dist/chunks/{7VC53B5X.js → V5YSJKRH.js} +13 -13
  443. package/build/dist/chunks/{INOYMBWE.js → VC5ZCQYZ.js} +1 -1
  444. package/build/dist/chunks/{M7ZXDLKM.js → VDJPDIBV.js} +1 -1
  445. package/build/dist/chunks/{2FHELZ7Y.js → VFM2BICB.js} +1 -1
  446. package/build/dist/chunks/{TE6D3OIX.js → VOJULRNU.js} +1 -1
  447. package/build/dist/chunks/{UEDGYZOC.js → VVAM3EAK.js} +1 -1
  448. package/build/dist/chunks/VVJO6OYK.js +1 -0
  449. package/build/dist/chunks/{JESMX2UC.js → VXCGMALF.js} +1 -1
  450. package/build/dist/chunks/{NUFZUKYS.js → W32UECOL.js} +1 -1
  451. package/build/dist/chunks/{UUID2E22.js → W3DGFMQE.js} +1 -1
  452. package/build/dist/chunks/W7OCS4AM.js +6 -0
  453. package/build/dist/chunks/{DNNFKDZR.js → W7QNSNOH.js} +1 -1
  454. package/build/dist/chunks/{2MZXTOZU.js → WAKZWSHB.js} +1 -1
  455. package/build/dist/chunks/{HM72DH4V.js → WRUTW6CG.js} +1 -1
  456. package/build/dist/chunks/{VYYSL557.js → WSILNJS2.js} +1 -1
  457. package/build/dist/chunks/{L646YWDP.js → X24YTJST.js} +1 -1
  458. package/build/dist/chunks/{FOD34G2H.js → XL3W7DAQ.js} +1 -1
  459. package/build/dist/chunks/{2E4I7CJ7.js → XRDLMTBJ.js} +1 -1
  460. package/build/dist/chunks/{GG24LO2R.js → XVOW6UCI.js} +1 -1
  461. package/build/dist/chunks/XW3VGWXK.js +1 -0
  462. package/build/dist/chunks/{6WD4HHID.js → Y2QADJOB.js} +1 -1
  463. package/build/dist/chunks/Y64GFBTA.js +1 -0
  464. package/build/dist/chunks/Y7HBFQYG.js +1 -0
  465. package/build/dist/chunks/{ARLGF5MU.js → YGW4ODAP.js} +1 -1
  466. package/build/dist/chunks/YRSAZTTC.js +7 -0
  467. package/build/dist/chunks/YW4W3LPQ.js +1 -0
  468. package/build/dist/chunks/{3VBIRLU3.js → YXXK6EPI.js} +1 -1
  469. package/build/dist/chunks/{EH5G4O3U.js → Z2QV6EZY.js} +1 -1
  470. package/build/dist/chunks/Z3IBPCY4.js +2 -0
  471. package/build/dist/chunks/{H5DY7CNB.js → Z7FGEWO2.js} +1 -1
  472. package/build/dist/chunks/{KDGSYNOP.js → ZDCCFEVL.js} +1 -1
  473. package/build/dist/chunks/{4RQAOOO2.js → ZOLHVZDK.js} +1 -1
  474. package/build/dist/chunks/{AI3VAPA3.js → ZSVAGOF2.js} +1 -1
  475. package/build/dist/chunks/{EVBHQQQG.js → ZTKT3ZQK.js} +1 -1
  476. package/build/dist/chunks/{4BVP652W.js → ZZ6FZGHF.js} +1 -1
  477. package/package.json +1 -1
  478. package/build/dist/chunks/3K2N5VFH.js +0 -1
  479. package/build/dist/chunks/3ZABD6ZF.js +0 -2
  480. package/build/dist/chunks/44MB6SA6.js +0 -1
  481. package/build/dist/chunks/4D4ZRZUW.js +0 -1
  482. package/build/dist/chunks/4OVIMYNH.js +0 -2
  483. package/build/dist/chunks/6NUNCD5J.js +0 -1
  484. package/build/dist/chunks/6PZGDVHV.js +0 -1
  485. package/build/dist/chunks/7MBVTNLU.js +0 -1
  486. package/build/dist/chunks/7VNO46LV.js +0 -1
  487. package/build/dist/chunks/CAWTAR5V.js +0 -1
  488. package/build/dist/chunks/DPE7SPW7.js +0 -1
  489. package/build/dist/chunks/E3RACZUY.js +0 -1
  490. package/build/dist/chunks/EI6GGPDS.js +0 -20
  491. package/build/dist/chunks/FV4WZOTD.js +0 -1
  492. package/build/dist/chunks/FWD4L3CJ.js +0 -1
  493. package/build/dist/chunks/JBTOZ6IH.js +0 -1
  494. package/build/dist/chunks/KREBNL2D.js +0 -1
  495. package/build/dist/chunks/MVD3KWPP.js +0 -1
  496. package/build/dist/chunks/P6OMKZMR.js +0 -3
  497. package/build/dist/chunks/PXVREXCS.js +0 -1
  498. package/build/dist/chunks/QJNLLI6N.js +0 -1
  499. package/build/dist/chunks/RPB46QAC.js +0 -1
  500. package/build/dist/chunks/TID4C2KC.js +0 -1
  501. package/build/dist/chunks/U2YCQWZK.js +0 -1
  502. package/build/dist/chunks/UWBKAWX3.js +0 -7
  503. package/build/dist/chunks/V6SDKPZS.js +0 -1
  504. package/build/dist/chunks/WHTRPRRD.js +0 -1
  505. package/build/dist/chunks/WLMWWEP7.js +0 -2
  506. package/build/dist/chunks/XQ24RSEI.js +0 -1
  507. package/build/dist/chunks/YDNTY67T.js +0 -1
  508. package/build/dist/chunks/ZQAFFWDK.js +0 -1
@@ -1 +1 @@
1
- import{a as $e,b as Ee}from"./YEIM6BZQ.js";import{c as en,d as nn,e as _e,f as he,i as Ue,j as tn}from"./RLI4JDOL.js";import{i as de}from"./U2YCQWZK.js";import{b as Te,o as Me}from"./CAWTAR5V.js";import{a as ce}from"./H5DY7CNB.js";import{a as T,b as Je}from"./43LI5NKJ.js";import{a as L}from"./66F5ZH34.js";import{b as K}from"./IX3GZMTM.js";import{a as y,d as Ze,i as Q,j as Ye,m as Qe}from"./FWD4L3CJ.js";import{a as o,b as Ge,e as oe}from"./XSD5NL7J.js";import{encodeAbiParameters as S,encodeFunctionData as re,erc20Abi as on,getAddress as w,isAddress as Nn,keccak256 as Kn,pad as Hn,parseAbi as Ae,parseAbiParameters as z,toEventSelector as Fn,toHex as rn}from"viem";var Vn=w(Q[4663].uniswap.v4_pool_manager.address),M=w(Q[4663].uniswap.v4_position_manager.address),le=w(Q[4663].uniswap.v4_state_view.address),He=w(Q[4663].uniswap.permit2.address),At=w(Q[4663].ponsTrade.universal_router.address),se=w(Q[4663].uniswap.WETH.address),D=w(Ye),k="0x0000000000000000000000000000000000000000",Xe=8388608,Fe=-887272,ve=887272,An=(1n<<48n)-1n,J=(1n<<128n)-1n,Bn=(1n<<160n)-1n,pe=1n<<96n,sn="V4 deposits use limits, not minimums: set amount0Max and amount1Max, and for more room for price movement set slippageBps (at most 500 = 5%).",an=1800n,me=50n,cn=(e,n=me)=>e*(10000n-n)/10000n,dn=(e,n,i=me)=>{let r=(e*(10000n+i)+9999n)/10000n;return r<n?r:n},Xn="0xbac3aa3b91584a53a579b3c999a56756e954e59247e497bad1d25a4334bde551",Ve=class extends o{name="PonsHookRefusal";token;constructor(n){let i=n===void 0?void 0:w(n),r=i?`To buy, use pons_buy {"token":"${i}","amountIn":"<ETH in wei>"}. To sell, use pons_sell {"token":"${i}","amountIn":"<token base units>"}.`:"For this custom pair, check the launch token and pairToken with pons_status, then use pons_buy or pons_sell with those addresses and amounts in the input token's base units.";super(`Oak's Uniswap tools don't quote this pool. Its hook is Pons's own trading hook, so Oak trades it only through Pons. ${r} Pons shows the exact fees before you approve.`),this.token=i}},Oe=[{poolId:"0xbac3aa3b91584a53a579b3c999a56756e954e59247e497bad1d25a4334bde551",key:{currency0:k,currency1:D,fee:8388608,tickSpacing:10,hooks:w("0x06a889870c8f83640d6816319f72e2aa579b6080")},liquidity:"5532026605872066941",sqrtPriceX96:"3839897026469220985301794",tick:-198703,protocolFee:0,lpFee:0},{poolId:"0x387bf619da4d3fb62bb276482693dba1b9b3520f573cabdfe033384a24125982",key:{currency0:k,currency1:D,fee:500,tickSpacing:10,hooks:k},liquidity:"225820987949255613",sqrtPriceX96:"3840577772610961024680304",tick:-198700,protocolFee:512125,lpFee:500},{poolId:"0x54f7883914619af9105355bf83ed678bcf9f63560218ac61c9963b9503d0ba32",key:{currency0:k,currency1:D,fee:460,tickSpacing:9,hooks:k},liquidity:"85654324417347171",sqrtPriceX96:"3840419018843648722761192",tick:-198701,protocolFee:479349,lpFee:460},{poolId:"0xc7b615a3721594f73664eb3f62d8290d0fcc8d9d1156aed1ddecbd7f32efd9f5",key:{currency0:k,currency1:D,fee:8388608,tickSpacing:10,hooks:w("0xcb787a5cdea8b3715d984d82f1203fd7bfebe0c4")},liquidity:"50517446454827887",sqrtPriceX96:"3840495145865430860317598",tick:-198700,protocolFee:0,lpFee:0},{poolId:"0x24107d152f14a76d292123265ae3f3c71f863fc2f4ef7ba49d64e78d28ea379e",key:{currency0:k,currency1:D,fee:100,tickSpacing:1,hooks:k},liquidity:"36478878201789434",sqrtPriceX96:"3840363370720475418748563",tick:-198701,protocolFee:102425,lpFee:100},{poolId:"0x84bd4e2d8be11aeb0afc1195b38f587b61e90068548f1063fdbe448fb8cad0b6",key:{currency0:se,currency1:D,fee:200,tickSpacing:4,hooks:k},liquidity:"5980655057479791",sqrtPriceX96:"3839891926195366283625355",tick:-198703,protocolFee:213044,lpFee:200},{poolId:"0x3b0cbf0603ecc67b5fc9bb4fbb6ac9e08d3b2f406b63d1662a36063a7fe5e866",key:{currency0:k,currency1:D,fee:87,tickSpacing:1,hooks:k},liquidity:"5486760264498148",sqrtPriceX96:"3840563617639470134132117",tick:-198700,protocolFee:90134,lpFee:87}],Re=w("0x987e330f00b79864a07fe81dfac344d0078abcc0"),Sn="0xa791e5169faf703c0b63fd9552c33ec1128a773a00f5dc33a640da62a022cd35",On={currency0:k,currency1:D,fee:Xe,tickSpacing:1,hooks:Re},Rn=new Set([...Oe.map(e=>e.key.hooks.toLowerCase()),Re.toLowerCase()]),zn=z("address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks"),jn=z("(address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) poolKey, int24 tickLower, int24 tickUpper, uint256 liquidity, uint128 amount0Max, uint128 amount1Max, address owner, bytes hookData"),Wn=z("address currency0, address currency1"),Gn=z("address currency, address recipient"),ge=z("uint256 tokenId, uint256 liquidity, uint128 amount0Min, uint128 amount1Min, bytes hookData"),Zn=z("uint256 tokenId, uint128 amount0Min, uint128 amount1Min, bytes hookData"),De=z("address currency0, address currency1, address recipient"),ue=z("bytes actions, bytes[] params"),X=Ae(["function modifyLiquidities(bytes unlockData, uint256 deadline) payable","function poolKeys(bytes25 poolId) view returns (address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks)","function getPositionLiquidity(uint256 tokenId) view returns (uint128 liquidity)","function getPoolAndPositionInfo(uint256 tokenId) view returns ((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) poolKey, uint256 info)","function positionInfo(uint256 tokenId) view returns (uint256 info)","function ownerOf(uint256 tokenId) view returns (address owner)","function nextTokenId() view returns (uint256 tokenId)"]),Yn=Ae(["function initialize((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, uint160 sqrtPriceX96) returns (int24 tick)"]),un=z("address currency"),pn=1e6,fe=Ae(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),Qn=Ae(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),Jn=Fn("Transfer(address,address,uint256)");function xe(e){if(typeof e!="string"||!Nn(e,{strict:!1}))throw new o("Provide a valid v4 currency address.");let n=e.toLowerCase();return n===k||n===ce.toLowerCase()?k:w(e)}function H(e){let n=e.toLowerCase();return n===k||n===ce.toLowerCase()}function ye(e){let n=xe(e.currency0),i=xe(e.currency1);T(e.hooks);let r=w(e.hooks);return Kn(S(zn,[n,i,e.fee,e.tickSpacing,r]))}function In(e){return((typeof e=="number"?e:e.fee)&Xe)!==0}function ln(e,n){return In(e)?{dynamicFee:!0,storedLpFee:n,swapsAreFree:!1,feeNote:Ee(e,n)}:{dynamicFee:!1,storedLpFee:n,swapsAreFree:n===0,feeNote:Ee(e,n)}}function ke(e,n){if(!e||typeof e!="object")throw new o("Provide a valid v4 PoolKey.");let i=xe(e.currency0),r=xe(e.currency1);if(BigInt(i)>=BigInt(r))throw new o("PoolKey currencies must be strictly sorted (currency0 < currency1).");if(!Number.isInteger(e.tickSpacing)||e.tickSpacing<=0||e.tickSpacing>32767)throw new o("PoolKey tickSpacing must be a positive integer.");if(!Number.isInteger(e.fee)||e.fee<0||e.fee>16777215)throw new o("PoolKey fee must be a valid uint24.");T(e.hooks);let c=w(e.hooks),s=In(e.fee);if(!s&&e.fee>pn)throw new o(`PoolKey static fee ${$e(e.fee)} exceeds the v4 maximum of ${$e(pn)}.`);if(s&&e.fee!==Xe)throw new o("Dynamic-fee PoolKey must use exact fee flag 0x800000 (8388608).");if(s&&c.toLowerCase()===k)throw new o("Dynamic-fee PoolKey requires a non-zero hook address.");if(!Rn.has(c.toLowerCase()))throw c.toLowerCase()===Qe.toLowerCase()?new Ve(i===k?r:void 0):new o(`Unsupported v4 hook ${c}: Oak does not assure arbitrary v4 hooks outside measured PoolKeys.`);let t={currency0:i,currency1:r,fee:e.fee,tickSpacing:e.tickSpacing,hooks:c},d=ye(t);if(c===Re&&d.toLowerCase()!==Sn)throw new o("Only the documented VolatilePair ETH/USDG PoolKey is supported. Pool creation requires the Uniswap Labs role.");if(n!==void 0){if(typeof n!="string"||!/^0x[0-9a-fA-F]{64}$/.test(n))throw new o("Provide a 32-byte hex poolId.");if(d.toLowerCase()!==n.toLowerCase())throw new o(`PoolKey hash (${d}) does not match expected poolId (${n}).`)}return t}function et(e){if(!Number.isInteger(e)||e<=0||e>ve)throw new o("tickSpacing must be a positive integer.");let n=Math.trunc(Fe/e)*e,i=Math.trunc(ve/e)*e;return{tickLower:n===0?0:n,tickUpper:i===0?0:i}}function nt(e,n,i){if(!Number.isInteger(i)||i<=0)throw new o("tickSpacing must be a positive integer.");if(!Number.isInteger(e)||!Number.isInteger(n))throw new o("tickLower and tickUpper must be integers.");if(e<Fe||n>ve)throw new o(`Ticks [${e}, ${n}] are outside Uniswap bounds [${Fe}, ${ve}].`);if(e>=n)throw new o("tickLower must be strictly less than tickUpper.");if(e%i!==0||n%i!==0)throw new o(`Ticks [${e}, ${n}] must be divisible by tickSpacing ${i}.`)}function mn(e,n,i,r,c=y){if(T(e),T(n),H(e))throw new o("Native ETH does not use Permit2 approval.");let s=K(i);if(s<=0n||s>Bn)throw new o("Permit2 approval amount must be a positive integer within uint160.");let t=K(String(r));if(t<=0n||t>An)throw new o("Permit2 expiration must be a positive timestamp within uint48.");let d=re({abi:Qn,functionName:"approve",args:[e,n,s,Number(t)]});return Je({to:He,data:d,value:"0",chainId:c,description:`Approve Permit2 allowance of ${s} base units of ${e} for ${n} until ${t}.`})}function fn(e){let n=Number(e&0xffffffn);return(n&8388608)!==0?n-16777216:n}function tt(e){let n=(e&0xffn)!==0n,i=fn(e>>8n&0xffffffn),r=fn(e>>32n&0xffffffn);return{poolIdBytes25:`0x${(e>>56n&(1n<<200n)-1n).toString(16).padStart(50,"0")}`,tickLower:i,tickUpper:r,hasSubscriber:n}}function yn(e,n,i,r=!1){let[c,s]=e<=n?[e,n]:[n,e];if(c<=0n||s<=0n)return 0n;let t=(i<<96n)*(s-c),d=s*c;return r?(t+d-1n)/d:t/d}function wn(e,n,i,r=!1){let[c,s]=e<=n?[e,n]:[n,e],t=i*(s-c);return r?(t+pe-1n)/pe:t/pe}function Cn(e){if(e.liquidity<=0n)return{amount0:0n,amount1:0n};let n=de(e.tickLower),i=de(e.tickUpper);return e.sqrtPriceX96<=n?{amount0:yn(n,i,e.liquidity,e.roundUp),amount1:0n}:e.sqrtPriceX96<i?{amount0:yn(e.sqrtPriceX96,i,e.liquidity,e.roundUp),amount1:wn(n,e.sqrtPriceX96,e.liquidity,e.roundUp)}:{amount0:0n,amount1:wn(n,i,e.liquidity,e.roundUp)}}function it(e){let n=de(e.tickLower),i=de(e.tickUpper),r=(s,t,d)=>t<=s||d<=0n?0n:d*s*t/pe/(t-s),c=(s,t,d)=>t<=s||d<=0n?0n:d*pe/(t-s);if(e.sqrtPriceX96<=n)return r(n,i,e.amount0);if(e.sqrtPriceX96<i){let s=r(e.sqrtPriceX96,i,e.amount0),t=c(n,e.sqrtPriceX96,e.amount1);return s<t?s:t}return c(n,i,e.amount1)}function Ne(e,n){return e.map(i=>{let r=i.amount.trim(),c=r.startsWith("-"),s=c||r.startsWith("+")?r.slice(1):r,t=n(s,i.token.decimals);return`${c?"-":""}${t} ${i.token.symbol}`})}function bn(e,n=y){if(H(e))return{address:ce,symbol:"ETH",decimals:18,chainId:n};let i=w(e);return i.toLowerCase()===D.toLowerCase()?{address:D,symbol:"USDG",decimals:Ze,chainId:n}:i.toLowerCase()===se.toLowerCase()?{address:se,symbol:"WETH",decimals:18,chainId:n}:{address:i,symbol:i.slice(0,10),decimals:18,chainId:n}}async function B(e,n,i=y){if(H(n))return bn(n,i);let r=w(n);if(r.toLowerCase()===D.toLowerCase()||r.toLowerCase()===se.toLowerCase())return bn(r,i);let[c,s]=await Promise.all([e.readContract({address:r,abi:on,functionName:"symbol"}),e.readContract({address:r,abi:on,functionName:"decimals"})]);if(!Number.isInteger(Number(s))||Number(s)<0||Number(s)>77)throw new o(`Token ${r} reports invalid decimals.`);return{address:r,symbol:tn(c,r),decimals:Number(s),chainId:i}}function Z(e,n){if(typeof e!="string"||!/^\d+$/.test(e))throw new o(`${n} must be a non-negative integer string in base units.`);return K(e)}function hn(e,n,i,r){let c=e===void 0?K(Me(n.toString(),i)):Z(e,r);if(c<=1n||c>J)throw new o(`${r} must exceed 1 base unit and fit in uint128; the simulated amount may be too small.`);return c}async function qn(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return BigInt(Math.floor(n>1e11?n/1e3:n));if(typeof n=="string"&&/^\d+$/.test(n.trim()))return BigInt(n.trim());try{let i=await e.request({method:"eth_getBlockByNumber",params:["latest",!1]});if(i&&typeof i.timestamp=="string")return BigInt(i.timestamp)}catch{}return BigInt(Math.floor(Date.now()/1e3))}async function Ke(e,n,i){let r=await qn(e,i);if(n==null)return r+1800n;let c=K(String(n));if(c<=r)throw new o(`Transaction deadline ${c} has expired (current timestamp ${r}).`);return c}async function Be(e,n){let i=typeof n.poolId=="string"?n.poolId.trim():void 0,r=n.poolKey&&typeof n.poolKey=="object"&&!Array.isArray(n.poolKey)?n.poolKey:void 0,c=r?{currency0:String(r.currency0??k),currency1:String(r.currency1??D),fee:Number(r.fee),tickSpacing:Number(r.tickSpacing),hooks:String(r.hooks??k)}:n.currency0!==void 0&&n.currency1!==void 0&&n.fee!==void 0&&n.tickSpacing!==void 0?{currency0:String(n.currency0),currency1:String(n.currency1),fee:Number(n.fee),tickSpacing:Number(n.tickSpacing),hooks:String(n.hooks??k)}:void 0;if(c){if(H(c.currency0)&&typeof n.token0=="string"&&n.token0.toLowerCase()===se.toLowerCase())throw new o("Native ETH currency0 differs from WETH; do not supply WETH for a native-ETH v4 pool.");let u=ke(c,i);return{poolId:ye(u),poolKey:u}}let s=(i??Xn).toLowerCase();if(s===Sn)return{poolId:s,poolKey:ke(On,s)};let t=Oe.find(u=>u.poolId.toLowerCase()===s);if(t){if(H(t.key.currency0)&&typeof n.token0=="string"&&n.token0.toLowerCase()===se.toLowerCase())throw new o("Native ETH currency0 differs from WETH; do not supply WETH for a native-ETH v4 pool.");return{poolId:t.poolId,poolKey:t.key}}let d=s.slice(0,52),a=await e.readContract({address:M,abi:X,functionName:"poolKeys",args:[d]}),[p,l,m,f,P]=a;if(p.toLowerCase()===k&&l.toLowerCase()===k&&Number(f)===0)throw new o(`Unknown or uninitialized v4 poolId ${s}.`);let b=ke({currency0:p,currency1:l,fee:Number(m),tickSpacing:Number(f),hooks:P},s);return{poolId:s,poolKey:b}}async function Pe(e,n,i){try{let[r,c]=await e.readContract({address:M,abi:X,functionName:"getPoolAndPositionInfo",args:[n]}),s=ke({currency0:r.currency0,currency1:r.currency1,fee:Number(r.fee),tickSpacing:Number(r.tickSpacing),hooks:r.hooks});if((i.poolKey||i.poolId)&&(await Be(e,i)).poolId.toLowerCase()!==ye(s).toLowerCase())throw new o("The supplied PoolKey does not match this v4 position.");let t=tt(BigInt(c));return{poolKey:s,poolId:ye(s),tickLower:t.tickLower,tickUpper:t.tickUpper}}catch(r){throw new o(`Could not read v4 position #${n}. ${oe(r)}`)}}function ot(e){if(typeof e!="string")throw new o("wallet must be a valid 20-byte hex address.");return T(e),w(e)}async function gn(e,n,i={}){T(n);let r=w(n),c=e.clientFor(y),s=new Set;if(i.tokenIds)for(let d of i.tokenIds)s.add(K(String(d)).toString());if(!i.tokenIds?.length)try{let d=await c.getBlockNumber(),a=10000000n;for(let p=0n;p<=d;p+=a){let l=p+a-1n<d?p+a-1n:d,m=await c.request({method:"eth_getLogs",params:[{address:M.toLowerCase(),topics:[Jn,null,Hn(r)],fromBlock:rn(p),toBlock:rn(l)}]});if(!Array.isArray(m))throw new o("Invalid v4 position log response.");for(let f of m){if(!Array.isArray(f.topics)||f.topics.length!==4||!/^0x[0-9a-fA-F]{64}$/.test(f.topics[3]??""))throw new o("Invalid v4 position transfer log.");s.add(BigInt(f.topics[3]).toString())}}}catch(d){if(!i.tokenIds)throw new o(`Could not discover v4 positions. ${oe(d)}`)}let t=[];for(let d of s){let a=BigInt(d);try{let p;try{p=await c.readContract({address:M,abi:X,functionName:"ownerOf",args:[a]})}catch(F){if(Ge(F,3))continue;throw F}if(p.toLowerCase()!==r.toLowerCase())continue;let l=await c.readContract({address:M,abi:X,functionName:"getPositionLiquidity",args:[a]}),m=BigInt(l);if(m===0n&&!i.includeZero)continue;let{poolKey:f,poolId:P,tickLower:b,tickUpper:u}=await Pe(c,a,{}),v=await c.readContract({address:le,abi:fe,functionName:"getSlot0",args:[P]}),x=BigInt(v[0]),{amount0:h,amount1:g}=Cn({liquidity:m,tickLower:b,tickUpper:u,sqrtPriceX96:x}),[A,I]=await Promise.all([B(c,f.currency0,y),B(c,f.currency1,y)]);t.push({module:"uniswap",id:`uniswap:v4:${a.toString()}`,chainId:y,assets:[{token:A,amount:h.toString()},{token:I,amount:g.toString()}],description:`Uniswap v4 LP position #${a.toString()} (${A.symbol}/${I.symbol}, liquidity=${m.toString()}, ticks=[${b},${u}], poolId=${P})`})}catch(p){throw new o(`Could not read v4 position #${a}. ${oe(p)}`)}}return t}var rt={type:"object",properties:{version:{description:"Uniswap v4 PoolManager version.",type:"string",enum:["v4"]},poolId:{type:"string",description:"32-byte Uniswap v4 poolId hex string."},poolKey:{description:"V4 pool key: sorted currencies, fee in pips, tick spacing and hook address.",type:"object",properties:{currency0:{description:"Lower sorted currency address; the zero address means native ETH.",type:"string"},currency1:{description:"Higher sorted currency address.",type:"string"},fee:{description:"Pool fee in pips, hundredths of a basis point (3000 = 0.3%; 950000 = 95%).",type:"number"},tickSpacing:{description:"Spacing between usable pool ticks, as an integer.",type:"number"},hooks:{description:"Hook contract address; the zero address means no hook.",type:"string"}}},currency0:{description:"Lower sorted currency address; the zero address means native ETH.",type:"string"},currency1:{description:"Higher sorted currency address.",type:"string"},fee:{description:"Pool fee in pips, hundredths of a basis point (3000 = 0.3%; 950000 = 95%).",type:"number"},tickSpacing:{description:"Spacing between usable pool ticks, as an integer.",type:"number"},hooks:{description:"Hook contract address; the zero address means no hook.",type:"string"},tickLower:{description:"Lower tick boundary, divisible by the pool tick spacing.",type:"number"},tickUpper:{description:"Upper tick boundary, divisible by the pool tick spacing.",type:"number"},fullRange:{description:"Use the widest tick range aligned to the pool tick spacing; omit explicit ticks.",type:"boolean"},liquidity:L('Position liquidity in protocol base units. Example: "1000" = 1000 liquidity units.'),amount0Max:L('Maximum amount of currency0 in base units; use currency0 decimals. Example: "1000000" = 1 currency0 at 6 decimals.'),amount1Max:L('Maximum amount of currency1 in base units; use currency1 decimals. Example: "1000000" = 1 currency1 at 6 decimals.'),recipient:{description:"Recipient address; must be the signing wallet.",type:"string"},deadline:L("Transaction deadline in Unix seconds, after the current block timestamp. Example: 1800000000."),permit2Expiration:{description:'Permit2 allowance expiry in Unix seconds, as a decimal string. Example: "1800000000".',type:"string"},exactCaps:{description:"Use both caller caps exactly for a new v4 mint; omit tokenId, initialPrice and sqrtPriceX96.",type:"boolean"},slippageBps:{description:"Mint cap headroom in basis points (50 = 0.5%), up to 500 (5%); unavailable when increasing an existing NFT.",type:"integer",minimum:0,maximum:500,default:Number(me)},hookData:{description:"Hex-encoded hook call data; only data supported by the measured hook is accepted.",type:"string"},tokenId:L('Existing v4 position NFT identifier to increase, as a decimal string; keeps its tick range. Omit to mint a new position. Example: "1".'),initialPrice:{type:"string",description:"Starting price as token1 per one token0 in human units; used only for a new pool. Pool creation and the first liquidity add require separate confirmations."},sqrtPriceX96:{type:"string",description:"Alternative starting price: square root of the token1/token0 base-unit price ratio, multiplied by 2^96, as a decimal string."},acceptPriceDeviation:{type:"boolean",description:"Allow a starting price more than 500 basis points (5%) from other live pools of the pair."}}},st={type:"object",description:"Create and initialize an empty Uniswap v4 pool (permissionless PoolManager.initialize). Add liquidity afterwards with uniswap_add.",properties:{version:{description:"Uniswap v4 PoolManager version.",type:"string",enum:["v4"]},poolKey:{description:"V4 pool key: sorted currencies, fee in pips, tick spacing and hook address.",type:"object",properties:{currency0:{description:"Lower sorted currency address; the zero address means native ETH.",type:"string"},currency1:{description:"Higher sorted currency address.",type:"string"},fee:{description:"Pool fee in pips, hundredths of a basis point (3000 = 0.3%; 950000 = 95%).",type:"number"},tickSpacing:{description:"Spacing between usable pool ticks, as an integer.",type:"number"},hooks:{description:"Hook contract address; the zero address means no hook.",type:"string"}}},currency0:{type:"string",description:"Lower sorted currency; the zero address is native ETH."},currency1:{description:"Higher sorted currency address.",type:"string"},fee:{type:"number",description:"Pool fee in pips, hundredths of a basis point (3000 = 0.3%; 950000 = 95%)."},tickSpacing:{description:"Spacing between usable pool ticks, as an integer.",type:"number"},hooks:{type:"string",description:"Hook address; only hooks Oak has measured are accepted. Defaults to none."},initialPrice:{type:"string",description:"Starting pool price as token1 per one token0 in human units. Add liquidity separately after initialization."},sqrtPriceX96:{type:"string",description:"Alternative starting price: square root of the token1/token0 base-unit price ratio, multiplied by 2^96, as a decimal string."},acceptPriceDeviation:{type:"boolean",description:"Allow a starting price more than 500 basis points (5%) from other live pools of the pair."}}},at={type:"object",properties:{version:{description:"Uniswap v4 PoolManager version.",type:"string",enum:["v4"]},tokenId:L('Identifier of the position NFT, as a decimal string. Example: "1".'),poolId:{description:"Identifier of the v4 pool, as a 32-byte hex string.",type:"string"},poolKey:{description:"V4 pool key: sorted currencies, fee in pips, tick spacing and hook address.",type:"object"},amount0Min:L('Minimum amount of currency0 in base units; use currency0 decimals. Example: "1000000" = 1 currency0 at 6 decimals.'),amount1Min:L('Minimum amount of currency1 in base units; use currency1 decimals. Example: "1000000" = 1 currency1 at 6 decimals.'),recipient:{description:"Recipient address; must be the signing wallet.",type:"string"},deadline:L("Transaction deadline in Unix seconds, after the current block timestamp. Example: 1800000000."),hookData:{description:"Hex-encoded hook call data; only data supported by the measured hook is accepted.",type:"string"}},required:["tokenId"]},ct={type:"object",properties:{version:{description:"Uniswap v4 PoolManager version.",type:"string",enum:["v4"]},tokenId:L('Identifier of the position NFT, as a decimal string. Example: "1".'),liquidity:{type:"string",pattern:"^(?:[0-9]+|all)$",description:'Liquidity in protocol base units, or "all" for a full exit where supported; not a token amount. Example: "1000" = 1000 liquidity units.'},slippageBps:{description:"Slippage tolerance in basis points (50 = 0.5%).",type:"integer",minimum:0,maximum:9999,default:Te},fullExit:{description:"Remove all position liquidity and collect the proceeds.",type:"boolean"},burn:{description:"Burn the position NFT after all liquidity and owed tokens have been removed.",type:"boolean"},amount0Min:L('Minimum amount of currency0 in base units; use currency0 decimals. Example: "1000000" = 1 currency0 at 6 decimals.'),amount1Min:L('Minimum amount of currency1 in base units; use currency1 decimals. Example: "1000000" = 1 currency1 at 6 decimals.'),poolId:{description:"Identifier of the v4 pool, as a 32-byte hex string.",type:"string"},poolKey:{description:"V4 pool key: sorted currencies, fee in pips, tick spacing and hook address.",type:"object"},recipient:{description:"Recipient address; must be the signing wallet.",type:"string"},deadline:L("Transaction deadline in Unix seconds, after the current block timestamp. Example: 1800000000."),hookData:{description:"Hex-encoded hook call data; only data supported by the measured hook is accepted.",type:"string"}},required:["tokenId"]},dt={type:"object",properties:{version:{description:"Uniswap v4 PoolManager version.",type:"string",enum:["v4"]},tokenIds:{description:'Position NFT identifiers as decimal strings. Example: ["1", "2"].',type:"array",items:L()},includeZero:{description:"Include positions whose current liquidity is zero.",type:"boolean"}}};function kn(e){let n=e.poolKey&&typeof e.poolKey=="object"&&!Array.isArray(e.poolKey)?e.poolKey:e;for(let i of["currency0","currency1","fee","tickSpacing"])if(n[i]===void 0)throw new o(`Creating a pool needs the full poolKey (currency0, currency1, fee, tickSpacing, hooks); ${i} is missing. A poolId alone cannot describe a pool that does not exist yet.`)}function Pn(e,n,i){if(e.initialPrice!==void 0&&e.sqrtPriceX96!==void 0)throw new o("Provide initialPrice or sqrtPriceX96, not both.");if(e.sqrtPriceX96!==void 0){if(typeof e.sqrtPriceX96!="string"||!/^\d+$/.test(e.sqrtPriceX96))throw new o("sqrtPriceX96 must be a non-negative integer string.");return nn(BigInt(e.sqrtPriceX96))}return en(e.initialPrice,n,i)}async function ut(e,n,i){let r;try{r=await e.readContract({address:M,abi:X,functionName:"ownerOf",args:[n]})}catch(c){throw new o(`Could not verify owner of Uniswap v4 position #${n}. ${oe(c)}`)}if(w(r)!==w(i))throw new o(`Wallet ${w(i)} is not the owner of Uniswap v4 position #${n} (owned by ${w(r)}).`)}async function vn(e,n){let i=ye(n).toLowerCase(),r=new Map;for(let s of Oe)s.key.currency0.toLowerCase()===n.currency0.toLowerCase()&&s.key.currency1.toLowerCase()===n.currency1.toLowerCase()&&r.set(s.poolId.toLowerCase(),s.key);let c=[];for(let[s,t]of r){if(s===i||BigInt(await e.readContract({address:le,abi:fe,functionName:"getLiquidity",args:[s]}))===0n)continue;let a=await e.readContract({address:le,abi:fe,functionName:"getSlot0",args:[s]});BigInt(a[0])>0n&&c.push({label:`v4 fee ${t.fee} spacing ${t.tickSpacing} pool ${s}`,sqrtPriceX96:BigInt(a[0])})}return c}function xn(e,n,i,r,c,s){return e.unsignedTx({to:Vn.toLowerCase(),data:re({abi:Yn,functionName:"initialize",args:[{currency0:n.currency0.toLowerCase(),currency1:n.currency1.toLowerCase(),fee:n.fee,tickSpacing:n.tickSpacing,hooks:n.hooks.toLowerCase()},r]}),value:"0",chainId:y,description:`Create and initialize Uniswap v4 pool ${i} (${c.symbol}/${s.symbol}, fee ${n.fee}, tickSpacing ${n.tickSpacing}) at ${he(r,c.decimals,s.decimals)} ${s.symbol} per ${c.symbol}.`})}var pt=e=>({tools:[{name:"uniswap_add",inputSchema:rt,async execute(t,d){if(T(d),t.version!==void 0&&t.version!=="v4")throw new o('Uniswap v4 part only handles version "v4".');let a=t.tokenId===void 0?void 0:K(String(t.tokenId));if(a!==void 0&&a<=0n)throw new o("Provide a positive v4 position tokenId.");let p=t.initialPrice!==void 0||t.sqrtPriceX96!==void 0;if(t.exactCaps!==void 0&&typeof t.exactCaps!="boolean")throw new o("exactCaps must be a boolean.");let l=t.exactCaps===!0;if(l&&(a!==void 0||p||t.amount0Max===void 0||t.amount1Max===void 0))throw new o("exactCaps is for v4 mints only: provide both amount0Max and amount1Max, without tokenId, initialPrice or sqrtPriceX96.");if(a!==void 0&&p)throw new o("initialPrice cannot be combined with tokenId.");if(a!==void 0&&(t.amount0Min!==void 0||t.amount1Min!==void 0||t.slippageBps!==void 0))throw new o("V4 mint encodes fixed liquidity and amount0Max/amount1Max; amount minima and slippageBps are not supported for minting.");if(t.amount0Min!==void 0||t.amount1Min!==void 0)throw new o(sn);let m=t.slippageBps===void 0?Number(me):t.slippageBps;if(typeof m!="number"||!Number.isInteger(m)||m<0||m>500)throw new o(sn);let f=BigInt(m),P=e.clientFor(y);p&&kn(t);let b,u,v,x;if(a!==void 0){if(t.tickLower!==void 0||t.tickUpper!==void 0||t.fullRange!==void 0)throw new o("An existing v4 position keeps its tick range; omit tickLower, tickUpper and fullRange when increasing.");await ut(P,a,d),{poolId:b,poolKey:u,tickLower:v,tickUpper:x}=await Pe(P,a,t)}else{({poolId:b,poolKey:u}=await Be(P,t));let q=et(u.tickSpacing);v=t.fullRange===!0&&t.tickLower===void 0?q.tickLower:Number(t.tickLower),x=t.fullRange===!0&&t.tickUpper===void 0?q.tickUpper:Number(t.tickUpper),nt(v,x,u.tickSpacing)}let[h,g]=await Promise.all([B(P,u.currency0,y),B(P,u.currency1,y)]),A=Z(t.amount0Max??t.amount0Desired,"amount0Max"),I=Z(t.amount1Max??t.amount1Desired,"amount1Max");if(A<=0n&&I<=0n||A>J||I>J)throw new o("Provide positive amount0Max/amount1Max within uint128.");let F=await P.readContract({address:le,abi:fe,functionName:"getSlot0",args:[b]}),_=BigInt(F[0]),j=Number(F[3]),C;if(p){if(_>0n)throw new o(`Pool ${b} already exists; remove initialPrice/sqrtPriceX96 to add liquidity at its current price.`);let q=Pn(t,h.decimals,g.decimals),V=Ue(q,await vn(P,u),t.acceptPriceDeviation===!0,h.decimals,g.decimals);C={sqrtPriceX96:q,note:V},_=q}else if(_<=0n)throw new o(`Pool ${b} is not initialized on StateView. To create it and add the first liquidity in one tool call with separately confirmed transactions, pass the full poolKey plus initialPrice (token1 per 1 token0, human units); to create it without liquidity use uniswap_create_pool.`);let E=t.liquidity!==void 0&&!l?Z(t.liquidity,"liquidity"):it({amount0:cn(A,f),amount1:cn(I,f),tickLower:v,tickUpper:x,sqrtPriceX96:_});if(E<=0n||E>J)throw new o("Position liquidity must be a positive integer within uint128.");let{amount0:ee,amount1:ne}=Cn({liquidity:E,tickLower:v,tickUpper:x,sqrtPriceX96:_,roundUp:!0});if(ee>A||ne>I)throw new o("Liquidity requires more tokens than amount0Max or amount1Max.");let W=l?A:dn(ee,A,f),Y=l?I:dn(ne,I,f),$=t.recipient!==void 0?String(t.recipient):d;if(T($),w($)!==w(d))throw new o("Uniswap recipient must be the signing wallet.");let U=await qn(P),O=await Ke(P,t.deadline,U.toString()),te=O<U+an?O:U+an,N=t.permit2Expiration===void 0?te:K(String(t.permit2Expiration));if(N<=U||N>te||N>An)throw new o("Permit2 expiration must be in the next 30 minutes and no later than the transaction deadline.");let ie=typeof t.hookData=="string"?t.hookData:"0x",Se=((q,V)=>{let G=C?[xn(e,u,b,C.sqrtPriceX96,h,g)]:[];if(!H(u.currency0)&&q>0n){let ae=u.currency0.toLowerCase();G.push(e.approval(ae,He.toLowerCase(),q.toString(),y)),G.push(mn(ae,M.toLowerCase(),q.toString(),N.toString(),y))}if(!H(u.currency1)&&V>0n){let ae=u.currency1.toLowerCase();G.push(e.approval(ae,He.toLowerCase(),V.toString(),y)),G.push(mn(ae,M.toLowerCase(),V.toString(),N.toString(),y))}let R={currency0:u.currency0.toLowerCase(),currency1:u.currency1.toLowerCase(),fee:u.fee,tickSpacing:u.tickSpacing,hooks:u.hooks.toLowerCase()},Le=S(jn,[R,v,x,E,q,V,$.toLowerCase(),ie]),$n=S(Wn,[R.currency0,R.currency1]),We=S(Gn,[k,$.toLowerCase()]),En=S(ge,[a??0n,E,q,V,ie]),_n=a===void 0?S(ue,["0x020d14",[Le,$n,We]]):S(ue,["0x00121214",[En,S(un,[R.currency0]),S(un,[R.currency1]),We]]),Un=re({abi:X,functionName:"modifyLiquidities",args:[_n,O]}),Dn=H(u.currency0)?q.toString():"0";return G.push(e.unsignedTx({to:M.toLowerCase(),data:Un,value:Dn,chainId:y,description:a!==void 0?`Increase Uniswap v4 position #${a} on pool ${b} (liquidity +${E}).`:`Mint Uniswap v4 position on pool ${b} (ticks [${v}, ${x}], liquidity ${E}).`})),G})(W,Y),we=await e.preview(Se,d),ze=(q,V)=>{let G=H(V)?ce:V.toLowerCase();return-q.changes.filter(R=>R.token.address.toLowerCase()===G).reduce((R,Le)=>R+BigInt(Le.amount),0n)},Ie=ze(we,u.currency0),Ce=ze(we,u.currency1);if(Ie<0n||Ce<0n||Ie>W||Ce>Y||Ie===0n&&Ce===0n&&a===void 0)throw new o("Invalid simulated v4 mint spend. Refresh the liquidity preview.");let Ln=Ne(we.changes,e.formatAmount),qe=ln(u,j),je=[...!H(u.currency0)&&W>0n?[h.symbol]:[],...!H(u.currency1)&&Y>0n?[g.symbol]:[]],Tn=Se.length,Mn=a===void 0?`This deposit takes ${Tn} approvals in a row: ${je.length?`let Permit2 use your ${je.join(" and ")}, let the Uniswap position manager use it through Permit2, then the deposit`:"the deposit"}. `:"",be=m>Number(me)?`You chose ${m/100}% room for price movement. Oak will approve up to ${e.formatAmount(W.toString(),h.decimals)} ${h.symbol} and ${e.formatAmount(Y.toString(),g.decimals)} ${g.symbol}, more than the expected ${e.formatAmount(ee.toString(),h.decimals)} and ${e.formatAmount(ne.toString(),g.decimals)}. Anything not used stays in your wallet, and any leftover permission is cancelled after the deposit.`:void 0;return{txs:Se,preview:we,poolId:b,poolKey:u,tickLower:v,tickUpper:x,liquidity:E.toString(),amount0Max:{token:h,amount:A.toString()},amount1Max:{token:g,amount:I.toString()},dynamicFee:qe.dynamicFee,swapsAreFree:qe.swapsAreFree,...a===void 0?{mintTerms:{amount0Max:W.toString(),amount1Max:Y.toString(),deadline:O.toString(),permit2Expiration:N.toString(),slippageBps:m.toString(),liquidity:E.toString()}}:{},...be?{warnings:[be]}:{},action:a!==void 0?"increase":C?"createAndMint":"mint",...a!==void 0?{tokenId:a.toString()}:{},...C?{poolCreated:!0,sqrtPriceX96:C.sqrtPriceX96.toString(),initialPrice:he(C.sqrtPriceX96,h.decimals,g.decimals),initialTick:_e(C.sqrtPriceX96),priceCheck:C.note}:{},summary:`${Mn}${a!==void 0?`Increase Uniswap v4 position #${a}`:C?"Create Uniswap v4 pool and add first liquidity":"Add Uniswap v4 liquidity"} (${E} L, ticks [${v}, ${x}]) on pool ${b}. Preview deltas: ${Ln.join(", ")||"none"}. A partial spend can leave ERC-20 and Permit2 allowances equal to grant minus spent, bounded by your caps. Use oak_cleanup_allowances to revoke remaining allowances. ${qe.feeNote}${be?` ${be}`:""}${C?` ${C.note}`:""}`}}},{name:"uniswap_collect",inputSchema:at,async execute(t,d){if(T(d),t.version!==void 0&&t.version!=="v4")throw new o('Uniswap v4 part only handles version "v4".');let a=K(String(t.tokenId??""));if(a<=0n)throw new o("Provide a positive v4 position tokenId.");let p=e.clientFor(y),l=t.recipient!==void 0?String(t.recipient):d;if(T(l),w(l)!==w(d))throw new o("Uniswap recipient must be the signing wallet.");let m=await Ke(p,t.deadline,t.now),f=t.amount0Min!==void 0?Z(t.amount0Min,"amount0Min"):0n,P=t.amount1Min!==void 0?Z(t.amount1Min,"amount1Min"):0n;if(f>J||P>J)throw new o("amount0Min and amount1Min must fit in uint128.");let b=typeof t.hookData=="string"?t.hookData:"0x",{poolKey:u,poolId:v}=await Pe(p,a,t),[x,h]=await Promise.all([B(p,u.currency0,y),B(p,u.currency1,y)]),g=S(ge,[a,0n,f,P,b]),A=S(De,[u.currency0.toLowerCase(),u.currency1.toLowerCase(),l.toLowerCase()]),I=S(ue,["0x0111",[g,A]]),F=re({abi:X,functionName:"modifyLiquidities",args:[I,m]}),_=[e.unsignedTx({to:M.toLowerCase(),data:F,value:"0",chainId:y,description:`Collect Uniswap v4 fees from position #${a} to ${l}.`})],j=await e.preview(_,d),C=Ne(j.changes,e.formatAmount);return{txs:_,preview:j,tokenId:a.toString(),poolId:v,recipient:l,currencies:[x,h],summary:`Collect Uniswap v4 fees for position #${a} (actions 0x0111). Preview deltas: ${C.join(", ")||"0"}.`}}},{name:"uniswap_remove",inputSchema:ct,async execute(t,d){if(T(d),t.version!==void 0&&t.version!=="v4")throw new o('Uniswap v4 part only handles version "v4".');let a=K(String(t.tokenId??""));if(a<=0n)throw new o("Provide a positive v4 position tokenId.");let p=e.clientFor(y),l=t.recipient!==void 0?String(t.recipient):d;if(T(l),w(l)!==w(d))throw new o("Uniswap recipient must be the signing wallet.");let m=await Ke(p,t.deadline,t.now),{poolKey:f,poolId:P}=await Pe(p,a,t),[b,u]=await Promise.all([B(p,f.currency0,y),B(p,f.currency1,y)]),v=t.slippageBps??Te;if(typeof v!="number")throw new o("Slippage must be an integer from 0 to 9999 bps.");Me("0",v);let x=typeof t.hookData=="string"?t.hookData:"0x",h=t.fullExit===!0||t.burn===!0||t.liquidity==="all";if(!h&&t.liquidity===void 0)throw new o('Provide a liquidity amount or explicitly choose liquidity "all" for a full exit.');let g=t.liquidity===void 0||t.liquidity==="all"?void 0:Z(t.liquidity,"liquidity");if(g!==void 0&&(g<0n||g===0n&&!h||g>J))throw new o("Provide positive liquidity within uint128 for v4 removal.");let A;try{A=BigInt(await p.readContract({address:M,abi:X,functionName:"getPositionLiquidity",args:[a]}))}catch($){throw new o(`Could not read v4 position liquidity. ${oe($)}`)}if(A<0n||A===0n&&!h||g!==void 0&&g>A)throw new o("Removal requires a nonempty position and cannot exceed its liquidity.");if(h&&g!==void 0&&g!==A)throw new o("A full burn must match the position liquidity; omit the amount when explicitly choosing all.");let I=h?"0x0311":"0x0111",F=($,U,O)=>{let te=h?S(Zn,[a,$,U,x]):S(ge,[a,g,$,U,x]),N=S(De,[f.currency0,f.currency1,O]);return e.unsignedTx({to:M.toLowerCase(),data:re({abi:X,functionName:"modifyLiquidities",args:[S(ue,[I,[te,N]]),m]}),value:"0",chainId:y,description:`${h?"Burn and exit":"Decrease"} Uniswap v4 position #${a} (${I}).`})},_=0n,j=0n;if(A>0n&&(t.amount0Min===void 0||t.amount1Min===void 0)){let $=e.unsignedTx({to:M.toLowerCase(),data:re({abi:X,functionName:"modifyLiquidities",args:[S(ue,["0x0111",[S(ge,[a,0n,0n,0n,x]),S(De,[f.currency0,f.currency1,M])]]),m]}),value:"0",chainId:y,description:"Simulation only: separate fees from removal principal."}),U=await e.preview([$,F(2n,2n,d)],d),O=te=>U.changes.reduce((N,ie)=>ie.token.chainId===y&&ie.token.address.toLowerCase()===te.address.toLowerCase()?N+BigInt(ie.amount):N,0n);if(_=O(b),j=O(u),_<0n||j<0n)throw new o("Removal simulation did not return the expected currencies.")}let C=($,U)=>{if($!==void 0&&Z($,U)!==0n)throw new o(`${U} must be zero for an empty position burn.`);return 0n},E=A===0n?C(t.amount0Min,"amount0Min"):hn(t.amount0Min,_,v,"amount0Min"),ee=A===0n?C(t.amount1Min,"amount1Min"):hn(t.amount1Min,j,v,"amount1Min"),ne=[F(E,ee,l)],W=await e.preview(ne,d),Y=Ne(W.changes,e.formatAmount);return{txs:ne,preview:W,action:I,tokenId:a.toString(),poolId:P,amount0Min:{token:b,amount:E.toString()},amount1Min:{token:u,amount:ee.toString()},summary:`${h?"Full exit":"Partial remove"} Uniswap v4 position #${a} (${I})${h?`; burns position #${a} at ${M}`:""}. Preview deltas: ${Y.join(", ")||"none"}.`}}},{name:"uniswap_list_positions",inputSchema:dt,async execute(t,d){if(T(d),t.version!==void 0&&t.version!=="v4")throw new o('Uniswap v4 part only handles version "v4".');let a=Array.isArray(t.tokenIds)?t.tokenIds:void 0,p=t.includeZero===!0,l=t.wallet===void 0?w(d):ot(t.wallet),m=await gn(e,l,{tokenIds:a,includeZero:p});return{version:"v4",positions:m,summary:`Found ${m.length} active Uniswap v4 position(s) for ${l}.`}}},{name:"uniswap_create_pool",inputSchema:st,async execute(t,d){if(T(d),t.version!==void 0&&t.version!=="v4")throw new o('Uniswap v4 part only handles version "v4".');kn(t);let a=e.clientFor(y),{poolId:p,poolKey:l}=await Be(a,t),[m,f]=await Promise.all([B(a,l.currency0,y),B(a,l.currency1,y)]),P=await a.readContract({address:le,abi:fe,functionName:"getSlot0",args:[p]});if(BigInt(P[0])>0n)throw new o(`Uniswap v4 pool ${p} already exists. Use uniswap_add to provide liquidity.`);let b=Pn(t,m.decimals,f.decimals),u=Ue(b,await vn(a,l),t.acceptPriceDeviation===!0,m.decimals,f.decimals),v=he(b,m.decimals,f.decimals),x=[xn(e,l,p,b,m,f)],h=await e.preview(x,d),g=ln(l,l.fee);return{txs:x,preview:h,poolId:p,poolKey:l,sqrtPriceX96:b.toString(),initialPrice:v,initialTick:_e(b),priceCheck:u,action:"createPool",summary:`${x[0].description} The pool starts empty: nothing trades until liquidity is added with uniswap_add. ${g.feeNote} ${u}`}}}],positions:t=>gn(e,t)}),St=pt;export{Vn as a,M as b,le as c,He as d,At as e,se as f,D as g,k as h,Xe as i,Fe as j,ve as k,Xn as l,Ve as m,Oe as n,Re as o,Sn as p,On as q,Rn as r,H as s,ye as t,In as u,ln as v,ke as w,et as x,nt as y,mn as z,tt as A,Cn as B,it as C,Ne as D,bn as E,B as F,Pe as G,gn as H,rt as I,st as J,at as K,ct as L,dt as M,vn as N,pt as O,St as P};
1
+ import{a as $e,b as Ee}from"./YEIM6BZQ.js";import{c as en,d as nn,e as _e,f as he,i as Ue,j as tn}from"./RA7DOR7F.js";import{k as de}from"./NV6FDIYT.js";import{b as Te,o as Me}from"./GYPMUYB5.js";import{a as ce}from"./Z7FGEWO2.js";import{a as T,b as Je}from"./43LI5NKJ.js";import{a as L}from"./66F5ZH34.js";import{b as K}from"./IX3GZMTM.js";import{b as y,e as Ze,j as Q,k as Ye,n as Qe}from"./TI727O2H.js";import{a as o,b as Ge,e as oe}from"./XSD5NL7J.js";import{encodeAbiParameters as S,encodeFunctionData as re,erc20Abi as on,getAddress as w,isAddress as Nn,keccak256 as Kn,pad as Hn,parseAbi as Ae,parseAbiParameters as z,toEventSelector as Fn,toHex as rn}from"viem";var Vn=w(Q[4663].uniswap.v4_pool_manager.address),M=w(Q[4663].uniswap.v4_position_manager.address),le=w(Q[4663].uniswap.v4_state_view.address),He=w(Q[4663].uniswap.permit2.address),At=w(Q[4663].ponsTrade.universal_router.address),se=w(Q[4663].uniswap.WETH.address),D=w(Ye),k="0x0000000000000000000000000000000000000000",Xe=8388608,Fe=-887272,ve=887272,An=(1n<<48n)-1n,J=(1n<<128n)-1n,Bn=(1n<<160n)-1n,pe=1n<<96n,sn="V4 deposits use limits, not minimums: set amount0Max and amount1Max, and for more room for price movement set slippageBps (at most 500 = 5%).",an=1800n,me=50n,cn=(e,n=me)=>e*(10000n-n)/10000n,dn=(e,n,i=me)=>{let r=(e*(10000n+i)+9999n)/10000n;return r<n?r:n},Xn="0xbac3aa3b91584a53a579b3c999a56756e954e59247e497bad1d25a4334bde551",Ve=class extends o{name="PonsHookRefusal";token;constructor(n){let i=n===void 0?void 0:w(n),r=i?`To buy, use pons_buy {"token":"${i}","amountIn":"<ETH in wei>"}. To sell, use pons_sell {"token":"${i}","amountIn":"<token base units>"}.`:"For this custom pair, check the launch token and pairToken with pons_status, then use pons_buy or pons_sell with those addresses and amounts in the input token's base units.";super(`Oak's Uniswap tools don't quote this pool. Its hook is Pons's own trading hook, so Oak trades it only through Pons. ${r} Pons shows the exact fees before you approve.`),this.token=i}},Oe=[{poolId:"0xbac3aa3b91584a53a579b3c999a56756e954e59247e497bad1d25a4334bde551",key:{currency0:k,currency1:D,fee:8388608,tickSpacing:10,hooks:w("0x06a889870c8f83640d6816319f72e2aa579b6080")},liquidity:"5532026605872066941",sqrtPriceX96:"3839897026469220985301794",tick:-198703,protocolFee:0,lpFee:0},{poolId:"0x387bf619da4d3fb62bb276482693dba1b9b3520f573cabdfe033384a24125982",key:{currency0:k,currency1:D,fee:500,tickSpacing:10,hooks:k},liquidity:"225820987949255613",sqrtPriceX96:"3840577772610961024680304",tick:-198700,protocolFee:512125,lpFee:500},{poolId:"0x54f7883914619af9105355bf83ed678bcf9f63560218ac61c9963b9503d0ba32",key:{currency0:k,currency1:D,fee:460,tickSpacing:9,hooks:k},liquidity:"85654324417347171",sqrtPriceX96:"3840419018843648722761192",tick:-198701,protocolFee:479349,lpFee:460},{poolId:"0xc7b615a3721594f73664eb3f62d8290d0fcc8d9d1156aed1ddecbd7f32efd9f5",key:{currency0:k,currency1:D,fee:8388608,tickSpacing:10,hooks:w("0xcb787a5cdea8b3715d984d82f1203fd7bfebe0c4")},liquidity:"50517446454827887",sqrtPriceX96:"3840495145865430860317598",tick:-198700,protocolFee:0,lpFee:0},{poolId:"0x24107d152f14a76d292123265ae3f3c71f863fc2f4ef7ba49d64e78d28ea379e",key:{currency0:k,currency1:D,fee:100,tickSpacing:1,hooks:k},liquidity:"36478878201789434",sqrtPriceX96:"3840363370720475418748563",tick:-198701,protocolFee:102425,lpFee:100},{poolId:"0x84bd4e2d8be11aeb0afc1195b38f587b61e90068548f1063fdbe448fb8cad0b6",key:{currency0:se,currency1:D,fee:200,tickSpacing:4,hooks:k},liquidity:"5980655057479791",sqrtPriceX96:"3839891926195366283625355",tick:-198703,protocolFee:213044,lpFee:200},{poolId:"0x3b0cbf0603ecc67b5fc9bb4fbb6ac9e08d3b2f406b63d1662a36063a7fe5e866",key:{currency0:k,currency1:D,fee:87,tickSpacing:1,hooks:k},liquidity:"5486760264498148",sqrtPriceX96:"3840563617639470134132117",tick:-198700,protocolFee:90134,lpFee:87}],Re=w("0x987e330f00b79864a07fe81dfac344d0078abcc0"),Sn="0xa791e5169faf703c0b63fd9552c33ec1128a773a00f5dc33a640da62a022cd35",On={currency0:k,currency1:D,fee:Xe,tickSpacing:1,hooks:Re},Rn=new Set([...Oe.map(e=>e.key.hooks.toLowerCase()),Re.toLowerCase()]),zn=z("address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks"),jn=z("(address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) poolKey, int24 tickLower, int24 tickUpper, uint256 liquidity, uint128 amount0Max, uint128 amount1Max, address owner, bytes hookData"),Wn=z("address currency0, address currency1"),Gn=z("address currency, address recipient"),ge=z("uint256 tokenId, uint256 liquidity, uint128 amount0Min, uint128 amount1Min, bytes hookData"),Zn=z("uint256 tokenId, uint128 amount0Min, uint128 amount1Min, bytes hookData"),De=z("address currency0, address currency1, address recipient"),ue=z("bytes actions, bytes[] params"),X=Ae(["function modifyLiquidities(bytes unlockData, uint256 deadline) payable","function poolKeys(bytes25 poolId) view returns (address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks)","function getPositionLiquidity(uint256 tokenId) view returns (uint128 liquidity)","function getPoolAndPositionInfo(uint256 tokenId) view returns ((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) poolKey, uint256 info)","function positionInfo(uint256 tokenId) view returns (uint256 info)","function ownerOf(uint256 tokenId) view returns (address owner)","function nextTokenId() view returns (uint256 tokenId)"]),Yn=Ae(["function initialize((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, uint160 sqrtPriceX96) returns (int24 tick)"]),un=z("address currency"),pn=1e6,fe=Ae(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),Qn=Ae(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),Jn=Fn("Transfer(address,address,uint256)");function xe(e){if(typeof e!="string"||!Nn(e,{strict:!1}))throw new o("Provide a valid v4 currency address.");let n=e.toLowerCase();return n===k||n===ce.toLowerCase()?k:w(e)}function H(e){let n=e.toLowerCase();return n===k||n===ce.toLowerCase()}function ye(e){let n=xe(e.currency0),i=xe(e.currency1);T(e.hooks);let r=w(e.hooks);return Kn(S(zn,[n,i,e.fee,e.tickSpacing,r]))}function In(e){return((typeof e=="number"?e:e.fee)&Xe)!==0}function ln(e,n){return In(e)?{dynamicFee:!0,storedLpFee:n,swapsAreFree:!1,feeNote:Ee(e,n)}:{dynamicFee:!1,storedLpFee:n,swapsAreFree:n===0,feeNote:Ee(e,n)}}function ke(e,n){if(!e||typeof e!="object")throw new o("Provide a valid v4 PoolKey.");let i=xe(e.currency0),r=xe(e.currency1);if(BigInt(i)>=BigInt(r))throw new o("PoolKey currencies must be strictly sorted (currency0 < currency1).");if(!Number.isInteger(e.tickSpacing)||e.tickSpacing<=0||e.tickSpacing>32767)throw new o("PoolKey tickSpacing must be a positive integer.");if(!Number.isInteger(e.fee)||e.fee<0||e.fee>16777215)throw new o("PoolKey fee must be a valid uint24.");T(e.hooks);let c=w(e.hooks),s=In(e.fee);if(!s&&e.fee>pn)throw new o(`PoolKey static fee ${$e(e.fee)} exceeds the v4 maximum of ${$e(pn)}.`);if(s&&e.fee!==Xe)throw new o("Dynamic-fee PoolKey must use exact fee flag 0x800000 (8388608).");if(s&&c.toLowerCase()===k)throw new o("Dynamic-fee PoolKey requires a non-zero hook address.");if(!Rn.has(c.toLowerCase()))throw c.toLowerCase()===Qe.toLowerCase()?new Ve(i===k?r:void 0):new o(`Unsupported v4 hook ${c}: Oak does not assure arbitrary v4 hooks outside measured PoolKeys.`);let t={currency0:i,currency1:r,fee:e.fee,tickSpacing:e.tickSpacing,hooks:c},d=ye(t);if(c===Re&&d.toLowerCase()!==Sn)throw new o("Only the documented VolatilePair ETH/USDG PoolKey is supported. Pool creation requires the Uniswap Labs role.");if(n!==void 0){if(typeof n!="string"||!/^0x[0-9a-fA-F]{64}$/.test(n))throw new o("Provide a 32-byte hex poolId.");if(d.toLowerCase()!==n.toLowerCase())throw new o(`PoolKey hash (${d}) does not match expected poolId (${n}).`)}return t}function et(e){if(!Number.isInteger(e)||e<=0||e>ve)throw new o("tickSpacing must be a positive integer.");let n=Math.trunc(Fe/e)*e,i=Math.trunc(ve/e)*e;return{tickLower:n===0?0:n,tickUpper:i===0?0:i}}function nt(e,n,i){if(!Number.isInteger(i)||i<=0)throw new o("tickSpacing must be a positive integer.");if(!Number.isInteger(e)||!Number.isInteger(n))throw new o("tickLower and tickUpper must be integers.");if(e<Fe||n>ve)throw new o(`Ticks [${e}, ${n}] are outside Uniswap bounds [${Fe}, ${ve}].`);if(e>=n)throw new o("tickLower must be strictly less than tickUpper.");if(e%i!==0||n%i!==0)throw new o(`Ticks [${e}, ${n}] must be divisible by tickSpacing ${i}.`)}function mn(e,n,i,r,c=y){if(T(e),T(n),H(e))throw new o("Native ETH does not use Permit2 approval.");let s=K(i);if(s<=0n||s>Bn)throw new o("Permit2 approval amount must be a positive integer within uint160.");let t=K(String(r));if(t<=0n||t>An)throw new o("Permit2 expiration must be a positive timestamp within uint48.");let d=re({abi:Qn,functionName:"approve",args:[e,n,s,Number(t)]});return Je({to:He,data:d,value:"0",chainId:c,description:`Approve Permit2 allowance of ${s} base units of ${e} for ${n} until ${t}.`})}function fn(e){let n=Number(e&0xffffffn);return(n&8388608)!==0?n-16777216:n}function tt(e){let n=(e&0xffn)!==0n,i=fn(e>>8n&0xffffffn),r=fn(e>>32n&0xffffffn);return{poolIdBytes25:`0x${(e>>56n&(1n<<200n)-1n).toString(16).padStart(50,"0")}`,tickLower:i,tickUpper:r,hasSubscriber:n}}function yn(e,n,i,r=!1){let[c,s]=e<=n?[e,n]:[n,e];if(c<=0n||s<=0n)return 0n;let t=(i<<96n)*(s-c),d=s*c;return r?(t+d-1n)/d:t/d}function wn(e,n,i,r=!1){let[c,s]=e<=n?[e,n]:[n,e],t=i*(s-c);return r?(t+pe-1n)/pe:t/pe}function Cn(e){if(e.liquidity<=0n)return{amount0:0n,amount1:0n};let n=de(e.tickLower),i=de(e.tickUpper);return e.sqrtPriceX96<=n?{amount0:yn(n,i,e.liquidity,e.roundUp),amount1:0n}:e.sqrtPriceX96<i?{amount0:yn(e.sqrtPriceX96,i,e.liquidity,e.roundUp),amount1:wn(n,e.sqrtPriceX96,e.liquidity,e.roundUp)}:{amount0:0n,amount1:wn(n,i,e.liquidity,e.roundUp)}}function it(e){let n=de(e.tickLower),i=de(e.tickUpper),r=(s,t,d)=>t<=s||d<=0n?0n:d*s*t/pe/(t-s),c=(s,t,d)=>t<=s||d<=0n?0n:d*pe/(t-s);if(e.sqrtPriceX96<=n)return r(n,i,e.amount0);if(e.sqrtPriceX96<i){let s=r(e.sqrtPriceX96,i,e.amount0),t=c(n,e.sqrtPriceX96,e.amount1);return s<t?s:t}return c(n,i,e.amount1)}function Ne(e,n){return e.map(i=>{let r=i.amount.trim(),c=r.startsWith("-"),s=c||r.startsWith("+")?r.slice(1):r,t=n(s,i.token.decimals);return`${c?"-":""}${t} ${i.token.symbol}`})}function bn(e,n=y){if(H(e))return{address:ce,symbol:"ETH",decimals:18,chainId:n};let i=w(e);return i.toLowerCase()===D.toLowerCase()?{address:D,symbol:"USDG",decimals:Ze,chainId:n}:i.toLowerCase()===se.toLowerCase()?{address:se,symbol:"WETH",decimals:18,chainId:n}:{address:i,symbol:i.slice(0,10),decimals:18,chainId:n}}async function B(e,n,i=y){if(H(n))return bn(n,i);let r=w(n);if(r.toLowerCase()===D.toLowerCase()||r.toLowerCase()===se.toLowerCase())return bn(r,i);let[c,s]=await Promise.all([e.readContract({address:r,abi:on,functionName:"symbol"}),e.readContract({address:r,abi:on,functionName:"decimals"})]);if(!Number.isInteger(Number(s))||Number(s)<0||Number(s)>77)throw new o(`Token ${r} reports invalid decimals.`);return{address:r,symbol:tn(c,r),decimals:Number(s),chainId:i}}function Z(e,n){if(typeof e!="string"||!/^\d+$/.test(e))throw new o(`${n} must be a non-negative integer string in base units.`);return K(e)}function hn(e,n,i,r){let c=e===void 0?K(Me(n.toString(),i)):Z(e,r);if(c<=1n||c>J)throw new o(`${r} must exceed 1 base unit and fit in uint128; the simulated amount may be too small.`);return c}async function qn(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return BigInt(Math.floor(n>1e11?n/1e3:n));if(typeof n=="string"&&/^\d+$/.test(n.trim()))return BigInt(n.trim());try{let i=await e.request({method:"eth_getBlockByNumber",params:["latest",!1]});if(i&&typeof i.timestamp=="string")return BigInt(i.timestamp)}catch{}return BigInt(Math.floor(Date.now()/1e3))}async function Ke(e,n,i){let r=await qn(e,i);if(n==null)return r+1800n;let c=K(String(n));if(c<=r)throw new o(`Transaction deadline ${c} has expired (current timestamp ${r}).`);return c}async function Be(e,n){let i=typeof n.poolId=="string"?n.poolId.trim():void 0,r=n.poolKey&&typeof n.poolKey=="object"&&!Array.isArray(n.poolKey)?n.poolKey:void 0,c=r?{currency0:String(r.currency0??k),currency1:String(r.currency1??D),fee:Number(r.fee),tickSpacing:Number(r.tickSpacing),hooks:String(r.hooks??k)}:n.currency0!==void 0&&n.currency1!==void 0&&n.fee!==void 0&&n.tickSpacing!==void 0?{currency0:String(n.currency0),currency1:String(n.currency1),fee:Number(n.fee),tickSpacing:Number(n.tickSpacing),hooks:String(n.hooks??k)}:void 0;if(c){if(H(c.currency0)&&typeof n.token0=="string"&&n.token0.toLowerCase()===se.toLowerCase())throw new o("Native ETH currency0 differs from WETH; do not supply WETH for a native-ETH v4 pool.");let u=ke(c,i);return{poolId:ye(u),poolKey:u}}let s=(i??Xn).toLowerCase();if(s===Sn)return{poolId:s,poolKey:ke(On,s)};let t=Oe.find(u=>u.poolId.toLowerCase()===s);if(t){if(H(t.key.currency0)&&typeof n.token0=="string"&&n.token0.toLowerCase()===se.toLowerCase())throw new o("Native ETH currency0 differs from WETH; do not supply WETH for a native-ETH v4 pool.");return{poolId:t.poolId,poolKey:t.key}}let d=s.slice(0,52),a=await e.readContract({address:M,abi:X,functionName:"poolKeys",args:[d]}),[p,l,m,f,P]=a;if(p.toLowerCase()===k&&l.toLowerCase()===k&&Number(f)===0)throw new o(`Unknown or uninitialized v4 poolId ${s}.`);let b=ke({currency0:p,currency1:l,fee:Number(m),tickSpacing:Number(f),hooks:P},s);return{poolId:s,poolKey:b}}async function Pe(e,n,i){try{let[r,c]=await e.readContract({address:M,abi:X,functionName:"getPoolAndPositionInfo",args:[n]}),s=ke({currency0:r.currency0,currency1:r.currency1,fee:Number(r.fee),tickSpacing:Number(r.tickSpacing),hooks:r.hooks});if((i.poolKey||i.poolId)&&(await Be(e,i)).poolId.toLowerCase()!==ye(s).toLowerCase())throw new o("The supplied PoolKey does not match this v4 position.");let t=tt(BigInt(c));return{poolKey:s,poolId:ye(s),tickLower:t.tickLower,tickUpper:t.tickUpper}}catch(r){throw new o(`Could not read v4 position #${n}. ${oe(r)}`)}}function ot(e){if(typeof e!="string")throw new o("wallet must be a valid 20-byte hex address.");return T(e),w(e)}async function gn(e,n,i={}){T(n);let r=w(n),c=e.clientFor(y),s=new Set;if(i.tokenIds)for(let d of i.tokenIds)s.add(K(String(d)).toString());if(!i.tokenIds?.length)try{let d=await c.getBlockNumber(),a=10000000n;for(let p=0n;p<=d;p+=a){let l=p+a-1n<d?p+a-1n:d,m=await c.request({method:"eth_getLogs",params:[{address:M.toLowerCase(),topics:[Jn,null,Hn(r)],fromBlock:rn(p),toBlock:rn(l)}]});if(!Array.isArray(m))throw new o("Invalid v4 position log response.");for(let f of m){if(!Array.isArray(f.topics)||f.topics.length!==4||!/^0x[0-9a-fA-F]{64}$/.test(f.topics[3]??""))throw new o("Invalid v4 position transfer log.");s.add(BigInt(f.topics[3]).toString())}}}catch(d){if(!i.tokenIds)throw new o(`Could not discover v4 positions. ${oe(d)}`)}let t=[];for(let d of s){let a=BigInt(d);try{let p;try{p=await c.readContract({address:M,abi:X,functionName:"ownerOf",args:[a]})}catch(F){if(Ge(F,3))continue;throw F}if(p.toLowerCase()!==r.toLowerCase())continue;let l=await c.readContract({address:M,abi:X,functionName:"getPositionLiquidity",args:[a]}),m=BigInt(l);if(m===0n&&!i.includeZero)continue;let{poolKey:f,poolId:P,tickLower:b,tickUpper:u}=await Pe(c,a,{}),v=await c.readContract({address:le,abi:fe,functionName:"getSlot0",args:[P]}),x=BigInt(v[0]),{amount0:h,amount1:g}=Cn({liquidity:m,tickLower:b,tickUpper:u,sqrtPriceX96:x}),[A,I]=await Promise.all([B(c,f.currency0,y),B(c,f.currency1,y)]);t.push({module:"uniswap",id:`uniswap:v4:${a.toString()}`,chainId:y,assets:[{token:A,amount:h.toString()},{token:I,amount:g.toString()}],description:`Uniswap v4 LP position #${a.toString()} (${A.symbol}/${I.symbol}, liquidity=${m.toString()}, ticks=[${b},${u}], poolId=${P})`})}catch(p){throw new o(`Could not read v4 position #${a}. ${oe(p)}`)}}return t}var rt={type:"object",properties:{version:{description:"Uniswap v4 PoolManager version.",type:"string",enum:["v4"]},poolId:{type:"string",description:"32-byte Uniswap v4 poolId hex string."},poolKey:{description:"V4 pool key: sorted currencies, fee in pips, tick spacing and hook address.",type:"object",properties:{currency0:{description:"Lower sorted currency address; the zero address means native ETH.",type:"string"},currency1:{description:"Higher sorted currency address.",type:"string"},fee:{description:"Pool fee in pips, hundredths of a basis point (3000 = 0.3%; 950000 = 95%).",type:"number"},tickSpacing:{description:"Spacing between usable pool ticks, as an integer.",type:"number"},hooks:{description:"Hook contract address; the zero address means no hook.",type:"string"}}},currency0:{description:"Lower sorted currency address; the zero address means native ETH.",type:"string"},currency1:{description:"Higher sorted currency address.",type:"string"},fee:{description:"Pool fee in pips, hundredths of a basis point (3000 = 0.3%; 950000 = 95%).",type:"number"},tickSpacing:{description:"Spacing between usable pool ticks, as an integer.",type:"number"},hooks:{description:"Hook contract address; the zero address means no hook.",type:"string"},tickLower:{description:"Lower tick boundary, divisible by the pool tick spacing.",type:"number"},tickUpper:{description:"Upper tick boundary, divisible by the pool tick spacing.",type:"number"},fullRange:{description:"Use the widest tick range aligned to the pool tick spacing; omit explicit ticks.",type:"boolean"},liquidity:L('Position liquidity in protocol base units. Example: "1000" = 1000 liquidity units.'),amount0Max:L('Maximum amount of currency0 in base units; use currency0 decimals. Example: "1000000" = 1 currency0 at 6 decimals.'),amount1Max:L('Maximum amount of currency1 in base units; use currency1 decimals. Example: "1000000" = 1 currency1 at 6 decimals.'),recipient:{description:"Recipient address; must be the signing wallet.",type:"string"},deadline:L("Transaction deadline in Unix seconds, after the current block timestamp. Example: 1800000000."),permit2Expiration:{description:'Permit2 allowance expiry in Unix seconds, as a decimal string. Example: "1800000000".',type:"string"},exactCaps:{description:"Use both caller caps exactly for a new v4 mint; omit tokenId, initialPrice and sqrtPriceX96.",type:"boolean"},slippageBps:{description:"Mint cap headroom in basis points (50 = 0.5%), up to 500 (5%); unavailable when increasing an existing NFT.",type:"integer",minimum:0,maximum:500,default:Number(me)},hookData:{description:"Hex-encoded hook call data; only data supported by the measured hook is accepted.",type:"string"},tokenId:L('Existing v4 position NFT identifier to increase, as a decimal string; keeps its tick range. Omit to mint a new position. Example: "1".'),initialPrice:{type:"string",description:"Starting price as token1 per one token0 in human units; used only for a new pool. Pool creation and the first liquidity add require separate confirmations."},sqrtPriceX96:{type:"string",description:"Alternative starting price: square root of the token1/token0 base-unit price ratio, multiplied by 2^96, as a decimal string."},acceptPriceDeviation:{type:"boolean",description:"Allow a starting price more than 500 basis points (5%) from other live pools of the pair."}}},st={type:"object",description:"Create and initialize an empty Uniswap v4 pool (permissionless PoolManager.initialize). Add liquidity afterwards with uniswap_add.",properties:{version:{description:"Uniswap v4 PoolManager version.",type:"string",enum:["v4"]},poolKey:{description:"V4 pool key: sorted currencies, fee in pips, tick spacing and hook address.",type:"object",properties:{currency0:{description:"Lower sorted currency address; the zero address means native ETH.",type:"string"},currency1:{description:"Higher sorted currency address.",type:"string"},fee:{description:"Pool fee in pips, hundredths of a basis point (3000 = 0.3%; 950000 = 95%).",type:"number"},tickSpacing:{description:"Spacing between usable pool ticks, as an integer.",type:"number"},hooks:{description:"Hook contract address; the zero address means no hook.",type:"string"}}},currency0:{type:"string",description:"Lower sorted currency; the zero address is native ETH."},currency1:{description:"Higher sorted currency address.",type:"string"},fee:{type:"number",description:"Pool fee in pips, hundredths of a basis point (3000 = 0.3%; 950000 = 95%)."},tickSpacing:{description:"Spacing between usable pool ticks, as an integer.",type:"number"},hooks:{type:"string",description:"Hook address; only hooks Oak has measured are accepted. Defaults to none."},initialPrice:{type:"string",description:"Starting pool price as token1 per one token0 in human units. Add liquidity separately after initialization."},sqrtPriceX96:{type:"string",description:"Alternative starting price: square root of the token1/token0 base-unit price ratio, multiplied by 2^96, as a decimal string."},acceptPriceDeviation:{type:"boolean",description:"Allow a starting price more than 500 basis points (5%) from other live pools of the pair."}}},at={type:"object",properties:{version:{description:"Uniswap v4 PoolManager version.",type:"string",enum:["v4"]},tokenId:L('Identifier of the position NFT, as a decimal string. Example: "1".'),poolId:{description:"Identifier of the v4 pool, as a 32-byte hex string.",type:"string"},poolKey:{description:"V4 pool key: sorted currencies, fee in pips, tick spacing and hook address.",type:"object"},amount0Min:L('Minimum amount of currency0 in base units; use currency0 decimals. Example: "1000000" = 1 currency0 at 6 decimals.'),amount1Min:L('Minimum amount of currency1 in base units; use currency1 decimals. Example: "1000000" = 1 currency1 at 6 decimals.'),recipient:{description:"Recipient address; must be the signing wallet.",type:"string"},deadline:L("Transaction deadline in Unix seconds, after the current block timestamp. Example: 1800000000."),hookData:{description:"Hex-encoded hook call data; only data supported by the measured hook is accepted.",type:"string"}},required:["tokenId"]},ct={type:"object",properties:{version:{description:"Uniswap v4 PoolManager version.",type:"string",enum:["v4"]},tokenId:L('Identifier of the position NFT, as a decimal string. Example: "1".'),liquidity:{type:"string",pattern:"^(?:[0-9]+|all)$",description:'Liquidity in protocol base units, or "all" for a full exit where supported; not a token amount. Example: "1000" = 1000 liquidity units.'},slippageBps:{description:"Slippage tolerance in basis points (50 = 0.5%).",type:"integer",minimum:0,maximum:9999,default:Te},fullExit:{description:"Remove all position liquidity and collect the proceeds.",type:"boolean"},burn:{description:"Burn the position NFT after all liquidity and owed tokens have been removed.",type:"boolean"},amount0Min:L('Minimum amount of currency0 in base units; use currency0 decimals. Example: "1000000" = 1 currency0 at 6 decimals.'),amount1Min:L('Minimum amount of currency1 in base units; use currency1 decimals. Example: "1000000" = 1 currency1 at 6 decimals.'),poolId:{description:"Identifier of the v4 pool, as a 32-byte hex string.",type:"string"},poolKey:{description:"V4 pool key: sorted currencies, fee in pips, tick spacing and hook address.",type:"object"},recipient:{description:"Recipient address; must be the signing wallet.",type:"string"},deadline:L("Transaction deadline in Unix seconds, after the current block timestamp. Example: 1800000000."),hookData:{description:"Hex-encoded hook call data; only data supported by the measured hook is accepted.",type:"string"}},required:["tokenId"]},dt={type:"object",properties:{version:{description:"Uniswap v4 PoolManager version.",type:"string",enum:["v4"]},tokenIds:{description:'Position NFT identifiers as decimal strings. Example: ["1", "2"].',type:"array",items:L()},includeZero:{description:"Include positions whose current liquidity is zero.",type:"boolean"}}};function kn(e){let n=e.poolKey&&typeof e.poolKey=="object"&&!Array.isArray(e.poolKey)?e.poolKey:e;for(let i of["currency0","currency1","fee","tickSpacing"])if(n[i]===void 0)throw new o(`Creating a pool needs the full poolKey (currency0, currency1, fee, tickSpacing, hooks); ${i} is missing. A poolId alone cannot describe a pool that does not exist yet.`)}function Pn(e,n,i){if(e.initialPrice!==void 0&&e.sqrtPriceX96!==void 0)throw new o("Provide initialPrice or sqrtPriceX96, not both.");if(e.sqrtPriceX96!==void 0){if(typeof e.sqrtPriceX96!="string"||!/^\d+$/.test(e.sqrtPriceX96))throw new o("sqrtPriceX96 must be a non-negative integer string.");return nn(BigInt(e.sqrtPriceX96))}return en(e.initialPrice,n,i)}async function ut(e,n,i){let r;try{r=await e.readContract({address:M,abi:X,functionName:"ownerOf",args:[n]})}catch(c){throw new o(`Could not verify owner of Uniswap v4 position #${n}. ${oe(c)}`)}if(w(r)!==w(i))throw new o(`Wallet ${w(i)} is not the owner of Uniswap v4 position #${n} (owned by ${w(r)}).`)}async function vn(e,n){let i=ye(n).toLowerCase(),r=new Map;for(let s of Oe)s.key.currency0.toLowerCase()===n.currency0.toLowerCase()&&s.key.currency1.toLowerCase()===n.currency1.toLowerCase()&&r.set(s.poolId.toLowerCase(),s.key);let c=[];for(let[s,t]of r){if(s===i||BigInt(await e.readContract({address:le,abi:fe,functionName:"getLiquidity",args:[s]}))===0n)continue;let a=await e.readContract({address:le,abi:fe,functionName:"getSlot0",args:[s]});BigInt(a[0])>0n&&c.push({label:`v4 fee ${t.fee} spacing ${t.tickSpacing} pool ${s}`,sqrtPriceX96:BigInt(a[0])})}return c}function xn(e,n,i,r,c,s){return e.unsignedTx({to:Vn.toLowerCase(),data:re({abi:Yn,functionName:"initialize",args:[{currency0:n.currency0.toLowerCase(),currency1:n.currency1.toLowerCase(),fee:n.fee,tickSpacing:n.tickSpacing,hooks:n.hooks.toLowerCase()},r]}),value:"0",chainId:y,description:`Create and initialize Uniswap v4 pool ${i} (${c.symbol}/${s.symbol}, fee ${n.fee}, tickSpacing ${n.tickSpacing}) at ${he(r,c.decimals,s.decimals)} ${s.symbol} per ${c.symbol}.`})}var pt=e=>({tools:[{name:"uniswap_add",inputSchema:rt,async execute(t,d){if(T(d),t.version!==void 0&&t.version!=="v4")throw new o('Uniswap v4 part only handles version "v4".');let a=t.tokenId===void 0?void 0:K(String(t.tokenId));if(a!==void 0&&a<=0n)throw new o("Provide a positive v4 position tokenId.");let p=t.initialPrice!==void 0||t.sqrtPriceX96!==void 0;if(t.exactCaps!==void 0&&typeof t.exactCaps!="boolean")throw new o("exactCaps must be a boolean.");let l=t.exactCaps===!0;if(l&&(a!==void 0||p||t.amount0Max===void 0||t.amount1Max===void 0))throw new o("exactCaps is for v4 mints only: provide both amount0Max and amount1Max, without tokenId, initialPrice or sqrtPriceX96.");if(a!==void 0&&p)throw new o("initialPrice cannot be combined with tokenId.");if(a!==void 0&&(t.amount0Min!==void 0||t.amount1Min!==void 0||t.slippageBps!==void 0))throw new o("V4 mint encodes fixed liquidity and amount0Max/amount1Max; amount minima and slippageBps are not supported for minting.");if(t.amount0Min!==void 0||t.amount1Min!==void 0)throw new o(sn);let m=t.slippageBps===void 0?Number(me):t.slippageBps;if(typeof m!="number"||!Number.isInteger(m)||m<0||m>500)throw new o(sn);let f=BigInt(m),P=e.clientFor(y);p&&kn(t);let b,u,v,x;if(a!==void 0){if(t.tickLower!==void 0||t.tickUpper!==void 0||t.fullRange!==void 0)throw new o("An existing v4 position keeps its tick range; omit tickLower, tickUpper and fullRange when increasing.");await ut(P,a,d),{poolId:b,poolKey:u,tickLower:v,tickUpper:x}=await Pe(P,a,t)}else{({poolId:b,poolKey:u}=await Be(P,t));let q=et(u.tickSpacing);v=t.fullRange===!0&&t.tickLower===void 0?q.tickLower:Number(t.tickLower),x=t.fullRange===!0&&t.tickUpper===void 0?q.tickUpper:Number(t.tickUpper),nt(v,x,u.tickSpacing)}let[h,g]=await Promise.all([B(P,u.currency0,y),B(P,u.currency1,y)]),A=Z(t.amount0Max??t.amount0Desired,"amount0Max"),I=Z(t.amount1Max??t.amount1Desired,"amount1Max");if(A<=0n&&I<=0n||A>J||I>J)throw new o("Provide positive amount0Max/amount1Max within uint128.");let F=await P.readContract({address:le,abi:fe,functionName:"getSlot0",args:[b]}),_=BigInt(F[0]),j=Number(F[3]),C;if(p){if(_>0n)throw new o(`Pool ${b} already exists; remove initialPrice/sqrtPriceX96 to add liquidity at its current price.`);let q=Pn(t,h.decimals,g.decimals),V=Ue(q,await vn(P,u),t.acceptPriceDeviation===!0,h.decimals,g.decimals);C={sqrtPriceX96:q,note:V},_=q}else if(_<=0n)throw new o(`Pool ${b} is not initialized on StateView. To create it and add the first liquidity in one tool call with separately confirmed transactions, pass the full poolKey plus initialPrice (token1 per 1 token0, human units); to create it without liquidity use uniswap_create_pool.`);let E=t.liquidity!==void 0&&!l?Z(t.liquidity,"liquidity"):it({amount0:cn(A,f),amount1:cn(I,f),tickLower:v,tickUpper:x,sqrtPriceX96:_});if(E<=0n||E>J)throw new o("Position liquidity must be a positive integer within uint128.");let{amount0:ee,amount1:ne}=Cn({liquidity:E,tickLower:v,tickUpper:x,sqrtPriceX96:_,roundUp:!0});if(ee>A||ne>I)throw new o("Liquidity requires more tokens than amount0Max or amount1Max.");let W=l?A:dn(ee,A,f),Y=l?I:dn(ne,I,f),$=t.recipient!==void 0?String(t.recipient):d;if(T($),w($)!==w(d))throw new o("Uniswap recipient must be the signing wallet.");let U=await qn(P),O=await Ke(P,t.deadline,U.toString()),te=O<U+an?O:U+an,N=t.permit2Expiration===void 0?te:K(String(t.permit2Expiration));if(N<=U||N>te||N>An)throw new o("Permit2 expiration must be in the next 30 minutes and no later than the transaction deadline.");let ie=typeof t.hookData=="string"?t.hookData:"0x",Se=((q,V)=>{let G=C?[xn(e,u,b,C.sqrtPriceX96,h,g)]:[];if(!H(u.currency0)&&q>0n){let ae=u.currency0.toLowerCase();G.push(e.approval(ae,He.toLowerCase(),q.toString(),y)),G.push(mn(ae,M.toLowerCase(),q.toString(),N.toString(),y))}if(!H(u.currency1)&&V>0n){let ae=u.currency1.toLowerCase();G.push(e.approval(ae,He.toLowerCase(),V.toString(),y)),G.push(mn(ae,M.toLowerCase(),V.toString(),N.toString(),y))}let R={currency0:u.currency0.toLowerCase(),currency1:u.currency1.toLowerCase(),fee:u.fee,tickSpacing:u.tickSpacing,hooks:u.hooks.toLowerCase()},Le=S(jn,[R,v,x,E,q,V,$.toLowerCase(),ie]),$n=S(Wn,[R.currency0,R.currency1]),We=S(Gn,[k,$.toLowerCase()]),En=S(ge,[a??0n,E,q,V,ie]),_n=a===void 0?S(ue,["0x020d14",[Le,$n,We]]):S(ue,["0x00121214",[En,S(un,[R.currency0]),S(un,[R.currency1]),We]]),Un=re({abi:X,functionName:"modifyLiquidities",args:[_n,O]}),Dn=H(u.currency0)?q.toString():"0";return G.push(e.unsignedTx({to:M.toLowerCase(),data:Un,value:Dn,chainId:y,description:a!==void 0?`Increase Uniswap v4 position #${a} on pool ${b} (liquidity +${E}).`:`Mint Uniswap v4 position on pool ${b} (ticks [${v}, ${x}], liquidity ${E}).`})),G})(W,Y),we=await e.preview(Se,d),ze=(q,V)=>{let G=H(V)?ce:V.toLowerCase();return-q.changes.filter(R=>R.token.address.toLowerCase()===G).reduce((R,Le)=>R+BigInt(Le.amount),0n)},Ie=ze(we,u.currency0),Ce=ze(we,u.currency1);if(Ie<0n||Ce<0n||Ie>W||Ce>Y||Ie===0n&&Ce===0n&&a===void 0)throw new o("Invalid simulated v4 mint spend. Refresh the liquidity preview.");let Ln=Ne(we.changes,e.formatAmount),qe=ln(u,j),je=[...!H(u.currency0)&&W>0n?[h.symbol]:[],...!H(u.currency1)&&Y>0n?[g.symbol]:[]],Tn=Se.length,Mn=a===void 0?`This deposit takes ${Tn} approvals in a row: ${je.length?`let Permit2 use your ${je.join(" and ")}, let the Uniswap position manager use it through Permit2, then the deposit`:"the deposit"}. `:"",be=m>Number(me)?`You chose ${m/100}% room for price movement. Oak will approve up to ${e.formatAmount(W.toString(),h.decimals)} ${h.symbol} and ${e.formatAmount(Y.toString(),g.decimals)} ${g.symbol}, more than the expected ${e.formatAmount(ee.toString(),h.decimals)} and ${e.formatAmount(ne.toString(),g.decimals)}. Anything not used stays in your wallet, and any leftover permission is cancelled after the deposit.`:void 0;return{txs:Se,preview:we,poolId:b,poolKey:u,tickLower:v,tickUpper:x,liquidity:E.toString(),amount0Max:{token:h,amount:A.toString()},amount1Max:{token:g,amount:I.toString()},dynamicFee:qe.dynamicFee,swapsAreFree:qe.swapsAreFree,...a===void 0?{mintTerms:{amount0Max:W.toString(),amount1Max:Y.toString(),deadline:O.toString(),permit2Expiration:N.toString(),slippageBps:m.toString(),liquidity:E.toString()}}:{},...be?{warnings:[be]}:{},action:a!==void 0?"increase":C?"createAndMint":"mint",...a!==void 0?{tokenId:a.toString()}:{},...C?{poolCreated:!0,sqrtPriceX96:C.sqrtPriceX96.toString(),initialPrice:he(C.sqrtPriceX96,h.decimals,g.decimals),initialTick:_e(C.sqrtPriceX96),priceCheck:C.note}:{},summary:`${Mn}${a!==void 0?`Increase Uniswap v4 position #${a}`:C?"Create Uniswap v4 pool and add first liquidity":"Add Uniswap v4 liquidity"} (${E} L, ticks [${v}, ${x}]) on pool ${b}. Preview deltas: ${Ln.join(", ")||"none"}. A partial spend can leave ERC-20 and Permit2 allowances equal to grant minus spent, bounded by your caps. Use oak_cleanup_allowances to revoke remaining allowances. ${qe.feeNote}${be?` ${be}`:""}${C?` ${C.note}`:""}`}}},{name:"uniswap_collect",inputSchema:at,async execute(t,d){if(T(d),t.version!==void 0&&t.version!=="v4")throw new o('Uniswap v4 part only handles version "v4".');let a=K(String(t.tokenId??""));if(a<=0n)throw new o("Provide a positive v4 position tokenId.");let p=e.clientFor(y),l=t.recipient!==void 0?String(t.recipient):d;if(T(l),w(l)!==w(d))throw new o("Uniswap recipient must be the signing wallet.");let m=await Ke(p,t.deadline,t.now),f=t.amount0Min!==void 0?Z(t.amount0Min,"amount0Min"):0n,P=t.amount1Min!==void 0?Z(t.amount1Min,"amount1Min"):0n;if(f>J||P>J)throw new o("amount0Min and amount1Min must fit in uint128.");let b=typeof t.hookData=="string"?t.hookData:"0x",{poolKey:u,poolId:v}=await Pe(p,a,t),[x,h]=await Promise.all([B(p,u.currency0,y),B(p,u.currency1,y)]),g=S(ge,[a,0n,f,P,b]),A=S(De,[u.currency0.toLowerCase(),u.currency1.toLowerCase(),l.toLowerCase()]),I=S(ue,["0x0111",[g,A]]),F=re({abi:X,functionName:"modifyLiquidities",args:[I,m]}),_=[e.unsignedTx({to:M.toLowerCase(),data:F,value:"0",chainId:y,description:`Collect Uniswap v4 fees from position #${a} to ${l}.`})],j=await e.preview(_,d),C=Ne(j.changes,e.formatAmount);return{txs:_,preview:j,tokenId:a.toString(),poolId:v,recipient:l,currencies:[x,h],summary:`Collect Uniswap v4 fees for position #${a} (actions 0x0111). Preview deltas: ${C.join(", ")||"0"}.`}}},{name:"uniswap_remove",inputSchema:ct,async execute(t,d){if(T(d),t.version!==void 0&&t.version!=="v4")throw new o('Uniswap v4 part only handles version "v4".');let a=K(String(t.tokenId??""));if(a<=0n)throw new o("Provide a positive v4 position tokenId.");let p=e.clientFor(y),l=t.recipient!==void 0?String(t.recipient):d;if(T(l),w(l)!==w(d))throw new o("Uniswap recipient must be the signing wallet.");let m=await Ke(p,t.deadline,t.now),{poolKey:f,poolId:P}=await Pe(p,a,t),[b,u]=await Promise.all([B(p,f.currency0,y),B(p,f.currency1,y)]),v=t.slippageBps??Te;if(typeof v!="number")throw new o("Slippage must be an integer from 0 to 9999 bps.");Me("0",v);let x=typeof t.hookData=="string"?t.hookData:"0x",h=t.fullExit===!0||t.burn===!0||t.liquidity==="all";if(!h&&t.liquidity===void 0)throw new o('Provide a liquidity amount or explicitly choose liquidity "all" for a full exit.');let g=t.liquidity===void 0||t.liquidity==="all"?void 0:Z(t.liquidity,"liquidity");if(g!==void 0&&(g<0n||g===0n&&!h||g>J))throw new o("Provide positive liquidity within uint128 for v4 removal.");let A;try{A=BigInt(await p.readContract({address:M,abi:X,functionName:"getPositionLiquidity",args:[a]}))}catch($){throw new o(`Could not read v4 position liquidity. ${oe($)}`)}if(A<0n||A===0n&&!h||g!==void 0&&g>A)throw new o("Removal requires a nonempty position and cannot exceed its liquidity.");if(h&&g!==void 0&&g!==A)throw new o("A full burn must match the position liquidity; omit the amount when explicitly choosing all.");let I=h?"0x0311":"0x0111",F=($,U,O)=>{let te=h?S(Zn,[a,$,U,x]):S(ge,[a,g,$,U,x]),N=S(De,[f.currency0,f.currency1,O]);return e.unsignedTx({to:M.toLowerCase(),data:re({abi:X,functionName:"modifyLiquidities",args:[S(ue,[I,[te,N]]),m]}),value:"0",chainId:y,description:`${h?"Burn and exit":"Decrease"} Uniswap v4 position #${a} (${I}).`})},_=0n,j=0n;if(A>0n&&(t.amount0Min===void 0||t.amount1Min===void 0)){let $=e.unsignedTx({to:M.toLowerCase(),data:re({abi:X,functionName:"modifyLiquidities",args:[S(ue,["0x0111",[S(ge,[a,0n,0n,0n,x]),S(De,[f.currency0,f.currency1,M])]]),m]}),value:"0",chainId:y,description:"Simulation only: separate fees from removal principal."}),U=await e.preview([$,F(2n,2n,d)],d),O=te=>U.changes.reduce((N,ie)=>ie.token.chainId===y&&ie.token.address.toLowerCase()===te.address.toLowerCase()?N+BigInt(ie.amount):N,0n);if(_=O(b),j=O(u),_<0n||j<0n)throw new o("Removal simulation did not return the expected currencies.")}let C=($,U)=>{if($!==void 0&&Z($,U)!==0n)throw new o(`${U} must be zero for an empty position burn.`);return 0n},E=A===0n?C(t.amount0Min,"amount0Min"):hn(t.amount0Min,_,v,"amount0Min"),ee=A===0n?C(t.amount1Min,"amount1Min"):hn(t.amount1Min,j,v,"amount1Min"),ne=[F(E,ee,l)],W=await e.preview(ne,d),Y=Ne(W.changes,e.formatAmount);return{txs:ne,preview:W,action:I,tokenId:a.toString(),poolId:P,amount0Min:{token:b,amount:E.toString()},amount1Min:{token:u,amount:ee.toString()},summary:`${h?"Full exit":"Partial remove"} Uniswap v4 position #${a} (${I})${h?`; burns position #${a} at ${M}`:""}. Preview deltas: ${Y.join(", ")||"none"}.`}}},{name:"uniswap_list_positions",inputSchema:dt,async execute(t,d){if(T(d),t.version!==void 0&&t.version!=="v4")throw new o('Uniswap v4 part only handles version "v4".');let a=Array.isArray(t.tokenIds)?t.tokenIds:void 0,p=t.includeZero===!0,l=t.wallet===void 0?w(d):ot(t.wallet),m=await gn(e,l,{tokenIds:a,includeZero:p});return{version:"v4",positions:m,summary:`Found ${m.length} active Uniswap v4 position(s) for ${l}.`}}},{name:"uniswap_create_pool",inputSchema:st,async execute(t,d){if(T(d),t.version!==void 0&&t.version!=="v4")throw new o('Uniswap v4 part only handles version "v4".');kn(t);let a=e.clientFor(y),{poolId:p,poolKey:l}=await Be(a,t),[m,f]=await Promise.all([B(a,l.currency0,y),B(a,l.currency1,y)]),P=await a.readContract({address:le,abi:fe,functionName:"getSlot0",args:[p]});if(BigInt(P[0])>0n)throw new o(`Uniswap v4 pool ${p} already exists. Use uniswap_add to provide liquidity.`);let b=Pn(t,m.decimals,f.decimals),u=Ue(b,await vn(a,l),t.acceptPriceDeviation===!0,m.decimals,f.decimals),v=he(b,m.decimals,f.decimals),x=[xn(e,l,p,b,m,f)],h=await e.preview(x,d),g=ln(l,l.fee);return{txs:x,preview:h,poolId:p,poolKey:l,sqrtPriceX96:b.toString(),initialPrice:v,initialTick:_e(b),priceCheck:u,action:"createPool",summary:`${x[0].description} The pool starts empty: nothing trades until liquidity is added with uniswap_add. ${g.feeNote} ${u}`}}}],positions:t=>gn(e,t)}),St=pt;export{Vn as a,M as b,le as c,He as d,At as e,se as f,D as g,k as h,Xe as i,Fe as j,ve as k,Xn as l,Ve as m,Oe as n,Re as o,Sn as p,On as q,Rn as r,H as s,ye as t,In as u,ln as v,ke as w,et as x,nt as y,mn as z,tt as A,Cn as B,it as C,Ne as D,bn as E,B as F,Pe as G,gn as H,rt as I,st as J,at as K,ct as L,dt as M,vn as N,pt as O,St as P};
@@ -1,3 +1,3 @@
1
- import{c as O,e as T,i as M,j as x,k as V,m as D,n as N}from"./PZEF5LBL.js";import{a as b,b as h,c as R,e as f,f as A,g as k,h as P,i as I,j as v,l as S,m as B,n as $}from"./CSOO4SW7.js";import{a as y}from"./I6PQW2JI.js";import{a as E}from"./K6D6SDIG.js";import{a as c}from"./XSD5NL7J.js";import{encodeFunctionData as j,formatUnits as z}from"viem";var m=(o,e)=>({token:o,amount:e.toString()}),J=6e4;function ie(){let o=new WeakMap;return{entry(e){let r=o.get(e);return(!r||Date.now()>=r.expiresAt)&&(r={logs:new Map,expiresAt:Date.now()+J},o.set(e,r)),r}}}function K(o,e){return{to:o.log.address,data:j({abi:E,functionName:"debond",args:[e,[],[]]}),value:"0",chainId:4663,description:`Unwrap ${e} log base units from ${o.log.address}.`}}async function _(o,e,r,a,t=BigInt(e.measuredAtBlock),s){if(a>BigInt(e.totalSupply))throw new c("Unwrap amount exceeds the issued Chop log supply.");let i=h(await A(o,e.log.address,"convertToAssets",[a],t,r,s)),p=1n<<96n,d=BigInt(e.managedUnderlying)*(a*p/BigInt(e.totalSupply))/p;if(i>d)throw new c("Chop redemption exceeds the measured backing.");return{gross:m(e.underlying,d),fee:m(e.underlying,d-i),net:m(e.underlying,i)}}async function F(o,e){if(f(e),o.network==="testnet")throw new c("Chop requires chain 4663.");let r=o.clientFor(4663),a=await P(r,e),t=I();await v(r,y.registry,a,e,t);let s=await A(r,y.registry.address,"allIndexes",[],a,void 0,e);if(!Array.isArray(s)||s.length>1e3)throw new c("Chop registry inventory is unreadable or too large.");let i=s.filter(n=>n&&n.verified===!0).map(n=>b(n.index));if(new Set(i).size!==i.length)throw new c("Chop registry returned duplicate logs.");let p=[];for(let n=0;n<i.length;n+=4)f(e),p.push(...await Promise.all(i.slice(n,n+4).map(l=>S(r,l,"read",a,e,t))));f(e);let d=p.map(n=>`${n.log.symbol} (${n.log.address}): ${M(n)}`),u=p.flatMap(n=>n.drift.length?[`Code changed for ${n.log.address}: ${n.drift.join(", ")}.`]:[]);return{logs:p.map(n=>({...n,plainSummary:V(n)})),measuredAtBlock:a.toString(),warnings:[...T,...d,...u]}}async function se(o,e,r){if(f(r),!e)return F(o,r);let a=o.clientFor(4663),t=e.entry(a);if(t.inventory)return structuredClone(t.inventory);let s=t.pending;if(!s){let n=new AbortController,l={controller:n,waiters:0,promise:F(o,n.signal)};l.promise=l.promise.then(g=>{f(n.signal),t.inventory=structuredClone(g);for(let w of g.logs)t.logs.set(w.log.address.toLowerCase(),structuredClone(w));return g}).finally(()=>{n.abort(),t.pending===l&&(t.pending=void 0)}),t.pending=s=l}let i=s;i.waiters++;let p,d=!1,u=()=>{d||(d=!0,--i.waiters===0&&t.pending===i&&(i.controller.abort(),t.pending=void 0))};try{let n=await new Promise((l,g)=>{p=()=>{u(),g(new c("Chop read was cancelled."))},r?.addEventListener("abort",p,{once:!0}),i.promise.then(l,g)});return f(r),structuredClone(n)}finally{p&&r?.removeEventListener("abort",p),u()}}async function ae(o,e,r){let{limit:a,offset:t}=r,s=new Set(e.logs.map(l=>`${l.log.symbol} (${l.log.address}): ${M(l)}`)),i=e.warnings.filter(l=>!s.has(l)),p=Object.entries(e).map(([l,g])=>({name:l,chars:JSON.stringify(g).length,...Array.isArray(g)?{items:g.length}:{}})),d=o.clientFor(4663),u=e.logs.slice(t,t+a),n=[];for(let l=0;l<u.length;l+=4)n.push(...await Promise.all(u.slice(l,l+4).map(async g=>{let w=await k(d,[{target:g.pool,fn:"balanceOf",args:[g.staking.address]},{target:g.pool,fn:"totalSupply"}],BigInt(g.measuredAtBlock)),L=h(w[0]),C=h(w[1]);if(L>C)throw new c("Chop staked LP balance exceeds the pool supply.");return{log:g.log.address,symbol:g.log.symbol,backingPerLog:g.backingPerLog,fees:g.fees,pool:g.pool,stakedShare:{stakedLp:L.toString(),totalLp:C.toString(),bps:C===0n?null:Number(L*10000n/C)},riskLines:x(g).split(`
1
+ import{c as O,e as T,i as M,j as x,k as V,m as D,n as N}from"./ETMD747Y.js";import{a as b,b as h,c as R,e as f,f as A,g as k,h as P,i as I,j as v,l as S,m as B,n as $}from"./K4GUZ5QS.js";import{a as E}from"./K6D6SDIG.js";import{a as y}from"./L2AE32SL.js";import{a as c}from"./XSD5NL7J.js";import{encodeFunctionData as j,formatUnits as z}from"viem";var m=(o,e)=>({token:o,amount:e.toString()}),J=6e4;function ie(){let o=new WeakMap;return{entry(e){let r=o.get(e);return(!r||Date.now()>=r.expiresAt)&&(r={logs:new Map,expiresAt:Date.now()+J},o.set(e,r)),r}}}function K(o,e){return{to:o.log.address,data:j({abi:E,functionName:"debond",args:[e,[],[]]}),value:"0",chainId:4663,description:`Unwrap ${e} log base units from ${o.log.address}.`}}async function _(o,e,r,a,t=BigInt(e.measuredAtBlock),s){if(a>BigInt(e.totalSupply))throw new c("Unwrap amount exceeds the issued Chop log supply.");let i=h(await A(o,e.log.address,"convertToAssets",[a],t,r,s)),p=1n<<96n,d=BigInt(e.managedUnderlying)*(a*p/BigInt(e.totalSupply))/p;if(i>d)throw new c("Chop redemption exceeds the measured backing.");return{gross:m(e.underlying,d),fee:m(e.underlying,d-i),net:m(e.underlying,i)}}async function F(o,e){if(f(e),o.network==="testnet")throw new c("Chop requires chain 4663.");let r=o.clientFor(4663),a=await P(r,e),t=I();await v(r,y.registry,a,e,t);let s=await A(r,y.registry.address,"allIndexes",[],a,void 0,e);if(!Array.isArray(s)||s.length>1e3)throw new c("Chop registry inventory is unreadable or too large.");let i=s.filter(n=>n&&n.verified===!0).map(n=>b(n.index));if(new Set(i).size!==i.length)throw new c("Chop registry returned duplicate logs.");let p=[];for(let n=0;n<i.length;n+=4)f(e),p.push(...await Promise.all(i.slice(n,n+4).map(l=>S(r,l,"read",a,e,t))));f(e);let d=p.map(n=>`${n.log.symbol} (${n.log.address}): ${M(n)}`),u=p.flatMap(n=>n.drift.length?[`Code changed for ${n.log.address}: ${n.drift.join(", ")}.`]:[]);return{logs:p.map(n=>({...n,plainSummary:V(n)})),measuredAtBlock:a.toString(),warnings:[...T,...d,...u]}}async function se(o,e,r){if(f(r),!e)return F(o,r);let a=o.clientFor(4663),t=e.entry(a);if(t.inventory)return structuredClone(t.inventory);let s=t.pending;if(!s){let n=new AbortController,l={controller:n,waiters:0,promise:F(o,n.signal)};l.promise=l.promise.then(g=>{f(n.signal),t.inventory=structuredClone(g);for(let w of g.logs)t.logs.set(w.log.address.toLowerCase(),structuredClone(w));return g}).finally(()=>{n.abort(),t.pending===l&&(t.pending=void 0)}),t.pending=s=l}let i=s;i.waiters++;let p,d=!1,u=()=>{d||(d=!0,--i.waiters===0&&t.pending===i&&(i.controller.abort(),t.pending=void 0))};try{let n=await new Promise((l,g)=>{p=()=>{u(),g(new c("Chop read was cancelled."))},r?.addEventListener("abort",p,{once:!0}),i.promise.then(l,g)});return f(r),structuredClone(n)}finally{p&&r?.removeEventListener("abort",p),u()}}async function ae(o,e,r){let{limit:a,offset:t}=r,s=new Set(e.logs.map(l=>`${l.log.symbol} (${l.log.address}): ${M(l)}`)),i=e.warnings.filter(l=>!s.has(l)),p=Object.entries(e).map(([l,g])=>({name:l,chars:JSON.stringify(g).length,...Array.isArray(g)?{items:g.length}:{}})),d=o.clientFor(4663),u=e.logs.slice(t,t+a),n=[];for(let l=0;l<u.length;l+=4)n.push(...await Promise.all(u.slice(l,l+4).map(async g=>{let w=await k(d,[{target:g.pool,fn:"balanceOf",args:[g.staking.address]},{target:g.pool,fn:"totalSupply"}],BigInt(g.measuredAtBlock)),L=h(w[0]),C=h(w[1]);if(L>C)throw new c("Chop staked LP balance exceeds the pool supply.");return{log:g.log.address,symbol:g.log.symbol,backingPerLog:g.backingPerLog,fees:g.fees,pool:g.pool,stakedShare:{stakedLp:L.toString(),totalLp:C.toString(),bps:C===0n?null:Number(L*10000n/C)},riskLines:x(g).split(`
2
2
  `).filter(W=>!T.includes(W)).join(`
3
3
  `)}})));for(;;){let l=t+n.length,g=`Use detail: "full" for every complete row, or fields: ["logs"] or ["warnings"] for whole sections. ${l<e.logs.length?`Continue with offset: ${l}, limit: ${a}.`:"End of this list; use offset: 0 to start again."} Summary rows omit financial measurements and full contract metadata.`,w={warnings:i,summary:{logs:n,offset:t,total:e.logs.length,omitted:e.logs.length-n.length,measuredAtBlock:e.measuredAtBlock},sections:p,more:g};if(JSON.stringify(w).length<=8e3)return w;if(n.length<=1)throw new c('Chop risk lines exceed the summary budget. Request fields or detail: "full" to read them whole.');n.pop()}}async function de(o,e){let r=o.clientFor(4663),a=[];for(let t=0;t<e.length;t+=4)a.push(...await Promise.all(e.slice(t,t+4).map(async s=>{let[i,p,d,u]=await k(r,[{target:b(y.chop),fn:"balanceOf",args:[s.rewards]},{target:s.pool,fn:"token0"},{target:s.pool,fn:"token1"},{target:s.pool,fn:"getReserves"}],BigInt(s.measuredAtBlock)),n=[b(p),b(d)].map(g=>[s.log,s.paired].find(w=>w.address.toLowerCase()===g.toLowerCase()));if(!n[0]||!n[1]||n[0]===n[1])throw new c("Chop pool tokens disagree with the verified log.");if(!Array.isArray(u)||u.length!==3)throw new c("Chop pool reserves are unavailable.");let l=m(s.underlying,BigInt(s.managedUnderlying));return{...s,backingNow:{...l,humanAmount:z(BigInt(l.amount),s.underlying.decimals)},rewardPot:m({address:b(y.chop),symbol:"CHOP",decimals:18,chainId:4663},h(i)),reserves:[m(n[0],h(u[0])),m(n[1],h(u[1]))]}})));return a}var U=o=>BigInt(o.replace(".","")),H=o=>`${o/100n}.${(o%100n).toString().padStart(2,"0")}`;function le(o){return o.some(e=>e.usdEstimate===null)?{reserves:o,usdEstimate:null,estimateLabel:"price unavailable",estimateReason:"A pool reserve has no USD estimate"}:{reserves:o,usdEstimate:H(o.reduce((e,r)=>e+U(r.usdEstimate),0n)),estimateLabel:"estimate, not a quote",estimateSource:"sum of the two reserve estimates"}}function pe(o,e){let r={label:"rough",pct:null,inputToken:e,assumptions:"Constant-product marginal price move for buying the log with $100 of the paired token; excludes pool and token fees, gas and other trades."};if(o.some(d=>BigInt(d.amount)===0n))return{...r,reason:"The pool is empty on at least one side"};let a=o.find(d=>d.token.address.toLowerCase()===e.address.toLowerCase());if(!a?.usdEstimate||U(a.usdEstimate)===0n)return{...r,reason:"Paired reserve price unavailable or below one cent"};let t=U(a.usdEstimate),i=((t+10000n)**2n-t**2n)*10000n,p=t**2n;return{...r,pct:H((2n*i+p)/(2n*p))}}var q=new WeakMap,Y=10;async function Z(o,e,r,a,t,s){if(f(t),e.length>Y)throw new c("Chop holdings probes support at most ten logs per call.");if(e.length===0)return[];let i=t?q.get(t):void 0;t&&!i&&(i=I(),q.set(t,i)),await v(o,y.whitelist,a,t,i);let p=await k(o,e.flatMap(d=>[{target:d.log.address,fn:"balanceOf",args:[r]},{target:d.staking.address,fn:"balanceOf",args:[r]},{target:d.staking.address,fn:"withdrawableStake",args:[r]},{target:d.rewards,fn:"getUnpaid",args:[y.chop,r]},{target:d.rewards,fn:"getClaimable",args:[y.chop,r]},{target:y.whitelist.address,fn:"paused",args:[y.chop]},{target:d.log.address,fn:"totalSupply"},{target:d.log.address,fn:"totalAssets",args:[d.underlying.address]}]),a,t);return f(t),Promise.all(e.map(async(d,u)=>{let n=await Q(o,d,r,a,t,p.slice(u*8,(u+1)*8));return f(t),s?.(n,u),n}))}async function G(o,e,r,a=BigInt(e.measuredAtBlock),t){return(await Z(o,[e],r,a,t))[0]}async function Q(o,e,r,a,t,s){if(f(t),typeof s[5]!="boolean")throw new c("Chop reward pause state is unavailable.");let i=h(s[0]),p=h(s[6]),d=h(s[7]);if(p===0n)throw new c("This Chop log has no issued supply.");let u={...e,totalSupply:p.toString(),managedUnderlying:d.toString()},n=i===0n?{gross:m(e.underlying,0n),fee:m(e.underlying,0n),net:m(e.underlying,0n)}:await _(o,u,r,i,a,t),l={address:b(y.chop),symbol:"CHOP",decimals:18,chainId:4663};return{log:e.log.address,logTokens:m(e.log,i),...n,stakedLp:m(e.staking,h(s[1])),withdrawableLp:m(e.staking,h(s[2])),pendingChop:m(l,h(s[3])),claimableChop:m(l,h(s[4])),rewardsPaused:s[5],measuredAtBlock:a.toString(),warnings:x(e)}}async function ge(o,e,r,a){let t=o.clientFor(4663);b(r);let s=a?.entry(t),i=b(e).toLowerCase(),p=s?.logs.get(i)??await S(t,e,"read");return s&&!s.logs.has(i)&&s.logs.set(i,structuredClone(p)),G(t,p,r,await P(t))}async function ue(o,e,r,a){let t=R(a),s=o.clientFor(4663);b(r);let i=await S(s,e,"exit"),p=h(await A(s,i.log.address,"balanceOf",[r],BigInt(i.measuredAtBlock)));if(p===0n)throw new c(D(i.log.symbol));if(t>p)throw new c(N(i.log,t,p));let d=await _(s,i,r,t),u=BigInt(d.net.amount);if(u===0n)throw new c("This Chop unwrap would return no underlying.");let n=K(i,t),l=o.unsignedTx(n);B([l],[n]);let g=await o.preview([l],r);B(g.txs,[n]);let w=$(g,[{token:i.log,min:-t,max:-t},{token:i.underlying,min:u}]);return{log:i.log.address,amount:t.toString(),...d,simulatedNet:m(i.underlying,w.get(i.underlying.address.toLowerCase())),quotedNet:d.net.amount,preview:g,measuredAtBlock:i.measuredAtBlock,warning:O,summary:x(i)}}export{m as a,J as b,ie as c,K as d,_ as e,se as f,ae as g,de as h,le as i,pe as j,Y as k,Z as l,G as m,ge as n,ue as o};
@@ -1 +1 @@
1
- import{a as v}from"./OZ5MDUD2.js";import{h as w}from"./2GXHYI23.js";import{a as y}from"./JKD2B6OX.js";import{b as P,c as k,d as l}from"./2MZXTOZU.js";import{k as h}from"./U2YCQWZK.js";import{a as f}from"./43LI5NKJ.js";import{m as b,n as B}from"./NWNYJ26T.js";import{a as d}from"./FWD4L3CJ.js";import{a as s}from"./XSD5NL7J.js";import{erc20Abi as L,formatUnits as R}from"viem";var U=70515n,C=250202n,S=568341n;function N(a,r){return{token:{...a},amount:r.toString()}}function A(a){if(a.network!==void 0&&a.network!=="mainnet")throw new s("LayerBank requires chain 4663.")}async function g(a,r,n,e){try{return b(await a.readContract({address:r.address,abi:L,functionName:"balanceOf",args:[n],blockNumber:e}),"LayerBank returned a malformed wallet balance read.")}catch(t){throw t instanceof s?t:new s("LayerBank wallet balance could not be read. Please try again.")}}async function T(a,r,n){try{let[e,t]=await Promise.all([r.getGasPrice(),h("ETH",{client:r,http:a.http,chainId:d,blockNumber:n})]),i=B(t.usdE18,"LayerBank gas reference is unavailable.",{positive:!0}),c=b(e,"LayerBank gas reference is unavailable.");if(c===0n)throw new s("LayerBank gas reference is unavailable.");let u=m=>Number(R(m*c*i/10n**18n,18)),o=u(U+C),p=u(S);if(![o,p].every(m=>Number.isFinite(m)&&m>0))throw new s("LayerBank gas reference is unavailable.");return{gasInUsd:o,gasOutUsd:p}}catch{throw new s("LayerBank gas costs could not be checked against a fresh ETH/USD reference. Please try again.")}}async function x(a,r){A(a),f(r);let n=a.clientFor(d),e=await y(n),[t,i,c,u]=await Promise.all([g(n,k,r,e.blockNumber),g(n,l,r,e.blockNumber),v(a.http),T(a,n,e.blockNumber)]),o=[...c.checks,"Gas costs use measured USDG calls plus 20% headroom; entry includes approval and supply."];e.active||o.push("LayerBank reserve is inactive."),e.frozen&&o.push("LayerBank reserve is frozen for deposits."),e.paused&&o.push("LayerBank reserve is paused."),e.capRoomBase===0n&&o.push("LayerBank supply cap has no room left.");let p={rateBasePct:e.rateBasePct,...c.bonus==="unavailable"?{}:{bonus:c.bonus},cashUsdgBase:e.cashUsdgBase,capRoomBase:e.capRoomBase,open:e.active&&!e.frozen&&!e.paused&&e.capRoomBase>0n,walletUsdgBase:t,walletReceiptBase:i,...u,checks:o};return{reserve:e,reading:p}}function F(a){return async r=>{try{return(await x(a,r)).reading}catch(n){return{rateBasePct:0,cashUsdgBase:0n,capRoomBase:0n,open:!1,walletUsdgBase:0n,walletReceiptBase:0n,gasInUsd:0,gasOutUsd:0,checks:[n instanceof s?a.plainError(n):"LayerBank could not be checked right now. Please try again."]}}}}async function W(a,r){A(a),f(r);let n=a.clientFor(d),e=await y(n),t=await g(n,l,r,e.blockNumber);if(t===0n)return[];let i=a.formatAmount(t.toString(),6);return[{module:"layerbank",id:`${d}:${P}`,chainId:d,assets:[N(l,t)],economics:{principal:[w("redeemable",{token:{...k},amount:t.toString(),source:"layerbank.receiptBalance",heldAs:l.address,measuredAtBlock:e.blockNumber.toString()})],debt:[],rewards:[],backing:[],coverage:{complete:!0}},description:`${i} lRobUSDG = ${i} USDG; base supply rate ${e.rateBasePct}% a year, read now.`}]}export{U as a,C as b,S as c,N as d,A as e,g as f,x as g,F as h,W as i};
1
+ import{a as v}from"./OVM4QIET.js";import{h as w}from"./2GXHYI23.js";import{a as y}from"./MSRCJ2BS.js";import{b as P,c as k,d as l}from"./WAKZWSHB.js";import{m as h}from"./NV6FDIYT.js";import{a as f}from"./43LI5NKJ.js";import{m as b,n as B}from"./NWNYJ26T.js";import{b as d}from"./TI727O2H.js";import{a as s}from"./XSD5NL7J.js";import{erc20Abi as L,formatUnits as R}from"viem";var U=70515n,C=250202n,S=568341n;function N(a,r){return{token:{...a},amount:r.toString()}}function A(a){if(a.network!==void 0&&a.network!=="mainnet")throw new s("LayerBank requires chain 4663.")}async function g(a,r,n,e){try{return b(await a.readContract({address:r.address,abi:L,functionName:"balanceOf",args:[n],blockNumber:e}),"LayerBank returned a malformed wallet balance read.")}catch(t){throw t instanceof s?t:new s("LayerBank wallet balance could not be read. Please try again.")}}async function T(a,r,n){try{let[e,t]=await Promise.all([r.getGasPrice(),h("ETH",{client:r,http:a.http,chainId:d,blockNumber:n})]),i=B(t.usdE18,"LayerBank gas reference is unavailable.",{positive:!0}),c=b(e,"LayerBank gas reference is unavailable.");if(c===0n)throw new s("LayerBank gas reference is unavailable.");let u=m=>Number(R(m*c*i/10n**18n,18)),o=u(U+C),p=u(S);if(![o,p].every(m=>Number.isFinite(m)&&m>0))throw new s("LayerBank gas reference is unavailable.");return{gasInUsd:o,gasOutUsd:p}}catch{throw new s("LayerBank gas costs could not be checked against a fresh ETH/USD reference. Please try again.")}}async function x(a,r){A(a),f(r);let n=a.clientFor(d),e=await y(n),[t,i,c,u]=await Promise.all([g(n,k,r,e.blockNumber),g(n,l,r,e.blockNumber),v(a.http),T(a,n,e.blockNumber)]),o=[...c.checks,"Gas costs use measured USDG calls plus 20% headroom; entry includes approval and supply."];e.active||o.push("LayerBank reserve is inactive."),e.frozen&&o.push("LayerBank reserve is frozen for deposits."),e.paused&&o.push("LayerBank reserve is paused."),e.capRoomBase===0n&&o.push("LayerBank supply cap has no room left.");let p={rateBasePct:e.rateBasePct,...c.bonus==="unavailable"?{}:{bonus:c.bonus},cashUsdgBase:e.cashUsdgBase,capRoomBase:e.capRoomBase,open:e.active&&!e.frozen&&!e.paused&&e.capRoomBase>0n,walletUsdgBase:t,walletReceiptBase:i,...u,checks:o};return{reserve:e,reading:p}}function F(a){return async r=>{try{return(await x(a,r)).reading}catch(n){return{rateBasePct:0,cashUsdgBase:0n,capRoomBase:0n,open:!1,walletUsdgBase:0n,walletReceiptBase:0n,gasInUsd:0,gasOutUsd:0,checks:[n instanceof s?a.plainError(n):"LayerBank could not be checked right now. Please try again."]}}}}async function W(a,r){A(a),f(r);let n=a.clientFor(d),e=await y(n),t=await g(n,l,r,e.blockNumber);if(t===0n)return[];let i=a.formatAmount(t.toString(),6);return[{module:"layerbank",id:`${d}:${P}`,chainId:d,assets:[N(l,t)],economics:{principal:[w("redeemable",{token:{...k},amount:t.toString(),source:"layerbank.receiptBalance",heldAs:l.address,measuredAtBlock:e.blockNumber.toString()})],debt:[],rewards:[],backing:[],coverage:{complete:!0}},description:`${i} lRobUSDG = ${i} USDG; base supply rate ${e.rateBasePct}% a year, read now.`}]}export{U as a,C as b,S as c,N as d,A as e,g as f,x as g,F as h,W as i};
@@ -1 +1 @@
1
- import{a as p,f as u,g as c}from"./J73ATSEQ.js";import{f as a}from"./BAIY32AV.js";import{a as r}from"./66F5ZH34.js";import{a as i}from"./FWD4L3CJ.js";import{a as e}from"./XSD5NL7J.js";import{encodeFunctionData as d,parseAbi as f}from"viem";var m=f(["function deposit() payable","function withdraw(uint256)"]);function W(n){return{tools:[{name:"uniswap_wrap",inputSchema:{type:"object",additionalProperties:!1,required:["direction","amount"],properties:{direction:{description:'Choose "wrap" to exchange ETH for WETH, or "unwrap" to exchange WETH for ETH.',type:"string",enum:["wrap","unwrap"]},amount:r('Amount of ETH or WETH in base units (18 decimals). Example: "1000000000000000000" = 1 ETH or WETH.')}},async execute(t,s){if(c(t,["direction","amount"]),t.direction!=="wrap"&&t.direction!=="unwrap")throw new e("Choose direction wrap or unwrap.");let o=p(t.amount,"amount"),w=t.direction==="wrap"?d({abi:m,functionName:"deposit"}):d({abi:m,functionName:"withdraw",args:[o]});return u(n,[n.unsignedTx({to:a,data:w,value:t.direction==="wrap"?o.toString():"0",chainId:i,description:`${t.direction} ${o} ETH/WETH base units to the signing wallet.`})],s,"Wrap or unwrap native ETH at the pinned WETH contract. Ratio 1:1; network gas is additional.")}}]}}export{m as a,W as b};
1
+ import{a as p,f as u,g as c}from"./QPY6UTLU.js";import{f as a}from"./KLEJ3W4T.js";import{a as r}from"./66F5ZH34.js";import{b as i}from"./TI727O2H.js";import{a as e}from"./XSD5NL7J.js";import{encodeFunctionData as d,parseAbi as f}from"viem";var m=f(["function deposit() payable","function withdraw(uint256)"]);function W(n){return{tools:[{name:"uniswap_wrap",inputSchema:{type:"object",additionalProperties:!1,required:["direction","amount"],properties:{direction:{description:'Choose "wrap" to exchange ETH for WETH, or "unwrap" to exchange WETH for ETH.',type:"string",enum:["wrap","unwrap"]},amount:r('Amount of ETH or WETH in base units (18 decimals). Example: "1000000000000000000" = 1 ETH or WETH.')}},async execute(t,s){if(c(t,["direction","amount"]),t.direction!=="wrap"&&t.direction!=="unwrap")throw new e("Choose direction wrap or unwrap.");let o=p(t.amount,"amount"),w=t.direction==="wrap"?d({abi:m,functionName:"deposit"}):d({abi:m,functionName:"withdraw",args:[o]});return u(n,[n.unsignedTx({to:a,data:w,value:t.direction==="wrap"?o.toString():"0",chainId:i,description:`${t.direction} ${o} ETH/WETH base units to the signing wallet.`})],s,"Wrap or unwrap native ETH at the pinned WETH contract. Ratio 1:1; network gas is additional.")}}]}}export{m as a,W as b};
@@ -1 +1 @@
1
- var a={registry:{address:"0xF2A26110396b4162d48A16eE8683372a6A2c3b76",codeHash:"0xb08c7571b87c9a5d1d0d32b2a9accb4e4e923f191127a733072d99b00f463479"},helper:{address:"0x88BfFDf0ce9EB8889577924Cf802B2237bf8aD79",codeHash:"0xa33bd7460219439ad0e659548b6f08a71b3aab40ac02109ab69b364a00a5f036"},whitelist:{address:"0xab74612eB2ef5642fa804A52529fEDC6D98f6Cbd",codeHash:"0x335b0b4210eaa3c3d8956b16e2326851b54918bf85266b1fbf9c04461ea2a512"},beacon:{address:"0x5413041ebddd006f8b50a03a05236eade8fa884e",codeHash:"0xa0693b5efe62447f561c327fb56d7d1ab0930a5bb147a0f8844461a6b976b7f7"},implementation:{address:"0x1570a79aa494043DC01Ecc96405d5A8b45d24bDa",codeHash:"0xd3a1db41d5c42de3d2b6ff176e8603b9b825ff5603de555ed8f41cb270d71985"},staking:{codeHash:"0x533bcf9a4518b33b2bb541af1c1daa06f69ab6092cfd84944c1d57ebec825a69"},rewards:{codeHash:"0x6a482e5367e1aced7f5448e31e40140e4b899959376d040e0be502c37ce739b1"},proxy:{codeHash:"0x813f4e3ccc34b924559faf1f81706763c9649bad4c4f6c07547acd5713f481b9"},stakingBeacon:{address:"0x9df506ae33dad46c83d226be462849c3071f63ac",codeHash:"0xa0693b5efe62447f561c327fb56d7d1ab0930a5bb147a0f8844461a6b976b7f7"},stakingImplementation:{address:"0x4c6b1D5377e353C6959C65d389aAe3127a84EC4e",codeHash:"0x30c917d96f73c2075d7d0cca801cd34c459060567ec90dfdb30b361bf29dd2ed"},rewardsBeacon:{address:"0x4768574074cf48b025457b14d109983079952134",codeHash:"0xa0693b5efe62447f561c327fb56d7d1ab0930a5bb147a0f8844461a6b976b7f7"},rewardsImplementation:{address:"0x15a8Ef0EA82c5D087BD8D89b5D10BA85FfD3BefE",codeHash:"0x2cdf99c071739c5bbde722901ab43a9085674c99647372d6d66ad2bec10ee3db"},oak:"0x6511c233790Ec10f7d673c64DC82C3F941D57828",dormantOak:"0x38fE199550E677Fa9caC196495460dfF97BCe28F",chop:"0x100765a16f42636Bd84EE1e86Bc5107b84bCdBA3",chainId:4663,measuredAtBlock:"106718816",source:"https://rpc.mainnet.chain.robinhood.com"};export{a};
1
+ var a={registry:{address:"0xF2A26110396b4162d48A16eE8683372a6A2c3b76",codeHash:"0xb08c7571b87c9a5d1d0d32b2a9accb4e4e923f191127a733072d99b00f463479"},helper:{address:"0x88BfFDf0ce9EB8889577924Cf802B2237bf8aD79",codeHash:"0xa33bd7460219439ad0e659548b6f08a71b3aab40ac02109ab69b364a00a5f036"},whitelist:{address:"0xab74612eB2ef5642fa804A52529fEDC6D98f6Cbd",codeHash:"0x335b0b4210eaa3c3d8956b16e2326851b54918bf85266b1fbf9c04461ea2a512"},beacon:{address:"0x5413041ebddd006f8b50a03a05236eade8fa884e",codeHash:"0xa0693b5efe62447f561c327fb56d7d1ab0930a5bb147a0f8844461a6b976b7f7"},implementation:{address:"0x1570a79aa494043DC01Ecc96405d5A8b45d24bDa",codeHash:"0xd3a1db41d5c42de3d2b6ff176e8603b9b825ff5603de555ed8f41cb270d71985"},staking:{codeHash:"0x533bcf9a4518b33b2bb541af1c1daa06f69ab6092cfd84944c1d57ebec825a69"},rewards:{codeHash:"0x6a482e5367e1aced7f5448e31e40140e4b899959376d040e0be502c37ce739b1"},proxy:{codeHash:"0x813f4e3ccc34b924559faf1f81706763c9649bad4c4f6c07547acd5713f481b9"},stakingBeacon:{address:"0x9df506ae33dad46c83d226be462849c3071f63ac",codeHash:"0xa0693b5efe62447f561c327fb56d7d1ab0930a5bb147a0f8844461a6b976b7f7"},stakingImplementation:{address:"0x4c6b1D5377e353C6959C65d389aAe3127a84EC4e",codeHash:"0x30c917d96f73c2075d7d0cca801cd34c459060567ec90dfdb30b361bf29dd2ed"},rewardsBeacon:{address:"0x4768574074cf48b025457b14d109983079952134",codeHash:"0xa0693b5efe62447f561c327fb56d7d1ab0930a5bb147a0f8844461a6b976b7f7"},rewardsImplementation:{address:"0x15a8Ef0EA82c5D087BD8D89b5D10BA85FfD3BefE",codeHash:"0x2cdf99c071739c5bbde722901ab43a9085674c99647372d6d66ad2bec10ee3db"},oak:"0x6511c233790Ec10f7d673c64DC82C3F941D57828",dormantOak:"0x38fE199550E677Fa9caC196495460dfF97BCe28F",chop:"0x100765a16f42636Bd84EE1e86Bc5107b84bCdBA3",chainId:4663,measuredAtBlock:"106718816",source:"https://rpc.mainnet.chain.robinhood.com"},d={poolId:"0x8111082d181841cbd123e82bced032b1331140332b6ce3da37f53a6b24ed736c",stateView:"0xf3334192d15450cdd385c8b70e03f9a6bd9e673b",poolManager:"0x8366a39cc670b4001a1121b8f6a443a643e40951",key:{currency0:"0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73",currency1:"0x100765a16f42636Bd84EE1e86Bc5107b84bCdBA3",fee:8388608,tickSpacing:200,hooks:"0x4e3468951D49f2EEa976eD0D6e75fFCb44a9a544"},dustV2Pool:"0x32c9b1748b914fd740054518d9322240a14b8aec"};export{a,d as b};
@@ -1 +1 @@
1
- import{b as f}from"./L646YWDP.js";import{a as p}from"./43LI5NKJ.js";import{a as u}from"./FWD4L3CJ.js";import{a as n}from"./XSD5NL7J.js";import{encodeFunctionData as A,getAddress as w,parseAbi as T,parseAbiItem as F}from"viem";var R=[["setOwner(address newOwner)","owner"],["setCurator(address newCurator)","owner"],["setIsSentinel(address account,bool enabled)","owner"],["setName(string name)","owner"],["setSymbol(string symbol)","owner"],["setIsAllocator(address account,bool enabled)","timelock"],["setReceiveSharesGate(address gate)","timelock"],["setSendSharesGate(address gate)","timelock"],["setReceiveAssetsGate(address gate)","timelock"],["setSendAssetsGate(address gate)","timelock"],["setAdapterRegistry(address registry)","timelock"],["addAdapter(address adapter)","timelock"],["removeAdapter(address adapter)","timelock"],["increaseTimelock(bytes4 selector,uint256 duration)","timelock"],["decreaseTimelock(bytes4 selector,uint256 duration)","timelock"],["abdicate(bytes4 selector)","timelock"],["setPerformanceFee(uint256 fee)","timelock"],["setManagementFee(uint256 fee)","timelock"],["setPerformanceFeeRecipient(address recipient)","timelock"],["setManagementFeeRecipient(address recipient)","timelock"],["increaseAbsoluteCap(bytes idData,uint256 cap)","timelock"],["increaseRelativeCap(bytes idData,uint256 cap)","timelock"],["decreaseAbsoluteCap(bytes idData,uint256 cap)","curatorOrSentinel"],["decreaseRelativeCap(bytes idData,uint256 cap)","curatorOrSentinel"],["setForceDeallocatePenalty(address adapter,uint256 penalty)","timelock"],["allocate(address adapter,bytes data,uint256 assets)","allocator"],["deallocate(address adapter,bytes data,uint256 assets)","allocatorOrSentinel"],["setLiquidityAdapterAndData(address adapter,bytes data)","allocator"],["setMaxRate(uint256 rate)","allocator"],["accrueInterest()","any"]],S=R.map(([a,t])=>({abi:F(`function ${a}`),authority:t})),x=T(["function asset() view returns (address)","function owner() view returns (address)","function curator() view returns (address)","function isSentinel(address) view returns (bool)","function isAllocator(address) view returns (bool)","function executableAt(bytes) view returns (uint256)","function abdicated(bytes4) view returns (bool)","function submit(bytes data)","function revoke(bytes data)"]);function M(a,t){if(a==="bool"){if(typeof t!="boolean")throw new n("Boolean operation values must be booleans.");return t}if(typeof t!="string")throw new n("All address, byte, text and integer operation values must be strings.");if(a==="address")return p(t),w(t);if(a==="uint256"){if(!/^\d+$/.test(t)||BigInt(t)>=1n<<256n)throw new n("Integer operation values must be uint256 decimal base-unit strings.");return BigInt(t)}if((a==="bytes"||a==="bytes4")&&!(a==="bytes4"?/^0x[0-9a-f]{8}$/i:/^0x(?:[0-9a-f]{2})*$/i).test(t))throw new n("Invalid hexadecimal operation bytes.");return t}function V(a,t,m,O){return{name:t,inputSchema:{type:"object",additionalProperties:!1,required:["operation","values"],properties:{operation:{type:"string",enum:S.map(i=>i.abi.name),description:"Vault management function to call (role-gated curator, owner, allocator or sentinel actions); values supplies its arguments in order."},values:{type:"array",maxItems:3,items:{oneOf:[{type:"string"},{type:"boolean"}]},description:"Ordered ABI values. Integers are decimal base-unit strings; addresses and bytes are explicit strings."},mode:{enum:["call","submit","revoke"],default:"call",description:"Submit/revoke only for timelocked curator operations. Execution is a separate call after the delay."}}},execute:async(i,c)=>{try{if(p(c),Object.keys(i).some(e=>!["operation","values","mode"].includes(e)))throw new n("Unexpected vault management argument.");let r=S.find(e=>e.abi.name===i.operation);if(!r||!Array.isArray(i.values)||i.values.length!==r.abi.inputs.length)throw new n("Provide a supported operation and its exact ordered values.");let o=i.mode??"call";if(!["call","submit","revoke"].includes(String(o))||o!=="call"&&r.authority!=="timelock")throw new n("Submit/revoke is available only for timelocked curator operations.");let I=r.abi.inputs.map((e,d)=>M(e.type,i.values[d])),l=A({abi:[r.abi],functionName:r.abi.name,args:I}),b=a.clientFor(u);if(await b.getChainId()!==u)throw new n("Vault management requires chain 4663.");let s=(e,d=[])=>b.readContract({address:m,abi:x,functionName:e,args:d}),y=await s("asset");if(typeof y!="string"||w(y)!==w(O.address))throw new n("Vault management requires the pinned vault asset.");let g=e=>typeof e=="string"&&e.toLowerCase()===c.toLowerCase(),C=async e=>e==="any"?!0:e==="owner"?g(await s("owner")):e==="allocator"?await s("isAllocator",[c])===!0:e==="allocatorOrSentinel"?await s("isAllocator",[c])===!0||await s("isSentinel",[c])===!0:g(await s("curator"))||e==="curatorOrSentinel"&&await s("isSentinel",[c])===!0;if(r.authority==="timelock"&&o==="call"){let[e,d,D]=await Promise.all([s("executableAt",[l]),s("abdicated",[l.slice(0,10)]),b.getBlock()]);if(f(e)===0n||f(e)>D.timestamp||d!==!1)throw new n("This exact operation has not matured or its selector is abdicated. Submit it with the curator, then wait for its executable time.")}else if(!await C(o==="submit"?"timelock":o==="revoke"?"curatorOrSentinel":r.authority))throw new n("This wallet does not hold the required vault management role. No transaction was built.");let $=o==="call"?l:A({abi:x,functionName:o==="submit"?"submit":"revoke",args:[l]}),k=`${o} ${r.abi.name} on ${m}; ordered values ${JSON.stringify(i.values)}. ${r.abi.name==="abdicate"?"Abdication is irreversible.":""}`,h=[a.unsignedTx({to:m,data:$,value:"0",chainId:u,description:k})],v=await a.preview(h,c);return{txs:h,preview:v,summary:`${k} ${v.summary} ${o==="submit"?"Submission schedules this exact operation; it does not execute the configuration change.":"Role, cap and timing checks can change before execution."}`}}catch(r){throw new n(a.plainError(r))}}}}export{S as a,M as b,V as c};
1
+ import{b as f}from"./X24YTJST.js";import{a as p}from"./43LI5NKJ.js";import{b as u}from"./TI727O2H.js";import{a as n}from"./XSD5NL7J.js";import{encodeFunctionData as A,getAddress as w,parseAbi as T,parseAbiItem as F}from"viem";var R=[["setOwner(address newOwner)","owner"],["setCurator(address newCurator)","owner"],["setIsSentinel(address account,bool enabled)","owner"],["setName(string name)","owner"],["setSymbol(string symbol)","owner"],["setIsAllocator(address account,bool enabled)","timelock"],["setReceiveSharesGate(address gate)","timelock"],["setSendSharesGate(address gate)","timelock"],["setReceiveAssetsGate(address gate)","timelock"],["setSendAssetsGate(address gate)","timelock"],["setAdapterRegistry(address registry)","timelock"],["addAdapter(address adapter)","timelock"],["removeAdapter(address adapter)","timelock"],["increaseTimelock(bytes4 selector,uint256 duration)","timelock"],["decreaseTimelock(bytes4 selector,uint256 duration)","timelock"],["abdicate(bytes4 selector)","timelock"],["setPerformanceFee(uint256 fee)","timelock"],["setManagementFee(uint256 fee)","timelock"],["setPerformanceFeeRecipient(address recipient)","timelock"],["setManagementFeeRecipient(address recipient)","timelock"],["increaseAbsoluteCap(bytes idData,uint256 cap)","timelock"],["increaseRelativeCap(bytes idData,uint256 cap)","timelock"],["decreaseAbsoluteCap(bytes idData,uint256 cap)","curatorOrSentinel"],["decreaseRelativeCap(bytes idData,uint256 cap)","curatorOrSentinel"],["setForceDeallocatePenalty(address adapter,uint256 penalty)","timelock"],["allocate(address adapter,bytes data,uint256 assets)","allocator"],["deallocate(address adapter,bytes data,uint256 assets)","allocatorOrSentinel"],["setLiquidityAdapterAndData(address adapter,bytes data)","allocator"],["setMaxRate(uint256 rate)","allocator"],["accrueInterest()","any"]],S=R.map(([a,t])=>({abi:F(`function ${a}`),authority:t})),x=T(["function asset() view returns (address)","function owner() view returns (address)","function curator() view returns (address)","function isSentinel(address) view returns (bool)","function isAllocator(address) view returns (bool)","function executableAt(bytes) view returns (uint256)","function abdicated(bytes4) view returns (bool)","function submit(bytes data)","function revoke(bytes data)"]);function M(a,t){if(a==="bool"){if(typeof t!="boolean")throw new n("Boolean operation values must be booleans.");return t}if(typeof t!="string")throw new n("All address, byte, text and integer operation values must be strings.");if(a==="address")return p(t),w(t);if(a==="uint256"){if(!/^\d+$/.test(t)||BigInt(t)>=1n<<256n)throw new n("Integer operation values must be uint256 decimal base-unit strings.");return BigInt(t)}if((a==="bytes"||a==="bytes4")&&!(a==="bytes4"?/^0x[0-9a-f]{8}$/i:/^0x(?:[0-9a-f]{2})*$/i).test(t))throw new n("Invalid hexadecimal operation bytes.");return t}function V(a,t,m,O){return{name:t,inputSchema:{type:"object",additionalProperties:!1,required:["operation","values"],properties:{operation:{type:"string",enum:S.map(i=>i.abi.name),description:"Vault management function to call (role-gated curator, owner, allocator or sentinel actions); values supplies its arguments in order."},values:{type:"array",maxItems:3,items:{oneOf:[{type:"string"},{type:"boolean"}]},description:"Ordered ABI values. Integers are decimal base-unit strings; addresses and bytes are explicit strings."},mode:{enum:["call","submit","revoke"],default:"call",description:"Submit/revoke only for timelocked curator operations. Execution is a separate call after the delay."}}},execute:async(i,c)=>{try{if(p(c),Object.keys(i).some(e=>!["operation","values","mode"].includes(e)))throw new n("Unexpected vault management argument.");let r=S.find(e=>e.abi.name===i.operation);if(!r||!Array.isArray(i.values)||i.values.length!==r.abi.inputs.length)throw new n("Provide a supported operation and its exact ordered values.");let o=i.mode??"call";if(!["call","submit","revoke"].includes(String(o))||o!=="call"&&r.authority!=="timelock")throw new n("Submit/revoke is available only for timelocked curator operations.");let I=r.abi.inputs.map((e,d)=>M(e.type,i.values[d])),l=A({abi:[r.abi],functionName:r.abi.name,args:I}),b=a.clientFor(u);if(await b.getChainId()!==u)throw new n("Vault management requires chain 4663.");let s=(e,d=[])=>b.readContract({address:m,abi:x,functionName:e,args:d}),y=await s("asset");if(typeof y!="string"||w(y)!==w(O.address))throw new n("Vault management requires the pinned vault asset.");let g=e=>typeof e=="string"&&e.toLowerCase()===c.toLowerCase(),C=async e=>e==="any"?!0:e==="owner"?g(await s("owner")):e==="allocator"?await s("isAllocator",[c])===!0:e==="allocatorOrSentinel"?await s("isAllocator",[c])===!0||await s("isSentinel",[c])===!0:g(await s("curator"))||e==="curatorOrSentinel"&&await s("isSentinel",[c])===!0;if(r.authority==="timelock"&&o==="call"){let[e,d,D]=await Promise.all([s("executableAt",[l]),s("abdicated",[l.slice(0,10)]),b.getBlock()]);if(f(e)===0n||f(e)>D.timestamp||d!==!1)throw new n("This exact operation has not matured or its selector is abdicated. Submit it with the curator, then wait for its executable time.")}else if(!await C(o==="submit"?"timelock":o==="revoke"?"curatorOrSentinel":r.authority))throw new n("This wallet does not hold the required vault management role. No transaction was built.");let $=o==="call"?l:A({abi:x,functionName:o==="submit"?"submit":"revoke",args:[l]}),k=`${o} ${r.abi.name} on ${m}; ordered values ${JSON.stringify(i.values)}. ${r.abi.name==="abdicate"?"Abdication is irreversible.":""}`,h=[a.unsignedTx({to:m,data:$,value:"0",chainId:u,description:k})],v=await a.preview(h,c);return{txs:h,preview:v,summary:`${k} ${v.summary} ${o==="submit"?"Submission schedules this exact operation; it does not execute the configuration change.":"Role, cap and timing checks can change before execution."}`}}catch(r){throw new n(a.plainError(r))}}}}export{S as a,M as b,V as c};
@@ -0,0 +1,3 @@
1
+ import{b as W}from"./JDSSYT6R.js";import{a as M,b as U}from"./IBL6TL2Q.js";import{a as b,b as P}from"./G2AA73ZE.js";import{fa as F,ga as G,ja as A}from"./HHYE42JG.js";import{g as $,i as T,m as I,n as O}from"./NWNYJ26T.js";import{d as V}from"./IX3GZMTM.js";import{b as v}from"./TI727O2H.js";import{a as n}from"./XSD5NL7J.js";import{encodeFunctionData as R}from"viem";var j={asset:{type:"string",pattern:"^[A-Za-z0-9.$_-]{1,32}$",description:"Official asset symbol; use vault if discovery is unavailable or ambiguous."},vault:{type:"string",pattern:"^0x[0-9a-fA-F]{40}$",description:"Vault address verified on chain on every call; required for a rebuild without HTTP."}};function E(r){return{type:"object",additionalProperties:!1,properties:{...j,amount:{type:"string",pattern:r==="withdraw"?"^(?:[0-9]+|max)$":"^[0-9]+$",description:'Selected vault asset amount in base units using its decimals (USDG has 6: "1000000" = 1 USDG); withdraw also accepts max to redeem all shares.'}},required:["amount"],anyOf:[{required:["asset"]},{required:["vault"]}]}}function H(r){return O(r,"Borro amount must be positive and fit uint256.",{positive:!0,notString:"Borro amount must be an integer string in asset base units."})}function B(r){return I(r,"Borro returned an invalid uint256 read.")}var L=r=>r*9950n/10000n,Z=new WeakMap;function oe(r,o){Z.set(r,{...o})}async function K(r,o,h,i=W){let k=await i(r,o).catch(()=>({kind:"unknown"})),f=k.kind!=="unknown"&&"readyBase"in k?k.readyBase:void 0,l=typeof f=="bigint"&&f>=0n&&f<1n<<256n?f:void 0,g=y=>V(y.toString(),o.assetDecimals);return{ready:l,...l!==void 0&&l<h?{refusal:A("too-little-ready",{ready:g(l),requested:g(h),maxNow:g(l),symbol:o.symbol})}:{}}}function z(r,o,h,i,k){let f=0n,l=0n;for(let g of r.changes){let y=g.token;if(typeof g.amount!="string"||!/^-?\d+$/.test(g.amount))throw new n("Borro preview returned invalid token changes. Nothing was signed.");let e=BigInt(g.amount);B(e<0n?-e:e);let d=$(y.address,o.address)?o:$(y.address,i.address)?i:void 0;if(!d||y.chainId!==v||y.decimals!==d.decimals)throw new n("Borro preview showed an unexpected token movement. Nothing was signed.");if(d===o){if(e>0n)throw new n("Borro preview showed a reversed input movement. Nothing was signed.");f-=e}else{if(e<0n)throw new n("Borro preview showed a reversed output movement. Nothing was signed.");l+=e}}if(B(f),B(l),f!==h||l<k||l===0n)throw new n("Borro preview did not match the requested receipt. Nothing was signed.")}var re=r=>{let{client:o,context:h,wallet:i}=r;async function k(e,d,s){if(T(s,"Provide a valid wallet address."),!$(s,i))throw new n("Borro action wallet differs from the signing wallet. Nothing was signed.");if(h.network==="testnet"||await o.getChainId()!==v)throw new n("Borro requires chain 4663. Nothing was signed.");if(Object.keys(e).some(m=>!["asset","vault","amount"].includes(m)))throw new n("Unsupported Borro argument.");if(e.asset!==void 0&&(typeof e.asset!="string"||!/^[A-Za-z0-9.$_-]{1,32}$/.test(e.asset)||/^0x/i.test(e.asset)))throw new n("Provide an asset symbol, or put the vault address in vault.");let w=e.vault===void 0?void 0:T(e.vault,"Provide a valid Borro vault address.");if(!w&&e.asset===void 0)throw new n("Provide an asset symbol or a vault address.");let t=w?await r.verifyVault(o,w,d,{wallet:i}):await r.resolveVault(o,{asset:e.asset},d,i);if(w&&!$(w,t.vault)||e.asset!==void 0&&e.asset.toUpperCase()!==t.symbol.toUpperCase())throw new n("Borro vault and asset selectors do not match. Nothing was signed.");if(T(t.vault,"Borro returned an invalid vault address."),T(t.asset,"Borro returned an invalid asset address."),t.chainId!==v||t.shareDecimals!==18||$(t.asset,t.vault)||!Number.isInteger(t.assetDecimals)||t.assetDecimals<0||t.assetDecimals>255||t.mode!==d)throw new n(A("setup-mismatch",{}));let a=await r.verifySetup(o,t,d);if(!a.ok||d==="deposit"&&(!t.assetAllowed||a.drift.length>0))throw new n(A("setup-mismatch",{}));return{...t,setup:a}}function f(e){let d=e.mode==="withdraw"&&!/^[A-Za-z0-9.$_-]{1,16}$/.test(e.symbol)?"token":e.symbol;return{asset:{address:T(e.asset,"Borro returned an invalid asset."),symbol:d,decimals:e.assetDecimals,chainId:v},share:{address:T(e.vault,"Borro returned an invalid vault."),symbol:e.vaultSymbol,decimals:18,chainId:v}}}let l=(e,d)=>h.formatAmount(e.toString(),d),g="The minimum is checked in the preview; standard ERC-4626 calldata does not enforce it on chain. Re-preview before signing; execution output can change.",y=[{name:"borro_deposit",inputSchema:E("deposit"),execute:async(e,d)=>{let s=H(e.amount),w=await k(e,"deposit",d),{asset:t,share:a}=f(w),m=B(await o.readContract({address:t.address,abi:b,functionName:"balanceOf",args:[i]}));if(s>m)throw new n("This wallet does not hold enough of that asset for the Borro deposit.");let p=B(await o.readContract({address:a.address,abi:b,functionName:"previewDeposit",args:[s]}));if(p===0n)throw new n(A("deposit-would-revert",{}));let c=w.builderEligible===!0,u=Z.get(e);if(u&&(!c||!$(u.token,a.address)||!$(u.recipient,i)||u.minimum<=0n||u.minimum>p))throw new n(A("deposit-would-revert",{}));let S=u?.minimum??L(p),C=c?M.builders.address:a.address,N=[h.approval(t.address,C,s.toString(),v),h.unsignedTx({to:C,data:c?R({abi:P,functionName:"deposit",args:[a.address,s,U,S]}):R({abi:b,functionName:"deposit",args:[s,i]}),value:"0",chainId:v,description:`Deposit ${s} asset base units into Borro vault ${a.address}.`})],x;try{x=await h.preview(N,i),z(x,t,s,a,S)}catch{throw new n(A("deposit-would-revert",{}))}let D=w.deployedAt===void 0?void 0:Date.parse(w.deployedAt)/1e3,_=F({viaBuilder:c,amount:l(s,t.decimals),symbol:t.symbol,kind:t.symbol==="USDG"?"usdg":"stock",shares:l(p,18),sharesMin:l(S,18),vaultSymbol:a.symbol,deployedAtSeconds:D,nowSeconds:Math.floor(Date.now()/1e3)});return{txs:N,preview:x,vault:a.address,asset:t,shareToken:a,amount:s.toString(),shares:p.toString(),shares_min:S.toString(),summary:`${_}
2
+ Base units: amount ${s} (${t.address}, decimals ${t.decimals}); shares ${p} (${a.address}, decimals 18); shares_min ${S}.`}}},{name:"borro_withdraw",inputSchema:E("withdraw"),execute:async(e,d)=>{let s=e.amount==="max",w=s?void 0:H(e.amount),t=await k(e,"withdraw",d),{asset:a,share:m}=f(t),p=B(await o.readContract({address:m.address,abi:b,functionName:"balanceOf",args:[i]}));if(p===0n)throw new n(A("no-shares",{symbol:a.symbol}));let c=s?p:B(await o.readContract({address:m.address,abi:b,functionName:"previewWithdraw",args:[w]}));if(c===0n||c>p)throw new n("This wallet does not hold enough Borro shares for that withdrawal.");let u=w??B(await o.readContract({address:m.address,abi:b,functionName:"previewRedeem",args:[c]}));if(u===0n)throw new n("Borro preview returned no assets for these shares. Nothing was signed.");let{ready:S,refusal:C}=await K(o,{...t,symbol:a.symbol},u,r.readLiquidity);if(C!==void 0)return{txs:[],vault:m.address,asset:a,shareToken:m,amount:u.toString(),shares:c.toString(),max_now:S.toString(),summary:C};let N=s?L(u):u,x=[h.unsignedTx({to:m.address,data:s?R({abi:b,functionName:"redeem",args:[c,i,i]}):R({abi:b,functionName:"withdraw",args:[u,i,i]}),value:"0",chainId:v,description:`Withdraw ${u} asset base units from Borro vault ${m.address}${s?` for ${c} share base units`:""}.`})],D=s?await h.preview(x,i):await h.preview(x,i,{reads:[{to:m.address,data:R({abi:b,functionName:"previewWithdraw",args:[u]}),chainId:v}]});if(!s){let q=D.readResults?.[0];if(D.readResults?.length!==1||typeof q!="string"||!/^0x[0-9a-fA-F]{64}$/.test(q))throw new n("Borro preview returned an invalid share quote. Nothing was signed.");if(c=B(BigInt(q)),c===0n||c>p)throw new n("This wallet does not hold enough Borro shares for that withdrawal.")}z(D,m,c,a,N);let _=G({amount:l(u,a.decimals),isAll:s,symbol:a.symbol,out:l(u,a.decimals),shares:l(c,18),vaultSymbol:m.symbol,drift:t.setup.drift.length>0});return{txs:x,preview:D,vault:m.address,asset:a,shareToken:m,amount:u.toString(),shares:c.toString(),assets_min:N.toString(),isMax:s,setup:t.setup,summary:`${_}
3
+ Base units: amount ${u} (${a.address}, decimals ${a.decimals}); shares ${c} (${m.address}, decimals 18); assets_min ${N}. ${g}`}}}];for(let e of y){let d=e.execute;e.execute=async(s,w)=>{try{return await d(s,w)}catch(t){throw new n(h.plainError(t))}}}return y};export{oe as a,K as b,re as c};
@@ -1 +1 @@
1
- var r=["netnet_blackjack_finalize","netnet_blackjack_expire","netnet_blackjack_claim"];function s(e,n){if(!r.includes(e))return!1;let a=n[e==="netnet_blackjack_claim"?"seriesId":"sessionId"];return Object.keys(n).length===1&&typeof a=="string"&&/^[1-9]\d{0,77}$/.test(a)&&BigInt(a)<1n<<256n}var t={setApprovalForAll:"Collection-wide card approval is not supportable under current policy. Owner transfers and burns need no approval.",seat:"New blackjack seating is disabled: channel State has no protocol-enforced signature expiry, so Oak cannot safely activate its signing key.",play:"Blackjack channel state has no protocol-enforced signature expiry under Oak\u2019s signing contract; nothing was signed.",signatures:"Existing blackjack signature relay needs a separately qualified signing contract, hash, signer and nonce validation. Signature import is disabled.",conversion:"NetNet card conversion is disabled until the router route, calldata, value and asset exits have been qualified. Arbitrary swap bytes are refused."};function o(e,n){if(r.includes(e)&&!s(e,n))return"Recovery accepts exactly one positive decimal session or series ID; recipients, signatures and extra fields are refused.";if(e==="netnet_turbo_action")return n.operation==="setApprovalForAll"?t.setApprovalForAll:["convertPremiums","convertSleeveFees"].includes(String(n.operation))?t.conversion:"TURBO card actions are unavailable. Read card balances and existing blackjack sessions to inspect their status.";if(e==="netnet_blackjack_seat")return t.seat;if(e==="netnet_blackjack_play"||e==="netnet_blackjack_action")return t.play}export{r as a,s as b,t as c,o as d};
1
+ var s=["netnet_blackjack_finalize","netnet_blackjack_expire","netnet_blackjack_claim"];function i(e,n){if(!s.includes(e))return!1;let a=n[e==="netnet_blackjack_claim"?"seriesId":"sessionId"];return Object.keys(n).length===1&&typeof a=="string"&&/^[1-9]\d{0,77}$/.test(a)&&BigInt(a)<1n<<256n}var t={setApprovalForAll:"Collection-wide card approval is not supportable under current policy. Owner transfers and burns need no approval.",seat:"New blackjack seating is disabled: channel State has no protocol-enforced signature expiry, so Oak cannot safely activate its signing key.",play:"Blackjack channel state has no protocol-enforced signature expiry under Oak\u2019s signing contract; nothing was signed.",signatures:"Existing blackjack signature relay needs a separately qualified signing contract, hash, signer and nonce validation. Signature import is disabled.",conversion:"NetNet card conversion is disabled until the router route, calldata, value and asset exits have been qualified. Arbitrary swap bytes are refused."};function o(e,n){if(s.includes(e)&&!i(e,n))return"Recovery accepts exactly one positive decimal session or series ID; recipients, signatures and extra fields are refused.";if(e==="netnet_turbo_action")return n.operation==="setApprovalForAll"?t.setApprovalForAll:["convertPremiums","convertSleeveFees"].includes(String(n.operation))?t.conversion:"TURBO card actions are unavailable. Read card balances and existing blackjack sessions to inspect their status.";if(e==="netnet_blackjack_seat")return t.seat;if(e==="netnet_blackjack_play"||e==="netnet_blackjack_action")return t.play}var c=(e,n)=>e==="netnet_turbo_action"&&["safeTransferFrom","safeBatchTransferFrom"].includes(String(n.operation))&&Object.keys(n).every(r=>["operation","values"].includes(r));export{s as a,i as b,t as c,o as d,c as e};
@@ -1 +1 @@
1
- import{b as le,o as K}from"./CAWTAR5V.js";import{b as x}from"./66F5ZH34.js";import{c as W,f as de,h as g,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 F}from"./JXOEJPJ4.js";import{randomBytes as ye,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)"),Ce=[{name:"predictionHash",type:"bytes32"},{name:"signer",type:"address"},{name:"collateral",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}],ve=[{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 O(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 A(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 Ae(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);(g(B,$.address)||g(B,G))&&i("Choose a Meridian position token to sell.");let C;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."),C=e}else{let e=BigInt(S)/100n>10n**18n?BigInt(S)/100n:10n**18n;C=c===void 0?e.toString():K(e.toString(),c)}return{side:n,token:B,amount:S,minPrice:C,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(C=>!["conditionResolver","conditionId","predictedOutcome"].includes(C))||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 C=`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}:${S.predictedOutcome}`,e=`${B.conditionResolver.toLowerCase()}:${B.conditionId.toLowerCase()}:${B.predictedOutcome}`;return C<e?-1:C>e?1:0}),y=m.map(S=>`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}`);new Set(y).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 y=A(m.type),l=_(m.payload);if(y==="error"&&i("Meridian rejected or failed the exchange. Start a fresh auction."),y===`${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: ${F(A(l.error))}.`),this.auctionId=A(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: ${F(A(l.error))}.`),l.accepted!==!0&&i("Meridian rejected acceptance of the exchange."));return}if((!y.startsWith(`${d}.`)||l.auctionId!==this.auctionId||!this.auctionId)&&i("Meridian returned a message for a different exchange."),["error","rejected","failed","expired"].some(I=>y===`${d}.${I}`)){let I=["reason","makerReason"].flatMap(D=>l[D]===void 0?[]:[`${D}=${F(A(l[D]))}`]);i(`Meridian exchange ${y.slice(d.length+1)}${I.length?`: ${I.join("; ")}`:""}. Start a fresh auction.`)}if((y===`${d}.pending`||y===`${d}.filled`)&&!this.accepting&&i("Meridian returned settlement before acceptance."),y===`${d}.pending`)return;this.queue.length>=16&&i("Meridian returned too many exchange messages."),this.queue.push({type:y,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 y=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(y),this.notify=void 0,c(I?.payload??{})}catch(I){clearTimeout(y),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 Pe(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:y}=n,l={name:d.side==="buy"?"PredictionMarketEscrow":"SecondaryMarketEscrow",version:"1",chainId:k,verifyingContract:n.continuation.escrowContract};return(!m||!y)&&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:Ce},message:{predictionHash:De(d,c,t),signer:c,collateral:d.stake,nonce:m,deadline:y}}):{domain:l,primaryType:"TradeApproval",types:{TradeApproval:ve},message:{tradeHash:Pe(d,c,t?t.buyer:L,t?t.price:"0"),signer:c,nonce:m,deadline:y}}}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 Fe=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 y(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,v;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,v=`${o.summary} Minimum USDe output: ${b.minAmountOut} base units (18 decimals).`}else p=[n.approval(u,e.continuation.escrowContract,r,k)],v=`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 P=await n.preview(p,s),T=P.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:`${v}${y(a)} ${P.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}.${y(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=A(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:A(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:A(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:A(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:A(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"||!g(h.transactionHash,u)||!g(w.hash,u)||!g(h.to,s.escrowContract)||!g(w.to,s.escrowContract)||w.chainId!==k)&&i("Meridian fill has no matching successful receipt on chain 4663.");let{input:p,wallet:v}=e;if(p.side==="buy"&&s.stage==="primary_accept"){let o=me({abi:Be,data:w.input}).args[0];(!g(te([...o.picks]),te(p.picks))||o.predictorCollateral!==BigInt(p.stake)||o.counterpartyCollateral!==BigInt(s.winningBid.counterpartyCollateral)||!g(o.predictor,v)||!g(o.counterparty,s.winningBid.counterparty)||o.predictorNonce!==BigInt(e.nonce)||o.predictorDeadline!==BigInt(e.deadline)||!g(o.predictorSponsor,L)||o.predictorSponsorData!=="0x"||!g(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];(!g(o.token,p.token)||!g(o.collateral,$.address)||!g(o.seller,v)||!g(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)||!g(o.sellerSignature,a))&&i("Meridian sale receipt does not match the accepted trade.")}let P=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(ge=>/^0x0{24}[0-9a-fA-F]{40}$/.test(ge)))&&i("Meridian receipt has malformed transfer logs.");let U=`0x${o.topics[1].slice(-40)}`,E=`0x${o.topics[2].slice(-40)}`,q=o.address.toLowerCase(),z=BigInt(o.data);P.set(q,(P.get(q)??0n)+(g(E,v)?z:0n)-(g(U,v)?z:0n)),g(U,L)&&g(E,v)&&T.set(q,(T.get(q)??0n)+z)}let b;if(p.side==="buy"&&s.stage==="primary_accept"){let o=BigInt(p.stake)+BigInt(s.winningBid.counterpartyCollateral),U=[...T].filter(([E,q])=>!g(E,$.address)&&q===o&&P.get(E)===o);(U.length!==1||P.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 ${U[0][0]}`}else p.side==="sell"&&s.stage==="secondary_accept"?((P.get(p.token.toLowerCase())!==-BigInt(p.amount)||P.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=Ae(e,a),r;if(a.continuation!==void 0){let h=_(a.continuation),w=t.get(A(h.requestId));w||i("Meridian exchange is lost or expired. Start a fresh auction."),(!g(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=(ye(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:O(r.nonce),predictorDeadline:O(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:O(r.nonce),sellerDeadline:O(r.deadline),chainId:k,escrowContract:V,mode:"blind",sellerSignature:p}),await D(r);let v=await S(r,p);return d(r),v}catch(h){throw d(r),new N(n.plainError(h))}finally{r.busy=!1}}let C={continuation:{type:"object",description:"Internal continuation returned by the previous local signing round."},signature:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$",description:"Internal hexadecimal signature supplied by local signing; never enter manually."}};return{tools:[{name:"meridian_buy",inputSchema:{type:"object",additionalProperties:!1,required:["picks","stake"],properties:{...C,stake:x('USDe stake in base units (18 decimals): "1000000000000000000" = 1 USDe.'),minCounterpartyCollateral:x('Minimum counterparty USDe collateral in base units (18 decimals): "1000000000000000000" = 1 USDe.'),usdgAmountIn:x('USDG swap input in base units if USDe is short (6 decimals): "1000000" = 1 USDG.'),slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage in basis points (50 = 0.5%)."},picks:{type:"array",minItems:1,maxItems:10,items:{type:"object",additionalProperties:!1,required:["conditionResolver","conditionId","predictedOutcome"],properties:{conditionResolver:{...W,description:"Condition resolver contract address on chain 4663."},conditionId:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$",description:"Condition identifier as a 0x-prefixed even-length hex string."},predictedOutcome:{type:"integer",enum:[0,1],description:"Predicted binary outcome, 0 or 1, as defined by the condition."}}},description:"Prediction picks for the auction."}}},execute:(e,a)=>B("buy",e,a)},{name:"meridian_sell",inputSchema:{type:"object",additionalProperties:!1,required:["token","amount"],properties:{...C,token:{...W,description:"Position token address on chain 4663."},amount:x('Position token amount in base units (18 decimals): "1000000000000000000" = 1 position token.'),minPrice:x('Minimum total USDe proceeds in base units (18 decimals): "1000000000000000000" = 1 USDe. Explicit minimum is not reduced by slippage.'),slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage in basis points (50 = 0.5%); applies only to the default floor when minPrice is omitted."}}},execute:(e,a)=>B("sell",e,a)}]}};export{Ce as a,ve as b,Fe as c};
1
+ import{b as le,o as K}from"./GYPMUYB5.js";import{b as x}from"./66F5ZH34.js";import{c as W,f as de,h as g,i as ce,l as ue}from"./NWNYJ26T.js";import{b as k,j as oe,k as G}from"./TI727O2H.js";import{a as N}from"./XSD5NL7J.js";import{a as F}from"./JXOEJPJ4.js";import{randomBytes as ye,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)"),Ce=[{name:"predictionHash",type:"bytes32"},{name:"signer",type:"address"},{name:"collateral",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}],ve=[{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 O(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 A(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 Ae(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);(g(B,$.address)||g(B,G))&&i("Choose a Meridian position token to sell.");let C;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."),C=e}else{let e=BigInt(S)/100n>10n**18n?BigInt(S)/100n:10n**18n;C=c===void 0?e.toString():K(e.toString(),c)}return{side:n,token:B,amount:S,minPrice:C,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(C=>!["conditionResolver","conditionId","predictedOutcome"].includes(C))||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 C=`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}:${S.predictedOutcome}`,e=`${B.conditionResolver.toLowerCase()}:${B.conditionId.toLowerCase()}:${B.predictedOutcome}`;return C<e?-1:C>e?1:0}),y=m.map(S=>`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}`);new Set(y).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 y=A(m.type),l=_(m.payload);if(y==="error"&&i("Meridian rejected or failed the exchange. Start a fresh auction."),y===`${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: ${F(A(l.error))}.`),this.auctionId=A(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: ${F(A(l.error))}.`),l.accepted!==!0&&i("Meridian rejected acceptance of the exchange."));return}if((!y.startsWith(`${d}.`)||l.auctionId!==this.auctionId||!this.auctionId)&&i("Meridian returned a message for a different exchange."),["error","rejected","failed","expired"].some(I=>y===`${d}.${I}`)){let I=["reason","makerReason"].flatMap(D=>l[D]===void 0?[]:[`${D}=${F(A(l[D]))}`]);i(`Meridian exchange ${y.slice(d.length+1)}${I.length?`: ${I.join("; ")}`:""}. Start a fresh auction.`)}if((y===`${d}.pending`||y===`${d}.filled`)&&!this.accepting&&i("Meridian returned settlement before acceptance."),y===`${d}.pending`)return;this.queue.length>=16&&i("Meridian returned too many exchange messages."),this.queue.push({type:y,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 y=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(y),this.notify=void 0,c(I?.payload??{})}catch(I){clearTimeout(y),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 Pe(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:y}=n,l={name:d.side==="buy"?"PredictionMarketEscrow":"SecondaryMarketEscrow",version:"1",chainId:k,verifyingContract:n.continuation.escrowContract};return(!m||!y)&&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:Ce},message:{predictionHash:De(d,c,t),signer:c,collateral:d.stake,nonce:m,deadline:y}}):{domain:l,primaryType:"TradeApproval",types:{TradeApproval:ve},message:{tradeHash:Pe(d,c,t?t.buyer:L,t?t.price:"0"),signer:c,nonce:m,deadline:y}}}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 Fe=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 y(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,v;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,v=`${o.summary} Minimum USDe output: ${b.minAmountOut} base units (18 decimals).`}else p=[n.approval(u,e.continuation.escrowContract,r,k)],v=`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 P=await n.preview(p,s),T=P.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:`${v}${y(a)} ${P.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}.${y(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=A(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:A(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:A(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:A(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:A(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"||!g(h.transactionHash,u)||!g(w.hash,u)||!g(h.to,s.escrowContract)||!g(w.to,s.escrowContract)||w.chainId!==k)&&i("Meridian fill has no matching successful receipt on chain 4663.");let{input:p,wallet:v}=e;if(p.side==="buy"&&s.stage==="primary_accept"){let o=me({abi:Be,data:w.input}).args[0];(!g(te([...o.picks]),te(p.picks))||o.predictorCollateral!==BigInt(p.stake)||o.counterpartyCollateral!==BigInt(s.winningBid.counterpartyCollateral)||!g(o.predictor,v)||!g(o.counterparty,s.winningBid.counterparty)||o.predictorNonce!==BigInt(e.nonce)||o.predictorDeadline!==BigInt(e.deadline)||!g(o.predictorSponsor,L)||o.predictorSponsorData!=="0x"||!g(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];(!g(o.token,p.token)||!g(o.collateral,$.address)||!g(o.seller,v)||!g(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)||!g(o.sellerSignature,a))&&i("Meridian sale receipt does not match the accepted trade.")}let P=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(ge=>/^0x0{24}[0-9a-fA-F]{40}$/.test(ge)))&&i("Meridian receipt has malformed transfer logs.");let U=`0x${o.topics[1].slice(-40)}`,E=`0x${o.topics[2].slice(-40)}`,q=o.address.toLowerCase(),z=BigInt(o.data);P.set(q,(P.get(q)??0n)+(g(E,v)?z:0n)-(g(U,v)?z:0n)),g(U,L)&&g(E,v)&&T.set(q,(T.get(q)??0n)+z)}let b;if(p.side==="buy"&&s.stage==="primary_accept"){let o=BigInt(p.stake)+BigInt(s.winningBid.counterpartyCollateral),U=[...T].filter(([E,q])=>!g(E,$.address)&&q===o&&P.get(E)===o);(U.length!==1||P.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 ${U[0][0]}`}else p.side==="sell"&&s.stage==="secondary_accept"?((P.get(p.token.toLowerCase())!==-BigInt(p.amount)||P.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=Ae(e,a),r;if(a.continuation!==void 0){let h=_(a.continuation),w=t.get(A(h.requestId));w||i("Meridian exchange is lost or expired. Start a fresh auction."),(!g(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=(ye(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:O(r.nonce),predictorDeadline:O(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:O(r.nonce),sellerDeadline:O(r.deadline),chainId:k,escrowContract:V,mode:"blind",sellerSignature:p}),await D(r);let v=await S(r,p);return d(r),v}catch(h){throw d(r),new N(n.plainError(h))}finally{r.busy=!1}}let C={continuation:{type:"object",description:"Internal continuation returned by the previous local signing round."},signature:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$",description:"Internal hexadecimal signature supplied by local signing; never enter manually."}};return{tools:[{name:"meridian_buy",inputSchema:{type:"object",additionalProperties:!1,required:["picks","stake"],properties:{...C,stake:x('USDe stake in base units (18 decimals): "1000000000000000000" = 1 USDe.'),minCounterpartyCollateral:x('Minimum counterparty USDe collateral in base units (18 decimals): "1000000000000000000" = 1 USDe.'),usdgAmountIn:x('USDG swap input in base units if USDe is short (6 decimals): "1000000" = 1 USDG.'),slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage in basis points (50 = 0.5%)."},picks:{type:"array",minItems:1,maxItems:10,items:{type:"object",additionalProperties:!1,required:["conditionResolver","conditionId","predictedOutcome"],properties:{conditionResolver:{...W,description:"Condition resolver contract address on chain 4663."},conditionId:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$",description:"Condition identifier as a 0x-prefixed even-length hex string."},predictedOutcome:{type:"integer",enum:[0,1],description:"Predicted binary outcome, 0 or 1, as defined by the condition."}}},description:"Prediction picks for the auction."}}},execute:(e,a)=>B("buy",e,a)},{name:"meridian_sell",inputSchema:{type:"object",additionalProperties:!1,required:["token","amount"],properties:{...C,token:{...W,description:"Position token address on chain 4663."},amount:x('Position token amount in base units (18 decimals): "1000000000000000000" = 1 position token.'),minPrice:x('Minimum total USDe proceeds in base units (18 decimals): "1000000000000000000" = 1 USDe. Explicit minimum is not reduced by slippage.'),slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage in basis points (50 = 0.5%); applies only to the default floor when minPrice is omitted."}}},execute:(e,a)=>B("sell",e,a)}]}};export{Ce as a,ve as b,Fe as c};
@@ -1 +1 @@
1
- import{b as q,o as U}from"./CAWTAR5V.js";import{a as le}from"./KKPMOAVI.js";import{a as pe,b as fe}from"./Y77EVVT4.js";import{a as ye}from"./XHYFISVV.js";import{a as J,b as ue,c as me}from"./5PI57UC2.js";import{e as F,h as L,m as ce}from"./PV5FDT6O.js";import{b as ae}from"./SPJCSEKP.js";import{a as E}from"./IOYRL6AY.js";import{c as de}from"./SCG5HWMN.js";import{c as O,e as A,g as w,k as ie,l as oe,m as re,n as se}from"./NWNYJ26T.js";import{a as h,i as te}from"./FWD4L3CJ.js";import{a as r}from"./XSD5NL7J.js";import{a as N}from"./JXOEJPJ4.js";import{decodeFunctionResult as Ce,encodeAbiParameters as j,encodeFunctionData as D,erc20Abi as V,isAddress as Ie,parseAbi as xe,parseAbiParameters as W,toHex as z,zeroAddress as Z}from"viem";var x=te[h].clanker,he=xe(["function deployToken(((address tokenAdmin,string name,string symbol,bytes32 salt,string image,string metadata,string context,uint256 originatingChainId) tokenConfig,(address hook,address pairedToken,int24 tickIfToken0IsClanker,int24 tickSpacing,bytes poolData) poolConfig,(address locker,address[] rewardAdmins,address[] rewardRecipients,uint16[] rewardBps,int24[] tickLower,int24[] tickUpper,uint16[] positionBps,bytes lockerData) lockerConfig,(address mevModule,bytes mevModuleData) mevModuleConfig,(address extension,uint256 msgValue,uint16 extensionBps,bytes extensionData)[] extensionConfigs) config) payable returns (address)","function tokenDeploymentInfo(address) view returns ((address,address,address,address[]))"]),T=xe(["function availableFees(address,address) view returns (uint256)","function claim(address,address)","function collectRewards(address)","function mevModuleEnabled(bytes32) view returns (bool)","function mevModuleOperational(bytes32) returns (bool)"]),P={address:x.paired_weth.address,symbol:"WETH",decimals:18,chainId:h},ve="https://www.clanker.world/api/tokens",be={type:"string",pattern:"^\\d+$"},ge={type:"string",pattern:"^0x[0-9a-fA-F]{64}$"};function C(e){return oe(ie(e,F),F)}function ke(e,t){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new r(`Provide an explicit bytes32 ${t}.`);return e}function I(e,t,s=!1){if(e===void 0&&!s)return"";if(typeof e!="string"||s&&!e.trim())throw new r(`Provide ${t} as text.`);return e}function G(e,t=256){return se(e,`Amount exceeds the uint${t} range.`,{bits:t})}function K(e){return re(e,"The contract returned an invalid amount.").toString()}function B(e,t){let s=Object.keys(e).find(u=>!t.includes(u));if(s)throw new r(`Unsupported Clanker input: ${s}.`)}function we(e,t){return t.changes.map(({token:s,amount:u})=>{let g=u.startsWith("-");return`${g?"-":"+"}${e.formatAmount(g?u.slice(1):u,s.decimals)} ${s.symbol} (${s.address}, chain ${s.chainId})`}).join("; ")}function Se(e){return A(e)&&Array.isArray(e.data)&&Number.isSafeInteger(e.total)&&Number(e.total)>=0&&Number.isSafeInteger(e.tokensDeployed)&&Number(e.tokensDeployed)>=0&&(e.cursor===null||e.cursor===void 0||typeof e.cursor=="string")&&e.data.every(t=>A(t)&&typeof t.name=="string"&&typeof t.symbol=="string"&&Number.isSafeInteger(t.chain_id)&&["contract_address","admin","msg_sender","factory_address"].every(s=>typeof t[s]=="string"&&Ie(t[s],{strict:!1})))}function Q(e,t=0){return typeof e=="string"?N(e):e===null||typeof e=="boolean"?e:typeof e=="number"?Number.isFinite(e)?e:null:t>=4?null:Array.isArray(e)?e.slice(0,20).map(s=>Q(s,t+1)):A(e)?Object.fromEntries(Object.entries(e).filter(([s])=>/^[A-Za-z0-9_]{1,40}$/.test(s)).slice(0,40).map(([s,u])=>[s,Q(u,t+1)])):null}function _e(e){return{...Q(e),contract_address:e.contract_address,admin:e.admin,msg_sender:e.msg_sender,chain_id:e.chain_id,factory_address:e.factory_address,name:N(e.name),symbol:N(e.symbol)}}function $e(e){try{if(typeof e!="string"||!/^[A-Za-z0-9_-]{1,256}={0,2}$/.test(e))throw new Error;let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if(!A(t)||typeof t.id!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z?$/.test(t.id)||!Number.isFinite(Date.parse(t.id)))throw new Error;return e}catch{throw new r("Use the cursor returned by the previous clanker_browse page.")}}async function Ne(e,t={}){B(t,["q","limit","cursor","deployer"]);let s=t.limit??10;if(typeof s!="number"||!Number.isInteger(s)||s<1||s>20)throw new r("Choose an indexer limit from 1 to 20.");let u=new URL(ve);u.searchParams.set("chainId",String(h)),u.searchParams.set("limit",String(s)),t.q!==void 0&&u.searchParams.set("q",I(t.q,"search")),t.cursor!==void 0&&u.searchParams.set("cursor",I(t.cursor,"cursor",!0)),t.deployer!==void 0&&u.searchParams.set("msgSender",C(t.deployer));let g=await de(e.http,u.toString(),{headers:{"User-Agent":"Oak-Clanker/1.0"}},Se);return{tokens:g.data.filter(v=>v.chain_id===h&&w(v.factory_address,x.factory.address)),total:g.total,cursor:g.cursor||null,tokensDeployed:g.tokensDeployed}}var Oe=e=>{let t=()=>e.clientFor(h),s=async n=>{try{return await n()}catch(i){throw new r(e.plainError(i))}},u=(n,i,a,c="0")=>e.unsignedTx({to:n,data:i,value:c,chainId:h,description:a}),g=async(n,i)=>K(await t().readContract({address:x.fee_locker.address,abi:T,functionName:"availableFees",args:[n,i]})),v=async n=>{if(w(n,P.address))return P;let[i,a]=await Promise.all([t().readContract({address:n,abi:V,functionName:"symbol"}),t().readContract({address:n,abi:V,functionName:"decimals"})]);if(typeof i!="string"||!i.trim()||!Number.isInteger(a)||a<0||a>255)throw new r("The contract returned invalid token metadata.");return{address:n,chainId:h,symbol:i,decimals:a}},X=async n=>{n.cursor!==void 0&&$e(n.cursor);let i=await Ne(e,n);return{...i,tokens:i.tokens.map(_e)}},Ae=async(n,i)=>{if(B(n,["name","symbol","salt","image","metadata","context","vanity","initialBuy","minAmountOut","slippageBps","rewards","vault","airdrop","feeBps","pool"]),n.vanity!==void 0&&n.vanity!==!1)throw new r("Clanker launches use vanity false and an explicit salt.");let a=I(n.name,"token name",!0),c=I(n.symbol,"token symbol",!0),b=ke(n.salt,"salt"),y=G(n.initialBuy??"0"),l=n.slippageBps??q;if(typeof l!="number")throw new r("Slippage must be an integer from 0 to 9999 bps.");U("0",l);let o=n.minAmountOut===void 0?void 0:G(n.minAmountOut,128);if(o!==void 0&&o<=1n)throw new r("Initial-buy minimum must exceed one base unit.");if(!y&&o!==void 0)throw new r("A minimum requires a positive initial buy.");let m=ue(n,i);L(n.feeBps??100,0,1e3);let p=fe(n);if(y&&!w(p.poolConfig.pairedToken,P.address))throw new r("An initial ETH buy currently requires a WETH-paired pool. Launch without an initial buy and obtain a protected swap quote separately.");let d=n.rewards??[{admin:i,recipient:i,bps:1e4,feePreference:0}];if(!Array.isArray(d)||!d.length||d.length>7)throw new r("Provide one to seven reward allocations.");let k=d.map(f=>{if(!A(f))throw new r("Provide reward allocations as objects.");return B(f,["admin","recipient","bps","feePreference"]),{admin:C(f.admin),recipient:C(f.recipient),bps:L(f.bps,1,1e4),feePreference:L(f.feePreference??0,0,2)}});if(k.reduce((f,S)=>f+S.bps,0)!==1e4)throw new r("Reward allocations must total 10000 bps.");let _={tokenConfig:{tokenAdmin:i,name:a,symbol:c,salt:b,image:I(n.image,"image"),metadata:I(n.metadata,"metadata"),context:n.context===void 0?JSON.stringify({interface:"Oak",platform:"robinhood"}):I(n.context,"context"),originatingChainId:BigInt(h)},poolConfig:p.poolConfig,lockerConfig:{locker:x.locker.address,rewardAdmins:k.map(f=>f.admin),rewardRecipients:k.map(f=>f.recipient),rewardBps:k.map(f=>f.bps),tickLower:p.tickLower,tickUpper:p.tickUpper,positionBps:p.positionBps,lockerData:j(W("(uint8[])"),[[k.map(f=>f.feePreference)]])},mevModuleConfig:{mevModule:x.mev_module.address,mevModuleData:j(W("(uint24,uint24,uint256)"),[[666777,41673,15n]])},extensionConfigs:m},Pe=await t().simulateContract({address:x.factory.address,abi:he,functionName:"deployToken",args:[_],account:i,value:0n,gas:E}),M=C(Pe.result),Y=f=>{let S=[...m,...y?[{extension:x.devbuy.address,msgValue:y,extensionBps:0,extensionData:j(W("(address,address,uint24,int24,address),uint128,address"),[[Z,Z,0,0,Z],f,i])}]:[]];return u(x.factory.address,D({abi:he,functionName:"deployToken",args:[{..._,extensionConfigs:S}]}),`Launch ${a} (${c}); initial buy ${y} native ETH base units.`,y.toString())};if(y&&o===void 0){let S=(await e.preview([Y(0n)],i)).changes.filter($=>$.token.chainId===h&&w($.token.address,M)&&$.token.decimals===18).reduce(($,ne)=>$+(/^-?\d+$/.test(ne.amount)?BigInt(ne.amount):(()=>{throw new r("Invalid initial-buy simulation amount.")})()),0n);if(S<=0n)throw new r("Initial-buy simulation returned no token output.");if(o=G(U(S.toString(),l),128),o<=1n)throw new r("Initial-buy output is too small for a protected minimum.")}let ee=[Y(o??0n)],H=await e.preview(ee,i);return{txs:ee,preview:H,predictedToken:M,token:{address:M,chainId:h,symbol:c,decimals:18},...o!==void 0?{minAmountOut:o.toString()}:{},summary:`Launch ${c} at ${M} (CREATE2 address predicted from simulation); vanity false; salt ${b}. Supply 100000000000000000000000000000 base units (18 decimals). ${p.feeSummary}; protocol adds 20% of LP fees. Pool and LP allocations: ${JSON.stringify(p)}. Reward allocations: ${JSON.stringify(k)}. Extensions: ${JSON.stringify({vault:n.vault,airdrop:n.airdrop})}. Sniper fees 666777 to 41673 over 15 seconds. ${H.summary} ${we(e,H)}`}},Te=async(n,i)=>{if(B(n,["token","poolId","collect"]),n.collect!==void 0&&typeof n.collect!="boolean")throw new r("collect must be boolean.");if(n.collect===!1&&n.poolId!==void 0)throw new r("poolId requires collection.");if(n.collect===!0&&n.token===void 0)throw new r("Collection requires a Clanker token.");if(n.poolId!==void 0&&n.token===void 0)throw new r("A pool ID requires its Clanker token.");let a=[P],c=[];if(n.token!==void 0){let o=C(n.token);if(w(o,P.address))throw new r("Provide the launched Clanker token, not WETH.");if(n.collect!==!1){let m=await ce(e,o),{poolId:p,hook:d,locker:k}=m;if(n.poolId!==void 0&&!w(ke(n.poolId,"pool ID for fee collection"),p))throw new r("The supplied pool ID does not match the onchain Clanker pool.");w(m.pairedToken,P.address)||a.splice(0,1,await v(m.pairedToken));let _=await t().readContract({address:d,abi:T,functionName:"mevModuleEnabled",args:[p]});if(typeof _!="boolean")throw new r("The hook returned an invalid MEV guard state.");_&&c.push(u(d,D({abi:T,functionName:"mevModuleOperational",args:[p]}),"Update the Clanker pool MEV guard before collection.")),c.push(u(k,D({abi:T,functionName:"collectRewards",args:[o]}),"Collect pending LP fees into the fee locker."))}a.push(await v(o))}let b;if(c.length){if(await t().getChainId()!==h)throw new r("Fee simulation endpoint is on the wrong chain.");let o=[...c.map(d=>({from:i,gas:z(E),to:d.to,data:d.data,value:z(BigInt(d.value))})),...a.map(d=>({from:i,gas:z(E),to:x.fee_locker.address,data:D({abi:T,functionName:"availableFees",args:[i,d.address]}),value:"0x0"}))],m=await t().request({method:"eth_simulateV1",params:[{blockStateCalls:[{calls:o}],validation:!1,traceTransfers:!1},"latest"]},{retryCount:0});if(!Array.isArray(m)||m.length!==1||!A(m[0])||!Array.isArray(m[0].calls)||m[0].calls.length!==o.length)throw new r("The endpoint returned an unexpected fee simulation response.");let p=m[0].calls;if(!p.every(d=>A(d)&&d.status==="0x1"&&!d.error))throw new r("Clanker fee collection simulation failed.");b=p.slice(c.length).map(d=>{if(!A(d)||typeof d.returnData!="string"||!/^0x[0-9a-fA-F]{64}$/.test(d.returnData))throw new r("The endpoint returned an invalid fee balance.");return K(Ce({abi:T,functionName:"availableFees",data:d.returnData}))})}else b=await Promise.all(a.map(o=>g(i,o.address)));let y=a.flatMap((o,m)=>BigInt(b[m])>0n?[{token:o,amount:b[m]}]:[]);if(!y.length)throw new r("No claimable fees for this wallet; pending LP fees may require the MEV window to end.");for(let{token:o}of y)c.push(u(x.fee_locker.address,D({abi:T,functionName:"claim",args:[i,o.address]}),`Claim ${o.symbol} fees to ${i}.`));let l=await e.preview(c,i);return{txs:c,preview:l,fees:y,summary:`Claim fees to ${i}. WETH fees aggregate across all Clanker launches for this recipient. ${l.summary} ${we(e,l)}`}},R=(n,i,a,c)=>({name:`clanker_${n}`,inputSchema:{type:"object",properties:i,required:a,additionalProperties:!1},execute:(b,y)=>s(async()=>c(b,C(y)))});return{tools:[R("launch",{name:{type:"string",description:"Token name, shown publicly."},symbol:{type:"string",description:"Token ticker symbol, shown publicly."},salt:{...ge,description:"Deployment salt as 0x followed by 64 hex digits; it fixes the predicted token address."},image:{type:"string",description:"Image URL for the token. Public."},metadata:{type:"string",description:"Token metadata as a JSON string (description, social links). Public."},context:{type:"string",description:"Launch context as a JSON string. Defaults to Oak on Robinhood."},vanity:{const:!1,description:"Vanity address mining is not supported; leave false or omit."},initialBuy:{...be,description:"Native ETH base units, 18 decimals."},minAmountOut:{...be,description:"Minimum new token base units, 18 decimals; derived from simulation when omitted."},slippageBps:{type:"integer",minimum:0,maximum:9999,default:q,description:"Slippage in basis points (50 = 0.5%) applied to the initial buy when minAmountOut is omitted."},feeBps:{type:"integer",minimum:0,maximum:1e3,default:100,description:"Static LP fee in basis points (100 = 1%). Not allowed together with pool.dynamicFee."},pool:{...pe,description:"Optional pool setup: paired token, starting tick, tick spacing, liquidity positions and dynamic fee. Defaults to a WETH pool."},rewards:{type:"array",minItems:1,maxItems:7,description:"How LP fees are split, 1 to 7 rows with bps totaling 10000. Default: all to the launching wallet.",items:{type:"object",properties:{admin:{...O,description:"Address that can later change this row."},recipient:{...O,description:"Address that receives this row's share of LP fees."},bps:{type:"integer",minimum:1,maximum:1e4,description:"This row's share of LP fees in basis points (5000 = 50%)."},feePreference:{type:"integer",minimum:0,maximum:2,description:"Which token this row is paid in: 0 = both tokens (default), 1 = paired token, 2 = launched token."}},required:["admin","recipient","bps"],additionalProperties:!1}},vault:{...J.vault,description:"Optional vault extension: lock part of the supply, then vest it to an admin."},airdrop:{...J.airdrop,description:"Optional airdrop extension: reserve part of the supply for a Merkle-tree airdrop."}},["name","symbol","salt"],async(n,i)=>{let a=await Ae(n,i);return{...a,summary:`${a.summary} After the launch is mined, use clanker_status to inspect ${a.predictedToken} and clanker_claim to collect creator fees.`}}),R("claim",{token:{...O,description:"Launched token; derives its onchain pool and collects pending LP fees before claiming."},poolId:{...ge,description:"Optional assertion against the derived pool ID."},collect:{type:"boolean",default:!0,description:"Set false to claim only already-collected fees."}},[],Te),R("browse",{q:{type:"string",description:"Optional search text matched against token name or symbol."},limit:{type:"integer",minimum:1,maximum:20,description:"Maximum tokens to return, 1 to 20 (default 10)."},cursor:{type:"string",description:"Opaque pagination cursor returned by a previous clanker_browse call."},deployer:{...O,description:"Optional address of the deploying wallet to filter tokens by."}},[],X)],positions:n=>s(async()=>{C(n);let i=new Map,a=new Set,c;do{let l=await X({deployer:n,limit:20,...c?{cursor:c}:{}});for(let o of l.tokens)w(o.msg_sender,n)&&i.set(o.contract_address.toLowerCase(),o);if(l.cursor&&a.has(l.cursor))throw new r("The Clanker indexer repeated a pagination cursor.");l.cursor&&a.add(l.cursor),c=l.cursor??void 0}while(c);let b=[],y=[P];for(let[l,o]of i){let m=await v(o.contract_address),p={...m,symbol:N(m.symbol)},d=K(await t().readContract({address:p.address,abi:V,functionName:"balanceOf",args:[n]}));b.push({module:"clanker",id:`launch:${l}`,chainId:h,assets:[{token:p,amount:d}],description:`Indexed launch ${o.name}; wallet token balance, not locked LP principal.`}),y.some(k=>w(k.address,p.address))||y.push(p)}for(let l of y){let o=await g(n,l.address);BigInt(o)>0n&&b.push({module:"clanker",id:`fees:${l.address.toLowerCase()}`,chainId:h,assets:[{token:l,amount:o}],description:"Collected fees across launches for this recipient. Pending LP fees excluded; token-side discovery covers indexed launches by this wallet."})}return b})}},ze=e=>ae("clanker",[Oe(e),le(e),me(e),ye(e)]);export{Ne as a,Oe as b,ze as c};
1
+ import{b as q,o as U}from"./GYPMUYB5.js";import{a as le}from"./ELHRXA5U.js";import{a as pe,b as fe}from"./DGDMRATN.js";import{a as ye}from"./4Z3IGMU6.js";import{a as J,b as ue,c as me}from"./C76D54YG.js";import{e as F,h as L,m as ce}from"./TXGZ6NWN.js";import{b as ae}from"./SPJCSEKP.js";import{a as E}from"./IOYRL6AY.js";import{c as de}from"./SCG5HWMN.js";import{c as O,e as A,g as w,k as ie,l as oe,m as re,n as se}from"./NWNYJ26T.js";import{b as h,j as te}from"./TI727O2H.js";import{a as r}from"./XSD5NL7J.js";import{a as N}from"./JXOEJPJ4.js";import{decodeFunctionResult as Ce,encodeAbiParameters as j,encodeFunctionData as D,erc20Abi as V,isAddress as Ie,parseAbi as xe,parseAbiParameters as W,toHex as z,zeroAddress as Z}from"viem";var x=te[h].clanker,he=xe(["function deployToken(((address tokenAdmin,string name,string symbol,bytes32 salt,string image,string metadata,string context,uint256 originatingChainId) tokenConfig,(address hook,address pairedToken,int24 tickIfToken0IsClanker,int24 tickSpacing,bytes poolData) poolConfig,(address locker,address[] rewardAdmins,address[] rewardRecipients,uint16[] rewardBps,int24[] tickLower,int24[] tickUpper,uint16[] positionBps,bytes lockerData) lockerConfig,(address mevModule,bytes mevModuleData) mevModuleConfig,(address extension,uint256 msgValue,uint16 extensionBps,bytes extensionData)[] extensionConfigs) config) payable returns (address)","function tokenDeploymentInfo(address) view returns ((address,address,address,address[]))"]),T=xe(["function availableFees(address,address) view returns (uint256)","function claim(address,address)","function collectRewards(address)","function mevModuleEnabled(bytes32) view returns (bool)","function mevModuleOperational(bytes32) returns (bool)"]),P={address:x.paired_weth.address,symbol:"WETH",decimals:18,chainId:h},ve="https://www.clanker.world/api/tokens",be={type:"string",pattern:"^\\d+$"},ge={type:"string",pattern:"^0x[0-9a-fA-F]{64}$"};function C(e){return oe(ie(e,F),F)}function ke(e,t){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new r(`Provide an explicit bytes32 ${t}.`);return e}function I(e,t,s=!1){if(e===void 0&&!s)return"";if(typeof e!="string"||s&&!e.trim())throw new r(`Provide ${t} as text.`);return e}function G(e,t=256){return se(e,`Amount exceeds the uint${t} range.`,{bits:t})}function K(e){return re(e,"The contract returned an invalid amount.").toString()}function B(e,t){let s=Object.keys(e).find(u=>!t.includes(u));if(s)throw new r(`Unsupported Clanker input: ${s}.`)}function we(e,t){return t.changes.map(({token:s,amount:u})=>{let g=u.startsWith("-");return`${g?"-":"+"}${e.formatAmount(g?u.slice(1):u,s.decimals)} ${s.symbol} (${s.address}, chain ${s.chainId})`}).join("; ")}function Se(e){return A(e)&&Array.isArray(e.data)&&Number.isSafeInteger(e.total)&&Number(e.total)>=0&&Number.isSafeInteger(e.tokensDeployed)&&Number(e.tokensDeployed)>=0&&(e.cursor===null||e.cursor===void 0||typeof e.cursor=="string")&&e.data.every(t=>A(t)&&typeof t.name=="string"&&typeof t.symbol=="string"&&Number.isSafeInteger(t.chain_id)&&["contract_address","admin","msg_sender","factory_address"].every(s=>typeof t[s]=="string"&&Ie(t[s],{strict:!1})))}function Q(e,t=0){return typeof e=="string"?N(e):e===null||typeof e=="boolean"?e:typeof e=="number"?Number.isFinite(e)?e:null:t>=4?null:Array.isArray(e)?e.slice(0,20).map(s=>Q(s,t+1)):A(e)?Object.fromEntries(Object.entries(e).filter(([s])=>/^[A-Za-z0-9_]{1,40}$/.test(s)).slice(0,40).map(([s,u])=>[s,Q(u,t+1)])):null}function _e(e){return{...Q(e),contract_address:e.contract_address,admin:e.admin,msg_sender:e.msg_sender,chain_id:e.chain_id,factory_address:e.factory_address,name:N(e.name),symbol:N(e.symbol)}}function $e(e){try{if(typeof e!="string"||!/^[A-Za-z0-9_-]{1,256}={0,2}$/.test(e))throw new Error;let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if(!A(t)||typeof t.id!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z?$/.test(t.id)||!Number.isFinite(Date.parse(t.id)))throw new Error;return e}catch{throw new r("Use the cursor returned by the previous clanker_browse page.")}}async function Ne(e,t={}){B(t,["q","limit","cursor","deployer"]);let s=t.limit??10;if(typeof s!="number"||!Number.isInteger(s)||s<1||s>20)throw new r("Choose an indexer limit from 1 to 20.");let u=new URL(ve);u.searchParams.set("chainId",String(h)),u.searchParams.set("limit",String(s)),t.q!==void 0&&u.searchParams.set("q",I(t.q,"search")),t.cursor!==void 0&&u.searchParams.set("cursor",I(t.cursor,"cursor",!0)),t.deployer!==void 0&&u.searchParams.set("msgSender",C(t.deployer));let g=await de(e.http,u.toString(),{headers:{"User-Agent":"Oak-Clanker/1.0"}},Se);return{tokens:g.data.filter(v=>v.chain_id===h&&w(v.factory_address,x.factory.address)),total:g.total,cursor:g.cursor||null,tokensDeployed:g.tokensDeployed}}var Oe=e=>{let t=()=>e.clientFor(h),s=async n=>{try{return await n()}catch(i){throw new r(e.plainError(i))}},u=(n,i,a,c="0")=>e.unsignedTx({to:n,data:i,value:c,chainId:h,description:a}),g=async(n,i)=>K(await t().readContract({address:x.fee_locker.address,abi:T,functionName:"availableFees",args:[n,i]})),v=async n=>{if(w(n,P.address))return P;let[i,a]=await Promise.all([t().readContract({address:n,abi:V,functionName:"symbol"}),t().readContract({address:n,abi:V,functionName:"decimals"})]);if(typeof i!="string"||!i.trim()||!Number.isInteger(a)||a<0||a>255)throw new r("The contract returned invalid token metadata.");return{address:n,chainId:h,symbol:i,decimals:a}},X=async n=>{n.cursor!==void 0&&$e(n.cursor);let i=await Ne(e,n);return{...i,tokens:i.tokens.map(_e)}},Ae=async(n,i)=>{if(B(n,["name","symbol","salt","image","metadata","context","vanity","initialBuy","minAmountOut","slippageBps","rewards","vault","airdrop","feeBps","pool"]),n.vanity!==void 0&&n.vanity!==!1)throw new r("Clanker launches use vanity false and an explicit salt.");let a=I(n.name,"token name",!0),c=I(n.symbol,"token symbol",!0),b=ke(n.salt,"salt"),y=G(n.initialBuy??"0"),l=n.slippageBps??q;if(typeof l!="number")throw new r("Slippage must be an integer from 0 to 9999 bps.");U("0",l);let o=n.minAmountOut===void 0?void 0:G(n.minAmountOut,128);if(o!==void 0&&o<=1n)throw new r("Initial-buy minimum must exceed one base unit.");if(!y&&o!==void 0)throw new r("A minimum requires a positive initial buy.");let m=ue(n,i);L(n.feeBps??100,0,1e3);let p=fe(n);if(y&&!w(p.poolConfig.pairedToken,P.address))throw new r("An initial ETH buy currently requires a WETH-paired pool. Launch without an initial buy and obtain a protected swap quote separately.");let d=n.rewards??[{admin:i,recipient:i,bps:1e4,feePreference:0}];if(!Array.isArray(d)||!d.length||d.length>7)throw new r("Provide one to seven reward allocations.");let k=d.map(f=>{if(!A(f))throw new r("Provide reward allocations as objects.");return B(f,["admin","recipient","bps","feePreference"]),{admin:C(f.admin),recipient:C(f.recipient),bps:L(f.bps,1,1e4),feePreference:L(f.feePreference??0,0,2)}});if(k.reduce((f,S)=>f+S.bps,0)!==1e4)throw new r("Reward allocations must total 10000 bps.");let _={tokenConfig:{tokenAdmin:i,name:a,symbol:c,salt:b,image:I(n.image,"image"),metadata:I(n.metadata,"metadata"),context:n.context===void 0?JSON.stringify({interface:"Oak",platform:"robinhood"}):I(n.context,"context"),originatingChainId:BigInt(h)},poolConfig:p.poolConfig,lockerConfig:{locker:x.locker.address,rewardAdmins:k.map(f=>f.admin),rewardRecipients:k.map(f=>f.recipient),rewardBps:k.map(f=>f.bps),tickLower:p.tickLower,tickUpper:p.tickUpper,positionBps:p.positionBps,lockerData:j(W("(uint8[])"),[[k.map(f=>f.feePreference)]])},mevModuleConfig:{mevModule:x.mev_module.address,mevModuleData:j(W("(uint24,uint24,uint256)"),[[666777,41673,15n]])},extensionConfigs:m},Pe=await t().simulateContract({address:x.factory.address,abi:he,functionName:"deployToken",args:[_],account:i,value:0n,gas:E}),M=C(Pe.result),Y=f=>{let S=[...m,...y?[{extension:x.devbuy.address,msgValue:y,extensionBps:0,extensionData:j(W("(address,address,uint24,int24,address),uint128,address"),[[Z,Z,0,0,Z],f,i])}]:[]];return u(x.factory.address,D({abi:he,functionName:"deployToken",args:[{..._,extensionConfigs:S}]}),`Launch ${a} (${c}); initial buy ${y} native ETH base units.`,y.toString())};if(y&&o===void 0){let S=(await e.preview([Y(0n)],i)).changes.filter($=>$.token.chainId===h&&w($.token.address,M)&&$.token.decimals===18).reduce(($,ne)=>$+(/^-?\d+$/.test(ne.amount)?BigInt(ne.amount):(()=>{throw new r("Invalid initial-buy simulation amount.")})()),0n);if(S<=0n)throw new r("Initial-buy simulation returned no token output.");if(o=G(U(S.toString(),l),128),o<=1n)throw new r("Initial-buy output is too small for a protected minimum.")}let ee=[Y(o??0n)],H=await e.preview(ee,i);return{txs:ee,preview:H,predictedToken:M,token:{address:M,chainId:h,symbol:c,decimals:18},...o!==void 0?{minAmountOut:o.toString()}:{},summary:`Launch ${c} at ${M} (CREATE2 address predicted from simulation); vanity false; salt ${b}. Supply 100000000000000000000000000000 base units (18 decimals). ${p.feeSummary}; protocol adds 20% of LP fees. Pool and LP allocations: ${JSON.stringify(p)}. Reward allocations: ${JSON.stringify(k)}. Extensions: ${JSON.stringify({vault:n.vault,airdrop:n.airdrop})}. Sniper fees 666777 to 41673 over 15 seconds. ${H.summary} ${we(e,H)}`}},Te=async(n,i)=>{if(B(n,["token","poolId","collect"]),n.collect!==void 0&&typeof n.collect!="boolean")throw new r("collect must be boolean.");if(n.collect===!1&&n.poolId!==void 0)throw new r("poolId requires collection.");if(n.collect===!0&&n.token===void 0)throw new r("Collection requires a Clanker token.");if(n.poolId!==void 0&&n.token===void 0)throw new r("A pool ID requires its Clanker token.");let a=[P],c=[];if(n.token!==void 0){let o=C(n.token);if(w(o,P.address))throw new r("Provide the launched Clanker token, not WETH.");if(n.collect!==!1){let m=await ce(e,o),{poolId:p,hook:d,locker:k}=m;if(n.poolId!==void 0&&!w(ke(n.poolId,"pool ID for fee collection"),p))throw new r("The supplied pool ID does not match the onchain Clanker pool.");w(m.pairedToken,P.address)||a.splice(0,1,await v(m.pairedToken));let _=await t().readContract({address:d,abi:T,functionName:"mevModuleEnabled",args:[p]});if(typeof _!="boolean")throw new r("The hook returned an invalid MEV guard state.");_&&c.push(u(d,D({abi:T,functionName:"mevModuleOperational",args:[p]}),"Update the Clanker pool MEV guard before collection.")),c.push(u(k,D({abi:T,functionName:"collectRewards",args:[o]}),"Collect pending LP fees into the fee locker."))}a.push(await v(o))}let b;if(c.length){if(await t().getChainId()!==h)throw new r("Fee simulation endpoint is on the wrong chain.");let o=[...c.map(d=>({from:i,gas:z(E),to:d.to,data:d.data,value:z(BigInt(d.value))})),...a.map(d=>({from:i,gas:z(E),to:x.fee_locker.address,data:D({abi:T,functionName:"availableFees",args:[i,d.address]}),value:"0x0"}))],m=await t().request({method:"eth_simulateV1",params:[{blockStateCalls:[{calls:o}],validation:!1,traceTransfers:!1},"latest"]},{retryCount:0});if(!Array.isArray(m)||m.length!==1||!A(m[0])||!Array.isArray(m[0].calls)||m[0].calls.length!==o.length)throw new r("The endpoint returned an unexpected fee simulation response.");let p=m[0].calls;if(!p.every(d=>A(d)&&d.status==="0x1"&&!d.error))throw new r("Clanker fee collection simulation failed.");b=p.slice(c.length).map(d=>{if(!A(d)||typeof d.returnData!="string"||!/^0x[0-9a-fA-F]{64}$/.test(d.returnData))throw new r("The endpoint returned an invalid fee balance.");return K(Ce({abi:T,functionName:"availableFees",data:d.returnData}))})}else b=await Promise.all(a.map(o=>g(i,o.address)));let y=a.flatMap((o,m)=>BigInt(b[m])>0n?[{token:o,amount:b[m]}]:[]);if(!y.length)throw new r("No claimable fees for this wallet; pending LP fees may require the MEV window to end.");for(let{token:o}of y)c.push(u(x.fee_locker.address,D({abi:T,functionName:"claim",args:[i,o.address]}),`Claim ${o.symbol} fees to ${i}.`));let l=await e.preview(c,i);return{txs:c,preview:l,fees:y,summary:`Claim fees to ${i}. WETH fees aggregate across all Clanker launches for this recipient. ${l.summary} ${we(e,l)}`}},R=(n,i,a,c)=>({name:`clanker_${n}`,inputSchema:{type:"object",properties:i,required:a,additionalProperties:!1},execute:(b,y)=>s(async()=>c(b,C(y)))});return{tools:[R("launch",{name:{type:"string",description:"Token name, shown publicly."},symbol:{type:"string",description:"Token ticker symbol, shown publicly."},salt:{...ge,description:"Deployment salt as 0x followed by 64 hex digits; it fixes the predicted token address."},image:{type:"string",description:"Image URL for the token. Public."},metadata:{type:"string",description:"Token metadata as a JSON string (description, social links). Public."},context:{type:"string",description:"Launch context as a JSON string. Defaults to Oak on Robinhood."},vanity:{const:!1,description:"Vanity address mining is not supported; leave false or omit."},initialBuy:{...be,description:"Native ETH base units, 18 decimals."},minAmountOut:{...be,description:"Minimum new token base units, 18 decimals; derived from simulation when omitted."},slippageBps:{type:"integer",minimum:0,maximum:9999,default:q,description:"Slippage in basis points (50 = 0.5%) applied to the initial buy when minAmountOut is omitted."},feeBps:{type:"integer",minimum:0,maximum:1e3,default:100,description:"Static LP fee in basis points (100 = 1%). Not allowed together with pool.dynamicFee."},pool:{...pe,description:"Optional pool setup: paired token, starting tick, tick spacing, liquidity positions and dynamic fee. Defaults to a WETH pool."},rewards:{type:"array",minItems:1,maxItems:7,description:"How LP fees are split, 1 to 7 rows with bps totaling 10000. Default: all to the launching wallet.",items:{type:"object",properties:{admin:{...O,description:"Address that can later change this row."},recipient:{...O,description:"Address that receives this row's share of LP fees."},bps:{type:"integer",minimum:1,maximum:1e4,description:"This row's share of LP fees in basis points (5000 = 50%)."},feePreference:{type:"integer",minimum:0,maximum:2,description:"Which token this row is paid in: 0 = both tokens (default), 1 = paired token, 2 = launched token."}},required:["admin","recipient","bps"],additionalProperties:!1}},vault:{...J.vault,description:"Optional vault extension: lock part of the supply, then vest it to an admin."},airdrop:{...J.airdrop,description:"Optional airdrop extension: reserve part of the supply for a Merkle-tree airdrop."}},["name","symbol","salt"],async(n,i)=>{let a=await Ae(n,i);return{...a,summary:`${a.summary} After the launch is mined, use clanker_status to inspect ${a.predictedToken} and clanker_claim to collect creator fees.`}}),R("claim",{token:{...O,description:"Launched token; derives its onchain pool and collects pending LP fees before claiming."},poolId:{...ge,description:"Optional assertion against the derived pool ID."},collect:{type:"boolean",default:!0,description:"Set false to claim only already-collected fees."}},[],Te),R("browse",{q:{type:"string",description:"Optional search text matched against token name or symbol."},limit:{type:"integer",minimum:1,maximum:20,description:"Maximum tokens to return, 1 to 20 (default 10)."},cursor:{type:"string",description:"Opaque pagination cursor returned by a previous clanker_browse call."},deployer:{...O,description:"Optional address of the deploying wallet to filter tokens by."}},[],X)],positions:n=>s(async()=>{C(n);let i=new Map,a=new Set,c;do{let l=await X({deployer:n,limit:20,...c?{cursor:c}:{}});for(let o of l.tokens)w(o.msg_sender,n)&&i.set(o.contract_address.toLowerCase(),o);if(l.cursor&&a.has(l.cursor))throw new r("The Clanker indexer repeated a pagination cursor.");l.cursor&&a.add(l.cursor),c=l.cursor??void 0}while(c);let b=[],y=[P];for(let[l,o]of i){let m=await v(o.contract_address),p={...m,symbol:N(m.symbol)},d=K(await t().readContract({address:p.address,abi:V,functionName:"balanceOf",args:[n]}));b.push({module:"clanker",id:`launch:${l}`,chainId:h,assets:[{token:p,amount:d}],description:`Indexed launch ${o.name}; wallet token balance, not locked LP principal.`}),y.some(k=>w(k.address,p.address))||y.push(p)}for(let l of y){let o=await g(n,l.address);BigInt(o)>0n&&b.push({module:"clanker",id:`fees:${l.address.toLowerCase()}`,chainId:h,assets:[{token:l,amount:o}],description:"Collected fees across launches for this recipient. Pending LP fees excluded; token-side discovery covers indexed launches by this wallet."})}return b})}},ze=e=>ae("clanker",[Oe(e),le(e),me(e),ye(e)]);export{Ne as a,Oe as b,ze as c};