@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{a as L}from"./
|
|
1
|
+
import{a as L}from"./PBQSJSZO.js";import{a as Q}from"./UP7FBDMJ.js";import{a as x,i as J}from"./FWD4L3CJ.js";import{a as r}from"./XSD5NL7J.js";import{decodeAbiParameters as se,encodeAbiParameters as Z,encodeFunctionData as F,erc20Abi as $,getAddress as g,keccak256 as ee,parseAbi as D,parseAbiParameters as oe,zeroAddress as te}from"viem";var N=10n**18n,B=(1n<<256n)-1n,q=g(J[x].morpho.morpho_blue.address),_=oe("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),w=D(["function adaptersLength() view returns (uint256)","function adapters(uint256) view returns (address)","function liquidityAdapter() view returns (address)","function liquidityData() view returns (bytes)","function forceDeallocatePenalty(address) view returns (uint256)","function performanceFee() view returns (uint256)","function managementFee() view returns (uint256)","function owner() view returns (address)","function curator() view returns (address)","function previewRedeem(uint256) view returns (uint256)","function previewWithdraw(uint256) view returns (uint256)","function forceDeallocate(address adapter,bytes data,uint256 assets,address onBehalf) returns (uint256)","function redeem(uint256 shares,address receiver,address owner) returns (uint256)","function multicall(bytes[] data)"]),I=D(["function parentVault() view returns (address)","function asset() view returns (address)","function morpho() view returns (address)","function marketIdsLength() view returns (uint256)","function marketIds(uint256) view returns (bytes32)","function expectedSupplyAssets(bytes32) view returns (uint256)"]),ne=D(["function idToMarketParams(bytes32) view returns (address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)","function market(bytes32) view returns (uint128 totalSupplyAssets,uint128 totalSupplyShares,uint128 totalBorrowAssets,uint128 totalBorrowShares,uint128 lastUpdate,uint128 fee)"]),M=(e,t)=>e<t?e:t,T=(e,t)=>(e+t-1n)/t;function f(e){if(typeof e!="bigint"||e<0n||e>B)throw new r("Invalid Morpho V2 integer read.");return e}function ye(e){if(typeof e!="string")throw new r("Provide maxPenaltyAssets as a USDG base-unit integer string, including 0 for no penalty.");let t=Q(e);if(t>B)throw new r("Penalty limit exceeds uint256.");return t}function h(e){if(typeof e!="string")throw new r("Invalid Morpho V2 address read.");return L(e),g(e)}async function ae(e,t,a){if(await e.getChainId()!==x||a.chainId!==x)throw new r("Vault exit requires chain 4663.");let c=await e.getBlockNumber({cacheTime:0}),n=(p,y,k,P=[])=>e.readContract({address:p,abi:y,functionName:k,args:P,blockNumber:c}),[l,o,i,d,u]=await Promise.all([n(t,w,"adaptersLength"),n(t,w,"liquidityAdapter"),n(t,w,"liquidityData"),n(g(a.address),$,"balanceOf",[t]),n(g(a.address),$,"balanceOf",[q])]);if(f(l)!==1n)throw new r("Force exit requires exactly one verified MorphoMarketV1AdapterV2. This vault needs a separately qualified adapter plan.");let s=h(await n(t,w,"adapters",[0n])),v=h(o);if(v!==te&&v!==s)throw new r("The liquidity adapter is not the supported market adapter.");let[A,C,S,m,O]=await Promise.all([n(s,I,"parentVault"),n(s,I,"asset"),n(s,I,"morpho"),n(s,I,"marketIdsLength"),n(t,w,"forceDeallocatePenalty",[s])]);if(h(A)!==g(t)||h(C)!==g(a.address)||h(S)!==q)throw new r("The adapter does not match this vault and pinned Morpho Blue deployment.");let b=f(m);if(b>64n)throw new r("The adapter market inventory exceeds this reader\u2019s supported size.");let E=f(O);if(E>N/50n)throw new r("The force-deallocation penalty exceeds the documented 2% maximum.");let H;if(v!==te){if(typeof i!="string")throw new r("Invalid liquidity-market data.");let[p]=se(_,i);H=ee(Z(_,[p])).toLowerCase()}let V=await Promise.all(Array.from({length:Number(b)},(p,y)=>n(s,I,"marketIds",[BigInt(y)])));if(V.some(p=>typeof p!="string"||!/^0x[0-9a-f]{64}$/i.test(p))||new Set(V.map(p=>String(p).toLowerCase())).size!==V.length)throw new r("The adapter returned an invalid or duplicate market ID.");let R=await Promise.all(V.map(async p=>{let y=p,[k,P,ie]=await Promise.all([n(q,ne,"idToMarketParams",[y]),n(q,ne,"market",[y]),n(s,I,"expectedSupplyAssets",[y])]);if(!Array.isArray(k)||k.length!==5||!Array.isArray(P)||P.length!==6)throw new r("Invalid Morpho market state.");let z={loanToken:h(k[0]),collateralToken:h(k[1]),oracle:h(k[2]),irm:h(k[3]),lltv:f(k[4])},j=Z(_,[z]);if(ee(j).toLowerCase()!==y.toLowerCase()||z.loanToken!==g(a.address))throw new r("Morpho market identity or loan asset does not match the vault.");let X=f(P[0]),Y=f(P[2]);if(Y>X)throw new r("Invalid Morpho market liquidity.");let G=f(ie),K=X-Y;return{id:y,adapter:s,data:j,supplied:G,liquidity:K,capacity:M(G,K),penalty:E,normal:y.toLowerCase()===H}})),U=f(d),W=f(u),re=U+M(W,R.filter(p=>p.normal).reduce((p,y)=>p+y.capacity,0n));return{vault:t,blockNumber:c,idle:U,blueCash:W,normalCapacity:re,markets:R}}function de(e,t){if(t<=0n||t>B)throw new r("Force exit needs a positive position value.");let a=t>e.normalCapacity?t-e.normalCapacity:0n,c=[],n=e.blueCash-(e.normalCapacity-e.idle);for(let l of e.markets.filter(o=>!o.normal).sort((o,i)=>o.capacity===i.capacity?o.id.localeCompare(i.id):o.capacity>i.capacity?-1:1)){if(a===0n)break;let o=M(l.capacity,n);if(o===0n)continue;let i=s=>s+T(s*l.penalty,N),d=o;i(o)>=a&&(d=T(a*N,N+l.penalty),d>0n&&i(d-1n)>=a&&(d-=1n),d=M(o,d+(T(t,10000n)||1n)));let u=T(d*l.penalty,N);c.push({...l,amount:d,penaltyAssets:u}),n-=d,a=i(d)>=a?0n:a-i(d)}if(a>0n)throw new r("Underlying market liquidity cannot cover this force exit. Request a partial withdrawal or use a separately supported in-kind exit; force deallocation cannot create liquidity.");return{requestedAssets:t,normalCapacity:e.normalCapacity,legs:c,penaltyAssets:c.reduce((l,o)=>l+o.penaltyAssets,0n)}}async function he(e,t,a,c,n,l,o){let i=await ae(t,a,o),d=f(await t.readContract({address:a,abi:$,functionName:"balanceOf",args:[c],blockNumber:i.blockNumber}));if(n<=0n||n>d)throw new r("The fresh share balance cannot cover this exit.");let u=f(await t.readContract({address:a,abi:w,functionName:"previewRedeem",args:[n],blockNumber:i.blockNumber})),s=de(i,u);if(s.penaltyAssets>l)throw new r("The force-exit penalty exceeds maxPenaltyAssets. Inspect a fresh plan before authorizing a larger penalty.");let A=(await Promise.all(s.legs.map(b=>t.readContract({address:a,abi:w,functionName:"previewWithdraw",args:[b.penaltyAssets],blockNumber:i.blockNumber})))).reduce((b,E)=>b+f(E),0n);if(A>=n)throw new r("The penalty would consume the share balance.");let C=n-A,S=s.legs.map(b=>F({abi:w,functionName:"forceDeallocate",args:[b.adapter,b.data,b.amount,c]})),m=F({abi:w,functionName:"redeem",args:[C,c,c]});return S.push(m),{tx:e.unsignedTx({to:a,chainId:x,value:"0",data:s.legs.length?F({abi:w,functionName:"multicall",args:[S]}):m,description:`Exit this wallet\u2019s Morpho V2 shares; estimated penalty ${s.penaltyAssets} ${o.symbol} base units. No approvals.`}),plan:s,penaltyShares:A,redeemShares:C,blockNumber:i.blockNumber}}var ce="In-kind exits transfer supported market positions rather than cash; use the project in_kind_exit tool.";function we(e,t,a,c,n=ce){return{name:t,inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:async(l,o)=>{try{if(L(o),Object.keys(l).length)throw new r("Vault details takes no arguments.");let i=e.clientFor(x);if(await i.getChainId()!==x)throw new r("Vault details requires chain 4663.");let d=await i.readContract({address:a,abi:D(["function asset() view returns (address)"]),functionName:"asset"});if(h(d)!==g(c.address))throw new r("The vault does not use the pinned underlying asset.");let u=await ae(i,a,c),[s,v,A,C]=await Promise.all(["performanceFee","managementFee","owner","curator"].map(m=>i.readContract({address:a,abi:w,functionName:m,blockNumber:u.blockNumber}))),S={...c,address:g(c.address)};return{vault:a,chainId:x,blockNumber:u.blockNumber.toString(),asset:S,owner:h(A),curator:h(C),idleAssets:u.idle.toString(),normalCapacityAssets:u.normalCapacity.toString(),markets:u.markets.map(m=>({marketId:m.id,adapter:m.adapter,suppliedAssets:m.supplied.toString(),marketLiquidityAssets:m.liquidity.toString(),capacityAssets:m.capacity.toString(),liquidityMarket:m.normal,penaltyWad:m.penalty.toString()})),fees:{performanceFeeWad:f(s).toString(),managementFeePerSecondWad:f(v).toString(),scale:N.toString()},apy:null,apyStatus:"This onchain snapshot does not include APY. Use the module analytics tool for indexed historical APY; maxRate is an accrual ceiling.",capacityCaveat:`Snapshot estimates; gates, price accrual, liquidity and penalties can change. Preview the exact action. Force exits may leave share rounding dust. ${n}`}}catch(i){throw new r(e.plainError(i))}}}}function be(e,t){return`Force-exit estimate: position ${e.requestedAssets} ${t} base units; penalty ${e.penaltyAssets}; net estimate ${e.requestedAssets-e.penaltyAssets}; effective penalty ${T(e.penaltyAssets*10000n,e.requestedAssets)} bps (rounded up). Penalty limit is a local preview check, not a calldata bound. Re-preview before signing and recheck positions for rounding dust.`}function ge(e,t,a,c,n){let l=(i,d)=>e.filter(u=>u.token.chainId===x&&u.token.address.toLowerCase()===i.toLowerCase()).reduce((u,s)=>{if(s.token.decimals!==d||!/^-?\d+$/.test(s.amount))throw new r("Invalid force-exit preview metadata.");return u+BigInt(s.amount)},0n),o=-l(t,18);if(o<=0n||o>a||l(g(n.address),n.decimals)<c)throw new r("The force-exit preview exceeds the share balance or returns less than minAmountOut.")}export{w as a,f as b,ye as c,ae as d,de as e,he as f,we as g,be as h,ge as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as P,b as S,c as b,f as N,g as y}from"./SK2VBNAU.js";import{c as v}from"./MYFAKCQI.js";import{a as M}from"./YHRUAQQK.js";import{e as c}from"./5KUWLUPM.js";import{a as m,i as x}from"./FWD4L3CJ.js";import{a as l}from"./XSD5NL7J.js";import{a as h}from"./JXOEJPJ4.js";import{getAddress as q,isAddress as F}from"viem";var E=`https://api-v2.pendle.finance/core/v1/${m}/markets?limit=100`,T=x[m].pendle.marketFactory.address;function f(e){if(e?.aborted)throw new l("The request was cancelled.")}var C=e=>typeof e=="number"&&Number.isFinite(e);function p(e){return typeof e=="string"&&F(e,{strict:!1})?q(e):void 0}function I(e){if(!c(e))return"a row was not an object";let t=p(e.address);if(!t)return"a row had no valid market address";let n=c(e.pt)?p(e.pt.address):void 0,r=c(e.yt)?p(e.yt.address):void 0,o=c(e.sy)?p(e.sy.address):void 0;if(!n||!r||!o)return`market ${t} had no valid PT, YT and SY addresses`;let i=typeof e.expiry=="string"?Date.parse(e.expiry):Number.NaN;if(!Number.isFinite(i)||i%1e3!==0||i<=0)return`market ${t} had no valid end date`;if(typeof e.isActive!="boolean")return`market ${t} had no active flag`;let a=c(e.pt)&&typeof e.pt.symbol=="string"?e.pt.symbol:typeof e.name=="string"?e.name:t,s=c(e.liquidity)&&C(e.liquidity.usd)&&e.liquidity.usd>=0?e.liquidity.usd:void 0;return{market:t,sy:o,pt:n,yt:r,expiry:i/1e3,active:e.isActive,label:h(a),source:"api",...C(e.impliedApy)?{impliedApy:e.impliedApy}:{},...s!==void 0?{liquidityUsd:s}:{}}}async function D(e,t={}){let n=await v(e,E,{method:"GET",headers:{"User-Agent":"oak-core/pendle",Accept:"application/json"},...t.signal?{signal:t.signal}:{}},i=>c(i)&&Array.isArray(i.results)),r=[],o=[];for(let i of n.results){let a=I(i);typeof a=="string"?o.push(a):r.push(a)}return{rows:r,dropped:o}}var L=10000000n,B=1000000n,W=52515580n,O=new WeakMap;async function U(e,t,n){f(n);let r=await e.getBlockNumber(),o=L;for(;t.next<=r;){f(n);let i=t.next,a=i+o-1n>r?r:i+o-1n;try{let s=await e.getLogs({address:T,event:S,fromBlock:i,toBlock:a});for(let u of s){let d=p(u.args.market);d&&t.found.add(d)}t.next=a+1n}catch{if(o<=B)throw new l("Oak can't list Pendle markets from the chain because the node refused the history request.");o/=2n}}return[...t.found]}function $(e,t={}){let n=O.get(e);n||(n={next:W,found:new Set,turn:Promise.resolve()},O.set(e,n));let r=n,o=r.turn.then(()=>U(e,r,t.signal));return r.turn=o.catch(()=>{}),o}async function _(e,t,n=Math.floor(Date.now()/1e3),r={}){f(r.signal);let o=await y(e,t.flatMap(s=>[{address:s,abi:b,functionName:"readTokens"},{address:s,abi:b,functionName:"expiry"}])),i=t.flatMap((s,u)=>{let d=o[u*2],k=o[u*2+1];if(!d.ok||!k.ok||!Array.isArray(d.value)||typeof k.value!="bigint")return[];let[w,g,A]=d.value.map(p),R=Number(k.value);return w&&g&&A&&Number.isSafeInteger(R)?[{market:s,sy:w,pt:g,yt:A,end:R}]:[]});f(r.signal);let a=await y(e,i.map(s=>({address:s.pt,abi:N,functionName:"symbol"})));return i.map((s,u)=>{let d=a[u];return{market:s.market,sy:s.sy,pt:s.pt,yt:s.yt,expiry:s.end,active:s.end>n,label:h(d.ok&&typeof d.value=="string"?d.value:s.market),source:"chain"}})}async function Y(e,t,n={}){return _(e,await $(e,n),t,n)}async function X(e,t,n){let[r]=await y(e,[{address:T,abi:P,functionName:"isValidMarket",args:[t]}]);if(!r.ok)throw new l("Oak couldn't read this Pendle market from the chain, so it won't use it.");if(r.value!==!0)throw new l("This isn't a market the Pendle factory created. Oak won't use this market.");let[o]=await _(e,[t],n);if(!o)throw new l("Oak couldn't read this Pendle market from the chain, so it won't use it.");return o}async function Z(e,t){f(t.signal);try{return{source:"api",...await D(e.http,t)}}catch(n){if(!t.allowChain||n instanceof M)throw n;return f(t.signal),{source:"chain",rows:await Y(e.clientFor(m),t.now,t),dropped:[]}}}export{E as a,f as b,D as c,W as d,$ as e,_ as f,Y as g,X as h,Z as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as H}from"./5ZLOCQA4.js";import{c as B,f as j,g as I,k as F,n as G}from"./5KUWLUPM.js";import{a as k,i as z}from"./FWD4L3CJ.js";import{a}from"./XSD5NL7J.js";import{encodeFunctionData as Q,erc20Abi as O,parseAbi as oe,zeroHash as J}from"viem";var ne=z[k].meridian,S=ne.PredictionMarketEscrow.address,M={address:ne.CollateralToken_USDe.address,chainId:k,symbol:"USDe",decimals:18},se="https://api.predict.meridian.xyz/graphql",ae="query GetOpenConditions($now: Int!, $first: Int!, $after: String, $search: String, $conditionIds: [Bytes!], $resolvers: [Address!]) { conditions(first: $first, after: $after, filter: { chainId: 4663, settled: false, public: true, endTime: { gte: $now }, search: $search, conditionIds: $conditionIds, resolvers: $resolvers }) { totalCount pageInfo { hasNextPage endCursor } nodes { conditionId resolver question shortName optionName endTime estimatedPrice openInterest similarMarketVolume24h marketType } } }",de="query GetHolderPositions($holder: Address!, $first: Int!, $after: String) { positions(first: $first, after: $after, filter: { holder: $holder, chainId: 4663 }, orderBy: { field: CREATED_AT, direction: DESC }) { totalCount pageInfo { hasNextPage endCursor } nodes { id chainId holder side balance tokenAddress: token pickConfigId userCollateral totalPayout prediction { predictionId } pickConfig { pickConfigId marketAddress: escrow resolved result } } } }",U=oe(["function getClaimableAmount(bytes32 pickConfigId, address positionToken, uint256 tokenAmount) view returns (uint256)","function settle(bytes32 predictionId, bytes32 refCode)","function redeem(address positionToken, uint256 amount, bytes32 refCode) returns (uint256)"]),K={type:"string",pattern:"^0x[0-9a-fA-F]{64}$"},V={type:"string",minLength:1,maxLength:4096,description:"Opaque nextCursor returned by the previous page."},E=25,W={type:"integer",minimum:1,maximum:E},ce=1e3;function Y(e,p){if(e===void 0)return p;if(!Number.isSafeInteger(e)||e<1||e>E)throw new a("Provide a Meridian page limit from 1 to 25.");return e}function Z(e){if(e===void 0)return;let p=()=>new a("Provide the opaque Meridian nextCursor returned by the previous page.");if(typeof e!="string"||e.length>4096||!/^[A-Za-z0-9+/_-]+={0,2}$/.test(e))throw p();try{let c=Buffer.from(e,"base64url");if(c.toString("base64url")!==e.replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_"))throw p();let m=C(JSON.parse(c.toString("utf8")));if(typeof m.k!="string"||!m.k||typeof m.id!="string"||!m.id)throw p()}catch{throw p()}return e}function X(e,p,c,m=!1){let l=C(e),f=C(l.pageInfo),P=Array.isArray(l.nodes)?l.nodes.filter(q=>!m||N(C(q).balance)!=="0").length:0;if(!Array.isArray(l.nodes)||l.nodes.length>p||!Number.isSafeInteger(l.totalCount)||l.totalCount<P||typeof f.hasNextPage!="boolean"||c===void 0&&!f.hasNextPage&&l.totalCount>l.nodes.length||f.endCursor!==null&&(typeof f.endCursor!="string"||!f.endCursor.trim()||f.endCursor.length>4096)||f.hasNextPage&&(l.nodes.length===0||f.endCursor===null||f.endCursor===c))throw new a("Meridian returned invalid pagination; retry the scan from the first page.");return{nodes:l.nodes,totalCount:l.totalCount,nextCursor:f.hasNextPage?f.endCursor:null,complete:!f.hasNextPage&&c===void 0}}function C(e){return j(e,"Meridian returned an unexpected response.")}function A(e){if(typeof e!="string"||!e.trim())throw new a("Meridian returned an invalid text field.");return e}function b(e){return F(e,"Provide a valid Meridian contract or wallet address.")}function v(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new a("Provide a valid Meridian prediction or pick configuration ID.");return e}function R(e){return G(e,"Meridian amount exceeds the uint256 range.",{notString:"Meridian amounts must be integer strings in base units."}).toString()}function N(e){return e===0?"0":R(e)}function D(e){if(typeof e!="bigint"||e<0n)throw new a("Meridian returned an invalid on-chain amount.");return R(e.toString())}function ue(e,p){return e.chainId===p.chainId&&I(e.address,p.address)}function ee(e,p){let c=C(e),m=C(c.pickConfig),l=b(c.holder),f=b(m.marketAddress);if(c.chainId!==k||!I(l,p))throw new a("Meridian returned a position for a different wallet or chain.");if(!I(f,S))throw new a("This Meridian position uses an unsupported escrow contract.");if(typeof m.resolved!="boolean"||m.result!==null&&typeof m.result!="string")throw new a("Meridian returned an invalid resolution.");let P=v(c.pickConfigId);if(!I(v(m.pickConfigId),P))throw new a("Meridian returned mismatched pick configuration IDs.");if(c.side!=="PREDICTOR"&&c.side!=="COUNTERPARTY")throw new a("Meridian returned an invalid position side.");return{id:A(c.id),chainId:k,holder:l,side:c.side,balance:N(c.balance),tokenAddress:b(c.tokenAddress),pickConfigId:P,userCollateral:N(c.userCollateral),totalPayout:N(c.totalPayout),prediction:{predictionId:v(C(c.prediction).predictionId)},pickConfig:{pickConfigId:P,marketAddress:f,resolved:m.resolved,result:m.result}}}var le=e=>{async function p(t){try{return await t()}catch(o){throw new a(e.plainError(o))}}async function c(){let t=e.clientFor(k);if(await t.getChainId()!==k)throw new a("Meridian requires an RPC on chain 4663.");return t}async function m(t,o,r){let s=new URL(se);s.searchParams.set("op",t),s.searchParams.set("query",o),s.searchParams.set("variables",JSON.stringify(r));let n=await e.http(s.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!n.ok)throw new a(`Meridian returned HTTP ${n.status}. Please try again.`);let u;try{u=await n.json()}catch{throw new a("Meridian returned malformed JSON.")}let d=C(u);if(d.errors!==void 0&&(!Array.isArray(d.errors)||d.errors.length>0))throw new a("Meridian could not complete the GraphQL query. Please try again.");return C(d.data)}async function l(t,o=10,r){b(t);let s=await m("GetHolderPositions",de,{holder:t,first:o,...r===void 0?{}:{after:r}});return X(s.positions,o,r,!0)}async function f(t,o){let r=[],s=new Set,n=new Set,u,d,h=0;for(let g=0;g<ce;g++){let w=await l(t,E,u);if(d!==void 0&&d!==w.totalCount)throw new a("Meridian positions changed during pagination; retry from the first page.");d=w.totalCount;for(let x of w.nodes){let i=C(x),y=A(i.id);if(n.has(y))throw new a("Meridian repeated a position during pagination; retry from the first page.");n.add(y),N(i.balance)!=="0"&&h++,(o===void 0||I(b(i.tokenAddress),o))&&r.push(ee(x,t))}if(w.nextCursor===null){if(h>d||n.size<d)throw new a("Meridian returned an incomplete positions scan; retry from the first page.");return r}if(s.has(w.nextCursor))throw new a("Meridian repeated a cursor; retry from the first page.");s.add(w.nextCursor),u=w.nextCursor}throw new a("Meridian positions scan exceeded 1000 pages. Use meridian_positions with limit and cursor to inspect pages; redeem a known settled positionToken directly.")}async function P(t,o){if(t.length===0)return[];let r=await c();return(await Promise.all(t.map(async n=>{let[u,d,h]=await Promise.all([r.readContract({address:n.tokenAddress,abi:O,functionName:"balanceOf",args:[o]}),r.readContract({address:n.tokenAddress,abi:O,functionName:"decimals"}),r.readContract({address:n.tokenAddress,abi:O,functionName:"symbol"})]);if(!Number.isInteger(d)||d<0||d>255)throw new a("Meridian returned invalid position token decimals.");let g={address:n.tokenAddress,chainId:k,decimals:d,symbol:A(h)},w=D(u),x=n.pickConfig.resolved?{token:{...M},amount:D(await r.readContract({address:S,abi:U,functionName:"getClaimableAmount",args:[n.pickConfigId,n.tokenAddress,BigInt(w)]}))}:null;return{module:"meridian",id:n.id,chainId:k,assets:[{token:g,amount:w}],description:`Meridian ${n.side.toLowerCase()} position; ${n.pickConfig.resolved?n.pickConfig.result??"resolved":"unresolved"}.`,holder:n.holder,side:n.side,pickConfigId:n.pickConfigId,prediction:n.prediction,pickConfig:n.pickConfig,userCollateral:{token:{...M},amount:n.userCollateral},totalPayout:{token:{...M},amount:n.totalPayout},claimable:x}}))).filter(n=>BigInt(n.assets[0].amount)>0n)}async function q(t){return P(await f(t),t)}function _(t){return e.unsignedTx({to:S,chainId:k,value:"0",data:Q({abi:U,functionName:"settle",args:[t,J]}),description:`Settle Meridian prediction ${t}.`})}function L(t,o,r){let s=o.changes.map(n=>{let u=n.amount.startsWith("-"),d=e.formatAmount(u?n.amount.slice(1):n.amount,n.token.decimals);return`${u?"-":"+"}${d} ${n.token.symbol} (${n.token.address}, chain ${n.token.chainId})`});return{txs:t,preview:o,summary:`${r} ${o.summary}${s.length?` Changes: ${s.join("; ")}.`:""}`}}async function te(t){let o=Y(t.limit,20),r=Z(t.cursor);if(r!==void 0&&t.asOf===void 0)throw new a("Pass the previous Meridian browse asOf with cursor to keep the same time filter.");let s=t.asOf===void 0?Math.floor(Date.now()/1e3):Number(R(t.asOf));if(!Number.isSafeInteger(s)||s<0||s>2147483647)throw new a("Provide Meridian asOf as Unix seconds within the GraphQL Int range.");let n;if(t.search!==void 0&&(n=A(t.search).trim(),n.length>500))throw new a("Keep the Meridian market search to 500 characters.");let u=t.conditionId===void 0?void 0:v(t.conditionId),d=t.resolver===void 0?void 0:b(t.resolver),h=await m("GetOpenConditions",ae,{now:s,first:o,...r===void 0?{}:{after:r},...n===void 0?{}:{search:n},...u===void 0?{}:{conditionIds:[u]},...d===void 0?{}:{resolvers:[d]}}),g=X(h.conditions,o,r),w=g.nodes.map(x=>{let i=C(x);if(!Number.isSafeInteger(i.endTime)||i.endTime<0||i.estimatedPrice!==null&&(typeof i.estimatedPrice!="number"||!Number.isFinite(i.estimatedPrice)||i.estimatedPrice<0||i.estimatedPrice>1))throw new a("Meridian returned invalid market pricing or time.");let y=v(i.conditionId),T=b(i.resolver);if(u!==void 0&&!I(y,u)||d!==void 0&&!I(T,d))throw new a("Meridian returned a different condition or resolver than requested.");return{conditionId:y,resolver:T,question:A(i.question),shortName:i.shortName===null?null:A(i.shortName),optionName:i.optionName===null?null:A(i.optionName),endTime:String(i.endTime),estimatedPrice:i.estimatedPrice===null?null:String(i.estimatedPrice),marketType:i.marketType===null?null:A(i.marketType)}});return{chainId:k,collateral:{...M},totalCount:g.totalCount,markets:w,limit:o,nextCursor:g.nextCursor,complete:g.complete,asOf:String(s)}}async function ie(t,o){let r=b(t.positionToken),s=R(t.amount);if(BigInt(s)===0n)throw new a("Provide a positive Meridian redemption amount.");let n=await c(),u=D(await n.readContract({address:r,abi:O,functionName:"balanceOf",args:[o]}));if(BigInt(s)>BigInt(u))throw new a("The redemption amount exceeds the wallet position balance.");let d=e.unsignedTx({to:S,chainId:k,value:"0",data:Q({abi:U,functionName:"redeem",args:[r,BigInt(s),J]}),description:`Redeem ${s} Meridian position base units for USDe.`}),h=[d],g;try{g=await e.preview(h,o)}catch(i){if(!/\breverted\b/i.test(e.plainError(i)))throw i;let y=await f(o,r);if(y.length!==1)throw new a("Direct Meridian redemption reverted and no unique indexed prediction was found for this token. Retry indexing or use meridian_settle with the known predictionId first.");let T=y[0];if(T.pickConfig.resolved){let re=D(await n.readContract({address:S,abi:U,functionName:"getClaimableAmount",args:[T.pickConfigId,r,BigInt(s)]}));if(BigInt(re)===0n)throw i}h=[_(T.prediction.predictionId),d],g=await e.preview(h,o)}let w=g.changes.filter(i=>ue(i.token,M)&&i.token.decimals===M.decimals).reduce((i,y)=>i+BigInt(y.amount),0n),x=g.changes.filter(i=>i.token.chainId===k&&I(i.token.address,r)).reduce((i,y)=>i+BigInt(y.amount),0n);if(w<=0n||x!==-BigInt(s))throw new a("Meridian preview did not show the requested position burn and a positive USDe payout.");return L(h,g,h.length===2?"Settle the prediction, then redeem for USDe. Unsigned transactions only.":"Redeem the position for USDe. Unsigned transaction only.")}function $(t,o,r,s,n){return{name:t,inputSchema:{type:"object",properties:o,required:r,additionalProperties:!1,description:s},execute:(u,d)=>p(async()=>{if(C(u),b(d),Object.keys(u).some(h=>!Object.hasOwn(o,h))||r.some(h=>u[h]===void 0))throw new a("Provide only the required Meridian tool inputs.");return n(u,d)})}}return{tools:[$("meridian_browse",{search:{type:"string",minLength:1,maxLength:500},cursor:V,limit:W,conditionId:K,resolver:B,asOf:H("Reuse the returned Unix seconds with cursor.")},[],"Search open Meridian conditions or look up a conditionId/resolver. Follow nextCursor with the same filters and asOf.",te),$("meridian_positions",{cursor:V,limit:W},[],"Page through indexed Meridian positions with on-chain balances and claimability. Follow nextCursor until null; indexing can lag transfers.",async(t,o)=>{let r=Y(t.limit,10),s=Z(t.cursor),n=await l(o,r,s);return{positions:await P(n.nodes.map(u=>ee(u,o)),o),totalCount:n.totalCount,limit:r,nextCursor:n.nextCursor,complete:n.complete,scope:"Indexed positions with current on-chain balances. Index totalCount may exclude zero-balance rows. Indexing can lag transfers; redeem known settled tokens directly."}}),$("meridian_settle",{predictionId:K},["predictionId"],"Preview an unsigned unilateral settlement; unresolved or already settled predictions may revert.",async(t,o)=>{let r=_(v(t.predictionId));await c();let s=[r];return L(s,await e.preview(s,o),"Settle the Meridian prediction. Unsigned transaction only.")}),$("meridian_redeem",{positionToken:B,amount:H("Position token amount in base units.")},["positionToken","amount"],"Preview redemption of a known position token directly; scan all indexed pages for settlement first if required. No approval or typed signature.",ie)],positions:t=>p(()=>q(t))}},we=le;export{le as a,we as b};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ae}from"./3CCBUYUM.js";import{a as bt,d as wt,e as ht}from"./AJP5LDM2.js";import{a as Ne}from"./7MR37STI.js";import{a as We,b as Be,d as pt}from"./AMICUXS6.js";import{b as ut,c as mt,d as ft}from"./JPOYTTTW.js";import{d as ct,e as te}from"./5O5ZE3ZV.js";import{a as dt}from"./CY75R4FK.js";import{b as lt}from"./AXYOJBX6.js";import{a as q}from"./6IM6A5VA.js";import{a as A,d as z}from"./UWOFA6GV.js";import{d as De,g as E,i as Ue}from"./73N3TOJL.js";import{a as Me}from"./RETS2ZEK.js";import{j as it}from"./CXLEQCP3.js";import{a as p,i as V}from"./G6HCV67X.js";import{a as i,d as se}from"./5YS5V2LK.js";import{a as ze}from"./JXOEJPJ4.js";import{encodeFunctionData as me,erc20Abi as Ha,getAddress as Kt,parseAbi as st,zeroAddress as qa}from"viem";import{decodeAbiParameters as aa,encodeFunctionData as oa,getAddress as ie,parseAbiParameters as ra,zeroAddress as fe,zeroHash as It}from"viem";import{decodeAbiParameters as Xt,encodeFunctionData as Yt,erc20Abi as Jt,getAddress as St,parseAbi as Zt,parseAbiParameters as ea,zeroHash as kt}from"viem";var Ke=St("0xCE29862924756584BBD0D75CA1249d22007E2813"),At="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",ta="(uint256 value,uint256 nonce,uint256 deadline,uint8 v,bytes32 r,bytes32 s)",yt=Zt(["function BLUE() view returns (address)",`function vaultExitBundlesV1InKindRedemptionVaultV2(address vault,address adapter,${At}[] marketParamsList,uint256 exitAssets,${ta} sharesPermit,uint256 deadline)`]);function N(e,t=!1){if(typeof e!="string"||!/^\d{1,78}$/.test(e)||BigInt(e)>=1n<<256n||!t&&BigInt(e)===0n)throw new i("Provide a positive uint256 decimal base-unit string.");return BigInt(e)}var gt=(e,t)=>e<t?e:t;async function Za(e,t,s,r,n){q(n);let l=N(r.amount),a=N(r.maxShares),o=N(r.maxPenaltyAssets,!0),u=N(r.deadline),d=e.clientFor(p),m=await pt(d,t,s),c=(S,B,Te,ee=[])=>d.readContract({address:S,abi:B,functionName:Te,args:ee,blockNumber:m.blockNumber}),[f,b,w,h]=await Promise.all([d.getBlock({blockNumber:m.blockNumber}),c(Ke,yt,"BLUE"),c(t,Jt,"balanceOf",[n]),c(t,We,"previewRedeem",[a])]);if(typeof b!="string"||St(b)!==U)throw new i("VaultExitBundlesV1 does not report the pinned Morpho Blue.");if(u<f.timestamp||u>f.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");if(a>Be(w))throw new i("maxShares exceeds the wallet share balance.");let y=gt(m.idle,l),k=m.markets.filter(S=>S.supplied>0n&&W(S.id)),g=l-y,T=k[0]?.penalty??0n,I=g*10n**18n/(10n**18n+T);if(g>0n&&I===0n)throw new i("The penalty-adjusted in-kind amount rounds to zero.");let M=[];for(let S of k){if(I===0n)break;let B=gt(S.supplied,I);M.push({marketId:S.id,assets:B,penalty:(B*S.penalty+10n**18n-1n)/10n**18n}),I-=B}if(I>0n)throw new i("The supported adapter positions cannot cover the requested in-kind exit. Reduce the amount; unverified market positions are not transferred.");if(l+BigInt(M.length)>Be(h))throw new i("maxShares cannot cover the exit and per-market rounding buffer.");if(M.some(S=>S.assets>m.blueCash))throw new i("Morpho Blue cannot fund the largest in-kind callback. Reduce the amount.");let C=M.reduce((S,B)=>S+B.penalty,0n);if(C>o)throw new i("In-kind penalty exceeds maxPenaltyAssets.");let v=[...y?[y]:[],...M.flatMap(S=>[S.assets,S.penalty].filter(B=>B>0n))],G=(await Promise.all(v.map(S=>c(t,We,"previewWithdraw",[S])))).reduce((S,B)=>S+Be(B),0n);if(G===0n||G>a)throw new i("Separately rounded burns exceed maxShares.");let Z=M.map(S=>Xt(ea(At),m.markets.find(B=>B.id===S.marketId).data)[0]),H=m.markets[0]?.adapter;if(!H)throw new i("In-kind exit requires a verified market adapter.");let F=`In-kind exit from ${t}: spend at most ${G} share base units; receive ${y} ${s.symbol} base units and Morpho Blue supply positions ${M.map(S=>`${S.marketId}: ${S.assets} ${s.symbol} base units`).join(", ")||"none"}. Penalty ${C} ${s.symbol} base units. Deadline ${u} (Unix seconds). Supply positions remain exposed to borrower default and can only be withdrawn when market liquidity returns. This is not a cash exit. The exact share allowance bounds drift; accrual can require a fresh preview.`,P=Yt({abi:yt,functionName:"vaultExitBundlesV1InKindRedemptionVaultV2",args:[t,H,Z,l,{value:0n,nonce:0n,deadline:0n,v:0,r:kt,s:kt},u]}),D=[e.approval(t,Ke,G.toString(),p),e.unsignedTx({to:Ke,data:P,value:"0",chainId:p,description:F})],$=await e.preview(D,n),j=-$.changes.filter(S=>S.token.chainId===p&&E(S.token.address,t)).reduce((S,B)=>{if(B.token.decimals!==18||!/^-?\d+$/.test(B.amount))throw new i("Invalid in-kind share preview.");return S+BigInt(B.amount)},0n);if(j<=0n||j>G)throw new i("In-kind preview exceeds the exact share authorization or burns no shares.");return{txs:D,preview:$,summary:F,receipt:{idleAssets:y.toString(),positions:M.map(S=>({marketId:S.marketId,asset:s,assets:S.assets.toString()})),penaltyAssets:C.toString()}}}var pe=ie("0x53A1eB6589861F686af7c531211E35Aefe30210f"),xt=["supply","withdraw","supplyCollateralAndBorrow","repayAndWithdrawCollateral","migrateBorrowPosition"],Qe={kind:0,data:"0x"},Oe={nonce:0n,deadline:0n,signature:{v:0,r:It,s:It}},na=ra("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),Tt=e=>({tools:[{name:"morpho_bundle",inputSchema:{type:"object",additionalProperties:!1,required:["operation","marketId","deadline"],properties:{operation:{type:"string",enum:xt},marketId:{type:"string"},destinationMarketId:{type:"string"},assets:A(),collateralAssets:A(),shares:A(),maxRepayAssets:A(),maxLtv:A(),deadline:A(),allocations:{type:"array",maxItems:4,items:{type:"object",additionalProperties:!1,required:["vault","assets","maxPenaltyAssets"],properties:{vault:{type:"string"},sourceMarketId:{type:"string"},assets:A(),maxPenaltyAssets:A()}}}}},execute:async(t,s)=>{try{q(s);let r=t.operation,n=e.clientFor(p);if(await n.getChainId()!==p||typeof r!="string"||!xt.includes(r))throw new i("Choose a supported Blue bundle on chain 4663.");let l=["operation","marketId","deadline",...r==="supply"?["assets"]:r==="withdraw"?["assets","shares","allocations"]:r==="supplyCollateralAndBorrow"?["collateralAssets","assets","maxLtv","allocations"]:r==="repayAndWithdrawCollateral"?["assets","shares","maxRepayAssets","collateralAssets","maxLtv"]:["destinationMarketId","maxLtv","allocations"]];if(Object.keys(t).some(P=>!l.includes(P)))throw new i("Unexpected argument for this Blue bundle.");let a=await n.getBlock(),o=N(t.deadline);if(o<a.timestamp||o>a.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");let[u,d]=await Promise.all([n.readContract({address:pe,abi:Ne,functionName:"BLUE",blockNumber:a.number}),n.readContract({address:pe,abi:Ne,functionName:"PUBLIC_ALLOCATOR",blockNumber:a.number})]);if(ie(u)!==U||ie(d)!==bt)throw new i("BlueBundlesV1 deployment does not match Oak\u2019s pinned Blue and Public Allocator.");let m=async P=>{if(typeof P!="string"||!W(P))throw new i("Choose a verified Morpho market with a supported exit.");let D=await n.readContract({address:U,abi:O,functionName:"idToMarketParams",args:[P],blockNumber:a.number}),$={loanToken:ie(D[0]),collateralToken:ie(D[1]),oracle:ie(D[2]),irm:ie(D[3]),lltv:D[4]};if(!E(be({...$,lltv:String($.lltv)}),P))throw new i("Blue bundle market identity mismatch.");return $},c=await m(t.marketId),f=r==="migrateBorrowPosition"?await m(t.destinationMarketId):c;if(c.loanToken!==f.loanToken||c.collateralToken!==f.collateralToken)throw new i("Migration requires the same loan and collateral tokens.");if(r==="migrateBorrowPosition"&&t.marketId===t.destinationMarketId)throw new i("Choose a different destination market.");if(r!=="supply"&&!await n.readContract({address:U,abi:O,functionName:"isAuthorized",args:[s,pe],blockNumber:a.number}))throw new i(`Authorize the pinned Blue bundle explicitly with morpho_manage setAuthorization account ${pe}, enabled true, then retry. That authority covers all Blue positions. Revoke it with enabled false after the bundle.`);let b=t.assets===void 0?0n:N(t.assets,!0),w=t.shares===void 0?0n:N(t.shares,!0),h=t.collateralAssets===void 0?0n:N(t.collateralAssets,!0),y=r==="supply"||r==="withdraw"?0n:N(t.maxLtv,!0);if(y>f.lltv)throw new i("maxLtv cannot exceed the verified destination market LLTV.");if(r==="supply"&&b===0n||r==="withdraw"&&b===0n==(w===0n)||r==="supplyCollateralAndBorrow"&&h===0n&&b===0n||r==="repayAndWithdrawCollateral"&&(b>0n&&w>0n||b===0n&&w===0n&&h===0n))throw new i("Choose a nonzero amount; assets and shares are mutually exclusive for repayment/withdrawal.");let k=t.allocations??[];if(!Array.isArray(k)||k.length>4||k.length&&r==="supplyCollateralAndBorrow"&&b===0n)throw new i("Provide at most four explicit allocations, only with a borrow or withdrawal.");let g=new Set,T=[],I=0n;for(let P of k){if(!P||typeof P!="object"||Array.isArray(P)||Object.keys(P).some(Ve=>!["vault","sourceMarketId","assets","maxPenaltyAssets"].includes(Ve)))throw new i("Unsupported bundled allocation input.");let D=P,$=await wt(e,{vault:D.vault,marketId:r==="migrateBorrowPosition"?t.destinationMarketId:t.marketId});if(g.has($.definition.vault.toLowerCase()))throw new i("Use each source vault at most once per bundle.");g.add($.definition.vault.toLowerCase());let j=N(D.assets),S=N(D.maxPenaltyAssets,!0);if(!$.permission||j>=1n<<128n||j>$.headroom||$.penalty>10n**18n||$.asset.address!==f.loanToken)throw new i("Bundled allocation is disabled, unqualified or exceeds target capacity.");let B=(j*$.penalty+10n**18n-1n)/10n**18n;if(B>S)throw new i("Bundled allocation exceeds maxPenaltyAssets.");I+=B;let Te=D.sourceMarketId===void 0,ee=Te?void 0:$.sources.find(Ve=>E(Ve.id,String(D.sourceMarketId)));if(Te?!$.canIdle||j>$.data.idle:!ee||!ee.canPull||j>ee.capacity||j>$.data.blueCash)throw new i("Bundled allocation source cannot cover the requested amount.");T.push({vault:$.definition.vault,adapter:$.target.adapter,marketParams:$.params,sourceAdapter:ee?.adapter??fe,sourceMarketParams:ee?aa(na,ee.data)[0]:$.params,assets:j,penalty:$.penalty,fromIdle:Te})}let M,C,v,x=0n;if(r==="supply")M="blueBundlesV1Supply",v=c.loanToken,x=b,C=[c,b,Qe,0n,fe,o];else if(r==="withdraw")M="blueBundlesV1Withdraw",C=[c,b,w,Oe,T,0n,fe,o];else if(r==="supplyCollateralAndBorrow"){if(M="blueBundlesV1SupplyCollateralAndBorrow",v=c.collateralToken,x=h,I>=b&&I>0n)throw new i("Allocation penalties would consume the borrow proceeds.");C=[c,h,b,y,Qe,Oe,T,0n,fe,o]}else if(r==="repayAndWithdrawCollateral"){if(M="blueBundlesV1RepayAndWithdrawCollateral",v=c.loanToken,x=N(t.maxRepayAssets,!0),b>x||w>0n&&x===0n)throw new i("Repayment requires a sufficient maxRepayAssets budget.");C=[c,b,w,x,h,y,Qe,Oe,0n,fe,o]}else M="blueBundlesV1MigrateBorrowPosition",C=[c,f,y,Oe,T,0n,fe,o];let G=`Morpho Blue atomic ${r}: ${JSON.stringify(t)}. Allocation penalties ${I} loan-token base units; zero referral fee. Max LTV ${y}; absolute deadline ${o}. Migration adds allocation penalties to destination debt; borrowing deducts them from proceeds. Exact input approval ${x}. Existing Blue bundle authorization remains until explicitly revoked with morpho_manage. No opaque callback, permit or signature is accepted.`,Z=[...v&&x?[e.approval(v,pe,x.toString(),p)]:[],e.unsignedTx({to:pe,data:oa({abi:Ne,functionName:M,args:C}),value:"0",chainId:p,description:G})],H=await e.preview(Z,s),F=new Map;for(let P of H.changes)if(BigInt(P.amount)<0n){let D=P.token.address.toLowerCase();F.set(D,(F.get(D)??0n)-BigInt(P.amount))}if([...F].some(([P,D])=>!v||P!==v.toLowerCase()||D>x))throw new i("Bundle preview spends outside the exact input budget.");return{txs:Z,preview:H,summary:G}}catch(r){throw new i(e.plainError(r))}}}]});import{concatHex as Mt,decodeAbiParameters as sa,encodeAbiParameters as $t,encodeFunctionData as Xe,erc20Abi as Pt,getAddress as K,keccak256 as Je,zeroAddress as we,zeroHash as ia}from"viem";var Y=K("0x6120765Ba5336150BbdDdD0Cd9108B5bFD369632"),la=["0x90B800999e4ACd1bD20283BD450bBd2e06D91F7C","0x708d6Bf6F847202a0755bb5636bE663B174242ea"].map(e=>K(e)),Ze=ae.find(e=>e.name==="take"),vt=[Ze.inputs[0]],da=[Ze.inputs[0].components[0]];function Ct(e){let t=Je(Mt(["0x600b380380600b5f395ff3",$t(da,[e])]));return Je(Mt(["0xff",e.midnight,ia,t]))}var le=10n**18n,Lt=(e,t)=>(e+(t-1n)/2n)/t;function Dt(e){if(e<0n)return 10n**36n/Dt(-e);let t=693147180559945309n,s=(e+322611214989459870n)/t,r=e-s*t,n=r*r/(2n*le),l=n*r/(3n*le);return le+r+n+l<<s}function ca(e){if(e<0n||e>6744n)throw new i("Midnight tick is outside 0..6744.");return Lt(Lt(10n**36n,le+Dt(4987541511039073n*(3372n-e))),10n**11n)*10n**11n}function Ge(e,t){if(typeof e!="string"||!/^0x([0-9a-f]{2})*$/i.test(e)||e.length>32770||t!==void 0&&e.length!==2+t*2)throw new i("Provide bounded canonical hex data.");return e}function Ye(e,t){if(!Array.isArray(e)||e.length!==t)throw new i("Invalid Midnight state tuple.");return e.map(s=>{if(typeof s=="number"&&Number.isSafeInteger(s)&&s>=0)return BigInt(s);if(typeof s=="bigint"&&s>=0n)return s;throw new i("Invalid Midnight integer state.")})}var ua=e=>JSON.parse(JSON.stringify(e,(t,s)=>typeof s=="bigint"?s.toString():s)),Ut=e=>{async function t(n,l){let a=Ge(n,32),o=e.clientFor(p);if(await o.getChainId()!==p)throw new i("Midnight requires chain 4663.");let u=await o.getBlock(),d=(k,g=[])=>o.readContract({address:Y,abi:ae,functionName:k,args:g,blockNumber:u.number}),m=await d("toMarket",[a]);if(m.chainId!==BigInt(p)||K(m.midnight)!==Y||!E(Ct(m),a))throw new i("Midnight market identity does not match the pinned chain and contract.");if(![V[p].tokens.USDG.address,V[p].tokens.WETH.address].some(k=>E(k,m.loanToken)))throw new i("This Midnight loan token needs a qualified transfer and exit fixture.");if(!m.collateralParams.length||m.collateralParams.length>128)throw new i("Invalid Midnight collateral inventory.");let[f,b,w,h]=await Promise.all([d("position",[a,l]),d("updatePositionView",[m,a,l]),d("marketState",[a]),d("isHealthy",[m,a,l])]),y=async k=>{let[g,T]=await Promise.all([o.readContract({address:k,abi:Pt,functionName:"decimals",blockNumber:u.number}),o.readContract({address:k,abi:Pt,functionName:"symbol",blockNumber:u.number})]);if(!Number.isInteger(g)||g>36||typeof T!="string")throw new i("Invalid Midnight token metadata.");return{address:K(k),decimals:g,symbol:T.replace(/[^a-zA-Z0-9.$_-]/g,"").slice(0,32),chainId:p}};return{id:a,rpc:o,block:u,market:m,read:d,token:y,loan:await y(m.loanToken),position:Ye(f,6),updated:Ye(b,3),state:Ye(w,13),healthy:h}}let s=(n,l,a,o)=>({name:n,inputSchema:{type:"object",properties:l,required:a,additionalProperties:!1},execute:async(u,d)=>{try{if(q(d),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Midnight argument.");return await o(u,d)}catch(m){throw new i(e.plainError(m))}}});async function r(n,l,a){return{txs:n,preview:await e.preview(n,l),summary:a}}return{tools:[s("morpho_midnight_status",{marketId:{type:"string"}},["marketId"],async(n,l)=>{let a=await t(n.marketId,l),o=await Promise.all(a.market.collateralParams.map(async(m,c)=>({token:await a.token(m.token),lltvWad:m.lltv.toString(),oracle:m.oracle,assets:String(await a.read("collateral",[a.id,l,BigInt(c)]))}))),u=["configurator","feeSetter","feeClaimer","tickSpacingSetter"],d=await Promise.all(u.map(m=>a.read(m)));return{protocol:Object.fromEntries(u.map((m,c)=>[m,K(String(d[c]))])),continuousFeePerSecondWad:String(a.state[11]),tickSpacing:String(a.state[12]),settlementFeeCbps:a.state.slice(4,11).map(String),settlementFeeCbpWadScale:"1000000000000",chainId:p,midnight:Y,marketId:a.id,blockNumber:String(a.block.number),market:ua(a.market),loanToken:a.loan,collaterals:o,debtUnits:String(a.position[4]),creditUnits:String(a.updated[0]),pendingFeeUnits:String(a.updated[1]),withdrawableUnits:String(a.state[2]),healthy:a.healthy,maturity:String(a.market.maturity),matured:a.block.timestamp>a.market.maturity,warning:"Maturity does not guarantee lender liquidity. Borrowers become liquidatable after maturity even when collateralized. Lender credit may absorb borrower default losses."}}),s("morpho_midnight_take",{offer:{type:"string",description:"ABI-encoded Offer struct, never transaction calldata."},ratifierData:{type:"string"},units:A(),maxAssets:A(),minAssets:A()},["offer","ratifierData","units","maxAssets","minAssets"],async(n,l)=>{let a=Ge(n.offer),[o]=sa(vt,a);if(!E($t(vt,[o]),a))throw new i("Offer encoding is not canonical.");let u=await t(Ct(o.market),l),d=N(n.units),m=N(n.maxAssets,!0),c=N(n.minAssets,!0),f=Ge(n.ratifierData);if(d>=1n<<128n||E(o.maker,l)||o.callback!==we||o.callbackData!=="0x"||!la.includes(K(o.ratifier)))throw new i("Use a non-self offer with a pinned ratifier and no maker callbacks. Callback routes need a separate qualified builder.");if(u.block.timestamp<o.start||u.block.timestamp>o.expiry||o.expiry<o.start)throw new i("The Midnight offer is not currently live.");if(o.buy&&o.receiverIfMakerIsSeller!==we||!o.buy&&o.receiverIfMakerIsSeller===we)throw new i("Invalid offer seller receiver.");if(o.buy&&u.block.timestamp>u.market.maturity&&d>u.updated[0])throw new i("Post-maturity sales cannot increase this wallet\u2019s debt.");let b=await u.read("settlementFee",[u.id,u.market.maturity>u.block.timestamp?u.market.maturity-u.block.timestamp:0n]),w=ca(o.tick);if(b>w&&o.buy)throw new i("Settlement fee exceeds the offer price.");let h=o.buy?w-b:w,y=h+b,k=P=>o.buy?P/le:(P+le-1n)/le,g=k(d*y),T=k(d*h);if(o.buy?T<c||T===0n:g>m||g===0n)throw new i("Midnight proceeds/spend do not fit the requested bounds.");let I=await u.read("consumed",[o.maker,o.group]);if(o.maxAssets===0n==(o.maxUnits===0n)||I+(o.maxAssets?o.buy?g:T:d)>(o.maxAssets||o.maxUnits))throw new i("Midnight offer capacity is exhausted or invalid.");if(u.state[11]>o.continuousFeeCap||o.tick%u.state[12]!==0n)throw new i("Offer fee cap or market tick spacing no longer permits execution.");let M=await u.read("isAuthorized",[o.maker,o.ratifier]),C=[{type:"function",name:"isRatified",stateMutability:"view",inputs:[Ze.inputs[0],{type:"bytes"},{type:"address"}],outputs:[{type:"bytes32"}]}],v=await u.rpc.readContract({address:o.ratifier,abi:C,functionName:"isRatified",args:[o,f,l],blockNumber:u.block.number});if(M!==!0||v!==Je(new TextEncoder().encode("morpho.midnight.callbackSuccess")))throw new i("The maker has not authorized and ratified this exact offer.");let x=Xe({abi:ae,functionName:"take",args:[o,f,d,l,o.buy?l:we,we,"0x"]}),G=`Midnight ${o.buy?"sell credit or borrow":"buy credit or reduce debt"}: ${d} fixed debt units; ${o.buy?`receive ${T}`:`spend ${g}`} ${u.loan.symbol} base units (token ${u.loan.address}, decimals ${u.loan.decimals}). Maturity ${u.market.maturity} Unix seconds; offer expiry ${o.expiry}. A borrower can lose collateral after maturity; lender withdrawal depends on repayments and bears default losses. No lender signature or callback is created. Bounds are rechecked locally; the take calldata fixes the offer and units. Exact buyer approval caps wallet spending.`,Z=[...o.buy?[]:[e.approval(u.loan.address,Y,g.toString(),p)],e.unsignedTx({to:Y,data:x,value:"0",chainId:p,description:G})],H=await r(Z,l,G),F=H.preview.changes.filter(P=>P.token.chainId===p&&E(P.token.address,u.loan.address)).reduce((P,D)=>P+BigInt(D.amount),0n);if(o.buy?F<T:F!==-g)throw new i("Midnight preview does not match the exact quoted cash flow.");return H}),s("morpho_midnight_action",{marketId:{type:"string"},operation:{enum:["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"]},amount:A(),collateralIndex:{type:"integer",minimum:0,maximum:127}},["marketId","operation"],async(n,l)=>{let a=await t(n.marketId,l),o=n.operation;if(!["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"].includes(String(o)))throw new i("Choose a finite Midnight position operation.");let u,d,m=a.loan,c=0n;if(o==="updatePosition"){if(n.amount!==void 0||n.collateralIndex!==void 0)throw new i("Position update takes no amount or collateral index.");u=[a.market,l]}else if(o==="claimContinuousFee"){if(c=N(n.amount),n.collateralIndex!==void 0||K(String(await a.read("feeClaimer")))!==K(l))throw new i("This wallet lacks the Midnight fee claimer role or supplied an unused collateral index.");u=[a.market,c,l]}else{if(c=N(n.amount),c>=1n<<128n)throw new i("Midnight position amount exceeds uint128.");if(o==="supplyCollateral"||o==="withdrawCollateral"){if(!Number.isInteger(n.collateralIndex)||Number(n.collateralIndex)<0||Number(n.collateralIndex)>=a.market.collateralParams.length)throw new i("Choose a current collateral index.");let w=BigInt(String(n.collateralIndex)),h=await a.token(a.market.collateralParams[Number(w)].token);if(m=h,o==="withdrawCollateral"&&c>await a.read("collateral",[a.id,l,w]))throw new i("Insufficient Midnight collateral.");u=o==="supplyCollateral"?[a.market,w,c,l]:[a.market,w,c,l,l],o==="supplyCollateral"&&(d=h)}else{if(n.collateralIndex!==void 0)throw new i("This operation takes no collateral index.");if(o==="repay"&&c>a.position[4]||o==="withdraw"&&(c>a.updated[0]||c>a.state[2]))throw new i("Amount exceeds current debt, credit or available repayment liquidity.");u=o==="repay"?[a.market,c,l,we,"0x"]:[a.market,c,l,l],o==="repay"&&(d=a.loan)}}let f=`Midnight ${o}: ${c} ${m.symbol} base units (token ${m.address}, decimals ${m.decimals}) on ${a.id}; beneficiary ${l}; maturity ${a.market.maturity} Unix seconds. No callbacks or delegation. Withdrawal can fail if collateral health or lender liquidity changes.`,b=[...d?[e.approval(d.address,Y,c.toString(),p)]:[],e.unsignedTx({to:Y,data:Xe({abi:ae,functionName:String(o),args:u}),value:"0",chainId:p,description:f})];return r(b,l,f)}),s("morpho_midnight_manage",{operation:{type:"string",enum:["setConsumed","setIsAuthorized","setConfigurator","setFeeSetter","setFeeClaimer","setTickSpacingSetter","enableLltv","enableLiquidationCursor","setMarketTickSpacing","setMarketSettlementFee","setMarketContinuousFee","setDefaultSettlementFee","setDefaultContinuousFee","claimSettlementFee"]},values:{type:"array",maxItems:3,items:{oneOf:[{type:"string"},{type:"boolean"}]}}},["operation","values"],async(n,l)=>{let a={setConfigurator:"configurator",setFeeSetter:"configurator",setFeeClaimer:"configurator",setTickSpacingSetter:"configurator",enableLltv:"configurator",enableLiquidationCursor:"configurator",setMarketTickSpacing:"tickSpacingSetter",setMarketSettlementFee:"feeSetter",setMarketContinuousFee:"feeSetter",setDefaultSettlementFee:"feeSetter",setDefaultContinuousFee:"feeSetter",claimSettlementFee:"feeClaimer"};if(typeof n.operation!="string"||!["setConsumed","setIsAuthorized",...Object.keys(a)].includes(n.operation)||!Array.isArray(n.values))throw new i("Choose a finite Midnight management operation and ordered values.");let o=n.operation,u=ae.find(f=>f.name===o);if(n.values.length!==u.inputs.length)throw new i("Provide the exact ordered operation values.");let d=e.clientFor(p);if(await d.getChainId()!==p)throw new i("Midnight requires chain 4663.");let m=u.inputs.map((f,b)=>{let w=n.values[b];if(f.type==="bool"){if(typeof w!="boolean")throw new i("Use boolean management values.");return w}if(f.type==="address")return Ue(w,"Use explicit management addresses.",De);if(f.type==="bytes32")return Ge(w,32);if(/^uint/.test(f.type)){let h=N(w,!0);if(h>=1n<<BigInt(f.type.slice(4)))throw new i("Management integer exceeds its ABI width.");return h}throw new i("Unsupported management argument type.")});if(o==="setConsumed"||o==="setIsAuthorized"){if(!E(String(m[2]),l))throw new i("Midnight management is bound to this wallet.")}else{let f=await d.readContract({address:Y,abi:ae,functionName:a[o]});if(typeof f!="string"||K(f)!==K(l))throw new i("This wallet lacks the Midnight configuration, fee or tick role.")}let c=`Midnight ${o}, ordered values ${JSON.stringify(n.values)}. ${o==="setIsAuthorized"&&m[1]?"This grants authority over all Midnight positions, cancellations and further delegation, without an amount cap. Revoke with false when done.":""}${o==="setConsumed"?"Consumption only increases; setting uint128 maximum permanently cancels this offer group.":""}`;return r([e.unsignedTx({to:Y,data:Xe({abi:ae,functionName:o,args:m}),value:"0",chainId:p,description:c})],l,c)})]}};import{decodeAbiParameters as oe,encodeAbiParameters as ma,encodeFunctionData as R,erc20Abi as et,getAddress as L,isAddress as Re,keccak256 as fa,parseAbi as Ee,parseAbiParameters as J}from"viem";var Pe="morpho",pa="https://api.morpho.org/graphql",U=L(V[p].morpho.morpho_blue.address),ba=L(V[p].morpho.adaptive_curve_irm.address),wa=L(V[p].morpho.USDG.address),de=L(V[p].morpho.WETH.address),ha=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],ka={"oak-recorded":"Oak recorded chain observations (block 100362239).","morpho-listed":"Morpho API (POST https://api.morpho.org/graphql, markets where chainId_in [4663]) returned listed: true, fetched 2026-10-31 UTC.",longbow:"Longbow market list: Longbow MCP list_markets/get_market (https://mcp.longbow.credit/mcp, named on https://longbow.cash/mcp) and the live market list on https://longbow.cash/earn, fetched 2026-10-31 UTC; each ID re-read on chain.",netnet:"NetNet Credit: six stock-token market IDs printed at https://docs.netnet.capital/credit, plus the Loopback wsNET/USDG market returned by NetNet's Turbo router marketId() and Credit adapter marketIds(6); fetched 2026-10-31 UTC."},tt=[{marketId:"0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2",label:"WETH/USDG 77%",source:"oak-recorded"},{marketId:"0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8",label:"USDG/WETH",source:"oak-recorded"},{marketId:"0x0309c02dabf0be02682af1a2bde9a457f4df0f0b6bc889cde3f948e5315e4114",label:"spUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x10151e2ac82a820153520d9d77d56de1c84775e23b79bdc11e2e34282d9afa10",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x127353ba63e08f74d8e9ce8a1c2b41b5f89c7167135b1c09fbed34a71b4cb06b",label:"WETH/USDG 86%",source:"morpho-listed"},{marketId:"0x1a31d1c8c05a98b94777663912e4166bf50f3fcdc9c3c3d29deb55634ac58239",label:"PONS/USDG 62.5%",source:"morpho-listed"},{marketId:"0x1efd13a2d1dc66a2466e7c25820537028e604791f00454d9c686fdfbf70f404d",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x21ea2a012b888120e328775c2a7bf6fb4619cf4c4c631ad1c9b6db51f8882d5a",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x22e4598e5cc16cff0056e72d61c5f1f2f8bf5bbffc22da5277ab196939c8a59e",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x66306c087add8907752320b309934abcc354d21626de8115c79df49d9c214edc",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x69400cfe81f2ae381b9a9f27076a4d637338379d999e9ffdfbde52f0876312ee",label:"META/USDG 62.5%",source:"morpho-listed"},{marketId:"0x7408b08b03e05ffd2d21c797489a0e77a28e4bb36acb4e827c69e805d06272b4",label:"GOOGL/USDG 77%",source:"morpho-listed"},{marketId:"0x7c1e38bf461da47df9805ae9b7e97a12ec023625a1f92d2a403b3b9a92260894",label:"CASHCAT/USDG 62.5%",source:"morpho-listed"},{marketId:"0x919a9b6b94dae7c86620eaf7a08e597aae8a4c3a9e9c7671771fbaf62b6b61c7",label:"syrupUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x93ed7865910b09f5a2e0dbfd4670c2d3bc1da9647f7c68e7975f37f497898cdb",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x947ae981cc823024ea00b602f6ea72d049cac05d66ef096198ceeb998651c175",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0x95312f02c1dae8407b2c80468a5657a9bd19c45ac277f1a61aa52c11444c5314",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xba01f6625137b692c5dd86afb8e654b4016d7b64e36dfca4124e84bef98bc4d2",label:"GOOGL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xc845da65a020ddca5f132efa8fea79676d8edfdea504226a4c01e7a9e34cddd6",label:"USDe/USDG 91.5%",source:"morpho-listed"},{marketId:"0xcaa167af7ba0422c76424fae56167b7db25bf19f4f435215e6dd7d06a943bdac",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe29c7d3790037800101ecbad9c45de2067698d206cbcab7c25069a9f43c9eb98",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe5a6d99c3721ef2ab00fb16f0ad226bc7c87a90394f82e27dc6bbca4b1d95c5d",label:"AI/USDG 62.5%",source:"morpho-listed"},{marketId:"0xeb1739b2a69dd22a4285d366a06698a01018b37c24d2994fefe19cc72f313613",label:"SPY/USDG 77%",source:"morpho-listed"},{marketId:"0xf5ff7d546af5e72f3912d2aa723088fd0bf66fddc158714995637714d9db6e4c",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xaa586d26a6fe62d9c0f0948fede6e2130500ac7a655587447e2d4a37e6330589",label:"wsNET/USDG 62.5% (NetNet Loopback)",source:"netnet"},{marketId:"0x8b16891f032a93b771347c9cb470a780e6699dd701553d3402aa3cdba6189c3e",label:"NVDA/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x9b4b47cdf7e295341c6c6cdfd3efb9805c4a5b3d580dba0c0c39d3a4232b297b",label:"SPCX/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0xdeb4782d012d5fd3b24962538c2f6559049d70bda4dabd2e4212dacb96c28d45",label:"AAPL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x7fa81b10e5d21b2e4c571f862442bc11aff2ed14f02335868d0ff933fd40d0ba",label:"GOOGL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x2e1859aa8f143b7220088f80562c6dfe0bf8e52b87d9cedf8da8805f231994ce",label:"MSFT/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x3ebd43d91c3960a9fac32bedd5c60428e0e414de5bdd67fda770207afb0eb615",label:"COIN/USDG 38.5% (NetNet Credit)",source:"netnet"},{marketId:"0x26f3bd5919ba0e6ea6f4bca1b8bd95ce29cbe3aad4ef824fb007570eac35103b",label:"cbBTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb095654f06f4d17d4fc010c2d89a107649e3c5b58e53a3812d1736c95e63e3f8",label:"NVDAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x947c05e7c0fa3ba187d57db710d04ba8be4fef53baba0cfbe71ce61b34a1367d",label:"SPCXon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf8f0b5badf06192908bc47af32b93742d9b4fb6072d388cb183ff7849ee6534c",label:"SPYon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x26c80a00f8facc6b081989965d89cedc274b90b81be660e69245a74e5384f5de",label:"METAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xeefec6c3e5cb7df1f2366ea7cf96a583081205b9720e807d2868d9866a702229",label:"GOOGLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf511a080dcb4d0a3b9d6aebb06e24afa011cda87f9f71ada70c60f8220e94f35",label:"AAPLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xa87da1cc931faa945a41861cc9c90076772ceeae9a663836df6b265c4f30106d",label:"MSTRon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x0279ea145eff84ed2ffd3b1ed1f2aca333060d9cef6fdd48bd21073c13ec86bf",label:"CRCLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xff2063ef18bc5f71867c56d6d3290b61f3da1d010c8a0552bdb7995cfad8cacc",label:"TSLAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x83d542605940b5495ef38d4b62a39293766a486a24e5c67930f41acd919cf1d1",label:"QQQon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9b01d5ad5ce8e477510854132cc47853f6e82a708c9c4723887550412f4ee522",label:"GMEon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8b2af4d69ad861a4099b995b6279aeaf6a905225a0ee889bce424c7faf19b7d9",label:"AMZN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4edbd2f2f3b33bc5f80ab588def67fab8c10945fc99f855d80ff4bef2c4aa1f0",label:"SLV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x7e6ebfdc58a893a5cddba0fba0483baf4fac2efece627ad50821dbe27d6f9738",label:"GOOGL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x30a2a5f1a098b23ed91eadc4529a8d1c967f2cdc2e40a709f3a5992004b01ac0",label:"AAPL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x14973a168cf6c6b1148309f5d567c255b292863ffe9cca59f4284e1426636f00",label:"RKLB/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf049167e6bf18a1b41b8e2acefcf7bc9b13ea013d8d65c7fbc7cbaeb3fe9b4e2",label:"NBIS/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8114b65dfc5e64222103e5588de261eca9defd25f47ea4ae2f91d49fe4fa2993",label:"CLSK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x96d3d5f9bc842e4c8a935c5628abd02fb0e10115560c35a9add768781434f471",label:"CRWV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x1b3555f7c1273688f01ae82da7dc8e508e6a7841ec0038dbb15767154a277b86",label:"EWY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x039503b6308d6d818d181e626d3fbc667d6e68393c3d74332a6124cd2dd6e755",label:"CASHCAT_LEGACY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x597227ca652ea5e8afb6e4801ecd766a4d6eb9b3b9fafa9127ba88a8b1f19629",label:"SPCX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x50bc39b5722fb5634c436d74c6787f3c125b879e7b73cf9e9ecc01bbb57b8e55",label:"SPY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x315b99abb698487891243a84afd28a5ff56fe02143f203c03edd3f103936bf60",label:"QQQ/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4979137c23c8fb519cd507adc290944c3c2120e8a3191547531fced28360e9c2",label:"GME/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x6b8a1f62d88d1cd1e8de609aef07cafc8226172ba703e57c52c3730350e61df1",label:"USO/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xafc86936af4f7edf083eb2550b8c42311b83c685982742b9271b309a58268855",label:"MSFT/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf6f3dbe0a19e948147e79e66502c6b05709d8dfde977fec7db1528fc8f0ebdfa",label:"SGOV/USDG 86% (Longbow)",source:"longbow"},{marketId:"0x2ab6a14c9f68d4216dcb3b4e6ed607cf82f2e6badfa2bd5618d7f69d012d7fab",label:"USAR/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb41b34c5989420ad080e79363a9cfe3e23bec7459fcd2d88029250da370288df",label:"TSLA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4d2075836fd32183b10e5be1b383f6430de859df6d2bd5ec5b859970c4dd14e8",label:"AMD/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9df4f54a2e46b35bd326cec97dbabc4203fa6c64a8e4182128f277adba8fefaf",label:"MU/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb5ba72c0d55c353fa37c0bea104eb117afb2f4934473bcb736d2218ae5686746",label:"PLTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xda5584635e8b14ea18f674dbe4243365505910fefd8e3aa1ac9bfaac0eba74e8",label:"INTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x74fece475178af9e06d31fb64f405046a305f8f0abc588782f596d6f261c1fbb",label:"SNDK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xee04847a312224d551d2267bb5c2c2695777af5fd1f05347bdcca397e8f54336",label:"ORCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x508b47fb12dbb8747644d4436aae65489b5f2819936adefc8a591323f64a5b01",label:"COIN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x243ac165f79a75a0590d2e994ffa9e260b70292fd1ca134ace95f3640895b19f",label:"TSM/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x01baec96478004fc7b74c8dfe38abef8d716fea59ffd481b6ec74db915d3bc80",label:"MSTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf0959f62e748938cf260ca6fe7cb21a412e0a6643913460f4a6770c3f4b90af6",label:"CRCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xbe881499e682850931951c998e76cfbf38c7979b1beeae7cbbb97a39b3336a07",label:"ASML/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xdd578ca54b4ef6a7827c6e9fc06905699a577f6e2f00712853d8aab13383bc38",label:"BABA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xd8b502d5c43f6e5cfff7f938c7ef18e684f114fb5b362611981144397e5d5aef",label:"DELL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x003390b057d753bd839981a0d45f9a567aa0b0ed6373fd42e951eac8ee86c2ba",label:"RGTI/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xc6e16cff2bcf185639562ab937b7a1c381522768ff16aefc85a25ff6ab1c45ea",label:"AI/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xaba3ac501ce4c6b80c08ed0dba19e1ac0de495f17af3ed692a38e92d176a6c9e",label:"PONS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8097c1d1000eb657e75265384137041ac92856c8dc0b72c99569c3681320a430",label:"DELTA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6e6762ae397a2b3f2500ea2f48f8adce0eadfbf54cbc37f6108602e907e844ad",label:"INDEX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x378713071c58206c6a826287d0051bcae113d83d6e3d3b6370b7e73128d06162",label:"STONKBROKER/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x2695be2638c98241c887e4cad4eeba0f01137205f46b9e302edab04b5fee0570",label:"AVGO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6c12c02536aa27831f713d658b59f74e149cc62b48528cb74455e79fab32f772",label:"GLD/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x298e8ff9b31f22be90507bc61b55e66ab93e78b55a60593035e309ed93137cb8",label:"RDDT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb33399a677e1a21152fa9969f02c57a7a342e692ec45608a3fa0d3d92519c343",label:"COST/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x3be7fe1b6b439cfeb737d9921e9b83c92095a23a4f50aeee0d6d04f44446170f",label:"DJT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0066bc47b87597993af0bca6f526175c0abae011b764d4bf12a3def45e1f4e78",label:"NFLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8c170f5c5df593791640ac9fbac297d59d08c2e92e86f38fe52d38e929e60fa3",label:"AMC/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0f18d4fd8d86bd4d100b867b67e1fd38c80981fcd43e442313c2d5408da9352d",label:"LLY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x7d4313cf1b0ede39395a2c7495dc1b1b47370caf51f70571d927f22e715e5f58",label:"LULU/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xa85928d77bd25cc348e13ea6587b8b3ca3793f4af5e5db8ca07d0f20fd5cfa99",label:"IBM/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x9d61e320efb766ce5c375032b399f08afe644b095a9cb0b2d6d1f6ab68399a6f",label:"F/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x43c51f6ff44ab406ab9c97cb5512c881f4a7498209f94bbcfd874d8f97fad79d",label:"HIMS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe6284cf12d0603aee18ff5ab412e262cf99f120e967579111d7a51f37f276f54",label:"TTWO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe8d9b45cdbedc4401a3145be7726c9f72b715e03c5399c961439f11636ee9fb6",label:"MRNA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x46eea143d473cdb8587505f8886dad452037f285f7729a7763e8c233c63b2e8e",label:"RIVN/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8338aed363a309039b2f271a83558831e7e445f2d13c6e72c576ec0b8a969415",label:"RBLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x4e92b336ecad6c842be20ae2ae27b28b3cf5ced6c5388a808167c03a8d75fdf8",label:"SPY/WETH 38.5% (Longbow)",source:"longbow"},{marketId:"0x141c2b1d2bbecf7f8a76563307d7e5bf586457e873c3d97c4bb1502e57b77952",label:"NVDA/WETH 38.5% (Longbow)",source:"longbow"}],ya=new Map(tt.map(e=>[e.marketId.toLowerCase(),e]));function W(e){return ya.get(e.toLowerCase())}function ot(e){let t=W(e);return t?{actions:"enabled",label:t.label,source:ka[t.source]}:{actions:"read-only",reason:"Not in Oak's verified Morpho market registry; Oak builds no transactions for it."}}var Bt=20,ve=120n,_e=1000000n,He=1n,he=10n**18n,ga=10n**36n,Et=(1n<<128n)-1n,Sa=(1n<<256n)-1n,X=Ee(["function idToMarketParams(bytes32 id) view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv)","function market(bytes32 id) view returns (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee)","function position(bytes32 id, address user) view returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral)","function supplyCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, bytes data)","function withdrawCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, address receiver)","function borrow((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsBorrowed, uint256 sharesBorrowed)","function repay((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsRepaid, uint256 sharesRepaid)","function supply((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsSupplied, uint256 sharesSupplied)","function withdraw((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn)"]),Aa=Ee(["function price() view returns (uint256)"]),Ia=Ee(["function borrowRateView((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee) market) view returns (uint256)"]),_t=Ee(["function deposit() payable"]);function ce(e){return{loanToken:e.loanToken,collateralToken:e.collateralToken,oracle:e.oracle,irm:e.irm,lltv:e.lltv.toString()}}function Ce(e,t){return e===0n?0n:(e+t-1n)/t}function xa(e,t,s){return e*(s+_e)/(t+He)}function Ta(e,t,s){return Ce(e*(s+_e),t+He)}function rt(e,t,s){return e*(t+He)/(s+_e)}function ne(e,t,s){return Ce(e*(t+He),s+_e)}function ke(e,t,s){return e*t/ga*s/he}function Ma(e,t,s){return t.startsWith("-")?`-${e.formatAmount(t.slice(1),s)}`:e.formatAmount(t,s)}function ye(e,t){let s=[],r={};for(let n of t.changes){let l=Ma(e,n.amount,n.token.decimals);s.push({token:n.token,amount:n.amount,formattedAmount:l}),r[n.token.address.toLowerCase()]=l}return{formattedChanges:s,formattedNetOutflows:r}}function Ht(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new i("Morpho marketId must be a 32-byte hex string.");return e.toLowerCase()}function qe(e){if(!e||typeof e!="object")throw new i("Morpho marketParams must be an object.");for(let a of[e.loanToken,e.collateralToken,e.oracle,e.irm])if(typeof a!="string"||!Re(a,{strict:!1}))throw new i("Morpho marketParams contains an invalid address.");let t=L(e.loanToken),s=L(e.collateralToken),r=L(e.oracle),n=L(e.irm),l=typeof e.lltv=="bigint"?e.lltv:Me(String(e.lltv));if(t===te||s===te||r===te)throw new i("Morpho marketParams loan, collateral, and oracle addresses must be non-zero.");if(l<=0n||l>=he)throw new i("Morpho marketParams LLTV must be between 0 and 1e18.");return{loanToken:t,collateralToken:s,oracle:r,irm:n,lltv:l}}function be(e){let t=qe(e),s=ma(J("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return fa(s)}function at(e){let t=e.toLowerCase();return t===dt.toLowerCase()||t===ct.toLowerCase()||t===te.toLowerCase()}function ge(e,t){let s=t??e.wallet;if(!s)throw new i("Provide a valid wallet address.");return q(s),L(s)}async function re(e,t,s){if(typeof e.call=="function"){let r=await e.call({to:t,data:s});if(r&&typeof r.data=="string")return r.data}if(typeof e.request=="function"){let r=await e.request({method:"eth_call",params:[{to:t,data:s},"latest"]});if(typeof r=="string")return r}throw new i(`Unable to execute eth_call on contract ${t}.`)}function qt(e){return typeof e=="string"&&/^[A-Za-z0-9$._+-]{1,32}$/.test(e)?e:"UNKNOWN"}async function Q(e,t,s=p){if(q(t),at(t))return{...ut,chainId:s};let r=L(t),n=r.toLowerCase();if(s===p){if(n===wa.toLowerCase())return mt;if(n===de.toLowerCase())return ft}let[l,a]=await Promise.all([re(e,r,R({abi:et,functionName:"symbol"})),re(e,r,R({abi:et,functionName:"decimals"}))]),[o]=oe(J("string"),l),[u]=oe(J("uint8"),a);return{address:r,symbol:qt(o),decimals:Number(u),chainId:s}}async function Ft(e,t){let s=await re(e,U,R({abi:X,functionName:"idToMarketParams",args:[t]})),[r,n,l,a,o]=oe(J("address, address, address, address, uint256"),s);return{loanToken:L(r),collateralToken:L(n),oracle:L(l),irm:L(a),lltv:o}}async function jt(e,t){let s=await re(e,U,R({abi:X,functionName:"market",args:[t]})),[r,n,l,a,o,u]=oe(J("uint128, uint128, uint128, uint128, uint128, uint128"),s);return{totalSupplyAssets:r,totalSupplyShares:n,totalBorrowAssets:l,totalBorrowShares:a,lastUpdate:o,fee:u}}async function Se(e,t,s){let r=await re(e,U,R({abi:X,functionName:"position",args:[t,L(s)]})),[n,l,a]=oe(J("uint256, uint128, uint128"),r);return{supplyShares:n,borrowShares:l,collateral:a}}async function Fe(e,t){let s=await re(e,L(t),R({abi:Aa,functionName:"price"})),[r]=oe(J("uint256"),s);return r}async function Pa(e,t,s){if(t.irm===te)return 0n;let r=await re(e,L(t.irm),R({abi:Ia,functionName:"borrowRateView",args:[t,s]})),[n]=oe(J("uint256"),r);return n}function je(e,t,s){let r=s>e.lastUpdate?s-e.lastUpdate:0n,n=t*r,l=Ce(n*n,2n*he),a=Ce(l*n,3n*he);return e.totalBorrowAssets+Ce(e.totalBorrowAssets*(n+l+a),he)}async function Le(e,t,s,r=0n){let[n,l]=await Promise.all([e.getBlock({blockTag:"latest"}),Pa(e,t,s)]),a=BigInt(Math.ceil(Date.now()/1e3)),o=(n.timestamp>a?n.timestamp:a)+r;return{totalBorrowAssets:je(s,l,o),accruedThrough:o,rate:l}}async function Vt(e,t,s){let r=await re(e,L(t),R({abi:et,functionName:"balanceOf",args:[L(s)]})),[n]=oe(J("uint256"),r);return n}async function ue(e,t,s=!1){let r=t.marketId,n=t.marketParams;if(!r&&!n)throw new i("Provide either marketId or marketParams for the Morpho Blue market.");let l=n?qe(n):void 0,a=l?be(l):void 0,o=r!==void 0?Ht(r):void 0;if(o&&a&&o!==a.toLowerCase())throw new i(`MarketParams tuple hash (${a}) does not match marketId (${o}).`);let u=(o??a).toLowerCase();if(s&&!W(u))throw new i(`Morpho actions require a known market from Oak's verified registry, which pins its oracle. Find one with morpho_status {"discover":true}; other markets are read-only.`);let[d,m]=await Promise.all([Ft(e,u),jt(e,u)]);if(d.loanToken===te||d.collateralToken===te||d.lltv===0n||m.lastUpdate===0n)throw new i(`Morpho market ${u} is not initialized on chain ${p}.`);let c=be(d);if(c.toLowerCase()!==u.toLowerCase())throw new i(`On-chain idToMarketParams tuple hash (${c}) does not match marketId (${u}).`);if(l&&!(l.loanToken.toLowerCase()===d.loanToken.toLowerCase()&&l.collateralToken.toLowerCase()===d.collateralToken.toLowerCase()&&l.oracle.toLowerCase()===d.oracle.toLowerCase()&&l.irm.toLowerCase()===d.irm.toLowerCase()&&l.lltv===d.lltv))throw new i(`Provided marketParams tuple does not match on-chain idToMarketParams for ${u}.`);return{marketId:u,marketParams:d,marketState:m}}function Ae(e){if(e.assets!==void 0&&e.amount!==void 0)throw new i("Specify either assets or amount, not both.");let t=e.assets??e.amount;if(typeof t!="string")throw new i("Provide an amount as a base-unit integer string.");let s=Me(t);if(s<=0n||s>Et)throw new i("Asset amount must be greater than zero and fit in uint128.");return s}function Ie(e,t){for(let s of["onBehalf","receiver"])if(e[s]!==void 0&&(typeof e[s]!="string"||e[s].toLowerCase()!==t.toLowerCase()))throw new i(`Morpho ${s} must be the wallet; overrides are not supported.`);if(e.data!==void 0&&e.data!=="0x")throw new i("Morpho callback data must be empty (0x).")}async function va(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=e.clientFor(p),{marketId:a,marketParams:o}=await ue(l,t,!0),u=await Q(l,o.collateralToken,p),d=o.collateralToken.toLowerCase()===de.toLowerCase(),m=typeof t.collateralToken=="string"?(q(t.collateralToken),L(t.collateralToken)):void 0,c=z("wrapNative",t.wrapNative)===!0||m!==void 0&&at(m);if(m&&!at(m)&&m.toLowerCase()!==o.collateralToken.toLowerCase())throw new i(`Collateral token ${m} does not match market collateral ${o.collateralToken}.`);if(c&&!d)throw new i("Native ETH wrapping is only supported when market collateralToken is WETH.");let f=Ae(t),b=f.toString(),w=e.formatAmount(b,u.decimals),h=[];c&&h.push(e.unsignedTx({chainId:p,to:de,data:R({abi:_t,functionName:"deposit"}),value:b,description:`Wrap ${w} ETH into WETH at ${de}.`})),h.push(e.approval(o.collateralToken,U,b,p)),h.push(e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"supplyCollateral",args:[o,f,n,"0x"]}),value:"0",description:`Supply ${w} ${u.symbol} (${b} base units) collateral to Morpho market ${a}.`}));let y=await e.preview(h,r),{formattedChanges:k,formattedNetOutflows:g}=ye(e,y);return{action:"morpho_supply_collateral",chainId:p,marketId:a,marketParams:ce(o),collateralToken:u,assets:b,formattedAssets:w,onBehalf:n,txs:h,summary:`${c?`Send ${w} ETH to wrap into WETH. `:""}Supply ${w} ${u.symbol} collateral to Morpho Blue market ${a}.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ca(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=r,a=e.clientFor(p),{marketId:o,marketParams:u,marketState:d}=await ue(a,t,!0),[m,c,f,b]=await Promise.all([Q(a,u.loanToken,p),Se(a,o,n),Fe(a,u.oracle),Le(a,u,d,ve)]),w=Ae(t),h=w.toString(),y=e.formatAmount(h,m.decimals),k=d.totalSupplyAssets>d.totalBorrowAssets?d.totalSupplyAssets-d.totalBorrowAssets:0n;if(w>k)throw new i(`Insufficient market liquidity: requested ${h} base units, available ${k.toString()} base units.`);let g=ke(c.collateral,f,u.lltv),T=ne(c.borrowShares,b.totalBorrowAssets,d.totalBorrowShares);if(c.collateral===0n||T+w>g)throw new i(`Insufficient collateral or unhealthy borrow: total debt ${(T+w).toString()} exceeds max borrow ${g.toString()} base units.`);let I=Ta(w,b.totalBorrowAssets,d.totalBorrowShares),C=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"borrow",args:[u,w,0n,n,l]}),value:"0",description:`Borrow ${y} ${m.symbol} (${h} base units) from Morpho market ${o}.`})],v=await e.preview(C,r),{formattedChanges:x,formattedNetOutflows:G}=ye(e,v);return{action:"morpho_borrow",chainId:p,marketId:o,marketParams:ce(u),loanToken:m,assets:h,formattedAssets:y,borrowShares:I.toString(),onBehalf:n,receiver:l,txs:C,summary:`Borrow ${y} ${m.symbol} from Morpho Blue market ${o}.`,preview:v,formattedChanges:x,formattedNetOutflows:G}}async function La(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=e.clientFor(p);if(t.shares!==void 0){let x=Me(t.shares);if(x<=0n||x===Sa||x>Et)throw new i("Morpho Blue core does not accept maxUint256 or out-of-range share sentinels; pass exact position.borrowShares.")}if(z("repayAll",t.repayAll)===!0&&(t.shares!==void 0||t.assets!==void 0||t.amount!==void 0))throw new i("Specify repayAll alone, without shares or assets/amount.");if(t.shares!==void 0&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify either assets/amount or shares for Morpho repay, not both.");let{marketId:a,marketParams:o,marketState:u}=await ue(l,t,!0),[d,m,c]=await Promise.all([Q(l,o.loanToken,p),Se(l,a,n),Vt(l,o.loanToken,r)]);if(m.borrowShares===0n)throw new i(`Position has no active borrow debt on Morpho market ${a}.`);let f=0n,b=0n;if(z("repayAll",t.repayAll)===!0)b=m.borrowShares;else if(t.shares!==void 0){let x=Me(t.shares);if(x>m.borrowShares)throw new i(`Repay shares (${x.toString()}) exceed current position borrowShares (${m.borrowShares.toString()}).`);b=x}else f=Ae(t);let w=b>0n?await Le(l,o,u,ve):void 0,h=b>0n?ne(b,w.totalBorrowAssets,u.totalBorrowShares):f;if(c<h)throw new i(`Insufficient loan token balance for repayment: wallet holds ${c.toString()} base units, but ${h.toString()} base units are required (including accrued interest).`);let y=h.toString(),k=e.formatAmount(y,d.decimals),g=e.approval(o.loanToken,U,y,p),T=e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"repay",args:[o,f,b,n,"0x"]}),value:"0",description:b>0n?`Repay ${b.toString()} borrow shares (${k} ${d.symbol}) on Morpho market ${a}.`:`Repay ${k} ${d.symbol} (${f.toString()} base units) on Morpho market ${a}.`}),I=[g,T],M=await e.preview(I,r),{formattedChanges:C,formattedNetOutflows:v}=ye(e,M);return{action:"morpho_repay",chainId:p,marketId:a,marketParams:ce(o),loanToken:d,repayAssets:f.toString(),repayShares:b.toString(),requiredAssets:y,...w?{accruedThrough:w.accruedThrough.toString(),borrowRatePerSecond:w.rate.toString(),inclusionSeconds:ve.toString()}:{},formattedRequiredAssets:k,onBehalf:n,txs:I,summary:b>0n?`Repay ${b.toString()} borrow shares (approval up to ${k} ${d.symbol}) on Morpho Blue market ${a}. Refresh if signing/inclusion takes more than ${ve} seconds.`:`Repay ${k} ${d.symbol} on Morpho Blue market ${a}.`,preview:M,formattedChanges:C,formattedNetOutflows:v}}async function $a(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=r,a=e.clientFor(p),{marketId:o,marketParams:u,marketState:d}=await ue(a,t,!0),[m,c,f,b]=await Promise.all([Q(a,u.collateralToken,p),Se(a,o,n),Fe(a,u.oracle),Le(a,u,d,ve)]),w=z("withdrawAll",t.withdrawAll)===!0?c.collateral:Ae(t);if(w<=0n||w>c.collateral)throw new i(`Insufficient collateral to withdraw: requested ${w.toString()} base units, position holds ${c.collateral.toString()} base units.`);if(c.borrowShares>0n){let C=c.collateral-w,v=ke(C,f,u.lltv),x=ne(c.borrowShares,b.totalBorrowAssets,d.totalBorrowShares);if(x>v)throw new i(`Unhealthy collateral withdrawal: remaining max borrow ${v.toString()} would fall below current debt ${x.toString()} base units.`)}let h=w.toString(),y=e.formatAmount(h,m.decimals),g=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"withdrawCollateral",args:[u,w,n,l]}),value:"0",description:`Withdraw ${y} ${m.symbol} (${h} base units) collateral from Morpho market ${o}.`})],T=await e.preview(g,r),{formattedChanges:I,formattedNetOutflows:M}=ye(e,T);return{action:"morpho_withdraw_collateral",chainId:p,marketId:o,marketParams:ce(u),collateralToken:m,assets:h,formattedAssets:y,onBehalf:n,receiver:l,txs:g,summary:`Withdraw ${y} ${m.symbol} collateral from Morpho Blue market ${o}.`,preview:T,formattedChanges:I,formattedNetOutflows:M}}async function Da(e,t,s){let r=ge(t,s);Ie(t,r);let n=e.clientFor(p),{marketId:l,marketParams:a,marketState:o}=await ue(n,t,!0),u=z("wrapNative",t.wrapNative)===!0;if(u&&a.loanToken.toLowerCase()!==de.toLowerCase())throw new i("Native ETH wrapping is only supported when the market loanToken is WETH.");let d=Ae(t),m=d.toString(),[c,f]=await Promise.all([Q(n,a.loanToken,p),u?Promise.resolve(d):Vt(n,a.loanToken,r)]);if(f<d)throw new i(`Insufficient ${c.symbol} balance to lend: wallet holds ${f.toString()} base units, requested ${m}.`);let b=e.formatAmount(m,c.decimals),w=[];u&&w.push(e.unsignedTx({chainId:p,to:de,data:R({abi:_t,functionName:"deposit"}),value:m,description:`Wrap ${b} ETH into WETH at ${de}.`})),w.push(e.approval(a.loanToken,U,m,p)),w.push(e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"supply",args:[a,d,0n,r,"0x"]}),value:"0",description:`Lend ${b} ${c.symbol} (${m} base units) to Morpho market ${l}.`}));let h=xa(d,o.totalSupplyAssets,o.totalSupplyShares),y=await e.preview(w,r),{formattedChanges:k,formattedNetOutflows:g}=ye(e,y);return{action:"morpho_supply",chainId:p,marketId:l,marketParams:ce(a),loanToken:c,assets:m,formattedAssets:b,supplySharesEstimated:h.toString(),onBehalf:r,oak:ot(l),txs:w,summary:`${u?`Send ${b} ETH to wrap into WETH. `:""}Lend ${b} ${c.symbol} to Morpho Blue market ${l}. It earns the market supply rate and is exposed to the market's collateral, oracle and liquidity risk.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ua(e,t,s){let r=ge(t,s);Ie(t,r);let n=e.clientFor(p),l=z("withdrawAll",t.withdrawAll)===!0;if(l&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify withdrawAll alone, without assets/amount.");let{marketId:a,marketParams:o,marketState:u}=await ue(n,t,!0),[d,m]=await Promise.all([Q(n,o.loanToken,p),Se(n,a,r)]);if(m.supplyShares===0n)throw new i(`This wallet has no lent ${d.symbol} on Morpho market ${a}.`);let c=rt(m.supplyShares,u.totalSupplyAssets,u.totalSupplyShares),f=l?0n:Ae(t),b=l?m.supplyShares:0n;if(!l&&f>c)throw new i(`Withdrawal exceeds the lent balance: requested ${f.toString()} base units, position holds about ${c.toString()}. Use withdrawAll for a full exit.`);let w=u.totalSupplyAssets>u.totalBorrowAssets?u.totalSupplyAssets-u.totalBorrowAssets:0n,h=l?c:f;if(h>w)throw new i(`Insufficient market liquidity: withdrawing ${h.toString()} base units needs idle assets, but only ${w.toString()} are available until borrowers repay. Withdraw at most that amount, or retry later.`);let y=e.formatAmount(h.toString(),d.decimals),g=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"withdraw",args:[o,f,b,r,r]}),value:"0",description:l?`Withdraw all ${m.supplyShares.toString()} supply shares (about ${y} ${d.symbol}) from Morpho market ${a}.`:`Withdraw ${y} ${d.symbol} (${f.toString()} base units) of lent assets from Morpho market ${a}.`})],T=await e.preview(g,r),{formattedChanges:I,formattedNetOutflows:M}=ye(e,T);return{action:"morpho_withdraw",chainId:p,marketId:a,marketParams:ce(o),loanToken:d,withdrawAssets:f.toString(),withdrawShares:b.toString(),estimatedAssets:h.toString(),formattedAssets:y,receiver:r,txs:g,summary:l?`Withdraw all lent ${d.symbol} (about ${y}, including interest) from Morpho Blue market ${a}.`:`Withdraw ${y} lent ${d.symbol} from Morpho Blue market ${a}.`,preview:T,formattedChanges:I,formattedNetOutflows:M}}async function zt(e,t,s){let r=await e.http(pa,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:t,variables:s})});if(!r.ok)throw new i(`Morpho GraphQL request failed (HTTP ${r.status}).`);let n=await r.json();if(n.errors?.length)throw new i("Morpho GraphQL returned query errors.");return n.data??{}}async function Wt(e){let t=`query Markets($chainId: Int!) {
|
|
1
|
+
import{a as ae}from"./3CCBUYUM.js";import{a as bt,d as wt,e as ht}from"./5N4A5XAW.js";import{a as Ne}from"./7MR37STI.js";import{a as We,b as Be,d as pt}from"./IKEJCBYU.js";import{b as ut,c as mt,d as ft}from"./65EQECL3.js";import{d as ct,e as te}from"./GHPREYQK.js";import{a as dt}from"./HTXKERNS.js";import{b as lt}from"./Z4SRGAVL.js";import{a as q}from"./PBQSJSZO.js";import{a as A,d as z}from"./5ZLOCQA4.js";import{d as De,g as E,i as Ue}from"./5KUWLUPM.js";import{a as Me}from"./UP7FBDMJ.js";import{j as it}from"./ABPL3ZZI.js";import{a as p,i as V}from"./FWD4L3CJ.js";import{a as i,e as se}from"./XSD5NL7J.js";import{a as ze}from"./JXOEJPJ4.js";import{encodeFunctionData as me,erc20Abi as Ha,getAddress as Kt,parseAbi as st,zeroAddress as qa}from"viem";import{decodeAbiParameters as aa,encodeFunctionData as oa,getAddress as ie,parseAbiParameters as ra,zeroAddress as fe,zeroHash as It}from"viem";import{decodeAbiParameters as Xt,encodeFunctionData as Yt,erc20Abi as Jt,getAddress as St,parseAbi as Zt,parseAbiParameters as ea,zeroHash as kt}from"viem";var Ke=St("0xCE29862924756584BBD0D75CA1249d22007E2813"),At="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",ta="(uint256 value,uint256 nonce,uint256 deadline,uint8 v,bytes32 r,bytes32 s)",yt=Zt(["function BLUE() view returns (address)",`function vaultExitBundlesV1InKindRedemptionVaultV2(address vault,address adapter,${At}[] marketParamsList,uint256 exitAssets,${ta} sharesPermit,uint256 deadline)`]);function N(e,t=!1){if(typeof e!="string"||!/^\d{1,78}$/.test(e)||BigInt(e)>=1n<<256n||!t&&BigInt(e)===0n)throw new i("Provide a positive uint256 decimal base-unit string.");return BigInt(e)}var gt=(e,t)=>e<t?e:t;async function Za(e,t,s,r,n){q(n);let l=N(r.amount),a=N(r.maxShares),o=N(r.maxPenaltyAssets,!0),u=N(r.deadline),d=e.clientFor(p),m=await pt(d,t,s),c=(S,B,Te,ee=[])=>d.readContract({address:S,abi:B,functionName:Te,args:ee,blockNumber:m.blockNumber}),[f,b,w,h]=await Promise.all([d.getBlock({blockNumber:m.blockNumber}),c(Ke,yt,"BLUE"),c(t,Jt,"balanceOf",[n]),c(t,We,"previewRedeem",[a])]);if(typeof b!="string"||St(b)!==U)throw new i("VaultExitBundlesV1 does not report the pinned Morpho Blue.");if(u<f.timestamp||u>f.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");if(a>Be(w))throw new i("maxShares exceeds the wallet share balance.");let y=gt(m.idle,l),k=m.markets.filter(S=>S.supplied>0n&&W(S.id)),g=l-y,T=k[0]?.penalty??0n,I=g*10n**18n/(10n**18n+T);if(g>0n&&I===0n)throw new i("The penalty-adjusted in-kind amount rounds to zero.");let M=[];for(let S of k){if(I===0n)break;let B=gt(S.supplied,I);M.push({marketId:S.id,assets:B,penalty:(B*S.penalty+10n**18n-1n)/10n**18n}),I-=B}if(I>0n)throw new i("The supported adapter positions cannot cover the requested in-kind exit. Reduce the amount; unverified market positions are not transferred.");if(l+BigInt(M.length)>Be(h))throw new i("maxShares cannot cover the exit and per-market rounding buffer.");if(M.some(S=>S.assets>m.blueCash))throw new i("Morpho Blue cannot fund the largest in-kind callback. Reduce the amount.");let C=M.reduce((S,B)=>S+B.penalty,0n);if(C>o)throw new i("In-kind penalty exceeds maxPenaltyAssets.");let v=[...y?[y]:[],...M.flatMap(S=>[S.assets,S.penalty].filter(B=>B>0n))],G=(await Promise.all(v.map(S=>c(t,We,"previewWithdraw",[S])))).reduce((S,B)=>S+Be(B),0n);if(G===0n||G>a)throw new i("Separately rounded burns exceed maxShares.");let Z=M.map(S=>Xt(ea(At),m.markets.find(B=>B.id===S.marketId).data)[0]),H=m.markets[0]?.adapter;if(!H)throw new i("In-kind exit requires a verified market adapter.");let F=`In-kind exit from ${t}: spend at most ${G} share base units; receive ${y} ${s.symbol} base units and Morpho Blue supply positions ${M.map(S=>`${S.marketId}: ${S.assets} ${s.symbol} base units`).join(", ")||"none"}. Penalty ${C} ${s.symbol} base units. Deadline ${u} (Unix seconds). Supply positions remain exposed to borrower default and can only be withdrawn when market liquidity returns. This is not a cash exit. The exact share allowance bounds drift; accrual can require a fresh preview.`,P=Yt({abi:yt,functionName:"vaultExitBundlesV1InKindRedemptionVaultV2",args:[t,H,Z,l,{value:0n,nonce:0n,deadline:0n,v:0,r:kt,s:kt},u]}),D=[e.approval(t,Ke,G.toString(),p),e.unsignedTx({to:Ke,data:P,value:"0",chainId:p,description:F})],$=await e.preview(D,n),j=-$.changes.filter(S=>S.token.chainId===p&&E(S.token.address,t)).reduce((S,B)=>{if(B.token.decimals!==18||!/^-?\d+$/.test(B.amount))throw new i("Invalid in-kind share preview.");return S+BigInt(B.amount)},0n);if(j<=0n||j>G)throw new i("In-kind preview exceeds the exact share authorization or burns no shares.");return{txs:D,preview:$,summary:F,receipt:{idleAssets:y.toString(),positions:M.map(S=>({marketId:S.marketId,asset:s,assets:S.assets.toString()})),penaltyAssets:C.toString()}}}var pe=ie("0x53A1eB6589861F686af7c531211E35Aefe30210f"),xt=["supply","withdraw","supplyCollateralAndBorrow","repayAndWithdrawCollateral","migrateBorrowPosition"],Qe={kind:0,data:"0x"},Oe={nonce:0n,deadline:0n,signature:{v:0,r:It,s:It}},na=ra("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),Tt=e=>({tools:[{name:"morpho_bundle",inputSchema:{type:"object",additionalProperties:!1,required:["operation","marketId","deadline"],properties:{operation:{type:"string",enum:xt},marketId:{type:"string"},destinationMarketId:{type:"string"},assets:A(),collateralAssets:A(),shares:A(),maxRepayAssets:A(),maxLtv:A(),deadline:A(),allocations:{type:"array",maxItems:4,items:{type:"object",additionalProperties:!1,required:["vault","assets","maxPenaltyAssets"],properties:{vault:{type:"string"},sourceMarketId:{type:"string"},assets:A(),maxPenaltyAssets:A()}}}}},execute:async(t,s)=>{try{q(s);let r=t.operation,n=e.clientFor(p);if(await n.getChainId()!==p||typeof r!="string"||!xt.includes(r))throw new i("Choose a supported Blue bundle on chain 4663.");let l=["operation","marketId","deadline",...r==="supply"?["assets"]:r==="withdraw"?["assets","shares","allocations"]:r==="supplyCollateralAndBorrow"?["collateralAssets","assets","maxLtv","allocations"]:r==="repayAndWithdrawCollateral"?["assets","shares","maxRepayAssets","collateralAssets","maxLtv"]:["destinationMarketId","maxLtv","allocations"]];if(Object.keys(t).some(P=>!l.includes(P)))throw new i("Unexpected argument for this Blue bundle.");let a=await n.getBlock(),o=N(t.deadline);if(o<a.timestamp||o>a.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");let[u,d]=await Promise.all([n.readContract({address:pe,abi:Ne,functionName:"BLUE",blockNumber:a.number}),n.readContract({address:pe,abi:Ne,functionName:"PUBLIC_ALLOCATOR",blockNumber:a.number})]);if(ie(u)!==U||ie(d)!==bt)throw new i("BlueBundlesV1 deployment does not match Oak\u2019s pinned Blue and Public Allocator.");let m=async P=>{if(typeof P!="string"||!W(P))throw new i("Choose a verified Morpho market with a supported exit.");let D=await n.readContract({address:U,abi:O,functionName:"idToMarketParams",args:[P],blockNumber:a.number}),$={loanToken:ie(D[0]),collateralToken:ie(D[1]),oracle:ie(D[2]),irm:ie(D[3]),lltv:D[4]};if(!E(be({...$,lltv:String($.lltv)}),P))throw new i("Blue bundle market identity mismatch.");return $},c=await m(t.marketId),f=r==="migrateBorrowPosition"?await m(t.destinationMarketId):c;if(c.loanToken!==f.loanToken||c.collateralToken!==f.collateralToken)throw new i("Migration requires the same loan and collateral tokens.");if(r==="migrateBorrowPosition"&&t.marketId===t.destinationMarketId)throw new i("Choose a different destination market.");if(r!=="supply"&&!await n.readContract({address:U,abi:O,functionName:"isAuthorized",args:[s,pe],blockNumber:a.number}))throw new i(`Authorize the pinned Blue bundle explicitly with morpho_manage setAuthorization account ${pe}, enabled true, then retry. That authority covers all Blue positions. Revoke it with enabled false after the bundle.`);let b=t.assets===void 0?0n:N(t.assets,!0),w=t.shares===void 0?0n:N(t.shares,!0),h=t.collateralAssets===void 0?0n:N(t.collateralAssets,!0),y=r==="supply"||r==="withdraw"?0n:N(t.maxLtv,!0);if(y>f.lltv)throw new i("maxLtv cannot exceed the verified destination market LLTV.");if(r==="supply"&&b===0n||r==="withdraw"&&b===0n==(w===0n)||r==="supplyCollateralAndBorrow"&&h===0n&&b===0n||r==="repayAndWithdrawCollateral"&&(b>0n&&w>0n||b===0n&&w===0n&&h===0n))throw new i("Choose a nonzero amount; assets and shares are mutually exclusive for repayment/withdrawal.");let k=t.allocations??[];if(!Array.isArray(k)||k.length>4||k.length&&r==="supplyCollateralAndBorrow"&&b===0n)throw new i("Provide at most four explicit allocations, only with a borrow or withdrawal.");let g=new Set,T=[],I=0n;for(let P of k){if(!P||typeof P!="object"||Array.isArray(P)||Object.keys(P).some(Ve=>!["vault","sourceMarketId","assets","maxPenaltyAssets"].includes(Ve)))throw new i("Unsupported bundled allocation input.");let D=P,$=await wt(e,{vault:D.vault,marketId:r==="migrateBorrowPosition"?t.destinationMarketId:t.marketId});if(g.has($.definition.vault.toLowerCase()))throw new i("Use each source vault at most once per bundle.");g.add($.definition.vault.toLowerCase());let j=N(D.assets),S=N(D.maxPenaltyAssets,!0);if(!$.permission||j>=1n<<128n||j>$.headroom||$.penalty>10n**18n||$.asset.address!==f.loanToken)throw new i("Bundled allocation is disabled, unqualified or exceeds target capacity.");let B=(j*$.penalty+10n**18n-1n)/10n**18n;if(B>S)throw new i("Bundled allocation exceeds maxPenaltyAssets.");I+=B;let Te=D.sourceMarketId===void 0,ee=Te?void 0:$.sources.find(Ve=>E(Ve.id,String(D.sourceMarketId)));if(Te?!$.canIdle||j>$.data.idle:!ee||!ee.canPull||j>ee.capacity||j>$.data.blueCash)throw new i("Bundled allocation source cannot cover the requested amount.");T.push({vault:$.definition.vault,adapter:$.target.adapter,marketParams:$.params,sourceAdapter:ee?.adapter??fe,sourceMarketParams:ee?aa(na,ee.data)[0]:$.params,assets:j,penalty:$.penalty,fromIdle:Te})}let M,C,v,x=0n;if(r==="supply")M="blueBundlesV1Supply",v=c.loanToken,x=b,C=[c,b,Qe,0n,fe,o];else if(r==="withdraw")M="blueBundlesV1Withdraw",C=[c,b,w,Oe,T,0n,fe,o];else if(r==="supplyCollateralAndBorrow"){if(M="blueBundlesV1SupplyCollateralAndBorrow",v=c.collateralToken,x=h,I>=b&&I>0n)throw new i("Allocation penalties would consume the borrow proceeds.");C=[c,h,b,y,Qe,Oe,T,0n,fe,o]}else if(r==="repayAndWithdrawCollateral"){if(M="blueBundlesV1RepayAndWithdrawCollateral",v=c.loanToken,x=N(t.maxRepayAssets,!0),b>x||w>0n&&x===0n)throw new i("Repayment requires a sufficient maxRepayAssets budget.");C=[c,b,w,x,h,y,Qe,Oe,0n,fe,o]}else M="blueBundlesV1MigrateBorrowPosition",C=[c,f,y,Oe,T,0n,fe,o];let G=`Morpho Blue atomic ${r}: ${JSON.stringify(t)}. Allocation penalties ${I} loan-token base units; zero referral fee. Max LTV ${y}; absolute deadline ${o}. Migration adds allocation penalties to destination debt; borrowing deducts them from proceeds. Exact input approval ${x}. Existing Blue bundle authorization remains until explicitly revoked with morpho_manage. No opaque callback, permit or signature is accepted.`,Z=[...v&&x?[e.approval(v,pe,x.toString(),p)]:[],e.unsignedTx({to:pe,data:oa({abi:Ne,functionName:M,args:C}),value:"0",chainId:p,description:G})],H=await e.preview(Z,s),F=new Map;for(let P of H.changes)if(BigInt(P.amount)<0n){let D=P.token.address.toLowerCase();F.set(D,(F.get(D)??0n)-BigInt(P.amount))}if([...F].some(([P,D])=>!v||P!==v.toLowerCase()||D>x))throw new i("Bundle preview spends outside the exact input budget.");return{txs:Z,preview:H,summary:G}}catch(r){throw new i(e.plainError(r))}}}]});import{concatHex as Mt,decodeAbiParameters as sa,encodeAbiParameters as $t,encodeFunctionData as Xe,erc20Abi as Pt,getAddress as K,keccak256 as Je,zeroAddress as we,zeroHash as ia}from"viem";var Y=K("0x6120765Ba5336150BbdDdD0Cd9108B5bFD369632"),la=["0x90B800999e4ACd1bD20283BD450bBd2e06D91F7C","0x708d6Bf6F847202a0755bb5636bE663B174242ea"].map(e=>K(e)),Ze=ae.find(e=>e.name==="take"),vt=[Ze.inputs[0]],da=[Ze.inputs[0].components[0]];function Ct(e){let t=Je(Mt(["0x600b380380600b5f395ff3",$t(da,[e])]));return Je(Mt(["0xff",e.midnight,ia,t]))}var le=10n**18n,Lt=(e,t)=>(e+(t-1n)/2n)/t;function Dt(e){if(e<0n)return 10n**36n/Dt(-e);let t=693147180559945309n,s=(e+322611214989459870n)/t,r=e-s*t,n=r*r/(2n*le),l=n*r/(3n*le);return le+r+n+l<<s}function ca(e){if(e<0n||e>6744n)throw new i("Midnight tick is outside 0..6744.");return Lt(Lt(10n**36n,le+Dt(4987541511039073n*(3372n-e))),10n**11n)*10n**11n}function Ge(e,t){if(typeof e!="string"||!/^0x([0-9a-f]{2})*$/i.test(e)||e.length>32770||t!==void 0&&e.length!==2+t*2)throw new i("Provide bounded canonical hex data.");return e}function Ye(e,t){if(!Array.isArray(e)||e.length!==t)throw new i("Invalid Midnight state tuple.");return e.map(s=>{if(typeof s=="number"&&Number.isSafeInteger(s)&&s>=0)return BigInt(s);if(typeof s=="bigint"&&s>=0n)return s;throw new i("Invalid Midnight integer state.")})}var ua=e=>JSON.parse(JSON.stringify(e,(t,s)=>typeof s=="bigint"?s.toString():s)),Ut=e=>{async function t(n,l){let a=Ge(n,32),o=e.clientFor(p);if(await o.getChainId()!==p)throw new i("Midnight requires chain 4663.");let u=await o.getBlock(),d=(k,g=[])=>o.readContract({address:Y,abi:ae,functionName:k,args:g,blockNumber:u.number}),m=await d("toMarket",[a]);if(m.chainId!==BigInt(p)||K(m.midnight)!==Y||!E(Ct(m),a))throw new i("Midnight market identity does not match the pinned chain and contract.");if(![V[p].tokens.USDG.address,V[p].tokens.WETH.address].some(k=>E(k,m.loanToken)))throw new i("This Midnight loan token needs a qualified transfer and exit fixture.");if(!m.collateralParams.length||m.collateralParams.length>128)throw new i("Invalid Midnight collateral inventory.");let[f,b,w,h]=await Promise.all([d("position",[a,l]),d("updatePositionView",[m,a,l]),d("marketState",[a]),d("isHealthy",[m,a,l])]),y=async k=>{let[g,T]=await Promise.all([o.readContract({address:k,abi:Pt,functionName:"decimals",blockNumber:u.number}),o.readContract({address:k,abi:Pt,functionName:"symbol",blockNumber:u.number})]);if(!Number.isInteger(g)||g>36||typeof T!="string")throw new i("Invalid Midnight token metadata.");return{address:K(k),decimals:g,symbol:T.replace(/[^a-zA-Z0-9.$_-]/g,"").slice(0,32),chainId:p}};return{id:a,rpc:o,block:u,market:m,read:d,token:y,loan:await y(m.loanToken),position:Ye(f,6),updated:Ye(b,3),state:Ye(w,13),healthy:h}}let s=(n,l,a,o)=>({name:n,inputSchema:{type:"object",properties:l,required:a,additionalProperties:!1},execute:async(u,d)=>{try{if(q(d),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Midnight argument.");return await o(u,d)}catch(m){throw new i(e.plainError(m))}}});async function r(n,l,a){return{txs:n,preview:await e.preview(n,l),summary:a}}return{tools:[s("morpho_midnight_status",{marketId:{type:"string"}},["marketId"],async(n,l)=>{let a=await t(n.marketId,l),o=await Promise.all(a.market.collateralParams.map(async(m,c)=>({token:await a.token(m.token),lltvWad:m.lltv.toString(),oracle:m.oracle,assets:String(await a.read("collateral",[a.id,l,BigInt(c)]))}))),u=["configurator","feeSetter","feeClaimer","tickSpacingSetter"],d=await Promise.all(u.map(m=>a.read(m)));return{protocol:Object.fromEntries(u.map((m,c)=>[m,K(String(d[c]))])),continuousFeePerSecondWad:String(a.state[11]),tickSpacing:String(a.state[12]),settlementFeeCbps:a.state.slice(4,11).map(String),settlementFeeCbpWadScale:"1000000000000",chainId:p,midnight:Y,marketId:a.id,blockNumber:String(a.block.number),market:ua(a.market),loanToken:a.loan,collaterals:o,debtUnits:String(a.position[4]),creditUnits:String(a.updated[0]),pendingFeeUnits:String(a.updated[1]),withdrawableUnits:String(a.state[2]),healthy:a.healthy,maturity:String(a.market.maturity),matured:a.block.timestamp>a.market.maturity,warning:"Maturity does not guarantee lender liquidity. Borrowers become liquidatable after maturity even when collateralized. Lender credit may absorb borrower default losses."}}),s("morpho_midnight_take",{offer:{type:"string",description:"ABI-encoded Offer struct, never transaction calldata."},ratifierData:{type:"string"},units:A(),maxAssets:A(),minAssets:A()},["offer","ratifierData","units","maxAssets","minAssets"],async(n,l)=>{let a=Ge(n.offer),[o]=sa(vt,a);if(!E($t(vt,[o]),a))throw new i("Offer encoding is not canonical.");let u=await t(Ct(o.market),l),d=N(n.units),m=N(n.maxAssets,!0),c=N(n.minAssets,!0),f=Ge(n.ratifierData);if(d>=1n<<128n||E(o.maker,l)||o.callback!==we||o.callbackData!=="0x"||!la.includes(K(o.ratifier)))throw new i("Use a non-self offer with a pinned ratifier and no maker callbacks. Callback routes need a separate qualified builder.");if(u.block.timestamp<o.start||u.block.timestamp>o.expiry||o.expiry<o.start)throw new i("The Midnight offer is not currently live.");if(o.buy&&o.receiverIfMakerIsSeller!==we||!o.buy&&o.receiverIfMakerIsSeller===we)throw new i("Invalid offer seller receiver.");if(o.buy&&u.block.timestamp>u.market.maturity&&d>u.updated[0])throw new i("Post-maturity sales cannot increase this wallet\u2019s debt.");let b=await u.read("settlementFee",[u.id,u.market.maturity>u.block.timestamp?u.market.maturity-u.block.timestamp:0n]),w=ca(o.tick);if(b>w&&o.buy)throw new i("Settlement fee exceeds the offer price.");let h=o.buy?w-b:w,y=h+b,k=P=>o.buy?P/le:(P+le-1n)/le,g=k(d*y),T=k(d*h);if(o.buy?T<c||T===0n:g>m||g===0n)throw new i("Midnight proceeds/spend do not fit the requested bounds.");let I=await u.read("consumed",[o.maker,o.group]);if(o.maxAssets===0n==(o.maxUnits===0n)||I+(o.maxAssets?o.buy?g:T:d)>(o.maxAssets||o.maxUnits))throw new i("Midnight offer capacity is exhausted or invalid.");if(u.state[11]>o.continuousFeeCap||o.tick%u.state[12]!==0n)throw new i("Offer fee cap or market tick spacing no longer permits execution.");let M=await u.read("isAuthorized",[o.maker,o.ratifier]),C=[{type:"function",name:"isRatified",stateMutability:"view",inputs:[Ze.inputs[0],{type:"bytes"},{type:"address"}],outputs:[{type:"bytes32"}]}],v=await u.rpc.readContract({address:o.ratifier,abi:C,functionName:"isRatified",args:[o,f,l],blockNumber:u.block.number});if(M!==!0||v!==Je(new TextEncoder().encode("morpho.midnight.callbackSuccess")))throw new i("The maker has not authorized and ratified this exact offer.");let x=Xe({abi:ae,functionName:"take",args:[o,f,d,l,o.buy?l:we,we,"0x"]}),G=`Midnight ${o.buy?"sell credit or borrow":"buy credit or reduce debt"}: ${d} fixed debt units; ${o.buy?`receive ${T}`:`spend ${g}`} ${u.loan.symbol} base units (token ${u.loan.address}, decimals ${u.loan.decimals}). Maturity ${u.market.maturity} Unix seconds; offer expiry ${o.expiry}. A borrower can lose collateral after maturity; lender withdrawal depends on repayments and bears default losses. No lender signature or callback is created. Bounds are rechecked locally; the take calldata fixes the offer and units. Exact buyer approval caps wallet spending.`,Z=[...o.buy?[]:[e.approval(u.loan.address,Y,g.toString(),p)],e.unsignedTx({to:Y,data:x,value:"0",chainId:p,description:G})],H=await r(Z,l,G),F=H.preview.changes.filter(P=>P.token.chainId===p&&E(P.token.address,u.loan.address)).reduce((P,D)=>P+BigInt(D.amount),0n);if(o.buy?F<T:F!==-g)throw new i("Midnight preview does not match the exact quoted cash flow.");return H}),s("morpho_midnight_action",{marketId:{type:"string"},operation:{enum:["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"]},amount:A(),collateralIndex:{type:"integer",minimum:0,maximum:127}},["marketId","operation"],async(n,l)=>{let a=await t(n.marketId,l),o=n.operation;if(!["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"].includes(String(o)))throw new i("Choose a finite Midnight position operation.");let u,d,m=a.loan,c=0n;if(o==="updatePosition"){if(n.amount!==void 0||n.collateralIndex!==void 0)throw new i("Position update takes no amount or collateral index.");u=[a.market,l]}else if(o==="claimContinuousFee"){if(c=N(n.amount),n.collateralIndex!==void 0||K(String(await a.read("feeClaimer")))!==K(l))throw new i("This wallet lacks the Midnight fee claimer role or supplied an unused collateral index.");u=[a.market,c,l]}else{if(c=N(n.amount),c>=1n<<128n)throw new i("Midnight position amount exceeds uint128.");if(o==="supplyCollateral"||o==="withdrawCollateral"){if(!Number.isInteger(n.collateralIndex)||Number(n.collateralIndex)<0||Number(n.collateralIndex)>=a.market.collateralParams.length)throw new i("Choose a current collateral index.");let w=BigInt(String(n.collateralIndex)),h=await a.token(a.market.collateralParams[Number(w)].token);if(m=h,o==="withdrawCollateral"&&c>await a.read("collateral",[a.id,l,w]))throw new i("Insufficient Midnight collateral.");u=o==="supplyCollateral"?[a.market,w,c,l]:[a.market,w,c,l,l],o==="supplyCollateral"&&(d=h)}else{if(n.collateralIndex!==void 0)throw new i("This operation takes no collateral index.");if(o==="repay"&&c>a.position[4]||o==="withdraw"&&(c>a.updated[0]||c>a.state[2]))throw new i("Amount exceeds current debt, credit or available repayment liquidity.");u=o==="repay"?[a.market,c,l,we,"0x"]:[a.market,c,l,l],o==="repay"&&(d=a.loan)}}let f=`Midnight ${o}: ${c} ${m.symbol} base units (token ${m.address}, decimals ${m.decimals}) on ${a.id}; beneficiary ${l}; maturity ${a.market.maturity} Unix seconds. No callbacks or delegation. Withdrawal can fail if collateral health or lender liquidity changes.`,b=[...d?[e.approval(d.address,Y,c.toString(),p)]:[],e.unsignedTx({to:Y,data:Xe({abi:ae,functionName:String(o),args:u}),value:"0",chainId:p,description:f})];return r(b,l,f)}),s("morpho_midnight_manage",{operation:{type:"string",enum:["setConsumed","setIsAuthorized","setConfigurator","setFeeSetter","setFeeClaimer","setTickSpacingSetter","enableLltv","enableLiquidationCursor","setMarketTickSpacing","setMarketSettlementFee","setMarketContinuousFee","setDefaultSettlementFee","setDefaultContinuousFee","claimSettlementFee"]},values:{type:"array",maxItems:3,items:{oneOf:[{type:"string"},{type:"boolean"}]}}},["operation","values"],async(n,l)=>{let a={setConfigurator:"configurator",setFeeSetter:"configurator",setFeeClaimer:"configurator",setTickSpacingSetter:"configurator",enableLltv:"configurator",enableLiquidationCursor:"configurator",setMarketTickSpacing:"tickSpacingSetter",setMarketSettlementFee:"feeSetter",setMarketContinuousFee:"feeSetter",setDefaultSettlementFee:"feeSetter",setDefaultContinuousFee:"feeSetter",claimSettlementFee:"feeClaimer"};if(typeof n.operation!="string"||!["setConsumed","setIsAuthorized",...Object.keys(a)].includes(n.operation)||!Array.isArray(n.values))throw new i("Choose a finite Midnight management operation and ordered values.");let o=n.operation,u=ae.find(f=>f.name===o);if(n.values.length!==u.inputs.length)throw new i("Provide the exact ordered operation values.");let d=e.clientFor(p);if(await d.getChainId()!==p)throw new i("Midnight requires chain 4663.");let m=u.inputs.map((f,b)=>{let w=n.values[b];if(f.type==="bool"){if(typeof w!="boolean")throw new i("Use boolean management values.");return w}if(f.type==="address")return Ue(w,"Use explicit management addresses.",De);if(f.type==="bytes32")return Ge(w,32);if(/^uint/.test(f.type)){let h=N(w,!0);if(h>=1n<<BigInt(f.type.slice(4)))throw new i("Management integer exceeds its ABI width.");return h}throw new i("Unsupported management argument type.")});if(o==="setConsumed"||o==="setIsAuthorized"){if(!E(String(m[2]),l))throw new i("Midnight management is bound to this wallet.")}else{let f=await d.readContract({address:Y,abi:ae,functionName:a[o]});if(typeof f!="string"||K(f)!==K(l))throw new i("This wallet lacks the Midnight configuration, fee or tick role.")}let c=`Midnight ${o}, ordered values ${JSON.stringify(n.values)}. ${o==="setIsAuthorized"&&m[1]?"This grants authority over all Midnight positions, cancellations and further delegation, without an amount cap. Revoke with false when done.":""}${o==="setConsumed"?"Consumption only increases; setting uint128 maximum permanently cancels this offer group.":""}`;return r([e.unsignedTx({to:Y,data:Xe({abi:ae,functionName:o,args:m}),value:"0",chainId:p,description:c})],l,c)})]}};import{decodeAbiParameters as oe,encodeAbiParameters as ma,encodeFunctionData as R,erc20Abi as et,getAddress as L,isAddress as Re,keccak256 as fa,parseAbi as Ee,parseAbiParameters as J}from"viem";var Pe="morpho",pa="https://api.morpho.org/graphql",U=L(V[p].morpho.morpho_blue.address),ba=L(V[p].morpho.adaptive_curve_irm.address),wa=L(V[p].morpho.USDG.address),de=L(V[p].morpho.WETH.address),ha=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],ka={"oak-recorded":"Oak recorded chain observations (block 100362239).","morpho-listed":"Morpho API (POST https://api.morpho.org/graphql, markets where chainId_in [4663]) returned listed: true, fetched 2026-10-31 UTC.",longbow:"Longbow market list: Longbow MCP list_markets/get_market (https://mcp.longbow.credit/mcp, named on https://longbow.cash/mcp) and the live market list on https://longbow.cash/earn, fetched 2026-10-31 UTC; each ID re-read on chain.",netnet:"NetNet Credit: six stock-token market IDs printed at https://docs.netnet.capital/credit, plus the Loopback wsNET/USDG market returned by NetNet's Turbo router marketId() and Credit adapter marketIds(6); fetched 2026-10-31 UTC."},tt=[{marketId:"0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2",label:"WETH/USDG 77%",source:"oak-recorded"},{marketId:"0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8",label:"USDG/WETH",source:"oak-recorded"},{marketId:"0x0309c02dabf0be02682af1a2bde9a457f4df0f0b6bc889cde3f948e5315e4114",label:"spUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x10151e2ac82a820153520d9d77d56de1c84775e23b79bdc11e2e34282d9afa10",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x127353ba63e08f74d8e9ce8a1c2b41b5f89c7167135b1c09fbed34a71b4cb06b",label:"WETH/USDG 86%",source:"morpho-listed"},{marketId:"0x1a31d1c8c05a98b94777663912e4166bf50f3fcdc9c3c3d29deb55634ac58239",label:"PONS/USDG 62.5%",source:"morpho-listed"},{marketId:"0x1efd13a2d1dc66a2466e7c25820537028e604791f00454d9c686fdfbf70f404d",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x21ea2a012b888120e328775c2a7bf6fb4619cf4c4c631ad1c9b6db51f8882d5a",label:"SPCX/USDG 62.5%",source:"morpho-listed"},{marketId:"0x22e4598e5cc16cff0056e72d61c5f1f2f8bf5bbffc22da5277ab196939c8a59e",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x66306c087add8907752320b309934abcc354d21626de8115c79df49d9c214edc",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0x69400cfe81f2ae381b9a9f27076a4d637338379d999e9ffdfbde52f0876312ee",label:"META/USDG 62.5%",source:"morpho-listed"},{marketId:"0x7408b08b03e05ffd2d21c797489a0e77a28e4bb36acb4e827c69e805d06272b4",label:"GOOGL/USDG 77%",source:"morpho-listed"},{marketId:"0x7c1e38bf461da47df9805ae9b7e97a12ec023625a1f92d2a403b3b9a92260894",label:"CASHCAT/USDG 62.5%",source:"morpho-listed"},{marketId:"0x919a9b6b94dae7c86620eaf7a08e597aae8a4c3a9e9c7671771fbaf62b6b61c7",label:"syrupUSDG/USDG 91.5%",source:"morpho-listed"},{marketId:"0x93ed7865910b09f5a2e0dbfd4670c2d3bc1da9647f7c68e7975f37f497898cdb",label:"mGLO/USDG 91.5%",source:"morpho-listed"},{marketId:"0x947ae981cc823024ea00b602f6ea72d049cac05d66ef096198ceeb998651c175",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0x95312f02c1dae8407b2c80468a5657a9bd19c45ac277f1a61aa52c11444c5314",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xba01f6625137b692c5dd86afb8e654b4016d7b64e36dfca4124e84bef98bc4d2",label:"GOOGL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xc845da65a020ddca5f132efa8fea79676d8edfdea504226a4c01e7a9e34cddd6",label:"USDe/USDG 91.5%",source:"morpho-listed"},{marketId:"0xcaa167af7ba0422c76424fae56167b7db25bf19f4f435215e6dd7d06a943bdac",label:"AAPL/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe29c7d3790037800101ecbad9c45de2067698d206cbcab7c25069a9f43c9eb98",label:"TSLA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xe5a6d99c3721ef2ab00fb16f0ad226bc7c87a90394f82e27dc6bbca4b1d95c5d",label:"AI/USDG 62.5%",source:"morpho-listed"},{marketId:"0xeb1739b2a69dd22a4285d366a06698a01018b37c24d2994fefe19cc72f313613",label:"SPY/USDG 77%",source:"morpho-listed"},{marketId:"0xf5ff7d546af5e72f3912d2aa723088fd0bf66fddc158714995637714d9db6e4c",label:"NVDA/USDG 62.5%",source:"morpho-listed"},{marketId:"0xaa586d26a6fe62d9c0f0948fede6e2130500ac7a655587447e2d4a37e6330589",label:"wsNET/USDG 62.5% (NetNet Loopback)",source:"netnet"},{marketId:"0x8b16891f032a93b771347c9cb470a780e6699dd701553d3402aa3cdba6189c3e",label:"NVDA/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x9b4b47cdf7e295341c6c6cdfd3efb9805c4a5b3d580dba0c0c39d3a4232b297b",label:"SPCX/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0xdeb4782d012d5fd3b24962538c2f6559049d70bda4dabd2e4212dacb96c28d45",label:"AAPL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x7fa81b10e5d21b2e4c571f862442bc11aff2ed14f02335868d0ff933fd40d0ba",label:"GOOGL/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x2e1859aa8f143b7220088f80562c6dfe0bf8e52b87d9cedf8da8805f231994ce",label:"MSFT/USDG 62.5% (NetNet Credit)",source:"netnet"},{marketId:"0x3ebd43d91c3960a9fac32bedd5c60428e0e414de5bdd67fda770207afb0eb615",label:"COIN/USDG 38.5% (NetNet Credit)",source:"netnet"},{marketId:"0x26f3bd5919ba0e6ea6f4bca1b8bd95ce29cbe3aad4ef824fb007570eac35103b",label:"cbBTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb095654f06f4d17d4fc010c2d89a107649e3c5b58e53a3812d1736c95e63e3f8",label:"NVDAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x947c05e7c0fa3ba187d57db710d04ba8be4fef53baba0cfbe71ce61b34a1367d",label:"SPCXon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf8f0b5badf06192908bc47af32b93742d9b4fb6072d388cb183ff7849ee6534c",label:"SPYon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x26c80a00f8facc6b081989965d89cedc274b90b81be660e69245a74e5384f5de",label:"METAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xeefec6c3e5cb7df1f2366ea7cf96a583081205b9720e807d2868d9866a702229",label:"GOOGLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf511a080dcb4d0a3b9d6aebb06e24afa011cda87f9f71ada70c60f8220e94f35",label:"AAPLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xa87da1cc931faa945a41861cc9c90076772ceeae9a663836df6b265c4f30106d",label:"MSTRon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x0279ea145eff84ed2ffd3b1ed1f2aca333060d9cef6fdd48bd21073c13ec86bf",label:"CRCLon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xff2063ef18bc5f71867c56d6d3290b61f3da1d010c8a0552bdb7995cfad8cacc",label:"TSLAon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x83d542605940b5495ef38d4b62a39293766a486a24e5c67930f41acd919cf1d1",label:"QQQon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9b01d5ad5ce8e477510854132cc47853f6e82a708c9c4723887550412f4ee522",label:"GMEon/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8b2af4d69ad861a4099b995b6279aeaf6a905225a0ee889bce424c7faf19b7d9",label:"AMZN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4edbd2f2f3b33bc5f80ab588def67fab8c10945fc99f855d80ff4bef2c4aa1f0",label:"SLV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x7e6ebfdc58a893a5cddba0fba0483baf4fac2efece627ad50821dbe27d6f9738",label:"GOOGL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x30a2a5f1a098b23ed91eadc4529a8d1c967f2cdc2e40a709f3a5992004b01ac0",label:"AAPL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x14973a168cf6c6b1148309f5d567c255b292863ffe9cca59f4284e1426636f00",label:"RKLB/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf049167e6bf18a1b41b8e2acefcf7bc9b13ea013d8d65c7fbc7cbaeb3fe9b4e2",label:"NBIS/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x8114b65dfc5e64222103e5588de261eca9defd25f47ea4ae2f91d49fe4fa2993",label:"CLSK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x96d3d5f9bc842e4c8a935c5628abd02fb0e10115560c35a9add768781434f471",label:"CRWV/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x1b3555f7c1273688f01ae82da7dc8e508e6a7841ec0038dbb15767154a277b86",label:"EWY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x039503b6308d6d818d181e626d3fbc667d6e68393c3d74332a6124cd2dd6e755",label:"CASHCAT_LEGACY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x597227ca652ea5e8afb6e4801ecd766a4d6eb9b3b9fafa9127ba88a8b1f19629",label:"SPCX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x50bc39b5722fb5634c436d74c6787f3c125b879e7b73cf9e9ecc01bbb57b8e55",label:"SPY/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x315b99abb698487891243a84afd28a5ff56fe02143f203c03edd3f103936bf60",label:"QQQ/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4979137c23c8fb519cd507adc290944c3c2120e8a3191547531fced28360e9c2",label:"GME/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x6b8a1f62d88d1cd1e8de609aef07cafc8226172ba703e57c52c3730350e61df1",label:"USO/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xafc86936af4f7edf083eb2550b8c42311b83c685982742b9271b309a58268855",label:"MSFT/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf6f3dbe0a19e948147e79e66502c6b05709d8dfde977fec7db1528fc8f0ebdfa",label:"SGOV/USDG 86% (Longbow)",source:"longbow"},{marketId:"0x2ab6a14c9f68d4216dcb3b4e6ed607cf82f2e6badfa2bd5618d7f69d012d7fab",label:"USAR/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb41b34c5989420ad080e79363a9cfe3e23bec7459fcd2d88029250da370288df",label:"TSLA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x4d2075836fd32183b10e5be1b383f6430de859df6d2bd5ec5b859970c4dd14e8",label:"AMD/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x9df4f54a2e46b35bd326cec97dbabc4203fa6c64a8e4182128f277adba8fefaf",label:"MU/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xb5ba72c0d55c353fa37c0bea104eb117afb2f4934473bcb736d2218ae5686746",label:"PLTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xda5584635e8b14ea18f674dbe4243365505910fefd8e3aa1ac9bfaac0eba74e8",label:"INTC/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x74fece475178af9e06d31fb64f405046a305f8f0abc588782f596d6f261c1fbb",label:"SNDK/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xee04847a312224d551d2267bb5c2c2695777af5fd1f05347bdcca397e8f54336",label:"ORCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x508b47fb12dbb8747644d4436aae65489b5f2819936adefc8a591323f64a5b01",label:"COIN/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x243ac165f79a75a0590d2e994ffa9e260b70292fd1ca134ace95f3640895b19f",label:"TSM/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x01baec96478004fc7b74c8dfe38abef8d716fea59ffd481b6ec74db915d3bc80",label:"MSTR/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xf0959f62e748938cf260ca6fe7cb21a412e0a6643913460f4a6770c3f4b90af6",label:"CRCL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xbe881499e682850931951c998e76cfbf38c7979b1beeae7cbbb97a39b3336a07",label:"ASML/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xdd578ca54b4ef6a7827c6e9fc06905699a577f6e2f00712853d8aab13383bc38",label:"BABA/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xd8b502d5c43f6e5cfff7f938c7ef18e684f114fb5b362611981144397e5d5aef",label:"DELL/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0x003390b057d753bd839981a0d45f9a567aa0b0ed6373fd42e951eac8ee86c2ba",label:"RGTI/USDG 62.5% (Longbow)",source:"longbow"},{marketId:"0xc6e16cff2bcf185639562ab937b7a1c381522768ff16aefc85a25ff6ab1c45ea",label:"AI/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xaba3ac501ce4c6b80c08ed0dba19e1ac0de495f17af3ed692a38e92d176a6c9e",label:"PONS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8097c1d1000eb657e75265384137041ac92856c8dc0b72c99569c3681320a430",label:"DELTA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6e6762ae397a2b3f2500ea2f48f8adce0eadfbf54cbc37f6108602e907e844ad",label:"INDEX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x378713071c58206c6a826287d0051bcae113d83d6e3d3b6370b7e73128d06162",label:"STONKBROKER/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x2695be2638c98241c887e4cad4eeba0f01137205f46b9e302edab04b5fee0570",label:"AVGO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x6c12c02536aa27831f713d658b59f74e149cc62b48528cb74455e79fab32f772",label:"GLD/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x298e8ff9b31f22be90507bc61b55e66ab93e78b55a60593035e309ed93137cb8",label:"RDDT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xb33399a677e1a21152fa9969f02c57a7a342e692ec45608a3fa0d3d92519c343",label:"COST/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x3be7fe1b6b439cfeb737d9921e9b83c92095a23a4f50aeee0d6d04f44446170f",label:"DJT/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0066bc47b87597993af0bca6f526175c0abae011b764d4bf12a3def45e1f4e78",label:"NFLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8c170f5c5df593791640ac9fbac297d59d08c2e92e86f38fe52d38e929e60fa3",label:"AMC/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x0f18d4fd8d86bd4d100b867b67e1fd38c80981fcd43e442313c2d5408da9352d",label:"LLY/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x7d4313cf1b0ede39395a2c7495dc1b1b47370caf51f70571d927f22e715e5f58",label:"LULU/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xa85928d77bd25cc348e13ea6587b8b3ca3793f4af5e5db8ca07d0f20fd5cfa99",label:"IBM/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x9d61e320efb766ce5c375032b399f08afe644b095a9cb0b2d6d1f6ab68399a6f",label:"F/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x43c51f6ff44ab406ab9c97cb5512c881f4a7498209f94bbcfd874d8f97fad79d",label:"HIMS/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe6284cf12d0603aee18ff5ab412e262cf99f120e967579111d7a51f37f276f54",label:"TTWO/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0xe8d9b45cdbedc4401a3145be7726c9f72b715e03c5399c961439f11636ee9fb6",label:"MRNA/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x46eea143d473cdb8587505f8886dad452037f285f7729a7763e8c233c63b2e8e",label:"RIVN/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x8338aed363a309039b2f271a83558831e7e445f2d13c6e72c576ec0b8a969415",label:"RBLX/USDG 38.5% (Longbow)",source:"longbow"},{marketId:"0x4e92b336ecad6c842be20ae2ae27b28b3cf5ced6c5388a808167c03a8d75fdf8",label:"SPY/WETH 38.5% (Longbow)",source:"longbow"},{marketId:"0x141c2b1d2bbecf7f8a76563307d7e5bf586457e873c3d97c4bb1502e57b77952",label:"NVDA/WETH 38.5% (Longbow)",source:"longbow"}],ya=new Map(tt.map(e=>[e.marketId.toLowerCase(),e]));function W(e){return ya.get(e.toLowerCase())}function ot(e){let t=W(e);return t?{actions:"enabled",label:t.label,source:ka[t.source]}:{actions:"read-only",reason:"Not in Oak's verified Morpho market registry; Oak builds no transactions for it."}}var Bt=20,ve=120n,_e=1000000n,He=1n,he=10n**18n,ga=10n**36n,Et=(1n<<128n)-1n,Sa=(1n<<256n)-1n,X=Ee(["function idToMarketParams(bytes32 id) view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv)","function market(bytes32 id) view returns (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee)","function position(bytes32 id, address user) view returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral)","function supplyCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, bytes data)","function withdrawCollateral((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, address onBehalf, address receiver)","function borrow((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsBorrowed, uint256 sharesBorrowed)","function repay((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsRepaid, uint256 sharesRepaid)","function supply((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) returns (uint256 assetsSupplied, uint256 sharesSupplied)","function withdraw((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn)"]),Aa=Ee(["function price() view returns (uint256)"]),Ia=Ee(["function borrowRateView((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee) market) view returns (uint256)"]),_t=Ee(["function deposit() payable"]);function ce(e){return{loanToken:e.loanToken,collateralToken:e.collateralToken,oracle:e.oracle,irm:e.irm,lltv:e.lltv.toString()}}function Ce(e,t){return e===0n?0n:(e+t-1n)/t}function xa(e,t,s){return e*(s+_e)/(t+He)}function Ta(e,t,s){return Ce(e*(s+_e),t+He)}function rt(e,t,s){return e*(t+He)/(s+_e)}function ne(e,t,s){return Ce(e*(t+He),s+_e)}function ke(e,t,s){return e*t/ga*s/he}function Ma(e,t,s){return t.startsWith("-")?`-${e.formatAmount(t.slice(1),s)}`:e.formatAmount(t,s)}function ye(e,t){let s=[],r={};for(let n of t.changes){let l=Ma(e,n.amount,n.token.decimals);s.push({token:n.token,amount:n.amount,formattedAmount:l}),r[n.token.address.toLowerCase()]=l}return{formattedChanges:s,formattedNetOutflows:r}}function Ht(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new i("Morpho marketId must be a 32-byte hex string.");return e.toLowerCase()}function qe(e){if(!e||typeof e!="object")throw new i("Morpho marketParams must be an object.");for(let a of[e.loanToken,e.collateralToken,e.oracle,e.irm])if(typeof a!="string"||!Re(a,{strict:!1}))throw new i("Morpho marketParams contains an invalid address.");let t=L(e.loanToken),s=L(e.collateralToken),r=L(e.oracle),n=L(e.irm),l=typeof e.lltv=="bigint"?e.lltv:Me(String(e.lltv));if(t===te||s===te||r===te)throw new i("Morpho marketParams loan, collateral, and oracle addresses must be non-zero.");if(l<=0n||l>=he)throw new i("Morpho marketParams LLTV must be between 0 and 1e18.");return{loanToken:t,collateralToken:s,oracle:r,irm:n,lltv:l}}function be(e){let t=qe(e),s=ma(J("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return fa(s)}function at(e){let t=e.toLowerCase();return t===dt.toLowerCase()||t===ct.toLowerCase()||t===te.toLowerCase()}function ge(e,t){let s=t??e.wallet;if(!s)throw new i("Provide a valid wallet address.");return q(s),L(s)}async function re(e,t,s){if(typeof e.call=="function"){let r=await e.call({to:t,data:s});if(r&&typeof r.data=="string")return r.data}if(typeof e.request=="function"){let r=await e.request({method:"eth_call",params:[{to:t,data:s},"latest"]});if(typeof r=="string")return r}throw new i(`Unable to execute eth_call on contract ${t}.`)}function qt(e){return typeof e=="string"&&/^[A-Za-z0-9$._+-]{1,32}$/.test(e)?e:"UNKNOWN"}async function Q(e,t,s=p){if(q(t),at(t))return{...ut,chainId:s};let r=L(t),n=r.toLowerCase();if(s===p){if(n===wa.toLowerCase())return mt;if(n===de.toLowerCase())return ft}let[l,a]=await Promise.all([re(e,r,R({abi:et,functionName:"symbol"})),re(e,r,R({abi:et,functionName:"decimals"}))]),[o]=oe(J("string"),l),[u]=oe(J("uint8"),a);return{address:r,symbol:qt(o),decimals:Number(u),chainId:s}}async function Ft(e,t){let s=await re(e,U,R({abi:X,functionName:"idToMarketParams",args:[t]})),[r,n,l,a,o]=oe(J("address, address, address, address, uint256"),s);return{loanToken:L(r),collateralToken:L(n),oracle:L(l),irm:L(a),lltv:o}}async function jt(e,t){let s=await re(e,U,R({abi:X,functionName:"market",args:[t]})),[r,n,l,a,o,u]=oe(J("uint128, uint128, uint128, uint128, uint128, uint128"),s);return{totalSupplyAssets:r,totalSupplyShares:n,totalBorrowAssets:l,totalBorrowShares:a,lastUpdate:o,fee:u}}async function Se(e,t,s){let r=await re(e,U,R({abi:X,functionName:"position",args:[t,L(s)]})),[n,l,a]=oe(J("uint256, uint128, uint128"),r);return{supplyShares:n,borrowShares:l,collateral:a}}async function Fe(e,t){let s=await re(e,L(t),R({abi:Aa,functionName:"price"})),[r]=oe(J("uint256"),s);return r}async function Pa(e,t,s){if(t.irm===te)return 0n;let r=await re(e,L(t.irm),R({abi:Ia,functionName:"borrowRateView",args:[t,s]})),[n]=oe(J("uint256"),r);return n}function je(e,t,s){let r=s>e.lastUpdate?s-e.lastUpdate:0n,n=t*r,l=Ce(n*n,2n*he),a=Ce(l*n,3n*he);return e.totalBorrowAssets+Ce(e.totalBorrowAssets*(n+l+a),he)}async function Le(e,t,s,r=0n){let[n,l]=await Promise.all([e.getBlock({blockTag:"latest"}),Pa(e,t,s)]),a=BigInt(Math.ceil(Date.now()/1e3)),o=(n.timestamp>a?n.timestamp:a)+r;return{totalBorrowAssets:je(s,l,o),accruedThrough:o,rate:l}}async function Vt(e,t,s){let r=await re(e,L(t),R({abi:et,functionName:"balanceOf",args:[L(s)]})),[n]=oe(J("uint256"),r);return n}async function ue(e,t,s=!1){let r=t.marketId,n=t.marketParams;if(!r&&!n)throw new i("Provide either marketId or marketParams for the Morpho Blue market.");let l=n?qe(n):void 0,a=l?be(l):void 0,o=r!==void 0?Ht(r):void 0;if(o&&a&&o!==a.toLowerCase())throw new i(`MarketParams tuple hash (${a}) does not match marketId (${o}).`);let u=(o??a).toLowerCase();if(s&&!W(u))throw new i(`Morpho actions require a known market from Oak's verified registry, which pins its oracle. Find one with morpho_status {"discover":true}; other markets are read-only.`);let[d,m]=await Promise.all([Ft(e,u),jt(e,u)]);if(d.loanToken===te||d.collateralToken===te||d.lltv===0n||m.lastUpdate===0n)throw new i(`Morpho market ${u} is not initialized on chain ${p}.`);let c=be(d);if(c.toLowerCase()!==u.toLowerCase())throw new i(`On-chain idToMarketParams tuple hash (${c}) does not match marketId (${u}).`);if(l&&!(l.loanToken.toLowerCase()===d.loanToken.toLowerCase()&&l.collateralToken.toLowerCase()===d.collateralToken.toLowerCase()&&l.oracle.toLowerCase()===d.oracle.toLowerCase()&&l.irm.toLowerCase()===d.irm.toLowerCase()&&l.lltv===d.lltv))throw new i(`Provided marketParams tuple does not match on-chain idToMarketParams for ${u}.`);return{marketId:u,marketParams:d,marketState:m}}function Ae(e){if(e.assets!==void 0&&e.amount!==void 0)throw new i("Specify either assets or amount, not both.");let t=e.assets??e.amount;if(typeof t!="string")throw new i("Provide an amount as a base-unit integer string.");let s=Me(t);if(s<=0n||s>Et)throw new i("Asset amount must be greater than zero and fit in uint128.");return s}function Ie(e,t){for(let s of["onBehalf","receiver"])if(e[s]!==void 0&&(typeof e[s]!="string"||e[s].toLowerCase()!==t.toLowerCase()))throw new i(`Morpho ${s} must be the wallet; overrides are not supported.`);if(e.data!==void 0&&e.data!=="0x")throw new i("Morpho callback data must be empty (0x).")}async function va(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=e.clientFor(p),{marketId:a,marketParams:o}=await ue(l,t,!0),u=await Q(l,o.collateralToken,p),d=o.collateralToken.toLowerCase()===de.toLowerCase(),m=typeof t.collateralToken=="string"?(q(t.collateralToken),L(t.collateralToken)):void 0,c=z("wrapNative",t.wrapNative)===!0||m!==void 0&&at(m);if(m&&!at(m)&&m.toLowerCase()!==o.collateralToken.toLowerCase())throw new i(`Collateral token ${m} does not match market collateral ${o.collateralToken}.`);if(c&&!d)throw new i("Native ETH wrapping is only supported when market collateralToken is WETH.");let f=Ae(t),b=f.toString(),w=e.formatAmount(b,u.decimals),h=[];c&&h.push(e.unsignedTx({chainId:p,to:de,data:R({abi:_t,functionName:"deposit"}),value:b,description:`Wrap ${w} ETH into WETH at ${de}.`})),h.push(e.approval(o.collateralToken,U,b,p)),h.push(e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"supplyCollateral",args:[o,f,n,"0x"]}),value:"0",description:`Supply ${w} ${u.symbol} (${b} base units) collateral to Morpho market ${a}.`}));let y=await e.preview(h,r),{formattedChanges:k,formattedNetOutflows:g}=ye(e,y);return{action:"morpho_supply_collateral",chainId:p,marketId:a,marketParams:ce(o),collateralToken:u,assets:b,formattedAssets:w,onBehalf:n,txs:h,summary:`${c?`Send ${w} ETH to wrap into WETH. `:""}Supply ${w} ${u.symbol} collateral to Morpho Blue market ${a}.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ca(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=r,a=e.clientFor(p),{marketId:o,marketParams:u,marketState:d}=await ue(a,t,!0),[m,c,f,b]=await Promise.all([Q(a,u.loanToken,p),Se(a,o,n),Fe(a,u.oracle),Le(a,u,d,ve)]),w=Ae(t),h=w.toString(),y=e.formatAmount(h,m.decimals),k=d.totalSupplyAssets>d.totalBorrowAssets?d.totalSupplyAssets-d.totalBorrowAssets:0n;if(w>k)throw new i(`Insufficient market liquidity: requested ${h} base units, available ${k.toString()} base units.`);let g=ke(c.collateral,f,u.lltv),T=ne(c.borrowShares,b.totalBorrowAssets,d.totalBorrowShares);if(c.collateral===0n||T+w>g)throw new i(`Insufficient collateral or unhealthy borrow: total debt ${(T+w).toString()} exceeds max borrow ${g.toString()} base units.`);let I=Ta(w,b.totalBorrowAssets,d.totalBorrowShares),C=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"borrow",args:[u,w,0n,n,l]}),value:"0",description:`Borrow ${y} ${m.symbol} (${h} base units) from Morpho market ${o}.`})],v=await e.preview(C,r),{formattedChanges:x,formattedNetOutflows:G}=ye(e,v);return{action:"morpho_borrow",chainId:p,marketId:o,marketParams:ce(u),loanToken:m,assets:h,formattedAssets:y,borrowShares:I.toString(),onBehalf:n,receiver:l,txs:C,summary:`Borrow ${y} ${m.symbol} from Morpho Blue market ${o}.`,preview:v,formattedChanges:x,formattedNetOutflows:G}}async function La(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=e.clientFor(p);if(t.shares!==void 0){let x=Me(t.shares);if(x<=0n||x===Sa||x>Et)throw new i("Morpho Blue core does not accept maxUint256 or out-of-range share sentinels; pass exact position.borrowShares.")}if(z("repayAll",t.repayAll)===!0&&(t.shares!==void 0||t.assets!==void 0||t.amount!==void 0))throw new i("Specify repayAll alone, without shares or assets/amount.");if(t.shares!==void 0&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify either assets/amount or shares for Morpho repay, not both.");let{marketId:a,marketParams:o,marketState:u}=await ue(l,t,!0),[d,m,c]=await Promise.all([Q(l,o.loanToken,p),Se(l,a,n),Vt(l,o.loanToken,r)]);if(m.borrowShares===0n)throw new i(`Position has no active borrow debt on Morpho market ${a}.`);let f=0n,b=0n;if(z("repayAll",t.repayAll)===!0)b=m.borrowShares;else if(t.shares!==void 0){let x=Me(t.shares);if(x>m.borrowShares)throw new i(`Repay shares (${x.toString()}) exceed current position borrowShares (${m.borrowShares.toString()}).`);b=x}else f=Ae(t);let w=b>0n?await Le(l,o,u,ve):void 0,h=b>0n?ne(b,w.totalBorrowAssets,u.totalBorrowShares):f;if(c<h)throw new i(`Insufficient loan token balance for repayment: wallet holds ${c.toString()} base units, but ${h.toString()} base units are required (including accrued interest).`);let y=h.toString(),k=e.formatAmount(y,d.decimals),g=e.approval(o.loanToken,U,y,p),T=e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"repay",args:[o,f,b,n,"0x"]}),value:"0",description:b>0n?`Repay ${b.toString()} borrow shares (${k} ${d.symbol}) on Morpho market ${a}.`:`Repay ${k} ${d.symbol} (${f.toString()} base units) on Morpho market ${a}.`}),I=[g,T],M=await e.preview(I,r),{formattedChanges:C,formattedNetOutflows:v}=ye(e,M);return{action:"morpho_repay",chainId:p,marketId:a,marketParams:ce(o),loanToken:d,repayAssets:f.toString(),repayShares:b.toString(),requiredAssets:y,...w?{accruedThrough:w.accruedThrough.toString(),borrowRatePerSecond:w.rate.toString(),inclusionSeconds:ve.toString()}:{},formattedRequiredAssets:k,onBehalf:n,txs:I,summary:b>0n?`Repay ${b.toString()} borrow shares (approval up to ${k} ${d.symbol}) on Morpho Blue market ${a}. Refresh if signing/inclusion takes more than ${ve} seconds.`:`Repay ${k} ${d.symbol} on Morpho Blue market ${a}.`,preview:M,formattedChanges:C,formattedNetOutflows:v}}async function $a(e,t,s){let r=ge(t,s);Ie(t,r);let n=r,l=r,a=e.clientFor(p),{marketId:o,marketParams:u,marketState:d}=await ue(a,t,!0),[m,c,f,b]=await Promise.all([Q(a,u.collateralToken,p),Se(a,o,n),Fe(a,u.oracle),Le(a,u,d,ve)]),w=z("withdrawAll",t.withdrawAll)===!0?c.collateral:Ae(t);if(w<=0n||w>c.collateral)throw new i(`Insufficient collateral to withdraw: requested ${w.toString()} base units, position holds ${c.collateral.toString()} base units.`);if(c.borrowShares>0n){let C=c.collateral-w,v=ke(C,f,u.lltv),x=ne(c.borrowShares,b.totalBorrowAssets,d.totalBorrowShares);if(x>v)throw new i(`Unhealthy collateral withdrawal: remaining max borrow ${v.toString()} would fall below current debt ${x.toString()} base units.`)}let h=w.toString(),y=e.formatAmount(h,m.decimals),g=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"withdrawCollateral",args:[u,w,n,l]}),value:"0",description:`Withdraw ${y} ${m.symbol} (${h} base units) collateral from Morpho market ${o}.`})],T=await e.preview(g,r),{formattedChanges:I,formattedNetOutflows:M}=ye(e,T);return{action:"morpho_withdraw_collateral",chainId:p,marketId:o,marketParams:ce(u),collateralToken:m,assets:h,formattedAssets:y,onBehalf:n,receiver:l,txs:g,summary:`Withdraw ${y} ${m.symbol} collateral from Morpho Blue market ${o}.`,preview:T,formattedChanges:I,formattedNetOutflows:M}}async function Da(e,t,s){let r=ge(t,s);Ie(t,r);let n=e.clientFor(p),{marketId:l,marketParams:a,marketState:o}=await ue(n,t,!0),u=z("wrapNative",t.wrapNative)===!0;if(u&&a.loanToken.toLowerCase()!==de.toLowerCase())throw new i("Native ETH wrapping is only supported when the market loanToken is WETH.");let d=Ae(t),m=d.toString(),[c,f]=await Promise.all([Q(n,a.loanToken,p),u?Promise.resolve(d):Vt(n,a.loanToken,r)]);if(f<d)throw new i(`Insufficient ${c.symbol} balance to lend: wallet holds ${f.toString()} base units, requested ${m}.`);let b=e.formatAmount(m,c.decimals),w=[];u&&w.push(e.unsignedTx({chainId:p,to:de,data:R({abi:_t,functionName:"deposit"}),value:m,description:`Wrap ${b} ETH into WETH at ${de}.`})),w.push(e.approval(a.loanToken,U,m,p)),w.push(e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"supply",args:[a,d,0n,r,"0x"]}),value:"0",description:`Lend ${b} ${c.symbol} (${m} base units) to Morpho market ${l}.`}));let h=xa(d,o.totalSupplyAssets,o.totalSupplyShares),y=await e.preview(w,r),{formattedChanges:k,formattedNetOutflows:g}=ye(e,y);return{action:"morpho_supply",chainId:p,marketId:l,marketParams:ce(a),loanToken:c,assets:m,formattedAssets:b,supplySharesEstimated:h.toString(),onBehalf:r,oak:ot(l),txs:w,summary:`${u?`Send ${b} ETH to wrap into WETH. `:""}Lend ${b} ${c.symbol} to Morpho Blue market ${l}. It earns the market supply rate and is exposed to the market's collateral, oracle and liquidity risk.`,preview:y,formattedChanges:k,formattedNetOutflows:g}}async function Ua(e,t,s){let r=ge(t,s);Ie(t,r);let n=e.clientFor(p),l=z("withdrawAll",t.withdrawAll)===!0;if(l&&(t.assets!==void 0||t.amount!==void 0))throw new i("Specify withdrawAll alone, without assets/amount.");let{marketId:a,marketParams:o,marketState:u}=await ue(n,t,!0),[d,m]=await Promise.all([Q(n,o.loanToken,p),Se(n,a,r)]);if(m.supplyShares===0n)throw new i(`This wallet has no lent ${d.symbol} on Morpho market ${a}.`);let c=rt(m.supplyShares,u.totalSupplyAssets,u.totalSupplyShares),f=l?0n:Ae(t),b=l?m.supplyShares:0n;if(!l&&f>c)throw new i(`Withdrawal exceeds the lent balance: requested ${f.toString()} base units, position holds about ${c.toString()}. Use withdrawAll for a full exit.`);let w=u.totalSupplyAssets>u.totalBorrowAssets?u.totalSupplyAssets-u.totalBorrowAssets:0n,h=l?c:f;if(h>w)throw new i(`Insufficient market liquidity: withdrawing ${h.toString()} base units needs idle assets, but only ${w.toString()} are available until borrowers repay. Withdraw at most that amount, or retry later.`);let y=e.formatAmount(h.toString(),d.decimals),g=[e.unsignedTx({chainId:p,to:U,data:R({abi:X,functionName:"withdraw",args:[o,f,b,r,r]}),value:"0",description:l?`Withdraw all ${m.supplyShares.toString()} supply shares (about ${y} ${d.symbol}) from Morpho market ${a}.`:`Withdraw ${y} ${d.symbol} (${f.toString()} base units) of lent assets from Morpho market ${a}.`})],T=await e.preview(g,r),{formattedChanges:I,formattedNetOutflows:M}=ye(e,T);return{action:"morpho_withdraw",chainId:p,marketId:a,marketParams:ce(o),loanToken:d,withdrawAssets:f.toString(),withdrawShares:b.toString(),estimatedAssets:h.toString(),formattedAssets:y,receiver:r,txs:g,summary:l?`Withdraw all lent ${d.symbol} (about ${y}, including interest) from Morpho Blue market ${a}.`:`Withdraw ${y} lent ${d.symbol} from Morpho Blue market ${a}.`,preview:T,formattedChanges:I,formattedNetOutflows:M}}async function zt(e,t,s){let r=await e.http(pa,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:t,variables:s})});if(!r.ok)throw new i(`Morpho GraphQL request failed (HTTP ${r.status}).`);let n=await r.json();if(n.errors?.length)throw new i("Morpho GraphQL returned query errors.");return n.data??{}}async function Wt(e){let t=`query Markets($chainId: Int!) {
|
|
2
2
|
markets(first: 1000, where: { chainId_in: [$chainId] }) {
|
|
3
3
|
items {
|
|
4
4
|
marketId chain { id } lltv listed
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as Me,d as Ce,e as we,f as ie,i as be,j as Ne}from"./HVM2EEXB.js";import{b as ne,o as ge}from"./GHPREYQK.js";import{a as O,b as me}from"./PBQSJSZO.js";import{a as Ue}from"./BQICZFLR.js";import{a as W,c as Te}from"./UP7FBDMJ.js";import{a as k,i as _}from"./FWD4L3CJ.js";import{a as c,b as te,e as T}from"./XSD5NL7J.js";import{decodeFunctionResult as he,encodeFunctionData as R,getAddress as l,parseAbi as Z,zeroAddress as M}from"viem";var re=-887272,se=887272,z=(1n<<128n)-1n,ze="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Ge="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",je="0x3067048beee31b25b2f1681f88dac838c8bba36af25bfb2b7cf7473a5847e35f",oe=2000n,Ke=5,$e=64n,Qe=1800n,f=Object.freeze({factory:l(_[4663].uniswap.v3_factory.address),positionManager:l(_[4663].uniswap.v3_position_manager.address),swapRouter02:l(_[4663].uniswap.swap_router02.address),permit2:l(_[4663].uniswap.permit2.address),weth:l(_[4663].uniswap.WETH.address),usdg:l(_[4663].uniswap.USDG.address),ethUsdgPool:l(_[4663].oracle.ethUsdgPool.address)}),ve=Object.freeze({100:1,500:10,3e3:60,1e4:200}),ht=Object.freeze([{fee:100,tickSpacing:1,address:l("0x52e65B17fB6E5BA00Ed806f37Afcd2DaA50271Ca"),token0:f.weth,token1:f.usdg,recordedLiquidity:"1957537485734736219",recordedSqrtPriceX96:"3839219776288481168641554",recordedTick:-198707,feeProtocol:68},{fee:500,tickSpacing:10,address:l("0x69bfaf19c9f377bb306a89aed9f6b07e2c1a8d9a"),token0:f.weth,token1:f.usdg,recordedLiquidity:"714542894544667104",recordedSqrtPriceX96:"3839644024453020182443671",recordedTick:-198705,feeProtocol:68},{fee:3e3,tickSpacing:60,address:l("0xa9188730fe85be88ad499d7d52b099e800fb0334"),token0:f.weth,token1:f.usdg,recordedLiquidity:"310559629687003603",recordedSqrtPriceX96:"3843235825752878635548672",recordedTick:-198686,feeProtocol:102},{fee:1e4,tickSpacing:200,address:l("0x5f009e071f07e92b6c624e83f52f17bbda34680d"),token0:f.weth,token1:f.usdg,recordedLiquidity:"5822966536584155",recordedSqrtPriceX96:"3853297838190389678059735",recordedTick:-198634,feeProtocol:102}]),v=Z(["function positions(uint256 tokenId) view returns (uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1)","function ownerOf(uint256 tokenId) view returns (address)","function balanceOf(address owner) view returns (uint256)","function tokenOfOwnerByIndex(address owner, uint256 index) view returns (uint256)","function mint((address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline) params) payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)","function increaseLiquidity((uint256 tokenId, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, uint256 deadline) params) payable returns (uint128 liquidity, uint256 amount0, uint256 amount1)","function decreaseLiquidity((uint256 tokenId, uint128 liquidity, uint256 amount0Min, uint256 amount1Min, uint256 deadline) params) payable returns (uint256 amount0, uint256 amount1)","function collect((uint256 tokenId, address recipient, uint128 amount0Max, uint128 amount1Max) params) payable returns (uint256 amount0, uint256 amount1)","function burn(uint256 tokenId) payable","function createAndInitializePoolIfNecessary(address token0, address token1, uint24 fee, uint160 sqrtPriceX96) payable returns (address pool)"]),Q=Z(["function getPool(address tokenA, address tokenB, uint24 fee) view returns (address pool)","function feeAmountTickSpacing(uint24 fee) view returns (int24)"]),ke=Z(["function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)","function liquidity() view returns (uint128)","function tickSpacing() view returns (int24)","function fee() view returns (uint24)","function token0() view returns (address)","function token1() view returns (address)"]),Ye=Z(["function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)"]),ye=Z(["function decimals() view returns (uint8)","function symbol() view returns (string)","function allowance(address owner, address spender) view returns (uint256)"]),Ze="0xd0e30db0";function Je(t){if(typeof t!="string")return!1;let e=t.trim().toLowerCase();return e===M||e===ze||e==="eth"||e==="native"}function E(t,e){if(Je(t))throw new c(`Uniswap v3 requires wrapped ERC-20 WETH (${f.weth}) rather than native ETH in ${e}.`);if(typeof t!="string")throw new c(`${e} must be a valid 20-byte hex address.`);return O(t),l(t)}function et(t,e,n){let a=Number(t),i=Number(e),o=Number(n);if(!Number.isInteger(o)||o<=0)throw new c("Uniswap v3 tickSpacing must be a positive integer.");if(!Number.isInteger(a)||!Number.isInteger(i))throw new c("Uniswap v3 tickLower and tickUpper must be integers.");if(a<re||i>se||a>se||i<re)throw new c(`Uniswap v3 ticks are out of bounds [${re}, ${se}].`);if(a>=i)throw new c("Uniswap v3 tickLower must be strictly less than tickUpper.");if(a%o!==0||i%o!==0)throw new c(`Uniswap v3 tickLower (${a}) and tickUpper (${i}) must be divisible by tickSpacing (${o}).`);return{tickLower:a,tickUpper:i,tickSpacing:o}}function tt(t,e){let n=t.trim(),a=n.startsWith("-"),i=a||n.startsWith("+")?n.slice(1):n,o=Te(W(i).toString(),e);return a&&o!=="0"?`-${o}`:o}function nt(t){let e=typeof t=="string"?he({abi:v,functionName:"positions",data:t}):t;return{nonce:BigInt(e[0]),operator:l(String(e[1])),token0:l(String(e[2])),token1:l(String(e[3])),fee:Number(e[4]),tickLower:Number(e[5]),tickUpper:Number(e[6]),liquidity:BigInt(e[7]),feeGrowthInside0LastX128:BigInt(e[8]),feeGrowthInside1LastX128:BigInt(e[9]),tokensOwed0:BigInt(e[10]),tokensOwed1:BigInt(e[11])}}function Le(t,e){if(!t||!Array.isArray(t.logs))return[];let n=e?l(e).toLowerCase():void 0,a=f.positionManager.toLowerCase(),i=new Set;for(let o of t.logs){if(!o||typeof o.address!="string"||o.address.toLowerCase()!==a)continue;let r=Array.isArray(o.topics)?o.topics.map(u=>String(u).toLowerCase()):[],s=r[0];if(s===Ge&&r.length>=4){let d=`0x${r[2].slice(-40)}`;if(!n||d===n){let p=BigInt(r[3]).toString();p!=="0"&&i.add(p)}}else if(s===je&&r.length>=2&&!n){let u=BigInt(r[1]).toString();u!=="0"&&i.add(u)}}return[...i]}function vt(t){let e=n=>typeof n=="bigint"?n:W(n);return R({abi:Ye,functionName:"exactInputSingle",args:[{tokenIn:l(t.tokenIn),tokenOut:l(t.tokenOut),fee:t.fee,recipient:l(t.recipient),amountIn:e(t.amountIn),amountOutMinimum:e(t.amountOutMinimum),sqrtPriceLimitX96:t.sqrtPriceLimitX96!==void 0?e(t.sqrtPriceLimitX96):0n}]})}var Re=1n<<96n;function _e(t){let e=Math.abs(t),n=(e&1)!==0?0xfffcb933bd6fad37aa2d162d1a594001n:0x100000000000000000000000000000000n;return(e&2)!==0&&(n=n*0xfff97272373d413259a46990580e213an>>128n),(e&4)!==0&&(n=n*0xfff2e50f5f656932ef12357cf3c7fdccn>>128n),(e&8)!==0&&(n=n*0xffe5caca7e10e4e61c3624eaa0941cd0n>>128n),(e&16)!==0&&(n=n*0xffcb9843d60f6159c9db58835c926644n>>128n),(e&32)!==0&&(n=n*0xff973b41fa98c081472e6896dfb254c0n>>128n),(e&64)!==0&&(n=n*0xff2ea16466c96a3843ec78b326b52861n>>128n),(e&128)!==0&&(n=n*0xfe5dee046a99a2a811c461f1969c3053n>>128n),(e&256)!==0&&(n=n*0xfcbe86c7900a88aedcffc83b479aa3a4n>>128n),(e&512)!==0&&(n=n*0xf987a7253ac413176f2b074cf7815e54n>>128n),(e&1024)!==0&&(n=n*0xf3392b0822b70005940c7a398e4b70f3n>>128n),(e&2048)!==0&&(n=n*0xe7159475a2c29b7443b29c7fa6e889d9n>>128n),(e&4096)!==0&&(n=n*0xd097f3bdfd2022b8845ad8f792aa5825n>>128n),(e&8192)!==0&&(n=n*0xa9f746462d870fdf8a65dc1f90e061e5n>>128n),(e&16384)!==0&&(n=n*0x70d869a156d2a1b890bb3df62baf32f7n>>128n),(e&32768)!==0&&(n=n*0x31be135f97d08fd981231505542fcfa6n>>128n),(e&65536)!==0&&(n=n*0x9aa508b5b7a84e1c677de54f3e99bc9n>>128n),(e&131072)!==0&&(n=n*0x5d6af8dedb81196699c329225ee604n>>128n),(e&262144)!==0&&(n=n*0x2216e584f5fa1ea926041bedfe98n>>128n),(e&524288)!==0&&(n=n*0x48a170391f7dc42444e8fa2n>>128n),t>0&&(n=((1n<<256n)-1n)/n),(n>>32n)+(n%(1n<<32n)===0n?0n:1n)}function it(t,e,n,a){if(a<=0n)return{amount0:0n,amount1:0n};let[i,o]=e<n?[e,n]:[n,e];if(t<=i)return{amount0:(a<<96n)*(o-i)/o/i,amount1:0n};if(t<o){let s=(a<<96n)*(o-t)/o/t,u=a*(t-i)/Re;return{amount0:s,amount1:u}}return{amount0:0n,amount1:a*(o-i)/Re}}async function C(t,e,n,a){let i=l(e),o,r;if(n===k&&i===f.weth?(o=18,r="WETH"):n===k&&i===f.usdg&&(o=6,r="USDG"),o===void 0){let s=await t.readContract({address:i,abi:ye,functionName:"decimals"});o=Number(s)}if(r===void 0)try{let s=await t.readContract({address:i,abi:ye,functionName:"symbol"});if(typeof s!="string"||!s.trim())throw new c("Token symbol is unavailable.");r=Ne(s.trim(),i)}catch(s){throw new c(`Could not read token metadata. ${T(s)}`)}if(!Number.isInteger(o)||o<0||o>255)throw new c("Token decimals are invalid.");if(a!=null){let s=Number(a);if(!Number.isInteger(s)||s!==o)throw new c(`Token ${i} on chain ${n} has ${o} decimals, not ${String(a)}.`)}return{address:i,symbol:r,decimals:o,chainId:n}}async function ot(t){try{if(!t.getBlock)throw new c("Block timestamps are unavailable.");let e=await t.getBlock();if(typeof e.timestamp!="bigint")throw new c("Invalid block timestamp.");return e.timestamp}catch(e){throw new c(`Could not read the current block timestamp. ${T(e)}`)}}function J(t,e){if(typeof t=="bigint"){if(t<0n)throw new c(`${e} must be a non-negative integer.`);return t}if(typeof t=="number"){if(!Number.isSafeInteger(t)||t<0)throw new c(`${e} must be a non-negative integer.`);return BigInt(t)}if(typeof t=="string")return W(t);throw new c(`${e} must be a non-negative integer.`)}async function Ee(t,e){let n=await ot(t);if(e==null)return n+Qe;let a=J(e,"deadline");if(a<=n)throw new c(`Uniswap v3 deadline (${a.toString()}) has expired at timestamp ${n.toString()}.`);return a}function V(t,e){if(typeof t!="string"||!/^\d+$/.test(t))throw new c(`${e} must be a non-negative integer string in base units.`);return W(t)}function Be(t){let e=t.slippageBps??ne;if(typeof e!="number")throw new c("Slippage must be an integer from 0 to 9999 bps.");return ge("0",e),e}function ae(t,e,n,a){let i=t===void 0?W(ge(e.toString(),n)):V(t,a);if(i<=1n)throw new c(`${a} must exceed 1 base unit; the simulated amount may be too small.`);return i}function X(t,e){return me({to:f.positionManager,data:t,value:"0",chainId:k,description:e})}async function Y(t,e,n){try{if(!t.request)throw new c("Sequential transaction simulation is unavailable.");let i=await t.request({method:"eth_simulateV1",params:[{blockStateCalls:[{calls:e.map(o=>({from:n,gas:`0x${Ue.toString(16)}`,to:o.to,data:o.data,value:`0x${BigInt(o.value).toString(16)}`}))}],validation:!1,traceTransfers:!0},"latest"]},{retryCount:0});if(!Array.isArray(i)||i.length!==1||!Array.isArray(i[0]?.calls)||i[0].calls.length!==e.length)throw new c("Unexpected batch simulation response.");return i[0].calls.map((o,r)=>{if(o.status!=="0x1"||o.error||typeof o.returnData!="string"||!/^0x([a-fA-F0-9]{2})*$/.test(o.returnData))throw new c(`Simulation call ${r+1} failed. ${T(o.error)}`);return o.returnData})}catch(a){throw new c(`Uniswap v3 simulation failed. ${T(a)}`)}}function ce(t,e){try{return he({abi:v,functionName:t,data:e})}catch{throw new c(`Uniswap v3 ${t} simulation returned invalid amounts.`)}}function De(t,e,n){if(t.initialPrice!==void 0&&t.sqrtPriceX96!==void 0)throw new c("Provide initialPrice or sqrtPriceX96, not both.");if(t.sqrtPriceX96!==void 0){if(typeof t.sqrtPriceX96!="string"||!/^\d+$/.test(t.sqrtPriceX96))throw new c("sqrtPriceX96 must be a non-negative integer string.");return Ce(BigInt(t.sqrtPriceX96))}if(t.initialPrice===void 0)throw new c("A new pool needs initialPrice (token1 per 1 token0, human units) or sqrtPriceX96.");return Me(t.initialPrice,e,n)}async function Oe(t,e,n,a){let i=[];for(let o of Object.keys(ve).map(Number)){if(o===a)continue;let r=l(String(await t.readContract({address:f.factory,abi:Q,functionName:"getPool",args:[e,n,o]})));if(r===M||BigInt(await t.readContract({address:r,abi:ke,functionName:"liquidity"}))===0n)continue;let u=await t.readContract({address:r,abi:ke,functionName:"slot0"});i.push({label:`v3 fee ${o} pool ${r}`,sqrtPriceX96:BigInt(u[0])})}return i}function G(t,e={}){if(e.chainId!==void 0&&Number(e.chainId)!==k)throw new c(`Uniswap v3 is only supported on Robinhood Chain (${k}).`);if(e.version!==void 0&&e.version!=="v3")throw new c(`Uniswap v3 handler received unsupported version "${String(e.version)}".`);let n=t.clientFor(k);return{...n,readContract:async a=>{try{return await n.readContract(a)}catch(i){throw new c(`Could not read Uniswap v3 ${a.functionName}. ${T(i)}`,{cause:i})}}}}async function xe(t,e,n){let a;try{a=await t.readContract({address:f.positionManager,abi:v,functionName:"ownerOf",args:[e]})}catch(r){throw new c(`Could not verify owner of Uniswap v3 position #${e}. ${T(r)}`)}let i=l(String(a)),o=l(n);if(i!==o)throw new c(`Wallet ${o} is not the owner of Uniswap v3 position #${e.toString()} (owned by ${i}).`);return i}async function de(t,e){let n=await t.readContract({address:f.positionManager,abi:v,functionName:"positions",args:[e]});return nt(n)}function Ie(t,e){if(!Array.isArray(e.changes)||!e.changes.length)return t;let n=e.changes.map(a=>`${tt(a.amount,a.token.decimals)} ${a.token.symbol}`);return`${t} (${n.join(", ")})`}async function rt(t,e,n){O(n);let a=l(n),i=G(t,e),o=await Ee(i,e.deadline),r=Be(e),s=e.tokenId===void 0?void 0:J(e.tokenId,"tokenId"),u;if(s!==void 0){if(s<=0n)throw new c("Uniswap v3 tokenId must be a positive integer.");await xe(i,s,a),u=await de(i,s)}let d=u?.token0??E(e.token0,"token0"),p=u?.token1??E(e.token1,"token1");if(BigInt(d)>=BigInt(p))throw new c("Uniswap v3 requires distinct sorted token addresses.");let m=u?.fee??Number(e.fee??100),g=ve[m];if(!g)throw new c("Unsupported Uniswap v3 fee tier.");let y=l(String(await i.readContract({address:f.factory,abi:Q,functionName:"getPool",args:[d,p,m]}))),h=e.initialPrice!==void 0||e.sqrtPriceX96!==void 0;if(y===M&&!h)throw new c("No Uniswap v3 pool exists for these tokens and fee tier. To create it and add the first liquidity in one tool call with separately confirmed transactions, add initialPrice (token1 per 1 token0, human units) to this call; to create it without liquidity use uniswap_create_pool.");if(y!==M&&h)throw new c(`The Uniswap v3 pool already exists at ${y}; remove initialPrice/sqrtPriceX96 to add liquidity at its current price.`);if(s!==void 0&&h)throw new c("initialPrice cannot be combined with tokenId.");if(e.fullRange!==void 0&&typeof e.fullRange!="boolean")throw new c("fullRange must be a boolean.");if(e.fullRange===!0&&(e.tickLower!==void 0||e.tickUpper!==void 0||u))throw new c("Use fullRange only for a new position, without explicit ticks. Existing position ticks cannot change.");let{tickLower:S,tickUpper:N,tickSpacing:U}=et(u?.tickLower??(e.fullRange===!0?Math.ceil(re/g)*g:e.tickLower),u?.tickUpper??(e.fullRange===!0?Math.floor(se/g)*g:e.tickUpper),g),w=await C(i,d,k,e.token0Decimals),b=await C(i,p,k,e.token1Decimals),P;if(y===M){let q=De(e,w.decimals,b.decimals),L=be(q,await Oe(i,d,p,m),e.acceptPriceDeviation===!0,w.decimals,b.decimals);P={sqrtPriceX96:q,note:L}}let x=V(e.amount0Desired,"amount0Desired"),I=V(e.amount1Desired,"amount1Desired");if(x===0n&&I===0n)throw new c("Liquidity addition requires a positive desired amount.");let $=e.recipient===void 0?a:E(e.recipient,"recipient");if($!==a)throw new c("Uniswap recipient must be the signing wallet.");if(e.wrapNative===!0&&d!==f.weth&&p!==f.weth)throw new c("Wrapping requires a positive WETH desired amount.");let H=await Promise.all([d,p].map(async q=>BigInt(await i.readContract({address:q,abi:ye,functionName:"allowance",args:[a,f.positionManager]})))),j=(q,L)=>{let pe=[];if(e.wrapNative===!0){let K=d===f.weth?q:L;K>0n&&pe.push(me({to:f.weth,data:Ze,value:K.toString(),chainId:k,description:"Wrap ETH into WETH."}))}for(let[K,We]of[d,p].entries()){let fe=K===0?q:L;fe>0n&&H[K]<fe&&pe.push(t.approval(We,f.positionManager,fe.toString(),k))}return pe},F=s===void 0?"mint":"increaseLiquidity",B=(q,L)=>X(s===void 0?R({abi:v,functionName:"mint",args:[{token0:d,token1:p,fee:m,tickLower:S,tickUpper:N,amount0Desired:x,amount1Desired:I,amount0Min:q,amount1Min:L,recipient:$,deadline:o}]}):R({abi:v,functionName:"increaseLiquidity",args:[{tokenId:s,amount0Desired:x,amount1Desired:I,amount0Min:q,amount1Min:L,deadline:o}]}),`${F==="mint"?"Mint":"Increase"} Uniswap v3 ${w.symbol}/${b.symbol} liquidity.`),D=P&&X(R({abi:v,functionName:"createAndInitializePoolIfNecessary",args:[d,p,m,P.sqrtPriceX96]}),`Create and initialize the Uniswap v3 ${w.symbol}/${b.symbol} fee ${m} pool at ${ie(P.sqrtPriceX96,w.decimals,b.decimals)} ${b.symbol} per ${w.symbol}.`),Pe=D?[D]:[],Se=await Y(i,[...Pe,...j(x,I),B(0n,0n)],a),A=ce(F,Se[Se.length-1]),He=A[A.length-2],Fe=A[A.length-1];if(He>x||Fe>I)throw new c("Simulated liquidity spend exceeds the desired amounts.");let ee=[...Pe,...j(x,I)],ue=ae(e.amount0Min,A[A.length-2],r,"amount0Min"),le=ae(e.amount1Min,A[A.length-1],r,"amount1Min");if(ue>x||le>I)throw new c("Uniswap v3 minimum amount cannot exceed desired amount.");let Ae=B(ue,le);ee.push(Ae);for(let[q,L]of[d,p].entries())(q===0?x:I)>0n&&ee.push(t.approval(L,f.positionManager,"0",k));let qe=await t.preview(ee,a);return{txs:ee,preview:qe,summary:Ie(Ae.description,qe),details:{version:"v3",action:F,...s===void 0?{}:{tokenId:s.toString()},pool:y===M?null:y,fee:m,tickSpacing:U,tickLower:S,tickUpper:N,token0:w,token1:b,amount0Desired:x.toString(),amount1Desired:I.toString(),amount0Min:ue.toString(),amount1Min:le.toString(),deadline:o.toString(),recipient:$,expectedAmount0:A[A.length-2].toString(),expectedAmount1:A[A.length-1].toString(),...P?{poolCreated:!0,sqrtPriceX96:P.sqrtPriceX96.toString(),initialPrice:ie(P.sqrtPriceX96,w.decimals,b.decimals),initialTick:we(P.sqrtPriceX96),priceCheck:P.note}:{}}}}async function st(t,e,n){O(n);let a=l(n),i=G(t,e),o=E(e.token0,"token0"),r=E(e.token1,"token1");if(BigInt(o)>=BigInt(r))throw new c(`Uniswap v3 requires sorted token addresses (token0 < token1). Use token0=${BigInt(o)<BigInt(r)?o:r}, token1=${BigInt(o)<BigInt(r)?r:o}; initialPrice is token1 per 1 token0 in that order.`);let s=Number(e.fee),u=ve[s];if(!u){let b=Number(await i.readContract({address:f.factory,abi:Q,functionName:"feeAmountTickSpacing",args:[s]}));if(!Number.isInteger(s)||b<=0)throw new c("Unsupported Uniswap v3 fee tier. Enabled tiers: 100, 500, 3000, 10000.");u=b}let d=l(String(await i.readContract({address:f.factory,abi:Q,functionName:"getPool",args:[o,r,s]})));if(d!==M)throw new c(`The Uniswap v3 pool already exists at ${d}. Use uniswap_add to provide liquidity.`);let p=await C(i,o,k,e.token0Decimals),m=await C(i,r,k,e.token1Decimals),g=De(e,p.decimals,m.decimals),y=be(g,await Oe(i,o,r,s),e.acceptPriceDeviation===!0,p.decimals,m.decimals),h=ie(g,p.decimals,m.decimals),S=[X(R({abi:v,functionName:"createAndInitializePoolIfNecessary",args:[o,r,s,g]}),`Create and initialize the Uniswap v3 ${p.symbol}/${m.symbol} fee ${s} pool at ${h} ${m.symbol} per ${p.symbol}.`)],N=await Y(i,S,a),U;try{U=l(String(he({abi:v,functionName:"createAndInitializePoolIfNecessary",data:N[0]})))}catch{throw new c("Uniswap v3 pool creation simulation returned an invalid pool address.")}if(U===M)throw new c("Uniswap v3 pool creation simulation returned no pool.");let w=await t.preview(S,a);return{txs:S,preview:w,summary:`${S[0].description} The pool starts empty: nothing trades until liquidity is added with uniswap_add.`,details:{version:"v3",action:"createPool",pool:U,fee:s,tickSpacing:u,token0:p,token1:m,sqrtPriceX96:g.toString(),initialPrice:h,initialTick:we(g),priceCheck:y}}}async function at(t,e,n){O(n);let a=l(n),i=G(t,e),o=J(e.tokenId,"tokenId");if(o<=0n)throw new c("Uniswap v3 tokenId must be a positive integer.");await xe(i,o,a);let r=await de(i,o),s=await C(i,r.token0,k),u=await C(i,r.token1,k),d=e.recipient===void 0?a:E(e.recipient,"recipient");if(d!==a)throw new c("Uniswap recipient must be the signing wallet.");let p=e.amount0Max===void 0?z:V(e.amount0Max,"amount0Max"),m=e.amount1Max===void 0?z:V(e.amount1Max,"amount1Max");if(p===0n&&m===0n||p>z||m>z)throw new c("Collect requires a positive amountMax within uint128.");let g=[X(R({abi:v,functionName:"collect",args:[{tokenId:o,recipient:d,amount0Max:p,amount1Max:m}]}),`Collect Uniswap v3 fees from position #${o}.`)],y=ce("collect",(await Y(i,g,a))[0]),h=await t.preview(g,a);return{txs:g,preview:h,summary:Ie(g[0].description,h),details:{version:"v3",action:"collect",tokenId:o.toString(),recipient:d,token0:s,token1:u,amount0Max:p.toString(),amount1Max:m.toString(),expectedAmount0:y[0].toString(),expectedAmount1:y[1].toString()}}}async function ct(t,e,n){O(n);let a=l(n),i=G(t,e),o=J(e.tokenId,"tokenId");if(o<=0n)throw new c("Uniswap v3 tokenId must be a positive integer.");await xe(i,o,a);let r=await de(i,o),s=r.liquidity===0n&&e.burn===!0;if(r.liquidity<=0n&&!s)throw new c("Position has zero active liquidity to remove.");if(e.liquidity===void 0&&!s)throw new c('Provide a liquidity amount or explicitly choose liquidity "all" for a full exit.');let u=e.liquidity==="all"||e.liquidity===void 0?r.liquidity:V(e.liquidity,"liquidity");if(u<=0n&&!s)throw new c("Liquidity to remove must be positive.");if(u>r.liquidity)throw new c("Requested liquidity exceeds position liquidity.");let d=await Ee(i,e.deadline),p=Be(e),m=await C(i,r.token0,k),g=await C(i,r.token1,k),y=e.recipient===void 0?a:E(e.recipient,"recipient");if(y!==a)throw new c("Uniswap recipient must be the signing wallet.");let h=(B,D)=>X(R({abi:v,functionName:"decreaseLiquidity",args:[{tokenId:o,liquidity:u,amount0Min:B,amount1Min:D,deadline:d}]}),`Decrease ${u} liquidity on Uniswap v3 position #${o}.`),S=s?[0n,0n]:ce("decreaseLiquidity",(await Y(i,[h(0n,0n)],a))[0]),N=(B,D)=>{if(B!==void 0&&V(B,D)!==0n)throw new c(`${D} must be zero for an empty position burn.`);return 0n},U=s?N(e.amount0Min,"amount0Min"):ae(e.amount0Min,S[0],p,"amount0Min"),w=s?N(e.amount1Min,"amount1Min"):ae(e.amount1Min,S[1],p,"amount1Min"),b=s?[]:[h(U,w)],P=b.length,x=!s||r.tokensOwed0>0n||r.tokensOwed1>0n;x&&b.push(X(R({abi:v,functionName:"collect",args:[{tokenId:o,recipient:y,amount0Max:z,amount1Max:z}]}),`Collect principal and fees from Uniswap v3 position #${o}.`));let I=u===r.liquidity,$=I&&e.burn===!0;$&&b.push(X(R({abi:v,functionName:"burn",args:[o]}),`Burn empty Uniswap v3 position #${o}.`));let H=await Y(i,b,a),j=x?ce("collect",H[P]):[0n,0n],F=await t.preview(b,a);return{txs:b,preview:F,summary:Ie(`Remove Uniswap v3 liquidity from position #${o}${$?`; burns position #${o} at ${f.positionManager}`:""}`,F),details:{version:"v3",action:"remove",tokenId:o.toString(),recipient:y,token0:m,token1:g,liquidityRemoved:u.toString(),amount0Min:U.toString(),amount1Min:w.toString(),deadline:d.toString(),expectedAmount0:j[0].toString(),expectedAmount1:j[1].toString(),fullExit:I,burned:$}}}async function dt(t,e,n={}){let a=l(e),i=new Set;if(Array.isArray(n.tokenIds))for(let r of n.tokenIds){let s=J(r,"tokenId");s>0n&&i.add(s.toString())}if(Array.isArray(n.receipts))for(let r of n.receipts)for(let s of Le(r,a))i.add(s);if(Array.isArray(n.tokenIds)&&n.tokenIds.length>0)return[...i].map(r=>BigInt(r)).sort((r,s)=>r<s?-1:r>s?1:0);let o=!1;try{let r=BigInt(await t.readContract({address:f.positionManager,abi:v,functionName:"balanceOf",args:[a]})),s=r>$e?$e:r;r>s&&n.onTruncated?.(r,s);for(let u=0n;u<s;u++){try{let d=BigInt(await t.readContract({address:f.positionManager,abi:v,functionName:"tokenOfOwnerByIndex",args:[a,u]}));d>0n&&i.add(d.toString())}catch(d){if(!te(d,3,-32601,-32004))throw d;break}u+1n===r&&(o=!0)}r===0n&&(o=!0)}catch(r){if(!te(r,3,-32601,-32004))throw r}if(typeof t.getLogs=="function"&&typeof t.getBlockNumber=="function")try{let r=n.toBlock??await t.getBlockNumber(),s=n.maxChunks??Ke,u=n.fromBlock??(r>oe*BigInt(s)?r-oe*BigInt(s)+1n:0n),d=r,p=0;for(;d>=u&&p<s;){let m=d>=oe-1n?d-(oe-1n):0n,g=m<u?u:m,y=await t.getLogs({address:f.positionManager,fromBlock:g,toBlock:d});for(let h of Le({logs:y},a))i.add(h);if(p+=1,g===0n||g<=u)break;d=g-1n}}catch(r){throw new c(`Could not discover Uniswap v3 positions from logs. ${T(r)}`)}else if(!o&&n.tokenIds===void 0&&n.receipts===void 0)throw new c("Uniswap v3 position discovery is unavailable; supply candidate token IDs or receipts.");return[...i].map(r=>BigInt(r)).sort((r,s)=>r<s?-1:r>s?1:0)}async function Xe(t,e,n={}){O(e);let a=l(e),i=G(t),o=await dt(i,a,n),r=[];for(let s of o){let u;try{let w=await i.readContract({address:f.positionManager,abi:v,functionName:"ownerOf",args:[s]});u=l(String(w))}catch(w){if(te(w,3))continue;throw new c(`Could not verify owner of position #${s}. ${T(w)}`)}if(u!==a)continue;let d;try{d=await de(i,s)}catch(w){throw new c(`Could not read position #${s}. ${T(w)}`)}if(d.liquidity===0n&&d.tokensOwed0===0n&&d.tokensOwed1===0n&&!n.includeEmpty)continue;let m=await C(i,d.token0,k),g=await C(i,d.token1,k),y=0n,h=0n;if(d.liquidity>0n)try{let w=await i.readContract({address:f.factory,abi:Q,functionName:"getPool",args:[d.token0,d.token1,d.fee]}),b=l(String(w));if(b===M)throw new c("Position pool was not found.");if(b!==M){let P=await i.readContract({address:b,abi:ke,functionName:"slot0"}),x=BigInt(P[0]);if(x<=0n)throw new c("Position pool has no initialized price.");let I=_e(d.tickLower),$=_e(d.tickUpper),H=it(x,I,$,d.liquidity);y=H.amount0,h=H.amount1}}catch(w){throw new c(`Could not value Uniswap v3 position #${s}. ${T(w)}`)}let S=y+d.tokensOwed0,N=h+d.tokensOwed1,U=[{token:m,amount:S.toString()},{token:g,amount:N.toString()}];r.push({module:"uniswap",id:`uniswap:v3:${s.toString()}`,chainId:k,assets:U,description:`Uniswap v3 LP position #${s.toString()} (${m.symbol}/${g.symbol} fee ${d.fee} ticks [${d.tickLower}, ${d.tickUpper}] liquidity ${d.liquidity.toString()})`})}return r}async function ut(t,e,n){G(t,e);let a=e.wallet!==void 0?E(e.wallet,"wallet"):l(n),i=Array.isArray(e.tokenIds)?e.tokenIds:void 0,o=Array.isArray(e.receipts)?e.receipts:void 0,r=e.includeZero===!0||e.includeEmpty===!0,s,u=await Xe(t,a,{tokenIds:i,receipts:o,includeEmpty:r,onTruncated:(d,p)=>{s={balance:d,listed:p}}});return{positions:u,details:{version:"v3",wallet:a,count:u.length,positionManager:f.positionManager,...s?{truncated:!0,incomplete:!0,note:`This wallet holds ${s.balance} Uniswap v3 position NFTs and only the first ${s.listed} were checked, so later positions are not listed. Pass tokenIds to check specific positions.`}:{}}}}function lt(t){return[{name:"uniswap_add",inputSchema:{type:"object",description:"Mint a new Uniswap v3 concentrated liquidity position or increase liquidity on an existing v3 NFT position on Robinhood Chain (4663).",properties:{version:{type:"string",enum:["v3"],default:"v3"},tokenId:{type:"string",description:"Optional existing v3 NFT tokenId for increaseLiquidity."},token0:{type:"string",description:"Sorted ERC-20 token0 address (e.g. WETH)."},token1:{type:"string",description:"Sorted ERC-20 token1 address (e.g. USDG)."},fee:{type:"integer",enum:[100,500,3e3,1e4],default:100},fullRange:{type:"boolean",description:"For a new v3 position, use the widest ticks aligned to the pool fee tier; omit explicit ticks."},tickLower:{type:"integer",description:"Lower tick boundary divisible by tickSpacing."},tickUpper:{type:"integer",description:"Upper tick boundary divisible by tickSpacing."},amount0Desired:{type:"string",description:"Desired token0 amount in decimal base units."},amount1Desired:{type:"string",description:"Desired token1 amount in decimal base units."},amount0Min:{type:"string",description:"Minimum token0 amount in decimal base units."},amount1Min:{type:"string",description:"Minimum token1 amount in decimal base units."},slippageBps:{type:"integer",minimum:0,maximum:9999,default:ne},deadline:{type:"integer",description:"Unix timestamp deadline (> current block timestamp)."},wrapNative:{type:"boolean",description:"Optional: wrap native ETH into WETH before minting."},initialPrice:{type:"string",description:"Only when the pool does not exist: starting price as token1 per 1 token0 in human units. The pool is created then liquidity is minted in separately confirmed transactions."},sqrtPriceX96:{type:"string",description:"Alternative to initialPrice: exact starting sqrtPriceX96."},acceptPriceDeviation:{type:"boolean",description:"Allow a starting price more than 500 bps from other live pools of the pair."}}},execute:(r,s)=>rt(t,r,s)},{name:"uniswap_collect",inputSchema:{type:"object",description:"Collect accrued Uniswap v3 LP fees for an owned NonfungiblePositionManager NFT.",properties:{version:{type:"string",enum:["v3"],default:"v3"},tokenId:{type:"string",description:"Uniswap v3 NFT tokenId."},recipient:{type:"string",description:"Optional fee recipient; must be the signing wallet."},amount0Max:{type:"string",description:"Max token0 to collect (defaults to uint128 max)."},amount1Max:{type:"string",description:"Max token1 to collect (defaults to uint128 max)."}},required:["tokenId"]},execute:(r,s)=>at(t,r,s)},{name:"uniswap_remove",inputSchema:{type:"object",description:"Decrease liquidity on an owned Uniswap v3 NFT position, collect principal and fees, and optionally burn the empty NFT.",properties:{version:{type:"string",enum:["v3"],default:"v3"},tokenId:{type:"string",description:"Uniswap v3 NFT tokenId."},liquidity:{type:"string",description:"Positive base-unit liquidity amount, or all for a full exit."},amount0Min:{type:"string",description:"Minimum token0 principal in decimal base units."},amount1Min:{type:"string",description:"Minimum token1 principal in decimal base units."},slippageBps:{type:"integer",minimum:0,maximum:9999,default:ne},deadline:{type:"integer",description:"Unix timestamp deadline (> current block timestamp)."},burn:{type:"boolean",description:"Whether to burn the NFT after removing 100% of liquidity, or burn an already-empty position."}},required:["tokenId"]},execute:(r,s)=>ct(t,r,s)},{name:"uniswap_list_positions",inputSchema:{type:"object",description:"List active Uniswap v3 LP positions owned by the wallet from NFT receipts and Transfer logs.",properties:{version:{type:"string",enum:["v3"],default:"v3"},wallet:{type:"string",description:"Optional wallet address override."},tokenIds:{type:"array",items:{type:"string"},description:"Optional candidate v3 NFT tokenIds to inspect."}}},execute:(r,s)=>ut(t,r,s)},{name:"uniswap_create_pool",inputSchema:{type:"object",description:"Create and initialize an empty Uniswap v3 pool on Robinhood Chain (4663). Add liquidity afterwards with uniswap_add.",properties:{version:{type:"string",enum:["v3"],default:"v3"},token0:{type:"string",description:"Sorted ERC-20 token0 address (WETH, not native ETH)."},token1:{type:"string",description:"Sorted ERC-20 token1 address."},fee:{type:"integer",enum:[100,500,3e3,1e4]},initialPrice:{type:"string",description:'Starting price as token1 per 1 token0 in human units, e.g. "3000" for 1 WETH = 3000 USDG.'},sqrtPriceX96:{type:"string",description:"Alternative to initialPrice: exact starting sqrtPriceX96."},acceptPriceDeviation:{type:"boolean",description:"Allow a starting price more than 500 bps from other live pools of the pair."}},required:["token0","token1","fee"]},execute:(r,s)=>st(t,r,s)}]}var Ve=t=>({tools:lt(t),positions:async e=>{let n,a=await Xe(t,e,{onTruncated:(i,o)=>{n={module:"uniswap",id:"uniswap-v3-discovery-truncated",chainId:k,assets:[],incomplete:!0,description:`This wallet holds ${i} Uniswap v3 position NFTs and only the first ${o} were checked, so later positions may be missing. Pass tokenIds to uniswap_list_positions to check the others.`}}});return n?[...a,n]:a}}),xt=Ve,It=Ve;export{re as a,se as b,z as c,f as d,ve as e,ht as f,v as g,Q as h,ke as i,Ye as j,et as k,tt as l,nt as m,Le as n,vt as o,De as p,rt as q,st as r,at as s,ct as t,Xe as u,ut as v,lt as w,Ve as x,xt as y,It as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as s}from"./
|
|
1
|
+
import{b as s}from"./VHLINDDS.js";import{a as o,c as t}from"./L7OQUHM5.js";import{getAddress as i}from"viem";var u=new Set(["priors_status",...s,...t.filter(r=>r.read).map(r=>r.name),"priors_ethos_status","priors_request_borrow","priors_request_repay","priors_request_stock","priors_request_backing","priors_pt_quote","priors_pt_position","priors_stock_quote","priors_savings_liquidity","priors_market_origin","priors_market_pins","priors_capabilities"]),p=new Set(["priors_sign_consent",...t.filter(r=>r.consentRoot).map(r=>r.name)]),d=new Set([...p,"priors_starter_line"]),R=new Set([...t.filter(r=>!r.read).map(r=>r.name),"priors_root_offer","priors_autopay_on","priors_autopay_off","priors_pt_buy","priors_pt_sell","priors_pt_redeem","priors_savings_force_withdraw","priors_stock_swap","priors_market_clear_bid_budget","priors_market_revoke_nft","priors_x_link"]);function S(r){let _=t.find(e=>e.name===r);return _?[o[_.contract],..._.approval==="bid"?[o.bidSpender]:[]]:r==="priors_root_offer"?[o.pool]:r==="priors_autopay_on"||r==="priors_autopay_off"?[o.autopay]:r==="priors_savings_force_withdraw"?[o.savings]:r==="priors_stock_swap"?[i("0xCaf681a66D020601342297493863E78C959E5cb2"),i("0x7Cd4E04E433E69e588728c86A3832753B5F846d4")]:r==="priors_pt_buy"||r==="priors_pt_sell"||r==="priors_pt_redeem"?[i("0x888888888889758F76e7103c6CbF23ABbF58F946")]:r==="priors_market_clear_bid_budget"?[o.bidSpender]:r==="priors_market_revoke_nft"?[o.registry,"0x0000000000000000000000000000000000000000"]:r==="priors_x_link"?[o.registry]:[]}export{u as a,p as b,d as c,R as d,S as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as k}from"./A3PN3PK3.js";import{g as P}from"./5KUWLUPM.js";import{a as b}from"./FWD4L3CJ.js";import{a as t}from"./XSD5NL7J.js";import{a as A}from"./JXOEJPJ4.js";import{getAddress as w,parseAbi as L}from"viem";var v={one_hour:3600n,six_hours:21600n,one_day:86400n,seven_days:604800n,thirty_days:2592000n,ninety_days:7776000n,one_year:31536000n},g=L(["function asset() view returns (address)","function decimals() view returns (uint8)","function previewRedeem(uint256) view returns (uint256)"]);async function C(u,o,i){let a=0n,s=i.number,e=await u.getBlock({blockNumber:a});if(e.timestamp>o)throw new t("Longbow has insufficient chain history for this window.");for(let n=0;a+1n<s&&n<64;n++){let r=(a+s)/2n,c=await u.getBlock({blockNumber:r});if(c.number!==r||c.timestamp<e.timestamp||c.timestamp>i.timestamp)throw new t("Longbow historical block response is inconsistent.");c.timestamp<=o?(a=r,e=c):s=r}if(a+1n<s||e.number!==a)throw new t("Longbow historical block search exceeded its bound.");return e}async function _(u,o,i,a="six_hours"){let s=v[a];if(!Object.hasOwn(v,a)||!s)throw new t("Choose a finite Longbow APY lookback from one_hour to one_year; inception is unavailable.");let e=u.clientFor(b);if(await e.getChainId()!==b)throw new t("Longbow APY assessment requires chain 4663.");let n=await e.getBlock({blockTag:"latest"});if(n.number===null||n.timestamp<s)throw new t("Longbow has insufficient chain history for this window.");let r=await C(e,n.timestamp-s,{number:n.number,timestamp:n.timestamp}),c=10n**27n,d=await Promise.all([r,n].map(async m=>{let[S,N,Y,f]=await Promise.all([e.readContract({address:o,abi:g,functionName:"asset",blockNumber:m.number}),e.readContract({address:o,abi:g,functionName:"decimals",blockNumber:m.number}),e.readContract({address:i.address,abi:g,functionName:"decimals",blockNumber:m.number}),e.readContract({address:o,abi:g,functionName:"previewRedeem",args:[c],blockNumber:m.number})]);if(w(S)!==w(i.address)||N!==18||Y!==i.decimals||typeof f!="bigint"||f<0n||f>=1n<<256n)throw new t("Longbow historical share price or token metadata is unavailable or invalid. No zero rate was inferred.");return f})),h=n.timestamp-r.timestamp;if(h<=0n||h>s+300n)throw new t("Longbow historical blocks do not cover the requested APY window within 300 seconds.");if(d[0]===0n)throw new t("Longbow starting share price is zero; a realized APY cannot be calculated.");let l=Number(d[1]-d[0])/Number(d[0]),p=Math.expm1(Math.log1p(l)*31536e3/Number(h));if(!Number.isFinite(p))throw new t("Longbow annualized share-price change is outside the supported numeric range.");let y=await k(e,o,n.number);return{chainId:b,vault:o,asset:{...i,address:w(i.address)},shareToken:{address:o,symbol:y,decimals:18,chainId:b},source:"Oak-computed on-chain",view:"apy",stale:!1,window:{lookback:a,requestedSeconds:s.toString(),elapsedSeconds:h.toString(),fromTimestamp:r.timestamp.toString(),toTimestamp:n.timestamp.toString(),fromBlock:r.number.toString(),toBlock:n.number.toString()},sharePrice:{shareUnits:c.toString(),startAssets:d[0].toString(),endAssets:d[1].toString(),assetDecimals:i.decimals},data:{annualYieldFraction:String(p),annualYieldPercent:String(p*100),lookback:a,basis:"Oak-computed realized APY: (end share price / start share price)^(31536000 / elapsed seconds) - 1, using ERC-4626 previewRedeem at two pinned blocks."},caveat:"Historical share-price change includes what the vault accounts for in previewRedeem, excludes external rewards and gas, and is not a promised return. Archive RPC history is required; missing history is not zero APY."}}async function I(u,o,i,a){if(Object.keys(a).some(d=>!["view","lookback"].includes(d)))throw new t("Longbow APY takes a lookback, not pagination.");let s=a.lookback??"six_hours";if(typeof s!="string"||!Object.hasOwn(v,s))throw new t("Choose a finite Longbow APY lookback from one_hour to one_year; inception is unavailable.");let[e,n]=await Promise.allSettled([O(u,o,i,{view:"published_apy"}),_(u,o,i,s)]),r=e.status==="fulfilled"&&!e.value.stale?e.value:void 0;if(!r&&n.status==="rejected")throw new t(`Longbow APY is unavailable: the vendor figure is unavailable or stale, and the on-chain window could not be measured. ${u.plainError(n.reason)}`);return{...r??(n.status==="fulfilled"?n.value:void 0),view:"apy",shown:r?"Longbow vendor":"Oak-computed on-chain",realized:n.status==="fulfilled"?n.value:null,published:e.status==="fulfilled"?e.value:null,warnings:[...r?[]:["Longbow vendor APY is unavailable or stale; showing Oak-computed realized APY."],...n.status==="rejected"?["Oak-computed APY is unavailable: the archive RPC window could not be measured."]:[]]}}async function O(u,o,i,a){if(Object.keys(a).some(m=>m!=="view")||a.view!=="published_apy")throw new t("published_apy takes no historical lookback, cursor or limit.");let s=u.clientFor(b);if(await s.getChainId()!==b)throw new t("Longbow APY assessment requires chain 4663.");let[e,n]=await Promise.all([s.getBlock(),s.readContract({address:o,abi:L(["function asset() view returns (address)"]),functionName:"asset"})]);if(w(n)!==w(i.address))throw new t("Longbow vault does not use the pinned asset.");let r="https://longbow.credit/api/v2/vaults",c=await u.http(r,{method:"GET",headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(15e3)});if(!c.ok)throw new t(`Longbow published APY HTTP ${c.status}; the rate is unavailable.`);let d=await c.json();if(!d||typeof d!="object"||!Number.isSafeInteger(d.asOf)||Number(d.asOf)<0||!Array.isArray(d.vaults)||d.vaults.length>100)throw new t("Longbow published APY response has an invalid timestamp or vault inventory.");let h=d.vaults.filter(m=>m&&typeof m=="object"&&typeof m.address=="string"&&P(String(m.address),o));if(h.length!==1)throw new t("Longbow published APY omitted or duplicated this vault; no zero rate is inferred.");let l=h[0];if(l.error||typeof l.asset!="string"||w(l.asset)!==w(i.address)||l.decimals!==i.decimals||typeof l.apy!="number"||!Number.isFinite(l.apy)||l.apy<-100||typeof l.apyBasis!="string"||l.apyBasis.length>64)throw new t("Longbow published APY asset, units, basis or rate is invalid.");let p=BigInt(Number(d.asOf)),y=await k(s,o,e.number);return{chainId:b,vault:o,asset:{...i,address:w(i.address)},shareToken:{address:o,symbol:y,decimals:18,chainId:b},sourceUrl:r,view:"published_apy",asOf:p.toString(),stale:e.timestamp>p+900n||p>e.timestamp+60n,data:{annualYieldPercent:String(l.apy),annualYieldFraction:String(l.apy/100),basis:A(l.apyBasis)},caveat:"Longbow publisher quote, not a realized Morpho lookback series or a promised return. The app formats this field directly as percent (0.03 means 0.03%, not 3%). No bonus, future payout or fee inclusion is inferred. Onchain book and fees remain available through longbow_details."}}export{_ as a,I as b,O as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as b,h as v,l as I,n as k,r as S}from"./
|
|
1
|
+
import{d as b,h as v,l as I,n as k,r as S}from"./WWHCEMNB.js";import{a as T}from"./X5V2Z2NM.js";import{e as c,g as y}from"./5KUWLUPM.js";import{a as i}from"./XSD5NL7J.js";import{a as l}from"./JXOEJPJ4.js";import{lookup as C}from"node:dns/promises";import{isIP as p}from"node:net";var N="/.well-known/agent-registration.json",P=262144;function R(n){let r=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(n);if(r)return R(r[1]);if(p(n)===4){let[e,t]=n.split(".").map(Number);return!(e===0||e===10||e===127||e>=224||e===100&&t>=64&&t<=127||e===169&&t===254||e===172&&t>=16&&t<=31||e===192&&t===168||e===192&&t===0||e===198&&(t===18||t===19))}if(p(n)===6){let e=n.toLowerCase();return!(e==="::"||e==="::1"||/^f[cd]/.test(e)||/^fe[89ab]/.test(e)||e.startsWith("ff")||e.startsWith("2001:db8")||e.startsWith("64:ff9b"))}return!1}async function E(n){let r;try{r=new URL(n)}catch{throw new i("Not a valid URL.")}if(r.protocol!=="https:"||r.username||r.password||r.port||p(r.hostname.replace(/^\[|\]$/g,""))!==0||!r.hostname.includes(".")||/\.(?:local|internal|localhost|lan)$/i.test(r.hostname))throw new i("Only public HTTPS hostnames on the default port are checked.");let e=await C(r.hostname,{all:!0});if(!e.length||!e.every(t=>R(t.address)))throw new i("That hostname does not resolve to a public address.");return r.hostname}async function L(n,r){let e=await n.http(r,{method:"GET",headers:{accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(8e3)});if(!e.ok)throw new i(`The server answered HTTP ${e.status}.`);if(Number(e.headers.get("content-length")??0)>P)throw new i("The file is larger than 256 KiB.");let a=await e.text();if(a.length>P)throw new i("The file is larger than 256 KiB.");try{return JSON.parse(a)}catch{throw new i("The file is not JSON.")}}function O(n,r,e){return Array.isArray(n)&&n.some(t=>c(t)&&typeof t.agentRegistry=="string"&&y(t.agentRegistry,r)&&(typeof t.agentId=="number"||typeof t.agentId=="string")&&String(t.agentId)===e.toString())}var J=n=>({tools:[{name:"erc8004_verify_domain",inputSchema:{type:"object",additionalProperties:!1,required:["agentId"],description:"Read-only, optional ERC-8004 endpoint-domain verification: for each HTTPS service endpoint in the agent's on-chain profile, fetch https://{domain}/.well-known/agent-registration.json and check it lists this registry and agent ID. Only public HTTPS names are fetched; the profile itself is read only from a data: URI.",properties:{agentId:b,endpoint:{type:"string",description:"Check only this HTTPS endpoint (must be one of the profile's services)."}}},async execute(e){try{k(n,e.chainId);let t=I(e.agentId),{chainId:a,registry:H,registryId:u}=v(n),h=await n.clientFor(a).readContract({address:H,abi:T,functionName:"tokenURI",args:[t]});if(typeof h!="string")throw new i("The registry returned an invalid URI.");let f=S(h);if(!f)return{agentId:t.toString(),verified:null,reason:"The agent profile is not a base64 data: URI, so Oak will not fetch it from an agent-controlled location. Pass the endpoint host check yourself, or update the profile to a data: URI.",uri:l(h)};let g=(Array.isArray(f.services)?f.services.filter(c):[]).map(o=>String(o.endpoint??"")).filter(o=>/^https:\/\//i.test(o)),m=e.endpoint===void 0?g:g.filter(o=>o===e.endpoint);if(e.endpoint!==void 0&&!m.length)throw new i("That endpoint is not an HTTPS service in the agent's profile.");let U=[...new Set(m.map(o=>{try{return new URL(o).hostname}catch{return""}}).filter(Boolean))].slice(0,10),s=[];for(let o of U)try{await E(`https://${o}/`);let d=await L(n,`https://${o}${N}`),A=c(d)?d.registrations:void 0,w=O(A,u,t);s.push({domain:l(o),verified:w,reason:w?"The well-known file lists this registry and agent ID.":"The well-known file does not list this registry and agent ID."})}catch(d){s.push({domain:l(o),verified:!1,reason:n.plainError(d)})}return{agentId:t.toString(),registry:u,domains:s,checked:s.length,note:s.length?"Verified means that domain publishes a file naming this agent; it proves domain control by the agent, not that the endpoint is safe.":"The profile lists no HTTPS service endpoints to verify."}}catch(t){throw new i(n.plainError(t))}}}]});export{R as a,J as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as qe,b as fe,g as Z,h as he,i as Be,m as ee,n as D,y as be,z as Oe}from"./GHPREYQK.js";import{b as y,c as Ie}from"./OFI3Y55L.js";import{a as le,b as z}from"./HTXKERNS.js";import{a as Q}from"./PBQSJSZO.js";import{a as $e}from"./BQICZFLR.js";import{a as Se}from"./5ZLOCQA4.js";import{c as me,g as P}from"./5KUWLUPM.js";import{a as Pe}from"./UP7FBDMJ.js";import{a as b,i as pe}from"./FWD4L3CJ.js";import{a as d}from"./XSD5NL7J.js";import{a as ce}from"./JXOEJPJ4.js";import{randomUUID as He}from"node:crypto";import{encodeAbiParameters as ne,encodeFunctionData as ke,erc20Abi as Te,getAddress as F,parseAbi as X,parseAbiParameters as oe,zeroAddress as K}from"viem";var Me=pe[b].pons,N=pe[b].ponsTrade,Re=X(["function getLaunchedToken(address) view returns ((address token,address curve,address deployer,address creatorFeeRecipient,address pairToken,uint256 graduationThreshold,uint24 poolFee,int24 tickSpacing,uint16 creatorTaxBps,bool buybackEnabled,uint8 phase,uint256 sweptQuote,uint256 sweptTokens,uint256 sweptAt,bool exists))"]),te=X(["function getReserves() view returns (uint256 quoteReserve,uint256 tokenReserve)","function feeBps() view returns (uint256)","function creatorTaxBps() view returns (uint256)","function currentSnipeTaxBps(address) view returns (uint256)","function sellableTokens() view returns (uint256)","function buy(uint256 quoteIn,uint256 minTokensOut,address recipient) payable returns (uint256)","function sell(uint256 tokensIn,uint256 minQuoteOut,address recipient) returns (uint256)"]),Le=X(["function quoteExactInputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountOut,uint256 gasEstimate)"]),ze=X(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),Ke=X(["function approve(address token,address spender,uint160 amount,uint48 expiration)"]),Xe=oe("((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 amountIn,uint128 amountOutMinimum,uint256 minHopPriceX36,bytes hookData)"),je={address:le,chainId:b,decimals:18,symbol:"ETH"},_e="There is no on-chain expiry. The signed transaction is protected by its minimum output.",Ge=`Quote expiry is enforced by Oak before signing only. ${_e}`,$=10000n,we=(1n<<256n)-1n,Ee=(1n<<128n)-1n,I=(n,t)=>({token:n,amount:t.toString()}),Ne=(n,t)=>(n+t-1n)/t,Ce="Reuse existing exact allowance";async function Ve(n,t,i,o,c){try{let e=await n.readContract({address:t,abi:Te,functionName:"allowance",args:[i,o],blockNumber:c});return typeof e=="bigint"?e:void 0}catch{return}}var We={type:"object",additionalProperties:!1,required:["token","amountIn"],properties:{token:{...me,description:"Pons launch token address on chain 4663."},amountIn:Se("Positive base units: the launch pair token for buy (native ETH wei for ETH pairs; pons_status shows pairToken), the launch token for sell."),pairToken:{...me,description:"The launch pair from pons_status. Required to buy a custom-pair launch, so amountIn is never read in the wrong units; omit or use the zero address for native ETH."},slippageBps:{type:"integer",minimum:0,maximum:9999,default:fe}}};function Qe(n,t,i,o){if(n===void 0){if(i&&y(t)!==K)throw new d(`This Pons launch is paired with ${o}; amountIn is in that token's base units. Repeat with pairToken "${t}" to confirm the input asset.`);return}if(typeof n!="string")throw new d("pairToken must be a token address.");if(Q(n),!P(y(n),y(t)))throw new Z(`This Pons launch trades only against ${o}.`)}async function De(n,t,i,o,{quoteOnly:c=!1,curveOnly:e=!1,blockNumber:p}={}){if(Q(i),Object.keys(t).some(f=>!["token","amountIn","slippageBps","pairToken"].includes(f)))throw new d("Provide only token, amountIn, optional pairToken and optional slippageBps.");if(typeof t.token!="string")throw new d("Provide a launch token address.");Q(t.token);let s=F(t.token),r=Pe(t.amountIn);if(r===0n||r>we)throw new d("Trade amount must be positive and within the uint256 range.");let m=t.slippageBps??fe;if(typeof m!="number"||!Number.isInteger(m)||m<0||m>=1e4)throw new d("Slippage must be an integer from 0 to 9999 basis points.");let x=f=>f*($-BigInt(m))/$,a=n.clientFor(b),l=p===void 0?await a.getBlock():await a.getBlock({blockNumber:p});if(p!==void 0&&l.number!==p)throw new d("Pons quote snapshot is unavailable.");let u=await a.readContract({address:Me.factory.address,abi:Re,functionName:"getLaunchedToken",args:[s],blockNumber:l.number});if(!u.exists||!P(u.token,s))throw new d("This address is not a Pons launch token.");if(e&&u.phase!==0)throw new Z("Pons curve quotes are only available before graduation.");if(u.phase===1)throw new d("Pons graduation is pending; the curve is closed and the pool is not ready.");if(u.phase===3)throw new d("This Pons launch was rescued and has no active trade route.");if(u.phase!==0&&u.phase!==2)throw new d("This Pons launch has an unknown trade phase.");let g=y(u.pairToken)===K,C=F(u.pairToken);if(P(C,s))throw new d("This Pons launch has an invalid pair.");let j=f=>Promise.all([a.readContract({address:f,abi:Te,functionName:"symbol",blockNumber:l.number}),a.readContract({address:f,abi:Te,functionName:"decimals",blockNumber:l.number})]),[[B,U],H]=await Promise.all([j(s),g?void 0:j(C)]),w=H?{address:C,chainId:b,symbol:ce(H[0]),decimals:H[1]}:je,G=g?"native ETH":`${w.symbol} (${w.address})`;Qe(t.pairToken,C,o,`${G}, ${w.decimals} decimals`);let V={address:s,chainId:b,symbol:ce(B),decimals:U},se=o?w:V,re=o?V:w,q=[],ie=(f,h,S,A)=>n.unsignedTx({to:f,data:h,value:S.toString(),chainId:b,description:A}),T,k,W,O=r,ge=null,ae,ve="";if(u.phase===0){let f=v=>a.readContract({address:u.curve,abi:te,functionName:v,blockNumber:l.number}),[[h,S],A,M,R,_]=await Promise.all([a.readContract({address:u.curve,abi:te,functionName:"getReserves",blockNumber:l.number}),f("feeBps"),f("creatorTaxBps"),o?a.readContract({address:u.curve,abi:te,functionName:"currentSnipeTaxBps",args:[i],blockNumber:l.number}):Promise.resolve(0n),o?f("sellableTokens"):Promise.resolve(0n)]);if(h<=0n||S<=0n||A+M>$-100n)throw new d("Pons curve reserves or fee settings are unavailable.");let J=$-A-M-100n,E=R<J?R:J,xe=v=>({base:v*A/$,creator:v*M/$,snipe:v*E/$}),Ae=v=>{let L=xe(v);return v-L.base-L.creator-L.snipe},Y;if(o){if(_<=0n||_>=S)throw new d("The curve has no available sellable tokens.");let v=Ae(r);if(T=v*S/(h+v),T>=_){T=_;let L=T*h/(S-T)+1n;O=Ne(L*$,$-A-M-E),O>r&&(O=r)}Y=O,k=x(T),W=Ne(k*r,O),g||q.push(n.approval(w.address,u.curve,r.toString(),b))}else Y=r*h/(S+r),T=Ae(Y),k=x(T),q.push(n.approval(s,u.curve,r.toString(),b));let de=xe(Y);ge={base:I(w,de.base),creator:I(w,de.creator),snipe:I(w,de.snipe)},ae=`Curve fees included: ${A} base, ${M} creator and ${E} opening-tax basis points, each rounded separately.`,q.push(ie(u.curve,ke({abi:te,functionName:o?"buy":"sell",args:[r,W??k,i]}),o&&g?r:0n,o?`Buy Pons curve tokens with ${G}.`:`Sell Pons curve tokens for ${G}.`))}else{if(r>Ee)throw new d("Trade amount exceeds the router uint128 range.");let f=Ie(u.pairToken,s,u.poolFee,u.tickSpacing),h=o?y(u.pairToken):s,S=o?s:y(u.pairToken),A=P(h,f.currency0);if(T=(await a.simulateContract({address:N.quoter.address,abi:Le,functionName:"quoteExactInputSingle",args:[{poolKey:f,zeroForOne:A,exactAmount:r,hookData:"0x"}],account:i,gas:$e,blockNumber:l.number})).result[0],k=x(T),k>Ee)throw new d("Minimum output exceeds the router uint128 range.");let R=l.timestamp+300n;if(R>=1n<<48n)throw new d("Permit2 expiry exceeds its timestamp range.");if(h!==K){let E=!c&&await Ve(a,h,i,N.permit2.address,l.number)===r;E||q.push(n.approval(h,N.permit2.address,r.toString(),b)),ve=E?`${Ce}: ${r} input base units already approved to Permit2. `:"",q.push(ie(N.permit2.address,ke({abi:Ke,functionName:"approve",args:[h,N.universal_router.address,r,Number(R)]}),0n,`${E?`${Ce}. `:""}Approve the exact token amount to the Pons router through Permit2 for five minutes.`))}let _=[ne(Xe,[{poolKey:f,zeroForOne:A,amountIn:r,amountOutMinimum:k,minHopPriceX36:0n,hookData:"0x"}]),ne(oe("address,uint256"),[h,r]),ne(oe("address,uint256"),[S,k])],J=ne(oe("bytes,bytes[]"),["0x060c0f",_]);q.push(ie(N.universal_router.address,ke({abi:ze,functionName:"execute",args:["0x10",[J],R]}),h===K?r:0n,"Trade through Pons Universal Router v2.1.2.")),ae="Quoter output is net of Pons hook fees; no additional fee is subtracted."}if(T<=0n||k<=0n||k>we||(W??k)>we)throw new d("Trade output or minimum is outside the supported positive range.");let ye=c?{changes:[],summary:"Quote only; preview is required before sending."}:await n.preview(q,i),ue=r-O;return{txs:q,changes:ye.changes,summary:`${o?"Buy":"Sell"} ${V.symbol} (${V.address}) on chain ${b}${g?"":` ${o?"with":"for"} ${G}`}. ${ae} ${ve}${u.phase===0?`${_e} `:""}${ue>0n?`Expected ${g?"native refund":"refund"}: ${n.formatAmount(ue.toString(),w.decimals)} ${w.symbol}; minimum output uses the expected spend after refund. `:""}${ye.summary}`,pairToken:w,quote:{phase:u.phase,amountIn:I(se,r),amountOut:I(re,T),minAmountOut:I(re,k),minimumKind:"absolute",calldataMinAmountOut:I(re,W??k),expectedSpend:I(se,O),expectedRefund:I(se,ue),fees:ge,blockNumber:l.number.toString(),blockTimestamp:l.timestamp.toString()}}}function ln(n){return Fe(n,!0)}function Fe(n,t=!1,i){let o=new Map,c=e=>{if(BigInt(ee())>=BigInt(e.expiresAt))throw new he};return{name:"pons",async quote(e,p){if(e={...e,from:z(e.from),to:z(e.to)},D(e.from)&&D(e.to))throw new Z("Pons quotes require a launch token and its pair token.");let s=D(e.from)||!D(e.to)&&await Je(n,e.from,e.to,i),r=ee(),m=await De(n,{token:s?e.to:e.from,amountIn:e.amountIn,slippageBps:e.slippageBps,pairToken:y(s?e.from:e.to)},p,s,{quoteOnly:!0,curveOnly:t,blockNumber:i}),x=m.txs.at(-1),a=m.quote,l=String(BigInt(i===void 0?r:a.blockTimestamp)+BigInt(qe)),u=a.minAmountOut.amount,g=a.fees,C=D(m.pairToken.address)?"native ETH base units (18 decimals)":`${m.pairToken.symbol} (${m.pairToken.address}) base units (${m.pairToken.decimals} decimals)`,j=g?`Pons curve fees included in net output: ${g.base.amount} base, ${g.creator.amount} creator and ${g.snipe.amount} opening tax, in ${C}. Oak swap fee: 0 (venue fee is never Oak income). ${Ge}`:"Quoter output is net of Pons hook fees; no additional fee is subtracted. Oak swap fee: 0.",B=Oe({...e,quoteId:`pons:${He()}`,provider:"pons",wallet:p,chainId:b,router:x.to,spender:a.phase===0?x.to:N.permit2.address,expiresAt:l,data:x.data,value:x.value,amountOut:a.amountOut.amount,minAmountOut:u,blockNumber:a.blockNumber,...a.phase===0?{ponsCurveToken:s?e.to:e.from,calldataMinAmountOut:a.calldataMinAmountOut.amount}:{ponsPoolToken:s?e.to:e.from},expectedSpend:a.expectedSpend.amount,expectedRefund:a.expectedRefund.amount,feeDisclosure:j,oakFee:"0"});be(x,B),c(B);for(let[U,H]of o)BigInt(ee())>=BigInt(H.quote.expiresAt)&&o.delete(U);for(;o.size>=Be;)o.delete(o.keys().next().value);return o.set(B.quoteId,{quote:{...B},txs:m.txs.map(U=>({...U})),summary:m.summary}),B},async build(e,p){let s=o.get(e);if(!s)throw new he;if(c(s.quote),Q(p),!P(p,s.quote.wallet))throw new d("Quote was issued for a different wallet.");let r=s.txs.map(a=>({...a}));be(r.at(-1),s.quote);let m=await n.preview(r,p);if(c(s.quote),m.changes.filter(a=>P(z(a.token.address),z(s.quote.to))).reduce((a,l)=>a+BigInt(l.amount),0n)<BigInt(s.quote.minAmountOut))throw new d("Preview retained output is below the accepted minimum.");return{txs:r,summary:`${s.summary} ${m.summary} ${s.quote.feeDisclosure}`}}}}async function Ue(n,t,i){return n.clientFor(b).readContract({address:Me.factory.address,abi:Re,functionName:"getLaunchedToken",args:[F(t)],...i===void 0?{}:{blockNumber:i}})}async function Je(n,t,i,o){let c=await Ue(n,i,o);return c.exists&&P(c.token,i)&&P(y(c.pairToken),y(t))}async function fn(n,t,i,o,c){if(typeof i.token!="string")throw new d("Provide a launch token address.");Q(i.token);let e=F(i.token),p=await Ue(n,e,c);if(!p.exists||!P(p.token,e))throw new d("This address is not a Pons launch token.");let s=y(p.pairToken)===K?le:F(p.pairToken);return Qe(i.pairToken,F(p.pairToken),t,s),{quote:await Fe(n,!1,c).quote({from:t?s:e,to:t?e:s,amountIn:String(i.amountIn),...i.slippageBps===void 0?{}:{slippageBps:i.slippageBps}},o),input:t?s:e}}var Ye=n=>({tools:[!0,!1].map(t=>({name:t?"pons_buy":"pons_sell",inputSchema:We,async execute(i,o){try{return await De(n,i,o,t)}catch(c){throw new d(n.plainError(c))}}}))}),hn=Ye;export{ln as a,Fe as b,fn as c,Ye as d,hn as e};
|