@oakagentkit/core 0.2.7 → 0.3.0
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.
- package/build/dist/api/addresses.d.ts +9 -0
- package/build/dist/api/addresses.js +1 -1
- package/build/dist/api/chain.d.ts +4 -0
- package/build/dist/api/chain.js +1 -1
- package/build/dist/api/history.js +1 -1
- package/build/dist/api/identity-link.js +1 -1
- package/build/dist/api/metadata.js +1 -1
- package/build/dist/api/modules/beefy/boosts.js +1 -1
- package/build/dist/api/modules/beefy/clm.js +1 -1
- package/build/dist/api/modules/beefy/guard.js +1 -1
- package/build/dist/api/modules/beefy/index.js +1 -1
- package/build/dist/api/modules/beefy/liquidity.js +1 -1
- package/build/dist/api/modules/beefy/management.js +1 -1
- package/build/dist/api/modules/beefy/vaults.js +1 -1
- package/build/dist/api/modules/borro/abi.d.ts +54 -0
- package/build/dist/api/modules/borro/abi.js +1 -1
- package/build/dist/api/modules/borro/actions.d.ts +14 -1
- package/build/dist/api/modules/borro/actions.js +1 -1
- package/build/dist/api/modules/borro/checks.js +1 -1
- package/build/dist/api/modules/borro/copy.d.ts +10 -2
- package/build/dist/api/modules/borro/copy.js +1 -1
- package/build/dist/api/modules/borro/index.js +1 -1
- package/build/dist/api/modules/borro/liquidity.js +1 -1
- package/build/dist/api/modules/borro/pins.d.ts +30 -14
- package/build/dist/api/modules/borro/pins.js +1 -1
- package/build/dist/api/modules/borro/positions.js +1 -1
- package/build/dist/api/modules/borro/reader.js +1 -1
- package/build/dist/api/modules/borro/types.d.ts +1 -0
- package/build/dist/api/modules/chop/guard.js +1 -1
- package/build/dist/api/modules/chop/index.js +1 -1
- package/build/dist/api/modules/clanker/extensions.js +1 -1
- package/build/dist/api/modules/clanker/index.js +1 -1
- package/build/dist/api/modules/clanker/manage.js +1 -1
- package/build/dist/api/modules/clanker/pool-config.js +1 -1
- package/build/dist/api/modules/clanker/protocol.js +1 -1
- package/build/dist/api/modules/clanker/state.js +1 -1
- package/build/dist/api/modules/earn/copy.d.ts +6 -6
- package/build/dist/api/modules/earn/copy.js +1 -1
- package/build/dist/api/modules/earn/cost.d.ts +1 -1
- package/build/dist/api/modules/earn/cost.js +1 -1
- package/build/dist/api/modules/earn/index.js +1 -1
- package/build/dist/api/modules/earn/lp.js +1 -1
- package/build/dist/api/modules/earn/options.js +1 -1
- package/build/dist/api/modules/erc8004/common.js +1 -1
- package/build/dist/api/modules/erc8004/domain.js +1 -1
- package/build/dist/api/modules/erc8004/index.js +1 -1
- package/build/dist/api/modules/erc8004/management.js +1 -1
- package/build/dist/api/modules/erc8004/reputation.js +1 -1
- package/build/dist/api/modules/erc8004/services.js +1 -1
- package/build/dist/api/modules/erc8004/thesis.d.ts +61 -0
- package/build/dist/api/modules/erc8004/thesis.js +1 -0
- package/build/dist/api/modules/erc8004/validation.js +1 -1
- package/build/dist/api/modules/gloam/index.js +1 -1
- package/build/dist/api/modules/grove/index.js +1 -1
- package/build/dist/api/modules/heyresearch/builder-feed.js +1 -1
- package/build/dist/api/modules/heyresearch/index.js +1 -1
- package/build/dist/api/modules/heyresearch/public-reads.js +1 -1
- package/build/dist/api/modules/heyresearch/token-facts.js +1 -1
- package/build/dist/api/modules/hoodag/chain-reads.js +1 -1
- package/build/dist/api/modules/hoodag/index.d.ts +12 -1
- package/build/dist/api/modules/hoodag/index.js +1 -1
- package/build/dist/api/modules/hoodag/management.js +1 -1
- package/build/dist/api/modules/hoodag/public-reads.js +1 -1
- package/build/dist/api/modules/hoodag/reconstruct.d.ts +14 -0
- package/build/dist/api/modules/hoodag/reconstruct.js +1 -1
- package/build/dist/api/modules/hoodlock/airdrop.js +1 -1
- package/build/dist/api/modules/hoodlock/buyback.js +1 -1
- package/build/dist/api/modules/hoodlock/commerce.js +1 -1
- package/build/dist/api/modules/hoodlock/fee.js +1 -1
- package/build/dist/api/modules/hoodlock/guard.js +1 -1
- package/build/dist/api/modules/hoodlock/index.js +1 -1
- package/build/dist/api/modules/hoodlock/lifecycle.js +1 -1
- package/build/dist/api/modules/hoodlock/locks-burn.js +1 -1
- package/build/dist/api/modules/hoodlock/public.js +1 -1
- package/build/dist/api/modules/hookr/actions.js +1 -1
- package/build/dist/api/modules/hookr/addons.js +1 -1
- package/build/dist/api/modules/hookr/agent-gate.js +1 -1
- package/build/dist/api/modules/hookr/contracts.js +1 -1
- package/build/dist/api/modules/hookr/create-cancel.js +1 -1
- package/build/dist/api/modules/hookr/discovery.js +1 -1
- package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
- package/build/dist/api/modules/hookr/index.js +1 -1
- package/build/dist/api/modules/hookr/launch-options.js +1 -1
- package/build/dist/api/modules/hookr/launch-receipt.js +1 -1
- package/build/dist/api/modules/hookr/launch.js +1 -1
- package/build/dist/api/modules/hookr/liquidity.js +1 -1
- package/build/dist/api/modules/hookr/lp-positions.js +1 -1
- package/build/dist/api/modules/hookr/lp-reads.js +1 -1
- package/build/dist/api/modules/hookr/lp-receipt.js +1 -1
- package/build/dist/api/modules/hookr/lp-state.js +1 -1
- package/build/dist/api/modules/hookr/public-reads.js +1 -1
- package/build/dist/api/modules/hookr/read-utils.js +1 -1
- package/build/dist/api/modules/hookr/relay.js +1 -1
- package/build/dist/api/modules/hookr/revenue.js +1 -1
- package/build/dist/api/modules/kyberswap/index.d.ts +2 -1
- package/build/dist/api/modules/kyberswap/index.js +1 -1
- package/build/dist/api/modules/kyberswap/source-pools.js +1 -1
- package/build/dist/api/modules/layerbank/abi.js +1 -1
- package/build/dist/api/modules/layerbank/actions.js +1 -1
- package/build/dist/api/modules/layerbank/checks.js +1 -1
- package/build/dist/api/modules/layerbank/index.js +1 -1
- package/build/dist/api/modules/layerbank/merkl.js +1 -1
- package/build/dist/api/modules/layerbank/reader.js +1 -1
- package/build/dist/api/modules/layerbank/reserve.js +1 -1
- package/build/dist/api/modules/lighter/index.js +1 -1
- package/build/dist/api/modules/longbow/administration.js +1 -1
- package/build/dist/api/modules/longbow/analytics.js +1 -1
- package/build/dist/api/modules/longbow/fixed.js +1 -1
- package/build/dist/api/modules/longbow/index.js +1 -1
- package/build/dist/api/modules/longbow/nft.js +1 -1
- package/build/dist/api/modules/longbow/rebates.js +1 -1
- package/build/dist/api/modules/longbow/staking.js +1 -1
- package/build/dist/api/modules/meridian/index.js +1 -1
- package/build/dist/api/modules/meridian/markets.js +1 -1
- package/build/dist/api/modules/meridian/predict-read.js +1 -1
- package/build/dist/api/modules/meridian/rfq.js +1 -1
- package/build/dist/api/modules/merkl/discovery.js +1 -1
- package/build/dist/api/modules/merkl/index.js +1 -1
- package/build/dist/api/modules/merkl/manage.js +1 -1
- package/build/dist/api/modules/merkl/protocol.js +1 -1
- package/build/dist/api/modules/morpho/allocator.js +1 -1
- package/build/dist/api/modules/morpho/bundles.js +1 -1
- package/build/dist/api/modules/morpho/in-kind.js +1 -1
- package/build/dist/api/modules/morpho/index.js +1 -1
- package/build/dist/api/modules/morpho/local-guard.js +1 -1
- package/build/dist/api/modules/morpho/midnight.js +1 -1
- package/build/dist/api/modules/morpho/protocol.js +1 -1
- package/build/dist/api/modules/morpho/vault-management.js +1 -1
- package/build/dist/api/modules/morpho/vault-tools.js +1 -1
- package/build/dist/api/modules/morpho/vault-v2.js +1 -1
- package/build/dist/api/modules/netnet/card-plan.js +1 -1
- package/build/dist/api/modules/netnet/card-policy.d.ts +1 -0
- package/build/dist/api/modules/netnet/card-policy.js +1 -1
- package/build/dist/api/modules/netnet/card-read.js +1 -1
- package/build/dist/api/modules/netnet/card-recovery.js +1 -1
- package/build/dist/api/modules/netnet/desk-action.js +1 -1
- package/build/dist/api/modules/netnet/desk-read.js +1 -1
- package/build/dist/api/modules/netnet/financial.js +1 -1
- package/build/dist/api/modules/netnet/index.js +1 -1
- package/build/dist/api/modules/netnet/staking.js +1 -1
- package/build/dist/api/modules/orbio/index.d.ts +6 -0
- package/build/dist/api/modules/orbio/index.js +1 -1
- package/build/dist/api/modules/orbio/positions.js +1 -1
- package/build/dist/api/modules/pendle/costs.js +1 -1
- package/build/dist/api/modules/pendle/index.js +1 -1
- package/build/dist/api/modules/pendle/markets.js +1 -1
- package/build/dist/api/modules/pendle/positions.js +1 -1
- package/build/dist/api/modules/pendle/pricecheck.js +1 -1
- package/build/dist/api/modules/pendle/reader.js +1 -1
- package/build/dist/api/modules/pendle/redeem.js +1 -1
- package/build/dist/api/modules/pendle/trade.js +1 -1
- package/build/dist/api/modules/pendle/validate.js +1 -1
- package/build/dist/api/modules/pendle/verify.js +1 -1
- package/build/dist/api/modules/pons/claim.js +1 -1
- package/build/dist/api/modules/pons/index.js +1 -1
- package/build/dist/api/modules/pons/launch-status.js +1 -1
- package/build/dist/api/modules/pons/prices.js +1 -1
- package/build/dist/api/modules/pons/reads.js +1 -1
- package/build/dist/api/modules/pons/swap-terms.js +1 -1
- package/build/dist/api/modules/pons/trade.js +1 -1
- package/build/dist/api/modules/poolstrade/index.js +1 -1
- package/build/dist/api/modules/priors/coverage.js +1 -1
- package/build/dist/api/modules/priors/discovery.js +1 -1
- package/build/dist/api/modules/priors/features.js +1 -1
- package/build/dist/api/modules/priors/holdings.js +1 -1
- package/build/dist/api/modules/priors/index.js +1 -1
- package/build/dist/api/modules/priors/integration.js +1 -1
- package/build/dist/api/modules/priors/market.js +1 -1
- package/build/dist/api/modules/priors/pt.js +1 -1
- package/build/dist/api/modules/priors/savings-exit.js +1 -1
- package/build/dist/api/modules/priors/starter-line.js +1 -1
- package/build/dist/api/modules/priors/stock-swap.js +1 -1
- package/build/dist/api/modules/raeto/index.js +1 -1
- package/build/dist/api/modules/relay/api.js +1 -1
- package/build/dist/api/modules/relay/bootstrap.js +1 -1
- package/build/dist/api/modules/relay/discovery.js +1 -1
- package/build/dist/api/modules/relay/inbound.js +1 -1
- package/build/dist/api/modules/relay/index.js +1 -1
- package/build/dist/api/modules/relay/order.js +1 -1
- package/build/dist/api/modules/relay/outbound-status.js +1 -1
- package/build/dist/api/modules/relay/readiness.js +1 -1
- package/build/dist/api/modules/relay/reads.js +1 -1
- package/build/dist/api/modules/relay/vaults.js +1 -1
- package/build/dist/api/modules/spark/actions.js +1 -1
- package/build/dist/api/modules/spark/details.js +1 -1
- package/build/dist/api/modules/spark/index.js +1 -1
- package/build/dist/api/modules/spark/management.js +1 -1
- package/build/dist/api/modules/steakhouse/analytics.js +1 -1
- package/build/dist/api/modules/steakhouse/erc4626.js +1 -1
- package/build/dist/api/modules/steakhouse/index.js +1 -1
- package/build/dist/api/modules/steakhouse/local-guard.js +1 -1
- package/build/dist/api/modules/steakhouse/management.js +1 -1
- package/build/dist/api/modules/steakhouse/v2-exit.js +1 -1
- package/build/dist/api/modules/tickerspring/basket-routes.js +1 -1
- package/build/dist/api/modules/tickerspring/contract-reads.js +1 -1
- package/build/dist/api/modules/tickerspring/discovery.js +1 -1
- package/build/dist/api/modules/tickerspring/exit-preview.js +1 -1
- package/build/dist/api/modules/tickerspring/guards.js +1 -1
- package/build/dist/api/modules/tickerspring/index.js +1 -1
- package/build/dist/api/modules/tickerspring/journeys.js +1 -1
- package/build/dist/api/modules/tickerspring/ladder.js +1 -1
- package/build/dist/api/modules/tickerspring/maker.js +1 -1
- package/build/dist/api/modules/tickerspring/order-accounting.js +1 -1
- package/build/dist/api/modules/tickerspring/research.js +1 -1
- package/build/dist/api/modules/tickerspring/strategies.js +1 -1
- package/build/dist/api/modules/uniswap/auction-create.js +1 -1
- package/build/dist/api/modules/uniswap/auction.js +1 -1
- package/build/dist/api/modules/uniswap/batch.js +1 -1
- package/build/dist/api/modules/uniswap/common.js +1 -1
- package/build/dist/api/modules/uniswap/fees.js +1 -1
- package/build/dist/api/modules/uniswap/index.js +1 -1
- package/build/dist/api/modules/uniswap/local-guard.js +1 -1
- package/build/dist/api/modules/uniswap/oracle.js +1 -1
- package/build/dist/api/modules/uniswap/pool-math.js +1 -1
- package/build/dist/api/modules/uniswap/pools.js +1 -1
- package/build/dist/api/modules/uniswap/position.js +1 -1
- package/build/dist/api/modules/uniswap/protocol.js +1 -1
- package/build/dist/api/modules/uniswap/quote-guard.js +1 -1
- package/build/dist/api/modules/uniswap/token-jar.js +1 -1
- package/build/dist/api/modules/uniswap/trade-batch.js +1 -1
- package/build/dist/api/modules/uniswap/trade.js +1 -1
- package/build/dist/api/modules/uniswap/v2.js +1 -1
- package/build/dist/api/modules/uniswap/v3.js +1 -1
- package/build/dist/api/modules/uniswap/v4.js +1 -1
- package/build/dist/api/modules/uniswap/wrap.js +1 -1
- package/build/dist/api/modules/upoch/copy.d.ts +5 -0
- package/build/dist/api/modules/upoch/copy.js +1 -0
- package/build/dist/api/modules/upoch/index.d.ts +8 -0
- package/build/dist/api/modules/upoch/index.js +1 -0
- package/build/dist/api/modules/upoch/pins.d.ts +8 -0
- package/build/dist/api/modules/upoch/pins.js +1 -0
- package/build/dist/api/modules/upoch/reads.d.ts +509 -0
- package/build/dist/api/modules/upoch/reads.js +1 -0
- package/build/dist/api/modules/velora/claims.js +1 -1
- package/build/dist/api/modules/velora/delta-reads.js +1 -1
- package/build/dist/api/modules/velora/index.js +1 -1
- package/build/dist/api/modules/wormhole/index.js +1 -1
- package/build/dist/api/modules/wormhole/x402-client.d.ts +17 -1
- package/build/dist/api/modules/wormhole/x402-client.js +1 -1
- package/build/dist/api/positions.js +1 -1
- package/build/dist/api/pricenote.js +1 -1
- package/build/dist/api/prices.js +1 -1
- package/build/dist/api/pricing.js +1 -1
- package/build/dist/api/rpc.js +1 -1
- package/build/dist/api/secret-fields.d.ts +2 -0
- package/build/dist/api/secret-fields.js +1 -1
- package/build/dist/api/send.js +1 -1
- package/build/dist/api/signing-registry.js +1 -1
- package/build/dist/api/signing.js +1 -1
- package/build/dist/api/simulate.js +1 -1
- package/build/dist/api/swap.js +1 -1
- package/build/dist/api/tokens.js +1 -1
- package/build/dist/api/tool-policy.d.ts +1 -0
- package/build/dist/api/tool-policy.js +1 -1
- package/build/dist/api/usd-estimate.js +1 -1
- package/build/dist/chunks/23HNDJ76.js +2 -0
- package/build/dist/chunks/{JS53DQVT.js → 24Q3FNGX.js} +1 -1
- package/build/dist/chunks/{N245WC5R.js → 25C4DTVA.js} +1 -1
- package/build/dist/chunks/{PV4AK32X.js → 2HN3U6OG.js} +1 -1
- package/build/dist/chunks/{GQYV4TFO.js → 2OVJ2BTJ.js} +1 -1
- package/build/dist/chunks/{DYYEA5HB.js → 2QGLPY2D.js} +1 -1
- package/build/dist/chunks/{ZFU65MB4.js → 2WRXH6BL.js} +1 -1
- package/build/dist/chunks/{EZZM2GQT.js → 2ZBSE2LD.js} +1 -1
- package/build/dist/chunks/{HIX5N25Z.js → 2ZQ7X223.js} +1 -1
- package/build/dist/chunks/{V37L4DU4.js → 3A2IKFTV.js} +1 -1
- package/build/dist/chunks/{FWIFTPSE.js → 3PU2SD3U.js} +1 -1
- package/build/dist/chunks/{SBY4RJ7I.js → 3ZH5SOC2.js} +1 -1
- package/build/dist/chunks/4NBXBKOX.js +2 -0
- package/build/dist/chunks/{FOKEFXGP.js → 4PLLS6CT.js} +1 -1
- package/build/dist/chunks/{KREBNL2D.js → 4R3G3H42.js} +1 -1
- package/build/dist/chunks/{XHYFISVV.js → 4Z3IGMU6.js} +1 -1
- package/build/dist/chunks/{CSDN4MYP.js → 5GQJVKVY.js} +1 -1
- package/build/dist/chunks/{JOKL5L6X.js → 5R576SDB.js} +1 -1
- package/build/dist/chunks/{UUID2E22.js → 5W74Z4WZ.js} +1 -1
- package/build/dist/chunks/{EH5G4O3U.js → 65356YKW.js} +1 -1
- package/build/dist/chunks/{QFSBDPLN.js → 65OITTDL.js} +1 -1
- package/build/dist/chunks/{DSTMEY5F.js → 6F527FLN.js} +1 -1
- package/build/dist/chunks/{CO4GCF4L.js → 6MDYKE2O.js} +1 -1
- package/build/dist/chunks/{IEG6GLFR.js → 6OCLWSMZ.js} +1 -1
- package/build/dist/chunks/75SULXNT.js +1 -0
- package/build/dist/chunks/{WU7XIAXB.js → 7EACRKFV.js} +1 -1
- package/build/dist/chunks/{AMTRDPVO.js → 7U62MMUQ.js} +1 -1
- package/build/dist/chunks/{DW4V5PUY.js → 7VH6JQ2H.js} +1 -1
- package/build/dist/chunks/{XVJ7ILKK.js → A2V4NFVA.js} +1 -1
- package/build/dist/chunks/A3BJSQ23.js +1 -0
- package/build/dist/chunks/{YSMWCKIX.js → ADIPEGNN.js} +1 -1
- package/build/dist/chunks/ANIF3JMV.js +4 -0
- package/build/dist/chunks/{RLI4JDOL.js → ATEVAJ5Y.js} +1 -1
- package/build/dist/chunks/{F3VDVTMS.js → B2HSLY5F.js} +1 -1
- package/build/dist/chunks/{N4XNNXOJ.js → B7BNDW35.js} +1 -1
- package/build/dist/chunks/{GLF7WEY2.js → C6VJAL5B.js} +1 -1
- package/build/dist/chunks/{5PI57UC2.js → C76D54YG.js} +1 -1
- package/build/dist/chunks/{GRSXWQWD.js → CD2JQ32C.js} +1 -1
- package/build/dist/chunks/{4GNUXN4K.js → CI5ENLYA.js} +1 -1
- package/build/dist/chunks/{F4UQEPJT.js → CZQ2CGYV.js} +1 -1
- package/build/dist/chunks/{APHNOGNS.js → D2IYA4LP.js} +1 -1
- package/build/dist/chunks/{4RQAOOO2.js → D7QXZM3S.js} +1 -1
- package/build/dist/chunks/{TDZTC5WR.js → DBOGRUPS.js} +1 -1
- package/build/dist/chunks/{Y77EVVT4.js → DGDMRATN.js} +1 -1
- package/build/dist/chunks/{3DNJTJ2X.js → DMB64UIN.js} +1 -1
- package/build/dist/chunks/{TM7Z5SA4.js → DMDOSHV7.js} +1 -1
- package/build/dist/chunks/{WHVZ372B.js → DRLBTB4E.js} +1 -1
- package/build/dist/chunks/{FZ6IJZZM.js → E76Z2TT4.js} +1 -1
- package/build/dist/chunks/{C75MT5SD.js → EHK7CDTU.js} +1 -1
- package/build/dist/chunks/{KKPMOAVI.js → ELHRXA5U.js} +1 -1
- package/build/dist/chunks/{XCKTE4ON.js → F7MGYRPU.js} +1 -1
- package/build/dist/chunks/{MRMR4QHA.js → FAH7FKUT.js} +1 -1
- package/build/dist/chunks/{M7ZXDLKM.js → FGEGJOAA.js} +1 -1
- package/build/dist/chunks/{N6GIC7HJ.js → FN6GNTPR.js} +1 -1
- package/build/dist/chunks/{ZF2VPDRQ.js → FTMA24EC.js} +1 -1
- package/build/dist/chunks/FXOFR432.js +1 -0
- package/build/dist/chunks/{VHV6WQ5F.js → G2AA73ZE.js} +1 -1
- package/build/dist/chunks/{JWR5XVP2.js → GBIBRYOV.js} +1 -1
- package/build/dist/chunks/{FNGIJKMZ.js → GDOHHXNH.js} +1 -1
- package/build/dist/chunks/{LR4XTZ37.js → GP6YO24Z.js} +1 -1
- package/build/dist/chunks/{2OKYXT25.js → GQITAJVF.js} +1 -1
- package/build/dist/chunks/H3E7UD2X.js +1 -0
- package/build/dist/chunks/HFVXNKA5.js +1 -0
- package/build/dist/chunks/HHYE42JG.js +21 -0
- package/build/dist/chunks/{UOCRYXAB.js → HRAHGYNK.js} +1 -1
- package/build/dist/chunks/{U363GQTF.js → HS5HWBMU.js} +1 -1
- package/build/dist/chunks/{ARI72OYT.js → HVFMIURK.js} +1 -1
- package/build/dist/chunks/IBL6TL2Q.js +1 -0
- package/build/dist/chunks/{HCBX4NFM.js → IT2JLILU.js} +1 -1
- package/build/dist/chunks/{REWXG6X6.js → JDSSYT6R.js} +1 -1
- package/build/dist/chunks/{XRDXFHIK.js → JFWJBZ7M.js} +1 -1
- package/build/dist/chunks/{523ZIR3J.js → JI5DXDMY.js} +1 -1
- package/build/dist/chunks/{7QKYDNF6.js → JPPQDELB.js} +1 -1
- package/build/dist/chunks/{ZP36DSOD.js → K4P5VYDP.js} +1 -1
- package/build/dist/chunks/{32RXFUOH.js → KBU3PYP7.js} +1 -1
- package/build/dist/chunks/{BB765L75.js → KH4QFN72.js} +1 -1
- package/build/dist/chunks/{YTLH4M4Y.js → KMSAUFYV.js} +1 -1
- package/build/dist/chunks/{6UVGQYZ3.js → KOTGFD2V.js} +1 -1
- package/build/dist/chunks/{4JTTA3BX.js → KZA5GYZR.js} +1 -1
- package/build/dist/chunks/{WUT7TZYM.js → LCH6F5HT.js} +1 -1
- package/build/dist/chunks/{ARLGF5MU.js → LDJI2JAL.js} +1 -1
- package/build/dist/chunks/LEV5SNNC.js +3 -0
- package/build/dist/chunks/{SPRVVJXI.js → LFSJDFMY.js} +1 -1
- package/build/dist/chunks/{J73ATSEQ.js → LJJYYUEG.js} +1 -1
- package/build/dist/chunks/{CAWTAR5V.js → LKX5WDOQ.js} +1 -1
- package/build/dist/chunks/M7BUKZW2.js +1 -0
- package/build/dist/chunks/{C5ZZAYXD.js → MI5HZDMH.js} +1 -1
- package/build/dist/chunks/{YWZQJJYY.js → MMCM3GSM.js} +1 -1
- package/build/dist/chunks/MQ5F2VOK.js +1 -0
- package/build/dist/chunks/{TE6D3OIX.js → MSMHS456.js} +1 -1
- package/build/dist/chunks/{JKD2B6OX.js → MSRCJ2BS.js} +1 -1
- package/build/dist/chunks/{YMV5TL5C.js → N64JJN37.js} +1 -1
- package/build/dist/chunks/{JKRBGAX2.js → NAO7VWZF.js} +1 -1
- package/build/dist/chunks/ND32LJWI.js +1 -0
- package/build/dist/chunks/{RT7IU6TI.js → NMJVQX5M.js} +1 -1
- package/build/dist/chunks/{67BWOVET.js → NMQBOBWJ.js} +1 -1
- package/build/dist/chunks/NQ4MTIU3.js +1 -0
- package/build/dist/chunks/{XWKK75TO.js → NWPAQER2.js} +1 -1
- package/build/dist/chunks/O2J5I4VA.js +1 -0
- package/build/dist/chunks/{2SUHQWND.js → O4S6XAYV.js} +1 -1
- package/build/dist/chunks/{TAEZTP4L.js → O5QTITN6.js} +1 -1
- package/build/dist/chunks/{NA424YAL.js → OB7BFDOV.js} +1 -1
- package/build/dist/chunks/{GW5IXLKU.js → OI3N4EW4.js} +1 -1
- package/build/dist/chunks/{FL5SSHUL.js → OIQTZOBN.js} +1 -1
- package/build/dist/chunks/{XPEDQBLI.js → OODSXDIH.js} +1 -1
- package/build/dist/chunks/OOPMZIG7.js +1 -0
- package/build/dist/chunks/{GG24LO2R.js → OQFNUDMQ.js} +1 -1
- package/build/dist/chunks/{Q2ACLVWR.js → ORG6LVKJ.js} +1 -1
- package/build/dist/chunks/{XYPGLG6A.js → OSMOBKRQ.js} +1 -1
- package/build/dist/chunks/{EGZREEG2.js → OTLUQWLF.js} +1 -1
- package/build/dist/chunks/{OYJFXEDU.js → OTYB6BHK.js} +1 -1
- package/build/dist/chunks/{OZ5MDUD2.js → OVM4QIET.js} +1 -1
- package/build/dist/chunks/{OYPAVXGQ.js → OYDKAIS2.js} +1 -1
- package/build/dist/chunks/P6OB2AFW.js +1 -0
- package/build/dist/chunks/{UQEEF5W5.js → PDPTJMTJ.js} +1 -1
- package/build/dist/chunks/PEHXHQVA.js +1 -0
- package/build/dist/chunks/PMFR47H3.js +1 -0
- package/build/dist/chunks/{HHO5ISMM.js → PQXYTOV5.js} +1 -1
- package/build/dist/chunks/{HKVQ646Q.js → PSGRZWES.js} +1 -1
- package/build/dist/chunks/Q7L3BX6U.js +1 -0
- package/build/dist/chunks/{753HZZTY.js → QBYV7NXH.js} +1 -1
- package/build/dist/chunks/{2LWBN35N.js → QIB6OMQV.js} +1 -1
- package/build/dist/chunks/{TPEKCXVE.js → QLAOBULN.js} +1 -1
- package/build/dist/chunks/{DNNFKDZR.js → QLFPAN6S.js} +1 -1
- package/build/dist/chunks/QMEGAKLI.js +1 -0
- package/build/dist/chunks/{TK55VASJ.js → QMNUB2GM.js} +1 -1
- package/build/dist/chunks/{YUHNPUNK.js → R73R4KN3.js} +1 -1
- package/build/dist/chunks/{VR344DAZ.js → RN3WUJIO.js} +1 -1
- package/build/dist/chunks/{5HIHUYA4.js → RNCMXKKS.js} +1 -1
- package/build/dist/chunks/{ZOMFHTB2.js → ROQQ62LP.js} +1 -1
- package/build/dist/chunks/{D742AYEV.js → RUTSEGGD.js} +1 -1
- package/build/dist/chunks/{TFDPEAVZ.js → S4JUFCT4.js} +1 -1
- package/build/dist/chunks/{KDGSYNOP.js → S4UJDZGN.js} +1 -1
- package/build/dist/chunks/{AI3VAPA3.js → SMSXZ3FN.js} +1 -1
- package/build/dist/chunks/{JLRHM2DQ.js → SUNTJ6IU.js} +1 -1
- package/build/dist/chunks/{2FHELZ7Y.js → TGFQQCRY.js} +1 -1
- package/build/dist/chunks/{4JRXEN7C.js → THL4TMQW.js} +2 -2
- package/build/dist/chunks/TI727O2H.js +1 -0
- package/build/dist/chunks/{RLMVA575.js → TMRAF2L2.js} +1 -1
- package/build/dist/chunks/{PV5FDT6O.js → TXGZ6NWN.js} +1 -1
- package/build/dist/chunks/U243AWCH.js +1 -0
- package/build/dist/chunks/U762746N.js +1 -0
- package/build/dist/chunks/{GDRQ2ANN.js → U7UPLF4F.js} +1 -1
- package/build/dist/chunks/{4Q2ZBZXM.js → UPKVD7WG.js} +1 -1
- package/build/dist/chunks/{ZQAFFWDK.js → URBEK2VV.js} +1 -1
- package/build/dist/chunks/{VTPT5544.js → USEF3QKG.js} +1 -1
- package/build/dist/chunks/{U2YCQWZK.js → UVAR6BHU.js} +1 -1
- package/build/dist/chunks/{7VC53B5X.js → V5YSJKRH.js} +13 -13
- package/build/dist/chunks/{7D73A6KS.js → VB36EHIR.js} +1 -1
- package/build/dist/chunks/VMZYFO6I.js +1 -0
- package/build/dist/chunks/{UEDGYZOC.js → VVAM3EAK.js} +1 -1
- package/build/dist/chunks/VVJO6OYK.js +1 -0
- package/build/dist/chunks/{JESMX2UC.js → VXCGMALF.js} +1 -1
- package/build/dist/chunks/{ZKZUS3QU.js → VZVW5J7J.js} +1 -1
- package/build/dist/chunks/{NUFZUKYS.js → W32UECOL.js} +1 -1
- package/build/dist/chunks/{O3JWCJIF.js → W4RYRLL5.js} +1 -1
- package/build/dist/chunks/{2MZXTOZU.js → WAKZWSHB.js} +1 -1
- package/build/dist/chunks/{BAIY32AV.js → WBNFRPAT.js} +1 -1
- package/build/dist/chunks/{HM72DH4V.js → WRUTW6CG.js} +1 -1
- package/build/dist/chunks/{VYYSL557.js → WSILNJS2.js} +1 -1
- package/build/dist/chunks/{L646YWDP.js → X24YTJST.js} +1 -1
- package/build/dist/chunks/{4FPV4CRC.js → X5AL3DUK.js} +1 -1
- package/build/dist/chunks/{SOTYQGPT.js → XBNZ7GTY.js} +1 -1
- package/build/dist/chunks/{BZ34ZR65.js → XEBMS5KU.js} +1 -1
- package/build/dist/chunks/{FOD34G2H.js → XL3W7DAQ.js} +1 -1
- package/build/dist/chunks/{GSFHM5L3.js → XPWGPZ2C.js} +1 -1
- package/build/dist/chunks/{2E4I7CJ7.js → XRDLMTBJ.js} +1 -1
- package/build/dist/chunks/{SKEKXEUU.js → XV3YJ4P6.js} +1 -1
- package/build/dist/chunks/XW3VGWXK.js +1 -0
- package/build/dist/chunks/{6WD4HHID.js → Y2QADJOB.js} +1 -1
- package/build/dist/chunks/Y64GFBTA.js +1 -0
- package/build/dist/chunks/{FJLJ7ZQ5.js → YARZE7SJ.js} +1 -1
- package/build/dist/chunks/{OARVU3RC.js → YBLJ75U5.js} +1 -1
- package/build/dist/chunks/YRSAZTTC.js +7 -0
- package/build/dist/chunks/{3VBIRLU3.js → YXXK6EPI.js} +1 -1
- package/build/dist/chunks/Z3IBPCY4.js +2 -0
- package/build/dist/chunks/{H5DY7CNB.js → Z7FGEWO2.js} +1 -1
- package/build/dist/chunks/{INOYMBWE.js → ZNPVBNC5.js} +1 -1
- package/build/dist/chunks/{EVBHQQQG.js → ZTKT3ZQK.js} +1 -1
- package/build/dist/chunks/{4BVP652W.js → ZZ6FZGHF.js} +1 -1
- package/package.json +1 -1
- package/build/dist/chunks/3K2N5VFH.js +0 -1
- package/build/dist/chunks/3ZABD6ZF.js +0 -2
- package/build/dist/chunks/44MB6SA6.js +0 -1
- package/build/dist/chunks/4D4ZRZUW.js +0 -1
- package/build/dist/chunks/4OVIMYNH.js +0 -2
- package/build/dist/chunks/6NUNCD5J.js +0 -1
- package/build/dist/chunks/6PZGDVHV.js +0 -1
- package/build/dist/chunks/7MBVTNLU.js +0 -1
- package/build/dist/chunks/7VNO46LV.js +0 -1
- package/build/dist/chunks/DPE7SPW7.js +0 -1
- package/build/dist/chunks/E3RACZUY.js +0 -1
- package/build/dist/chunks/EI6GGPDS.js +0 -20
- package/build/dist/chunks/FV4WZOTD.js +0 -1
- package/build/dist/chunks/FWD4L3CJ.js +0 -1
- package/build/dist/chunks/JBTOZ6IH.js +0 -1
- package/build/dist/chunks/MVD3KWPP.js +0 -1
- package/build/dist/chunks/P6OMKZMR.js +0 -3
- package/build/dist/chunks/PXVREXCS.js +0 -1
- package/build/dist/chunks/QJNLLI6N.js +0 -1
- package/build/dist/chunks/RPB46QAC.js +0 -1
- package/build/dist/chunks/TID4C2KC.js +0 -1
- package/build/dist/chunks/UWBKAWX3.js +0 -7
- package/build/dist/chunks/WHTRPRRD.js +0 -1
- package/build/dist/chunks/WLMWWEP7.js +0 -2
- package/build/dist/chunks/XQ24RSEI.js +0 -1
- package/build/dist/chunks/YDNTY67T.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"./ATEVAJ5Y.js";import{i as de}from"./UVAR6BHU.js";import{b as Te,o as Me}from"./LKX5WDOQ.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 +1 @@
|
|
|
1
|
-
import{b as o,g as s}from"./NWNYJ26T.js";import{
|
|
1
|
+
import{b as o,g as s}from"./NWNYJ26T.js";import{b as i,t as r}from"./TI727O2H.js";var d=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",r.mainnet.usdg.toLowerCase()]);function a(f,e,n){if(f!=="relay_bridge_in"||e.swap!==void 0||typeof n!="string"||!o.test(n)||e.destinationChainId!==void 0&&e.destinationChainId!==i||e.recipient!==void 0&&(typeof e.recipient!="string"||!s(e.recipient,n)))return!1;let t=e.destinationCurrency??"0x0000000000000000000000000000000000000000";return typeof t=="string"&&d.has(t.toLowerCase())}export{a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as D}from"./IX3GZMTM.js";import{
|
|
1
|
+
import{b as D}from"./IX3GZMTM.js";import{b as d}from"./TI727O2H.js";import{a as c}from"./XSD5NL7J.js";import{concat as B,encodeAbiParameters as k,getAddress as v,isAddress as F,keccak256 as g,parseAbiParameters as O,recoverAddress as q,toHex as N}from"viem";import{privateKeyToAccount as U}from"viem/accounts";var T="OakPriceNote",l="1",w=300,E="0x0000000000000000000000000000000000000000",W=g(N("PriceNote(address wallet,uint256 oakPerEthE18,uint64 timestamp,bytes32 nonce)")),L=g(N("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")),M=(1n<<64n)-1n,P=(1n<<256n)-1n,z=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,G=0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0n;function X(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{130}$/.test(e))return!1;let n=BigInt(`0x${e.slice(2,66)}`),t=BigInt(`0x${e.slice(66,130)}`),i=Number.parseInt(e.slice(130,132),16);return!(i!==27&&i!==28||n<=0n||n>=z||t<=0n||t>G)}function m(e,n){if(typeof e!="string"||!F(e,{strict:!1}))throw new c(`Invalid ${n} address.`);return v(e)}function p(e,n){let t;if(typeof e=="bigint")t=e;else if(typeof e=="number"){if(!Number.isSafeInteger(e)||e<0)throw new c(`Invalid ${n}.`);t=BigInt(e)}else t=D(e);if(t<0n||t>P)throw new c(`${n} exceeds uint256 bounds.`);return t}function h(e,n){let t=p(e,n);if(t>M)throw new c(`${n} exceeds uint64 bounds.`);return t}function Y(e,n){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new c(`${n} must be a 32-byte hex string.`);return e}function j(e){if(typeof e=="bigint"){if(e<=0n||e>P)throw new c("Private key must be a positive scalar.");return`0x${e.toString(16).padStart(64,"0")}`}if(typeof e=="string"&&/^0x[0-9a-fA-F]{1,64}$/.test(e))return`0x${e.slice(2).padStart(64,"0")}`;throw new c("Invalid private key format.")}function K(e){let n=p(e.chainId,"chainId"),t=m(e.verifyingContract,"verifyingContract");return g(k(O("bytes32, bytes32, bytes32, uint256, address"),[L,g(N(e.name)),g(N(e.version)),n,t]))}function ae(e,n=d,t=l){return{name:T,version:t,chainId:Number(p(n,"chainId")),verifyingContract:m(e,"consumer")}}function J(e,n=d,t=l){return K({name:T,version:t,chainId:n,verifyingContract:e})}function Q(e){let n=m(e.wallet,"wallet"),t=p(e.oakPerEthE18,"oakPerEthE18"),i=h(e.timestamp,"timestamp"),r=Y(e.nonce,"nonce");return g(k(O("bytes32, address, uint256, uint64, bytes32"),[W,n,t,i,r]))}function C(e,n,t=d,i=l){let r=J(n,t,i),o=Q(e);return g(B(["0x1901",r,o]))}async function ce(e,n,t,i=d,r=l){let o=C(e,n,i,r);return typeof t=="object"&&t!==null&&"sign"in t?t.sign({hash:o}):U(j(t)).sign({hash:o})}async function Z(e,n,t,i=d,r=l){if(!X(n))return E;try{let o=C(e,t,i,r),x=await q({hash:o,signature:n});return v(x)}catch{return E}}function ee(e,n){let t=p(e,"oakPerEthE18"),i=p(n,"spotOakPerEthE18");if(i<=0n||t<=0n)return!1;if(t>P/2n||i>P/3n)throw new c("Guard arithmetic overflow.");let r=t*2n;return r>=i&&r<=i*3n}function te(e,n,t,i){if("signature"in e&&"consumer"in e&&"note"in e&&!("average"in e))return e;if("note"in e&&"signature"in e&&"consumer"in e){let a=e,f=n??{};return{...f,note:a.note,signature:a.signature,consumer:f.consumer??a.consumer,expiresAt:f.expiresAt??a.expiresAt}}return{...i??{},note:e,signature:n,consumer:t}}async function fe(e,n,t,i){let r=te(e,n,t,i),{note:o,signature:x,consumer:S}=r,a=h(o.timestamp,"timestamp"),f=p(o.oakPerEthE18,"oakPerEthE18"),y=(a+BigInt(w)).toString(),s=(b,V,H)=>({valid:!1,ok:!1,...H?{signer:H}:{},oakPerEthE18:f.toString(),expiresAt:y,reason:b,error:V}),I=r.wallet??r.boundWallet;if(I===void 0)return s("wrong_wallet","Bound wallet context is required to verify a price note.");if(m(o.wallet,"wallet")!==m(I,"boundWallet"))return s("wrong_wallet","Price note wallet does not match the bound wallet.");if(r.now===void 0)return s("expired","Current time (now) is required to verify price note expiry.");let A=h(r.now,"now");if(a>A)return s("not_yet_valid","Price note timestamp is in the future.");if(A-a>BigInt(w))return s("expired","Price note has expired.");if(r.expiresAt!==void 0){let b=h(r.expiresAt,"expiresAt");if(b!==a+BigInt(w)||A>b)return s("expired","Price note has expired.")}let R=r.chainId??d,$=r.version??l,u=await Z(o,x,S,R,$);if(u===E)return s("bad_signature","Price note signature could not be recovered.");if(r.signer===void 0)return s("bad_signature","Expected oracle signer is required to verify a price note.",u);let _=m(r.signer,"signer");return _===E||u!==_?s("bad_signature","Price note signer does not match the oracle signer.",u):r.spotOakPerEthE18===void 0?s("outside_guard","Spot OAK/ETH price is required to verify the price note guard band.",u):ee(f,r.spotOakPerEthE18)?{valid:!0,ok:!0,signer:u,oakPerEthE18:f.toString(),expiresAt:y}:s("outside_guard","Price note is outside the 50% spot guard band.",u)}export{T as a,l as b,w as c,E as d,W as e,K as f,ae as g,J as h,Q as i,C as j,ce as k,Z as l,ee as m,fe as n};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as D}from"./43LI5NKJ.js";import{b as Q}from"./IX3GZMTM.js";import{a as x,i as J}from"./FWD4L3CJ.js";import{a as r}from"./XSD5NL7J.js";import{decodeAbiParameters as se,encodeAbiParameters as Z,encodeFunctionData as F,erc20Abi as O,getAddress as g,keccak256 as ee,parseAbi as L,parseAbiParameters as oe,zeroAddress as te}from"viem";var I=10n**18n,$=(1n<<256n)-1n,q=g(J[x].morpho.morpho_blue.address),_=oe("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),w=L(["function adaptersLength() view returns (uint256)","function adapters(uint256) view returns (address)","function liquidityAdapter() view returns (address)","function liquidityData() view returns (bytes)","function forceDeallocatePenalty(address) view returns (uint256)","function performanceFee() view returns (uint256)","function managementFee() view returns (uint256)","function owner() view returns (address)","function curator() view returns (address)","function previewRedeem(uint256) view returns (uint256)","function previewWithdraw(uint256) view returns (uint256)","function forceDeallocate(address adapter,bytes data,uint256 assets,address onBehalf) returns (uint256)","function redeem(uint256 shares,address receiver,address owner) returns (uint256)","function multicall(bytes[] data)"]),v=L(["function parentVault() view returns (address)","function asset() view returns (address)","function morpho() view returns (address)","function marketIdsLength() view returns (uint256)","function marketIds(uint256) view returns (bytes32)","function expectedSupplyAssets(bytes32) view returns (uint256)"]),ne=L(["function idToMarketParams(bytes32) view returns (address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)","function market(bytes32) view returns (uint128 totalSupplyAssets,uint128 totalSupplyShares,uint128 totalBorrowAssets,uint128 totalBorrowShares,uint128 lastUpdate,uint128 fee)"]),M=(e,t)=>e<t?e:t,T=(e,t)=>(e+t-1n)/t;function p(e){if(typeof e!="bigint"||e<0n||e>$)throw new r("Invalid Morpho V2 integer read.");return e}function he(e){if(typeof e!="string")throw new r("Provide maxPenaltyAssets as a USDG base-unit integer string, including 0 for no penalty.");let t=Q(e);if(t>$)throw new r("Penalty limit exceeds uint256.");return t}function h(e){if(typeof e!="string")throw new r("Invalid Morpho V2 address read.");return D(e),g(e)}async function ae(e,t,n){if(await e.getChainId()!==x||n.chainId!==x)throw new r("Vault exit requires chain 4663.");let c=await e.getBlockNumber({cacheTime:0}),a=(m,y,k,S=[])=>e.readContract({address:m,abi:y,functionName:k,args:S,blockNumber:c}),[d,o,i,l,u]=await Promise.all([a(t,w,"adaptersLength"),a(t,w,"liquidityAdapter"),a(t,w,"liquidityData"),a(g(n.address),O,"balanceOf",[t]),a(g(n.address),O,"balanceOf",[q])]);if(p(d)!==1n)throw new r("Force exit requires exactly one verified MorphoMarketV1AdapterV2. This vault needs a separately qualified adapter plan.");let s=h(await a(t,w,"adapters",[0n])),C=h(o);if(C!==te&&C!==s)throw new r("The liquidity adapter is not the supported market adapter.");let[A,N,P,f,B]=await Promise.all([a(s,v,"parentVault"),a(s,v,"asset"),a(s,v,"morpho"),a(s,v,"marketIdsLength"),a(t,w,"forceDeallocatePenalty",[s])]);if(h(A)!==g(t)||h(N)!==g(n.address)||h(P)!==q)throw new r("The adapter does not match this vault and pinned Morpho Blue deployment.");let b=p(f);if(b>64n)throw new r("The adapter market inventory exceeds this reader\u2019s supported size.");let E=p(B);if(E>I/50n)throw new r("The force-deallocation penalty exceeds the documented 2% maximum.");let H;if(C!==te){if(typeof i!="string")throw new r("Invalid liquidity-market data.");let[m]=se(_,i);H=ee(Z(_,[m])).toLowerCase()}let V=await Promise.all(Array.from({length:Number(b)},(m,y)=>a(s,v,"marketIds",[BigInt(y)])));if(V.some(m=>typeof m!="string"||!/^0x[0-9a-f]{64}$/i.test(m))||new Set(V.map(m=>String(m).toLowerCase())).size!==V.length)throw new r("The adapter returned an invalid or duplicate market ID.");let R=await Promise.all(V.map(async m=>{let y=m,[k,S,ie]=await Promise.all([a(q,ne,"idToMarketParams",[y]),a(q,ne,"market",[y]),a(s,v,"expectedSupplyAssets",[y])]);if(!Array.isArray(k)||k.length!==5||!Array.isArray(S)||S.length!==6)throw new r("Invalid Morpho market state.");let z={loanToken:h(k[0]),collateralToken:h(k[1]),oracle:h(k[2]),irm:h(k[3]),lltv:p(k[4])},j=Z(_,[z]);if(ee(j).toLowerCase()!==y.toLowerCase()||z.loanToken!==g(n.address))throw new r("Morpho market identity or loan asset does not match the vault.");let G=p(S[0]),X=p(S[2]);if(X>G)throw new r("Invalid Morpho market liquidity.");let Y=p(ie),K=G-X;return{id:y,adapter:s,data:j,supplied:Y,liquidity:K,capacity:M(Y,K),penalty:E,normal:y.toLowerCase()===H}})),U=p(l),W=p(u),re=U+M(W,R.filter(m=>m.normal).reduce((m,y)=>m+y.capacity,0n));return{vault:t,blockNumber:c,idle:U,blueCash:W,normalCapacity:re,markets:R}}function de(e,t){if(t<=0n||t>$)throw new r("Force exit needs a positive position value.");let n=t>e.normalCapacity?t-e.normalCapacity:0n,c=[],a=e.blueCash-(e.normalCapacity-e.idle);for(let d of e.markets.filter(o=>!o.normal).sort((o,i)=>o.capacity===i.capacity?o.id.localeCompare(i.id):o.capacity>i.capacity?-1:1)){if(n===0n)break;let o=M(d.capacity,a);if(o===0n)continue;let i=s=>s+T(s*d.penalty,I),l=o;i(o)>=n&&(l=T(n*I,I+d.penalty),l>0n&&i(l-1n)>=n&&(l-=1n),l=M(o,l+(T(t,10000n)||1n)));let u=T(l*d.penalty,I);c.push({...d,amount:l,penaltyAssets:u}),a-=l,n=i(l)>=n?0n:n-i(l)}if(n>0n)throw new r("Underlying market liquidity cannot cover this force exit. Request a partial withdrawal or use a separately supported in-kind exit; force deallocation cannot create liquidity.");return{requestedAssets:t,normalCapacity:e.normalCapacity,legs:c,penaltyAssets:c.reduce((d,o)=>d+o.penaltyAssets,0n)}}async function we(e,t,n,c,a,d,o){let i=await ae(t,n,o),l=p(await t.readContract({address:n,abi:O,functionName:"balanceOf",args:[c],blockNumber:i.blockNumber}));if(a<=0n||a>l)throw new r("The fresh share balance cannot cover this exit.");let u=p(await t.readContract({address:n,abi:w,functionName:"previewRedeem",args:[a],blockNumber:i.blockNumber})),s=de(i,u);if(s.penaltyAssets>d)throw new r("The force-exit penalty exceeds maxPenaltyAssets. Inspect a fresh plan before authorizing a larger penalty.");let A=(await Promise.all(s.legs.map(b=>t.readContract({address:n,abi:w,functionName:"previewWithdraw",args:[b.penaltyAssets],blockNumber:i.blockNumber})))).reduce((b,E)=>b+p(E),0n);if(A>=a)throw new r("The penalty would consume the share balance.");let N=a-A,P=s.legs.map(b=>F({abi:w,functionName:"forceDeallocate",args:[b.adapter,b.data,b.amount,c]})),f=F({abi:w,functionName:"redeem",args:[N,c,c]});return P.push(f),{tx:e.unsignedTx({to:n,chainId:x,value:"0",data:s.legs.length?F({abi:w,functionName:"multicall",args:[P]}):f,description:`Exit this wallet\u2019s Morpho V2 shares; estimated penalty ${s.penaltyAssets} ${o.symbol} base units. No approvals.`}),plan:s,penaltyShares:A,redeemShares:N,blockNumber:i.blockNumber}}var ye="This vault lists no lending markets right now, and Morpho's index shows 0% over this window. On these numbers it earns nothing.";async function be(e,t){try{let n=p(await e.readContract({address:t,abi:w,functionName:"adaptersLength"}));if(n>8n)return;let c=await Promise.all(Array.from({length:Number(n)},(d,o)=>e.readContract({address:t,abi:w,functionName:"adapters",args:[BigInt(o)]})));return(await Promise.all(c.map(d=>e.readContract({address:h(d),abi:v,functionName:"marketIdsLength"})))).every(d=>p(d)===0n)}catch{return}}var ce="In-kind exits transfer supported market positions rather than cash; use the project in_kind_exit tool.";function ge(e,t,n,c,a=ce){return{name:t,inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:async(d,o)=>{try{if(D(o),Object.keys(d).length)throw new r("Vault details takes no arguments.");let i=e.clientFor(x);if(await i.getChainId()!==x)throw new r("Vault details requires chain 4663.");let l=await i.readContract({address:n,abi:L(["function asset() view returns (address)"]),functionName:"asset"});if(h(l)!==g(c.address))throw new r("The vault does not use the pinned underlying asset.");let u=await ae(i,n,c),[s,C,A,N]=await Promise.all(["performanceFee","managementFee","owner","curator"].map(f=>i.readContract({address:n,abi:w,functionName:f,blockNumber:u.blockNumber}))),P={...c,address:g(c.address)};return{vault:n,chainId:x,blockNumber:u.blockNumber.toString(),asset:P,owner:h(A),curator:h(N),idleAssets:u.idle.toString(),normalCapacityAssets:u.normalCapacity.toString(),markets:u.markets.map(f=>({marketId:f.id,adapter:f.adapter,suppliedAssets:f.supplied.toString(),marketLiquidityAssets:f.liquidity.toString(),capacityAssets:f.capacity.toString(),liquidityMarket:f.normal,penaltyWad:f.penalty.toString()})),fees:{performanceFeeWad:p(s).toString(),managementFeePerSecondWad:p(C).toString(),scale:I.toString()},apy:null,apyStatus:"This onchain snapshot does not include APY. Use the module analytics tool for indexed historical APY; maxRate is an accrual ceiling.",capacityCaveat:`Snapshot estimates; gates, price accrual, liquidity and penalties can change. Preview the exact action. Force exits may leave share rounding dust. ${a}`}}catch(i){throw new r(e.plainError(i))}}}}function ke(e,t){return`Force-exit estimate: position ${e.requestedAssets} ${t} base units; penalty ${e.penaltyAssets}; net estimate ${e.requestedAssets-e.penaltyAssets}; effective penalty ${T(e.penaltyAssets*10000n,e.requestedAssets)} bps (rounded up). Penalty limit is a local preview check, not a calldata bound. Re-preview before signing and recheck positions for rounding dust.`}function xe(e,t,n,c,a){let d=(i,l)=>e.filter(u=>u.token.chainId===x&&u.token.address.toLowerCase()===i.toLowerCase()).reduce((u,s)=>{if(s.token.decimals!==l||!/^-?\d+$/.test(s.amount))throw new r("Invalid force-exit preview metadata.");return u+BigInt(s.amount)},0n),o=-d(t,18);if(o<=0n||o>n||d(g(a.address),a.decimals)<c)throw new r("The force-exit preview exceeds the share balance or returns less than minAmountOut.")}export{w as a,p as b,he as c,ae as d,de as e,we as f,ye as g,be as h,ge as i,ke as j,xe as k};
|
|
1
|
+
import{a as D}from"./43LI5NKJ.js";import{b as Q}from"./IX3GZMTM.js";import{b as x,j as J}from"./TI727O2H.js";import{a as r}from"./XSD5NL7J.js";import{decodeAbiParameters as se,encodeAbiParameters as Z,encodeFunctionData as F,erc20Abi as O,getAddress as g,keccak256 as ee,parseAbi as L,parseAbiParameters as oe,zeroAddress as te}from"viem";var I=10n**18n,$=(1n<<256n)-1n,q=g(J[x].morpho.morpho_blue.address),_=oe("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),w=L(["function adaptersLength() view returns (uint256)","function adapters(uint256) view returns (address)","function liquidityAdapter() view returns (address)","function liquidityData() view returns (bytes)","function forceDeallocatePenalty(address) view returns (uint256)","function performanceFee() view returns (uint256)","function managementFee() view returns (uint256)","function owner() view returns (address)","function curator() view returns (address)","function previewRedeem(uint256) view returns (uint256)","function previewWithdraw(uint256) view returns (uint256)","function forceDeallocate(address adapter,bytes data,uint256 assets,address onBehalf) returns (uint256)","function redeem(uint256 shares,address receiver,address owner) returns (uint256)","function multicall(bytes[] data)"]),v=L(["function parentVault() view returns (address)","function asset() view returns (address)","function morpho() view returns (address)","function marketIdsLength() view returns (uint256)","function marketIds(uint256) view returns (bytes32)","function expectedSupplyAssets(bytes32) view returns (uint256)"]),ne=L(["function idToMarketParams(bytes32) view returns (address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)","function market(bytes32) view returns (uint128 totalSupplyAssets,uint128 totalSupplyShares,uint128 totalBorrowAssets,uint128 totalBorrowShares,uint128 lastUpdate,uint128 fee)"]),M=(e,t)=>e<t?e:t,T=(e,t)=>(e+t-1n)/t;function p(e){if(typeof e!="bigint"||e<0n||e>$)throw new r("Invalid Morpho V2 integer read.");return e}function he(e){if(typeof e!="string")throw new r("Provide maxPenaltyAssets as a USDG base-unit integer string, including 0 for no penalty.");let t=Q(e);if(t>$)throw new r("Penalty limit exceeds uint256.");return t}function h(e){if(typeof e!="string")throw new r("Invalid Morpho V2 address read.");return D(e),g(e)}async function ae(e,t,n){if(await e.getChainId()!==x||n.chainId!==x)throw new r("Vault exit requires chain 4663.");let c=await e.getBlockNumber({cacheTime:0}),a=(m,y,k,S=[])=>e.readContract({address:m,abi:y,functionName:k,args:S,blockNumber:c}),[d,o,i,l,u]=await Promise.all([a(t,w,"adaptersLength"),a(t,w,"liquidityAdapter"),a(t,w,"liquidityData"),a(g(n.address),O,"balanceOf",[t]),a(g(n.address),O,"balanceOf",[q])]);if(p(d)!==1n)throw new r("Force exit requires exactly one verified MorphoMarketV1AdapterV2. This vault needs a separately qualified adapter plan.");let s=h(await a(t,w,"adapters",[0n])),C=h(o);if(C!==te&&C!==s)throw new r("The liquidity adapter is not the supported market adapter.");let[A,N,P,f,B]=await Promise.all([a(s,v,"parentVault"),a(s,v,"asset"),a(s,v,"morpho"),a(s,v,"marketIdsLength"),a(t,w,"forceDeallocatePenalty",[s])]);if(h(A)!==g(t)||h(N)!==g(n.address)||h(P)!==q)throw new r("The adapter does not match this vault and pinned Morpho Blue deployment.");let b=p(f);if(b>64n)throw new r("The adapter market inventory exceeds this reader\u2019s supported size.");let E=p(B);if(E>I/50n)throw new r("The force-deallocation penalty exceeds the documented 2% maximum.");let H;if(C!==te){if(typeof i!="string")throw new r("Invalid liquidity-market data.");let[m]=se(_,i);H=ee(Z(_,[m])).toLowerCase()}let V=await Promise.all(Array.from({length:Number(b)},(m,y)=>a(s,v,"marketIds",[BigInt(y)])));if(V.some(m=>typeof m!="string"||!/^0x[0-9a-f]{64}$/i.test(m))||new Set(V.map(m=>String(m).toLowerCase())).size!==V.length)throw new r("The adapter returned an invalid or duplicate market ID.");let R=await Promise.all(V.map(async m=>{let y=m,[k,S,ie]=await Promise.all([a(q,ne,"idToMarketParams",[y]),a(q,ne,"market",[y]),a(s,v,"expectedSupplyAssets",[y])]);if(!Array.isArray(k)||k.length!==5||!Array.isArray(S)||S.length!==6)throw new r("Invalid Morpho market state.");let z={loanToken:h(k[0]),collateralToken:h(k[1]),oracle:h(k[2]),irm:h(k[3]),lltv:p(k[4])},j=Z(_,[z]);if(ee(j).toLowerCase()!==y.toLowerCase()||z.loanToken!==g(n.address))throw new r("Morpho market identity or loan asset does not match the vault.");let G=p(S[0]),X=p(S[2]);if(X>G)throw new r("Invalid Morpho market liquidity.");let Y=p(ie),K=G-X;return{id:y,adapter:s,data:j,supplied:Y,liquidity:K,capacity:M(Y,K),penalty:E,normal:y.toLowerCase()===H}})),U=p(l),W=p(u),re=U+M(W,R.filter(m=>m.normal).reduce((m,y)=>m+y.capacity,0n));return{vault:t,blockNumber:c,idle:U,blueCash:W,normalCapacity:re,markets:R}}function de(e,t){if(t<=0n||t>$)throw new r("Force exit needs a positive position value.");let n=t>e.normalCapacity?t-e.normalCapacity:0n,c=[],a=e.blueCash-(e.normalCapacity-e.idle);for(let d of e.markets.filter(o=>!o.normal).sort((o,i)=>o.capacity===i.capacity?o.id.localeCompare(i.id):o.capacity>i.capacity?-1:1)){if(n===0n)break;let o=M(d.capacity,a);if(o===0n)continue;let i=s=>s+T(s*d.penalty,I),l=o;i(o)>=n&&(l=T(n*I,I+d.penalty),l>0n&&i(l-1n)>=n&&(l-=1n),l=M(o,l+(T(t,10000n)||1n)));let u=T(l*d.penalty,I);c.push({...d,amount:l,penaltyAssets:u}),a-=l,n=i(l)>=n?0n:n-i(l)}if(n>0n)throw new r("Underlying market liquidity cannot cover this force exit. Request a partial withdrawal or use a separately supported in-kind exit; force deallocation cannot create liquidity.");return{requestedAssets:t,normalCapacity:e.normalCapacity,legs:c,penaltyAssets:c.reduce((d,o)=>d+o.penaltyAssets,0n)}}async function we(e,t,n,c,a,d,o){let i=await ae(t,n,o),l=p(await t.readContract({address:n,abi:O,functionName:"balanceOf",args:[c],blockNumber:i.blockNumber}));if(a<=0n||a>l)throw new r("The fresh share balance cannot cover this exit.");let u=p(await t.readContract({address:n,abi:w,functionName:"previewRedeem",args:[a],blockNumber:i.blockNumber})),s=de(i,u);if(s.penaltyAssets>d)throw new r("The force-exit penalty exceeds maxPenaltyAssets. Inspect a fresh plan before authorizing a larger penalty.");let A=(await Promise.all(s.legs.map(b=>t.readContract({address:n,abi:w,functionName:"previewWithdraw",args:[b.penaltyAssets],blockNumber:i.blockNumber})))).reduce((b,E)=>b+p(E),0n);if(A>=a)throw new r("The penalty would consume the share balance.");let N=a-A,P=s.legs.map(b=>F({abi:w,functionName:"forceDeallocate",args:[b.adapter,b.data,b.amount,c]})),f=F({abi:w,functionName:"redeem",args:[N,c,c]});return P.push(f),{tx:e.unsignedTx({to:n,chainId:x,value:"0",data:s.legs.length?F({abi:w,functionName:"multicall",args:[P]}):f,description:`Exit this wallet\u2019s Morpho V2 shares; estimated penalty ${s.penaltyAssets} ${o.symbol} base units. No approvals.`}),plan:s,penaltyShares:A,redeemShares:N,blockNumber:i.blockNumber}}var ye="This vault lists no lending markets right now, and Morpho's index shows 0% over this window. On these numbers it earns nothing.";async function be(e,t){try{let n=p(await e.readContract({address:t,abi:w,functionName:"adaptersLength"}));if(n>8n)return;let c=await Promise.all(Array.from({length:Number(n)},(d,o)=>e.readContract({address:t,abi:w,functionName:"adapters",args:[BigInt(o)]})));return(await Promise.all(c.map(d=>e.readContract({address:h(d),abi:v,functionName:"marketIdsLength"})))).every(d=>p(d)===0n)}catch{return}}var ce="In-kind exits transfer supported market positions rather than cash; use the project in_kind_exit tool.";function ge(e,t,n,c,a=ce){return{name:t,inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:async(d,o)=>{try{if(D(o),Object.keys(d).length)throw new r("Vault details takes no arguments.");let i=e.clientFor(x);if(await i.getChainId()!==x)throw new r("Vault details requires chain 4663.");let l=await i.readContract({address:n,abi:L(["function asset() view returns (address)"]),functionName:"asset"});if(h(l)!==g(c.address))throw new r("The vault does not use the pinned underlying asset.");let u=await ae(i,n,c),[s,C,A,N]=await Promise.all(["performanceFee","managementFee","owner","curator"].map(f=>i.readContract({address:n,abi:w,functionName:f,blockNumber:u.blockNumber}))),P={...c,address:g(c.address)};return{vault:n,chainId:x,blockNumber:u.blockNumber.toString(),asset:P,owner:h(A),curator:h(N),idleAssets:u.idle.toString(),normalCapacityAssets:u.normalCapacity.toString(),markets:u.markets.map(f=>({marketId:f.id,adapter:f.adapter,suppliedAssets:f.supplied.toString(),marketLiquidityAssets:f.liquidity.toString(),capacityAssets:f.capacity.toString(),liquidityMarket:f.normal,penaltyWad:f.penalty.toString()})),fees:{performanceFeeWad:p(s).toString(),managementFeePerSecondWad:p(C).toString(),scale:I.toString()},apy:null,apyStatus:"This onchain snapshot does not include APY. Use the module analytics tool for indexed historical APY; maxRate is an accrual ceiling.",capacityCaveat:`Snapshot estimates; gates, price accrual, liquidity and penalties can change. Preview the exact action. Force exits may leave share rounding dust. ${a}`}}catch(i){throw new r(e.plainError(i))}}}}function ke(e,t){return`Force-exit estimate: position ${e.requestedAssets} ${t} base units; penalty ${e.penaltyAssets}; net estimate ${e.requestedAssets-e.penaltyAssets}; effective penalty ${T(e.penaltyAssets*10000n,e.requestedAssets)} bps (rounded up). Penalty limit is a local preview check, not a calldata bound. Re-preview before signing and recheck positions for rounding dust.`}function xe(e,t,n,c,a){let d=(i,l)=>e.filter(u=>u.token.chainId===x&&u.token.address.toLowerCase()===i.toLowerCase()).reduce((u,s)=>{if(s.token.decimals!==l||!/^-?\d+$/.test(s.amount))throw new r("Invalid force-exit preview metadata.");return u+BigInt(s.amount)},0n),o=-d(t,18);if(o<=0n||o>n||d(g(a.address),a.decimals)<c)throw new r("The force-exit preview exceeds the share balance or returns less than minAmountOut.")}export{w as a,p as b,he as c,ae as d,de as e,we as f,ye as g,be as h,ge as i,ke as j,xe as k};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as Te,d as $e,e as be,f as ie,i as ke,j as Me}from"./RLI4JDOL.js";import{b as ne,o as we}from"./CAWTAR5V.js";import{a as F,b as ge}from"./43LI5NKJ.js";import{a as Ne}from"./IOYRL6AY.js";import{b as z,d as Ue}from"./IX3GZMTM.js";import{a as y,i as O}from"./FWD4L3CJ.js";import{a,b as me,e as q}from"./XSD5NL7J.js";import{decodeFunctionResult as ve,encodeFunctionData as B,getAddress as m,parseAbi as J,zeroAddress as $}from"viem";var re=-887272,se=887272,G=(1n<<128n)-1n,je="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Ke="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",Qe="0x3067048beee31b25b2f1681f88dac838c8bba36af25bfb2b7cf7473a5847e35f",oe=2000n,Ye=5,Le=64n,Ze=1800n,Be="^v3:(0x[0-9a-fA-F]{40}):(0|[1-9][0-9]{0,19}):(0|[1-9][0-9]{0,19})$",Je=new RegExp(Be),et=Object.freeze({type:"string",pattern:Be,description:"v3 only. Pass the nextCursor of the previous page to read the next 64 owner indices at the same block. Cannot be combined with tokenIds."}),w=Object.freeze({factory:m(O[4663].uniswap.v3_factory.address),positionManager:m(O[4663].uniswap.v3_position_manager.address),swapRouter02:m(O[4663].uniswap.swap_router02.address),permit2:m(O[4663].uniswap.permit2.address),weth:m(O[4663].uniswap.WETH.address),usdg:m(O[4663].uniswap.USDG.address),ethUsdgPool:m(O[4663].oracle.ethUsdgPool.address)}),Pe=Object.freeze({100:1,500:10,3e3:60,1e4:200}),qt=Object.freeze([{fee:100,tickSpacing:1,address:m("0x52e65B17fB6E5BA00Ed806f37Afcd2DaA50271Ca"),token0:w.weth,token1:w.usdg,recordedLiquidity:"1957537485734736219",recordedSqrtPriceX96:"3839219776288481168641554",recordedTick:-198707,feeProtocol:68},{fee:500,tickSpacing:10,address:m("0x69bfaf19c9f377bb306a89aed9f6b07e2c1a8d9a"),token0:w.weth,token1:w.usdg,recordedLiquidity:"714542894544667104",recordedSqrtPriceX96:"3839644024453020182443671",recordedTick:-198705,feeProtocol:68},{fee:3e3,tickSpacing:60,address:m("0xa9188730fe85be88ad499d7d52b099e800fb0334"),token0:w.weth,token1:w.usdg,recordedLiquidity:"310559629687003603",recordedSqrtPriceX96:"3843235825752878635548672",recordedTick:-198686,feeProtocol:102},{fee:1e4,tickSpacing:200,address:m("0x5f009e071f07e92b6c624e83f52f17bbda34680d"),token0:w.weth,token1:w.usdg,recordedLiquidity:"5822966536584155",recordedSqrtPriceX96:"3853297838190389678059735",recordedTick:-198634,feeProtocol:102}]),P=J(["function positions(uint256 tokenId) view returns (uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1)","function ownerOf(uint256 tokenId) view returns (address)","function balanceOf(address owner) view returns (uint256)","function tokenOfOwnerByIndex(address owner, uint256 index) view returns (uint256)","function mint((address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline) params) payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)","function increaseLiquidity((uint256 tokenId, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, uint256 deadline) params) payable returns (uint128 liquidity, uint256 amount0, uint256 amount1)","function decreaseLiquidity((uint256 tokenId, uint128 liquidity, uint256 amount0Min, uint256 amount1Min, uint256 deadline) params) payable returns (uint256 amount0, uint256 amount1)","function collect((uint256 tokenId, address recipient, uint128 amount0Max, uint128 amount1Max) params) payable returns (uint256 amount0, uint256 amount1)","function burn(uint256 tokenId) payable","function createAndInitializePoolIfNecessary(address token0, address token1, uint24 fee, uint160 sqrtPriceX96) payable returns (address pool)"]),Y=J(["function getPool(address tokenA, address tokenB, uint24 fee) view returns (address pool)","function feeAmountTickSpacing(uint24 fee) view returns (int24)"]),he=J(["function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)","function liquidity() view returns (uint128)","function tickSpacing() view returns (int24)","function fee() view returns (uint24)","function token0() view returns (address)","function token1() view returns (address)"]),tt=J(["function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)"]),xe=J(["function decimals() view returns (uint8)","function symbol() view returns (string)","function allowance(address owner, address spender) view returns (uint256)"]),nt="0xd0e30db0";function it(t){if(typeof t!="string")return!1;let e=t.trim().toLowerCase();return e===$||e===je||e==="eth"||e==="native"}function D(t,e){if(it(t))throw new a(`Uniswap v3 requires wrapped ERC-20 WETH (${w.weth}) rather than native ETH in ${e}.`);if(typeof t!="string")throw new a(`${e} must be a valid 20-byte hex address.`);return F(t),m(t)}function ot(t,e,n){let s=Number(t),o=Number(e),i=Number(n);if(!Number.isInteger(i)||i<=0)throw new a("Uniswap v3 tickSpacing must be a positive integer.");if(!Number.isInteger(s)||!Number.isInteger(o))throw new a("Uniswap v3 tickLower and tickUpper must be integers.");if(s<re||o>se||s>se||o<re)throw new a(`Uniswap v3 ticks are out of bounds [${re}, ${se}].`);if(s>=o)throw new a("Uniswap v3 tickLower must be strictly less than tickUpper.");if(s%i!==0||o%i!==0)throw new a(`Uniswap v3 tickLower (${s}) and tickUpper (${o}) must be divisible by tickSpacing (${i}).`);return{tickLower:s,tickUpper:o,tickSpacing:i}}function rt(t,e){let n=t.trim(),s=n.startsWith("-"),o=s||n.startsWith("+")?n.slice(1):n,i=Ue(z(o).toString(),e);return s&&i!=="0"?`-${i}`:i}function st(t){let e=typeof t=="string"?ve({abi:P,functionName:"positions",data:t}):t;return{nonce:BigInt(e[0]),operator:m(String(e[1])),token0:m(String(e[2])),token1:m(String(e[3])),fee:Number(e[4]),tickLower:Number(e[5]),tickUpper:Number(e[6]),liquidity:BigInt(e[7]),feeGrowthInside0LastX128:BigInt(e[8]),feeGrowthInside1LastX128:BigInt(e[9]),tokensOwed0:BigInt(e[10]),tokensOwed1:BigInt(e[11])}}function Re(t,e){if(!t||!Array.isArray(t.logs))return[];let n=e?m(e).toLowerCase():void 0,s=w.positionManager.toLowerCase(),o=new Set;for(let i of t.logs){if(!i||typeof i.address!="string"||i.address.toLowerCase()!==s)continue;let c=Array.isArray(i.topics)?i.topics.map(p=>String(p).toLowerCase()):[],r=c[0];if(r===Ke&&c.length>=4){let d=`0x${c[2].slice(-40)}`;if(!n||d===n){let u=BigInt(c[3]).toString();u!=="0"&&o.add(u)}}else if(r===Qe&&c.length>=2&&!n){let p=BigInt(c[1]).toString();p!=="0"&&o.add(p)}}return[...o]}function Ut(t){let e=n=>typeof n=="bigint"?n:z(n);return B({abi:tt,functionName:"exactInputSingle",args:[{tokenIn:m(t.tokenIn),tokenOut:m(t.tokenOut),fee:t.fee,recipient:m(t.recipient),amountIn:e(t.amountIn),amountOutMinimum:e(t.amountOutMinimum),sqrtPriceLimitX96:t.sqrtPriceLimitX96!==void 0?e(t.sqrtPriceLimitX96):0n}]})}var Ee=1n<<96n;function _e(t){let e=Math.abs(t),n=(e&1)!==0?0xfffcb933bd6fad37aa2d162d1a594001n:0x100000000000000000000000000000000n;return(e&2)!==0&&(n=n*0xfff97272373d413259a46990580e213an>>128n),(e&4)!==0&&(n=n*0xfff2e50f5f656932ef12357cf3c7fdccn>>128n),(e&8)!==0&&(n=n*0xffe5caca7e10e4e61c3624eaa0941cd0n>>128n),(e&16)!==0&&(n=n*0xffcb9843d60f6159c9db58835c926644n>>128n),(e&32)!==0&&(n=n*0xff973b41fa98c081472e6896dfb254c0n>>128n),(e&64)!==0&&(n=n*0xff2ea16466c96a3843ec78b326b52861n>>128n),(e&128)!==0&&(n=n*0xfe5dee046a99a2a811c461f1969c3053n>>128n),(e&256)!==0&&(n=n*0xfcbe86c7900a88aedcffc83b479aa3a4n>>128n),(e&512)!==0&&(n=n*0xf987a7253ac413176f2b074cf7815e54n>>128n),(e&1024)!==0&&(n=n*0xf3392b0822b70005940c7a398e4b70f3n>>128n),(e&2048)!==0&&(n=n*0xe7159475a2c29b7443b29c7fa6e889d9n>>128n),(e&4096)!==0&&(n=n*0xd097f3bdfd2022b8845ad8f792aa5825n>>128n),(e&8192)!==0&&(n=n*0xa9f746462d870fdf8a65dc1f90e061e5n>>128n),(e&16384)!==0&&(n=n*0x70d869a156d2a1b890bb3df62baf32f7n>>128n),(e&32768)!==0&&(n=n*0x31be135f97d08fd981231505542fcfa6n>>128n),(e&65536)!==0&&(n=n*0x9aa508b5b7a84e1c677de54f3e99bc9n>>128n),(e&131072)!==0&&(n=n*0x5d6af8dedb81196699c329225ee604n>>128n),(e&262144)!==0&&(n=n*0x2216e584f5fa1ea926041bedfe98n>>128n),(e&524288)!==0&&(n=n*0x48a170391f7dc42444e8fa2n>>128n),t>0&&(n=((1n<<256n)-1n)/n),(n>>32n)+(n%(1n<<32n)===0n?0n:1n)}function at(t,e,n,s){if(s<=0n)return{amount0:0n,amount1:0n};let[o,i]=e<n?[e,n]:[n,e];if(t<=o)return{amount0:(s<<96n)*(i-o)/i/o,amount1:0n};if(t<i){let r=(s<<96n)*(i-t)/i/t,p=s*(t-o)/Ee;return{amount0:r,amount1:p}}return{amount0:0n,amount1:s*(i-o)/Ee}}async function M(t,e,n,s){let o=m(e),i,c;if(n===y&&o===w.weth?(i=18,c="WETH"):n===y&&o===w.usdg&&(i=6,c="USDG"),i===void 0){let r=await t.readContract({address:o,abi:xe,functionName:"decimals"});i=Number(r)}if(c===void 0)try{let r=await t.readContract({address:o,abi:xe,functionName:"symbol"});if(typeof r!="string"||!r.trim())throw new a("Token symbol is unavailable.");c=Me(r.trim(),o)}catch(r){throw new a(`Could not read token metadata. ${q(r)}`)}if(!Number.isInteger(i)||i<0||i>255)throw new a("Token decimals are invalid.");if(s!=null){let r=Number(s);if(!Number.isInteger(r)||r!==i)throw new a(`Token ${o} on chain ${n} has ${i} decimals, not ${String(s)}.`)}return{address:o,symbol:c,decimals:i,chainId:n}}async function ct(t){try{if(!t.getBlock)throw new a("Block timestamps are unavailable.");let e=await t.getBlock();if(typeof e.timestamp!="bigint")throw new a("Invalid block timestamp.");return e.timestamp}catch(e){throw new a(`Could not read the current block timestamp. ${q(e)}`)}}function ee(t,e){if(typeof t=="bigint"){if(t<0n)throw new a(`${e} must be a non-negative integer.`);return t}if(typeof t=="number"){if(!Number.isSafeInteger(t)||t<0)throw new a(`${e} must be a non-negative integer.`);return BigInt(t)}if(typeof t=="string")return z(t);throw new a(`${e} must be a non-negative integer.`)}async function Oe(t,e){let n=await ct(t);if(e==null)return n+Ze;let s=ee(e,"deadline");if(s<=n)throw new a(`Uniswap v3 deadline (${s.toString()}) has expired at timestamp ${n.toString()}.`);return s}function W(t,e){if(typeof t!="string"||!/^\d+$/.test(t))throw new a(`${e} must be a non-negative integer string in base units.`);return z(t)}function De(t){let e=t.slippageBps??ne;if(typeof e!="number")throw new a("Slippage must be an integer from 0 to 9999 bps.");return we("0",e),e}function ae(t,e,n,s){let o=t===void 0?z(we(e.toString(),n)):W(t,s);if(o<=1n)throw new a(`${s} must exceed 1 base unit; the simulated amount may be too small.`);return o}function H(t,e){return ge({to:w.positionManager,data:t,value:"0",chainId:y,description:e})}async function Z(t,e,n){try{if(!t.request)throw new a("Sequential transaction simulation is unavailable.");let o=await t.request({method:"eth_simulateV1",params:[{blockStateCalls:[{calls:e.map(i=>({from:n,gas:`0x${Ne.toString(16)}`,to:i.to,data:i.data,value:`0x${BigInt(i.value).toString(16)}`}))}],validation:!1,traceTransfers:!0},"latest"]},{retryCount:0});if(!Array.isArray(o)||o.length!==1||!Array.isArray(o[0]?.calls)||o[0].calls.length!==e.length)throw new a("Unexpected batch simulation response.");return o[0].calls.map((i,c)=>{if(i.status!=="0x1"||i.error||typeof i.returnData!="string"||!/^0x([a-fA-F0-9]{2})*$/.test(i.returnData))throw new a(`Simulation call ${c+1} failed. ${q(i.error)}`);return i.returnData})}catch(s){throw new a(`Uniswap v3 simulation failed. ${q(s)}`)}}function ce(t,e){try{return ve({abi:P,functionName:t,data:e})}catch{throw new a(`Uniswap v3 ${t} simulation returned invalid amounts.`)}}function Ve(t,e,n){if(t.initialPrice!==void 0&&t.sqrtPriceX96!==void 0)throw new a("Provide initialPrice or sqrtPriceX96, not both.");if(t.sqrtPriceX96!==void 0){if(typeof t.sqrtPriceX96!="string"||!/^\d+$/.test(t.sqrtPriceX96))throw new a("sqrtPriceX96 must be a non-negative integer string.");return $e(BigInt(t.sqrtPriceX96))}if(t.initialPrice===void 0)throw new a("A new pool needs initialPrice (token1 per 1 token0, human units) or sqrtPriceX96.");return Te(t.initialPrice,e,n)}async function Xe(t,e,n,s){let o=[];for(let i of Object.keys(Pe).map(Number)){if(i===s)continue;let c=m(String(await t.readContract({address:w.factory,abi:Y,functionName:"getPool",args:[e,n,i]})));if(c===$||BigInt(await t.readContract({address:c,abi:he,functionName:"liquidity"}))===0n)continue;let p=await t.readContract({address:c,abi:he,functionName:"slot0"});o.push({label:`v3 fee ${i} pool ${c}`,sqrtPriceX96:BigInt(p[0])})}return o}function j(t,e={}){if(e.chainId!==void 0&&Number(e.chainId)!==y)throw new a(`Uniswap v3 is only supported on Robinhood Chain (${y}).`);if(e.version!==void 0&&e.version!=="v3")throw new a(`Uniswap v3 handler received unsupported version "${String(e.version)}".`);let n=t.clientFor(y);return{...n,readContract:async s=>{try{return await n.readContract(s)}catch(o){throw new a(`Could not read Uniswap v3 ${s.functionName}. ${q(o)}`,{cause:o})}}}}async function Ie(t,e,n){let s;try{s=await t.readContract({address:w.positionManager,abi:P,functionName:"ownerOf",args:[e]})}catch(c){throw new a(`Could not verify owner of Uniswap v3 position #${e}. ${q(c)}`)}let o=m(String(s)),i=m(n);if(o!==i)throw new a(`Wallet ${i} is not the owner of Uniswap v3 position #${e.toString()} (owned by ${o}).`);return o}async function de(t,e){let n=await t.readContract({address:w.positionManager,abi:P,functionName:"positions",args:[e]});return st(n)}function Se(t,e){if(!Array.isArray(e.changes)||!e.changes.length)return t;let n=e.changes.map(s=>`${rt(s.amount,s.token.decimals)} ${s.token.symbol}`);return`${t} (${n.join(", ")})`}async function dt(t,e,n){F(n);let s=m(n),o=j(t,e),i=await Oe(o,e.deadline),c=De(e),r=e.tokenId===void 0?void 0:ee(e.tokenId,"tokenId"),p;if(r!==void 0){if(r<=0n)throw new a("Uniswap v3 tokenId must be a positive integer.");await Ie(o,r,s),p=await de(o,r)}let d=p?.token0??D(e.token0,"token0"),u=p?.token1??D(e.token1,"token1");if(BigInt(d)>=BigInt(u))throw new a("Uniswap v3 requires distinct sorted token addresses.");let g=p?.fee??Number(e.fee??100),f=Pe[g];if(!f)throw new a("Unsupported Uniswap v3 fee tier.");let b=m(String(await o.readContract({address:w.factory,abi:Y,functionName:"getPool",args:[d,u,g]}))),l=e.initialPrice!==void 0||e.sqrtPriceX96!==void 0;if(b===$&&!l)throw new a("No Uniswap v3 pool exists for these tokens and fee tier. To create it and add the first liquidity in one tool call with separately confirmed transactions, add initialPrice (token1 per 1 token0, human units) to this call; to create it without liquidity use uniswap_create_pool.");if(b!==$&&l)throw new a(`The Uniswap v3 pool already exists at ${b}; remove initialPrice/sqrtPriceX96 to add liquidity at its current price.`);if(r!==void 0&&l)throw new a("initialPrice cannot be combined with tokenId.");if(e.fullRange!==void 0&&typeof e.fullRange!="boolean")throw new a("fullRange must be a boolean.");if(e.fullRange===!0&&(e.tickLower!==void 0||e.tickUpper!==void 0||p))throw new a("Use fullRange only for a new position, without explicit ticks. Existing position ticks cannot change.");let{tickLower:k,tickUpper:U,tickSpacing:A}=ot(p?.tickLower??(e.fullRange===!0?Math.ceil(re/f)*f:e.tickLower),p?.tickUpper??(e.fullRange===!0?Math.floor(se/f)*f:e.tickUpper),f),v=await M(o,d,y,e.token0Decimals),h=await M(o,u,y,e.token1Decimals),C;if(b===$){let T=Ve(e,v.decimals,h.decimals),_=ke(T,await Xe(o,d,u,g),e.acceptPriceDeviation===!0,v.decimals,h.decimals);C={sqrtPriceX96:T,note:_}}let I=W(e.amount0Desired,"amount0Desired"),S=W(e.amount1Desired,"amount1Desired");if(I===0n&&S===0n)throw new a("Liquidity addition requires a positive desired amount.");let x=e.recipient===void 0?s:D(e.recipient,"recipient");if(x!==s)throw new a("Uniswap recipient must be the signing wallet.");if(e.wrapNative===!0&&d!==w.weth&&u!==w.weth)throw new a("Wrapping requires a positive WETH desired amount.");let V=await Promise.all([d,u].map(async T=>BigInt(await o.readContract({address:T,abi:xe,functionName:"allowance",args:[s,w.positionManager]})))),X=(T,_)=>{let pe=[];if(e.wrapNative===!0){let Q=d===w.weth?T:_;Q>0n&&pe.push(ge({to:w.weth,data:nt,value:Q.toString(),chainId:y,description:"Wrap ETH into WETH."}))}for(let[Q,Ge]of[d,u].entries()){let fe=Q===0?T:_;fe>0n&&V[Q]<fe&&pe.push(t.approval(Ge,w.positionManager,fe.toString(),y))}return pe},L=r===void 0?"mint":"increaseLiquidity",R=(T,_)=>H(r===void 0?B({abi:P,functionName:"mint",args:[{token0:d,token1:u,fee:g,tickLower:k,tickUpper:U,amount0Desired:I,amount1Desired:S,amount0Min:T,amount1Min:_,recipient:x,deadline:i}]}):B({abi:P,functionName:"increaseLiquidity",args:[{tokenId:r,amount0Desired:I,amount1Desired:S,amount0Min:T,amount1Min:_,deadline:i}]}),`${L==="mint"?"Mint":"Increase"} Uniswap v3 ${v.symbol}/${h.symbol} liquidity.`),E=C&&H(B({abi:P,functionName:"createAndInitializePoolIfNecessary",args:[d,u,g,C.sqrtPriceX96]}),`Create and initialize the Uniswap v3 ${v.symbol}/${h.symbol} fee ${g} pool at ${ie(C.sqrtPriceX96,v.decimals,h.decimals)} ${h.symbol} per ${v.symbol}.`),K=E?[E]:[],Ae=await Z(o,[...K,...X(I,S),R(0n,0n)],s),N=ce(L,Ae[Ae.length-1]),We=N[N.length-2],ze=N[N.length-1];if(We>I||ze>S)throw new a("Simulated liquidity spend exceeds the desired amounts.");let te=[...K,...X(I,S)],ue=ae(e.amount0Min,N[N.length-2],c,"amount0Min"),le=ae(e.amount1Min,N[N.length-1],c,"amount1Min");if(ue>I||le>S)throw new a("Uniswap v3 minimum amount cannot exceed desired amount.");let Ce=R(ue,le);te.push(Ce);for(let[T,_]of[d,u].entries())(T===0?I:S)>0n&&te.push(t.approval(_,w.positionManager,"0",y));let qe=await t.preview(te,s);return{txs:te,preview:qe,summary:Se(Ce.description,qe),details:{version:"v3",action:L,...r===void 0?{}:{tokenId:r.toString()},pool:b===$?null:b,fee:g,tickSpacing:A,tickLower:k,tickUpper:U,token0:v,token1:h,amount0Desired:I.toString(),amount1Desired:S.toString(),amount0Min:ue.toString(),amount1Min:le.toString(),deadline:i.toString(),recipient:x,expectedAmount0:N[N.length-2].toString(),expectedAmount1:N[N.length-1].toString(),...C?{poolCreated:!0,sqrtPriceX96:C.sqrtPriceX96.toString(),initialPrice:ie(C.sqrtPriceX96,v.decimals,h.decimals),initialTick:be(C.sqrtPriceX96),priceCheck:C.note}:{}}}}async function ut(t,e,n){F(n);let s=m(n),o=j(t,e),i=D(e.token0,"token0"),c=D(e.token1,"token1");if(BigInt(i)>=BigInt(c))throw new a(`Uniswap v3 requires sorted token addresses (token0 < token1). Use token0=${BigInt(i)<BigInt(c)?i:c}, token1=${BigInt(i)<BigInt(c)?c:i}; initialPrice is token1 per 1 token0 in that order.`);let r=Number(e.fee),p=Pe[r];if(!p){let h=Number(await o.readContract({address:w.factory,abi:Y,functionName:"feeAmountTickSpacing",args:[r]}));if(!Number.isInteger(r)||h<=0)throw new a("Unsupported Uniswap v3 fee tier. Enabled tiers: 100, 500, 3000, 10000.");p=h}let d=m(String(await o.readContract({address:w.factory,abi:Y,functionName:"getPool",args:[i,c,r]})));if(d!==$)throw new a(`The Uniswap v3 pool already exists at ${d}. Use uniswap_add to provide liquidity.`);let u=await M(o,i,y,e.token0Decimals),g=await M(o,c,y,e.token1Decimals),f=Ve(e,u.decimals,g.decimals),b=ke(f,await Xe(o,i,c,r),e.acceptPriceDeviation===!0,u.decimals,g.decimals),l=ie(f,u.decimals,g.decimals),k=[H(B({abi:P,functionName:"createAndInitializePoolIfNecessary",args:[i,c,r,f]}),`Create and initialize the Uniswap v3 ${u.symbol}/${g.symbol} fee ${r} pool at ${l} ${g.symbol} per ${u.symbol}.`)],U=await Z(o,k,s),A;try{A=m(String(ve({abi:P,functionName:"createAndInitializePoolIfNecessary",data:U[0]})))}catch{throw new a("Uniswap v3 pool creation simulation returned an invalid pool address.")}if(A===$)throw new a("Uniswap v3 pool creation simulation returned no pool.");let v=await t.preview(k,s);return{txs:k,preview:v,summary:`${k[0].description} The pool starts empty: nothing trades until liquidity is added with uniswap_add.`,details:{version:"v3",action:"createPool",pool:A,fee:r,tickSpacing:p,token0:u,token1:g,sqrtPriceX96:f.toString(),initialPrice:l,initialTick:be(f),priceCheck:b}}}async function lt(t,e,n){F(n);let s=m(n),o=j(t,e),i=ee(e.tokenId,"tokenId");if(i<=0n)throw new a("Uniswap v3 tokenId must be a positive integer.");await Ie(o,i,s);let c=await de(o,i),r=await M(o,c.token0,y),p=await M(o,c.token1,y),d=e.recipient===void 0?s:D(e.recipient,"recipient");if(d!==s)throw new a("Uniswap recipient must be the signing wallet.");let u=e.amount0Max===void 0?G:W(e.amount0Max,"amount0Max"),g=e.amount1Max===void 0?G:W(e.amount1Max,"amount1Max");if(u===0n&&g===0n||u>G||g>G)throw new a("Collect requires a positive amountMax within uint128.");let f=[H(B({abi:P,functionName:"collect",args:[{tokenId:i,recipient:d,amount0Max:u,amount1Max:g}]}),`Collect Uniswap v3 fees from position #${i}.`)],b=ce("collect",(await Z(o,f,s))[0]),l=await t.preview(f,s);return{txs:f,preview:l,summary:Se(f[0].description,l),details:{version:"v3",action:"collect",tokenId:i.toString(),recipient:d,token0:r,token1:p,amount0Max:u.toString(),amount1Max:g.toString(),expectedAmount0:b[0].toString(),expectedAmount1:b[1].toString()}}}async function pt(t,e,n){F(n);let s=m(n),o=j(t,e),i=ee(e.tokenId,"tokenId");if(i<=0n)throw new a("Uniswap v3 tokenId must be a positive integer.");await Ie(o,i,s);let c=await de(o,i),r=c.liquidity===0n&&e.burn===!0;if(c.liquidity<=0n&&!r)throw new a("Position has zero active liquidity to remove.");if(e.liquidity===void 0&&!r)throw new a('Provide a liquidity amount or explicitly choose liquidity "all" for a full exit.');let p=e.liquidity==="all"||e.liquidity===void 0?c.liquidity:W(e.liquidity,"liquidity");if(p<=0n&&!r)throw new a("Liquidity to remove must be positive.");if(p>c.liquidity)throw new a("Requested liquidity exceeds position liquidity.");let d=await Oe(o,e.deadline),u=De(e),g=await M(o,c.token0,y),f=await M(o,c.token1,y),b=e.recipient===void 0?s:D(e.recipient,"recipient");if(b!==s)throw new a("Uniswap recipient must be the signing wallet.");let l=(R,E)=>H(B({abi:P,functionName:"decreaseLiquidity",args:[{tokenId:i,liquidity:p,amount0Min:R,amount1Min:E,deadline:d}]}),`Decrease ${p} liquidity on Uniswap v3 position #${i}.`),k=r?[0n,0n]:ce("decreaseLiquidity",(await Z(o,[l(0n,0n)],s))[0]),U=(R,E)=>{if(R!==void 0&&W(R,E)!==0n)throw new a(`${E} must be zero for an empty position burn.`);return 0n},A=r?U(e.amount0Min,"amount0Min"):ae(e.amount0Min,k[0],u,"amount0Min"),v=r?U(e.amount1Min,"amount1Min"):ae(e.amount1Min,k[1],u,"amount1Min"),h=r?[]:[l(A,v)],C=h.length,I=!r||c.tokensOwed0>0n||c.tokensOwed1>0n;I&&h.push(H(B({abi:P,functionName:"collect",args:[{tokenId:i,recipient:b,amount0Max:G,amount1Max:G}]}),`Collect principal and fees from Uniswap v3 position #${i}.`));let S=p===c.liquidity,x=S&&e.burn===!0;x&&h.push(H(B({abi:P,functionName:"burn",args:[i]}),`Burn empty Uniswap v3 position #${i}.`));let V=await Z(o,h,s),X=I?ce("collect",V[C]):[0n,0n],L=await t.preview(h,s);return{txs:h,preview:L,summary:Se(`Remove Uniswap v3 liquidity from position #${i}${x?`; burns position #${i} at ${w.positionManager}`:""}`,L),details:{version:"v3",action:"remove",tokenId:i.toString(),recipient:b,token0:g,token1:f,liquidityRemoved:p.toString(),amount0Min:A.toString(),amount1Min:v.toString(),deadline:d.toString(),expectedAmount0:X[0].toString(),expectedAmount1:X[1].toString(),fullExit:S,burned:x}}}function ft(t,e){let n=typeof t=="string"?Je.exec(t):null;if(!n)throw new a('cursor is not a Uniswap v3 position cursor. Pass the nextCursor exactly as a previous uniswap_list_positions {"version":"v3"} page returned it.');if(m(n[1])!==e)throw new a("This cursor was issued for a different wallet. Start again without a cursor to page this wallet.");return{block:BigInt(n[2]),next:BigInt(n[3])}}function mt(t,e,n){return`v3:${t.toLowerCase()}:${e}:${n}`}function gt(t,e){return{...t,readContract:n=>t.readContract({...n,blockNumber:e})}}var ye=t=>me(t,3,-32601,-32004);async function wt(t,e,n={}){let s=m(e),o=new Set;if(Array.isArray(n.tokenIds))for(let d of n.tokenIds){let u=ee(d,"tokenId");u>0n&&o.add(u.toString())}if(Array.isArray(n.receipts))for(let d of n.receipts)for(let u of Re(d,s))o.add(u);if(Array.isArray(n.tokenIds)&&n.tokenIds.length>0)return[...o].map(d=>BigInt(d)).sort((d,u)=>d<u?-1:d>u?1:0);let i=n.cursor,c=()=>new a("This Uniswap v3 position manager cannot enumerate NFTs by owner, so there are no pages to continue. Pass tokenIds to check specific positions."),r=!1,p=!1;try{let d;try{d=BigInt(await t.readContract({address:w.positionManager,abi:P,functionName:"balanceOf",args:[s]}))}catch(l){throw ye(l)||!i?l:new a(`Could not read this wallet's Uniswap v3 holdings at the cursor's snapshot block ${i.block}; the node may no longer serve it. Start again without a cursor. ${q(l)}`)}let u=i?.next??0n;if(u>d)throw new a(`This cursor starts at owner index ${u}, but the wallet held ${d} Uniswap v3 NFTs at block ${i?.block}. Start again without a cursor.`);let g=d-u>Le?u+Le:d,f=[],b=!0;for(let l=u;l<g;l++)try{f.push(BigInt(await t.readContract({address:w.positionManager,abi:P,functionName:"tokenOfOwnerByIndex",args:[s,l]})))}catch(k){if(!ye(k))throw k;b=!1;break}if(b){r=!0,p=u===0n&&g===d;for(let k of f)k>0n&&o.add(k.toString());let l=n.blockNumber;n.onPage?.({balance:d,from:u,to:g,blockNumber:l,...g<d&&l!==void 0?{nextCursor:mt(s,l,g)}:{}})}}catch(d){if(!ye(d))throw d}if(i&&!r)throw c();if((!r||p)&&typeof t.getLogs=="function"&&typeof t.getBlockNumber=="function")try{let d=n.toBlock??await t.getBlockNumber(),u=n.maxChunks??Ye,g=n.fromBlock??(d>oe*BigInt(u)?d-oe*BigInt(u)+1n:0n),f=d,b=0;for(;f>=g&&b<u;){let l=f>=oe-1n?f-(oe-1n):0n,k=l<g?g:l,U=await t.getLogs({address:w.positionManager,fromBlock:k,toBlock:f});for(let A of Re({logs:U},s))o.add(A);if(b+=1,k===0n||k<=g)break;f=k-1n}}catch(d){throw new a(`Could not discover Uniswap v3 positions from logs. ${q(d)}`)}else if(!r&&n.tokenIds===void 0&&n.receipts===void 0)throw new a("Uniswap v3 position discovery is unavailable; supply candidate token IDs or receipts.");return[...o].map(d=>BigInt(d)).sort((d,u)=>d<u?-1:d>u?1:0)}async function Fe(t,e,n={}){F(e);let s=m(e),o=j(t),i=Array.isArray(n.tokenIds)&&n.tokenIds.length>0,c=Array.isArray(n.receipts)&&n.receipts.length>0;if(n.cursor!==void 0&&(i||c))throw new a(`${i?"tokenIds":"receipts"} and cursor cannot be combined: ${i?"tokenIds":"receipts"} inspects exactly those NFTs and has no pages. Send one or the other.`);let r=n.cursor===void 0?void 0:ft(n.cursor,s),p=o,d;if(!i){let f;if(typeof o.getBlockNumber=="function")try{f=await o.getBlockNumber()}catch(b){throw new a(`Could not read the latest block for the Uniswap v3 listing. ${q(b)}`)}if(r&&f!==void 0&&r.block>f)throw new a(`This cursor is from block ${r.block}, ahead of the chain's latest block ${f}. Start again without a cursor.`);d=r?.block??f,d!==void 0&&(p=gt(o,d))}let u=await wt(p,s,{...n,cursor:r,blockNumber:d}),g=[];for(let f of u){let b;try{let x=await p.readContract({address:w.positionManager,abi:P,functionName:"ownerOf",args:[f]});b=m(String(x))}catch(x){if(me(x,3))continue;throw new a(`Could not verify owner of position #${f}. ${q(x)}`)}if(b!==s)continue;let l;try{l=await de(p,f)}catch(x){throw new a(`Could not read position #${f}. ${q(x)}`)}if(l.liquidity===0n&&l.tokensOwed0===0n&&l.tokensOwed1===0n&&!n.includeEmpty)continue;let U=await M(p,l.token0,y),A=await M(p,l.token1,y),v=0n,h=0n;if(l.liquidity>0n)try{let x=await p.readContract({address:w.factory,abi:Y,functionName:"getPool",args:[l.token0,l.token1,l.fee]}),V=m(String(x));if(V===$)throw new a("Position pool was not found.");if(V!==$){let X=await p.readContract({address:V,abi:he,functionName:"slot0"}),L=BigInt(X[0]);if(L<=0n)throw new a("Position pool has no initialized price.");let R=_e(l.tickLower),E=_e(l.tickUpper),K=at(L,R,E,l.liquidity);v=K.amount0,h=K.amount1}}catch(x){throw new a(`Could not value Uniswap v3 position #${f}. ${q(x)}`)}let C=v+l.tokensOwed0,I=h+l.tokensOwed1,S=[{token:U,amount:C.toString()},{token:A,amount:I.toString()}];g.push({module:"uniswap",id:`uniswap:v3:${f.toString()}`,chainId:y,assets:S,description:`Uniswap v3 LP position #${f.toString()} (${U.symbol}/${A.symbol} fee ${l.fee} ticks [${l.tickLower}, ${l.tickUpper}] liquidity ${l.liquidity.toString()})`})}return g}function bt(t){let e=t.nextCursor?`Pass cursor "${t.nextCursor}" to read the next page, or tokenIds to check specific positions.`:"Pass tokenIds to check specific positions.";return t.from===0n?`This wallet holds ${t.balance} Uniswap v3 position NFTs and only the first ${t.to} were checked, so later positions are not listed. ${e}`:`This page checked owner indices ${t.from}-${t.to-1n} of ${t.balance} Uniswap v3 position NFTs, so later positions are not listed. ${e}`}async function kt(t,e,n){j(t,e);let s=e.wallet!==void 0?D(e.wallet,"wallet"):m(n),o=Array.isArray(e.tokenIds)?e.tokenIds:void 0,i=Array.isArray(e.receipts)?e.receipts:void 0,c=e.includeZero===!0||e.includeEmpty===!0,r,p=await Fe(t,s,{tokenIds:o,receipts:i,includeEmpty:c,cursor:e.cursor,onPage:u=>{r=u}}),d=r!==void 0&&r.to<r.balance;return{positions:p,...r?.nextCursor?{nextCursor:r.nextCursor}:{},details:{version:"v3",wallet:s,count:p.length,positionManager:w.positionManager,...r?{balance:Number(r.balance),from:Number(r.from),to:Number(r.to),examined:Number(r.to-r.from),...r.blockNumber!==void 0?{blockNumber:r.blockNumber.toString()}:{}}:{},...r&&d?{truncated:!0,incomplete:!0,note:bt(r)}:{}}}}function yt(t){return[{name:"uniswap_add",inputSchema:{type:"object",description:"Mint a new Uniswap v3 concentrated liquidity position or increase liquidity on an existing v3 NFT position on Robinhood Chain (4663).",properties:{version:{description:"Uniswap v3 concentrated-liquidity version.",type:"string",enum:["v3"],default:"v3"},tokenId:{type:"string",description:'Optional existing v3 position NFT identifier to increase, as a decimal string; omit to mint. Example: "1".'},token0:{type:"string",description:"Sorted ERC-20 token0 address (e.g. WETH)."},token1:{type:"string",description:"Sorted ERC-20 token1 address (e.g. USDG)."},fee:{description:"Pool fee in pips, hundredths of a basis point (3000 = 0.3%; 950000 = 95%).",type:"integer",enum:[100,500,3e3,1e4],default:100},fullRange:{type:"boolean",description:"For a new v3 position, use the widest ticks aligned to the pool fee tier; omit explicit ticks."},tickLower:{type:"integer",description:"Lower tick boundary divisible by tickSpacing."},tickUpper:{type:"integer",description:"Upper tick boundary divisible by tickSpacing."},amount0Desired:{type:"string",description:'Desired amount of token0 in base units; use token0 decimals. Example: "1000000" = 1 token0 at 6 decimals.'},amount1Desired:{type:"string",description:'Desired amount of token1 in base units; use token1 decimals. Example: "1000000" = 1 token1 at 6 decimals.'},amount0Min:{type:"string",description:'Minimum amount of token0 in base units; use token0 decimals. Example: "1000000" = 1 token0 at 6 decimals.'},amount1Min:{type:"string",description:'Minimum amount of token1 in base units; use token1 decimals. Example: "1000000" = 1 token1 at 6 decimals.'},slippageBps:{description:"Slippage tolerance in basis points (50 = 0.5%).",type:"integer",minimum:0,maximum:9999,default:ne},deadline:{type:"integer",description:"Transaction deadline in Unix seconds, after the current block timestamp. Example: 1800000000."},wrapNative:{type:"boolean",description:"Optional: wrap native ETH into WETH before minting."},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."}}},execute:(c,r)=>dt(t,c,r)},{name:"uniswap_collect",inputSchema:{type:"object",description:"Collect accrued Uniswap v3 LP fees for an owned NonfungiblePositionManager NFT.",properties:{version:{description:"Uniswap v3 concentrated-liquidity version.",type:"string",enum:["v3"],default:"v3"},tokenId:{type:"string",description:'Identifier of the position NFT, as a decimal string. Example: "1".'},recipient:{type:"string",description:"Optional fee recipient; must be the signing wallet."},amount0Max:{type:"string",description:'Maximum amount of token0 in base units; use token0 decimals. Example: "1000000" = 1 token0 at 6 decimals.'},amount1Max:{type:"string",description:'Maximum amount of token1 in base units; use token1 decimals. Example: "1000000" = 1 token1 at 6 decimals.'}},required:["tokenId"]},execute:(c,r)=>lt(t,c,r)},{name:"uniswap_remove",inputSchema:{type:"object",description:"Decrease liquidity on an owned Uniswap v3 NFT position, collect principal and fees, and optionally burn the empty NFT.",properties:{version:{description:"Uniswap v3 concentrated-liquidity version.",type:"string",enum:["v3"],default:"v3"},tokenId:{type:"string",description:'Identifier of the position NFT, as a decimal string. Example: "1".'},liquidity:{type:"string",description:'Liquidity in protocol base units, or "all" for a full exit where supported; not a token amount. Example: "1000" = 1000 liquidity units.'},amount0Min:{type:"string",description:'Minimum amount of token0 in base units; use token0 decimals. Example: "1000000" = 1 token0 at 6 decimals.'},amount1Min:{type:"string",description:'Minimum amount of token1 in base units; use token1 decimals. Example: "1000000" = 1 token1 at 6 decimals.'},slippageBps:{description:"Slippage tolerance in basis points (50 = 0.5%).",type:"integer",minimum:0,maximum:9999,default:ne},deadline:{type:"integer",description:"Transaction deadline in Unix seconds, after the current block timestamp. Example: 1800000000."},burn:{type:"boolean",description:"Whether to burn the NFT after removing 100% of liquidity, or burn an already-empty position."}},required:["tokenId"]},execute:(c,r)=>pt(t,c,r)},{name:"uniswap_list_positions",inputSchema:{type:"object",description:"List active Uniswap v3 LP positions owned by the wallet, 64 owner indices per page at one pinned block; follow nextCursor for more. Falls back to a bounded Transfer-log scan for managers that cannot enumerate by owner.",properties:{version:{description:"Uniswap v3 concentrated-liquidity version.",type:"string",enum:["v3"],default:"v3"},wallet:{type:"string",description:"Optional wallet address override."},tokenIds:{type:"array",items:{type:"string"},description:'Optional v3 NFT identifiers as decimal strings, e.g. ["1", "2"]. Inspects exactly these NFTs without paging.'},cursor:et}},execute:(c,r)=>kt(t,c,r)},{name:"uniswap_create_pool",inputSchema:{type:"object",description:"Create and initialize an empty Uniswap v3 pool on Robinhood Chain (4663). Add liquidity afterwards with uniswap_add.",properties:{version:{description:"Uniswap v3 concentrated-liquidity version.",type:"string",enum:["v3"],default:"v3"},token0:{type:"string",description:"Sorted ERC-20 token0 address (WETH, not native ETH)."},token1:{type:"string",description:"Sorted ERC-20 token1 address."},fee:{description:"Pool fee in pips, hundredths of a basis point (3000 = 0.3%; 950000 = 95%).",type:"integer",enum:[100,500,3e3,1e4]},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."}},required:["token0","token1","fee"]},execute:(c,r)=>ut(t,c,r)}]}var He=t=>({tools:yt(t),positions:async e=>{let n,s=await Fe(t,e,{onPage:o=>{o.to>=o.balance||(n={module:"uniswap",id:"uniswap-v3-discovery-truncated",chainId:y,assets:[],incomplete:!0,description:`This wallet holds ${o.balance} Uniswap v3 position NFTs and only the first ${o.to} were checked, so later positions may be missing. Pass tokenIds to uniswap_list_positions to check the others, or page through them with uniswap_list_positions {"version":"v3"} and each nextCursor.`})}});return n?[...s,n]:s}}),Nt=He,Tt=He;export{re as a,se as b,G as c,et as d,w as e,Pe as f,qt as g,P as h,Y as i,he as j,tt as k,ot as l,rt as m,st as n,Re as o,Ut as p,Ve as q,dt as r,ut as s,lt as t,pt as u,Fe as v,kt as w,yt as x,He as y,Nt as z,Tt as A};
|
|
1
|
+
import{c as Te,d as $e,e as be,f as ie,i as ke,j as Me}from"./ATEVAJ5Y.js";import{b as ne,o as we}from"./LKX5WDOQ.js";import{a as F,b as ge}from"./43LI5NKJ.js";import{a as Ne}from"./IOYRL6AY.js";import{b as z,d as Ue}from"./IX3GZMTM.js";import{b as y,j as O}from"./TI727O2H.js";import{a,b as me,e as q}from"./XSD5NL7J.js";import{decodeFunctionResult as ve,encodeFunctionData as B,getAddress as m,parseAbi as J,zeroAddress as $}from"viem";var re=-887272,se=887272,G=(1n<<128n)-1n,je="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Ke="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",Qe="0x3067048beee31b25b2f1681f88dac838c8bba36af25bfb2b7cf7473a5847e35f",oe=2000n,Ye=5,Le=64n,Ze=1800n,Be="^v3:(0x[0-9a-fA-F]{40}):(0|[1-9][0-9]{0,19}):(0|[1-9][0-9]{0,19})$",Je=new RegExp(Be),et=Object.freeze({type:"string",pattern:Be,description:"v3 only. Pass the nextCursor of the previous page to read the next 64 owner indices at the same block. Cannot be combined with tokenIds."}),w=Object.freeze({factory:m(O[4663].uniswap.v3_factory.address),positionManager:m(O[4663].uniswap.v3_position_manager.address),swapRouter02:m(O[4663].uniswap.swap_router02.address),permit2:m(O[4663].uniswap.permit2.address),weth:m(O[4663].uniswap.WETH.address),usdg:m(O[4663].uniswap.USDG.address),ethUsdgPool:m(O[4663].oracle.ethUsdgPool.address)}),Pe=Object.freeze({100:1,500:10,3e3:60,1e4:200}),qt=Object.freeze([{fee:100,tickSpacing:1,address:m("0x52e65B17fB6E5BA00Ed806f37Afcd2DaA50271Ca"),token0:w.weth,token1:w.usdg,recordedLiquidity:"1957537485734736219",recordedSqrtPriceX96:"3839219776288481168641554",recordedTick:-198707,feeProtocol:68},{fee:500,tickSpacing:10,address:m("0x69bfaf19c9f377bb306a89aed9f6b07e2c1a8d9a"),token0:w.weth,token1:w.usdg,recordedLiquidity:"714542894544667104",recordedSqrtPriceX96:"3839644024453020182443671",recordedTick:-198705,feeProtocol:68},{fee:3e3,tickSpacing:60,address:m("0xa9188730fe85be88ad499d7d52b099e800fb0334"),token0:w.weth,token1:w.usdg,recordedLiquidity:"310559629687003603",recordedSqrtPriceX96:"3843235825752878635548672",recordedTick:-198686,feeProtocol:102},{fee:1e4,tickSpacing:200,address:m("0x5f009e071f07e92b6c624e83f52f17bbda34680d"),token0:w.weth,token1:w.usdg,recordedLiquidity:"5822966536584155",recordedSqrtPriceX96:"3853297838190389678059735",recordedTick:-198634,feeProtocol:102}]),P=J(["function positions(uint256 tokenId) view returns (uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1)","function ownerOf(uint256 tokenId) view returns (address)","function balanceOf(address owner) view returns (uint256)","function tokenOfOwnerByIndex(address owner, uint256 index) view returns (uint256)","function mint((address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline) params) payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)","function increaseLiquidity((uint256 tokenId, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, uint256 deadline) params) payable returns (uint128 liquidity, uint256 amount0, uint256 amount1)","function decreaseLiquidity((uint256 tokenId, uint128 liquidity, uint256 amount0Min, uint256 amount1Min, uint256 deadline) params) payable returns (uint256 amount0, uint256 amount1)","function collect((uint256 tokenId, address recipient, uint128 amount0Max, uint128 amount1Max) params) payable returns (uint256 amount0, uint256 amount1)","function burn(uint256 tokenId) payable","function createAndInitializePoolIfNecessary(address token0, address token1, uint24 fee, uint160 sqrtPriceX96) payable returns (address pool)"]),Y=J(["function getPool(address tokenA, address tokenB, uint24 fee) view returns (address pool)","function feeAmountTickSpacing(uint24 fee) view returns (int24)"]),he=J(["function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)","function liquidity() view returns (uint128)","function tickSpacing() view returns (int24)","function fee() view returns (uint24)","function token0() view returns (address)","function token1() view returns (address)"]),tt=J(["function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)"]),xe=J(["function decimals() view returns (uint8)","function symbol() view returns (string)","function allowance(address owner, address spender) view returns (uint256)"]),nt="0xd0e30db0";function it(t){if(typeof t!="string")return!1;let e=t.trim().toLowerCase();return e===$||e===je||e==="eth"||e==="native"}function D(t,e){if(it(t))throw new a(`Uniswap v3 requires wrapped ERC-20 WETH (${w.weth}) rather than native ETH in ${e}.`);if(typeof t!="string")throw new a(`${e} must be a valid 20-byte hex address.`);return F(t),m(t)}function ot(t,e,n){let s=Number(t),o=Number(e),i=Number(n);if(!Number.isInteger(i)||i<=0)throw new a("Uniswap v3 tickSpacing must be a positive integer.");if(!Number.isInteger(s)||!Number.isInteger(o))throw new a("Uniswap v3 tickLower and tickUpper must be integers.");if(s<re||o>se||s>se||o<re)throw new a(`Uniswap v3 ticks are out of bounds [${re}, ${se}].`);if(s>=o)throw new a("Uniswap v3 tickLower must be strictly less than tickUpper.");if(s%i!==0||o%i!==0)throw new a(`Uniswap v3 tickLower (${s}) and tickUpper (${o}) must be divisible by tickSpacing (${i}).`);return{tickLower:s,tickUpper:o,tickSpacing:i}}function rt(t,e){let n=t.trim(),s=n.startsWith("-"),o=s||n.startsWith("+")?n.slice(1):n,i=Ue(z(o).toString(),e);return s&&i!=="0"?`-${i}`:i}function st(t){let e=typeof t=="string"?ve({abi:P,functionName:"positions",data:t}):t;return{nonce:BigInt(e[0]),operator:m(String(e[1])),token0:m(String(e[2])),token1:m(String(e[3])),fee:Number(e[4]),tickLower:Number(e[5]),tickUpper:Number(e[6]),liquidity:BigInt(e[7]),feeGrowthInside0LastX128:BigInt(e[8]),feeGrowthInside1LastX128:BigInt(e[9]),tokensOwed0:BigInt(e[10]),tokensOwed1:BigInt(e[11])}}function Re(t,e){if(!t||!Array.isArray(t.logs))return[];let n=e?m(e).toLowerCase():void 0,s=w.positionManager.toLowerCase(),o=new Set;for(let i of t.logs){if(!i||typeof i.address!="string"||i.address.toLowerCase()!==s)continue;let c=Array.isArray(i.topics)?i.topics.map(p=>String(p).toLowerCase()):[],r=c[0];if(r===Ke&&c.length>=4){let d=`0x${c[2].slice(-40)}`;if(!n||d===n){let u=BigInt(c[3]).toString();u!=="0"&&o.add(u)}}else if(r===Qe&&c.length>=2&&!n){let p=BigInt(c[1]).toString();p!=="0"&&o.add(p)}}return[...o]}function Ut(t){let e=n=>typeof n=="bigint"?n:z(n);return B({abi:tt,functionName:"exactInputSingle",args:[{tokenIn:m(t.tokenIn),tokenOut:m(t.tokenOut),fee:t.fee,recipient:m(t.recipient),amountIn:e(t.amountIn),amountOutMinimum:e(t.amountOutMinimum),sqrtPriceLimitX96:t.sqrtPriceLimitX96!==void 0?e(t.sqrtPriceLimitX96):0n}]})}var Ee=1n<<96n;function _e(t){let e=Math.abs(t),n=(e&1)!==0?0xfffcb933bd6fad37aa2d162d1a594001n:0x100000000000000000000000000000000n;return(e&2)!==0&&(n=n*0xfff97272373d413259a46990580e213an>>128n),(e&4)!==0&&(n=n*0xfff2e50f5f656932ef12357cf3c7fdccn>>128n),(e&8)!==0&&(n=n*0xffe5caca7e10e4e61c3624eaa0941cd0n>>128n),(e&16)!==0&&(n=n*0xffcb9843d60f6159c9db58835c926644n>>128n),(e&32)!==0&&(n=n*0xff973b41fa98c081472e6896dfb254c0n>>128n),(e&64)!==0&&(n=n*0xff2ea16466c96a3843ec78b326b52861n>>128n),(e&128)!==0&&(n=n*0xfe5dee046a99a2a811c461f1969c3053n>>128n),(e&256)!==0&&(n=n*0xfcbe86c7900a88aedcffc83b479aa3a4n>>128n),(e&512)!==0&&(n=n*0xf987a7253ac413176f2b074cf7815e54n>>128n),(e&1024)!==0&&(n=n*0xf3392b0822b70005940c7a398e4b70f3n>>128n),(e&2048)!==0&&(n=n*0xe7159475a2c29b7443b29c7fa6e889d9n>>128n),(e&4096)!==0&&(n=n*0xd097f3bdfd2022b8845ad8f792aa5825n>>128n),(e&8192)!==0&&(n=n*0xa9f746462d870fdf8a65dc1f90e061e5n>>128n),(e&16384)!==0&&(n=n*0x70d869a156d2a1b890bb3df62baf32f7n>>128n),(e&32768)!==0&&(n=n*0x31be135f97d08fd981231505542fcfa6n>>128n),(e&65536)!==0&&(n=n*0x9aa508b5b7a84e1c677de54f3e99bc9n>>128n),(e&131072)!==0&&(n=n*0x5d6af8dedb81196699c329225ee604n>>128n),(e&262144)!==0&&(n=n*0x2216e584f5fa1ea926041bedfe98n>>128n),(e&524288)!==0&&(n=n*0x48a170391f7dc42444e8fa2n>>128n),t>0&&(n=((1n<<256n)-1n)/n),(n>>32n)+(n%(1n<<32n)===0n?0n:1n)}function at(t,e,n,s){if(s<=0n)return{amount0:0n,amount1:0n};let[o,i]=e<n?[e,n]:[n,e];if(t<=o)return{amount0:(s<<96n)*(i-o)/i/o,amount1:0n};if(t<i){let r=(s<<96n)*(i-t)/i/t,p=s*(t-o)/Ee;return{amount0:r,amount1:p}}return{amount0:0n,amount1:s*(i-o)/Ee}}async function M(t,e,n,s){let o=m(e),i,c;if(n===y&&o===w.weth?(i=18,c="WETH"):n===y&&o===w.usdg&&(i=6,c="USDG"),i===void 0){let r=await t.readContract({address:o,abi:xe,functionName:"decimals"});i=Number(r)}if(c===void 0)try{let r=await t.readContract({address:o,abi:xe,functionName:"symbol"});if(typeof r!="string"||!r.trim())throw new a("Token symbol is unavailable.");c=Me(r.trim(),o)}catch(r){throw new a(`Could not read token metadata. ${q(r)}`)}if(!Number.isInteger(i)||i<0||i>255)throw new a("Token decimals are invalid.");if(s!=null){let r=Number(s);if(!Number.isInteger(r)||r!==i)throw new a(`Token ${o} on chain ${n} has ${i} decimals, not ${String(s)}.`)}return{address:o,symbol:c,decimals:i,chainId:n}}async function ct(t){try{if(!t.getBlock)throw new a("Block timestamps are unavailable.");let e=await t.getBlock();if(typeof e.timestamp!="bigint")throw new a("Invalid block timestamp.");return e.timestamp}catch(e){throw new a(`Could not read the current block timestamp. ${q(e)}`)}}function ee(t,e){if(typeof t=="bigint"){if(t<0n)throw new a(`${e} must be a non-negative integer.`);return t}if(typeof t=="number"){if(!Number.isSafeInteger(t)||t<0)throw new a(`${e} must be a non-negative integer.`);return BigInt(t)}if(typeof t=="string")return z(t);throw new a(`${e} must be a non-negative integer.`)}async function Oe(t,e){let n=await ct(t);if(e==null)return n+Ze;let s=ee(e,"deadline");if(s<=n)throw new a(`Uniswap v3 deadline (${s.toString()}) has expired at timestamp ${n.toString()}.`);return s}function W(t,e){if(typeof t!="string"||!/^\d+$/.test(t))throw new a(`${e} must be a non-negative integer string in base units.`);return z(t)}function De(t){let e=t.slippageBps??ne;if(typeof e!="number")throw new a("Slippage must be an integer from 0 to 9999 bps.");return we("0",e),e}function ae(t,e,n,s){let o=t===void 0?z(we(e.toString(),n)):W(t,s);if(o<=1n)throw new a(`${s} must exceed 1 base unit; the simulated amount may be too small.`);return o}function H(t,e){return ge({to:w.positionManager,data:t,value:"0",chainId:y,description:e})}async function Z(t,e,n){try{if(!t.request)throw new a("Sequential transaction simulation is unavailable.");let o=await t.request({method:"eth_simulateV1",params:[{blockStateCalls:[{calls:e.map(i=>({from:n,gas:`0x${Ne.toString(16)}`,to:i.to,data:i.data,value:`0x${BigInt(i.value).toString(16)}`}))}],validation:!1,traceTransfers:!0},"latest"]},{retryCount:0});if(!Array.isArray(o)||o.length!==1||!Array.isArray(o[0]?.calls)||o[0].calls.length!==e.length)throw new a("Unexpected batch simulation response.");return o[0].calls.map((i,c)=>{if(i.status!=="0x1"||i.error||typeof i.returnData!="string"||!/^0x([a-fA-F0-9]{2})*$/.test(i.returnData))throw new a(`Simulation call ${c+1} failed. ${q(i.error)}`);return i.returnData})}catch(s){throw new a(`Uniswap v3 simulation failed. ${q(s)}`)}}function ce(t,e){try{return ve({abi:P,functionName:t,data:e})}catch{throw new a(`Uniswap v3 ${t} simulation returned invalid amounts.`)}}function Ve(t,e,n){if(t.initialPrice!==void 0&&t.sqrtPriceX96!==void 0)throw new a("Provide initialPrice or sqrtPriceX96, not both.");if(t.sqrtPriceX96!==void 0){if(typeof t.sqrtPriceX96!="string"||!/^\d+$/.test(t.sqrtPriceX96))throw new a("sqrtPriceX96 must be a non-negative integer string.");return $e(BigInt(t.sqrtPriceX96))}if(t.initialPrice===void 0)throw new a("A new pool needs initialPrice (token1 per 1 token0, human units) or sqrtPriceX96.");return Te(t.initialPrice,e,n)}async function Xe(t,e,n,s){let o=[];for(let i of Object.keys(Pe).map(Number)){if(i===s)continue;let c=m(String(await t.readContract({address:w.factory,abi:Y,functionName:"getPool",args:[e,n,i]})));if(c===$||BigInt(await t.readContract({address:c,abi:he,functionName:"liquidity"}))===0n)continue;let p=await t.readContract({address:c,abi:he,functionName:"slot0"});o.push({label:`v3 fee ${i} pool ${c}`,sqrtPriceX96:BigInt(p[0])})}return o}function j(t,e={}){if(e.chainId!==void 0&&Number(e.chainId)!==y)throw new a(`Uniswap v3 is only supported on Robinhood Chain (${y}).`);if(e.version!==void 0&&e.version!=="v3")throw new a(`Uniswap v3 handler received unsupported version "${String(e.version)}".`);let n=t.clientFor(y);return{...n,readContract:async s=>{try{return await n.readContract(s)}catch(o){throw new a(`Could not read Uniswap v3 ${s.functionName}. ${q(o)}`,{cause:o})}}}}async function Ie(t,e,n){let s;try{s=await t.readContract({address:w.positionManager,abi:P,functionName:"ownerOf",args:[e]})}catch(c){throw new a(`Could not verify owner of Uniswap v3 position #${e}. ${q(c)}`)}let o=m(String(s)),i=m(n);if(o!==i)throw new a(`Wallet ${i} is not the owner of Uniswap v3 position #${e.toString()} (owned by ${o}).`);return o}async function de(t,e){let n=await t.readContract({address:w.positionManager,abi:P,functionName:"positions",args:[e]});return st(n)}function Se(t,e){if(!Array.isArray(e.changes)||!e.changes.length)return t;let n=e.changes.map(s=>`${rt(s.amount,s.token.decimals)} ${s.token.symbol}`);return`${t} (${n.join(", ")})`}async function dt(t,e,n){F(n);let s=m(n),o=j(t,e),i=await Oe(o,e.deadline),c=De(e),r=e.tokenId===void 0?void 0:ee(e.tokenId,"tokenId"),p;if(r!==void 0){if(r<=0n)throw new a("Uniswap v3 tokenId must be a positive integer.");await Ie(o,r,s),p=await de(o,r)}let d=p?.token0??D(e.token0,"token0"),u=p?.token1??D(e.token1,"token1");if(BigInt(d)>=BigInt(u))throw new a("Uniswap v3 requires distinct sorted token addresses.");let g=p?.fee??Number(e.fee??100),f=Pe[g];if(!f)throw new a("Unsupported Uniswap v3 fee tier.");let b=m(String(await o.readContract({address:w.factory,abi:Y,functionName:"getPool",args:[d,u,g]}))),l=e.initialPrice!==void 0||e.sqrtPriceX96!==void 0;if(b===$&&!l)throw new a("No Uniswap v3 pool exists for these tokens and fee tier. To create it and add the first liquidity in one tool call with separately confirmed transactions, add initialPrice (token1 per 1 token0, human units) to this call; to create it without liquidity use uniswap_create_pool.");if(b!==$&&l)throw new a(`The Uniswap v3 pool already exists at ${b}; remove initialPrice/sqrtPriceX96 to add liquidity at its current price.`);if(r!==void 0&&l)throw new a("initialPrice cannot be combined with tokenId.");if(e.fullRange!==void 0&&typeof e.fullRange!="boolean")throw new a("fullRange must be a boolean.");if(e.fullRange===!0&&(e.tickLower!==void 0||e.tickUpper!==void 0||p))throw new a("Use fullRange only for a new position, without explicit ticks. Existing position ticks cannot change.");let{tickLower:k,tickUpper:U,tickSpacing:A}=ot(p?.tickLower??(e.fullRange===!0?Math.ceil(re/f)*f:e.tickLower),p?.tickUpper??(e.fullRange===!0?Math.floor(se/f)*f:e.tickUpper),f),v=await M(o,d,y,e.token0Decimals),h=await M(o,u,y,e.token1Decimals),C;if(b===$){let T=Ve(e,v.decimals,h.decimals),_=ke(T,await Xe(o,d,u,g),e.acceptPriceDeviation===!0,v.decimals,h.decimals);C={sqrtPriceX96:T,note:_}}let I=W(e.amount0Desired,"amount0Desired"),S=W(e.amount1Desired,"amount1Desired");if(I===0n&&S===0n)throw new a("Liquidity addition requires a positive desired amount.");let x=e.recipient===void 0?s:D(e.recipient,"recipient");if(x!==s)throw new a("Uniswap recipient must be the signing wallet.");if(e.wrapNative===!0&&d!==w.weth&&u!==w.weth)throw new a("Wrapping requires a positive WETH desired amount.");let V=await Promise.all([d,u].map(async T=>BigInt(await o.readContract({address:T,abi:xe,functionName:"allowance",args:[s,w.positionManager]})))),X=(T,_)=>{let pe=[];if(e.wrapNative===!0){let Q=d===w.weth?T:_;Q>0n&&pe.push(ge({to:w.weth,data:nt,value:Q.toString(),chainId:y,description:"Wrap ETH into WETH."}))}for(let[Q,Ge]of[d,u].entries()){let fe=Q===0?T:_;fe>0n&&V[Q]<fe&&pe.push(t.approval(Ge,w.positionManager,fe.toString(),y))}return pe},L=r===void 0?"mint":"increaseLiquidity",R=(T,_)=>H(r===void 0?B({abi:P,functionName:"mint",args:[{token0:d,token1:u,fee:g,tickLower:k,tickUpper:U,amount0Desired:I,amount1Desired:S,amount0Min:T,amount1Min:_,recipient:x,deadline:i}]}):B({abi:P,functionName:"increaseLiquidity",args:[{tokenId:r,amount0Desired:I,amount1Desired:S,amount0Min:T,amount1Min:_,deadline:i}]}),`${L==="mint"?"Mint":"Increase"} Uniswap v3 ${v.symbol}/${h.symbol} liquidity.`),E=C&&H(B({abi:P,functionName:"createAndInitializePoolIfNecessary",args:[d,u,g,C.sqrtPriceX96]}),`Create and initialize the Uniswap v3 ${v.symbol}/${h.symbol} fee ${g} pool at ${ie(C.sqrtPriceX96,v.decimals,h.decimals)} ${h.symbol} per ${v.symbol}.`),K=E?[E]:[],Ae=await Z(o,[...K,...X(I,S),R(0n,0n)],s),N=ce(L,Ae[Ae.length-1]),We=N[N.length-2],ze=N[N.length-1];if(We>I||ze>S)throw new a("Simulated liquidity spend exceeds the desired amounts.");let te=[...K,...X(I,S)],ue=ae(e.amount0Min,N[N.length-2],c,"amount0Min"),le=ae(e.amount1Min,N[N.length-1],c,"amount1Min");if(ue>I||le>S)throw new a("Uniswap v3 minimum amount cannot exceed desired amount.");let Ce=R(ue,le);te.push(Ce);for(let[T,_]of[d,u].entries())(T===0?I:S)>0n&&te.push(t.approval(_,w.positionManager,"0",y));let qe=await t.preview(te,s);return{txs:te,preview:qe,summary:Se(Ce.description,qe),details:{version:"v3",action:L,...r===void 0?{}:{tokenId:r.toString()},pool:b===$?null:b,fee:g,tickSpacing:A,tickLower:k,tickUpper:U,token0:v,token1:h,amount0Desired:I.toString(),amount1Desired:S.toString(),amount0Min:ue.toString(),amount1Min:le.toString(),deadline:i.toString(),recipient:x,expectedAmount0:N[N.length-2].toString(),expectedAmount1:N[N.length-1].toString(),...C?{poolCreated:!0,sqrtPriceX96:C.sqrtPriceX96.toString(),initialPrice:ie(C.sqrtPriceX96,v.decimals,h.decimals),initialTick:be(C.sqrtPriceX96),priceCheck:C.note}:{}}}}async function ut(t,e,n){F(n);let s=m(n),o=j(t,e),i=D(e.token0,"token0"),c=D(e.token1,"token1");if(BigInt(i)>=BigInt(c))throw new a(`Uniswap v3 requires sorted token addresses (token0 < token1). Use token0=${BigInt(i)<BigInt(c)?i:c}, token1=${BigInt(i)<BigInt(c)?c:i}; initialPrice is token1 per 1 token0 in that order.`);let r=Number(e.fee),p=Pe[r];if(!p){let h=Number(await o.readContract({address:w.factory,abi:Y,functionName:"feeAmountTickSpacing",args:[r]}));if(!Number.isInteger(r)||h<=0)throw new a("Unsupported Uniswap v3 fee tier. Enabled tiers: 100, 500, 3000, 10000.");p=h}let d=m(String(await o.readContract({address:w.factory,abi:Y,functionName:"getPool",args:[i,c,r]})));if(d!==$)throw new a(`The Uniswap v3 pool already exists at ${d}. Use uniswap_add to provide liquidity.`);let u=await M(o,i,y,e.token0Decimals),g=await M(o,c,y,e.token1Decimals),f=Ve(e,u.decimals,g.decimals),b=ke(f,await Xe(o,i,c,r),e.acceptPriceDeviation===!0,u.decimals,g.decimals),l=ie(f,u.decimals,g.decimals),k=[H(B({abi:P,functionName:"createAndInitializePoolIfNecessary",args:[i,c,r,f]}),`Create and initialize the Uniswap v3 ${u.symbol}/${g.symbol} fee ${r} pool at ${l} ${g.symbol} per ${u.symbol}.`)],U=await Z(o,k,s),A;try{A=m(String(ve({abi:P,functionName:"createAndInitializePoolIfNecessary",data:U[0]})))}catch{throw new a("Uniswap v3 pool creation simulation returned an invalid pool address.")}if(A===$)throw new a("Uniswap v3 pool creation simulation returned no pool.");let v=await t.preview(k,s);return{txs:k,preview:v,summary:`${k[0].description} The pool starts empty: nothing trades until liquidity is added with uniswap_add.`,details:{version:"v3",action:"createPool",pool:A,fee:r,tickSpacing:p,token0:u,token1:g,sqrtPriceX96:f.toString(),initialPrice:l,initialTick:be(f),priceCheck:b}}}async function lt(t,e,n){F(n);let s=m(n),o=j(t,e),i=ee(e.tokenId,"tokenId");if(i<=0n)throw new a("Uniswap v3 tokenId must be a positive integer.");await Ie(o,i,s);let c=await de(o,i),r=await M(o,c.token0,y),p=await M(o,c.token1,y),d=e.recipient===void 0?s:D(e.recipient,"recipient");if(d!==s)throw new a("Uniswap recipient must be the signing wallet.");let u=e.amount0Max===void 0?G:W(e.amount0Max,"amount0Max"),g=e.amount1Max===void 0?G:W(e.amount1Max,"amount1Max");if(u===0n&&g===0n||u>G||g>G)throw new a("Collect requires a positive amountMax within uint128.");let f=[H(B({abi:P,functionName:"collect",args:[{tokenId:i,recipient:d,amount0Max:u,amount1Max:g}]}),`Collect Uniswap v3 fees from position #${i}.`)],b=ce("collect",(await Z(o,f,s))[0]),l=await t.preview(f,s);return{txs:f,preview:l,summary:Se(f[0].description,l),details:{version:"v3",action:"collect",tokenId:i.toString(),recipient:d,token0:r,token1:p,amount0Max:u.toString(),amount1Max:g.toString(),expectedAmount0:b[0].toString(),expectedAmount1:b[1].toString()}}}async function pt(t,e,n){F(n);let s=m(n),o=j(t,e),i=ee(e.tokenId,"tokenId");if(i<=0n)throw new a("Uniswap v3 tokenId must be a positive integer.");await Ie(o,i,s);let c=await de(o,i),r=c.liquidity===0n&&e.burn===!0;if(c.liquidity<=0n&&!r)throw new a("Position has zero active liquidity to remove.");if(e.liquidity===void 0&&!r)throw new a('Provide a liquidity amount or explicitly choose liquidity "all" for a full exit.');let p=e.liquidity==="all"||e.liquidity===void 0?c.liquidity:W(e.liquidity,"liquidity");if(p<=0n&&!r)throw new a("Liquidity to remove must be positive.");if(p>c.liquidity)throw new a("Requested liquidity exceeds position liquidity.");let d=await Oe(o,e.deadline),u=De(e),g=await M(o,c.token0,y),f=await M(o,c.token1,y),b=e.recipient===void 0?s:D(e.recipient,"recipient");if(b!==s)throw new a("Uniswap recipient must be the signing wallet.");let l=(R,E)=>H(B({abi:P,functionName:"decreaseLiquidity",args:[{tokenId:i,liquidity:p,amount0Min:R,amount1Min:E,deadline:d}]}),`Decrease ${p} liquidity on Uniswap v3 position #${i}.`),k=r?[0n,0n]:ce("decreaseLiquidity",(await Z(o,[l(0n,0n)],s))[0]),U=(R,E)=>{if(R!==void 0&&W(R,E)!==0n)throw new a(`${E} must be zero for an empty position burn.`);return 0n},A=r?U(e.amount0Min,"amount0Min"):ae(e.amount0Min,k[0],u,"amount0Min"),v=r?U(e.amount1Min,"amount1Min"):ae(e.amount1Min,k[1],u,"amount1Min"),h=r?[]:[l(A,v)],C=h.length,I=!r||c.tokensOwed0>0n||c.tokensOwed1>0n;I&&h.push(H(B({abi:P,functionName:"collect",args:[{tokenId:i,recipient:b,amount0Max:G,amount1Max:G}]}),`Collect principal and fees from Uniswap v3 position #${i}.`));let S=p===c.liquidity,x=S&&e.burn===!0;x&&h.push(H(B({abi:P,functionName:"burn",args:[i]}),`Burn empty Uniswap v3 position #${i}.`));let V=await Z(o,h,s),X=I?ce("collect",V[C]):[0n,0n],L=await t.preview(h,s);return{txs:h,preview:L,summary:Se(`Remove Uniswap v3 liquidity from position #${i}${x?`; burns position #${i} at ${w.positionManager}`:""}`,L),details:{version:"v3",action:"remove",tokenId:i.toString(),recipient:b,token0:g,token1:f,liquidityRemoved:p.toString(),amount0Min:A.toString(),amount1Min:v.toString(),deadline:d.toString(),expectedAmount0:X[0].toString(),expectedAmount1:X[1].toString(),fullExit:S,burned:x}}}function ft(t,e){let n=typeof t=="string"?Je.exec(t):null;if(!n)throw new a('cursor is not a Uniswap v3 position cursor. Pass the nextCursor exactly as a previous uniswap_list_positions {"version":"v3"} page returned it.');if(m(n[1])!==e)throw new a("This cursor was issued for a different wallet. Start again without a cursor to page this wallet.");return{block:BigInt(n[2]),next:BigInt(n[3])}}function mt(t,e,n){return`v3:${t.toLowerCase()}:${e}:${n}`}function gt(t,e){return{...t,readContract:n=>t.readContract({...n,blockNumber:e})}}var ye=t=>me(t,3,-32601,-32004);async function wt(t,e,n={}){let s=m(e),o=new Set;if(Array.isArray(n.tokenIds))for(let d of n.tokenIds){let u=ee(d,"tokenId");u>0n&&o.add(u.toString())}if(Array.isArray(n.receipts))for(let d of n.receipts)for(let u of Re(d,s))o.add(u);if(Array.isArray(n.tokenIds)&&n.tokenIds.length>0)return[...o].map(d=>BigInt(d)).sort((d,u)=>d<u?-1:d>u?1:0);let i=n.cursor,c=()=>new a("This Uniswap v3 position manager cannot enumerate NFTs by owner, so there are no pages to continue. Pass tokenIds to check specific positions."),r=!1,p=!1;try{let d;try{d=BigInt(await t.readContract({address:w.positionManager,abi:P,functionName:"balanceOf",args:[s]}))}catch(l){throw ye(l)||!i?l:new a(`Could not read this wallet's Uniswap v3 holdings at the cursor's snapshot block ${i.block}; the node may no longer serve it. Start again without a cursor. ${q(l)}`)}let u=i?.next??0n;if(u>d)throw new a(`This cursor starts at owner index ${u}, but the wallet held ${d} Uniswap v3 NFTs at block ${i?.block}. Start again without a cursor.`);let g=d-u>Le?u+Le:d,f=[],b=!0;for(let l=u;l<g;l++)try{f.push(BigInt(await t.readContract({address:w.positionManager,abi:P,functionName:"tokenOfOwnerByIndex",args:[s,l]})))}catch(k){if(!ye(k))throw k;b=!1;break}if(b){r=!0,p=u===0n&&g===d;for(let k of f)k>0n&&o.add(k.toString());let l=n.blockNumber;n.onPage?.({balance:d,from:u,to:g,blockNumber:l,...g<d&&l!==void 0?{nextCursor:mt(s,l,g)}:{}})}}catch(d){if(!ye(d))throw d}if(i&&!r)throw c();if((!r||p)&&typeof t.getLogs=="function"&&typeof t.getBlockNumber=="function")try{let d=n.toBlock??await t.getBlockNumber(),u=n.maxChunks??Ye,g=n.fromBlock??(d>oe*BigInt(u)?d-oe*BigInt(u)+1n:0n),f=d,b=0;for(;f>=g&&b<u;){let l=f>=oe-1n?f-(oe-1n):0n,k=l<g?g:l,U=await t.getLogs({address:w.positionManager,fromBlock:k,toBlock:f});for(let A of Re({logs:U},s))o.add(A);if(b+=1,k===0n||k<=g)break;f=k-1n}}catch(d){throw new a(`Could not discover Uniswap v3 positions from logs. ${q(d)}`)}else if(!r&&n.tokenIds===void 0&&n.receipts===void 0)throw new a("Uniswap v3 position discovery is unavailable; supply candidate token IDs or receipts.");return[...o].map(d=>BigInt(d)).sort((d,u)=>d<u?-1:d>u?1:0)}async function Fe(t,e,n={}){F(e);let s=m(e),o=j(t),i=Array.isArray(n.tokenIds)&&n.tokenIds.length>0,c=Array.isArray(n.receipts)&&n.receipts.length>0;if(n.cursor!==void 0&&(i||c))throw new a(`${i?"tokenIds":"receipts"} and cursor cannot be combined: ${i?"tokenIds":"receipts"} inspects exactly those NFTs and has no pages. Send one or the other.`);let r=n.cursor===void 0?void 0:ft(n.cursor,s),p=o,d;if(!i){let f;if(typeof o.getBlockNumber=="function")try{f=await o.getBlockNumber()}catch(b){throw new a(`Could not read the latest block for the Uniswap v3 listing. ${q(b)}`)}if(r&&f!==void 0&&r.block>f)throw new a(`This cursor is from block ${r.block}, ahead of the chain's latest block ${f}. Start again without a cursor.`);d=r?.block??f,d!==void 0&&(p=gt(o,d))}let u=await wt(p,s,{...n,cursor:r,blockNumber:d}),g=[];for(let f of u){let b;try{let x=await p.readContract({address:w.positionManager,abi:P,functionName:"ownerOf",args:[f]});b=m(String(x))}catch(x){if(me(x,3))continue;throw new a(`Could not verify owner of position #${f}. ${q(x)}`)}if(b!==s)continue;let l;try{l=await de(p,f)}catch(x){throw new a(`Could not read position #${f}. ${q(x)}`)}if(l.liquidity===0n&&l.tokensOwed0===0n&&l.tokensOwed1===0n&&!n.includeEmpty)continue;let U=await M(p,l.token0,y),A=await M(p,l.token1,y),v=0n,h=0n;if(l.liquidity>0n)try{let x=await p.readContract({address:w.factory,abi:Y,functionName:"getPool",args:[l.token0,l.token1,l.fee]}),V=m(String(x));if(V===$)throw new a("Position pool was not found.");if(V!==$){let X=await p.readContract({address:V,abi:he,functionName:"slot0"}),L=BigInt(X[0]);if(L<=0n)throw new a("Position pool has no initialized price.");let R=_e(l.tickLower),E=_e(l.tickUpper),K=at(L,R,E,l.liquidity);v=K.amount0,h=K.amount1}}catch(x){throw new a(`Could not value Uniswap v3 position #${f}. ${q(x)}`)}let C=v+l.tokensOwed0,I=h+l.tokensOwed1,S=[{token:U,amount:C.toString()},{token:A,amount:I.toString()}];g.push({module:"uniswap",id:`uniswap:v3:${f.toString()}`,chainId:y,assets:S,description:`Uniswap v3 LP position #${f.toString()} (${U.symbol}/${A.symbol} fee ${l.fee} ticks [${l.tickLower}, ${l.tickUpper}] liquidity ${l.liquidity.toString()})`})}return g}function bt(t){let e=t.nextCursor?`Pass cursor "${t.nextCursor}" to read the next page, or tokenIds to check specific positions.`:"Pass tokenIds to check specific positions.";return t.from===0n?`This wallet holds ${t.balance} Uniswap v3 position NFTs and only the first ${t.to} were checked, so later positions are not listed. ${e}`:`This page checked owner indices ${t.from}-${t.to-1n} of ${t.balance} Uniswap v3 position NFTs, so later positions are not listed. ${e}`}async function kt(t,e,n){j(t,e);let s=e.wallet!==void 0?D(e.wallet,"wallet"):m(n),o=Array.isArray(e.tokenIds)?e.tokenIds:void 0,i=Array.isArray(e.receipts)?e.receipts:void 0,c=e.includeZero===!0||e.includeEmpty===!0,r,p=await Fe(t,s,{tokenIds:o,receipts:i,includeEmpty:c,cursor:e.cursor,onPage:u=>{r=u}}),d=r!==void 0&&r.to<r.balance;return{positions:p,...r?.nextCursor?{nextCursor:r.nextCursor}:{},details:{version:"v3",wallet:s,count:p.length,positionManager:w.positionManager,...r?{balance:Number(r.balance),from:Number(r.from),to:Number(r.to),examined:Number(r.to-r.from),...r.blockNumber!==void 0?{blockNumber:r.blockNumber.toString()}:{}}:{},...r&&d?{truncated:!0,incomplete:!0,note:bt(r)}:{}}}}function yt(t){return[{name:"uniswap_add",inputSchema:{type:"object",description:"Mint a new Uniswap v3 concentrated liquidity position or increase liquidity on an existing v3 NFT position on Robinhood Chain (4663).",properties:{version:{description:"Uniswap v3 concentrated-liquidity version.",type:"string",enum:["v3"],default:"v3"},tokenId:{type:"string",description:'Optional existing v3 position NFT identifier to increase, as a decimal string; omit to mint. Example: "1".'},token0:{type:"string",description:"Sorted ERC-20 token0 address (e.g. WETH)."},token1:{type:"string",description:"Sorted ERC-20 token1 address (e.g. USDG)."},fee:{description:"Pool fee in pips, hundredths of a basis point (3000 = 0.3%; 950000 = 95%).",type:"integer",enum:[100,500,3e3,1e4],default:100},fullRange:{type:"boolean",description:"For a new v3 position, use the widest ticks aligned to the pool fee tier; omit explicit ticks."},tickLower:{type:"integer",description:"Lower tick boundary divisible by tickSpacing."},tickUpper:{type:"integer",description:"Upper tick boundary divisible by tickSpacing."},amount0Desired:{type:"string",description:'Desired amount of token0 in base units; use token0 decimals. Example: "1000000" = 1 token0 at 6 decimals.'},amount1Desired:{type:"string",description:'Desired amount of token1 in base units; use token1 decimals. Example: "1000000" = 1 token1 at 6 decimals.'},amount0Min:{type:"string",description:'Minimum amount of token0 in base units; use token0 decimals. Example: "1000000" = 1 token0 at 6 decimals.'},amount1Min:{type:"string",description:'Minimum amount of token1 in base units; use token1 decimals. Example: "1000000" = 1 token1 at 6 decimals.'},slippageBps:{description:"Slippage tolerance in basis points (50 = 0.5%).",type:"integer",minimum:0,maximum:9999,default:ne},deadline:{type:"integer",description:"Transaction deadline in Unix seconds, after the current block timestamp. Example: 1800000000."},wrapNative:{type:"boolean",description:"Optional: wrap native ETH into WETH before minting."},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."}}},execute:(c,r)=>dt(t,c,r)},{name:"uniswap_collect",inputSchema:{type:"object",description:"Collect accrued Uniswap v3 LP fees for an owned NonfungiblePositionManager NFT.",properties:{version:{description:"Uniswap v3 concentrated-liquidity version.",type:"string",enum:["v3"],default:"v3"},tokenId:{type:"string",description:'Identifier of the position NFT, as a decimal string. Example: "1".'},recipient:{type:"string",description:"Optional fee recipient; must be the signing wallet."},amount0Max:{type:"string",description:'Maximum amount of token0 in base units; use token0 decimals. Example: "1000000" = 1 token0 at 6 decimals.'},amount1Max:{type:"string",description:'Maximum amount of token1 in base units; use token1 decimals. Example: "1000000" = 1 token1 at 6 decimals.'}},required:["tokenId"]},execute:(c,r)=>lt(t,c,r)},{name:"uniswap_remove",inputSchema:{type:"object",description:"Decrease liquidity on an owned Uniswap v3 NFT position, collect principal and fees, and optionally burn the empty NFT.",properties:{version:{description:"Uniswap v3 concentrated-liquidity version.",type:"string",enum:["v3"],default:"v3"},tokenId:{type:"string",description:'Identifier of the position NFT, as a decimal string. Example: "1".'},liquidity:{type:"string",description:'Liquidity in protocol base units, or "all" for a full exit where supported; not a token amount. Example: "1000" = 1000 liquidity units.'},amount0Min:{type:"string",description:'Minimum amount of token0 in base units; use token0 decimals. Example: "1000000" = 1 token0 at 6 decimals.'},amount1Min:{type:"string",description:'Minimum amount of token1 in base units; use token1 decimals. Example: "1000000" = 1 token1 at 6 decimals.'},slippageBps:{description:"Slippage tolerance in basis points (50 = 0.5%).",type:"integer",minimum:0,maximum:9999,default:ne},deadline:{type:"integer",description:"Transaction deadline in Unix seconds, after the current block timestamp. Example: 1800000000."},burn:{type:"boolean",description:"Whether to burn the NFT after removing 100% of liquidity, or burn an already-empty position."}},required:["tokenId"]},execute:(c,r)=>pt(t,c,r)},{name:"uniswap_list_positions",inputSchema:{type:"object",description:"List active Uniswap v3 LP positions owned by the wallet, 64 owner indices per page at one pinned block; follow nextCursor for more. Falls back to a bounded Transfer-log scan for managers that cannot enumerate by owner.",properties:{version:{description:"Uniswap v3 concentrated-liquidity version.",type:"string",enum:["v3"],default:"v3"},wallet:{type:"string",description:"Optional wallet address override."},tokenIds:{type:"array",items:{type:"string"},description:'Optional v3 NFT identifiers as decimal strings, e.g. ["1", "2"]. Inspects exactly these NFTs without paging.'},cursor:et}},execute:(c,r)=>kt(t,c,r)},{name:"uniswap_create_pool",inputSchema:{type:"object",description:"Create and initialize an empty Uniswap v3 pool on Robinhood Chain (4663). Add liquidity afterwards with uniswap_add.",properties:{version:{description:"Uniswap v3 concentrated-liquidity version.",type:"string",enum:["v3"],default:"v3"},token0:{type:"string",description:"Sorted ERC-20 token0 address (WETH, not native ETH)."},token1:{type:"string",description:"Sorted ERC-20 token1 address."},fee:{description:"Pool fee in pips, hundredths of a basis point (3000 = 0.3%; 950000 = 95%).",type:"integer",enum:[100,500,3e3,1e4]},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."}},required:["token0","token1","fee"]},execute:(c,r)=>ut(t,c,r)}]}var He=t=>({tools:yt(t),positions:async e=>{let n,s=await Fe(t,e,{onPage:o=>{o.to>=o.balance||(n={module:"uniswap",id:"uniswap-v3-discovery-truncated",chainId:y,assets:[],incomplete:!0,description:`This wallet holds ${o.balance} Uniswap v3 position NFTs and only the first ${o.to} were checked, so later positions may be missing. Pass tokenIds to uniswap_list_positions to check the others, or page through them with uniswap_list_positions {"version":"v3"} and each nextCursor.`})}});return n?[...s,n]:s}}),Nt=He,Tt=He;export{re as a,se as b,G as c,et as d,w as e,Pe as f,qt as g,P as h,Y as i,he as j,tt as k,ot as l,rt as m,st as n,Re as o,Ut as p,Ve as q,dt as r,ut as s,lt as t,pt as u,Fe as v,kt as w,yt as x,He as y,Nt as z,Tt as A};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as q}from"./NCQFWPAW.js";import{a as v}from"./D742AYEV.js";import{K as A}from"./7QKYDNF6.js";import{c as k}from"./DNNFKDZR.js";import{a as $}from"./43LI5NKJ.js";import{a as I}from"./66F5ZH34.js";import{d as M,g as F,i as G,m as U}from"./NWNYJ26T.js";import{a as y}from"./FWD4L3CJ.js";import{a as o}from"./XSD5NL7J.js";import{encodeFunctionData as L,erc20Abi as R,getAddress as N,zeroAddress as j}from"viem";var C={genesis:N("0x575b7B7c97Ef3E21C82DAeB427899d583e1E913f"),bond:N("0xff32a969A0c567129eECD926D04657728E1980C1"),inverse:N("0x92166e94Eea5B7799b761653881692f881dFC4C9"),treasury:N("0x04822Ea321A0DEE6F40656172F29312104855d66"),pteam:N("0x650F58079dAa17ee28928c2F92d22291d038B2B0"),rwa:N("0x99B6eE6eDe47d9a8a9bfd03F728a99B789df1961"),premium:N("0x346e1a31171A0f7aC73909010b5435768d3B5462"),tax:N("0x086C58400b8708Ef993f256E12e752dcF0AC918e")},z=N("0x59F95461E68e0c77605299791E1449f175165B54"),O={genesis:["purchase","finalize","refund","claim"],bond:["deposit","redeem"],inverse:["swap"],treasury:["rebalanceToMorpho","rebalanceFromMorpho","mintNet","spendUsdg"],pteam:["exercise"],rwa:["redeem","depositInventory","pokeHwm","setDiscount","setInventoryMax","setHalt","setMenu","skim"],premium:["execute"],tax:["convert"]},V={genesis:["wired","finalized","finalizeTime","saleStart","saleDeadline","raisedRaw","totalRaised","registryLength"],bond:["wired","enabled","startTime","marketCount"],inverse:["active","price","capacityRemaining","spreadBps"],treasury:["wired","rfv","backingPerToken","liquidUsdg","morphoAssets","polRfv","morphoCapBps","morphoVault","canonicalPair"],pteam:["wired","holder","vestedFraction","exercisableNow","exercised","strikeWad","capBps","circulatingSupply","excludedFromFloat"],rwa:["manager","halted","inventory","inventoryMax","owedNet","bHwm","deskDiscountBps","VEST","MAX_DISCOUNT_BPS","INVENTORY_HARD_CAP","menu","routerSource","sleeve"],premium:["active","clipSize","lastExecuteAt","premiumThresholdWad","router","pairContract"],tax:["wired","pendingNet","teamBps","treasuryBps","teamWallet","router","pairContract"]},T=h=>JSON.parse(JSON.stringify(h,(P,S)=>typeof S=="bigint"?S.toString():S));function g(h){return G(h,"Provide a checksummed address.",M)}var oe=h=>{async function P(t){if(typeof t!="string"||!Object.hasOwn(C,t))throw new o("Choose a published NetNet financial product.");let c=t,e=C[c],r=q[c],u=h.clientFor(y);if(await u.getChainId()!==y)throw new o("NetNet requires chain 4663.");let n=await u.getBlock(),a=(w,x=[])=>u.readContract({address:e,abi:r,functionName:w,args:x,blockNumber:n.number}),[i,s,l,p]=await Promise.all([a("net"),a("usdg"),u.readContract({address:v.address,abi:R,functionName:"decimals",blockNumber:n.number}),u.readContract({address:k.address,abi:R,functionName:"decimals",blockNumber:n.number})]);if(g(i)!==v.address||g(s)!==k.address||l!==v.decimals||p!==k.decimals)throw new o("NetNet financial token pins or decimals do not match the deployment.");return{product:c,contract:e,abi:r,rpc:u,block:n,read:a}}async function S(t){$(t);let c=(e,r)=>({module:"netnet",id:`4663:${C.bond.toLowerCase()}:${e}`,chainId:y,incomplete:!0,assets:[],description:`NetNet bond notes unreadable: ${h.plainError(r)} Use netnet_financial_status with product bond to inspect notes.`});try{let e=await P("bond"),r=U(await e.read("noteCount",[t]),"Invalid NetNet bond note count."),u=r<50n?Number(r):50,n=[];for(let a=0;a<u;a++)try{let i=await e.read("notes",[t,BigInt(a)]);if(!Array.isArray(i)||i.length!==4)throw new o("Invalid NetNet bond note.");let[s,l,p,w]=i.map(B=>U(B,"Invalid NetNet bond note amount or timestamp."));if(l>s||w<=p||w>=1n<<64n)throw new o("Invalid NetNet bond note vesting or claimed amount.");let x=s-l;if(x===0n)continue;let E=e.block.timestamp>=w?s:e.block.timestamp<=p?0n:s*(e.block.timestamp-p)/(w-p),D=E>l?E-l:0n;n.push({module:"netnet",id:`4663:${e.contract.toLowerCase()}:${a}`,chainId:y,matured:e.block.timestamp>=w,assets:[{token:v,amount:x.toString()}],description:`NetNet bond note ${a}: ${x} NET base units outstanding; ${D} claimable now, vesting ends at Unix ${w}. Redeem vested NET with netnet_financial_action product bond operation redeem. Payment cannot be withdrawn. Block ${e.block.number}.`})}catch(i){n.push(c(String(a),i))}return r>BigInt(u)&&n.push({module:"netnet",id:`4663:${e.contract.toLowerCase()}:coverage`,chainId:y,incomplete:!0,assets:[],description:`NetNet bond positions checked the first ${u} of ${r} notes. Use netnet_financial_status product bond offset ${u} to read the remaining notes.`}),n}catch(e){return[c("unreadable",e)]}}let _=(t,c,e,r)=>({name:t,inputSchema:{type:"object",properties:c,required:e,additionalProperties:!1},execute:async(u,n)=>{try{if($(n),Object.keys(u).some(a=>!Object.hasOwn(c,a)))throw new o("Unsupported NetNet financial argument.");return await r(u,n)}catch(a){throw new o(h.plainError(a))}}}),W={type:"string",enum:Object.keys(C),description:"NetNet financial product: genesis (founding sale), bond, inverse (NET buyback), treasury, pteam (team option), rwa (equity desk), premium (premium keeper) or tax (tax collector)."};return{positions:S,tools:[_("netnet_financial_status",{product:W,offset:{type:"integer",minimum:0,description:"Index of the first wallet note to return (bond and rwa products only). Default 0."},limit:{type:"integer",minimum:1,maximum:50,description:"Maximum notes to return, 1 to 50 (default 20; bond and rwa products only)."}},["product"],async(t,c)=>{let e=await P(t.product),r=V[e.product],u=t.offset??0,n=t.limit??20;if(!Number.isSafeInteger(u)||Number(u)<0||!Number.isSafeInteger(n)||Number(n)<1||Number(n)>50)throw new o("Use a nonnegative offset and limit 1..50.");let a=await Promise.all(r.map(async s=>{try{return[s,{value:T(await e.read(s))}]}catch(l){return[s,{unavailable:h.plainError(l)}]}})),i={};if(e.product==="genesis")for(let s of["purchasedRaw","purchasedNetOf","claimedNet","claimableNetOf"])i[s]=T(await e.read(s,[c]));if(e.product==="bond"||e.product==="rwa"){i.pending=T(await e.read("pendingFor",[c]));let s=await e.read("noteCount",[c]);if(typeof s!="bigint"||s<0n)throw new o("Invalid NetNet note count.");let l=s<BigInt(Number(u)+Number(n))?s:BigInt(Number(u)+Number(n));i.noteCount=s.toString(),i.notes=await Promise.all(Array.from({length:Math.max(0,Number(l-BigInt(Number(u))))},async(p,w)=>({id:String(Number(u)+w),note:T(await e.read(e.product==="bond"?"notes":"noteAt",[c,BigInt(Number(u)+w)]))}))),i.nextOffset=l<s?l.toString():null,e.product==="bond"&&(i.markets=await Promise.all([0n,1n].map(async p=>{try{return{id:p.toString(),quoteToken:g(await e.read("quoteToken",[p])),priceWad:String(await e.read("bondPrice",[p]))}}catch(w){return{id:p.toString(),unavailable:h.plainError(w)}}})))}return e.product==="treasury"&&(i.isMinter=await e.read("isMinter",[c]),i.isSpender=await e.read("isSpender",[c])),{chainId:y,contract:e.contract,product:e.product,blockNumber:String(e.block.number),tokens:[v,k],metrics:Object.fromEntries(a),wallet:i,units:"Raw token amounts use each token\u2019s decimals. Prices, NAV, reserve values and capacityRemaining use 18-decimal USDG WAD. Note timestamps are Unix seconds.",operations:O[e.product],caveat:"An unavailable metric is not zero. Formulaic eligibility, oracle liveness, caps and vesting are checked by the action preview. RWA entry/router calldata and initial deployment wiring remain unsupported."}}),_("netnet_financial_action",{product:W,operation:{type:"string",enum:[...new Set(Object.values(O).flat())],description:"Action to run; it must be one the chosen product supports, for example bond deposit or redeem, genesis purchase or claim, inverse swap."},amount:I('Amount in base units of the token the operation spends or moves: USDG has 6 decimals, NET 9 ("1000000" = 1 USDG, "1000000000" = 1 NET).'),minAmountOut:I('Least output you must receive, in base units of the output token (USDG 6 decimals, NET 9). Example: "1000000" = 1 USDG.'),maxPriceWad:I("Highest bond price you accept, as an 18-decimal wad of USDG per NET in base units (1e18 = 1 USDG). Bond deposit only."),maxPayment:I('Most USDG you will pay to exercise, in USDG base units (6 decimals). Example: "1000000" = 1 USDG. pteam exercise only.'),marketId:{type:"integer",enum:[0,1],description:"Bond market: 0 pays with USDG, 1 pays with the canonical NET/USDG LP token. Bond deposit only."},recipient:{type:"string",description:"Address that receives the minted NET or spent USDG. Treasury mintNet and spendUsdg only; use the intended address."},halted:{type:"boolean",description:"rwa setHalt only: true halts the desk, false resumes it."},token:{type:"string",description:"Address of the stray token to sweep (0x + 40 hex digits). rwa skim only."},noteIds:{type:"array",maxItems:50,description:"Bond note ids to redeem, unique decimal strings (rwa redeem only); omit to redeem every vested note.",items:I('Note id (index of the wallet note), as a decimal string. Example: "0".')},menu:{type:"array",maxItems:32,description:"Complete replacement RWA equity menu (rwa setMenu only): up to 32 entries; target weights must sum to 10000 basis points.",items:{type:"object",description:"Menu entry with token and feed addresses, targetWeightBps (10000 = 100%) and active (boolean)."}}},["product","operation"],async(t,c)=>{let e=await P(t.product),r=t.operation;if(typeof r!="string"||!O[e.product].includes(r))throw new o("This operation is not supported by the selected financial product.");let u=new Set(["product","operation"]),n=[],a,i=0n,s="",l=(...d)=>d.forEach(m=>u.add(m)),p=()=>(l("amount"),A(t.amount)),w=()=>(l("minAmountOut"),A(t.minAmountOut));if(e.product==="genesis"){if(r==="purchase"&&(i=p(),a=k,n=[i],s="Founding subscription; NET is claimable only after successful finalization and vesting. A failed sale requires refund."),r==="claim"&&await e.read("claimableNetOf",[c])===0n)throw new o("No vested founding NET is claimable by this wallet.")}else if(e.product==="bond")if(r==="deposit"){if(l("marketId","maxPriceWad"),t.marketId!==0&&t.marketId!==1)throw new o("Bond marketId must be 0 (USDG) or 1 (canonical LP).");let d=BigInt(t.marketId);if(g(await e.read("quoteToken",[d]))!==(d===0n?k.address:z))throw new o("Bond quote token is not the pinned USDG or canonical LP.");i=p(),a=d===0n?k:{address:z,decimals:18,symbol:"NET/USDG LP",chainId:y};let f=A(t.maxPriceWad),b=await e.read("bondPrice",[d]);if(typeof b!="bigint"||b===0n||b>f)throw new o("Bond price exceeds maxPriceWad or is invalid.");n=[d,i,f,c],s="Payment is exchanged for a non-transferable NET note with two-day linear vesting. Redeem vested NET with the same product; payment cannot be withdrawn."}else n=[c];else if(e.product==="inverse"){if(i=p(),a=v,n=[i,w()],s="Purchased NET is burned permanently; USDG pays directly to this wallet. Capacity is denominated in USDG WAD, not raw USDG.",await e.read("active")!==!0)throw new o("NetNet buyback is inactive: oracle, finalization or capacity is unavailable.")}else if(e.product==="pteam"){if(g(await e.read("holder"))!==N(c))throw new o("This wallet is not the immutable pTEAM holder.");let d=p();if(l("maxPayment"),d>await e.read("exercisableNow"))throw new o("The NET exercise amount exceeds the vested cap.");let m=await e.read("strikeWad");if(i=(d*m/10n**BigInt(v.decimals)+10n**12n-1n)/10n**12n,i===0n||i>A(t.maxPayment))throw new o("The exercise payment exceeds maxPayment or rounds to zero.");a=k,n=[d],s=`Exercise pays ${i} USDG base units into treasury reserves and mints ${d} NET base units to the immutable holder. No withdrawal or exercise reversal exists.`}else if(e.product==="treasury"){let d=p();if(r==="mintNet"||r==="spendUsdg"){l("recipient");let m=g(t.recipient);if(await e.read(r==="mintNet"?"isMinter":"isSpender",[c])!==!0)throw new o("This wallet lacks the fixed NetNet treasury minter/spender role.");n=[m,d],s=`Protocol treasury operation sends ${d} base units to ${m}; it does not deposit into this wallet\u2019s savings.`}else n=[d],s="Permissionless protocol reserve rebalance; assets remain owned by the NetNet treasury. The deployed fraction is constrained by the immutable cap."}else if(e.product==="rwa"){if(["depositInventory","setDiscount","setInventoryMax","setHalt","setMenu"].includes(r)&&g(await e.read("manager"))!==N(c))throw new o("This wallet lacks the immutable RWA manager role.");if(r==="redeem")if(l("noteIds"),t.noteIds===void 0)n=[c];else{if(!Array.isArray(t.noteIds)||!t.noteIds.length||t.noteIds.length>50)throw new o("Provide 1..50 unique note IDs.");let m=t.noteIds.map(b=>A(b,!0));if(new Set(m.map(String)).size!==m.length)throw new o("Note IDs must be unique.");let f=await e.read("noteCount",[c]);if(m.some(b=>b>=f))throw new o("RWA note ID is out of range.");n=[c,m]}else if(r==="setHalt"){if(l("halted"),typeof t.halted!="boolean")throw new o("Provide halted as a boolean.");n=[t.halted]}else if(r==="setMenu"){if(l("menu"),!Array.isArray(t.menu)||!t.menu.length||t.menu.length>32)throw new o("Provide 1..32 explicit RWA menu entries.");let m=t.menu.map(f=>{if(!f||typeof f!="object"||Array.isArray(f)||Object.keys(f).some(H=>!["token","feed","targetWeightBps","active"].includes(H)))throw new o("Invalid RWA menu fields.");let b=f;if(typeof b.active!="boolean")throw new o("RWA active must be boolean.");return{token:g(b.token),feed:g(b.feed),targetWeightBps:A(b.targetWeightBps,!0),active:b.active}});if(new Set(m.map(f=>f.token)).size!==m.length||m.reduce((f,b)=>f+b.targetWeightBps,0n)!==10000n||m.some(f=>f.active&&(f.token===j||f.feed===j)))throw new o("RWA menu tokens must be unique, weights sum to 10000, active feeds/tokens nonzero.");n=[m],s=`Replace the complete RWA equity menu: ${JSON.stringify(T(m))}.`}else if(r==="skim")l("token"),n=[g(t.token)],s=`Sweep eligible stray assets to sleeve ${g(await e.read("sleeve"))}, not to this wallet.`;else if(r!=="pokeHwm"){let m=p();if(n=[m],r==="depositInventory"&&(a=v,i=m,s="Inventory funding is one-way. The manager cannot withdraw these NET; they are committed to bond obligations."),r==="setDiscount"&&m>await e.read("MAX_DISCOUNT_BPS")||r==="setInventoryMax"&&m>await e.read("INVENTORY_HARD_CAP"))throw new o("RWA setting exceeds its immutable maximum.")}}else e.product==="premium"?(n=[w()],s="Permissionless mint-and-sell keeper operation; all sale proceeds go to NetNet treasury. The caller receives no reward."):(n=[p(),w()],s="Convert NET already owned by the tax collector. Proceeds split to treasury and team; the caller receives no reward and supplies no NET.");if(Object.keys(t).some(d=>!u.has(d)))throw new o("Unexpected fields for this NetNet operation.");if(a&&await e.rpc.readContract({address:a.address,abi:R,functionName:"balanceOf",args:[c],blockNumber:e.block.number})<i)throw new o(`Top up ${a.symbol}: needs ${i} base units.`);let x=`NetNet ${e.product}.${r}, contract ${e.contract}, chain ${y}, values ${JSON.stringify(T(n))}. ${a?`Approve exactly ${i} ${a.symbol} base units (${a.address}, decimals ${a.decimals}). `:""}${s}`,E=[...a?[h.approval(a.address,e.contract,i.toString(),y)]:[],h.unsignedTx({to:e.contract,data:L({abi:e.abi,functionName:r,args:n}),value:"0",chainId:y,description:x})],D=await h.preview(E,c),B=0n;for(let d of D.changes){if(!/^-?\d+$/.test(d.amount))throw new o("Invalid NetNet preview amount.");if(BigInt(d.amount)<0n&&(B-=BigInt(d.amount)),BigInt(d.amount)<0n&&(!a||d.token.chainId!==y||!F(d.token.address,a.address)||d.token.decimals!==a.decimals||-BigInt(d.amount)>i))throw new o("NetNet preview spends outside the exact input budget.")}if(B>i)throw new o("NetNet preview exceeds the aggregate input budget.");return{txs:E,preview:D,summary:x}})]}};export{C as a,z as b,oe as c};
|
|
1
|
+
import{a as q}from"./NCQFWPAW.js";import{a as v}from"./RUTSEGGD.js";import{K as A}from"./JPPQDELB.js";import{c as k}from"./QLFPAN6S.js";import{a as $}from"./43LI5NKJ.js";import{a as I}from"./66F5ZH34.js";import{d as M,g as F,i as G,m as U}from"./NWNYJ26T.js";import{b as y}from"./TI727O2H.js";import{a as o}from"./XSD5NL7J.js";import{encodeFunctionData as L,erc20Abi as R,getAddress as N,zeroAddress as j}from"viem";var C={genesis:N("0x575b7B7c97Ef3E21C82DAeB427899d583e1E913f"),bond:N("0xff32a969A0c567129eECD926D04657728E1980C1"),inverse:N("0x92166e94Eea5B7799b761653881692f881dFC4C9"),treasury:N("0x04822Ea321A0DEE6F40656172F29312104855d66"),pteam:N("0x650F58079dAa17ee28928c2F92d22291d038B2B0"),rwa:N("0x99B6eE6eDe47d9a8a9bfd03F728a99B789df1961"),premium:N("0x346e1a31171A0f7aC73909010b5435768d3B5462"),tax:N("0x086C58400b8708Ef993f256E12e752dcF0AC918e")},z=N("0x59F95461E68e0c77605299791E1449f175165B54"),O={genesis:["purchase","finalize","refund","claim"],bond:["deposit","redeem"],inverse:["swap"],treasury:["rebalanceToMorpho","rebalanceFromMorpho","mintNet","spendUsdg"],pteam:["exercise"],rwa:["redeem","depositInventory","pokeHwm","setDiscount","setInventoryMax","setHalt","setMenu","skim"],premium:["execute"],tax:["convert"]},V={genesis:["wired","finalized","finalizeTime","saleStart","saleDeadline","raisedRaw","totalRaised","registryLength"],bond:["wired","enabled","startTime","marketCount"],inverse:["active","price","capacityRemaining","spreadBps"],treasury:["wired","rfv","backingPerToken","liquidUsdg","morphoAssets","polRfv","morphoCapBps","morphoVault","canonicalPair"],pteam:["wired","holder","vestedFraction","exercisableNow","exercised","strikeWad","capBps","circulatingSupply","excludedFromFloat"],rwa:["manager","halted","inventory","inventoryMax","owedNet","bHwm","deskDiscountBps","VEST","MAX_DISCOUNT_BPS","INVENTORY_HARD_CAP","menu","routerSource","sleeve"],premium:["active","clipSize","lastExecuteAt","premiumThresholdWad","router","pairContract"],tax:["wired","pendingNet","teamBps","treasuryBps","teamWallet","router","pairContract"]},T=h=>JSON.parse(JSON.stringify(h,(P,S)=>typeof S=="bigint"?S.toString():S));function g(h){return G(h,"Provide a checksummed address.",M)}var oe=h=>{async function P(t){if(typeof t!="string"||!Object.hasOwn(C,t))throw new o("Choose a published NetNet financial product.");let c=t,e=C[c],r=q[c],u=h.clientFor(y);if(await u.getChainId()!==y)throw new o("NetNet requires chain 4663.");let n=await u.getBlock(),a=(w,x=[])=>u.readContract({address:e,abi:r,functionName:w,args:x,blockNumber:n.number}),[i,s,l,p]=await Promise.all([a("net"),a("usdg"),u.readContract({address:v.address,abi:R,functionName:"decimals",blockNumber:n.number}),u.readContract({address:k.address,abi:R,functionName:"decimals",blockNumber:n.number})]);if(g(i)!==v.address||g(s)!==k.address||l!==v.decimals||p!==k.decimals)throw new o("NetNet financial token pins or decimals do not match the deployment.");return{product:c,contract:e,abi:r,rpc:u,block:n,read:a}}async function S(t){$(t);let c=(e,r)=>({module:"netnet",id:`4663:${C.bond.toLowerCase()}:${e}`,chainId:y,incomplete:!0,assets:[],description:`NetNet bond notes unreadable: ${h.plainError(r)} Use netnet_financial_status with product bond to inspect notes.`});try{let e=await P("bond"),r=U(await e.read("noteCount",[t]),"Invalid NetNet bond note count."),u=r<50n?Number(r):50,n=[];for(let a=0;a<u;a++)try{let i=await e.read("notes",[t,BigInt(a)]);if(!Array.isArray(i)||i.length!==4)throw new o("Invalid NetNet bond note.");let[s,l,p,w]=i.map(B=>U(B,"Invalid NetNet bond note amount or timestamp."));if(l>s||w<=p||w>=1n<<64n)throw new o("Invalid NetNet bond note vesting or claimed amount.");let x=s-l;if(x===0n)continue;let E=e.block.timestamp>=w?s:e.block.timestamp<=p?0n:s*(e.block.timestamp-p)/(w-p),D=E>l?E-l:0n;n.push({module:"netnet",id:`4663:${e.contract.toLowerCase()}:${a}`,chainId:y,matured:e.block.timestamp>=w,assets:[{token:v,amount:x.toString()}],description:`NetNet bond note ${a}: ${x} NET base units outstanding; ${D} claimable now, vesting ends at Unix ${w}. Redeem vested NET with netnet_financial_action product bond operation redeem. Payment cannot be withdrawn. Block ${e.block.number}.`})}catch(i){n.push(c(String(a),i))}return r>BigInt(u)&&n.push({module:"netnet",id:`4663:${e.contract.toLowerCase()}:coverage`,chainId:y,incomplete:!0,assets:[],description:`NetNet bond positions checked the first ${u} of ${r} notes. Use netnet_financial_status product bond offset ${u} to read the remaining notes.`}),n}catch(e){return[c("unreadable",e)]}}let _=(t,c,e,r)=>({name:t,inputSchema:{type:"object",properties:c,required:e,additionalProperties:!1},execute:async(u,n)=>{try{if($(n),Object.keys(u).some(a=>!Object.hasOwn(c,a)))throw new o("Unsupported NetNet financial argument.");return await r(u,n)}catch(a){throw new o(h.plainError(a))}}}),W={type:"string",enum:Object.keys(C),description:"NetNet financial product: genesis (founding sale), bond, inverse (NET buyback), treasury, pteam (team option), rwa (equity desk), premium (premium keeper) or tax (tax collector)."};return{positions:S,tools:[_("netnet_financial_status",{product:W,offset:{type:"integer",minimum:0,description:"Index of the first wallet note to return (bond and rwa products only). Default 0."},limit:{type:"integer",minimum:1,maximum:50,description:"Maximum notes to return, 1 to 50 (default 20; bond and rwa products only)."}},["product"],async(t,c)=>{let e=await P(t.product),r=V[e.product],u=t.offset??0,n=t.limit??20;if(!Number.isSafeInteger(u)||Number(u)<0||!Number.isSafeInteger(n)||Number(n)<1||Number(n)>50)throw new o("Use a nonnegative offset and limit 1..50.");let a=await Promise.all(r.map(async s=>{try{return[s,{value:T(await e.read(s))}]}catch(l){return[s,{unavailable:h.plainError(l)}]}})),i={};if(e.product==="genesis")for(let s of["purchasedRaw","purchasedNetOf","claimedNet","claimableNetOf"])i[s]=T(await e.read(s,[c]));if(e.product==="bond"||e.product==="rwa"){i.pending=T(await e.read("pendingFor",[c]));let s=await e.read("noteCount",[c]);if(typeof s!="bigint"||s<0n)throw new o("Invalid NetNet note count.");let l=s<BigInt(Number(u)+Number(n))?s:BigInt(Number(u)+Number(n));i.noteCount=s.toString(),i.notes=await Promise.all(Array.from({length:Math.max(0,Number(l-BigInt(Number(u))))},async(p,w)=>({id:String(Number(u)+w),note:T(await e.read(e.product==="bond"?"notes":"noteAt",[c,BigInt(Number(u)+w)]))}))),i.nextOffset=l<s?l.toString():null,e.product==="bond"&&(i.markets=await Promise.all([0n,1n].map(async p=>{try{return{id:p.toString(),quoteToken:g(await e.read("quoteToken",[p])),priceWad:String(await e.read("bondPrice",[p]))}}catch(w){return{id:p.toString(),unavailable:h.plainError(w)}}})))}return e.product==="treasury"&&(i.isMinter=await e.read("isMinter",[c]),i.isSpender=await e.read("isSpender",[c])),{chainId:y,contract:e.contract,product:e.product,blockNumber:String(e.block.number),tokens:[v,k],metrics:Object.fromEntries(a),wallet:i,units:"Raw token amounts use each token\u2019s decimals. Prices, NAV, reserve values and capacityRemaining use 18-decimal USDG WAD. Note timestamps are Unix seconds.",operations:O[e.product],caveat:"An unavailable metric is not zero. Formulaic eligibility, oracle liveness, caps and vesting are checked by the action preview. RWA entry/router calldata and initial deployment wiring remain unsupported."}}),_("netnet_financial_action",{product:W,operation:{type:"string",enum:[...new Set(Object.values(O).flat())],description:"Action to run; it must be one the chosen product supports, for example bond deposit or redeem, genesis purchase or claim, inverse swap."},amount:I('Amount in base units of the token the operation spends or moves: USDG has 6 decimals, NET 9 ("1000000" = 1 USDG, "1000000000" = 1 NET).'),minAmountOut:I('Least output you must receive, in base units of the output token (USDG 6 decimals, NET 9). Example: "1000000" = 1 USDG.'),maxPriceWad:I("Highest bond price you accept, as an 18-decimal wad of USDG per NET in base units (1e18 = 1 USDG). Bond deposit only."),maxPayment:I('Most USDG you will pay to exercise, in USDG base units (6 decimals). Example: "1000000" = 1 USDG. pteam exercise only.'),marketId:{type:"integer",enum:[0,1],description:"Bond market: 0 pays with USDG, 1 pays with the canonical NET/USDG LP token. Bond deposit only."},recipient:{type:"string",description:"Address that receives the minted NET or spent USDG. Treasury mintNet and spendUsdg only; use the intended address."},halted:{type:"boolean",description:"rwa setHalt only: true halts the desk, false resumes it."},token:{type:"string",description:"Address of the stray token to sweep (0x + 40 hex digits). rwa skim only."},noteIds:{type:"array",maxItems:50,description:"Bond note ids to redeem, unique decimal strings (rwa redeem only); omit to redeem every vested note.",items:I('Note id (index of the wallet note), as a decimal string. Example: "0".')},menu:{type:"array",maxItems:32,description:"Complete replacement RWA equity menu (rwa setMenu only): up to 32 entries; target weights must sum to 10000 basis points.",items:{type:"object",description:"Menu entry with token and feed addresses, targetWeightBps (10000 = 100%) and active (boolean)."}}},["product","operation"],async(t,c)=>{let e=await P(t.product),r=t.operation;if(typeof r!="string"||!O[e.product].includes(r))throw new o("This operation is not supported by the selected financial product.");let u=new Set(["product","operation"]),n=[],a,i=0n,s="",l=(...d)=>d.forEach(m=>u.add(m)),p=()=>(l("amount"),A(t.amount)),w=()=>(l("minAmountOut"),A(t.minAmountOut));if(e.product==="genesis"){if(r==="purchase"&&(i=p(),a=k,n=[i],s="Founding subscription; NET is claimable only after successful finalization and vesting. A failed sale requires refund."),r==="claim"&&await e.read("claimableNetOf",[c])===0n)throw new o("No vested founding NET is claimable by this wallet.")}else if(e.product==="bond")if(r==="deposit"){if(l("marketId","maxPriceWad"),t.marketId!==0&&t.marketId!==1)throw new o("Bond marketId must be 0 (USDG) or 1 (canonical LP).");let d=BigInt(t.marketId);if(g(await e.read("quoteToken",[d]))!==(d===0n?k.address:z))throw new o("Bond quote token is not the pinned USDG or canonical LP.");i=p(),a=d===0n?k:{address:z,decimals:18,symbol:"NET/USDG LP",chainId:y};let f=A(t.maxPriceWad),b=await e.read("bondPrice",[d]);if(typeof b!="bigint"||b===0n||b>f)throw new o("Bond price exceeds maxPriceWad or is invalid.");n=[d,i,f,c],s="Payment is exchanged for a non-transferable NET note with two-day linear vesting. Redeem vested NET with the same product; payment cannot be withdrawn."}else n=[c];else if(e.product==="inverse"){if(i=p(),a=v,n=[i,w()],s="Purchased NET is burned permanently; USDG pays directly to this wallet. Capacity is denominated in USDG WAD, not raw USDG.",await e.read("active")!==!0)throw new o("NetNet buyback is inactive: oracle, finalization or capacity is unavailable.")}else if(e.product==="pteam"){if(g(await e.read("holder"))!==N(c))throw new o("This wallet is not the immutable pTEAM holder.");let d=p();if(l("maxPayment"),d>await e.read("exercisableNow"))throw new o("The NET exercise amount exceeds the vested cap.");let m=await e.read("strikeWad");if(i=(d*m/10n**BigInt(v.decimals)+10n**12n-1n)/10n**12n,i===0n||i>A(t.maxPayment))throw new o("The exercise payment exceeds maxPayment or rounds to zero.");a=k,n=[d],s=`Exercise pays ${i} USDG base units into treasury reserves and mints ${d} NET base units to the immutable holder. No withdrawal or exercise reversal exists.`}else if(e.product==="treasury"){let d=p();if(r==="mintNet"||r==="spendUsdg"){l("recipient");let m=g(t.recipient);if(await e.read(r==="mintNet"?"isMinter":"isSpender",[c])!==!0)throw new o("This wallet lacks the fixed NetNet treasury minter/spender role.");n=[m,d],s=`Protocol treasury operation sends ${d} base units to ${m}; it does not deposit into this wallet\u2019s savings.`}else n=[d],s="Permissionless protocol reserve rebalance; assets remain owned by the NetNet treasury. The deployed fraction is constrained by the immutable cap."}else if(e.product==="rwa"){if(["depositInventory","setDiscount","setInventoryMax","setHalt","setMenu"].includes(r)&&g(await e.read("manager"))!==N(c))throw new o("This wallet lacks the immutable RWA manager role.");if(r==="redeem")if(l("noteIds"),t.noteIds===void 0)n=[c];else{if(!Array.isArray(t.noteIds)||!t.noteIds.length||t.noteIds.length>50)throw new o("Provide 1..50 unique note IDs.");let m=t.noteIds.map(b=>A(b,!0));if(new Set(m.map(String)).size!==m.length)throw new o("Note IDs must be unique.");let f=await e.read("noteCount",[c]);if(m.some(b=>b>=f))throw new o("RWA note ID is out of range.");n=[c,m]}else if(r==="setHalt"){if(l("halted"),typeof t.halted!="boolean")throw new o("Provide halted as a boolean.");n=[t.halted]}else if(r==="setMenu"){if(l("menu"),!Array.isArray(t.menu)||!t.menu.length||t.menu.length>32)throw new o("Provide 1..32 explicit RWA menu entries.");let m=t.menu.map(f=>{if(!f||typeof f!="object"||Array.isArray(f)||Object.keys(f).some(H=>!["token","feed","targetWeightBps","active"].includes(H)))throw new o("Invalid RWA menu fields.");let b=f;if(typeof b.active!="boolean")throw new o("RWA active must be boolean.");return{token:g(b.token),feed:g(b.feed),targetWeightBps:A(b.targetWeightBps,!0),active:b.active}});if(new Set(m.map(f=>f.token)).size!==m.length||m.reduce((f,b)=>f+b.targetWeightBps,0n)!==10000n||m.some(f=>f.active&&(f.token===j||f.feed===j)))throw new o("RWA menu tokens must be unique, weights sum to 10000, active feeds/tokens nonzero.");n=[m],s=`Replace the complete RWA equity menu: ${JSON.stringify(T(m))}.`}else if(r==="skim")l("token"),n=[g(t.token)],s=`Sweep eligible stray assets to sleeve ${g(await e.read("sleeve"))}, not to this wallet.`;else if(r!=="pokeHwm"){let m=p();if(n=[m],r==="depositInventory"&&(a=v,i=m,s="Inventory funding is one-way. The manager cannot withdraw these NET; they are committed to bond obligations."),r==="setDiscount"&&m>await e.read("MAX_DISCOUNT_BPS")||r==="setInventoryMax"&&m>await e.read("INVENTORY_HARD_CAP"))throw new o("RWA setting exceeds its immutable maximum.")}}else e.product==="premium"?(n=[w()],s="Permissionless mint-and-sell keeper operation; all sale proceeds go to NetNet treasury. The caller receives no reward."):(n=[p(),w()],s="Convert NET already owned by the tax collector. Proceeds split to treasury and team; the caller receives no reward and supplies no NET.");if(Object.keys(t).some(d=>!u.has(d)))throw new o("Unexpected fields for this NetNet operation.");if(a&&await e.rpc.readContract({address:a.address,abi:R,functionName:"balanceOf",args:[c],blockNumber:e.block.number})<i)throw new o(`Top up ${a.symbol}: needs ${i} base units.`);let x=`NetNet ${e.product}.${r}, contract ${e.contract}, chain ${y}, values ${JSON.stringify(T(n))}. ${a?`Approve exactly ${i} ${a.symbol} base units (${a.address}, decimals ${a.decimals}). `:""}${s}`,E=[...a?[h.approval(a.address,e.contract,i.toString(),y)]:[],h.unsignedTx({to:e.contract,data:L({abi:e.abi,functionName:r,args:n}),value:"0",chainId:y,description:x})],D=await h.preview(E,c),B=0n;for(let d of D.changes){if(!/^-?\d+$/.test(d.amount))throw new o("Invalid NetNet preview amount.");if(BigInt(d.amount)<0n&&(B-=BigInt(d.amount)),BigInt(d.amount)<0n&&(!a||d.token.chainId!==y||!F(d.token.address,a.address)||d.token.decimals!==a.decimals||-BigInt(d.amount)>i))throw new o("NetNet preview spends outside the exact input budget.")}if(B>i)throw new o("NetNet preview exceeds the aggregate input budget.");return{txs:E,preview:D,summary:x}})]}};export{C as a,z as b,oe as c};
|