@oakagentkit/core 0.2.2 → 0.2.4
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 +112 -0
- package/build/dist/api/addresses.js +1 -1
- package/build/dist/api/amounts.js +1 -1
- package/build/dist/api/args.js +1 -1
- package/build/dist/api/cache.js +1 -1
- package/build/dist/api/canonical.js +1 -1
- package/build/dist/api/chain.js +1 -1
- package/build/dist/api/deployments.js +1 -1
- package/build/dist/api/errors.d.ts +1 -0
- package/build/dist/api/errors.js +1 -1
- package/build/dist/api/gas.js +1 -1
- package/build/dist/api/grandfather.js +1 -1
- package/build/dist/api/guards.js +1 -1
- package/build/dist/api/history.js +1 -1
- package/build/dist/api/http.js +1 -1
- package/build/dist/api/identity-link.d.ts +1 -0
- package/build/dist/api/identity-link.js +1 -1
- package/build/dist/api/launch.js +1 -1
- package/build/dist/api/merkle.js +1 -1
- package/build/dist/api/metadata.js +1 -1
- package/build/dist/api/module.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/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 +114 -0
- package/build/dist/api/modules/earn/copy.js +1 -0
- package/build/dist/api/modules/earn/cost.d.ts +47 -0
- package/build/dist/api/modules/earn/cost.js +1 -0
- package/build/dist/api/modules/earn/index.d.ts +8 -0
- package/build/dist/api/modules/earn/index.js +1 -0
- package/build/dist/api/modules/earn/lp.d.ts +17 -0
- package/build/dist/api/modules/earn/lp.js +1 -0
- package/build/dist/api/modules/earn/options.d.ts +36 -0
- package/build/dist/api/modules/earn/options.js +1 -0
- package/build/dist/api/modules/earn/types.d.ts +39 -0
- package/build/dist/api/modules/earn/types.js +0 -0
- package/build/dist/api/modules/erc8004/abi.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/validation.js +1 -1
- package/build/dist/api/modules/grove/index.js +1 -1
- package/build/dist/api/modules/heyresearch/backoff.js +1 -1
- package/build/dist/api/modules/heyresearch/builder-feed.js +1 -1
- package/build/dist/api/modules/heyresearch/freshness.js +1 -1
- package/build/dist/api/modules/heyresearch/index.js +1 -1
- package/build/dist/api/modules/heyresearch/proof-reads.js +1 -1
- package/build/dist/api/modules/heyresearch/public-reads.js +1 -1
- package/build/dist/api/modules/heyresearch/scan.js +1 -1
- package/build/dist/api/modules/heyresearch/status-labels.d.ts +1 -1
- package/build/dist/api/modules/heyresearch/status-labels.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.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.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-profile.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/pins.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.js +1 -1
- package/build/dist/api/modules/kyberswap/source-pools.js +1 -1
- package/build/dist/api/modules/layerbank/abi.d.ts +165 -0
- package/build/dist/api/modules/layerbank/abi.js +1 -0
- package/build/dist/api/modules/layerbank/actions.d.ts +2 -0
- package/build/dist/api/modules/layerbank/actions.js +1 -0
- package/build/dist/api/modules/layerbank/checks.d.ts +21 -0
- package/build/dist/api/modules/layerbank/checks.js +1 -0
- package/build/dist/api/modules/layerbank/index.d.ts +2 -0
- package/build/dist/api/modules/layerbank/index.js +1 -0
- package/build/dist/api/modules/layerbank/merkl.d.ts +6 -0
- package/build/dist/api/modules/layerbank/merkl.js +1 -0
- package/build/dist/api/modules/layerbank/reader.d.ts +15 -0
- package/build/dist/api/modules/layerbank/reader.js +1 -0
- package/build/dist/api/modules/layerbank/reserve.d.ts +13 -0
- package/build/dist/api/modules/layerbank/reserve.js +1 -0
- 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/perps-batch.js +1 -1
- package/build/dist/api/modules/meridian/perps-common.js +1 -1
- package/build/dist/api/modules/meridian/perps-guards.js +1 -1
- package/build/dist/api/modules/meridian/perps-intents.js +1 -1
- package/build/dist/api/modules/meridian/perps-stream.js +1 -1
- package/build/dist/api/modules/meridian/perps.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-abi.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-abi.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/surface.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/blackjack-hashes.js +1 -1
- package/build/dist/api/modules/netnet/card-abi.js +1 -1
- package/build/dist/api/modules/netnet/card-plan.js +1 -1
- 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-abi.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/desk-registry.js +1 -1
- package/build/dist/api/modules/netnet/financial-abi.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/gateway.js +1 -1
- package/build/dist/api/modules/orbio/index.js +1 -1
- package/build/dist/api/modules/orbio/pins.js +1 -1
- package/build/dist/api/modules/orbio/positions.d.ts +2 -0
- package/build/dist/api/modules/orbio/positions.js +1 -0
- package/build/dist/api/modules/pendle/abi.d.ts +205 -0
- package/build/dist/api/modules/pendle/abi.js +1 -0
- package/build/dist/api/modules/pendle/convert.d.ts +24 -0
- package/build/dist/api/modules/pendle/convert.js +1 -0
- package/build/dist/api/modules/pendle/costs.d.ts +3 -0
- package/build/dist/api/modules/pendle/costs.js +1 -0
- package/build/dist/api/modules/pendle/index.d.ts +11 -0
- package/build/dist/api/modules/pendle/index.js +1 -0
- package/build/dist/api/modules/pendle/markets.d.ts +37 -0
- package/build/dist/api/modules/pendle/markets.js +1 -0
- package/build/dist/api/modules/pendle/positions.d.ts +18 -0
- package/build/dist/api/modules/pendle/positions.js +1 -0
- package/build/dist/api/modules/pendle/pricecheck.d.ts +95 -0
- package/build/dist/api/modules/pendle/pricecheck.js +1 -0
- package/build/dist/api/modules/pendle/reader.d.ts +17 -0
- package/build/dist/api/modules/pendle/reader.js +1 -0
- package/build/dist/api/modules/pendle/redeem.d.ts +15 -0
- package/build/dist/api/modules/pendle/redeem.js +1 -0
- package/build/dist/api/modules/pendle/trade.d.ts +2 -0
- package/build/dist/api/modules/pendle/trade.js +1 -0
- package/build/dist/api/modules/pendle/types.d.ts +26 -0
- package/build/dist/api/modules/pendle/types.js +0 -0
- package/build/dist/api/modules/pendle/validate.d.ts +424 -0
- package/build/dist/api/modules/pendle/validate.js +1 -0
- package/build/dist/api/modules/pendle/verify.d.ts +22 -0
- package/build/dist/api/modules/pendle/verify.js +1 -0
- package/build/dist/api/modules/pons/claim.js +1 -1
- package/build/dist/api/modules/pons/holder-directory.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.d.ts +38 -2
- 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.d.ts +4 -0
- package/build/dist/api/modules/priors/holdings.js +1 -0
- 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/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/share-symbol.d.ts +3 -0
- package/build/dist/api/modules/steakhouse/share-symbol.js +1 -0
- 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/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.d.ts +1 -0
- 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/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/license.js +1 -1
- package/build/dist/api/modules/wormhole/quotetext.js +1 -1
- package/build/dist/api/modules/wormhole/scan-text.js +1 -1
- package/build/dist/api/modules/wormhole/token-check.js +1 -1
- package/build/dist/api/owner-signature.js +1 -1
- package/build/dist/api/positions.d.ts +5 -5
- 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/reads.js +1 -1
- package/build/dist/api/routes.js +1 -1
- package/build/dist/api/rpc.js +1 -1
- 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/token-output.js +1 -1
- package/build/dist/api/tokens.js +1 -1
- package/build/dist/api/tool-policy.js +1 -1
- package/build/dist/api/tx.js +1 -1
- package/build/dist/api/types.d.ts +7 -2
- package/build/dist/api/untrusted.js +1 -1
- package/build/dist/api/vendor-limits.js +1 -1
- package/build/dist/chunks/{7YU6DELJ.js → 24CQ2SPB.js} +1 -1
- package/build/dist/chunks/2DUCTO5C.js +1 -0
- package/build/dist/chunks/2MZXTOZU.js +1 -0
- package/build/dist/chunks/2OJAOVMG.js +1 -0
- package/build/dist/chunks/2ZUP7ZEV.js +1 -0
- package/build/dist/chunks/{DHOBTJRD.js → 3AXVB23N.js} +1 -1
- package/build/dist/chunks/3ESNHZT5.js +1 -0
- package/build/dist/chunks/{GIV5JMTE.js → 3VAJW6TQ.js} +1 -1
- package/build/dist/chunks/{ALK6NKFP.js → 3WXK2FUA.js} +1 -1
- package/build/dist/chunks/{TQL7UDFL.js → 42DQTKEO.js} +1 -1
- package/build/dist/chunks/{E7R3J4H7.js → 43CSMYDO.js} +1 -1
- package/build/dist/chunks/46547QT3.js +1 -0
- package/build/dist/chunks/{XV2HQKND.js → 47YN4OUI.js} +1 -1
- package/build/dist/chunks/{S3HNPTXA.js → 4ALMYJJV.js} +1 -1
- package/build/dist/chunks/{SOYQOE5P.js → 4BVP652W.js} +1 -1
- package/build/dist/chunks/{JNZZLA2A.js → 4ISR2U72.js} +1 -1
- package/build/dist/chunks/{AAGDMH54.js → 4TQQH7N6.js} +1 -1
- package/build/dist/chunks/{WTSMPDT5.js → 4YFVAYKR.js} +1 -1
- package/build/dist/chunks/{PTAWEHKB.js → 57JFKIMK.js} +1 -1
- package/build/dist/chunks/{3RFSGU2Y.js → 5CAAFU7R.js} +1 -1
- package/build/dist/chunks/{73N3TOJL.js → 5KUWLUPM.js} +1 -1
- package/build/dist/chunks/{SKQGLGES.js → 5MQ5KSSV.js} +1 -1
- package/build/dist/chunks/{AJP5LDM2.js → 5N4A5XAW.js} +1 -1
- package/build/dist/chunks/{OQVZVR2S.js → 5OKJEGBH.js} +1 -1
- package/build/dist/chunks/5U7TCKX2.js +2 -0
- package/build/dist/chunks/5WUKOQIJ.js +1 -0
- package/build/dist/chunks/5ZLOCQA4.js +1 -0
- package/build/dist/chunks/63YRSLDK.js +1 -0
- package/build/dist/chunks/64WKYWZV.js +1 -0
- package/build/dist/chunks/{JPOYTTTW.js → 65EQECL3.js} +1 -1
- package/build/dist/chunks/{57HAXNQV.js → 6AAARNZ3.js} +1 -1
- package/build/dist/chunks/6FTYNYGF.js +1 -0
- package/build/dist/chunks/{L7YBCMZU.js → 6L5KTE6Y.js} +1 -1
- package/build/dist/chunks/{53N7PNJH.js → 6PY3IRDS.js} +1 -1
- package/build/dist/chunks/{5VHH5PW3.js → 6YYCGUCU.js} +1 -1
- package/build/dist/chunks/{UNZRE3YU.js → 7UOOIDR3.js} +1 -1
- package/build/dist/chunks/{LQUDJCAR.js → 7WQEPZJY.js} +1 -1
- package/build/dist/chunks/A3PN3PK3.js +1 -0
- package/build/dist/chunks/A6YQ5H24.js +1 -0
- package/build/dist/chunks/{CXLEQCP3.js → ABPL3ZZI.js} +1 -1
- package/build/dist/chunks/{R7FXNZRM.js → AG67Z3SC.js} +1 -1
- package/build/dist/chunks/{BX7XQANB.js → ALPYEM7B.js} +1 -1
- package/build/dist/chunks/{OE3CLZHR.js → ALRRW7SF.js} +1 -1
- package/build/dist/chunks/AUOXDNUO.js +7 -0
- package/build/dist/chunks/AWXJV2YH.js +1 -0
- package/build/dist/chunks/{66VBACC2.js → BAAXGB4K.js} +1 -1
- package/build/dist/chunks/{R53P2K3C.js → BIRMUW7Z.js} +1 -1
- package/build/dist/chunks/{EA6IYKIB.js → BK23XJXE.js} +1 -1
- package/build/dist/chunks/{NATG6YA6.js → BNG2IWZL.js} +1 -1
- package/build/dist/chunks/BQICZFLR.js +1 -0
- package/build/dist/chunks/{Y2KH6DCE.js → BXHNYCH2.js} +1 -1
- package/build/dist/chunks/{L62M7LOB.js → C5ZZAYXD.js} +1 -1
- package/build/dist/chunks/{52DHGSG4.js → CERNEJ2F.js} +1 -1
- package/build/dist/chunks/{EPZ7SWKM.js → CTMA4BTM.js} +1 -1
- package/build/dist/chunks/{QXNPPCOU.js → D6ZJPNK7.js} +1 -1
- package/build/dist/chunks/DFM4T6ZE.js +1 -0
- package/build/dist/chunks/{SJPM5ST4.js → DP2NIYBP.js} +1 -1
- package/build/dist/chunks/DVVFT42J.js +1 -0
- package/build/dist/chunks/E3UBHTJO.js +1 -0
- package/build/dist/chunks/E6RRXNV2.js +1 -0
- package/build/dist/chunks/{ZT47KN7A.js → E6UU7DL2.js} +1 -1
- package/build/dist/chunks/ECWGKLBW.js +1 -0
- package/build/dist/chunks/EKNSLLJK.js +1 -0
- package/build/dist/chunks/{XWEFKXKA.js → ENX72ARB.js} +1 -1
- package/build/dist/chunks/{DRWWPBOQ.js → EOQYLFXA.js} +1 -1
- package/build/dist/chunks/{ELZNT5Q3.js → ET23SES4.js} +1 -1
- package/build/dist/chunks/EU3OAJU2.js +1 -0
- package/build/dist/chunks/{2W46IRX6.js → EYFBVQ46.js} +1 -1
- package/build/dist/chunks/{VXLJRRKV.js → F26FK47J.js} +1 -1
- package/build/dist/chunks/{MFNP4KOK.js → F3BSEE52.js} +1 -1
- package/build/dist/chunks/FWD4L3CJ.js +1 -0
- package/build/dist/chunks/G7XSFUDL.js +1 -0
- package/build/dist/chunks/{5O5ZE3ZV.js → GHPREYQK.js} +1 -1
- package/build/dist/chunks/{AFHHRDPJ.js → GRIGSPD4.js} +1 -1
- package/build/dist/chunks/{J2XAEVKC.js → GVPX5XCL.js} +1 -1
- package/build/dist/chunks/{TLJPVYRJ.js → GW5IXLKU.js} +1 -1
- package/build/dist/chunks/H4NYYJ3Z.js +1 -0
- package/build/dist/chunks/{J3GFCBZZ.js → HSFOWJ3Z.js} +1 -1
- package/build/dist/chunks/{CY75R4FK.js → HTXKERNS.js} +1 -1
- package/build/dist/chunks/{6ZYLNB2B.js → HVM2EEXB.js} +1 -1
- package/build/dist/chunks/{U3F6DDML.js → I4TGMF2C.js} +1 -1
- package/build/dist/chunks/I6KUORFT.js +1 -0
- package/build/dist/chunks/{AMICUXS6.js → IKEJCBYU.js} +1 -1
- package/build/dist/chunks/IMRXZ7JB.js +1 -0
- package/build/dist/chunks/IQGY5FW7.js +1 -0
- package/build/dist/chunks/{L3ZM77SJ.js → IQIWASRD.js} +1 -1
- package/build/dist/chunks/JG27HM4P.js +1 -0
- package/build/dist/chunks/{V5LTA42G.js → JPNYUEQP.js} +1 -1
- package/build/dist/chunks/JZXYLHI7.js +1 -0
- package/build/dist/chunks/{QYYFRAWY.js → K22EXPWN.js} +1 -1
- package/build/dist/chunks/K72EYD6R.js +1 -0
- package/build/dist/chunks/KA7BPBCV.js +2 -0
- package/build/dist/chunks/KBKK7UNY.js +1 -0
- package/build/dist/chunks/{LBEMCOND.js → KBXU7U6Q.js} +1 -1
- package/build/dist/chunks/L6D26AMO.js +1 -0
- package/build/dist/chunks/{GGUEKSR4.js → L7OQUHM5.js} +1 -1
- package/build/dist/chunks/{F6WBPPBN.js → LDT3QTSY.js} +1 -1
- package/build/dist/chunks/{ZUG6MG46.js → LROVANUR.js} +1 -1
- package/build/dist/chunks/{WWFOYZT2.js → LVLVP5KQ.js} +1 -1
- package/build/dist/chunks/MBTARLZQ.js +1 -0
- package/build/dist/chunks/{SSTROLQM.js → MDDHG34Y.js} +1 -1
- package/build/dist/chunks/{OVK4EEOD.js → MDV7GECM.js} +1 -1
- package/build/dist/chunks/{DCTUYDWF.js → MFCPL6LF.js} +1 -1
- package/build/dist/chunks/MGPHD4VV.js +1 -0
- package/build/dist/chunks/{VC2RCYQE.js → MKAPRRKF.js} +1 -1
- package/build/dist/chunks/{FBSUTF3B.js → MKBNLGDD.js} +1 -1
- package/build/dist/chunks/{NRBIXV7V.js → MOPETB64.js} +1 -1
- package/build/dist/chunks/{ACN2BFMA.js → MQK6OP7S.js} +1 -1
- package/build/dist/chunks/{TWCSCRFS.js → MQYOG66Q.js} +1 -1
- package/build/dist/chunks/{2UU5TBBB.js → MXW2TP5P.js} +1 -1
- package/build/dist/chunks/MYFAKCQI.js +1 -0
- package/build/dist/chunks/{MKQVS3IO.js → NA7R6J5N.js} +1 -1
- package/build/dist/chunks/NB3LYS3G.js +1 -0
- package/build/dist/chunks/{TNSKEHPC.js → NDW5DAFL.js} +1 -1
- package/build/dist/chunks/{MRWCFTMS.js → NKX3FE34.js} +1 -1
- package/build/dist/chunks/NYNJITCM.js +1 -0
- package/build/dist/chunks/{YZSTP2E6.js → NZXQWDGF.js} +1 -1
- package/build/dist/chunks/{Z7RL4NGX.js → O6L4BJP4.js} +1 -1
- package/build/dist/chunks/{KSZMMNXK.js → OFI3Y55L.js} +1 -1
- package/build/dist/chunks/{2LM7U4S7.js → OTIXQZ3X.js} +1 -1
- package/build/dist/chunks/{WCKMQFGS.js → PADWZX7J.js} +1 -1
- package/build/dist/chunks/{6IM6A5VA.js → PBQSJSZO.js} +1 -1
- package/build/dist/chunks/PLZKXQ76.js +1 -0
- package/build/dist/chunks/{TFVWAYHY.js → PQC5635W.js} +1 -1
- package/build/dist/chunks/PSVOVZH7.js +70 -0
- package/build/dist/chunks/{PWBL4WKB.js → PWH464CJ.js} +1 -1
- package/build/dist/chunks/QJFXLYZG.js +1 -0
- package/build/dist/chunks/{4KQZTPMS.js → QRC4ZPDA.js} +1 -1
- package/build/dist/chunks/{4AKIXLXH.js → QSN6Y2K6.js} +1 -1
- package/build/dist/chunks/{C3TJLARP.js → QVYCJ6WV.js} +1 -1
- package/build/dist/chunks/{WVXW6VL3.js → RNC463IM.js} +1 -1
- package/build/dist/chunks/RPNAFUM5.js +1 -0
- package/build/dist/chunks/RVO3QK2B.js +1 -0
- package/build/dist/chunks/{FUXT7GRK.js → S2TAJHHK.js} +1 -1
- package/build/dist/chunks/{YHPOXAKA.js → S3FPF537.js} +1 -1
- package/build/dist/chunks/{H4S2ZCWK.js → S5WICHIS.js} +1 -1
- package/build/dist/chunks/SDHPFXRM.js +1 -0
- package/build/dist/chunks/{3NDVXEBR.js → SGEZIYJW.js} +1 -1
- package/build/dist/chunks/SK2VBNAU.js +1 -0
- package/build/dist/chunks/SKMPKAZI.js +1 -0
- package/build/dist/chunks/{5IIR3GIN.js → SQL6HD5E.js} +1 -1
- package/build/dist/chunks/SSIENQVU.js +1 -0
- package/build/dist/chunks/{EXRKBBX2.js → SUFA2GKR.js} +1 -1
- package/build/dist/chunks/TBCSZDAF.js +1 -0
- package/build/dist/chunks/{LMVB3B6T.js → TBIVTEP5.js} +1 -1
- package/build/dist/chunks/{2FSX7MMR.js → TJWVY4VO.js} +1 -1
- package/build/dist/chunks/{7XLEYOZH.js → TNKVRVTH.js} +1 -1
- package/build/dist/chunks/{SI6GCOAS.js → TPL4U3AQ.js} +1 -1
- package/build/dist/chunks/{QRDDKA4I.js → U4JGEMKT.js} +1 -1
- package/build/dist/chunks/{6AWTAE4Q.js → UA4O226F.js} +1 -1
- package/build/dist/chunks/UFVPMWPJ.js +1 -0
- package/build/dist/chunks/UHRCM7AG.js +1 -0
- package/build/dist/chunks/{XQXLFF7Y.js → UOGHQLQX.js} +1 -1
- package/build/dist/chunks/UP7FBDMJ.js +1 -0
- package/build/dist/chunks/{YQUKU2LS.js → UPMGGK34.js} +1 -1
- package/build/dist/chunks/VHLINDDS.js +1 -0
- package/build/dist/chunks/{PARWLWXW.js → VV2HEIFI.js} +1 -1
- package/build/dist/chunks/{YA5WWDEW.js → VVA72C6O.js} +1 -1
- package/build/dist/chunks/{TCPPYBGQ.js → W2OJ57ZO.js} +1 -1
- package/build/dist/chunks/{WQ6H62DM.js → W76QC2AW.js} +1 -1
- package/build/dist/chunks/{VFSRRDLY.js → WD37MEMZ.js} +1 -1
- package/build/dist/chunks/{R7QPJQP6.js → WGL46F3S.js} +1 -1
- package/build/dist/chunks/WIVYKLQM.js +2 -0
- package/build/dist/chunks/{XQUPZ3GU.js → WMNRP3YH.js} +1 -1
- package/build/dist/chunks/WOEKXQAH.js +1 -0
- package/build/dist/chunks/WPAF55SP.js +1 -0
- package/build/dist/chunks/{EVANKNJV.js → WPFAEBE7.js} +1 -1
- package/build/dist/chunks/WVONJOWN.js +1 -0
- package/build/dist/chunks/{TWSTOFN3.js → WWHCEMNB.js} +1 -1
- package/build/dist/chunks/{DZGEQBO7.js → XDZRO5JQ.js} +1 -1
- package/build/dist/chunks/XFKVU46U.js +3 -0
- package/build/dist/chunks/{RAKUK5VR.js → XJEOEMDS.js} +1 -1
- package/build/dist/chunks/XSD5NL7J.js +1 -0
- package/build/dist/chunks/{NU4K3TEZ.js → XSRIJUFU.js} +1 -1
- package/build/dist/chunks/{JVI26KQO.js → Y7PRJOIK.js} +1 -1
- package/build/dist/chunks/Y7RPSDD2.js +1 -0
- package/build/dist/chunks/YAJYDD6C.js +1 -0
- package/build/dist/chunks/{5OEHZJ6X.js → YEXUSRIZ.js} +1 -1
- package/build/dist/chunks/YHRUAQQK.js +1 -0
- package/build/dist/chunks/{3EFV4FQF.js → YPM2UITD.js} +1 -1
- package/build/dist/chunks/{3WBDHUV2.js → YRXT3HTW.js} +1 -1
- package/build/dist/chunks/Z4SRGAVL.js +1 -0
- package/build/dist/chunks/{SQ5BNSXR.js → ZBFKKUNP.js} +1 -1
- package/build/dist/chunks/{NWSPC3NH.js → ZCOFMGPS.js} +1 -1
- package/build/dist/chunks/ZCUXM52B.js +1 -0
- package/build/dist/chunks/ZE7EU2CS.js +1 -0
- package/build/dist/chunks/{CQCVFRQ5.js → ZET37EIG.js} +1 -1
- package/build/dist/chunks/{VVEUJ36E.js → ZGKVXFM5.js} +1 -1
- package/build/dist/chunks/{WQQJ7UPJ.js → ZSQOMSOC.js} +1 -1
- package/build/dist/chunks/{JST5JGAP.js → ZYH4B2GR.js} +1 -1
- package/package.json +2 -2
- package/build/dist/chunks/2MSQ6JII.js +0 -1
- package/build/dist/chunks/3SC5UI35.js +0 -1
- package/build/dist/chunks/4GAWMCQC.js +0 -1
- package/build/dist/chunks/4GHVIBL5.js +0 -1
- package/build/dist/chunks/4X2JOQ2L.js +0 -1
- package/build/dist/chunks/5YS5V2LK.js +0 -1
- package/build/dist/chunks/6UPPUHCL.js +0 -1
- package/build/dist/chunks/AXYOJBX6.js +0 -1
- package/build/dist/chunks/CEIPDEXZ.js +0 -1
- package/build/dist/chunks/CUNQ5RG5.js +0 -1
- package/build/dist/chunks/EG6M6SSO.js +0 -1
- package/build/dist/chunks/EGUMOD3A.js +0 -1
- package/build/dist/chunks/G6HCV67X.js +0 -1
- package/build/dist/chunks/GJY3P6OG.js +0 -1
- package/build/dist/chunks/HIMVOTIU.js +0 -1
- package/build/dist/chunks/IBXYIN7Q.js +0 -1
- package/build/dist/chunks/IUE6RASI.js +0 -1
- package/build/dist/chunks/JWCOXLYA.js +0 -1
- package/build/dist/chunks/KHJFXJBU.js +0 -1
- package/build/dist/chunks/LQGPMOD2.js +0 -1
- package/build/dist/chunks/MLPWQTBS.js +0 -1
- package/build/dist/chunks/MYBDO5SA.js +0 -1
- package/build/dist/chunks/NAYRD43N.js +0 -1
- package/build/dist/chunks/NMYGNJIJ.js +0 -1
- package/build/dist/chunks/NSOEDRBU.js +0 -3
- package/build/dist/chunks/PZHR4ITH.js +0 -1
- package/build/dist/chunks/Q356HHCL.js +0 -1
- package/build/dist/chunks/R7SXC74O.js +0 -1
- package/build/dist/chunks/RETS2ZEK.js +0 -1
- package/build/dist/chunks/SJPYXNOK.js +0 -1
- package/build/dist/chunks/SQZRVIVF.js +0 -1
- package/build/dist/chunks/SXAIXD56.js +0 -1
- package/build/dist/chunks/SXX3VTBP.js +0 -1
- package/build/dist/chunks/TMGWXDCZ.js +0 -1
- package/build/dist/chunks/UFS2RVEZ.js +0 -1
- package/build/dist/chunks/USSOVTD5.js +0 -1
- package/build/dist/chunks/UWOFA6GV.js +0 -1
- package/build/dist/chunks/V2OOOV6B.js +0 -1
- package/build/dist/chunks/XMA25DXR.js +0 -1
- package/build/dist/chunks/XVFLT275.js +0 -1
- package/build/dist/chunks/YHB55C5T.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as S,e as G,f as M,h as U,i as x,l as T,m as C,n as L,o as B,p as I,q as j,w as D,z as _}from"./
|
|
1
|
+
import{d as S,e as G,f as M,h as U,i as x,l as T,m as C,n as L,o as B,p as I,q as j,w as D,z as _}from"./WWHCEMNB.js";import{a as O,b as h}from"./X5V2Z2NM.js";import{a as N}from"./PBQSJSZO.js";import{c as F,g as A}from"./5KUWLUPM.js";import{a as p}from"./XSD5NL7J.js";import{a as $}from"./JXOEJPJ4.js";import{encodeFunctionData as q}from"viem";var z=10n**38n,W=`0x${"00".repeat(32)}`;function E(s,g){let k=s<0n,l=(k?-s:s).toString().padStart(g+1,"0"),P=l.slice(0,l.length-g),v=g?l.slice(l.length-g).replace(/0+$/,""):"";return`${k?"-":""}${P}${v?`.${v}`:""}`}var ie=s=>{let g=(e,a,i)=>({name:e,inputSchema:a,execute:async(t,n)=>{try{return N(n),L(s,t.chainId),await i(t,n)}catch(r){throw new p(s.plainError(r))}}}),k={transactionHash:{...G,description:"After local submission, repeat the same arguments with the mined hash to verify calldata, event and registry state."}},l=(e,a,i)=>s.clientFor(U(s).chainId).readContract({address:e,abi:h,functionName:a,args:i});async function P(e){let{chainId:a,registry:i}=U(s),t=await s.clientFor(a).readContract({address:i,abi:O,functionName:"ownerOf",args:[e]});return N(t),t}let v=e=>{if(typeof e!="string"||!/^[1-9][0-9]{0,18}$/.test(e)||BigInt(e)>=2n**64n)throw new p("Provide feedbackIndex as a decimal integer string of at least 1 (indexes are 1-based).");return BigInt(e)},X=g("erc8004_give_feedback",{type:"object",additionalProperties:!1,required:["agentId","value"],description:"Post public, permanent-by-hash feedback about an agent (ERC-8004 Reputation Registry giveFeedback). You cannot rate an agent you own or operate.",properties:{agentId:S,value:{type:"string",pattern:"^-?[0-9]+$",description:'Signed integer in fixed point, e.g. "87" with valueDecimals 0 is 87; "9977" with valueDecimals 2 is 99.77.'},valueDecimals:{type:"integer",minimum:0,maximum:18,default:0},tag1:{type:"string",description:"Optional filter tag such as starred, uptime, successRate, responseTime."},tag2:{type:"string"},endpoint:{type:"string",description:"Optional endpoint the feedback is about."},feedbackURI:{type:"string",description:"Optional HTTPS/IPFS URI of an off-chain feedback file."},feedbackHash:{...M,description:"keccak256 of the feedbackURI content; optional for IPFS, recommended for HTTPS."},...k}},async(e,a)=>{let{address:i}=x(s),t=T(e.agentId);if(typeof e.value!="string"||!/^-?[0-9]+$/.test(e.value))throw new p("Provide value as a signed integer string.");let n=BigInt(e.value);if(n>z||n<-z)throw new p("The feedback value is out of range (\xB11e38).");let r=e.valueDecimals===void 0?0:e.valueDecimals;if(typeof r!="number"||!Number.isInteger(r)||r<0||r>18)throw new p("valueDecimals must be an integer from 0 to 18.");let o=I(e.tag1,"tag1",128),b=I(e.tag2,"tag2",128),u=e.endpoint===void 0?"":I(e.endpoint,"endpoint",2048),f=e.feedbackURI===void 0?"":j(e.feedbackURI,"feedbackURI"),w=e.feedbackHash===void 0?W:B(e.feedbackHash,"feedbackHash"),R=q({abi:h,functionName:"giveFeedback",args:[t,n,r,o,b,u,f,w]});return _(s,a,e,{to:i,data:R,description:`Give feedback ${e.value}e-${r} to ERC-8004 agent ${t}.`,summary:`Publishes feedback ${E(n,r)} about agent ${t}${o?` (tag ${$(o)})`:""} from this wallet. Feedback is public and attributable to this wallet; it can be revoked later but never erased. Repeat with transactionHash to read back the feedback index.`,authority:async()=>{await P(t);let{registry:m,chainId:d}=U(s);if(await s.clientFor(d).readContract({address:m,abi:O,functionName:"isAuthorizedOrOwner",args:[a,t]})===!0)throw new p("The registry refuses feedback from the owner or an approved operator of the same agent.")},verify:async m=>{let d=D(m,i,h,"NewFeedback"),c=d.feedbackIndex,H=await l(i,"readFeedback",[t,a,c]);if(d.agentId!==t||!A(String(d.clientAddress),a)||d.value!==n||H[0]!==n||H[4])throw new p("The registry event or stored feedback does not match.");return{agentId:t.toString(),feedbackIndex:c.toString(),value:E(n,r),confirmed:!0}}})}),Y=g("erc8004_revoke_feedback",{type:"object",additionalProperties:!1,required:["agentId","feedbackIndex"],properties:{agentId:S,feedbackIndex:{type:"string",pattern:"^[1-9][0-9]*$",description:"1-based index from erc8004_give_feedback or erc8004_reputation."},...k}},async(e,a)=>{let{address:i}=x(s),t=T(e.agentId),n=v(e.feedbackIndex);return _(s,a,e,{to:i,data:q({abi:h,functionName:"revokeFeedback",args:[t,n]}),description:`Revoke feedback #${n} on ERC-8004 agent ${t}.`,summary:`Marks your feedback #${n} about agent ${t} as revoked. The original entry stays on-chain, flagged revoked. Repeat with transactionHash to verify.`,authority:async()=>{let r=await l(i,"getLastIndex",[t,a]);if(n>r)throw new p(`This wallet has given only ${r} feedback entries on agent ${t}.`);if((await l(i,"readFeedback",[t,a,n]))[4])throw new p("That feedback is already revoked.")},verify:async r=>{let o=D(r,i,h,"FeedbackRevoked"),b=await l(i,"readFeedback",[t,a,n]);if(o.agentId!==t||o.feedbackIndex!==n||!A(String(o.clientAddress),a)||!b[4])throw new p("The registry event or stored feedback does not show a revocation.");return{agentId:t.toString(),feedbackIndex:n.toString(),revoked:!0}}})}),Z=g("erc8004_append_response",{type:"object",additionalProperties:!1,required:["agentId","clientAddress","feedbackIndex","responseURI"],description:"Append a public response to a feedback entry (the agent showing a refund, or anyone tagging spam).",properties:{agentId:S,clientAddress:{...F,description:"The wallet that gave the feedback."},feedbackIndex:{type:"string",pattern:"^[1-9][0-9]*$"},responseURI:{type:"string",description:"HTTPS or IPFS URI of the response file."},responseHash:{...M,description:"keccak256 of the response content; optional for IPFS."},...k}},async(e,a)=>{let{address:i}=x(s),t=T(e.agentId),n=C(e.clientAddress,"clientAddress"),r=v(e.feedbackIndex),o=j(e.responseURI,"responseURI"),b=e.responseHash===void 0?W:B(e.responseHash,"responseHash");return _(s,a,e,{to:i,data:q({abi:h,functionName:"appendResponse",args:[t,n,r,o,b]}),description:`Append a response to feedback #${r} by ${n} on ERC-8004 agent ${t}.`,summary:`Publishes a response (${$(o)}) under feedback #${r} that ${n} gave agent ${t}, attributed to this wallet. Responses are append-only. Repeat with transactionHash to verify.`,authority:async()=>{let u=await l(i,"getLastIndex",[t,n]);if(r>u)throw new p(`${n} has given only ${u} feedback entries on agent ${t}.`)},verify:async u=>{let f=D(u,i,h,"ResponseAppended");if(f.agentId!==t||f.feedbackIndex!==r||!A(String(f.clientAddress),n)||!A(String(f.responder),a)||f.responseURI!==o)throw new p("The registry event does not match the response.");return{agentId:t.toString(),clientAddress:n,feedbackIndex:r.toString(),responder:a,confirmed:!0}}})}),J=g("erc8004_reputation",{type:"object",additionalProperties:!1,required:["agentId"],description:"Read-only: an agent's feedback summary and entries. Pass the reviewers you trust in clients; without it the summary counts every wallet, which anyone can spam.",properties:{agentId:S,clients:{type:"array",maxItems:200,items:F,description:"Reviewer wallets to count (recommended)."},tag1:{type:"string"},tag2:{type:"string"},includeRevoked:{type:"boolean",default:!1},limit:{type:"integer",minimum:1,maximum:200,default:50},clientAddress:{...F,description:"With feedbackIndex: also count responses to that one entry."},feedbackIndex:{type:"string",pattern:"^[1-9][0-9]*$"}}},async e=>{let{address:a}=x(s),i=T(e.agentId);await P(i);let t=I(e.tag1,"tag1",128),n=I(e.tag2,"tag2",128),r=typeof e.limit=="number"?Math.min(Math.max(1,Math.trunc(e.limit)),200):50,o=Array.isArray(e.clients)?e.clients.map(d=>C(d,"client")):void 0;if(o&&o.length>200)throw new p("Provide at most 200 reviewer wallets.");let b=o??await l(a,"getClients",[i]),u=b.slice(0,200),f={count:"0",value:"0",valueDecimals:0},w=[],R=0;if(u.length){let[d,c]=await Promise.all([l(a,"getSummary",[i,u,t,n]),l(a,"readAllFeedback",[i,u,t,n,e.includeRevoked===!0])]);f={count:d[0].toString(),value:E(d[1],d[2]),valueDecimals:d[2]},R=c[0].length,w=c[0].slice(0,r).map((H,y)=>({clientAddress:H,feedbackIndex:c[1][y].toString(),value:E(c[2][y],c[3][y]),valueDecimals:c[3][y],tag1:$(c[4][y]),tag2:$(c[5][y]),revoked:c[6][y]}))}let m;if(e.clientAddress!==void 0){let d=C(e.clientAddress,"clientAddress"),c=e.feedbackIndex===void 0?0n:v(e.feedbackIndex);m=(await l(a,"getResponseCount",[i,d,c,[]])).toString()}return{agentId:i.toString(),registry:a,clientsTotal:b.length,clientsUsed:u.length,filteredByClients:o!==void 0,summary:f,feedback:w,feedbackTotal:R,truncated:R>w.length||b.length>u.length,...m===void 0?{}:{responseCount:m},note:o?"Summary counts only the reviewers you named.":"Unfiltered: every reviewer wallet counts, and anyone can post feedback for free, so a high score is not evidence. Name trusted reviewers in clients for a meaningful score."}});return{tools:[X,Y,Z,J]}};export{E as a,ie as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o}from"./
|
|
1
|
+
import{a as o}from"./XSD5NL7J.js";import{createHash as c}from"node:crypto";function f(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;let t=Object.getPrototypeOf(n);return t===Object.prototype||t===null}function s(n){if(n===null||typeof n=="boolean"||typeof n=="string")return JSON.stringify(n);if(typeof n=="number"){if(!Number.isSafeInteger(n))throw new o("Canonical JSON numbers must be safe integers; encode base-unit amounts as decimal strings.");return Object.is(n,-0)?"0":String(n)}if(typeof n=="bigint")throw new o("BigInt values must be encoded as decimal strings before JSON serialization.");if(Array.isArray(n)){let t=[];for(let r=0;r<n.length;r++){if(!Object.prototype.hasOwnProperty.call(n,r))throw new o(`Sparse arrays are not permitted in canonical JSON (missing index ${r}).`);t.push(s(n[r]))}return`[${t.join(",")}]`}if(f(n)){let t=Object.keys(n).sort((e,i)=>e<i?-1:e>i?1:0),r=[];for(let e of t){let i=n[e];if(i===void 0)throw new o(`Canonical JSON object key "${e}" must not be undefined.`);r.push(`${JSON.stringify(e)}:${s(i)}`)}return`{${r.join(",")}}`}throw new o("Unsupported value in canonical JSON.")}function p(n){return new TextEncoder().encode(s(n))}function g(n){return`0x${c("sha256").update(p(n)).digest("hex")}`}export{s as a,p as b,g as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as d}from"./
|
|
1
|
+
import{a as d}from"./UP7FBDMJ.js";import{a as o}from"./XSD5NL7J.js";import{getAddress as w,isAddress as c,zeroAddress as g}from"viem";var u="^0x[0-9a-fA-F]{40}$",m=new RegExp(u),y={type:"string",pattern:u},R="Provide a valid contract or wallet address.";function a(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function h(n,t){if(!a(n))throw new o(t);return n}function A(n,t){return n.toLowerCase()===t.toLowerCase()}function S(n,t){return typeof n=="string"&&typeof t=="string"&&A(n,t)}function s(n,t,r){if(typeof n!="string")throw new o(t);if(!c(n,{strict:!1}))throw new o(r);return n}function E(n,t,r=t){return w(s(n,t,r))}function D(n,t,r=t){return s(n,t,r).toLowerCase()}function T(n,t,r=t){return s(n,t,r)}function L(n,t){if(n.toLowerCase()===g)throw new o(t);return n}function B(n,t){if(typeof n!="bigint"||n<0n||n>=1n<<256n)throw new o(t);return n}function C(n,t,r={}){let{notString:i,bits:f=256,positive:p=!1}=r;if(i!==void 0&&typeof n!="string")throw new o(i);let e=d(n);if(e>=1n<<BigInt(f)||p&&e===0n)throw new o(t);return e}export{u as a,m as b,y as c,R as d,a as e,h as f,A as g,S as h,E as i,D as j,T as k,L as l,B as m,C as n};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as le,o as K}from"./5O5ZE3ZV.js";import{b as x}from"./UWOFA6GV.js";import{c as W,f as de,h as y,i as ce,l as ue}from"./73N3TOJL.js";import{a as k,i as oe,j as G}from"./G6HCV67X.js";import{a as N}from"./5YS5V2LK.js";import{a as O}from"./JXOEJPJ4.js";import{randomBytes as ge,randomUUID as he}from"node:crypto";import{isDeepStrictEqual as pe}from"node:util";import{decodeFunctionData as me,encodeAbiParameters as ne,erc20Abi as J,keccak256 as ie,parseAbi as re,parseAbiParameters as ae,toEventSelector as be,zeroAddress as L}from"viem";var se=oe[k].meridian,Q=se.PredictionMarketEscrow.address,V=se.SecondaryMarketEscrow.address,$={address:se.CollateralToken_USDe.address,chainId:k,symbol:"USDe",decimals:18},we="wss://relayer.predict.meridian.xyz/auction",ke=ae("(address conditionResolver,bytes conditionId,uint8 predictedOutcome)[]"),Ie=ae("bytes32,uint256,uint256,address,address,address,bytes"),Se=ae("address,address,address,address,uint256,uint256"),X=re(["function isNonceUsed(address,uint256) view returns (bool)"]),Be=re(["function mint(((address conditionResolver,bytes conditionId,uint8 predictedOutcome)[] picks,uint256 predictorCollateral,uint256 counterpartyCollateral,address predictor,address counterparty,uint256 predictorNonce,uint256 counterpartyNonce,uint256 predictorDeadline,uint256 counterpartyDeadline,bytes predictorSignature,bytes counterpartySignature,bytes32 refCode,bytes predictorSessionKeyData,bytes counterpartySessionKeyData,address predictorSponsor,bytes predictorSponsorData) request)"]),Me=re(["function executeTrade((address token,address collateral,address seller,address buyer,uint256 tokenAmount,uint256 price,uint256 sellerNonce,uint256 buyerNonce,uint256 sellerDeadline,uint256 buyerDeadline,bytes sellerSignature,bytes buyerSignature,bytes32 refCode,bytes sellerSessionKeyData,bytes buyerSessionKeyData) request)"]),$e=be("Transfer(address,address,uint256)"),Ae=[{name:"predictionHash",type:"bytes32"},{name:"signer",type:"address"},{name:"collateral",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}],Ce=[{name:"tradeHash",type:"bytes32"},{name:"signer",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}];function i(n){throw new N(n)}function _(n){return de(n,"Meridian returned an invalid exchange object.")}function M(n,t,d=!1){return d&&typeof n=="number"&&Number.isSafeInteger(n)&&n>=0&&(n=String(n)),(typeof n!="string"||!/^\d+$/.test(n)||BigInt(n)>=1n<<256n)&&i(`Provide ${t} as a decimal base-unit integer string.`),n}function F(n){let t=Number(n);return(!Number.isSafeInteger(t)||t<0||BigInt(t)!==BigInt(n))&&i("Meridian signing terms cannot be represented exactly as JSON numbers."),t}function R(n){let t="Provide a nonzero token, resolver or wallet address.";return ue(ce(n,t),t)}function Z(n,t){return(typeof n!="string"||!/^0x(?:[0-9a-fA-F]{2})+$/.test(n)||t!==void 0&&n.length!==2+t*2)&&i("Meridian returned invalid hexadecimal data."),n}function v(n){return(typeof n!="string"||n.length===0||n.length>256)&&i("Meridian returned an invalid exchange identifier."),n}function j(){return BigInt(Math.floor(Date.now()/1e3))}function ve(n,t){let d=n==="buy"?["picks","stake","minCounterpartyCollateral","usdgAmountIn","slippageBps","continuation","signature"]:["token","amount","minPrice","slippageBps","continuation","signature"];Object.keys(t).some(S=>!d.includes(S))&&i("Unsupported Meridian arguments; use the tool input schema."),t.slippageBps!==void 0&&(typeof t.slippageBps!="number"||!Number.isInteger(t.slippageBps)||t.slippageBps<0||t.slippageBps>=1e4)&&i("Slippage must be an integer from 0 to 9999 basis points.");let c=t.slippageBps;if(n==="sell"){let S=M(t.amount,"the position amount");BigInt(S)===0n&&i("The position amount must be positive.");let B=R(t.token);(y(B,$.address)||y(B,G))&&i("Choose a Meridian position token to sell.");let A;if(t.minPrice!==void 0){let e=M(t.minPrice,"the minimum sale price");BigInt(e)<=1n&&i("The minimum sale price must be greater than 1 base unit."),A=e}else{let e=BigInt(S)/100n>10n**18n?BigInt(S)/100n:10n**18n;A=c===void 0?e.toString():K(e.toString(),c)}return{side:n,token:B,amount:S,minPrice:A,priceFloorSource:t.minPrice===void 0?"default":"explicit",...c===void 0?{}:{slippageBps:c}}}(!Array.isArray(t.picks)||t.picks.length<1||t.picks.length>10)&&i("Provide between one and ten Meridian picks.");let m=t.picks.map(S=>{let B=_(S);return(Object.keys(B).some(A=>!["conditionResolver","conditionId","predictedOutcome"].includes(A))||B.predictedOutcome!==0&&B.predictedOutcome!==1)&&i("Each pick needs a resolver, condition ID and outcome 0 or 1."),{conditionResolver:R(B.conditionResolver),conditionId:Z(B.conditionId),predictedOutcome:B.predictedOutcome}}).sort((S,B)=>{let A=`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}:${S.predictedOutcome}`,e=`${B.conditionResolver.toLowerCase()}:${B.conditionId.toLowerCase()}:${B.predictedOutcome}`;return A<e?-1:A>e?1:0}),g=m.map(S=>`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}`);new Set(g).size!==m.length&&i("Do not repeat a condition in the same prediction.");let l=M(t.stake,"the USDe stake");BigInt(l)<10n**18n&&i("Meridian requires a stake of at least 1 USDe.");let I=t.usdgAmountIn===void 0?void 0:M(t.usdgAmountIn,"the USDG swap amount");I!==void 0&&BigInt(I)===0n&&i("The USDG swap amount must be positive.");let D=t.minCounterpartyCollateral!==void 0?M(t.minCounterpartyCollateral,"the minimum counterparty collateral"):K(l,c??le);return BigInt(D)<=1n&&i("The minimum counterparty collateral must be greater than 1 base unit."),{side:n,picks:m,stake:l,minCounterpartyCollateral:D,...I===void 0?{}:{usdgAmountIn:I},...c===void 0?{}:{slippageBps:c}}}var ee=class{constructor(t,d){this.id=t;this.prefix=d;this.socket=new globalThis.WebSocket(we),this.socket.addEventListener("open",()=>{this.opened=!0,this.notify?.()}),this.socket.addEventListener("close",()=>this.stop("Meridian exchange socket was lost. Start a fresh auction.")),this.socket.addEventListener("error",()=>this.stop("Meridian exchange socket failed. Start a fresh auction.")),this.socket.addEventListener("message",c=>{try{(typeof c.data!="string"||c.data.length>65536)&&i("Meridian returned a malformed exchange message.");let m=_(JSON.parse(c.data));if(m.type==="pong")return;let g=v(m.type),l=_(m.payload);if(g==="error"&&i("Meridian rejected or failed the exchange. Start a fresh auction."),g===`${d}.ack`){this.auctionId===void 0?((l.id!==t||this.accepting||l.accepted!==void 0)&&i("Meridian acknowledged a different exchange."),l.error!==void 0&&i(`Meridian rejected the exchange: ${O(v(l.error))}.`),this.auctionId=v(l.auctionId)):((!this.accepting||l.auctionId!==this.auctionId||l.id!==void 0&&l.id!==t)&&i("Meridian acknowledged a different exchange."),l.error!==void 0&&i(`Meridian rejected acceptance: ${O(v(l.error))}.`),l.accepted!==!0&&i("Meridian rejected acceptance of the exchange."));return}if((!g.startsWith(`${d}.`)||l.auctionId!==this.auctionId||!this.auctionId)&&i("Meridian returned a message for a different exchange."),["error","rejected","failed","expired"].some(I=>g===`${d}.${I}`)){let I=["reason","makerReason"].flatMap(D=>l[D]===void 0?[]:[`${D}=${O(v(l[D]))}`]);i(`Meridian exchange ${g.slice(d.length+1)}${I.length?`: ${I.join("; ")}`:""}. Start a fresh auction.`)}if((g===`${d}.pending`||g===`${d}.filled`)&&!this.accepting&&i("Meridian returned settlement before acceptance."),g===`${d}.pending`)return;this.queue.length>=16&&i("Meridian returned too many exchange messages."),this.queue.push({type:g,payload:l}),this.notify?.()}catch(m){this.stop(m instanceof N?m.message:"Meridian rejected or returned an invalid exchange message. Start a fresh auction.")}})}id;prefix;socket;queue=[];notify;error;auctionId;accepting=!1;opened=!1;check(){if(this.error)throw this.error;this.socket.readyState>1&&i("Meridian exchange socket was lost. Start a fresh auction.")}stop(t){this.error??=new N(t),this.notify?.(),this.socket.readyState<2&&this.socket.close()}async wait(t,d=3e4){return new Promise((c,m)=>{let g=setTimeout(()=>this.stop("Meridian exchange timed out. Start a fresh auction."),d),l=()=>{try{if(this.check(),t===void 0?!this.opened:!this.queue.length)return;let I=t===void 0?void 0:this.queue.shift();I&&I.type!==`${this.prefix}.${t}`&&i("Meridian returned an unexpected exchange stage."),clearTimeout(g),this.notify=void 0,c(I?.payload??{})}catch(I){clearTimeout(g),this.notify=void 0,m(I)}};this.notify=l,l()})}send(t,d){this.check(),this.socket.readyState!==1&&i("Meridian exchange socket is not open."),t==="accept"&&(this.accepting=!0),this.socket.send(JSON.stringify({...t==="start"?{id:this.id}:{},type:`${this.prefix}.${t}`,payload:d}))}};function te(n){return ie(ne(ke,[n]))}function De(n,t,d){return ie(ne(Ie,[te(n.picks),BigInt(n.stake),BigInt(d.counterpartyCollateral),t,d.counterparty,L,"0x"]))}function qe(n,t,d,c){return ie(ne(Se,[n.token,$.address,t,d,BigInt(n.amount),BigInt(c)]))}function Y(n,t){let{input:d,wallet:c,nonce:m,deadline:g}=n,l={name:d.side==="buy"?"PredictionMarketEscrow":"SecondaryMarketEscrow",version:"1",chainId:k,verifyingContract:n.continuation.escrowContract};return(!m||!g)&&i("Meridian exchange is missing its signing terms."),d.side==="buy"?(t||i("Meridian has not returned a winning bid."),{domain:l,primaryType:"MintApproval",types:{MintApproval:Ae},message:{predictionHash:De(d,c,t),signer:c,collateral:d.stake,nonce:m,deadline:g}}):{domain:l,primaryType:"TradeApproval",types:{TradeApproval:Ce},message:{tradeHash:qe(d,c,t?t.buyer:L,t?t.price:"0"),signer:c,nonce:m,deadline:g}}}function fe(n){let t=[BigInt(n.deadline)],d=n.continuation;if(d.stage==="primary_accept"||d.stage==="secondary_accept"){t.push(BigInt(d.acceptDeadline));let c=d.winningBid;d.stage==="primary_accept"&&t.push(BigInt(c.counterpartyDeadline)),c.buyerDeadline!==void 0&&t.push(BigInt(M(c.buyerDeadline,"the buyer deadline",!0)))}return t.reduce((c,m)=>c<m?c:m)}function H(n){n.channel?.check(),n.deadline&&j()>=fe(n)&&i("Meridian exchange expired. Start a fresh auction.")}var Oe=n=>{let t=new Map;function d(e){clearTimeout(e.timer),t.delete(e.continuation.requestId),e.channel?.stop("Meridian exchange is closed or expired. Start a fresh auction.")}function c(e,a){clearTimeout(e.timer),e.timer=setTimeout(()=>d(e),a),e.timer.unref?.()}function m(e){let{wallet:a,chainId:s,escrowContract:f,requestId:u}=e.continuation;return{wallet:a,chainId:s,escrowContract:f,requestId:u}}function g(e){return e.side!=="sell"?"":` Effective minimum sale proceeds: ${e.minPrice} USDe base units (${$.address}, 18 decimals). ${e.priceFloorSource==="explicit"?"Caller minPrice is unchanged; slippageBps does not reduce this floor.":`Default floor with ${e.slippageBps??0} bps slippage applied.`}`}async function l(e){let{input:a,wallet:s}=e,f=n.clientFor(k),u=a.side==="buy"?$.address:a.token,r=a.side==="buy"?a.stake:a.amount,[h,w]=await Promise.all([f.readContract({address:u,abi:J,functionName:"balanceOf",args:[s]}),f.readContract({address:u,abi:J,functionName:"allowance",args:[s,e.continuation.escrowContract]})]);if(a.side==="sell"&&await f.readContract({address:u,abi:J,functionName:"decimals"})!==18&&i("Meridian position tokens must have 18 decimals."),h>=BigInt(r)&&w>=BigInt(r))return;(e.continuation.stage==="primary_accept"||e.continuation.stage==="secondary_accept")&&i("Meridian prerequisites changed during the auction. Start a fresh auction after funding and approval.");let p,C;if(h<BigInt(r)){a.side==="sell"&&i("The wallet does not have enough position tokens to sell."),a.usdgAmountIn||i("Not enough USDe. Provide usdgAmountIn in USDG base units to quote a swap before the auction.");let b=await n.quoteSwap({from:G,to:$.address,amountIn:a.usdgAmountIn,...a.slippageBps===void 0?{}:{slippageBps:a.slippageBps}},s);(j()>=BigInt(M(b.expiresAt,"the swap expiry"))||BigInt(M(b.minAmountOut,"the swap minimum"))+h<BigInt(r))&&i("The USDG swap minimum does not cover the USDe stake, or the quote expired. Request a fresh quote with sufficient input.");let o=await n.buildSwap(b.quoteId,s);(!("txs"in o)||!o.txs.length)&&i("The swap coordinator did not return prerequisite transactions."),p=o.txs,C=`${o.summary} Minimum USDe output: ${b.minAmountOut} base units (18 decimals).`}else p=[n.approval(u,e.continuation.escrowContract,r,k)],C=`Approve exactly ${r} base units (18 decimals) of ${u} for ${e.continuation.escrowContract} on chain ${k}.`;p.some(b=>b.chainId!==k)&&i("Meridian prerequisite transactions must use chain 4663.");let q=await n.preview(p,s),T=q.changes.map(b=>{let o=b.amount.startsWith("-");return`${o?"-":"+"}${n.formatAmount(o?b.amount.slice(1):b.amount,b.token.decimals)} ${b.token.symbol} (${b.token.address}, chain ${b.token.chainId}, ${b.token.decimals} decimals)`}).join("; ");return e.channel?.stop("Meridian prerequisites must be mined before the auction."),e.channel=void 0,e.deadline=void 0,e.nonce=void 0,e.continuation={...m(e),stage:"prerequisites"},{steps:p.map(b=>({kind:"tx",tx:b})),continuation:structuredClone(e.continuation),summary:`${C}${g(a)} ${q.summary} ${T}. Mine these prerequisites before continuing; no RFQ has started.`}}function I(e){let a=e.continuation;a.stage==="prerequisites"&&i("Meridian prerequisites need to finish before signing."),H(e),c(e,Number(fe(e)-j())*1e3);let s=e.input,f=s.side==="buy"?`Stake ${s.stake} base units of USDe (${$.address}, 18 decimals)`:`Sell ${s.amount} base units of position ${s.token} (18 decimals)`,u=a.stage==="secondary_start"?"Initial buyer-zero, price-zero intent only.":a.stage==="primary_accept"?`Counterparty ${a.winningBid.counterparty}; counterparty collateral ${a.winningBid.counterpartyCollateral} USDe base units; counterparty deadline ${a.winningBid.counterpartyDeadline}.`:`Buyer ${a.winningBid.buyer}; receive ${a.winningBid.price} USDe base units (${$.address}, 18 decimals).`;return{steps:[{kind:"typedData",request:structuredClone(a.request)}],continuation:structuredClone(a),summary:`${f} on chain ${k}.${g(s)} Approval was checked on chain. ${u} Sign locally for domain ${a.request.domain.name}, version 1, escrow ${a.escrowContract}, signature deadline ${e.deadline}${"acceptDeadline"in a?`, acceptance deadline ${a.acceptDeadline}`:""}. External relayer settlement is pending; a signature is not a fill.`}}async function D(e){let a=await e.channel.wait("result"),s=_(a.winningBid),f=v(a.auctionId);s.auctionId!==f&&i("Meridian winning bid belongs to another auction.");let u=M(a.acceptDeadline,"the acceptance deadline",!0);if(e.input.side==="buy"){let r={auctionId:f,counterparty:v(s.counterparty),counterpartyCollateral:M(s.counterpartyCollateral,"the counterparty collateral"),counterpartyNonce:M(s.counterpartyNonce,"the counterparty nonce",!0),counterpartyDeadline:M(s.counterpartyDeadline,"the counterparty deadline",!0),receivedAt:v(s.receivedAt)};R(r.counterparty),(!Number.isFinite(Date.parse(r.receivedAt))||BigInt(r.counterpartyCollateral)<=1n||BigInt(r.counterpartyCollateral)<BigInt(e.input.minCounterpartyCollateral))&&i("Meridian winning bid counterparty collateral is below the caller minimum."),e.continuation={...m(e),stage:"primary_accept",auctionId:f,winningBid:r,acceptDeadline:u,request:Y(e,r)}}else{let r={auctionId:f,buyer:v(s.buyer),price:M(s.price,"the sale price"),...s.buyerDeadline!==void 0?{buyerDeadline:M(s.buyerDeadline,"the buyer deadline",!0)}:{},...s.buyerNonce!==void 0?{buyerNonce:M(s.buyerNonce,"the buyer nonce",!0)}:{},...s.receivedAt!==void 0?{receivedAt:v(s.receivedAt)}:{}};R(r.buyer),(BigInt(r.price)<=1n||BigInt(r.price)<BigInt(e.input.minPrice))&&i("Meridian winning bid sale price is below the caller minimum."),e.continuation={...m(e),stage:"secondary_accept",auctionId:f,winningBid:r,acceptDeadline:u,request:Y(e,r)}}return I(e)}async function S(e,a){let s=e.continuation;s.stage!=="primary_accept"&&s.stage!=="secondary_accept"&&i("Meridian exchange is not ready for acceptance."),H(e),e.channel.send("accept",{auctionId:s.auctionId,[e.input.side==="buy"?"predictorSignature":"sellerSignature"]:a}),c(e,15e4);let f=await e.channel.wait("filled",12e4),u=Z(f.transactionHash,32),r=n.clientFor(k),[h,w]=await Promise.all([r.waitForTransactionReceipt({hash:u,timeout:12e4}),r.getTransaction({hash:u})]);(h.status!=="success"||!y(h.transactionHash,u)||!y(w.hash,u)||!y(h.to,s.escrowContract)||!y(w.to,s.escrowContract)||w.chainId!==k)&&i("Meridian fill has no matching successful receipt on chain 4663.");let{input:p,wallet:C}=e;if(p.side==="buy"&&s.stage==="primary_accept"){let o=me({abi:Be,data:w.input}).args[0];(!y(te([...o.picks]),te(p.picks))||o.predictorCollateral!==BigInt(p.stake)||o.counterpartyCollateral!==BigInt(s.winningBid.counterpartyCollateral)||!y(o.predictor,C)||!y(o.counterparty,s.winningBid.counterparty)||o.predictorNonce!==BigInt(e.nonce)||o.predictorDeadline!==BigInt(e.deadline)||!y(o.predictorSponsor,L)||o.predictorSponsorData!=="0x"||!y(o.predictorSignature,a))&&i("Meridian mint receipt does not match the accepted prediction.")}else if(p.side==="sell"&&s.stage==="secondary_accept"){let o=me({abi:Me,data:w.input}).args[0];(!y(o.token,p.token)||!y(o.collateral,$.address)||!y(o.seller,C)||!y(o.buyer,s.winningBid.buyer)||o.tokenAmount!==BigInt(p.amount)||o.price!==BigInt(s.winningBid.price)||o.sellerNonce!==BigInt(e.nonce)||o.sellerDeadline!==BigInt(e.deadline)||!y(o.sellerSignature,a))&&i("Meridian sale receipt does not match the accepted trade.")}let q=new Map,T=new Map;for(let o of h.logs){if(o.topics[0]!==$e||o.topics.length!==3)continue;(!/^0x[0-9a-fA-F]{64}$/.test(o.data)||!o.topics.slice(1).every(ye=>/^0x0{24}[0-9a-fA-F]{40}$/.test(ye)))&&i("Meridian receipt has malformed transfer logs.");let E=`0x${o.topics[1].slice(-40)}`,U=`0x${o.topics[2].slice(-40)}`,P=o.address.toLowerCase(),z=BigInt(o.data);q.set(P,(q.get(P)??0n)+(y(U,C)?z:0n)-(y(E,C)?z:0n)),y(E,L)&&y(U,C)&&T.set(P,(T.get(P)??0n)+z)}let b;if(p.side==="buy"&&s.stage==="primary_accept"){let o=BigInt(p.stake)+BigInt(s.winningBid.counterpartyCollateral),E=[...T].filter(([U,P])=>!y(U,$.address)&&P===o&&q.get(U)===o);(E.length!==1||q.get($.address.toLowerCase())!==-BigInt(p.stake))&&i("Meridian mint receipt does not prove the expected collateral and position delta."),b=`${o} base units received in position ${E[0][0]}`}else p.side==="sell"&&s.stage==="secondary_accept"?((q.get(p.token.toLowerCase())!==-BigInt(p.amount)||q.get($.address.toLowerCase())!==BigInt(s.winningBid.price))&&i("Meridian sale receipt does not prove the expected collateral and position delta."),b=`${p.amount} base units sold from position ${p.token}; ${s.winningBid.price} USDe base units received`):i("Meridian fill has a different exchange stage.");return{txs:[],hashes:[u],status:"mined",summary:`Mined: ${u}. Status: mined. Meridian ${p.side} filled by the external relayer. Successful receipt and transfer deltas verified on chain ${k}: ${b} (18 decimals); collateral USDe ${$.address} (18 decimals).`}}async function B(e,a,s){let f=R(s),u=ve(e,a),r;if(a.continuation!==void 0){let h=_(a.continuation),w=t.get(v(h.requestId));w||i("Meridian exchange is lost or expired. Start a fresh auction."),(!y(w.wallet,f)||!pe(w.input,u)||!pe(w.continuation,h))&&i("Meridian continuation or arguments do not match the active wallet exchange."),w.busy&&i("Meridian exchange is already processing this continuation."),r=w}else{a.signature!==void 0&&i("A signature requires an active Meridian continuation."),t.size>=1e3&&i("Too many active Meridian exchanges. Please try again later.");let h=he(),w=setTimeout(()=>{let p=t.get(h);p&&d(p)},9e5);w.unref?.(),r={input:u,wallet:f,continuation:{stage:"prerequisites",wallet:f,chainId:k,escrowContract:e==="buy"?Q:V,requestId:h},busy:!1,timer:w},t.set(h,r)}r.busy=!0;try{H(r),await n.clientFor(k).getChainId()!==k&&i("Meridian requires an RPC on chain 4663.");let h=r.continuation.stage;h==="prerequisites"&&a.signature!==void 0&&i("Do not sign before Meridian prerequisites have mined.");let w=await l(r);if(w)return w;if(h==="prerequisites")return r.nonce=(ge(4).readUInt32BE()+1).toString(),r.deadline=(j()+300n).toString(),await n.clientFor(k).readContract({address:r.continuation.escrowContract,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i(`Meridian ${e==="buy"?"predictor":"seller"} nonce is already used. Start a fresh auction.`),r.channel=new ee(r.continuation.requestId,e==="buy"?"auction":"secondary.auction"),await r.channel.wait(),u.side==="buy"?(r.channel.send("start",{id:r.continuation.requestId,picks:u.picks,predictorCollateral:u.stake,predictor:f,predictorNonce:F(r.nonce),predictorDeadline:F(r.deadline),chainId:k,escrowContract:Q,mode:"blind"}),await D(r)):(r.continuation={...m(r),stage:"secondary_start",request:Y(r)},I(r));let p=Z(a.signature);if(e==="sell"&&await n.clientFor(k).readContract({address:V,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i("Meridian seller nonce is already used. Start a fresh auction."),e==="buy"&&await n.clientFor(k).readContract({address:Q,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i("Meridian predictor nonce is already used. Start a fresh auction."),H(r),h==="secondary_start"&&u.side==="sell")return r.channel.send("start",{id:r.continuation.requestId,token:u.token,collateral:$.address,tokenAmount:u.amount,seller:f,sellerNonce:F(r.nonce),sellerDeadline:F(r.deadline),chainId:k,escrowContract:V,mode:"blind",sellerSignature:p}),await D(r);let C=await S(r,p);return d(r),C}catch(h){throw d(r),new N(n.plainError(h))}finally{r.busy=!1}}let A={continuation:{type:"object"},signature:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"}};return{tools:[{name:"meridian_buy",inputSchema:{type:"object",additionalProperties:!1,required:["picks","stake"],properties:{...A,stake:x("USDe stake in base units, 18 decimals, chain 4663."),minCounterpartyCollateral:x("Optional caller minimum counterparty collateral in USDe base units, 18 decimals."),usdgAmountIn:x("Optional exact USDG swap input in base units, 6 decimals, if USDe balance is insufficient."),slippageBps:{type:"integer",minimum:0,maximum:9999},picks:{type:"array",minItems:1,maxItems:10,items:{type:"object",additionalProperties:!1,required:["conditionResolver","conditionId","predictedOutcome"],properties:{conditionResolver:W,conditionId:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"},predictedOutcome:{type:"integer",enum:[0,1]}}}}}},execute:(e,a)=>B("buy",e,a)},{name:"meridian_sell",inputSchema:{type:"object",additionalProperties:!1,required:["token","amount"],properties:{...A,token:{...W,description:"Position token address on chain 4663."},amount:x("Position amount in base units, 18 decimals."),minPrice:x("Optional minimum total sale proceeds in USDe base units, 18 decimals. Explicit minPrice is never reduced by slippageBps."),slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Applied only to the default sale floor when minPrice is omitted."}}},execute:(e,a)=>B("sell",e,a)}]}};export{Ae as a,Ce as b,Oe as c};
|
|
1
|
+
import{b as le,o as K}from"./GHPREYQK.js";import{b as x}from"./5ZLOCQA4.js";import{c as W,f as de,h as y,i as ce,l as ue}from"./5KUWLUPM.js";import{a as k,i as oe,j as G}from"./FWD4L3CJ.js";import{a as N}from"./XSD5NL7J.js";import{a as O}from"./JXOEJPJ4.js";import{randomBytes as ge,randomUUID as he}from"node:crypto";import{isDeepStrictEqual as pe}from"node:util";import{decodeFunctionData as me,encodeAbiParameters as ne,erc20Abi as J,keccak256 as ie,parseAbi as re,parseAbiParameters as ae,toEventSelector as be,zeroAddress as L}from"viem";var se=oe[k].meridian,Q=se.PredictionMarketEscrow.address,V=se.SecondaryMarketEscrow.address,$={address:se.CollateralToken_USDe.address,chainId:k,symbol:"USDe",decimals:18},we="wss://relayer.predict.meridian.xyz/auction",ke=ae("(address conditionResolver,bytes conditionId,uint8 predictedOutcome)[]"),Ie=ae("bytes32,uint256,uint256,address,address,address,bytes"),Se=ae("address,address,address,address,uint256,uint256"),X=re(["function isNonceUsed(address,uint256) view returns (bool)"]),Be=re(["function mint(((address conditionResolver,bytes conditionId,uint8 predictedOutcome)[] picks,uint256 predictorCollateral,uint256 counterpartyCollateral,address predictor,address counterparty,uint256 predictorNonce,uint256 counterpartyNonce,uint256 predictorDeadline,uint256 counterpartyDeadline,bytes predictorSignature,bytes counterpartySignature,bytes32 refCode,bytes predictorSessionKeyData,bytes counterpartySessionKeyData,address predictorSponsor,bytes predictorSponsorData) request)"]),Me=re(["function executeTrade((address token,address collateral,address seller,address buyer,uint256 tokenAmount,uint256 price,uint256 sellerNonce,uint256 buyerNonce,uint256 sellerDeadline,uint256 buyerDeadline,bytes sellerSignature,bytes buyerSignature,bytes32 refCode,bytes sellerSessionKeyData,bytes buyerSessionKeyData) request)"]),$e=be("Transfer(address,address,uint256)"),Ae=[{name:"predictionHash",type:"bytes32"},{name:"signer",type:"address"},{name:"collateral",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}],Ce=[{name:"tradeHash",type:"bytes32"},{name:"signer",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}];function i(n){throw new N(n)}function _(n){return de(n,"Meridian returned an invalid exchange object.")}function M(n,t,d=!1){return d&&typeof n=="number"&&Number.isSafeInteger(n)&&n>=0&&(n=String(n)),(typeof n!="string"||!/^\d+$/.test(n)||BigInt(n)>=1n<<256n)&&i(`Provide ${t} as a decimal base-unit integer string.`),n}function F(n){let t=Number(n);return(!Number.isSafeInteger(t)||t<0||BigInt(t)!==BigInt(n))&&i("Meridian signing terms cannot be represented exactly as JSON numbers."),t}function R(n){let t="Provide a nonzero token, resolver or wallet address.";return ue(ce(n,t),t)}function Z(n,t){return(typeof n!="string"||!/^0x(?:[0-9a-fA-F]{2})+$/.test(n)||t!==void 0&&n.length!==2+t*2)&&i("Meridian returned invalid hexadecimal data."),n}function v(n){return(typeof n!="string"||n.length===0||n.length>256)&&i("Meridian returned an invalid exchange identifier."),n}function j(){return BigInt(Math.floor(Date.now()/1e3))}function ve(n,t){let d=n==="buy"?["picks","stake","minCounterpartyCollateral","usdgAmountIn","slippageBps","continuation","signature"]:["token","amount","minPrice","slippageBps","continuation","signature"];Object.keys(t).some(S=>!d.includes(S))&&i("Unsupported Meridian arguments; use the tool input schema."),t.slippageBps!==void 0&&(typeof t.slippageBps!="number"||!Number.isInteger(t.slippageBps)||t.slippageBps<0||t.slippageBps>=1e4)&&i("Slippage must be an integer from 0 to 9999 basis points.");let c=t.slippageBps;if(n==="sell"){let S=M(t.amount,"the position amount");BigInt(S)===0n&&i("The position amount must be positive.");let B=R(t.token);(y(B,$.address)||y(B,G))&&i("Choose a Meridian position token to sell.");let A;if(t.minPrice!==void 0){let e=M(t.minPrice,"the minimum sale price");BigInt(e)<=1n&&i("The minimum sale price must be greater than 1 base unit."),A=e}else{let e=BigInt(S)/100n>10n**18n?BigInt(S)/100n:10n**18n;A=c===void 0?e.toString():K(e.toString(),c)}return{side:n,token:B,amount:S,minPrice:A,priceFloorSource:t.minPrice===void 0?"default":"explicit",...c===void 0?{}:{slippageBps:c}}}(!Array.isArray(t.picks)||t.picks.length<1||t.picks.length>10)&&i("Provide between one and ten Meridian picks.");let m=t.picks.map(S=>{let B=_(S);return(Object.keys(B).some(A=>!["conditionResolver","conditionId","predictedOutcome"].includes(A))||B.predictedOutcome!==0&&B.predictedOutcome!==1)&&i("Each pick needs a resolver, condition ID and outcome 0 or 1."),{conditionResolver:R(B.conditionResolver),conditionId:Z(B.conditionId),predictedOutcome:B.predictedOutcome}}).sort((S,B)=>{let A=`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}:${S.predictedOutcome}`,e=`${B.conditionResolver.toLowerCase()}:${B.conditionId.toLowerCase()}:${B.predictedOutcome}`;return A<e?-1:A>e?1:0}),g=m.map(S=>`${S.conditionResolver.toLowerCase()}:${S.conditionId.toLowerCase()}`);new Set(g).size!==m.length&&i("Do not repeat a condition in the same prediction.");let l=M(t.stake,"the USDe stake");BigInt(l)<10n**18n&&i("Meridian requires a stake of at least 1 USDe.");let I=t.usdgAmountIn===void 0?void 0:M(t.usdgAmountIn,"the USDG swap amount");I!==void 0&&BigInt(I)===0n&&i("The USDG swap amount must be positive.");let D=t.minCounterpartyCollateral!==void 0?M(t.minCounterpartyCollateral,"the minimum counterparty collateral"):K(l,c??le);return BigInt(D)<=1n&&i("The minimum counterparty collateral must be greater than 1 base unit."),{side:n,picks:m,stake:l,minCounterpartyCollateral:D,...I===void 0?{}:{usdgAmountIn:I},...c===void 0?{}:{slippageBps:c}}}var ee=class{constructor(t,d){this.id=t;this.prefix=d;this.socket=new globalThis.WebSocket(we),this.socket.addEventListener("open",()=>{this.opened=!0,this.notify?.()}),this.socket.addEventListener("close",()=>this.stop("Meridian exchange socket was lost. Start a fresh auction.")),this.socket.addEventListener("error",()=>this.stop("Meridian exchange socket failed. Start a fresh auction.")),this.socket.addEventListener("message",c=>{try{(typeof c.data!="string"||c.data.length>65536)&&i("Meridian returned a malformed exchange message.");let m=_(JSON.parse(c.data));if(m.type==="pong")return;let g=v(m.type),l=_(m.payload);if(g==="error"&&i("Meridian rejected or failed the exchange. Start a fresh auction."),g===`${d}.ack`){this.auctionId===void 0?((l.id!==t||this.accepting||l.accepted!==void 0)&&i("Meridian acknowledged a different exchange."),l.error!==void 0&&i(`Meridian rejected the exchange: ${O(v(l.error))}.`),this.auctionId=v(l.auctionId)):((!this.accepting||l.auctionId!==this.auctionId||l.id!==void 0&&l.id!==t)&&i("Meridian acknowledged a different exchange."),l.error!==void 0&&i(`Meridian rejected acceptance: ${O(v(l.error))}.`),l.accepted!==!0&&i("Meridian rejected acceptance of the exchange."));return}if((!g.startsWith(`${d}.`)||l.auctionId!==this.auctionId||!this.auctionId)&&i("Meridian returned a message for a different exchange."),["error","rejected","failed","expired"].some(I=>g===`${d}.${I}`)){let I=["reason","makerReason"].flatMap(D=>l[D]===void 0?[]:[`${D}=${O(v(l[D]))}`]);i(`Meridian exchange ${g.slice(d.length+1)}${I.length?`: ${I.join("; ")}`:""}. Start a fresh auction.`)}if((g===`${d}.pending`||g===`${d}.filled`)&&!this.accepting&&i("Meridian returned settlement before acceptance."),g===`${d}.pending`)return;this.queue.length>=16&&i("Meridian returned too many exchange messages."),this.queue.push({type:g,payload:l}),this.notify?.()}catch(m){this.stop(m instanceof N?m.message:"Meridian rejected or returned an invalid exchange message. Start a fresh auction.")}})}id;prefix;socket;queue=[];notify;error;auctionId;accepting=!1;opened=!1;check(){if(this.error)throw this.error;this.socket.readyState>1&&i("Meridian exchange socket was lost. Start a fresh auction.")}stop(t){this.error??=new N(t),this.notify?.(),this.socket.readyState<2&&this.socket.close()}async wait(t,d=3e4){return new Promise((c,m)=>{let g=setTimeout(()=>this.stop("Meridian exchange timed out. Start a fresh auction."),d),l=()=>{try{if(this.check(),t===void 0?!this.opened:!this.queue.length)return;let I=t===void 0?void 0:this.queue.shift();I&&I.type!==`${this.prefix}.${t}`&&i("Meridian returned an unexpected exchange stage."),clearTimeout(g),this.notify=void 0,c(I?.payload??{})}catch(I){clearTimeout(g),this.notify=void 0,m(I)}};this.notify=l,l()})}send(t,d){this.check(),this.socket.readyState!==1&&i("Meridian exchange socket is not open."),t==="accept"&&(this.accepting=!0),this.socket.send(JSON.stringify({...t==="start"?{id:this.id}:{},type:`${this.prefix}.${t}`,payload:d}))}};function te(n){return ie(ne(ke,[n]))}function De(n,t,d){return ie(ne(Ie,[te(n.picks),BigInt(n.stake),BigInt(d.counterpartyCollateral),t,d.counterparty,L,"0x"]))}function qe(n,t,d,c){return ie(ne(Se,[n.token,$.address,t,d,BigInt(n.amount),BigInt(c)]))}function Y(n,t){let{input:d,wallet:c,nonce:m,deadline:g}=n,l={name:d.side==="buy"?"PredictionMarketEscrow":"SecondaryMarketEscrow",version:"1",chainId:k,verifyingContract:n.continuation.escrowContract};return(!m||!g)&&i("Meridian exchange is missing its signing terms."),d.side==="buy"?(t||i("Meridian has not returned a winning bid."),{domain:l,primaryType:"MintApproval",types:{MintApproval:Ae},message:{predictionHash:De(d,c,t),signer:c,collateral:d.stake,nonce:m,deadline:g}}):{domain:l,primaryType:"TradeApproval",types:{TradeApproval:Ce},message:{tradeHash:qe(d,c,t?t.buyer:L,t?t.price:"0"),signer:c,nonce:m,deadline:g}}}function fe(n){let t=[BigInt(n.deadline)],d=n.continuation;if(d.stage==="primary_accept"||d.stage==="secondary_accept"){t.push(BigInt(d.acceptDeadline));let c=d.winningBid;d.stage==="primary_accept"&&t.push(BigInt(c.counterpartyDeadline)),c.buyerDeadline!==void 0&&t.push(BigInt(M(c.buyerDeadline,"the buyer deadline",!0)))}return t.reduce((c,m)=>c<m?c:m)}function H(n){n.channel?.check(),n.deadline&&j()>=fe(n)&&i("Meridian exchange expired. Start a fresh auction.")}var Oe=n=>{let t=new Map;function d(e){clearTimeout(e.timer),t.delete(e.continuation.requestId),e.channel?.stop("Meridian exchange is closed or expired. Start a fresh auction.")}function c(e,a){clearTimeout(e.timer),e.timer=setTimeout(()=>d(e),a),e.timer.unref?.()}function m(e){let{wallet:a,chainId:s,escrowContract:f,requestId:u}=e.continuation;return{wallet:a,chainId:s,escrowContract:f,requestId:u}}function g(e){return e.side!=="sell"?"":` Effective minimum sale proceeds: ${e.minPrice} USDe base units (${$.address}, 18 decimals). ${e.priceFloorSource==="explicit"?"Caller minPrice is unchanged; slippageBps does not reduce this floor.":`Default floor with ${e.slippageBps??0} bps slippage applied.`}`}async function l(e){let{input:a,wallet:s}=e,f=n.clientFor(k),u=a.side==="buy"?$.address:a.token,r=a.side==="buy"?a.stake:a.amount,[h,w]=await Promise.all([f.readContract({address:u,abi:J,functionName:"balanceOf",args:[s]}),f.readContract({address:u,abi:J,functionName:"allowance",args:[s,e.continuation.escrowContract]})]);if(a.side==="sell"&&await f.readContract({address:u,abi:J,functionName:"decimals"})!==18&&i("Meridian position tokens must have 18 decimals."),h>=BigInt(r)&&w>=BigInt(r))return;(e.continuation.stage==="primary_accept"||e.continuation.stage==="secondary_accept")&&i("Meridian prerequisites changed during the auction. Start a fresh auction after funding and approval.");let p,C;if(h<BigInt(r)){a.side==="sell"&&i("The wallet does not have enough position tokens to sell."),a.usdgAmountIn||i("Not enough USDe. Provide usdgAmountIn in USDG base units to quote a swap before the auction.");let b=await n.quoteSwap({from:G,to:$.address,amountIn:a.usdgAmountIn,...a.slippageBps===void 0?{}:{slippageBps:a.slippageBps}},s);(j()>=BigInt(M(b.expiresAt,"the swap expiry"))||BigInt(M(b.minAmountOut,"the swap minimum"))+h<BigInt(r))&&i("The USDG swap minimum does not cover the USDe stake, or the quote expired. Request a fresh quote with sufficient input.");let o=await n.buildSwap(b.quoteId,s);(!("txs"in o)||!o.txs.length)&&i("The swap coordinator did not return prerequisite transactions."),p=o.txs,C=`${o.summary} Minimum USDe output: ${b.minAmountOut} base units (18 decimals).`}else p=[n.approval(u,e.continuation.escrowContract,r,k)],C=`Approve exactly ${r} base units (18 decimals) of ${u} for ${e.continuation.escrowContract} on chain ${k}.`;p.some(b=>b.chainId!==k)&&i("Meridian prerequisite transactions must use chain 4663.");let q=await n.preview(p,s),T=q.changes.map(b=>{let o=b.amount.startsWith("-");return`${o?"-":"+"}${n.formatAmount(o?b.amount.slice(1):b.amount,b.token.decimals)} ${b.token.symbol} (${b.token.address}, chain ${b.token.chainId}, ${b.token.decimals} decimals)`}).join("; ");return e.channel?.stop("Meridian prerequisites must be mined before the auction."),e.channel=void 0,e.deadline=void 0,e.nonce=void 0,e.continuation={...m(e),stage:"prerequisites"},{steps:p.map(b=>({kind:"tx",tx:b})),continuation:structuredClone(e.continuation),summary:`${C}${g(a)} ${q.summary} ${T}. Mine these prerequisites before continuing; no RFQ has started.`}}function I(e){let a=e.continuation;a.stage==="prerequisites"&&i("Meridian prerequisites need to finish before signing."),H(e),c(e,Number(fe(e)-j())*1e3);let s=e.input,f=s.side==="buy"?`Stake ${s.stake} base units of USDe (${$.address}, 18 decimals)`:`Sell ${s.amount} base units of position ${s.token} (18 decimals)`,u=a.stage==="secondary_start"?"Initial buyer-zero, price-zero intent only.":a.stage==="primary_accept"?`Counterparty ${a.winningBid.counterparty}; counterparty collateral ${a.winningBid.counterpartyCollateral} USDe base units; counterparty deadline ${a.winningBid.counterpartyDeadline}.`:`Buyer ${a.winningBid.buyer}; receive ${a.winningBid.price} USDe base units (${$.address}, 18 decimals).`;return{steps:[{kind:"typedData",request:structuredClone(a.request)}],continuation:structuredClone(a),summary:`${f} on chain ${k}.${g(s)} Approval was checked on chain. ${u} Sign locally for domain ${a.request.domain.name}, version 1, escrow ${a.escrowContract}, signature deadline ${e.deadline}${"acceptDeadline"in a?`, acceptance deadline ${a.acceptDeadline}`:""}. External relayer settlement is pending; a signature is not a fill.`}}async function D(e){let a=await e.channel.wait("result"),s=_(a.winningBid),f=v(a.auctionId);s.auctionId!==f&&i("Meridian winning bid belongs to another auction.");let u=M(a.acceptDeadline,"the acceptance deadline",!0);if(e.input.side==="buy"){let r={auctionId:f,counterparty:v(s.counterparty),counterpartyCollateral:M(s.counterpartyCollateral,"the counterparty collateral"),counterpartyNonce:M(s.counterpartyNonce,"the counterparty nonce",!0),counterpartyDeadline:M(s.counterpartyDeadline,"the counterparty deadline",!0),receivedAt:v(s.receivedAt)};R(r.counterparty),(!Number.isFinite(Date.parse(r.receivedAt))||BigInt(r.counterpartyCollateral)<=1n||BigInt(r.counterpartyCollateral)<BigInt(e.input.minCounterpartyCollateral))&&i("Meridian winning bid counterparty collateral is below the caller minimum."),e.continuation={...m(e),stage:"primary_accept",auctionId:f,winningBid:r,acceptDeadline:u,request:Y(e,r)}}else{let r={auctionId:f,buyer:v(s.buyer),price:M(s.price,"the sale price"),...s.buyerDeadline!==void 0?{buyerDeadline:M(s.buyerDeadline,"the buyer deadline",!0)}:{},...s.buyerNonce!==void 0?{buyerNonce:M(s.buyerNonce,"the buyer nonce",!0)}:{},...s.receivedAt!==void 0?{receivedAt:v(s.receivedAt)}:{}};R(r.buyer),(BigInt(r.price)<=1n||BigInt(r.price)<BigInt(e.input.minPrice))&&i("Meridian winning bid sale price is below the caller minimum."),e.continuation={...m(e),stage:"secondary_accept",auctionId:f,winningBid:r,acceptDeadline:u,request:Y(e,r)}}return I(e)}async function S(e,a){let s=e.continuation;s.stage!=="primary_accept"&&s.stage!=="secondary_accept"&&i("Meridian exchange is not ready for acceptance."),H(e),e.channel.send("accept",{auctionId:s.auctionId,[e.input.side==="buy"?"predictorSignature":"sellerSignature"]:a}),c(e,15e4);let f=await e.channel.wait("filled",12e4),u=Z(f.transactionHash,32),r=n.clientFor(k),[h,w]=await Promise.all([r.waitForTransactionReceipt({hash:u,timeout:12e4}),r.getTransaction({hash:u})]);(h.status!=="success"||!y(h.transactionHash,u)||!y(w.hash,u)||!y(h.to,s.escrowContract)||!y(w.to,s.escrowContract)||w.chainId!==k)&&i("Meridian fill has no matching successful receipt on chain 4663.");let{input:p,wallet:C}=e;if(p.side==="buy"&&s.stage==="primary_accept"){let o=me({abi:Be,data:w.input}).args[0];(!y(te([...o.picks]),te(p.picks))||o.predictorCollateral!==BigInt(p.stake)||o.counterpartyCollateral!==BigInt(s.winningBid.counterpartyCollateral)||!y(o.predictor,C)||!y(o.counterparty,s.winningBid.counterparty)||o.predictorNonce!==BigInt(e.nonce)||o.predictorDeadline!==BigInt(e.deadline)||!y(o.predictorSponsor,L)||o.predictorSponsorData!=="0x"||!y(o.predictorSignature,a))&&i("Meridian mint receipt does not match the accepted prediction.")}else if(p.side==="sell"&&s.stage==="secondary_accept"){let o=me({abi:Me,data:w.input}).args[0];(!y(o.token,p.token)||!y(o.collateral,$.address)||!y(o.seller,C)||!y(o.buyer,s.winningBid.buyer)||o.tokenAmount!==BigInt(p.amount)||o.price!==BigInt(s.winningBid.price)||o.sellerNonce!==BigInt(e.nonce)||o.sellerDeadline!==BigInt(e.deadline)||!y(o.sellerSignature,a))&&i("Meridian sale receipt does not match the accepted trade.")}let q=new Map,T=new Map;for(let o of h.logs){if(o.topics[0]!==$e||o.topics.length!==3)continue;(!/^0x[0-9a-fA-F]{64}$/.test(o.data)||!o.topics.slice(1).every(ye=>/^0x0{24}[0-9a-fA-F]{40}$/.test(ye)))&&i("Meridian receipt has malformed transfer logs.");let E=`0x${o.topics[1].slice(-40)}`,U=`0x${o.topics[2].slice(-40)}`,P=o.address.toLowerCase(),z=BigInt(o.data);q.set(P,(q.get(P)??0n)+(y(U,C)?z:0n)-(y(E,C)?z:0n)),y(E,L)&&y(U,C)&&T.set(P,(T.get(P)??0n)+z)}let b;if(p.side==="buy"&&s.stage==="primary_accept"){let o=BigInt(p.stake)+BigInt(s.winningBid.counterpartyCollateral),E=[...T].filter(([U,P])=>!y(U,$.address)&&P===o&&q.get(U)===o);(E.length!==1||q.get($.address.toLowerCase())!==-BigInt(p.stake))&&i("Meridian mint receipt does not prove the expected collateral and position delta."),b=`${o} base units received in position ${E[0][0]}`}else p.side==="sell"&&s.stage==="secondary_accept"?((q.get(p.token.toLowerCase())!==-BigInt(p.amount)||q.get($.address.toLowerCase())!==BigInt(s.winningBid.price))&&i("Meridian sale receipt does not prove the expected collateral and position delta."),b=`${p.amount} base units sold from position ${p.token}; ${s.winningBid.price} USDe base units received`):i("Meridian fill has a different exchange stage.");return{txs:[],hashes:[u],status:"mined",summary:`Mined: ${u}. Status: mined. Meridian ${p.side} filled by the external relayer. Successful receipt and transfer deltas verified on chain ${k}: ${b} (18 decimals); collateral USDe ${$.address} (18 decimals).`}}async function B(e,a,s){let f=R(s),u=ve(e,a),r;if(a.continuation!==void 0){let h=_(a.continuation),w=t.get(v(h.requestId));w||i("Meridian exchange is lost or expired. Start a fresh auction."),(!y(w.wallet,f)||!pe(w.input,u)||!pe(w.continuation,h))&&i("Meridian continuation or arguments do not match the active wallet exchange."),w.busy&&i("Meridian exchange is already processing this continuation."),r=w}else{a.signature!==void 0&&i("A signature requires an active Meridian continuation."),t.size>=1e3&&i("Too many active Meridian exchanges. Please try again later.");let h=he(),w=setTimeout(()=>{let p=t.get(h);p&&d(p)},9e5);w.unref?.(),r={input:u,wallet:f,continuation:{stage:"prerequisites",wallet:f,chainId:k,escrowContract:e==="buy"?Q:V,requestId:h},busy:!1,timer:w},t.set(h,r)}r.busy=!0;try{H(r),await n.clientFor(k).getChainId()!==k&&i("Meridian requires an RPC on chain 4663.");let h=r.continuation.stage;h==="prerequisites"&&a.signature!==void 0&&i("Do not sign before Meridian prerequisites have mined.");let w=await l(r);if(w)return w;if(h==="prerequisites")return r.nonce=(ge(4).readUInt32BE()+1).toString(),r.deadline=(j()+300n).toString(),await n.clientFor(k).readContract({address:r.continuation.escrowContract,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i(`Meridian ${e==="buy"?"predictor":"seller"} nonce is already used. Start a fresh auction.`),r.channel=new ee(r.continuation.requestId,e==="buy"?"auction":"secondary.auction"),await r.channel.wait(),u.side==="buy"?(r.channel.send("start",{id:r.continuation.requestId,picks:u.picks,predictorCollateral:u.stake,predictor:f,predictorNonce:F(r.nonce),predictorDeadline:F(r.deadline),chainId:k,escrowContract:Q,mode:"blind"}),await D(r)):(r.continuation={...m(r),stage:"secondary_start",request:Y(r)},I(r));let p=Z(a.signature);if(e==="sell"&&await n.clientFor(k).readContract({address:V,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i("Meridian seller nonce is already used. Start a fresh auction."),e==="buy"&&await n.clientFor(k).readContract({address:Q,abi:X,functionName:"isNonceUsed",args:[f,BigInt(r.nonce)]})&&i("Meridian predictor nonce is already used. Start a fresh auction."),H(r),h==="secondary_start"&&u.side==="sell")return r.channel.send("start",{id:r.continuation.requestId,token:u.token,collateral:$.address,tokenAmount:u.amount,seller:f,sellerNonce:F(r.nonce),sellerDeadline:F(r.deadline),chainId:k,escrowContract:V,mode:"blind",sellerSignature:p}),await D(r);let C=await S(r,p);return d(r),C}catch(h){throw d(r),new N(n.plainError(h))}finally{r.busy=!1}}let A={continuation:{type:"object"},signature:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"}};return{tools:[{name:"meridian_buy",inputSchema:{type:"object",additionalProperties:!1,required:["picks","stake"],properties:{...A,stake:x("USDe stake in base units, 18 decimals, chain 4663."),minCounterpartyCollateral:x("Optional caller minimum counterparty collateral in USDe base units, 18 decimals."),usdgAmountIn:x("Optional exact USDG swap input in base units, 6 decimals, if USDe balance is insufficient."),slippageBps:{type:"integer",minimum:0,maximum:9999},picks:{type:"array",minItems:1,maxItems:10,items:{type:"object",additionalProperties:!1,required:["conditionResolver","conditionId","predictedOutcome"],properties:{conditionResolver:W,conditionId:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"},predictedOutcome:{type:"integer",enum:[0,1]}}}}}},execute:(e,a)=>B("buy",e,a)},{name:"meridian_sell",inputSchema:{type:"object",additionalProperties:!1,required:["token","amount"],properties:{...A,token:{...W,description:"Position token address on chain 4663."},amount:x("Position amount in base units, 18 decimals."),minPrice:x("Optional minimum total sale proceeds in USDe base units, 18 decimals. Explicit minPrice is never reduced by slippageBps."),slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Applied only to the default sale floor when minPrice is omitted."}}},execute:(e,a)=>B("sell",e,a)}]}};export{Ae as a,Ce as b,Oe as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as U}from"./
|
|
1
|
+
import{d as U}from"./IKEJCBYU.js";import{a as _}from"./PBQSJSZO.js";import{a as I}from"./5ZLOCQA4.js";import{g as $}from"./5KUWLUPM.js";import{a as w,i as V}from"./FWD4L3CJ.js";import{a as s}from"./XSD5NL7J.js";import{decodeAbiParameters as N,encodeAbiParameters as K,encodeFunctionData as h,getAddress as P,keccak256 as Y,parseAbi as H,parseAbiParameters as B}from"viem";var y=P("0xCe5c1aFa115fF8b1D6913509bfc79D9AE08CC857"),q=P("0x0FBad98595b0186dA120E41f77C102beb49f803c"),D=B("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),A="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",m=H(["function vaultV2Factory() view returns (address)","function vaultData(address) view returns (bool canPullFromIdle,uint64 penalty)","function absoluteCap(address,bytes32) view returns (uint256)","function canPullFromMarket(address,bytes32) view returns (bool)","function isActiveAdapter(address,address) view returns (bool)",`function reallocate(address vault,address deallocateAdapter,${A} deallocateMarketParams,address allocateAdapter,${A} allocateMarketParams,uint128 assets,uint64 penalty)`,`function allocateFromIdle(address vault,address adapter,${A} marketParams,uint128 assets,uint64 penalty)`,`function setAbsoluteCap(address vault,address adapter,${A} marketParams,uint256 newAbsoluteCap)`,`function setCanPullFromMarket(address vault,address adapter,${A} marketParams,bool newCanPullFromMarket)`,"function setCanPullFromIdle(address vault,bool newCanPullFromIdle)","function setIsActiveAdapter(address vault,address adapter,bool newIsActiveAdapter)","function setPenalty(address vault,uint64 newPenalty)"]),E=H(["function isAllocator(address) view returns (bool)","function allocation(bytes32) view returns (uint256)"]),z=H(["function isVaultV2(address) view returns (bool)"]),v=V[w],L=[{vault:v.vaults.netnet.address,underlying:v.tokens.USDG.address,symbol:"USDG",decimals:6},{vault:v.vaults.longbowCore.address,underlying:v.tokens.USDG.address,symbol:"USDG",decimals:6},{vault:v.vaults.longbowFrontier.address,underlying:v.tokens.USDG.address,symbol:"USDG",decimals:6},{vault:v.vaults.longbowEth.address,underlying:v.tokens.WETH.address,symbol:"WETH",decimals:18}];function x(n,c=256){if(typeof n!="string"||!/^\d+$/.test(n)||n.length>78||BigInt(n)>=1n<<BigInt(c))throw new s("Provide uint decimal base-unit strings.");return BigInt(n)}function R(n){if(typeof n!="string"||!/^0x[0-9a-f]{64}$/i.test(n))throw new s("Provide the exact bytes32 marketId.");return n.toLowerCase()}var M=(n,c)=>n<c?n:c;async function Q(n,c){let l=L.find(u=>typeof c.vault=="string"&&$(u.vault,c.vault));if(!l)throw new s("Choose a pinned NetNet or Longbow V2 vault.");let a={address:P(l.underlying),chainId:w,symbol:l.symbol,decimals:l.decimals},o=n.clientFor(w),e=await U(o,l.vault,a),i=(u,F,W,J=[])=>o.readContract({address:u,abi:F,functionName:W,args:J,blockNumber:e.blockNumber}),t=R(c.marketId),r=e.markets.find(u=>u.id.toLowerCase()===t);if(!r)throw new s("Target market is not in this verified vault adapter inventory.");let[p,b,k,f,O]=await Promise.all([i(y,m,"vaultV2Factory"),i(q,z,"isVaultV2",[l.vault]),i(l.vault,E,"isAllocator",[y]),i(y,m,"vaultData",[l.vault]),i(y,m,"isActiveAdapter",[l.vault,r.adapter])]);if(typeof p!="string"||P(p)!==q||b!==!0||!Array.isArray(f)||f.length!==2||typeof f[0]!="boolean"||typeof f[1]!="bigint")throw new s("Invalid Public Allocator deployment or vault configuration.");let[d]=N(D,r.data);if(P(d.irm)!==P(v.morpho.adaptive_curve_irm.address))throw new s("Public allocation requires the pinned Adaptive Curve IRM.");let g=(u,F)=>Y(K(B(`string,address,${A}`),["this/marketParams",F,N(D,u)[0]])),C=g(r.data,r.adapter),[S,T]=await Promise.all([i(y,m,"absoluteCap",[l.vault,C]),i(l.vault,E,"allocation",[C])]);if(typeof S!="bigint"||typeof T!="bigint")throw new s("Invalid allocator cap read.");let G=S>T?S-T:0n,j=await Promise.all(e.markets.filter(u=>u.id.toLowerCase()!==t).map(async u=>({...u,canPull:await i(y,m,"canPullFromMarket",[l.vault,g(u.data,u.adapter)])===!0})));return{client:o,read:i,asset:a,definition:l,data:e,target:r,params:d,permission:k===!0&&O===!0,canIdle:f[0],penalty:f[1],headroom:G,sources:j}}var rt=n=>{let c=a=>Q(n,a),l=(a,o,e,i)=>{let t={vault:{type:"string",enum:L.map(r=>r.vault)},marketId:{type:"string"},...o};return{name:a,inputSchema:{type:"object",properties:t,required:["vault","marketId",...e],additionalProperties:!1},execute:async(r,p)=>{try{if(_(p),Object.keys(r).some(b=>!Object.hasOwn(t,b)))throw new s("Unsupported Public Allocator argument.");return await i(r,p)}catch(b){throw new s(n.plainError(b))}}}};return{tools:[l("morpho_allocator",{},[],async a=>{let o=await c(a);return{chainId:w,allocator:y,vault:o.definition.vault,targetMarketId:o.target.id,asset:o.asset,blockNumber:o.data.blockNumber.toString(),enabled:o.permission,penaltyWad:o.penalty.toString(),absoluteCapHeadroom:o.headroom.toString(),idleUpperBound:(o.permission&&o.canIdle?M(o.data.idle,o.headroom):0n).toString(),sources:o.sources.map(e=>({marketId:e.id,canPull:e.canPull,assetsUpperBound:(o.permission&&e.canPull?M(M(e.capacity,o.data.blueCash),o.headroom):0n).toString()})),caveat:"Upper bounds only; vault relative/absolute caps, accrual and liquidity still constrain execution. Preview an explicit source and amount with morpho_reallocate. This standalone allocation charges its disclosed penalty; a later borrow is a separate transaction and can fail or lose the added liquidity to another borrower."}}),l("morpho_reallocate",{sourceMarketId:{type:"string",description:"A returned source market ID, or omit to allocate idle assets."},assets:I(),maxPenaltyAssets:I()},["assets","maxPenaltyAssets"],async(a,o)=>{let e=x(a.assets,128),i=x(a.maxPenaltyAssets),t=await c(a);if(!t.permission||e===0n||e>t.headroom||t.penalty>10n**18n)throw new s("Public allocation is disabled or the requested amount exceeds target headroom.");let r=(e*t.penalty+10n**18n-1n)/10n**18n;if(r>i)throw new s("Allocator penalty exceeds maxPenaltyAssets.");let p;if(a.sourceMarketId===void 0){if(!t.canIdle||e>t.data.idle)throw new s("Public idle allocation is disabled or idle funds are insufficient.");p=h({abi:m,functionName:"allocateFromIdle",args:[t.definition.vault,t.target.adapter,t.params,e,t.penalty]})}else{let d=t.sources.find(C=>C.id.toLowerCase()===R(a.sourceMarketId));if(!d||!d.canPull||e>M(d.capacity,t.data.blueCash))throw new s("The source cannot publicly supply the requested liquidity.");let[g]=N(D,d.data);p=h({abi:m,functionName:"reallocate",args:[t.definition.vault,d.adapter,g,t.target.adapter,t.params,e,t.penalty]})}let b=`Move ${e} ${t.asset.symbol} base units inside ${t.definition.vault} to market ${t.target.id}; pay ${r} ${t.asset.symbol} base units as a donation penalty. This is a standalone reallocation; a subsequent borrow is separate and not guaranteed.`,k=[...r?[n.approval(t.asset.address,y,r.toString(),w)]:[],n.unsignedTx({to:y,data:p,value:"0",chainId:w,description:b})],f=await n.preview(k,o);if(f.changes.filter(d=>d.token.chainId===w&&$(d.token.address,t.asset.address)&&d.token.decimals===t.asset.decimals).reduce((d,g)=>d+BigInt(g.amount),0n)!==-r)throw new s("Allocator preview does not match the exact donation penalty.");return{txs:k,preview:f,penaltyAmount:r.toString(),summary:`${b} The calldata binds the current penalty rate. ${f.summary}`}}),l("morpho_manage_allocator",{operation:{enum:["setIsActiveAdapter","setCanPullFromMarket","setCanPullFromIdle","setAbsoluteCap","setPenalty"]},enabled:{type:"boolean"},amount:I()},["operation"],async(a,o)=>{let e=await c(a);if(await e.read(e.definition.vault,E,"isAllocator",[o])!==!0)throw new s("This wallet is not an allocator of this vault.");let i=a.enabled,t;if(a.operation==="setAbsoluteCap")t=h({abi:m,functionName:"setAbsoluteCap",args:[e.definition.vault,e.target.adapter,e.params,x(a.amount)]});else if(a.operation==="setPenalty"){let b=x(a.amount,64);if(b>10n**18n)throw new s("Public Allocator penalty must not exceed 1e18.");t=h({abi:m,functionName:"setPenalty",args:[e.definition.vault,b]})}else{if(typeof i!="boolean")throw new s("Provide enabled as a boolean.");if(a.operation==="setIsActiveAdapter")t=h({abi:m,functionName:"setIsActiveAdapter",args:[e.definition.vault,e.target.adapter,i]});else if(a.operation==="setCanPullFromMarket")t=h({abi:m,functionName:"setCanPullFromMarket",args:[e.definition.vault,e.target.adapter,e.params,i]});else if(a.operation==="setCanPullFromIdle")t=h({abi:m,functionName:"setCanPullFromIdle",args:[e.definition.vault,i]});else throw new s("Choose a supported allocator configuration operation.")}let r=`Configure Morpho Public Allocator ${String(a.operation)}: ${JSON.stringify(a)}.`,p=[n.unsignedTx({to:y,data:t,value:"0",chainId:w,description:r})];return{txs:p,preview:await n.preview(p,o),summary:r}})]}};export{y as a,q as b,m as c,Q as d,rt as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as d,b as f}from"./
|
|
1
|
+
import{a as d,b as f}from"./WMNRP3YH.js";import{a}from"./P4UQGWCP.js";import{g as s}from"./5KUWLUPM.js";import{a as n}from"./XSD5NL7J.js";import{getAddress as m,keccak256 as u}from"viem";var l=a.vaults;function c(t,o=!0){let e=l.find(r=>s(r.earnContractAddress,t));if(!e&&o)throw new n("This Beefy vault is not in the pinned chain 4663 standard-vault inventory.");return e}async function v(t,o,e){c(o);let[r,i]=await Promise.all([t.getCode({address:m(o),blockNumber:e}),t.getCode({address:d,blockNumber:e})]),p=`0x363d3d373d3d3d363d73${d.slice(2).toLowerCase()}5af43d82803e903d91602b57fd5bf3`;if(r?.toLowerCase()!==p||!i||u(i)!==f)throw new n("The Beefy standard vault or implementation no longer matches its verified code.")}export{l as a,c as b,v as c};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{f as b,g as L,i as B,m as o,n as D,o as U}from"./KBKK7UNY.js";import{$ as _,T as f,Y as m,Z as g,_ as p,aa as d,b as e}from"./PSVOVZH7.js";function S(n){if(n==null)return;let t=n instanceof Date?n.getTime()/1e3:typeof n=="string"?Date.parse(n)/1e3:n;return typeof t=="number"&&Number.isFinite(t)?Math.floor(t):void 0}function x(n){let t=n.nowSec??Math.floor(Date.now()/1e3),r=S(n.endDate),u=typeof n.apr=="number"&&Number.isFinite(n.apr)?n.apr:void 0,a=Number.isFinite(n.amountUsd)&&n.amountUsd>0?n.amountUsd:void 0,l={addButton:_,declineButton:d};if(u===void 0||r===void 0||r<=t||a===void 0)return{text:e(p,{}),readable:!1,notWorth:!0,defaultButton:d,...l};let i=b(n.gasUsd),c=B({amountUsd:a,ratePct:u,days:(r-t)/86400}),s=L({gross:c,costs:i.usd,amount:a}),W=[s.tooSmall?e(g,{}):"",i.estimatedHigh?e(f,{}):""].filter(Boolean).join(" ");return{text:e(m,{apr:D(u).replace(/\.00$/,""),amount_usd:o(a),gross_usd:o(c),end_date:U(r),gas_usd:o(i.usd),net_usd:o(s.netUsd),worth_clause:W}).replace(/ +\n/g,`
|
|
2
|
+
`),readable:!0,notWorth:s.tooSmall,...s.tooSmall?{defaultButton:d}:{},...l}}function N(n){return x(n).text}export{x as a,N as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as Y}from"./S2TAJHHK.js";import{b as V,c as W,d as G}from"./65EQECL3.js";import{d as de,e as P}from"./GHPREYQK.js";import{a as B}from"./HTXKERNS.js";import{a as N}from"./PBQSJSZO.js";import{a as H,b as se,c as ae,d as j}from"./UP7FBDMJ.js";import{a as C,i as D}from"./FWD4L3CJ.js";import{a as o}from"./XSD5NL7J.js";import{a as S}from"./JXOEJPJ4.js";import{decodeEventLog as $e,encodeAbiParameters as pe,encodeFunctionData as ye,erc20Abi as Z,getAddress as l,isAddress as E,keccak256 as Ee,parseAbi as _e,parseAbiParameters as we,toEventSelector as ge}from"viem";var A=l(D[4663].hookr.HookrLimitOrders.address),ve=l(D[4663].hookr.HookrRoot.address),Ne=l(D[4663].hookr.HookrRouter.address),It=l(D[4663].hookr.HookrRegistry.address),Be=l(D[4663].hookr.HookrForwarder.address),Fe=l(D[4663].hookr.PoolManager.address),At=l(D[4663].hookr.HOOKR_Token.address),Me=l("0x000000000000000000000000000000000000dEaD"),ze=8388608,qe=200,ce=60n,Xe=604800n,ue=31536000n,ht=10,St=100,Ct="500000000000000",xt="10000000000000000",me=4096n,Q=32n,Ke=1e4,Ue=(1n<<127n)-1n,le=(1n<<128n)-1n,je=(1n<<160n)-1n,Ve=(1n<<40n)-1n,We=16777215,Ge=8388607,fe=1n<<192n,ee=0,M=1,Ye=2,Qe=3,Ze=ge("OrderCreated(uint256,address,bytes32,bool,uint128,uint128,uint128,uint40,address)"),Dt=ge("OrderCancelled(uint256,address,address,uint256,uint256)"),L=_e(["function bountyBounds((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, bool zeroForOne, uint128 amountIn, uint128 minAmountOut) view returns (uint128 minBounty, uint128 defaultBounty, uint128 maxBounty)","function createOrder(((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, bool zeroForOne, uint128 amountIn, uint128 minAmountOut, uint160 sqrtPriceLimitX96, address recipient, uint40 expiry, uint128 bounty) params) payable returns (uint256 orderId)","function cancel(uint256 orderId, address to)","function getOrder(uint256 orderId) view returns (((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, address owner, uint40 createdAt, uint40 expiry, bool zeroForOne, uint8 status, address recipient, uint128 amountIn, uint128 minAmountOut, uint128 bounty, uint160 sqrtPriceLimitX96))","function quoteFill(uint256 orderId) view returns (bool fillable, uint256 amountOut)","function lastOrderId() view returns (uint256)","function liabilities(address currency) view returns (uint256)","function router() view returns (address)","function registry() view returns (address)","function poolManager() view returns (address)","function forwarder() view returns (address)","event OrderCreated(uint256 indexed orderId, address indexed owner, bytes32 indexed poolId, bool zeroForOne, uint128 amountIn, uint128 minAmountOut, uint128 bounty, uint40 expiry, address recipient)","event OrderCancelled(uint256 indexed orderId, address indexed owner, address indexed to, uint256 amountIn, uint256 bounty)"]);function F(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function be(e){let t=e.toLowerCase();return t===P.toLowerCase()||t===B.toLowerCase()||t===de.toLowerCase()}function $(e,t){if(typeof e!="string"||!e.trim())throw new o(`Provide a valid contract address for ${t}. Identify tokens by chain and address, never by symbol.`);let n=e.trim();if(!E(n,{strict:!1}))throw new o(`Invalid token address "${n}" for ${t}. Identify tokens by chain and address, never by symbol.`);return be(n)?P:l(n)}function ke(e){let t=e===void 0?C:Number(e);if(!Number.isSafeInteger(t)||t!==C)throw new o(`Hookr limit orders are only supported on Robinhood Chain (${C}).`);return C}function Je(e){switch(e){case ee:return"None";case M:return"Open";case Ye:return"Filled";case Qe:return"Cancelled";default:return"Unknown"}}function et(e,t,n=ae){if(typeof e!="string"||!/^-?\d+$/.test(e.trim()))throw new o("Signed amount must be an integer string in base units.");let r=e.trim();if(r.startsWith("-")){let i=r.slice(1),u=n(i,t);return u==="0"?"0":`-${u}`}return n(r,t)}function Lt(e,t,n="floor"){return se(e,t,n)}function Oe(e){return Ee(pe(we("address, address, uint24, int24, address"),[l(e.currency0),l(e.currency1),e.fee,e.tickSpacing,l(e.hooks)]))}function Ie(e,t){let n=e.toLowerCase();if(new Set([P.toLowerCase(),Me.toLowerCase(),A.toLowerCase(),Ne.toLowerCase(),Be.toLowerCase(),Fe.toLowerCase(),t.toLowerCase()]).has(n))throw new o(`Recipient ${e} is a reserved address and cannot receive Hookr limit order funds.`)}async function J(e,t,n,r){if(be(e))return{address:B,symbol:V.symbol,decimals:V.decimals,chainId:t};let i=l(e),u=i.toLowerCase();if(F(r)){let s=typeof r.decimals=="number"&&Number.isInteger(r.decimals)&&r.decimals>=0&&r.decimals<=255?r.decimals:void 0,a=typeof r.symbol=="string"&&r.symbol.trim()?r.symbol.trim():void 0;if(s!==void 0&&a!==void 0)return{address:i,symbol:a,decimals:s,chainId:t}}if(u===W.address.toLowerCase())return{...W,chainId:t};if(u===G.address.toLowerCase())return{...G,chainId:t};try{let[s,a]=await Promise.all([n.readContract({address:i,abi:Z,functionName:"symbol"}),n.readContract({address:i,abi:Z,functionName:"decimals"})]);if(typeof s!="string"||!s.trim()||typeof a!="number"||!Number.isInteger(a)||a<0||a>255)throw new o(`Invalid token metadata for ${i}.`);return{address:i,symbol:s.trim(),decimals:a,chainId:t}}catch{throw new o(`Could not read valid token metadata for ${i}. Refusing to guess token decimals.`)}}function tt(e){let t=F(e.key)?e.key:F(e.poolKey)?e.poolKey:void 0,n=t?.fee??e.fee??ze,r=(typeof n=="string"&&/^\d+$/.test(n),Number(n));if(!Number.isInteger(r)||r<0||r>We)throw new o("Pool fee must be a valid uint24 integer (default 8388608 for Hookr dynamic fee pools).");let i=t?.tickSpacing??e.tickSpacing??qe,u=(typeof i=="string"&&/^-?\d+$/.test(i),Number(i));if(!Number.isInteger(u)||u<=0||u>Ge)throw new o("Pool tickSpacing must be a positive int24 integer.");let s=t?.hooks??e.hooks??ve;if(typeof s!="string"||!E(s,{strict:!1}))throw new o("Provide a valid Hookr root contract address for hooks.");let a=l(s);if(t?.currency0!==void 0&&t?.currency1!==void 0||e.currency0!==void 0&&e.currency1!==void 0){let m=$(t?.currency0??e.currency0,"currency0"),I=$(t?.currency1??e.currency1,"currency1");if(m.toLowerCase()===I.toLowerCase())throw new o("Pool currency0 and currency1 must be distinct token addresses.");if(BigInt(m)>=BigInt(I))throw new o("Pool currency0 must sort strictly before currency1 by address.");let k;if(typeof e.zeroForOne=="boolean")k=e.zeroForOne;else if(e.tokenIn!==void 0||e.from!==void 0){let x=$(e.tokenIn??e.from,"tokenIn");if(x.toLowerCase()===m.toLowerCase())k=!0;else if(x.toLowerCase()===I.toLowerCase())k=!1;else throw new o("tokenIn does not match currency0 or currency1 of the pool key.")}else throw new o("Provide zeroForOne (boolean) or tokenIn when specifying a pool key.");return{key:{currency0:m,currency1:I,fee:r,tickSpacing:u,hooks:a},zeroForOne:k}}let w=e.tokenIn??e.from,f=e.tokenOut??e.to;if(w===void 0||f===void 0)throw new o("Provide either key ({ currency0, currency1, fee, tickSpacing, hooks }) with zeroForOne or tokenIn and tokenOut addresses.");let g=$(w,"tokenIn"),b=$(f,"tokenOut");if(g.toLowerCase()===b.toLowerCase())throw new o("Input and output tokens must have distinct addresses.");let p=BigInt(g)<BigInt(b),y=p?g:b,d=p?b:g;if(typeof e.zeroForOne=="boolean"&&e.zeroForOne!==p)throw new o("zeroForOne conflicts with the canonical sorting of tokenIn and tokenOut.");return{key:{currency0:y,currency1:d,fee:r,tickSpacing:u,hooks:a},zeroForOne:p}}function nt(e,t,n){let r=Y(t),i=r*r;if(n){let s=j(e.toString(),i.toString(),fe.toString(),"ceil");return BigInt(s)}let u=j(e.toString(),fe.toString(),i.toString(),"ceil");return BigInt(u)}function R(e,t){if(typeof e=="bigint"){if(e<0n)throw new o(`${t} must be a non-negative integer.`);return e}if(typeof e=="number"){if(!Number.isSafeInteger(e)||e<0)throw new o(`${t} must be a non-negative safe integer.`);return BigInt(e)}if(typeof e=="string")return H(e.trim());throw new o(`Provide ${t} as a decimal base-unit string.`)}async function ot(e,t){if(t!==void 0)return R(t,"now");if(typeof e.getBlock=="function"){let n=await e.getBlock().catch(()=>{throw new o("Could not read the chain timestamp for Hookr order expiry.")});return BigInt(n.timestamp)}throw new o("Could not read the chain timestamp for Hookr order expiry.")}function Ae(e,t){return!e.changes||e.changes.length===0?"no net ERC-20 transfer deltas":e.changes.map(n=>`${et(n.amount,n.token.decimals,t.formatAmount)} ${S(n.token.symbol)}`).join(", ")}function rt(e,t,n,r){if(!e||!Array.isArray(e.logs))throw new o("Provide a transaction receipt with a logs array.");for(let i of e.logs){if(!i||typeof i.address!="string"||!E(i.address,{strict:!1})||!Array.isArray(i.topics)||typeof i.data!="string"||i.topics.some(u=>typeof u!="string"||!/^0x[0-9a-fA-F]{64}$/.test(u)))throw new o(`Malformed Hookr ${t} receipt log.`);if(i.address.toLowerCase()===A.toLowerCase()&&i.topics[0]?.toLowerCase()===n.toLowerCase()){if(i.topics.length!==4||!/^0x0{24}/i.test(i.topics[2])||t==="OrderCancelled"&&!/^0x0{24}/i.test(i.topics[3])||!/^0x[0-9a-fA-F]*$/.test(i.data)||i.data.length!==2+r*64)throw new o(`Malformed Hookr ${t} receipt log.`);return{topics:i.topics,data:i.data}}}throw new o(`Could not find Hookr ${t} event in transaction receipt logs.`)}function he(e){if(e.receipt!==void 0){if(!F(e.receipt)||!Array.isArray(e.receipt.logs))throw new o("Provide a transaction receipt with a logs array.");return st({logs:e.receipt.logs})}if(e.logs!==void 0){if(!Array.isArray(e.logs))throw new o("Provide receipt logs as an array.");return it(e.logs)}}function Se(e){let t=rt(e,"OrderCreated",Ze,6);try{let n=$e({abi:L,eventName:"OrderCreated",...t,strict:!0});if(pe(we("bool, uint128, uint128, uint128, uint40, address"),[n.args.zeroForOne,n.args.amountIn,n.args.minAmountOut,n.args.bounty,n.args.expiry,n.args.recipient]).toLowerCase()!==t.data.toLowerCase())throw new o("Noncanonical Hookr OrderCreated event data.");return{orderId:n.args.orderId.toString(),owner:l(n.args.owner),poolId:n.args.poolId,zeroForOne:n.args.zeroForOne,amountIn:n.args.amountIn.toString(),minAmountOut:n.args.minAmountOut.toString(),bounty:n.args.bounty.toString(),expiry:n.args.expiry.toString(),recipient:l(n.args.recipient)}}catch{throw new o("Malformed Hookr OrderCreated receipt log.")}}function it(e){return Se({logs:e}).orderId}function st(e){return Se(e).orderId}function Ce(e){if(Array.isArray(e)){let[n,r,i,u,s,a,c,w,f,g,b]=e;return{key:Array.isArray(n)?{currency0:n[0],currency1:n[1],fee:Number(n[2]),tickSpacing:Number(n[3]),hooks:n[4]}:n,owner:r,createdAt:i,expiry:u,zeroForOne:s,status:a,recipient:c,amountIn:BigInt(w),minAmountOut:BigInt(f),bounty:BigInt(g),sqrtPriceLimitX96:BigInt(b)}}let t=e;return{key:{currency0:t.key.currency0,currency1:t.key.currency1,fee:Number(t.key.fee),tickSpacing:Number(t.key.tickSpacing),hooks:t.key.hooks},owner:t.owner,createdAt:t.createdAt,expiry:t.expiry,zeroForOne:!!t.zeroForOne,status:Number(t.status),recipient:t.recipient,amountIn:BigInt(t.amountIn),minAmountOut:BigInt(t.minAmountOut),bounty:BigInt(t.bounty),sqrtPriceLimitX96:BigInt(t.sqrtPriceLimitX96)}}async function xe(e,t,n){let r=R(t,"orderId");if(r<=0n)throw new o("Order ID must be a positive integer.");let i=e.clientFor(C),u=n?.order??await i.readContract({address:A,abi:L,functionName:"getOrder",args:[r]}).catch(()=>{throw new o(`Could not read Hookr order #${r}. Order coverage is incomplete.`)}),s=Ce(u),a=Number(s.status);if(s.owner.toLowerCase()===P.toLowerCase()||a===ee)throw new o(`Hookr order #${r} does not exist.`);let c={currency0:l(s.key.currency0),currency1:l(s.key.currency1),fee:Number(s.key.fee),tickSpacing:Number(s.key.tickSpacing),hooks:l(s.key.hooks)},w=s.zeroForOne?c.currency0:c.currency1,f=s.zeroForOne?c.currency1:c.currency0,g=m=>{let I=m.toLowerCase(),k=n?.tokens.get(I);if(k)return k;let x=J(m,C,i);return n?.tokens.set(I,x),x},[b,p]=await Promise.all([g(w),g(f)]),y=!1,d=0n;if(a===M)try{let m=await i.readContract({address:A,abi:L,functionName:"quoteFill",args:[r]});if(typeof m[0]!="boolean"||typeof m[1]!="bigint"||m[1]<0n)throw new o(`Invalid quote for Hookr order #${r}.`);y=m[0],d=m[1]}catch{throw new o(`Could not quote Hookr order #${r}. Fillability and output amount are unknown.`)}return{orderId:r.toString(),poolId:Oe(c),key:c,owner:l(s.owner),recipient:l(s.recipient),createdAt:BigInt(s.createdAt).toString(),expiry:BigInt(s.expiry).toString(),zeroForOne:s.zeroForOne,status:a,statusLabel:Je(a),amountIn:s.amountIn.toString(),minAmountOut:s.minAmountOut.toString(),bounty:s.bounty.toString(),sqrtPriceLimitX96:s.sqrtPriceLimitX96.toString(),tokenIn:b,tokenOut:p,fillable:y,quotedAmountOut:d.toString()}}function at(e){return{name:"hookr_create",inputSchema:{type:"object",properties:{key:{type:"object",properties:{currency0:{type:"string"},currency1:{type:"string"},fee:{type:"number"},tickSpacing:{type:"number"},hooks:{type:"string"}}},tokenIn:{type:"string",description:"Input token address on chain 4663."},tokenOut:{type:"string",description:"Output token address on chain 4663."},zeroForOne:{type:"boolean",description:"True when selling currency0 for currency1."},amountIn:{type:"string",description:"Input amount in base units (uint128)."},minAmountOut:{type:"string",description:"Minimum net output amount in base units (uint128)."},tick:{type:"number",description:"Optional limit tick in [-887272, 887272]."},expiry:{type:"string",description:"Order expiry unix timestamp in seconds (uint40)."},deadline:{type:"string",description:"Alias for expiry unix timestamp in seconds."},bounty:{type:"string",description:"Keeper bounty in native ETH wei (uint128)."},recipient:{type:"string",description:"Order output recipient address (must be the signing wallet)."},sqrtPriceLimitX96:{type:"string",description:"Optional sqrtPriceLimitX96 (defaults to 0)."},chainId:{type:"number",description:"Must be 4663 (Robinhood Chain)."}},required:["amountIn"]},async execute(t,n){N(n);let r=l(n),i=ke(t.chainId),u=e.clientFor(i),s=he(t),{key:a,zeroForOne:c}=tt(t),w=c?a.currency0:a.currency1,f=c?a.currency1:a.currency0,[g,b]=await Promise.all([J(w,i,u,t.tokenInMeta),J(f,i,u,t.tokenOutMeta)]),p=t.recipient??r;if(typeof p!="string"||!E(p,{strict:!1}))throw new o("Provide a valid recipient address for the Hookr limit order.");let y=l(p);if(Ie(y,a.hooks),y!==r)throw new o("Hookr recipient must be the signing wallet.");if(typeof t.amountIn!="string")throw new o("Provide amountIn as an integer string in base units.");let d=H(t.amountIn);if(d<=0n||d>Ue)throw new o("amountIn must be between 1 and int128.max base units.");if(t.tick!==void 0){let T=Number(t.tick);Y(T)}let m;if(t.minAmountOut!==void 0){if(typeof t.minAmountOut!="string")throw new o("Provide minAmountOut as an integer string in base units.");m=H(t.minAmountOut)}else if(t.tick!==void 0)m=nt(d,Number(t.tick),c);else throw new o("Provide minAmountOut in base units (or tick to derive minAmountOut).");if(m<=0n||m>le)throw new o("minAmountOut must be between 1 and uint128.max base units.");let I=t.sqrtPriceLimitX96!==void 0?R(t.sqrtPriceLimitX96,"sqrtPriceLimitX96"):0n;if(I>je)throw new o("sqrtPriceLimitX96 exceeds uint160 bounds.");let k=await ot(u,t.now),x=t.expiry??t.deadline,O;if(x!==void 0)O=R(x,"expiry");else if(t.lifetime!==void 0||t.ttlSeconds!==void 0){let T=R(t.lifetime??t.ttlSeconds,"lifetime");O=k+T}else O=k+Xe;if(O<k+ce)throw new o(`Order expiry (${O}) is expired or below the minimum lifetime of ${ce} seconds from block timestamp ${k}.`);if(O>k+ue||O>Ve)throw new o(`Order expiry (${O}) exceeds the maximum lifetime of ${ue} seconds (365 days).`);let z=await u.readContract({address:A,abi:L,functionName:"bountyBounds",args:[a,c,d,m]}).catch(()=>{throw new o("Could not read Hookr bounty bounds.")}),_=BigInt(z[0]),q=BigInt(z[1]),X=BigInt(z[2]);if(t.bounty!==void 0&&typeof t.bounty!="string")throw new o("Provide bounty as an integer string in base units.");let h=t.bounty!==void 0?H(t.bounty):q,K=_>0n?_:q;if(h<_||K>0n&&h<K)throw new o(`Order keeper bounty (${h} wei) is underbounty: must be at least ${K} wei (default keeper bounty floor).`);if(h>X||h>le)throw new o(`Order keeper bounty (${h} wei) exceeds the maximum allowed bounty of ${X} wei.`);let te=w.toLowerCase()===P.toLowerCase(),v=[];if(!te){let T;try{let U=await u.readContract({address:w,abi:Z,functionName:"allowance",args:[r,A]});if(typeof U!="bigint"||U<0n)throw new o("Invalid token allowance.");T=U}catch{throw new o(`Could not read token allowance for ${w}. No approval was prepared.`)}T<d&&v.push(e.approval(w,A,d.toString(),i))}let Le=te?d+h:h,Pe=ye({abi:L,functionName:"createOrder",args:[{key:a,zeroForOne:c,amountIn:d,minAmountOut:m,sqrtPriceLimitX96:I,recipient:y,expiry:Number(O),bounty:h}]}),ne=e.formatAmount(d.toString(),g.decimals),oe=e.formatAmount(m.toString(),b.decimals),re=e.formatAmount(h.toString(),18),Te=e.unsignedTx({to:A,data:Pe,value:Le.toString(),chainId:i,description:`Create Hookr limit order on ${A}: sell ${ne} ${S(g.symbol)} (${g.address}) for at least ${oe} ${S(b.symbol)} (${b.address}) with ${re} ETH keeper bounty (fee=${a.fee}, tickSpacing=${a.tickSpacing}, expiry=${O}).`});v.push(Te);let ie=await e.preview(v,r),Re=Ae(ie,e),He=Oe(a);return{txs:v,summary:`Hookr limit order prepared: sell ${ne} ${S(g.symbol)} for at least ${oe} ${S(b.symbol)} (bounty ${re} ETH, expiry ${O}; preview deltas: ${Re}).`,preview:ie,poolId:He,key:a,zeroForOne:c,amountIn:d.toString(),minAmountOut:m.toString(),bounty:h.toString(),bountyBounds:{minBounty:_.toString(),defaultBounty:q.toString(),maxBounty:X.toString()},expiry:O.toString(),recipient:y,sqrtPriceLimitX96:I.toString(),tokenIn:g,tokenOut:b,...s!==void 0?{orderId:s}:{}}}}}function dt(e){return{name:"hookr_cancel",inputSchema:{type:"object",properties:{orderId:{type:"string",description:"Hookr order ID to cancel (uint256 decimal string)."},to:{type:"string",description:"Recipient address for the refunded principal and bounty (must be the signing wallet)."},chainId:{type:"number",description:"Must be 4663 (Robinhood Chain)."}},required:["orderId"]},async execute(t,n){N(n);let r=l(n),i=ke(t.chainId),u=he(t),s=t.orderId??t.id??u;if(s===void 0)throw new o("Provide orderId to cancel a Hookr limit order.");let a=R(s,"orderId");if(a<=0n)throw new o("orderId must be a positive integer.");let c=await xe(e,a);if(c.owner.toLowerCase()!==r.toLowerCase())throw new o(`Unauthorized cancellation: only the order owner (${c.owner}) can cancel Hookr order #${a} (caller is ${r}).`);if(c.status!==M)throw new o(`Hookr order #${a} is not open (current status: ${c.statusLabel}).`);let w=t.to??r;if(typeof w!="string"||!E(w,{strict:!1}))throw new o("Provide a valid refund recipient address for cancel.");let f=l(w);if(Ie(f,c.key.hooks),f!==r)throw new o("Hookr refund recipient must be the signing wallet.");let g=ye({abi:L,functionName:"cancel",args:[a,f]}),b=e.formatAmount(c.amountIn,c.tokenIn.decimals),p=e.formatAmount(c.bounty,18),y=e.unsignedTx({to:A,data:g,value:"0",chainId:i,description:`Cancel Hookr limit order #${a} on ${A} and refund ${b} ${S(c.tokenIn.symbol)} plus ${p} ETH bounty to ${f}.`}),d=await e.preview([y],r),m=Ae(d,e);return{txs:[y],summary:`Cancel Hookr limit order #${a}: refund ${b} ${S(c.tokenIn.symbol)} and ${p} ETH bounty to ${f} (preview deltas: ${m}).`,preview:d,orderId:a.toString(),to:f,refundedAmountIn:c.amountIn,refundedBounty:c.bounty,tokenIn:c.tokenIn,tokenOut:c.tokenOut}}}}function ct(e){let t=performance.now()+Ke;return new Proxy(e,{get(n,r,i){return r!=="readContract"?Reflect.get(n,r,i):async(...u)=>{let s=t-performance.now(),a=()=>new o("Hookr scan deadline exceeded. Order coverage is incomplete; retry later.");if(s<=0)throw a();let c;try{return await Promise.race([n.readContract(...u),new Promise((w,f)=>{c=setTimeout(()=>f(a()),s)})])}finally{c!==void 0&&clearTimeout(c)}}}})}function ut(e){return async t=>{N(t);let n=l(t),r=ct(e.clientFor(C)),i={...e,clientFor:()=>r},u=await r.readContract({address:A,abi:L,functionName:"lastOrderId"}).catch(()=>{throw new o("Could not read the last Hookr order ID. Order coverage is incomplete.")});if(typeof u!="bigint"||u<0n)throw new o("Could not read a valid last Hookr order ID. Order coverage is incomplete.");let s=u,a=s>me?s-me+1n:1n;if(s<=0n)return[];let c=[],w=new Map;for(let f=a;f<=s;f+=Q){let g=Array.from({length:Number(s-f+1n<Q?s-f+1n:Q)},(p,y)=>f+BigInt(y)),b=await Promise.all(g.map(async p=>{let y=await r.readContract({address:A,abi:L,functionName:"getOrder",args:[p]}).catch(()=>{throw new o(`Could not read Hookr order #${p}. Order coverage is incomplete.`)}),d=Ce(y);if(d.owner.toLowerCase()===P||Number(d.status)===ee)throw new o(`Hookr order #${p} does not exist. Order coverage is incomplete.`);return{id:p,order:d}}));for(let{id:p,order:y}of b){if(y.owner.toLowerCase()!==n.toLowerCase()||Number(y.status)!==M)continue;let d=await xe(i,p,{order:y,tokens:w}),m=[{token:d.tokenIn,amount:d.amountIn}];BigInt(d.bounty)>0n&&m.push({token:{address:B,symbol:"ETH",decimals:18,chainId:C},amount:d.bounty});let I=e.formatAmount(d.amountIn,d.tokenIn.decimals),k=e.formatAmount(d.minAmountOut,d.tokenOut.decimals),x=e.formatAmount(d.bounty,18),O=e.formatAmount(d.quotedAmountOut,d.tokenOut.decimals);c.push({module:"hookr",id:d.orderId,chainId:C,assets:m,description:`Hookr open limit order #${d.orderId}: sell ${I} ${S(d.tokenIn.symbol)} (${d.tokenIn.address}) for at least ${k} ${S(d.tokenOut.symbol)} (${d.tokenOut.address}), bounty ${x} ETH, expiry ${d.expiry}, fillable=${d.fillable} (quoted output ${O} ${S(d.tokenOut.symbol)}).`})}}return a>1n&&c.push({module:"hookr",id:"coverage",chainId:C,assets:[],description:`Hookr order coverage is incomplete: scanned IDs ${a}-${s}. Older orders require an explicit order ID.`}),c}}var De=e=>{let t=[at(e),dt(e)],n=ut(e);return{tools:t,positions:n}},Pt=De,Tt=De;export{A as a,ve as b,Ne as c,It as d,Be as e,Fe as f,At as g,Me as h,ze as i,qe as j,ce as k,Xe as l,ue as m,ht as n,St as o,Ct as p,xt as q,me as r,Ke as s,ee as t,M as u,Ye as v,Qe as w,Ze as x,Dt as y,L as z,et as A,Lt as B,Oe as C,rt as D,Se as E,it as F,st as G,Ce as H,xe as I,at as J,dt as K,ct as L,ut as M,De as N,Pt as O,Tt as P};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as A,b as h}from"./5KUWLUPM.js";import{a as c}from"./XSD5NL7J.js";import{getAddress as E,isAddress as I}from"viem";var j=/^[0-9]+$/,D=new Set(["^[0-9]+$","^\\d+$"]),b=new Set(["all","max"]),p={ETH:18,WETH:18,USDE:18,USDG:6},x=new WeakSet,$=new WeakMap;function R(e){return{type:"string",pattern:"^[0-9]+$",...e?{description:e}:{}}}function H(e){let n=R(e);return x.add(n),n}function a(e){let n;try{n=e===void 0?"nothing":JSON.stringify(e)??String(e)}catch{n=String(e)}return n.length>80?`${n.slice(0,77)}...`:n}function _(e,n){if(n===void 0||typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1;throw new c(`${e} must be true or false; received ${a(n)}. Send the JSON boolean true or false (the strings "true" and "false" are also accepted).`)}function U(e,n,i={}){if(n===void 0)return;let r=typeof n=="number"?n:typeof n=="string"&&/^-?[0-9]{1,16}$/.test(n)?Number(n):Number.NaN,{minimum:t,maximum:o}=i;if(Number.isSafeInteger(r)&&(t===void 0||r>=t)&&(o===void 0||r<=o))return r;let d=t!==void 0&&o!==void 0?t===o?` equal to ${t}`:` from ${t} to ${o}`:t!==void 0?` of at least ${t}`:o!==void 0?` of at most ${o}`:"",s=e.endsWith("Bps")?" Use a whole number of basis points such as 50 (100 = 1%).":"";throw new c(`${e} must be a whole number${d}; received ${a(n)}. Send a JSON number such as ${t!==void 0&&t===o?t:o!==void 0&&o>=50&&(t??0)<=50?50:t??1} (a string of digits is also accepted).${s}`)}function l(e,n){let[i="",r=""]=e.split(".");if(!(r.length>n))return(BigInt(i||"0")*10n**BigInt(n)+BigInt(r.padEnd(n,"0")||"0")).toString()}function W(e){let i=(typeof e=="number"&&Number.isFinite(e)&&e>=0&&!/e/i.test(String(e))?String(e):typeof e=="string"?e.trim():void 0)?.match(/^(\d+\.?\d*|\.\d+)\s*\$?([A-Za-z]{2,10})?$/);if(!i||!i[1].includes(".")&&!i[2])return;let r=i[1].startsWith(".")?`0${i[1]}`:i[1].replace(/\.$/,""),t=i[2]?.toUpperCase();if(t&&p[t]!==void 0){let s=l(r,p[t]);return s===void 0?`${r} ${t} has more than ${p[t]} decimal places.`:`${r} ${t} = "${s}" (${p[t]} decimals). Send "${s}".`}let d=[[18,"ETH or WETH"],[6,"USDG"]].flatMap(([s,u])=>{let f=l(r,s);return f===void 0?[]:[`${r} ${u} (${s} decimals) = "${f}"`]});return`${d.length?`${d.join("; ")}. `:""}Multiply by 10^decimals of the token and send the whole-number string.`}function J(e,n,i={}){if(n===void 0)return;let{keyword:r,numbers:t=!0}=i;if(typeof n=="string"&&j.test(n))return n;if(r&&typeof n=="string"&&b.has(n))return r;let o=`a decimal integer string of base units such as "1000000"${t?" (a JSON whole number up to 9007199254740991 is also accepted)":""}${r?`, or "${r}" for the full balance`:""}`;if(typeof n=="number"&&Number.isInteger(n)&&n>=0){if(!Number.isSafeInteger(n))throw new c(`${e} received the JSON number ${a(n)}, which is above 9007199254740991 (2^53 - 1) and cannot be represented exactly. Send the exact value as a decimal integer string.`);if(!t)throw new c(`${e} must be a decimal integer string; received the JSON number ${n}. Send "${n}".`);return String(n)}if(e==="agentId"||e==="agent_id")throw new c(`${e} must be a whole number with no decimal point; received ${a(n)}. Send the agent ID as a string of digits, such as "1".`);let d=W(n);if(d)throw new c(`${e} must be base units, a whole number with no decimal point; received ${a(n)}. ${d}`);let s=typeof n=="string"&&b.has(n.toLowerCase())&&!r?" This field has no full-balance keyword; use the tool's separate full-exit option if it has one.":"";throw new c(`${e} must be ${o}; received ${a(n)}.${s}`)}function K(e,n){if(n===void 0)return;if(typeof n=="string"&&I(n,{strict:!1}))return E(n);let i=typeof n=="string"&&/^\$?[A-Za-z][A-Za-z0-9.]{0,15}$/.test(n)?" Token symbols are not accepted here; look up the address with find_token.":"";throw new c(`${e} must be a 0x address (0x followed by 40 hex digits, any letter case); received ${a(n)}.${i}`)}function L(e,n,i){if(typeof n=="string"){if(i.includes(n))return n;let r=i.filter(t=>h.test(t)&&t.toLowerCase()===n.toLowerCase());if(r.length===1)return r[0]}throw new c(`${e} must be one of ${i.map(r=>`"${r}"`).join(", ")} (addresses in any letter case); received ${a(n)}.`)}function w(e){return(e.type==="string"||e.type===void 0)&&D.has(e.pattern)}function S(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(n.type==="boolean")return{kind:"boolean"};if(n.type==="integer")return{kind:"integer",...typeof n.minimum=="number"?{minimum:n.minimum}:{},...typeof n.maximum=="number"?{maximum:n.maximum}:{}};if(typeof n.const=="number"&&Number.isSafeInteger(n.const))return{kind:"integer",minimum:n.const,maximum:n.const};if(w(n))return{kind:"uint",numbers:!x.has(n)};let i=typeof n.pattern=="string"?n.pattern.match(/^\^\(\?:\[0-9\]\+\|(all|max)\)\$$/):null;if(n.type==="string"&&i)return{kind:"uint",keyword:i[1],numbers:!0};let r=n.anyOf??n.oneOf;if(Array.isArray(r)&&r.length===2){let t=r.find(d=>d&&w(d)),o=r.find(d=>d&&typeof d.const=="string"&&b.has(d.const));if(t&&o)return{kind:"uint",keyword:o.const,numbers:!0}}if(n.type==="string"&&n.pattern===A)return{kind:"address"};if(n.type==="string"&&Array.isArray(n.enum)&&n.enum.every(t=>typeof t=="string")&&n.enum.some(t=>h.test(t)))return{kind:"enum",values:n.enum};if(n.type==="array"){let t=S(n.items);if(t&&(t.kind==="uint"||t.kind==="address"))return{kind:"array",item:t}}}function N(e,n,i){switch(n.kind){case"boolean":return _(e,i);case"integer":return U(e,i,n);case"uint":return J(e,i,n);case"address":return K(e,i);case"enum":return L(e,i,n.values);case"array":return Array.isArray(i)?i.map((r,t)=>N(`${e}[${t}]`,n.item,r)):i}}function O(e,n){let{pattern:i,anyOf:r,oneOf:t,enum:o,const:d,...s}=e;switch(n.kind){case"boolean":return{...e,type:["boolean","string"]};case"integer":return{...s,...Array.isArray(o)?{enum:[...o,...o.map(String)]}:{},type:["integer","string"]};case"uint":{let u=r??t,f=Array.isArray(u)?u:[],g=f.find(y=>w(y)),m=f.find(y=>typeof y.const=="string"),k=s.description??[g?.description,m?`Or "${m.const}"${m.description?`: ${m.description}`:"."}`:void 0].filter(Boolean).join(" ");return{...s,...k?{description:k}:{},type:n.numbers?["string","integer"]:"string"}}case"address":return{...s,type:"string",description:s.description??"A 0x address (any letter case)."};case"enum":return{...s,type:"string",description:`${s.description?`${s.description} `:""}One of: ${o.join(", ")} (any letter case).`};case"array":return{...e,items:O(e.items,n.item)}}}function T(e){let n=e.properties;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function M(e){let n=T(e);if(!n||$.has(e))return e;let i=!1,r={};for(let[o,d]of Object.entries(n)){let s=S(d);r[o]=s?O(d,s):d,i||=r[o]!==d}if(!i)return e;let t={...e,properties:r};return $.set(t,e),t}function z(e){return $.get(e)??e}function P(e,n){let i=T(z(e));if(!i||!n||typeof n!="object"||Array.isArray(n))return n;let r;for(let[t,o]of Object.entries(i)){if(!Object.hasOwn(n,t))continue;let d=S(o);if(!d)continue;let s=n[t],u=N(t,d,s);u!==s&&!(Array.isArray(u)&&Array.isArray(s)&&u.every((f,g)=>f===s[g]))&&(r??={...n},r[t]=u)}return r??n}export{R as a,H as b,a as c,_ as d,U as e,J as f,K as g,M as h,z as i,P as j};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as g,b as p}from"./RVO3QK2B.js";import{a as y,b as D,c as m,d as T,e as I}from"./UHRCM7AG.js";import{c as O,d as A,f as P,g as R}from"./EU3OAJU2.js";import{b as k,c as x}from"./PBQSJSZO.js";import{a as b}from"./FWD4L3CJ.js";import{a as f}from"./XSD5NL7J.js";import{encodeFunctionData as C,zeroAddress as N}from"viem";function v(t=10){if(!Number.isInteger(t)||t<0||t>50)throw new f("Oak won't accept a cash-out reduction that big. Use a whole number from 0 to 50 bps (0.5%).");return t}async function z(t,e,a,u=10,r){let l=v(u);p(a,!0),m(e.tokensOut.some(n=>T(n,e.inputToken)),"the market input token cannot be redeemed from SY");try{let n=await t.client.getBlock();m(e.expired&&n.timestamp>=BigInt(e.expiry),"this term has not ended; wait for its end date");let h=p((await t.client.simulateContract({address:e.yt,abi:g,functionName:"pyIndexCurrent",blockNumber:n.number})).result,!0);for(let o of[e.syDecimals,e.ptDecimals])m(Number.isInteger(o)&&o>=0&&o<=77,"unreadable token decimals");let d=a*10n**18n*10n**BigInt(e.syDecimals)/(h*10n**BigInt(e.ptDecimals));p(d,!0);let i=p(await t.client.readContract({address:e.sy,abi:g,functionName:"previewRedeem",args:[e.inputToken,d],blockNumber:n.number}),!0),s=I(i,l);if(m(s>0n,"this cash-out amount is too small"),r&&(r.apiAmountOut>i?r.apiAmountOut-i:i-r.apiAmountOut)*10000n>i*50n)try{r.note("Pendle\u2019s API cash-out estimate differs from the chain by over 0.5%. Oak kept the chain estimate.")}catch{}let c={tokenOut:e.inputToken,minTokenOut:s,tokenRedeemSy:e.inputToken,pendleSwap:N,swapData:{swapType:0,extRouter:N,extCalldata:"0x",needScale:!1}},w=k({to:y,data:C({abi:D,functionName:"redeemPyToToken",args:[t.wallet,e.yt,a,c]}),value:"0",chainId:b,description:"Cash out ended Pendle PT to its input token."});return{txs:[x(e.pt,y,a.toString(),b),w],expected:i,minOut:s,summary:"Approve the exact PT amount, then cash out the ended term to its input token."}}catch(n){throw n instanceof f?n:new f("Oak could not read the Pendle cash-out amount from the chain. Try again.")}}async function F(t,e,a,u,r){let l=new AbortController,n;try{let h=new Promise(o=>{n=setTimeout(()=>{l.abort(),o(void 0)},1500)}),d=await Promise.race([R((o,B)=>t.http(o,{...B,signal:l.signal}),{inputToken:e.pt,outputToken:e.inputToken,amount:a,wallet:t.wallet,slippageBps:r}),h]);if(!d)return;let i=P(d.body).outputs;if(i.length!==1)return;let s=O(i[0]);if(!T(s.token,e.inputToken))return;let c=A(s.amount);return(c>u?c-u:u-c)*10000n>u*50n?"Pendle\u2019s API cash-out estimate differs from the chain by over 0.5%. Oak kept the chain estimate.":void 0}catch{return}finally{n!==void 0&&clearTimeout(n)}}export{v as a,z as b,F as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as ue}from"./LQGPMOD2.js";import{c as le}from"./NSOEDRBU.js";import{a as X}from"./XVFLT275.js";import{a as x,b as v}from"./CY75R4FK.js";import{a as L}from"./QRDDKA4I.js";import{a as de}from"./P4UQGWCP.js";import{a as E}from"./6IM6A5VA.js";import{b as ie,c as ce}from"./MYBDO5SA.js";import{a as oe,b as G,c as V}from"./5HCXZWUH.js";import{l as ae,n as F,o as re}from"./CXLEQCP3.js";import{a as w,b as U,c as B,d as te,i as P,j as se,s as N}from"./G6HCV67X.js";import{a as m}from"./5YS5V2LK.js";import{a as p,b as W,c as ne}from"./JXOEJPJ4.js";import{decodeFunctionResult as Ie,encodeFunctionData as Le,erc20Abi as Z,getAddress as b,isAddress as H,parseAbi as ee}from"viem";var Te="https://api.robinhood.com/rhj/assets",Ne={address:x,symbol:"ETH",decimals:18,chainId:w},j={address:b(se),symbol:"USDG",decimals:te,chainId:w},Y={address:b(P[4663].tokens.WETH.address),symbol:"WETH",decimals:18,chainId:w},be={address:b(P[4663].meridian.CollateralToken_USDe.address),symbol:"USDe",decimals:18,chainId:w};function _(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Q(e,t=w,s={}){let n=Array.isArray(e)?e:_(e)&&Array.isArray(e.assets)?e.assets:void 0;if(!n)throw new m("Official stock asset list response is malformed.");let o=new Map,d=new Map;if(n.length>1e4)throw new m("Official stock asset list exceeds the lookup limit.");for(let a of n){if(!_(a))continue;let r=a;if(typeof r.tokenSymbol!="string"||!r.tokenSymbol.trim()||!Array.isArray(r.deployments))continue;if(r.deployments.length>100)throw new m("Official stock deployment list exceeds the lookup limit.");let l=r.tokenSymbol;if(!/^[A-Za-z0-9.$_-]{1,32}$/.test(l))throw new m(`Invalid official stock ticker ${p(l)}.`);if(r.tokenDecimals!==void 0&&(typeof r.tokenDecimals!="number"||!Number.isInteger(r.tokenDecimals)||r.tokenDecimals<0||r.tokenDecimals>255))throw new m("Official stock asset has invalid token decimals.");let f=typeof r.tokenDecimals=="number"&&Number.isInteger(r.tokenDecimals)&&r.tokenDecimals>=0&&r.tokenDecimals<=255?r.tokenDecimals:18;for(let k of r.deployments){if(!_(k))continue;let h=k;if(h.chainId!==t)continue;if(typeof h.contractAddress!="string"||!H(h.contractAddress,{strict:!1}))throw new m("Official stock deployment has an invalid contract address.");let y=b(h.contractAddress),u=y.toLowerCase(),g=l.toUpperCase(),i=d.get(g);if(!s.allowAmbiguousSymbols&&i&&i!==u)throw new m(`Ambiguous official stock ticker ${p(l)} across multiple addresses.`);let c=o.get(u);if(c&&(c.symbol!==l||c.decimals!==f))throw new m(`Conflicting official stock identity at ${y}.`);d.set(g,u),o.set(u,{address:y,symbol:l,decimals:f,chainId:t,...s.includeNames&&typeof r.tokenName=="string"&&r.tokenName.trim()?{name:r.tokenName.trim()}:{}})}}return[...o.values()]}function De(e,t){if(typeof e.address!="string"||!H(e.address,{strict:!1}))return!1;let s=e.chainId??w,n=e.address.toLowerCase();return t.some(o=>o.chainId===s&&o.address.toLowerCase()===n&&o.symbol===e.symbol)}function $(e,t){E(e.address);let s=e.chainId??w,n=b(e.address),o=n.toLowerCase(),d=C(e.symbol),a=t.find(l=>l.chainId===s&&l.address.toLowerCase()===o),r=t.find(l=>l.chainId===s&&C(l.symbol)===d);if(a){if(e.symbol!==a.symbol)throw new m(`Token at ${n} does not match official stock ticker ${p(a.symbol)} (received ${p(e.symbol)}).`);if(e.decimals!==void 0&&e.decimals!==a.decimals)throw new m(`Token ${p(a.symbol)} at ${n} does not match official decimals ${a.decimals}.`);return a}if(r)throw new m(`Token symbol ${p(e.symbol)} at ${n} does not match the official stock contract address ${r.address}.`);return{address:n,symbol:e.symbol.trim(),decimals:e.decimals??18,chainId:s}}var ve=["AAOI","AAPL","ABCL","ADBE","AEHR","AEIS","ALAB","AMAT","AMBA","AMC","AMD","AMKR","AMZN","ANET","APLD","APP","ASML","ASTS","AUR","AVAV","AVGO","AXON","AXTI","BA","BABA","BB","BE","BMNR","BND","BULL","CBRS","CCL","CEG","CELH","CIEN","CLOV","CLS","CLSK","COHR","COIN","COST","CRCL","CRDO","CRM","CRWD","CRWV","CSCO","CTSH","CVNA","DDOG","DELL","DIS","DJT","DOCN","ELF","EWT","EWY","F","FICO","FIG","FISV","FIX","FLNC","FLY","FTNT","FUTU","GDX","GE","GEV","GLD","GLW","GLXY","GME","GOOGL","HII","HIMS","HPE","HWM","IBM","IBRX","INDA","INFQ","INOD","INTC","INTU","IONQ","IREN","JBL","JNJ","JOBY","JPM","KLAC","KSS","KTOS","LHX","LITE","LLY","LMT","LRCX","LULU","LUNR","MCD","MDB","META","MOD","MPWR","MRNA","MRVL","MSFT","MSTR","MTSI","MU","MXL","NAVN","NBIS","NET","NFLX","NNE","NOW","NU","NVDA","NVTS","OKLO","ON","ONTO","ORCL","OUST","P","PANW","PATH","PENG","PFE","PL","PLTR","POET","POWL","PR","PWR","PYPL","QBTS","QCOM","QQQ","QUBT","RBLX","RCAT","RDDT","RDW","RGTI","RIVN","RKLB","RUN","SATS","SCHD","SGOV","SHOP","SHY","SIMO","SKHY","SLS","SLV","SMCI","SMH","SMR","SNAP","SNDK","SNOW","SOFI","SOUN","SOXX","SPCX","SPMO","SPY","TE","TEAM","TEM","TER","TSEM","TSLA","TSM","TTD","TTWO","UBER","UMC","UNH","UPS","USAR","USO","V","VICR","VRT","VSAT","VST","VTI","WDAY","WDC","WULF","WYFI","XLK","XNDU","XOM","ZETA","ZM","ZS"],J=new WeakMap,me=new WeakMap,z=new WeakMap;function K(e,t){return(z.get(e)??F)(t)}async function pe(e){let t=e?.http??ie(),s=e?.url??Te,n=e?.chainId??w,o=V(t),d=me.get(o);d||(d=new oe(3e4),me.set(o,d));let{value:a}=await K(t,()=>d.read(`${n}:${s}`,async()=>{let l=await F(k=>ce(o,s,{method:"GET",signal:k},h=>_(h)||Array.isArray(h))),f=Q(l,n,{allowAmbiguousSymbols:!0});if(n===w&&f.length===0)throw new m("Official stock asset list has no mainnet deployments; retry when the list is available.");return l})),r=Q(a,n,e);if(n===w){let l=J.get(o);l||(l=new Set,J.set(o,l));for(let f of r)l.add(C(f.symbol))}return r}var Pe=ee(["function aggregate3((address target, bool allowFailure, bytes callData)[] calls) payable returns ((bool success, bytes returnData)[] returnData)"]);function fe(e){let t=e,s=new Set;for(;t&&typeof t=="object"&&!s.has(t)&&s.size<10;){s.add(t);let n=t;if(n.name==="ContractFunctionZeroDataError"||n.name==="AbiDecodingZeroDataError")return!0;let o=`${typeof n.shortMessage=="string"?n.shortMessage:""} ${typeof n.message=="string"?n.message:""}`;if(/returned no data \("0x"\)|Cannot decode zero data/i.test(o))return!0;t=n.cause}return!1}function Ee(e){return e instanceof m?/RPC endpoint|too many requests|malformed JSON/i.test(e.message):e instanceof Error?/fetch failed|network|ECONNREFUSED|ETIMEDOUT|HTTP \d{3}|rate limit|too many requests/i.test(e.message):!1}async function xe(e,t,s){if(typeof e.getCode=="function")try{let n=await e.getCode({address:t});return!n||n==="0x"}catch{return fe(s)}return fe(s)}async function ke(e,t,s){if(t.length===0)return[];let n=await Promise.allSettled(t.map(o=>e.readContract({address:o.address,abi:Z,functionName:"balanceOf",args:[s]})));if(n.every(o=>o.status==="rejected")&&n[0]?.status==="rejected"&&Ee(n[0].reason))throw n[0].reason;return n.map(o=>{if(o.status!=="fulfilled"||o.value===void 0||o.value===null)return{ok:!1};try{let d=typeof o.value=="bigint"?o.value:BigInt(o.value);return d>=0n?{ok:!0,amount:d}:{ok:!1}}catch{return{ok:!1}}})}async function we(e,t,s,n){if(s.length===0)return[];let o=ae(t,e);if(!o)return ke(e,s,n);let d=s.map(r=>({target:r.address,allowFailure:!0,callData:Le({abi:Z,functionName:"balanceOf",args:[n]})})),a;try{a=await e.readContract({address:o,abi:Pe,functionName:"aggregate3",args:[d]})}catch(r){if(await xe(e,o,r))return ke(e,s,n);throw r}if(!Array.isArray(a)||a.length!==s.length)throw new m("Multicall3 aggregate3 returned an invalid result list.");return a.map(r=>{let l=r,f=Array.isArray(l)?l[0]:l?.success,k=Array.isArray(l)?l[1]:l?.returnData;if(!f||typeof k!="string"||k==="0x")return{ok:!1};try{let h=Ie({abi:Z,functionName:"balanceOf",data:k}),y=typeof h=="bigint"?h:BigInt(h);return y>=0n?{ok:!0,amount:y}:{ok:!1}}catch{return{ok:!1}}})}async function ze(e,t={}){E(e);let s=b(e),n=t.chainId??w,o=t.client??re(t.rpcUrl,n),d=[];if(t.stockTokens?d=[...t.stockTokens]:t.stockAssetsPayload!==void 0?d=Q(t.stockAssetsPayload,n):t.includeStockTokens!==!1&&n!==U&&(d=await pe({http:t.http,url:t.stockAssetsUrl,chainId:n})),t.tokens)for(let i of t.tokens)$(i,d);let a=n===w?[j,Y,be,...t.oakTokenAddress||process.env.OAK_TOKEN_ADDRESS?[{address:b(t.oakTokenAddress??process.env.OAK_TOKEN_ADDRESS),symbol:"OAK",decimals:B,chainId:n}]:[]]:n===U?[{...j,address:b(N.testnet.usdg),chainId:n},{...Y,address:b(N.testnet.weth),chainId:n},...t.oakTokenAddress?[{address:b(t.oakTokenAddress),symbol:"OAK",decimals:B,chainId:n}]:[]]:[],r=n===w&&t.includePoolTokens!==!1?de.vaults.flatMap(i=>[{address:b(i.tokenAddress),symbol:b(i.tokenAddress),decimals:i.tokenDecimals,chainId:n},{address:b(i.earnContractAddress),symbol:b(i.earnContractAddress),decimals:18,chainId:n}]):[],l=new Set(r.map(i=>i.address.toLowerCase())),f=[],k=new Set;for(let i of[...a,...d,...t.tokens??[],...r]){if(i.chainId!==n||v(i.address)===x)continue;let c=$(i,d),T=c.address.toLowerCase();k.has(T)||(k.add(T),f.push(c))}let[h,y]=await Promise.all([o.getBalance({address:s}),we(o,n,f,s)]),u=[],g={address:x,symbol:"ETH",decimals:18,chainId:n};(h>0n||t.includeZero)&&u.push({token:g,amount:h.toString()});for(let i=0;i<f.length;i++){let c=f[i],T=a.some(S=>O(S.address,c.address))||d.some(S=>O(S.address,c.address))?c.symbol:p(c.symbol),I=y[i]??{ok:!1};if(!I.ok){u.push({token:{address:c.address,symbol:T,decimals:c.decimals,chainId:c.chainId},amount:"unavailable"});continue}let A=I.amount;if(A>0n&&l.has(c.address.toLowerCase()))try{let[S,M]=await Promise.all([L(o,n,c.address,"symbol"),L(o,n,c.address,"decimals")]);T=p(S),c.decimals=M}catch{}(A>0n||t.includeZero)&&u.push({token:{address:c.address,symbol:T,decimals:c.decimals,chainId:c.chainId},amount:A.toString()})}return u}async function qe(e,t,s){if(E(e),t.length>1e4)throw new m("Journal token discovery exceeds the balance lookup limit.");let n=[...new Set(t.map(a=>(E(a),b(a))))].filter(a=>v(a)!==x).map(a=>({address:a,symbol:a,decimals:0,chainId:s.chainId})),o=await we(s.client,s.chainId,n,b(e)),d=n.flatMap((a,r)=>{let l=o[r];return l.ok&&l.amount===0n?[]:[{token:a,amount:l.ok?l.amount.toString():"unavailable"}]});return Promise.all(d.map(async({token:a,amount:r})=>{let[l,f]=await Promise.all([L(s.client,s.chainId,a.address,"symbol").catch(()=>a.address),L(s.client,s.chainId,a.address,"decimals").catch(()=>{throw new m(`Token decimals are unavailable for journal-received token ${a.address}; retry balances when RPC metadata is available.`)})]);return{token:{...a,symbol:p(l),decimals:f},amount:r}}))}var O=(e,t)=>e.toLowerCase()===t.toLowerCase(),C=e=>ne(e.normalize("NFKC")).toLowerCase().replace(/[^\p{L}\p{N}]/gu,"");function ge(e){let t=e.context.network??"mainnet",{chainId:s,usdg:n,weth:o}=N[t],d=(a,r,l)=>({...a,address:v(b(a.address)),name:r,kind:l,verified:!0,source:"Oak fixed addresses",warnings:[]});return[d({...Ne,chainId:s},"Ether","native"),d({...j,address:n,chainId:s},"Global Dollar","stablecoin"),d({...Y,address:o,chainId:s},"Wrapped Ether","wrapped"),...t==="mainnet"?[d(be,"USDe","stablecoin")]:[],...e.oakTokenAddress?[d({address:e.oakTokenAddress,symbol:"OAK",decimals:B,chainId:s},"Oak","oak")]:[]]}async function Ae(e){if(e.context.network==="testnet")return[];let t=e.officialStockTokens??await pe({http:e.context.http,includeNames:!0,allowAmbiguousSymbols:!0});return t.filter(s=>De(s,t)).map(s=>({...s,name:s.name??s.symbol,kind:"official_stock",verified:!0,source:Te,warnings:[]}))}async function q(e,t,s=!0){let{chainId:n}=N[t.context.network??"mainnet"],o=t.context.clientFor(n);if(await o.getChainId()!==n)throw new m(`Token lookup requires Robinhood Chain ${n}.`);let[d,a,r]=await Promise.all([K(o,()=>L(o,n,e,"name",t.blockNumber)).catch(l=>{if(s)throw l;return""}),K(o,()=>L(o,n,e,"symbol",t.blockNumber)),K(o,()=>L(o,n,e,"decimals",t.blockNumber))]);if(typeof d!="string"||s&&!d.trim()||typeof a!="string"||!a.trim()||!Number.isInteger(r)||r<0||r>255)throw new m("The contract returned invalid token metadata.");return{address:b(e),name:d||a,symbol:a,decimals:r,chainId:n}}async function he(e,t){let s=await t.context.clientFor(w).readContract({address:P[w].clanker.factory.address,abi:ee(["function tokenDeploymentInfo(address) view returns ((address,address,address,address[]))"]),functionName:"tokenDeploymentInfo",args:[e]});return Array.isArray(s)&&s.length===4&&typeof s[0]=="string"&&O(s[0],e)}async function Me(e,t){let s=t.context.clientFor(w),n=P[w].poolsTrade,o=[n.instantLaunchStrategyFeesOn.address,n.instantLaunchStrategyFeesOff.address],d=ee(["event TokenLaunched(bytes32 indexed poolId,address indexed token,address indexed feeSplitter,(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey)"])[0],a=await s.getBlockNumber(),r=new Set,l=0,f=0;for(let k=63127652n;k<=a;k+=10000000n){if(++l>Se)throw new m("Token origin scan limit reached.");let h=k+9999999n>a?a:k+9999999n,y=await s.getLogs({address:o,event:d,args:{token:e},fromBlock:k,toBlock:h,strict:!0});for(let u of y){if(u.removed||!o.some(i=>O(i,u.address))||!u.args.token||!O(u.args.token,e)||!u.transactionHash||r.has(u.transactionHash))continue;if(r.add(u.transactionHash),++f>20)throw new m("Token origin receipt limit reached.");let g=await s.getTransactionReceipt({hash:u.transactionHash});if(ue(g).some(i=>O(i.token,e)))return b(g.from)}}}var Se=5,Re=100,Ue=500,Be=3e4;function Ce(e){let t=Date.now()+Be,s=0,n=new Map,o=a=>{let r=t-Date.now();if(r<=0)throw new m("Token lookup time budget reached; results are partial.");return F(a,Math.min(1e4,r))},d=G((a,r)=>o(async l=>{let f=await e.context.http(a,{...r,signal:l});return new Proxy(f,{get(k,h){if(h==="json")return()=>o(()=>k.json());let y=Reflect.get(k,h,k);return typeof y=="function"?y.bind(k):y}})}),e.context.http);return z.set(d,o),{...e,context:{...e.context,http:d,clientFor:a=>{if(!n.has(a)){let r=e.context.clientFor(a),l=f=>{if(++s>Ue)throw new m("Token lookup RPC budget reached; results are partial.");return o(f)};n.set(a,G(new Proxy(r,{get(f,k){let h=Reflect.get(f,k);return typeof h!="function"?h:(...y)=>l(()=>h.apply(f,y))}}),r)),z.set(n.get(a),l)}return n.get(a)}}}}function ye(e){return e.source==="Oak fixed addresses"?e:{...e,symbol:p(e.symbol),name:p(e.name)}}async function en(e,t){if(t=Ce(t),typeof e!="string"||e.length>256||!C(e))throw new m("Provide a token name, symbol or address to find_token.");let s=C(e),n=H(e.trim(),{strict:!1})?v(b(e.trim())):void 0,{chainId:o}=N[t.context.network??"mainnet"],d=[],a=ge(t),r=!1;try{a.push(...await Ae(t))}catch{r=!0,d.push("The official stock list is unavailable; results are partial and stock identities and lookalikes could not be checked.")}let l=i=>n?O(i.address,n):C(i.symbol).includes(s)||C(i.name).includes(s),f=a.filter(l),k=[],h=(i,c)=>[i.symbol,i.name??""].some(T=>[c.symbol,c.name].some(I=>{let A=C(T),S=C(I);return!!A&&!!S&&(A.includes(S)||S.includes(A))})),y=(i,c={})=>{if(k.some(A=>O(A.address,i.address)))return;let T=[`Token ${p(i.symbol)} at ${i.address} is an unverified ${c.launchpad?"launchpad token":"token"}. Use its address, not its name or symbol.`];(W(i.symbol)||W(i.name)||a.some(A=>!O(A.address,i.address)&&h(i,A)))&&T.push(`Lookalike warning: ${p(i.symbol)} at ${i.address} resembles a verified token's name or symbol.`);let I={...i,...c,kind:c.launchpad?"launchpad":"erc20",verified:!1,source:c.launchpad?`${c.launchpad} origin and on-chain metadata; not a verified token`:"On-chain metadata only",warnings:T};k.push(I),d.push(...T)};if(n&&!f.length){let i=await q(n,t),c={};if(o===w){try{await he(n,t)&&(c.launchpad="clanker")}catch{d.push("Clanker origin lookup was unavailable for this address.")}if(c.launchpad==="clanker")try{let I=(await X(t.context,{q:n,limit:20})).tokens.find(A=>O(A.contract_address,n));I&&(c.creator=b(I.msg_sender),c.creatorSource="Clanker indexer msg_sender")}catch{d.push("Clanker creator lookup is unavailable.")}else try{let T=await le(t.context,n);c.launchpad="pons",c.creator=b(T.creator),c.creatorSource="Pons factory deployer"}catch{d.push("Pons launch origin could not be confirmed for this address.")}if(!c.launchpad)try{let T=await Me(n,t);T&&(c.launchpad="pools.trade",c.creator=T,c.creatorSource="Launch transaction sender; may be a relayer")}catch{r=!0,d.push("pools.trade launch receipt lookup is unavailable; origin results are partial.")}}y(i,c)}else if(!n&&o===w){let i=new Set,c=new Set,T,I=0,A=0;try{do{if(++I>Se)throw new m("Token search page limit reached.");let S=await X(t.context,{q:e.trim(),limit:20,...T?{cursor:T}:{}});for(let M of S.tokens){if(++A>Re)throw new m("Token candidate limit reached.");let D=b(M.contract_address);if(!(c.has(D)||a.some(R=>O(R.address,D)))){c.add(D);try{let R=await q(D,t);if(!l(R))continue;let Oe=await he(D,t)?{launchpad:"clanker",creator:b(M.msg_sender),creatorSource:"Clanker indexer msg_sender"}:{};y(R,Oe)}catch{r=!0,d.push(`Could not read Clanker candidate ${D}; it was omitted from these partial results.`)}}}if(S.cursor&&i.has(S.cursor))throw new m("The Clanker indexer repeated a pagination cursor.");S.cursor&&i.add(S.cursor),T=S.cursor??void 0}while(T)}catch{r=!0,d.push("Clanker name search is unavailable, incomplete or reached its scan limit; results are partial.")}d.push("Pons and pools.trade require a token address; name search does not cover those launchpads.")}o===U&&d.push("Testnet lookup covers pinned tokens and explicit token addresses; stock and launchpad discovery are unavailable.");let u=i=>[...new Map(i.map(c=>[c.address.toLowerCase(),c])).values()],g=u([...f,...k]);for(let i of g)if(g.some(c=>!O(c.address,i.address)&&(C(i.symbol)===C(c.symbol)||C(i.name)===C(c.name)))){let c=`Duplicate warning: several tokens share the symbol or name of ${i.address}. Choose the intended address; do not guess from the name.`;i.warnings.push(c),d.push(c)}return f.length>1&&d.push("Several verified tokens match this search, including possible substring matches. Choose an exact address; the search does not select a quote token."),{query:p(e.trim()),chainId:o,partial:r,matches:u(f).map(ye),unverified:u(k).map(ye),warnings:d}}async function nn(e,t){if(typeof e!="string"||!e.trim())throw new m("Provide a token address or verified symbol; use find_token to look it up.");if(!/^[A-Za-z0-9.$_-]{1,42}$/.test(e))throw new m("Use an exact ASCII verified symbol or token address; use find_token to look it up.");let s=e,n=H(s,{strict:!1})?v(b(s)):void 0,o=ge(t),d=n&&o.find(y=>O(y.address,n));if(d)return d;let a=s.toUpperCase()==="$OAK"?"OAK":s.toUpperCase(),r=!n&&o.find(y=>y.symbol.toUpperCase()===a),l=[],f=!1;try{l=await Ae(t)}catch{if(r)return r;if(!n)throw new m("The official stock list is unavailable; stock symbols cannot be checked. Use find_token and try again when the list is reachable.");f=!0}if(n){let y=l.find(i=>O(i.address,n));if(y)return t.tokenMetadata&&$(t.tokenMetadata,l),{...y,name:p(y.name)};let u=t.tokenMetadata??await t.readMetadata?.(n);if(u&&(!O(u.address,n)||u.chainId!==N[t.context.network??"mainnet"].chainId))throw new m("Token metadata does not match the requested address and chain.");if(u&&(typeof u.symbol!="string"||!u.symbol.trim()||!Number.isInteger(u.decimals)||u.decimals<0||u.decimals>255))throw new m("The contract returned invalid token metadata.");let g=u?{...u,name:u.symbol}:await q(n,Ce(t),!1);if(f){let i=C(g.symbol),c=J.get(V(t.context.http));if(ve.some(T=>C(T)===i)||c?.has(i))throw new m("The official stock list is unavailable; this address claims a stock ticker that cannot be checked. Try again when the list is reachable.")}return $(g,l),{...g,symbol:p(g.symbol),name:p(g.name),kind:"erc20",verified:!1,source:"On-chain metadata only",warnings:["This token address is unverified. On-chain names and symbols do not prove identity.",...f?["The official stock list is unavailable; stock identity could not be verified."]:[]]}}let k=[...o,...l].filter(y=>y.symbol.toUpperCase()===a);if(k.length!==1)throw new m(`Token symbol ${p(s)} is ${k.length?"ambiguous":"unverified"}; use find_token and choose an explicit address.`);let h=k[0];if(h.kind==="official_stock"&&s!==h.symbol)throw new m(`Use the exact official stock ticker ${p(h.symbol)}; case variants are refused.`);return h.source==="Oak fixed addresses"?h:{...h,name:p(h.name)}}export{Te as a,Ne as b,j as c,Y as d,be as e,Q as f,De as g,$ as h,pe as i,Pe as j,ze as k,qe as l,en as m,nn as n};
|
|
1
|
+
import{c as le}from"./XFKVU46U.js";import{a as ue}from"./MGPHD4VV.js";import{a as X}from"./3ESNHZT5.js";import{a as x,b as v}from"./HTXKERNS.js";import{a as L}from"./U4JGEMKT.js";import{a as de}from"./P4UQGWCP.js";import{a as E}from"./PBQSJSZO.js";import{b as ie,c as ce}from"./MYFAKCQI.js";import{a as oe,b as G,c as V}from"./5HCXZWUH.js";import{l as ae,n as F,o as re}from"./ABPL3ZZI.js";import{a as w,b as U,c as B,d as te,i as P,j as se,s as N}from"./FWD4L3CJ.js";import{a as m}from"./XSD5NL7J.js";import{a as p,b as W,c as ne}from"./JXOEJPJ4.js";import{decodeFunctionResult as Ie,encodeFunctionData as Le,erc20Abi as Z,getAddress as b,isAddress as H,parseAbi as ee}from"viem";var Te="https://api.robinhood.com/rhj/assets",Ne={address:x,symbol:"ETH",decimals:18,chainId:w},j={address:b(se),symbol:"USDG",decimals:te,chainId:w},Y={address:b(P[4663].tokens.WETH.address),symbol:"WETH",decimals:18,chainId:w},be={address:b(P[4663].meridian.CollateralToken_USDe.address),symbol:"USDe",decimals:18,chainId:w};function _(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Q(e,t=w,s={}){let n=Array.isArray(e)?e:_(e)&&Array.isArray(e.assets)?e.assets:void 0;if(!n)throw new m("Official stock asset list response is malformed.");let o=new Map,d=new Map;if(n.length>1e4)throw new m("Official stock asset list exceeds the lookup limit.");for(let a of n){if(!_(a))continue;let r=a;if(typeof r.tokenSymbol!="string"||!r.tokenSymbol.trim()||!Array.isArray(r.deployments))continue;if(r.deployments.length>100)throw new m("Official stock deployment list exceeds the lookup limit.");let l=r.tokenSymbol;if(!/^[A-Za-z0-9.$_-]{1,32}$/.test(l))throw new m(`Invalid official stock ticker ${p(l)}.`);if(r.tokenDecimals!==void 0&&(typeof r.tokenDecimals!="number"||!Number.isInteger(r.tokenDecimals)||r.tokenDecimals<0||r.tokenDecimals>255))throw new m("Official stock asset has invalid token decimals.");let f=typeof r.tokenDecimals=="number"&&Number.isInteger(r.tokenDecimals)&&r.tokenDecimals>=0&&r.tokenDecimals<=255?r.tokenDecimals:18;for(let k of r.deployments){if(!_(k))continue;let h=k;if(h.chainId!==t)continue;if(typeof h.contractAddress!="string"||!H(h.contractAddress,{strict:!1}))throw new m("Official stock deployment has an invalid contract address.");let y=b(h.contractAddress),u=y.toLowerCase(),g=l.toUpperCase(),i=d.get(g);if(!s.allowAmbiguousSymbols&&i&&i!==u)throw new m(`Ambiguous official stock ticker ${p(l)} across multiple addresses.`);let c=o.get(u);if(c&&(c.symbol!==l||c.decimals!==f))throw new m(`Conflicting official stock identity at ${y}.`);d.set(g,u),o.set(u,{address:y,symbol:l,decimals:f,chainId:t,...s.includeNames&&typeof r.tokenName=="string"&&r.tokenName.trim()?{name:r.tokenName.trim()}:{}})}}return[...o.values()]}function De(e,t){if(typeof e.address!="string"||!H(e.address,{strict:!1}))return!1;let s=e.chainId??w,n=e.address.toLowerCase();return t.some(o=>o.chainId===s&&o.address.toLowerCase()===n&&o.symbol===e.symbol)}function $(e,t){E(e.address);let s=e.chainId??w,n=b(e.address),o=n.toLowerCase(),d=C(e.symbol),a=t.find(l=>l.chainId===s&&l.address.toLowerCase()===o),r=t.find(l=>l.chainId===s&&C(l.symbol)===d);if(a){if(e.symbol!==a.symbol)throw new m(`Token at ${n} does not match official stock ticker ${p(a.symbol)} (received ${p(e.symbol)}).`);if(e.decimals!==void 0&&e.decimals!==a.decimals)throw new m(`Token ${p(a.symbol)} at ${n} does not match official decimals ${a.decimals}.`);return a}if(r)throw new m(`Token symbol ${p(e.symbol)} at ${n} does not match the official stock contract address ${r.address}.`);return{address:n,symbol:e.symbol.trim(),decimals:e.decimals??18,chainId:s}}var ve=["AAOI","AAPL","ABCL","ADBE","AEHR","AEIS","ALAB","AMAT","AMBA","AMC","AMD","AMKR","AMZN","ANET","APLD","APP","ASML","ASTS","AUR","AVAV","AVGO","AXON","AXTI","BA","BABA","BB","BE","BMNR","BND","BULL","CBRS","CCL","CEG","CELH","CIEN","CLOV","CLS","CLSK","COHR","COIN","COST","CRCL","CRDO","CRM","CRWD","CRWV","CSCO","CTSH","CVNA","DDOG","DELL","DIS","DJT","DOCN","ELF","EWT","EWY","F","FICO","FIG","FISV","FIX","FLNC","FLY","FTNT","FUTU","GDX","GE","GEV","GLD","GLW","GLXY","GME","GOOGL","HII","HIMS","HPE","HWM","IBM","IBRX","INDA","INFQ","INOD","INTC","INTU","IONQ","IREN","JBL","JNJ","JOBY","JPM","KLAC","KSS","KTOS","LHX","LITE","LLY","LMT","LRCX","LULU","LUNR","MCD","MDB","META","MOD","MPWR","MRNA","MRVL","MSFT","MSTR","MTSI","MU","MXL","NAVN","NBIS","NET","NFLX","NNE","NOW","NU","NVDA","NVTS","OKLO","ON","ONTO","ORCL","OUST","P","PANW","PATH","PENG","PFE","PL","PLTR","POET","POWL","PR","PWR","PYPL","QBTS","QCOM","QQQ","QUBT","RBLX","RCAT","RDDT","RDW","RGTI","RIVN","RKLB","RUN","SATS","SCHD","SGOV","SHOP","SHY","SIMO","SKHY","SLS","SLV","SMCI","SMH","SMR","SNAP","SNDK","SNOW","SOFI","SOUN","SOXX","SPCX","SPMO","SPY","TE","TEAM","TEM","TER","TSEM","TSLA","TSM","TTD","TTWO","UBER","UMC","UNH","UPS","USAR","USO","V","VICR","VRT","VSAT","VST","VTI","WDAY","WDC","WULF","WYFI","XLK","XNDU","XOM","ZETA","ZM","ZS"],J=new WeakMap,me=new WeakMap,z=new WeakMap;function K(e,t){return(z.get(e)??F)(t)}async function pe(e){let t=e?.http??ie(),s=e?.url??Te,n=e?.chainId??w,o=V(t),d=me.get(o);d||(d=new oe(3e4),me.set(o,d));let{value:a}=await K(t,()=>d.read(`${n}:${s}`,async()=>{let l=await F(k=>ce(o,s,{method:"GET",signal:k},h=>_(h)||Array.isArray(h))),f=Q(l,n,{allowAmbiguousSymbols:!0});if(n===w&&f.length===0)throw new m("Official stock asset list has no mainnet deployments; retry when the list is available.");return l})),r=Q(a,n,e);if(n===w){let l=J.get(o);l||(l=new Set,J.set(o,l));for(let f of r)l.add(C(f.symbol))}return r}var Pe=ee(["function aggregate3((address target, bool allowFailure, bytes callData)[] calls) payable returns ((bool success, bytes returnData)[] returnData)"]);function fe(e){let t=e,s=new Set;for(;t&&typeof t=="object"&&!s.has(t)&&s.size<10;){s.add(t);let n=t;if(n.name==="ContractFunctionZeroDataError"||n.name==="AbiDecodingZeroDataError")return!0;let o=`${typeof n.shortMessage=="string"?n.shortMessage:""} ${typeof n.message=="string"?n.message:""}`;if(/returned no data \("0x"\)|Cannot decode zero data/i.test(o))return!0;t=n.cause}return!1}function Ee(e){return e instanceof m?/RPC endpoint|too many requests|malformed JSON/i.test(e.message):e instanceof Error?/fetch failed|network|ECONNREFUSED|ETIMEDOUT|HTTP \d{3}|rate limit|too many requests/i.test(e.message):!1}async function xe(e,t,s){if(typeof e.getCode=="function")try{let n=await e.getCode({address:t});return!n||n==="0x"}catch{return fe(s)}return fe(s)}async function ke(e,t,s){if(t.length===0)return[];let n=await Promise.allSettled(t.map(o=>e.readContract({address:o.address,abi:Z,functionName:"balanceOf",args:[s]})));if(n.every(o=>o.status==="rejected")&&n[0]?.status==="rejected"&&Ee(n[0].reason))throw n[0].reason;return n.map(o=>{if(o.status!=="fulfilled"||o.value===void 0||o.value===null)return{ok:!1};try{let d=typeof o.value=="bigint"?o.value:BigInt(o.value);return d>=0n?{ok:!0,amount:d}:{ok:!1}}catch{return{ok:!1}}})}async function we(e,t,s,n){if(s.length===0)return[];let o=ae(t,e);if(!o)return ke(e,s,n);let d=s.map(r=>({target:r.address,allowFailure:!0,callData:Le({abi:Z,functionName:"balanceOf",args:[n]})})),a;try{a=await e.readContract({address:o,abi:Pe,functionName:"aggregate3",args:[d]})}catch(r){if(await xe(e,o,r))return ke(e,s,n);throw r}if(!Array.isArray(a)||a.length!==s.length)throw new m("Multicall3 aggregate3 returned an invalid result list.");return a.map(r=>{let l=r,f=Array.isArray(l)?l[0]:l?.success,k=Array.isArray(l)?l[1]:l?.returnData;if(!f||typeof k!="string"||k==="0x")return{ok:!1};try{let h=Ie({abi:Z,functionName:"balanceOf",data:k}),y=typeof h=="bigint"?h:BigInt(h);return y>=0n?{ok:!0,amount:y}:{ok:!1}}catch{return{ok:!1}}})}async function ze(e,t={}){E(e);let s=b(e),n=t.chainId??w,o=t.client??re(t.rpcUrl,n),d=[];if(t.stockTokens?d=[...t.stockTokens]:t.stockAssetsPayload!==void 0?d=Q(t.stockAssetsPayload,n):t.includeStockTokens!==!1&&n!==U&&(d=await pe({http:t.http,url:t.stockAssetsUrl,chainId:n})),t.tokens)for(let i of t.tokens)$(i,d);let a=n===w?[j,Y,be,...t.oakTokenAddress||process.env.OAK_TOKEN_ADDRESS?[{address:b(t.oakTokenAddress??process.env.OAK_TOKEN_ADDRESS),symbol:"OAK",decimals:B,chainId:n}]:[]]:n===U?[{...j,address:b(N.testnet.usdg),chainId:n},{...Y,address:b(N.testnet.weth),chainId:n},...t.oakTokenAddress?[{address:b(t.oakTokenAddress),symbol:"OAK",decimals:B,chainId:n}]:[]]:[],r=n===w&&t.includePoolTokens!==!1?de.vaults.flatMap(i=>[{address:b(i.tokenAddress),symbol:b(i.tokenAddress),decimals:i.tokenDecimals,chainId:n},{address:b(i.earnContractAddress),symbol:b(i.earnContractAddress),decimals:18,chainId:n}]):[],l=new Set(r.map(i=>i.address.toLowerCase())),f=[],k=new Set;for(let i of[...a,...d,...t.tokens??[],...r]){if(i.chainId!==n||v(i.address)===x)continue;let c=$(i,d),T=c.address.toLowerCase();k.has(T)||(k.add(T),f.push(c))}let[h,y]=await Promise.all([o.getBalance({address:s}),we(o,n,f,s)]),u=[],g={address:x,symbol:"ETH",decimals:18,chainId:n};(h>0n||t.includeZero)&&u.push({token:g,amount:h.toString()});for(let i=0;i<f.length;i++){let c=f[i],T=a.some(S=>O(S.address,c.address))||d.some(S=>O(S.address,c.address))?c.symbol:p(c.symbol),I=y[i]??{ok:!1};if(!I.ok){u.push({token:{address:c.address,symbol:T,decimals:c.decimals,chainId:c.chainId},amount:"unavailable"});continue}let A=I.amount;if(A>0n&&l.has(c.address.toLowerCase()))try{let[S,M]=await Promise.all([L(o,n,c.address,"symbol"),L(o,n,c.address,"decimals")]);T=p(S),c.decimals=M}catch{}(A>0n||t.includeZero)&&u.push({token:{address:c.address,symbol:T,decimals:c.decimals,chainId:c.chainId},amount:A.toString()})}return u}async function qe(e,t,s){if(E(e),t.length>1e4)throw new m("Journal token discovery exceeds the balance lookup limit.");let n=[...new Set(t.map(a=>(E(a),b(a))))].filter(a=>v(a)!==x).map(a=>({address:a,symbol:a,decimals:0,chainId:s.chainId})),o=await we(s.client,s.chainId,n,b(e)),d=n.flatMap((a,r)=>{let l=o[r];return l.ok&&l.amount===0n?[]:[{token:a,amount:l.ok?l.amount.toString():"unavailable"}]});return Promise.all(d.map(async({token:a,amount:r})=>{let[l,f]=await Promise.all([L(s.client,s.chainId,a.address,"symbol").catch(()=>a.address),L(s.client,s.chainId,a.address,"decimals").catch(()=>{throw new m(`Token decimals are unavailable for journal-received token ${a.address}; retry balances when RPC metadata is available.`)})]);return{token:{...a,symbol:p(l),decimals:f},amount:r}}))}var O=(e,t)=>e.toLowerCase()===t.toLowerCase(),C=e=>ne(e.normalize("NFKC")).toLowerCase().replace(/[^\p{L}\p{N}]/gu,"");function ge(e){let t=e.context.network??"mainnet",{chainId:s,usdg:n,weth:o}=N[t],d=(a,r,l)=>({...a,address:v(b(a.address)),name:r,kind:l,verified:!0,source:"Oak fixed addresses",warnings:[]});return[d({...Ne,chainId:s},"Ether","native"),d({...j,address:n,chainId:s},"Global Dollar","stablecoin"),d({...Y,address:o,chainId:s},"Wrapped Ether","wrapped"),...t==="mainnet"?[d(be,"USDe","stablecoin")]:[],...e.oakTokenAddress?[d({address:e.oakTokenAddress,symbol:"OAK",decimals:B,chainId:s},"Oak","oak")]:[]]}async function Ae(e){if(e.context.network==="testnet")return[];let t=e.officialStockTokens??await pe({http:e.context.http,includeNames:!0,allowAmbiguousSymbols:!0});return t.filter(s=>De(s,t)).map(s=>({...s,name:s.name??s.symbol,kind:"official_stock",verified:!0,source:Te,warnings:[]}))}async function q(e,t,s=!0){let{chainId:n}=N[t.context.network??"mainnet"],o=t.context.clientFor(n);if(await o.getChainId()!==n)throw new m(`Token lookup requires Robinhood Chain ${n}.`);let[d,a,r]=await Promise.all([K(o,()=>L(o,n,e,"name",t.blockNumber)).catch(l=>{if(s)throw l;return""}),K(o,()=>L(o,n,e,"symbol",t.blockNumber)),K(o,()=>L(o,n,e,"decimals",t.blockNumber))]);if(typeof d!="string"||s&&!d.trim()||typeof a!="string"||!a.trim()||!Number.isInteger(r)||r<0||r>255)throw new m("The contract returned invalid token metadata.");return{address:b(e),name:d||a,symbol:a,decimals:r,chainId:n}}async function he(e,t){let s=await t.context.clientFor(w).readContract({address:P[w].clanker.factory.address,abi:ee(["function tokenDeploymentInfo(address) view returns ((address,address,address,address[]))"]),functionName:"tokenDeploymentInfo",args:[e]});return Array.isArray(s)&&s.length===4&&typeof s[0]=="string"&&O(s[0],e)}async function Me(e,t){let s=t.context.clientFor(w),n=P[w].poolsTrade,o=[n.instantLaunchStrategyFeesOn.address,n.instantLaunchStrategyFeesOff.address],d=ee(["event TokenLaunched(bytes32 indexed poolId,address indexed token,address indexed feeSplitter,(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey)"])[0],a=await s.getBlockNumber(),r=new Set,l=0,f=0;for(let k=63127652n;k<=a;k+=10000000n){if(++l>Se)throw new m("Token origin scan limit reached.");let h=k+9999999n>a?a:k+9999999n,y=await s.getLogs({address:o,event:d,args:{token:e},fromBlock:k,toBlock:h,strict:!0});for(let u of y){if(u.removed||!o.some(i=>O(i,u.address))||!u.args.token||!O(u.args.token,e)||!u.transactionHash||r.has(u.transactionHash))continue;if(r.add(u.transactionHash),++f>20)throw new m("Token origin receipt limit reached.");let g=await s.getTransactionReceipt({hash:u.transactionHash});if(ue(g).some(i=>O(i.token,e)))return b(g.from)}}}var Se=5,Re=100,Ue=500,Be=3e4;function Ce(e){let t=Date.now()+Be,s=0,n=new Map,o=a=>{let r=t-Date.now();if(r<=0)throw new m("Token lookup time budget reached; results are partial.");return F(a,Math.min(1e4,r))},d=G((a,r)=>o(async l=>{let f=await e.context.http(a,{...r,signal:l});return new Proxy(f,{get(k,h){if(h==="json")return()=>o(()=>k.json());let y=Reflect.get(k,h,k);return typeof y=="function"?y.bind(k):y}})}),e.context.http);return z.set(d,o),{...e,context:{...e.context,http:d,clientFor:a=>{if(!n.has(a)){let r=e.context.clientFor(a),l=f=>{if(++s>Ue)throw new m("Token lookup RPC budget reached; results are partial.");return o(f)};n.set(a,G(new Proxy(r,{get(f,k){let h=Reflect.get(f,k);return typeof h!="function"?h:(...y)=>l(()=>h.apply(f,y))}}),r)),z.set(n.get(a),l)}return n.get(a)}}}}function ye(e){return e.source==="Oak fixed addresses"?e:{...e,symbol:p(e.symbol),name:p(e.name)}}async function en(e,t){if(t=Ce(t),typeof e!="string"||e.length>256||!C(e))throw new m("Provide a token name, symbol or address to find_token.");let s=C(e),n=H(e.trim(),{strict:!1})?v(b(e.trim())):void 0,{chainId:o}=N[t.context.network??"mainnet"],d=[],a=ge(t),r=!1;try{a.push(...await Ae(t))}catch{r=!0,d.push("The official stock list is unavailable; results are partial and stock identities and lookalikes could not be checked.")}let l=i=>n?O(i.address,n):C(i.symbol).includes(s)||C(i.name).includes(s),f=a.filter(l),k=[],h=(i,c)=>[i.symbol,i.name??""].some(T=>[c.symbol,c.name].some(I=>{let A=C(T),S=C(I);return!!A&&!!S&&(A.includes(S)||S.includes(A))})),y=(i,c={})=>{if(k.some(A=>O(A.address,i.address)))return;let T=[`Token ${p(i.symbol)} at ${i.address} is an unverified ${c.launchpad?"launchpad token":"token"}. Use its address, not its name or symbol.`];(W(i.symbol)||W(i.name)||a.some(A=>!O(A.address,i.address)&&h(i,A)))&&T.push(`Lookalike warning: ${p(i.symbol)} at ${i.address} resembles a verified token's name or symbol.`);let I={...i,...c,kind:c.launchpad?"launchpad":"erc20",verified:!1,source:c.launchpad?`${c.launchpad} origin and on-chain metadata; not a verified token`:"On-chain metadata only",warnings:T};k.push(I),d.push(...T)};if(n&&!f.length){let i=await q(n,t),c={};if(o===w){try{await he(n,t)&&(c.launchpad="clanker")}catch{d.push("Clanker origin lookup was unavailable for this address.")}if(c.launchpad==="clanker")try{let I=(await X(t.context,{q:n,limit:20})).tokens.find(A=>O(A.contract_address,n));I&&(c.creator=b(I.msg_sender),c.creatorSource="Clanker indexer msg_sender")}catch{d.push("Clanker creator lookup is unavailable.")}else try{let T=await le(t.context,n);c.launchpad="pons",c.creator=b(T.creator),c.creatorSource="Pons factory deployer"}catch{d.push("Pons launch origin could not be confirmed for this address.")}if(!c.launchpad)try{let T=await Me(n,t);T&&(c.launchpad="pools.trade",c.creator=T,c.creatorSource="Launch transaction sender; may be a relayer")}catch{r=!0,d.push("pools.trade launch receipt lookup is unavailable; origin results are partial.")}}y(i,c)}else if(!n&&o===w){let i=new Set,c=new Set,T,I=0,A=0;try{do{if(++I>Se)throw new m("Token search page limit reached.");let S=await X(t.context,{q:e.trim(),limit:20,...T?{cursor:T}:{}});for(let M of S.tokens){if(++A>Re)throw new m("Token candidate limit reached.");let D=b(M.contract_address);if(!(c.has(D)||a.some(R=>O(R.address,D)))){c.add(D);try{let R=await q(D,t);if(!l(R))continue;let Oe=await he(D,t)?{launchpad:"clanker",creator:b(M.msg_sender),creatorSource:"Clanker indexer msg_sender"}:{};y(R,Oe)}catch{r=!0,d.push(`Could not read Clanker candidate ${D}; it was omitted from these partial results.`)}}}if(S.cursor&&i.has(S.cursor))throw new m("The Clanker indexer repeated a pagination cursor.");S.cursor&&i.add(S.cursor),T=S.cursor??void 0}while(T)}catch{r=!0,d.push("Clanker name search is unavailable, incomplete or reached its scan limit; results are partial.")}d.push("Pons and pools.trade require a token address; name search does not cover those launchpads.")}o===U&&d.push("Testnet lookup covers pinned tokens and explicit token addresses; stock and launchpad discovery are unavailable.");let u=i=>[...new Map(i.map(c=>[c.address.toLowerCase(),c])).values()],g=u([...f,...k]);for(let i of g)if(g.some(c=>!O(c.address,i.address)&&(C(i.symbol)===C(c.symbol)||C(i.name)===C(c.name)))){let c=`Duplicate warning: several tokens share the symbol or name of ${i.address}. Choose the intended address; do not guess from the name.`;i.warnings.push(c),d.push(c)}return f.length>1&&d.push("Several verified tokens match this search, including possible substring matches. Choose an exact address; the search does not select a quote token."),{query:p(e.trim()),chainId:o,partial:r,matches:u(f).map(ye),unverified:u(k).map(ye),warnings:d}}async function nn(e,t){if(typeof e!="string"||!e.trim())throw new m("Provide a token address or verified symbol; use find_token to look it up.");if(!/^[A-Za-z0-9.$_-]{1,42}$/.test(e))throw new m("Use an exact ASCII verified symbol or token address; use find_token to look it up.");let s=e,n=H(s,{strict:!1})?v(b(s)):void 0,o=ge(t),d=n&&o.find(y=>O(y.address,n));if(d)return d;let a=s.toUpperCase()==="$OAK"?"OAK":s.toUpperCase(),r=!n&&o.find(y=>y.symbol.toUpperCase()===a),l=[],f=!1;try{l=await Ae(t)}catch{if(r)return r;if(!n)throw new m("The official stock list is unavailable; stock symbols cannot be checked. Use find_token and try again when the list is reachable.");f=!0}if(n){let y=l.find(i=>O(i.address,n));if(y)return t.tokenMetadata&&$(t.tokenMetadata,l),{...y,name:p(y.name)};let u=t.tokenMetadata??await t.readMetadata?.(n);if(u&&(!O(u.address,n)||u.chainId!==N[t.context.network??"mainnet"].chainId))throw new m("Token metadata does not match the requested address and chain.");if(u&&(typeof u.symbol!="string"||!u.symbol.trim()||!Number.isInteger(u.decimals)||u.decimals<0||u.decimals>255))throw new m("The contract returned invalid token metadata.");let g=u?{...u,name:u.symbol}:await q(n,Ce(t),!1);if(f){let i=C(g.symbol),c=J.get(V(t.context.http));if(ve.some(T=>C(T)===i)||c?.has(i))throw new m("The official stock list is unavailable; this address claims a stock ticker that cannot be checked. Try again when the list is reachable.")}return $(g,l),{...g,symbol:p(g.symbol),name:p(g.name),kind:"erc20",verified:!1,source:"On-chain metadata only",warnings:["This token address is unverified. On-chain names and symbols do not prove identity.",...f?["The official stock list is unavailable; stock identity could not be verified."]:[]]}}let k=[...o,...l].filter(y=>y.symbol.toUpperCase()===a);if(k.length!==1)throw new m(`Token symbol ${p(s)} is ${k.length?"ambiguous":"unverified"}; use find_token and choose an explicit address.`);let h=k[0];if(h.kind==="official_stock"&&s!==h.symbol)throw new m(`Use the exact official stock ticker ${p(h.symbol)}; case variants are refused.`);return h.source==="Oak fixed addresses"?h:{...h,name:p(h.name)}}export{Te as a,Ne as b,j as c,Y as d,be as e,Q as f,De as g,$ as h,pe as i,Pe as j,ze as k,qe as l,en as m,nn as n};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as y,h as A}from"./
|
|
1
|
+
import{d as y,h as A}from"./JG27HM4P.js";import{b as p,e as f,g as v}from"./SGEZIYJW.js";import{c as l}from"./5KUWLUPM.js";import{a as g}from"./FWD4L3CJ.js";import{a as r}from"./XSD5NL7J.js";import{parseAbi as I,zeroAddress as N}from"viem";var S=I(["function observe(uint32[] secondsAgos) view returns (int56[] tickCumulatives,uint160[] secondsPerLiquidityCumulativeX128s)"]);function j(s){return{tools:[{name:"uniswap_oracle",inputSchema:{type:"object",additionalProperties:!1,required:["token0","token1","fee","secondsAgo"],properties:{token0:l,token1:l,fee:{type:"integer",minimum:0,maximum:999999},secondsAgo:{type:"integer",minimum:1,maximum:4294967295}}},async execute(t){v(t,["token0","token1","fee","secondsAgo"]);let a=p(t.token0),c=p(t.token1),o=t.fee,e=t.secondsAgo;if(BigInt(a)>=BigInt(c))throw new r("Oracle tokens must be strictly sorted token0 < token1.");if(typeof o!="number"||!Number.isInteger(o)||o<0||o>=1e6||typeof e!="number"||!Number.isInteger(e)||e<=0||e>4294967295)throw new r("Provide integer fee pips and a positive uint32 secondsAgo.");let m=s.clientFor(g),i=await m.getBlockNumber(),u=await m.readContract({address:y.factory,abi:A,functionName:"getPool",args:[a,c,o],blockNumber:i});if(u===N)throw new r("No factory-verified v3 pool exists for this oracle.");let[[n,k],w,h]=await Promise.all([m.readContract({address:u,abi:S,functionName:"observe",args:[[e,0]],blockNumber:i}),f(s,a,i),f(s,c,i)]);if(n.length!==2||k.length!==2)throw new r("Oracle returned an unexpected observation count.");let d=n[1]-n[0],b=BigInt(e),P=d/b-(d<0n&&d%b!==0n?1n:0n);return{pool:u,token0:w,token1:h,secondsAgo:e,blockNumber:i.toString(),tickCumulatives:n.map(String),secondsPerLiquidityCumulativeX128s:k.map(String),arithmeticMeanTick:P.toString(),summary:"V3 time-weighted arithmetic mean tick, rounded toward negative infinity. Price is token1-base-units per token0-base-unit before decimal adjustment. Insufficient pool history reverts; an unavailable oracle is never reported as zero."}}}]}}export{j as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as q}from"./PBQSJSZO.js";import{a as j}from"./5ZLOCQA4.js";import{d as ne,f as te,g as v,i as oe}from"./5KUWLUPM.js";import{a as p,i as ee}from"./FWD4L3CJ.js";import{a as o}from"./XSD5NL7J.js";import{a as U}from"./JXOEJPJ4.js";import{encodeFunctionData as W,encodePacked as ue,erc20Abi as V,getAddress as y,hashMessage as fe,keccak256 as pe,parseAbi as D,recoverMessageAddress as me,toHex as we,zeroAddress as _}from"viem";var g=y("0xE3535330a82867cD7b81C0d7e518f465D12dDd99"),A=y("0xf08c65564eb07d880021105489552080b08e4319"),re=y("0xc3e91d2d8a4145055c26c1174eb124ff3e3ed697"),ae=y("0x7c4726c6fb8eeb7b329ac037bbc71cc3153234b5"),le=y("0xa76c1d0bdcd94f16d5edd01c29483a2131d4c529"),C={address:y(ee[p].tokens.USDG.address),symbol:"USDG",decimals:6,chainId:p},N=D(["function acceptOffer((uint256 loanPrincipalAmount,uint256 maximumRepaymentAmount,uint256 nftCollateralId,address nftCollateralContract,uint32 loanDuration,uint16 loanAdminFeeInBasisPoints,address loanERC20Denomination,address referrer) offer,(uint256 nonce,uint256 expiry,address signer,bytes signature) signature,(address revenueSharePartner,uint16 referralFeeInBasisPoints) borrowerSettings) returns (uint32)","function payBackLoan(uint32 loanId)","function getPayoffAmount(uint32 loanId) view returns (uint256)","function loanIdToLoan(uint32 loanId) view returns (uint256 loanPrincipalAmount,uint256 maximumRepaymentAmount,uint256 nftCollateralId,address loanERC20Denomination,uint32 loanDuration,uint16 loanInterestRateForDurationInBasisPoints,uint16 loanAdminFeeInBasisPoints,address nftCollateralWrapper,uint64 loanStartTime,address nftCollateralContract,address borrower)","function loanRepaidOrLiquidated(uint32 loanId) view returns (bool)","function getWhetherNonceHasBeenUsedForUser(address user,uint256 nonce) view returns (bool)","function hub() view returns (address)","function paused() view returns (bool)","function maximumLoanDuration() view returns (uint256)","function adminFeeInBasisPoints() view returns (uint16)"]),J=D(["function ownerOf(uint256 tokenId) view returns (address)","function approve(address spender,uint256 tokenId)","function supportsInterface(bytes4) view returns (bool)"]),ge=D(["function getContract(bytes32) view returns (address)"]),be=D(["function getNFTWrapper(address) view returns (address)"]),M=["loanPrincipalAmount","maximumRepaymentAmount","nftCollateralId","nftCollateralContract","loanDuration","loanAdminFeeInBasisPoints","loanERC20Denomination","referrer"],Z=["nonce","expiry","signer","signature"],$=n=>te(n,"Provide the documented Longbow NFT object.");function F(n,d){if(Object.keys(n).some(i=>!d.includes(i)))throw new o("Unsupported Longbow NFT argument.")}function h(n,d=256){if(typeof n!="string"||!/^\d+$/.test(n)||n.length>78||BigInt(n)>=1n<<BigInt(d))throw new o(`NFT amounts and IDs must be uint${d} decimal strings.`);return BigInt(n)}function f(n){return oe(n,"Provide an NFT contract address.",ne)}var K=n=>{if(n>8640000000000n)throw new o("NFT deadline exceeds the supported timestamp range.");return new Date(Number(n)*1e3).toISOString()};function ie(n,d,i=!0){let s=$(n),e=$(d);F(s,M),F(e,Z);let t={loanPrincipalAmount:h(s.loanPrincipalAmount),maximumRepaymentAmount:h(s.maximumRepaymentAmount),nftCollateralId:h(s.nftCollateralId),nftCollateralContract:f(s.nftCollateralContract),loanDuration:Number(h(s.loanDuration,32)),loanAdminFeeInBasisPoints:Number(h(s.loanAdminFeeInBasisPoints,16)),loanERC20Denomination:f(s.loanERC20Denomination),referrer:f(s.referrer)};if(i&&(!v(t.nftCollateralContract,A)||!v(t.loanERC20Denomination,C.address)))throw new o("NFT borrowing supports only Robinhood Punks collateral and canonical USDG.");if(i&&(t.loanPrincipalAmount===0n||t.maximumRepaymentAmount<t.loanPrincipalAmount||t.loanDuration===0||t.referrer!==_))throw new o("NFT offer principal, payoff, duration or referrer is unsupported.");if(typeof e.signature!="string"||!/^0x(?:[0-9a-f]{2}){0,4096}$/i.test(e.signature))throw new o("Provide the existing lender\u2019s bounded hexadecimal offer signature; Oak does not sign lender offers.");let r={nonce:h(e.nonce),expiry:h(e.expiry),signer:f(e.signer),signature:e.signature};if(r.signer===_)throw new o("NFT lender cannot be the zero address.");return{offer:t,signature:r}}function he(n){let{offer:d,signature:i}=n;return pe(ue(["address","uint256","uint256","address","uint256","address","uint32","uint16","address","uint256","uint256","address","uint256"],[d.loanERC20Denomination,d.loanPrincipalAmount,d.maximumRepaymentAmount,d.nftCollateralContract,d.nftCollateralId,d.referrer,d.loanDuration,d.loanAdminFeeInBasisPoints,i.signer,i.nonce,i.expiry,g,BigInt(p)]))}function se(n,d){if(n.filter(s=>s.token.chainId===p&&v(s.token.address,C.address)).reduce((s,e)=>{if(e.token.decimals!==C.decimals||!/^-?\d+$/.test(e.amount))throw new o("Invalid NFT currency preview metadata.");return s+BigInt(e.amount)},0n)!==d)throw new o("NFT preview does not match the exact principal or payoff.")}async function de(n){let d=n.clientFor(p);if(await d.getChainId()!==p)throw new o("Longbow NFT loans require chain 4663.");let i=await d.getBlock(),s=(a,w,m,u=[])=>d.readContract({address:a,abi:w,functionName:m,args:u,blockNumber:i.number}),[e,t,r,l]=await Promise.all([s(g,N,"hub"),s(re,ge,"getContract",[we("PERMITTED_NFTS",{size:32})]),s(ae,be,"getNFTWrapper",[A]),s(A,J,"supportsInterface",["0x80ac58cd"])]);if(f(e)!==re||f(t)!==ae||f(r)!==le||l!==!0)throw new o("The NFT hub, collection interface or collateral wrapper changed. No action was built.");return{client:d,block:i,read:s}}async function G(n,d){let i=Number(h(d,32));if(i===0)throw new o("NFT loanId must be positive.");let s=n.clientFor(p);if(await s.getChainId()!==p)throw new o("Longbow NFT loan reads require chain 4663.");let e=await s.getBlock(),t=(T,I,E,b=[])=>s.readContract({address:T,abi:I,functionName:E,args:b,blockNumber:e.number}),[r,l,a]=await Promise.all([t(g,N,"loanIdToLoan",[i]),t(g,N,"loanRepaidOrLiquidated",[i]),t(g,N,"getPayoffAmount",[i])]);if(!Array.isArray(r)||r.length!==11||typeof l!="boolean")throw new o("Invalid NFT loan state.");let[w,m,u,c,z,,,R,S,B,O]=r;if(BigInt(S)===0n)throw new o("This NFT loan does not exist.");let L=f(c)===C.address&&f(B)===A&&f(R)===le&&f(O)!==_,x=C;if(f(c)!==C.address){let[T,I]=await Promise.all([t(f(c),V,"symbol"),t(f(c),V,"decimals")]);if(typeof I!="number"||!Number.isInteger(I)||I<0||I>255)throw new o("NFT loan currency decimals are unavailable.");x={address:f(c),symbol:typeof T=="string"&&/^[A-Za-z0-9$._ -]{1,32}$/.test(T)?T:"TOKEN",decimals:I,chainId:p}}if(typeof a!="bigint"||a!==BigInt(m)||a<BigInt(w))throw new o("NFT payoff does not match the fixed loan terms.");let P=BigInt(S)+BigInt(z);return{loanId:d,loanContract:g,chainId:p,blockNumber:e.number.toString(),collection:f(B),wrapper:f(R),tokenId:String(u),borrower:f(O),currency:x,supportedForActions:L,principalAmount:String(w),payoffAmount:a.toString(),startedAt:String(S),deadline:P.toString(),deadlineUtc:K(P),status:l?"repaid_or_liquidated":e.timestamp>P?"overdue":"active",repayable:!l&&e.timestamp<=P,warning:"After the on-chain deadline repayment is rejected; the lender can permanently take this NFT. Settled state alone does not distinguish repayment from liquidation."}}async function H(n,d){let i=await n.http(`https://longbow.credit/api/nft${d}`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4),redirect:"error"});if(!i.ok)throw new o("Longbow NFT discovery is unavailable. Retry the read; no loan was originated.");let s=await i.json();if(!Array.isArray(s)||s.length>1e3)throw new o("Longbow NFT discovery returned an invalid or oversized list.");return s.map($)}var ve=n=>{async function d(e,t,r){if(q(t),r){if(F(e,["loanId","maxPayoff"]),typeof e.loanId!="string")throw new o("NFT loanId must be a decimal string.");let b=await G(n,e.loanId);if(!b.supportedForActions)throw new o("This NFT loan is read-only in Oak; its collection, currency, wrapper or obligation-receipt borrower is not qualified for repayment.");let ce=h(e.maxPayoff);if(await de(n),b.borrower!==y(t))throw new o("Only this NFT loan\u2019s borrower may repay through Oak.");if(!b.repayable)throw new o("NFT loan is settled or overdue; repayment is unavailable.");let k=BigInt(b.payoffAmount);if(k>ce)throw new o("NFT payoff exceeds maxPayoff.");if(await n.clientFor(p).readContract({address:C.address,abi:V,functionName:"balanceOf",args:[t]})<k)throw new o(`NFT repayment needs ${k} USDG base units. Top up before the deadline ${b.deadlineUtc}.`);let Y=`Repay ${k} USDG base units to recover Robinhood Punks ${b.collection} token ID ${b.tokenId}; deadline ${b.deadlineUtc}.`,Q=[n.approval(C.address,g,k.toString(),p),n.unsignedTx({to:g,data:W({abi:N,functionName:"payBackLoan",args:[Number(b.loanId)]}),value:"0",chainId:p,description:Y})],X=await n.preview(Q,t);return se(X.changes,-k),{txs:Q,preview:X,summary:Y,requiresHumanConfirmation:!0}}F(e,["offer","lenderSignature"]);let l=ie(e.offer,e.lenderSignature),{offer:a,signature:w}=l,{client:m,block:u,read:c}=await de(n),[z,R,S,B,O]=await Promise.all([c(A,J,"ownerOf",[a.nftCollateralId]),c(g,N,"getWhetherNonceHasBeenUsedForUser",[w.signer,w.nonce]),c(g,N,"paused"),c(g,N,"maximumLoanDuration"),c(g,N,"adminFeeInBasisPoints")]);if(f(z)!==y(t))throw new o("This wallet does not own the offered NFT.");if(R!==!1||S!==!1||w.expiry<u.timestamp||BigInt(a.loanDuration)>BigInt(String(B))||a.loanAdminFeeInBasisPoints!==O)throw new o("NFT offer is used, expired, paused or inconsistent with current loan settings.");let L=he(l),x=!1;try{x=v(await me({message:{raw:L},signature:w.signature}),w.signer)}catch{}if(!x){let b=await m.getCode({address:w.signer,blockNumber:u.number});b&&b!=="0x"&&(x=await c(w.signer,D(["function isValidSignature(bytes32,bytes) view returns (bytes4)"]),"isValidSignature",[fe({raw:L}),w.signature])==="0x1626ba7e")}if(!x)throw new o("NFT offer signature does not match these terms, chain and loan contract.");let P=u.timestamp+BigInt(a.loanDuration),T=`Borrow ${a.loanPrincipalAmount} USDG base units; total payoff ${a.maximumRepaymentAmount} USDG base units. Escrow Robinhood Punks collection ${a.nftCollateralContract}, token ID ${a.nftCollateralId}. Estimated absolute repayment deadline ${K(P)} at snapshot ${u.number}; actual deadline is the mined start plus ${a.loanDuration} seconds. Read longbow_nft_loan after mining. Late repayment is rejected and you can permanently lose this NFT. Approve only this token ID to ${g}.`,I=[n.unsignedTx({to:A,data:W({abi:J,functionName:"approve",args:[g,a.nftCollateralId]}),value:"0",chainId:p,description:`Approve only Robinhood Punks token ID ${a.nftCollateralId} to the pinned loan contract.`}),n.unsignedTx({to:g,data:W({abi:N,functionName:"acceptOffer",args:[a,w,{revenueSharePartner:_,referralFeeInBasisPoints:0}]}),value:"0",chainId:p,description:T})],E=await n.preview(I,t);return se(E.changes,a.loanPrincipalAmount),{txs:I,preview:E,summary:T,requiresHumanConfirmation:!0,estimatedDeadlineUtc:K(P),deadlineIsEstimate:!0}}let i=(e,t,r,l)=>({name:e,inputSchema:{type:"object",properties:t,required:r,additionalProperties:!1},execute:async(a,w)=>{try{return await l(a,w)}catch(m){throw new o(n.plainError(m))}}});async function s(e){q(e);let t=(r,l)=>({module:"longbow",id:`4663:${g.toLowerCase()}:${r}`,chainId:p,incomplete:!0,assets:[],description:`Longbow borrower NFT loans unreadable: ${n.plainError(l)} Use longbow_nft_loans or longbow_nft_loan for a known loanId.`});try{let r=await H(n,`/loans/borrower/${y(e)}`);if(r.length>100)throw new o("NFT loan discovery exceeds 100 rows; read specific loan IDs with longbow_nft_loan.");let l=new Set,a=[];for(let[w,m]of r.entries()){let u=`unreadable-${w}`;try{if(m.loanContract!==void 0&&f(m.loanContract)!==g)throw new o("The NFT indexer returned a loan from another contract.");if(u=h(String(m.loanId??m.id),32).toString(),l.has(u))continue;l.add(u);let c=await G(n,u);if(c.borrower!==y(e))throw new o("The NFT indexer returned another borrower\u2019s loan.");if(c.status==="repaid_or_liquidated")continue;a.push({module:"longbow",id:`4663:${g.toLowerCase()}:${u}`,chainId:p,assets:[],description:`Longbow borrower NFT loan ${u}: ${c.status}, payoff debt ${c.payoffAmount} ${c.currency.symbol} base units (token ${c.currency.address}, decimals ${c.currency.decimals}); collateral ${c.collection} token ID ${c.tokenId} is escrowed. Deadline ${c.deadlineUtc}. ${c.repayable?"Use longbow_nft_repay before the deadline.":"Repayment is unavailable; the lender can permanently take the collateral."} Indexer discovery may be incomplete; lender interests are not included.`})}catch(c){a.push(t(u,c))}}return a}catch(r){return[t("unreadable",r)]}}return{positions:s,tools:[i("longbow_nft_listings",{},[],async e=>{F(e,[]);let t=await H(n,"/listings");return{chainId:p,source:"Longbow public order book; untrusted and potentially stale. No offer or execution is guaranteed.",listings:t.map(r=>{if(r.chainId!==p)throw new o("Longbow returned a listing on another chain.");return{id:U(String(r.id)),collection:f(r.nftContract??r.collection),tokenId:h(r.tokenId).toString(),borrower:f(r.borrower??r.owner),status:U(String(r.status)),note:r.note==null?null:U(String(r.note)).slice(0,512)}})}}),i("longbow_nft_offers",{listingId:{type:"string",maxLength:128}},["listingId"],async e=>{if(F(e,["listingId"]),typeof e.listingId!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(e.listingId))throw new o("Provide the listingId returned by longbow_nft_listings.");let t=await H(n,`/listings/${encodeURIComponent(e.listingId)}/offers`);return{listingId:e.listingId,offers:t.map(r=>{let l=r.raw?$(r.raw):r,a={...$(l.offer??Object.fromEntries(M.map(m=>[m,l[m]])))};for(let m of["loanDuration","loanAdminFeeInBasisPoints"]){let u=a[m];typeof u=="number"&&Number.isSafeInteger(u)&&u>=0&&(a[m]=String(u))}let w=ie(a,typeof l.signature=="object"?l.signature:{nonce:l.nonce,expiry:l.expiry,signer:l.signer??l.lender,signature:l.signature},!1);return JSON.parse(JSON.stringify({id:String(r.id),...w},(m,u)=>typeof u=="bigint"||m==="loanDuration"||m==="loanAdminFeeInBasisPoints"?String(u):u))}),caveat:"These are lender-signed terms from an untrusted indexer. Accept rechecks ownership, wrapper, nonce, expiry and signature on chain. Empty offers do not imply a discovery failure."}}),i("longbow_nft_loan",{loanId:j()},["loanId"],async e=>{if(F(e,["loanId"]),typeof e.loanId!="string")throw new o("NFT loanId must be a decimal string.");return G(n,e.loanId)}),i("longbow_nft_loans",{role:{enum:["borrower","lender"]}},[],async(e,t)=>{F(e,["role"]),q(t);let r=e.role??"borrower";if(r!=="borrower"&&r!=="lender")throw new o("Choose borrower or lender NFT loan discovery.");let l=await H(n,`/loans/${r}/${y(t)}`);if(l.length>100)throw new o("NFT loan discovery exceeds 100 rows; read a specific loanId.");return{source:"Longbow indexer IDs, freshly checked on chain. Indexer completeness is not guaranteed.",loans:await Promise.all(l.map(a=>{if(a.loanContract!==void 0&&f(a.loanContract)!==g)throw new o("The NFT indexer returned a loan from another contract.");return G(n,String(a.loanId??a.id))}))}}),i("longbow_nft_accept_offer",{offer:{type:"object",properties:Object.fromEntries(M.map(e=>[e,{type:"string"}])),required:M,additionalProperties:!1},lenderSignature:{type:"object",properties:Object.fromEntries(Z.map(e=>[e,{type:"string"}])),required:Z,additionalProperties:!1}},["offer","lenderSignature"],(e,t)=>d(e,t,!1)),i("longbow_nft_repay",{loanId:j(),maxPayoff:j()},["loanId","maxPayoff"],(e,t)=>d(e,t,!0))]}};async function ke(n,d,i){if(await n.getChainId()!==p||i<0n||i>=1n<<256n)throw new o("NFT cleanup requires chain 4663 and the original token ID.");let s=D(["function ownerOf(uint256) view returns (address)","function getApproved(uint256) view returns (address)","function approve(address,uint256)"]),e=await n.readContract({address:A,abi:s,functionName:"ownerOf",args:[i]});if(!v(e,d))return;let t=await n.readContract({address:A,abi:s,functionName:"getApproved",args:[i]});if(v(t,g))return{to:A,data:W({abi:s,functionName:"approve",args:[_,i]}),value:"0",chainId:p,description:`Revoke only Robinhood Punks token ID ${i} approval to the Longbow loan contract.`}}export{g as a,A as b,re as c,ae as d,le as e,N as f,h as g,ie as h,he as i,G as j,ve as k,ke as l};
|