@oakagentkit/core 0.3.5 → 0.3.6
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 +14 -0
- package/build/dist/api/addresses.js +1 -1
- package/build/dist/api/chain.js +1 -1
- package/build/dist/api/history.d.ts +2 -0
- package/build/dist/api/history.js +1 -1
- package/build/dist/api/identity-link.js +1 -1
- package/build/dist/api/metadata.js +1 -1
- package/build/dist/api/modules/beefy/boosts.js +1 -1
- package/build/dist/api/modules/beefy/clm.js +1 -1
- package/build/dist/api/modules/beefy/guard.js +1 -1
- package/build/dist/api/modules/beefy/index.js +1 -1
- package/build/dist/api/modules/beefy/liquidity.js +1 -1
- package/build/dist/api/modules/beefy/management.js +1 -1
- package/build/dist/api/modules/beefy/vaults.js +1 -1
- package/build/dist/api/modules/borro/actions.js +1 -1
- package/build/dist/api/modules/borro/index.js +1 -1
- package/build/dist/api/modules/borro/liquidity.js +1 -1
- package/build/dist/api/modules/borro/positions.js +1 -1
- package/build/dist/api/modules/borro/reader.js +1 -1
- package/build/dist/api/modules/chop/display.js +1 -1
- package/build/dist/api/modules/chop/guard.js +1 -1
- package/build/dist/api/modules/chop/index.js +1 -1
- package/build/dist/api/modules/clanker/extensions.js +1 -1
- package/build/dist/api/modules/clanker/index.js +1 -1
- package/build/dist/api/modules/clanker/manage.js +1 -1
- package/build/dist/api/modules/clanker/pool-config.js +1 -1
- package/build/dist/api/modules/clanker/protocol.js +1 -1
- package/build/dist/api/modules/clanker/state.js +1 -1
- package/build/dist/api/modules/earn/index.js +1 -1
- package/build/dist/api/modules/erc8004/common.js +1 -1
- package/build/dist/api/modules/erc8004/domain.js +1 -1
- package/build/dist/api/modules/erc8004/index.js +1 -1
- package/build/dist/api/modules/erc8004/management.js +1 -1
- package/build/dist/api/modules/erc8004/reputation.js +1 -1
- package/build/dist/api/modules/erc8004/services.js +1 -1
- package/build/dist/api/modules/erc8004/thesis.js +1 -1
- package/build/dist/api/modules/erc8004/validation.js +1 -1
- package/build/dist/api/modules/fobo/index.js +1 -1
- package/build/dist/api/modules/fobo/intent.js +1 -1
- package/build/dist/api/modules/fobo/steps.js +1 -1
- package/build/dist/api/modules/fobo/verify.js +1 -1
- package/build/dist/api/modules/grove/index.js +1 -1
- package/build/dist/api/modules/heyresearch/builder-feed.js +1 -1
- package/build/dist/api/modules/heyresearch/index.js +1 -1
- package/build/dist/api/modules/heyresearch/public-reads.js +1 -1
- package/build/dist/api/modules/heyresearch/token-facts.js +1 -1
- package/build/dist/api/modules/hoodag/chain-reads.js +1 -1
- package/build/dist/api/modules/hoodag/index.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.d.ts +39 -2
- 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.d.ts +14 -2
- package/build/dist/api/modules/hookr/agent-gate.js +1 -1
- package/build/dist/api/modules/hookr/agent-link.d.ts +17 -0
- package/build/dist/api/modules/hookr/agent-link.js +1 -0
- package/build/dist/api/modules/hookr/api-client.d.ts +9 -0
- package/build/dist/api/modules/hookr/api-client.js +1 -0
- package/build/dist/api/modules/hookr/blocks/advisory.d.ts +41 -0
- package/build/dist/api/modules/hookr/blocks/advisory.js +1 -0
- package/build/dist/api/modules/hookr/blocks/buy-sell-block.d.ts +7 -0
- package/build/dist/api/modules/hookr/blocks/buy-sell-block.js +1 -0
- package/build/dist/api/modules/hookr/blocks/core-settings.d.ts +6 -0
- package/build/dist/api/modules/hookr/blocks/core-settings.js +1 -0
- package/build/dist/api/modules/hookr/blocks/exit-clock.d.ts +14 -0
- package/build/dist/api/modules/hookr/blocks/exit-clock.js +1 -0
- package/build/dist/api/modules/hookr/blocks/holder-pot.d.ts +30 -0
- package/build/dist/api/modules/hookr/blocks/holder-pot.js +1 -0
- package/build/dist/api/modules/hookr/blocks/managed-fee.d.ts +96 -0
- package/build/dist/api/modules/hookr/blocks/managed-fee.js +1 -0
- package/build/dist/api/modules/hookr/blocks/market-guard.d.ts +116 -0
- package/build/dist/api/modules/hookr/blocks/market-guard.js +1 -0
- package/build/dist/api/modules/hookr/blocks/market-hours-fee.d.ts +87 -0
- package/build/dist/api/modules/hookr/blocks/market-hours-fee.js +1 -0
- package/build/dist/api/modules/hookr/blocks/pay-later.d.ts +199 -0
- package/build/dist/api/modules/hookr/blocks/pay-later.js +1 -0
- package/build/dist/api/modules/hookr/blocks/sandwich-guard.d.ts +3 -0
- package/build/dist/api/modules/hookr/blocks/sandwich-guard.js +1 -0
- package/build/dist/api/modules/hookr/blocks/storm-fee.d.ts +3 -0
- package/build/dist/api/modules/hookr/blocks/storm-fee.js +1 -0
- package/build/dist/api/modules/hookr/blocks/swap-cut.d.ts +3 -0
- package/build/dist/api/modules/hookr/blocks/swap-cut.js +1 -0
- package/build/dist/api/modules/hookr/blocks/swap-reward-mint.d.ts +125 -0
- package/build/dist/api/modules/hookr/blocks/swap-reward-mint.js +1 -0
- package/build/dist/api/modules/hookr/blocks/wallet-cap.d.ts +3 -0
- package/build/dist/api/modules/hookr/blocks/wallet-cap.js +1 -0
- package/build/dist/api/modules/hookr/blocks/zap-source.d.ts +161 -0
- package/build/dist/api/modules/hookr/blocks/zap-source.js +1 -0
- package/build/dist/api/modules/hookr/blocks/zap-target.d.ts +51 -0
- package/build/dist/api/modules/hookr/blocks/zap-target.js +1 -0
- package/build/dist/api/modules/hookr/claims.d.ts +53 -0
- package/build/dist/api/modules/hookr/claims.js +1 -0
- package/build/dist/api/modules/hookr/contracts.d.ts +3 -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.d.ts +2 -2
- package/build/dist/api/modules/hookr/discovery.js +1 -1
- package/build/dist/api/modules/hookr/fill-bounty.d.ts +2 -0
- package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
- package/build/dist/api/modules/hookr/gas.d.ts +48 -0
- package/build/dist/api/modules/hookr/gas.js +1 -0
- package/build/dist/api/modules/hookr/gates.d.ts +51 -0
- package/build/dist/api/modules/hookr/gates.js +1 -0
- package/build/dist/api/modules/hookr/hook-blocks.d.ts +304 -0
- package/build/dist/api/modules/hookr/hook-blocks.js +1 -0
- package/build/dist/api/modules/hookr/index.d.ts +4 -2
- package/build/dist/api/modules/hookr/index.js +1 -1
- package/build/dist/api/modules/hookr/jobs.d.ts +7 -0
- package/build/dist/api/modules/hookr/jobs.js +1 -0
- package/build/dist/api/modules/hookr/launch-options.d.ts +52 -3
- package/build/dist/api/modules/hookr/launch-options.js +1 -1
- package/build/dist/api/modules/hookr/launch-profile.d.ts +8 -0
- 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.d.ts +24 -0
- 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.d.ts +90 -2
- package/build/dist/api/modules/hookr/lp-state.js +1 -1
- package/build/dist/api/modules/hookr/pay-later-actions.d.ts +52 -0
- package/build/dist/api/modules/hookr/pay-later-actions.js +1 -0
- package/build/dist/api/modules/hookr/pins.d.ts +5 -0
- package/build/dist/api/modules/hookr/pins.js +1 -1
- package/build/dist/api/modules/hookr/pm-liquidity.d.ts +215 -0
- package/build/dist/api/modules/hookr/pm-liquidity.js +1 -0
- package/build/dist/api/modules/hookr/public-reads.d.ts +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.d.ts +4 -1
- package/build/dist/api/modules/hookr/revenue.js +1 -1
- package/build/dist/api/modules/hookr/scan.d.ts +25 -0
- package/build/dist/api/modules/hookr/scan.js +1 -0
- package/build/dist/api/modules/hookr/swap.d.ts +161 -0
- package/build/dist/api/modules/hookr/swap.js +1 -0
- package/build/dist/api/modules/kyberswap/index.js +1 -1
- package/build/dist/api/modules/kyberswap/source-pools.js +1 -1
- package/build/dist/api/modules/layerbank/abi.js +1 -1
- package/build/dist/api/modules/layerbank/actions.js +1 -1
- package/build/dist/api/modules/layerbank/checks.js +1 -1
- package/build/dist/api/modules/layerbank/index.js +1 -1
- package/build/dist/api/modules/layerbank/merkl.js +1 -1
- package/build/dist/api/modules/layerbank/reader.js +1 -1
- package/build/dist/api/modules/layerbank/reserve.js +1 -1
- package/build/dist/api/modules/lighter/index.js +1 -1
- package/build/dist/api/modules/longbow/administration.js +1 -1
- package/build/dist/api/modules/longbow/analytics.js +1 -1
- package/build/dist/api/modules/longbow/fixed.js +1 -1
- package/build/dist/api/modules/longbow/index.js +1 -1
- package/build/dist/api/modules/longbow/nft.js +1 -1
- package/build/dist/api/modules/longbow/rebates.js +1 -1
- package/build/dist/api/modules/longbow/staking.js +1 -1
- package/build/dist/api/modules/meridian/index.js +1 -1
- package/build/dist/api/modules/meridian/markets.js +1 -1
- package/build/dist/api/modules/meridian/rfq.js +1 -1
- package/build/dist/api/modules/merkl/discovery.js +1 -1
- package/build/dist/api/modules/merkl/index.js +1 -1
- package/build/dist/api/modules/merkl/manage.js +1 -1
- package/build/dist/api/modules/merkl/protocol.js +1 -1
- package/build/dist/api/modules/morpho/allocator.js +1 -1
- package/build/dist/api/modules/morpho/bundles.js +1 -1
- package/build/dist/api/modules/morpho/in-kind.js +1 -1
- package/build/dist/api/modules/morpho/index.js +1 -1
- package/build/dist/api/modules/morpho/local-guard.js +1 -1
- package/build/dist/api/modules/morpho/midnight.js +1 -1
- package/build/dist/api/modules/morpho/protocol.js +1 -1
- package/build/dist/api/modules/morpho/vault-management.js +1 -1
- package/build/dist/api/modules/morpho/vault-tools.js +1 -1
- package/build/dist/api/modules/morpho/vault-v2.js +1 -1
- package/build/dist/api/modules/netnet/card-plan.js +1 -1
- package/build/dist/api/modules/netnet/card-read.js +1 -1
- package/build/dist/api/modules/netnet/card-recovery.js +1 -1
- package/build/dist/api/modules/netnet/desk-action.js +1 -1
- package/build/dist/api/modules/netnet/desk-read.js +1 -1
- package/build/dist/api/modules/netnet/financial.js +1 -1
- package/build/dist/api/modules/netnet/index.js +1 -1
- package/build/dist/api/modules/netnet/staking.js +1 -1
- package/build/dist/api/modules/orbio/index.js +1 -1
- package/build/dist/api/modules/orbio/positions.js +1 -1
- package/build/dist/api/modules/pendle/costs.js +1 -1
- package/build/dist/api/modules/pendle/index.js +1 -1
- package/build/dist/api/modules/pendle/markets.js +1 -1
- package/build/dist/api/modules/pendle/positions.js +1 -1
- package/build/dist/api/modules/pendle/pricecheck.js +1 -1
- package/build/dist/api/modules/pendle/reader.js +1 -1
- package/build/dist/api/modules/pendle/redeem.js +1 -1
- package/build/dist/api/modules/pendle/trade.js +1 -1
- package/build/dist/api/modules/pendle/validate.js +1 -1
- package/build/dist/api/modules/pendle/verify.js +1 -1
- package/build/dist/api/modules/pons/claim.js +1 -1
- package/build/dist/api/modules/pons/index.js +1 -1
- package/build/dist/api/modules/pons/launch-status.js +1 -1
- package/build/dist/api/modules/pons/prices.js +1 -1
- package/build/dist/api/modules/pons/reads.js +1 -1
- package/build/dist/api/modules/pons/swap-terms.js +1 -1
- package/build/dist/api/modules/pons/trade.js +1 -1
- package/build/dist/api/modules/poolstrade/index.js +1 -1
- package/build/dist/api/modules/priors/coverage.js +1 -1
- package/build/dist/api/modules/priors/discovery.js +1 -1
- package/build/dist/api/modules/priors/features.js +1 -1
- package/build/dist/api/modules/priors/holdings.js +1 -1
- package/build/dist/api/modules/priors/index.js +1 -1
- package/build/dist/api/modules/priors/integration.js +1 -1
- package/build/dist/api/modules/priors/market.js +1 -1
- package/build/dist/api/modules/priors/pt.js +1 -1
- package/build/dist/api/modules/priors/savings-exit.js +1 -1
- package/build/dist/api/modules/priors/starter-line.js +1 -1
- package/build/dist/api/modules/priors/stock-swap.js +1 -1
- package/build/dist/api/modules/raeto/index.js +1 -1
- package/build/dist/api/modules/relay/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/outbound-status.js +1 -1
- package/build/dist/api/modules/relay/reads.js +1 -1
- package/build/dist/api/modules/spark/actions.js +1 -1
- package/build/dist/api/modules/spark/details.js +1 -1
- package/build/dist/api/modules/spark/index.js +1 -1
- package/build/dist/api/modules/spark/management.js +1 -1
- package/build/dist/api/modules/steakhouse/analytics.js +1 -1
- package/build/dist/api/modules/steakhouse/erc4626.js +1 -1
- package/build/dist/api/modules/steakhouse/index.js +1 -1
- package/build/dist/api/modules/steakhouse/local-guard.js +1 -1
- package/build/dist/api/modules/steakhouse/management.js +1 -1
- package/build/dist/api/modules/steakhouse/v2-exit.js +1 -1
- package/build/dist/api/modules/tickerspring/basket-routes.js +1 -1
- package/build/dist/api/modules/tickerspring/contract-reads.js +1 -1
- package/build/dist/api/modules/tickerspring/discovery.js +1 -1
- package/build/dist/api/modules/tickerspring/exit-preview.js +1 -1
- package/build/dist/api/modules/tickerspring/guards.js +1 -1
- package/build/dist/api/modules/tickerspring/index.js +1 -1
- package/build/dist/api/modules/tickerspring/journeys.js +1 -1
- package/build/dist/api/modules/tickerspring/ladder.js +1 -1
- package/build/dist/api/modules/tickerspring/maker.js +1 -1
- package/build/dist/api/modules/tickerspring/order-accounting.js +1 -1
- package/build/dist/api/modules/tickerspring/research.js +1 -1
- package/build/dist/api/modules/tickerspring/strategies.js +1 -1
- package/build/dist/api/modules/uniswap/auction-create.js +1 -1
- package/build/dist/api/modules/uniswap/auction.js +1 -1
- package/build/dist/api/modules/uniswap/batch.js +1 -1
- package/build/dist/api/modules/uniswap/common.js +1 -1
- package/build/dist/api/modules/uniswap/fees.js +1 -1
- package/build/dist/api/modules/uniswap/index.js +1 -1
- package/build/dist/api/modules/uniswap/local-guard.js +1 -1
- package/build/dist/api/modules/uniswap/oracle.js +1 -1
- package/build/dist/api/modules/uniswap/pool-math.js +1 -1
- package/build/dist/api/modules/uniswap/pools.js +1 -1
- package/build/dist/api/modules/uniswap/position.js +1 -1
- package/build/dist/api/modules/uniswap/protocol.js +1 -1
- package/build/dist/api/modules/uniswap/quote-guard.js +1 -1
- package/build/dist/api/modules/uniswap/stock-prices.d.ts +25 -0
- package/build/dist/api/modules/uniswap/stock-prices.js +1 -1
- package/build/dist/api/modules/uniswap/stocks.js +1 -1
- package/build/dist/api/modules/uniswap/token-jar.js +1 -1
- package/build/dist/api/modules/uniswap/trade-batch.js +1 -1
- package/build/dist/api/modules/uniswap/trade.js +1 -1
- package/build/dist/api/modules/uniswap/v2.js +1 -1
- package/build/dist/api/modules/uniswap/v3.js +1 -1
- package/build/dist/api/modules/uniswap/v4.js +1 -1
- package/build/dist/api/modules/uniswap/wrap.js +1 -1
- package/build/dist/api/modules/upoch/index.js +1 -1
- package/build/dist/api/modules/upoch/reads.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/scan-text.d.ts +1 -1
- package/build/dist/api/positions.js +1 -1
- package/build/dist/api/pricenote.js +1 -1
- package/build/dist/api/prices.js +1 -1
- package/build/dist/api/rpc.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.d.ts +2 -0
- package/build/dist/api/swap.js +1 -1
- package/build/dist/api/tokens.d.ts +9 -1
- package/build/dist/api/tokens.js +1 -1
- package/build/dist/api/tool-policy.js +1 -1
- package/build/dist/api/universal-router.js +1 -1
- package/build/dist/api/usd-estimate.js +1 -1
- package/build/dist/chunks/{DMDOSHV7.js → 266VIESP.js} +1 -1
- package/build/dist/chunks/{R66NSNNQ.js → 2BKZLF5A.js} +1 -1
- package/build/dist/chunks/{HFVXNKA5.js → 2BM2WX2G.js} +1 -1
- package/build/dist/chunks/{OY5W7ZSL.js → 2H2OZE6X.js} +1 -1
- package/build/dist/chunks/{E76Z2TT4.js → 2QQ5CGQI.js} +1 -1
- package/build/dist/chunks/{4PLLS6CT.js → 2VYA6WIN.js} +1 -1
- package/build/dist/chunks/{LCH6F5HT.js → 342OZP53.js} +1 -1
- package/build/dist/chunks/{C57DITTF.js → 3HF6WE4L.js} +1 -1
- package/build/dist/chunks/3M7RMROZ.js +1 -0
- package/build/dist/chunks/3RGED2KO.js +1 -0
- package/build/dist/chunks/{4HQEJHCD.js → 3XIJCHT7.js} +1 -1
- package/build/dist/chunks/3XY44BP5.js +1 -0
- package/build/dist/chunks/3YNXQ3EZ.js +1 -0
- package/build/dist/chunks/45QP74CE.js +1 -0
- package/build/dist/chunks/{SX5YNFHG.js → 4GAU3JLN.js} +1 -1
- package/build/dist/chunks/{Y2QADJOB.js → 4P6DRKY3.js} +1 -1
- package/build/dist/chunks/{W3DGFMQE.js → 4RTXP2YP.js} +1 -1
- package/build/dist/chunks/{QMIH6HXH.js → 4SXRXNHG.js} +1 -1
- package/build/dist/chunks/{ZTKT3ZQK.js → 53VBLEYS.js} +1 -1
- package/build/dist/chunks/{FRT6AC6M.js → 5677LZOV.js} +1 -1
- package/build/dist/chunks/{ADIPEGNN.js → 5AO2QPWE.js} +1 -1
- package/build/dist/chunks/{GQITAJVF.js → 5BPFF7NX.js} +1 -1
- package/build/dist/chunks/{JDHPMS7X.js → 5DWQUEBA.js} +1 -1
- package/build/dist/chunks/{WAKZWSHB.js → 5KKAN7XQ.js} +1 -1
- package/build/dist/chunks/{VVAM3EAK.js → 5N6YJFFA.js} +1 -1
- package/build/dist/chunks/{QIB6OMQV.js → 5O67QQIY.js} +1 -1
- package/build/dist/chunks/5PNFV7HH.js +1 -0
- package/build/dist/chunks/5RAZFRO4.js +1 -0
- package/build/dist/chunks/{FAH7FKUT.js → 5UWVXEPD.js} +1 -1
- package/build/dist/chunks/5VKVAUFQ.js +1 -0
- package/build/dist/chunks/5Y457HYC.js +1 -0
- package/build/dist/chunks/64LAWFBE.js +1 -0
- package/build/dist/chunks/{3BQ5XHDJ.js → 6EWSLHXL.js} +1 -1
- package/build/dist/chunks/{6F527FLN.js → 6HNQAYBM.js} +1 -1
- package/build/dist/chunks/{FUP53K6G.js → 6LDC5D2S.js} +1 -1
- package/build/dist/chunks/{TZ7S5KRB.js → 6QXTL65K.js} +1 -1
- package/build/dist/chunks/6RVAV6BB.js +1 -0
- package/build/dist/chunks/{WSILNJS2.js → 6STUQOFL.js} +1 -1
- package/build/dist/chunks/{RUHNLNVX.js → 6Y2546JA.js} +1 -1
- package/build/dist/chunks/{4Z3IGMU6.js → 7AYP4ATZ.js} +1 -1
- package/build/dist/chunks/{YGW4ODAP.js → 7EPU3XGY.js} +1 -1
- package/build/dist/chunks/7GL547YZ.js +1 -0
- package/build/dist/chunks/7JTXYMNP.js +1 -0
- package/build/dist/chunks/{A3BJSQ23.js → 7VU5VCTL.js} +1 -1
- package/build/dist/chunks/{Z7FGEWO2.js → 7WXAS54T.js} +1 -1
- package/build/dist/chunks/{WQ2XTDHO.js → 7X5JVF3F.js} +1 -1
- package/build/dist/chunks/{DRLBTB4E.js → A72ADVYF.js} +1 -1
- package/build/dist/chunks/{ANIF3JMV.js → AG66NM3J.js} +1 -1
- package/build/dist/chunks/AODUTN65.js +1 -0
- package/build/dist/chunks/{DBOGRUPS.js → AONO47JX.js} +1 -1
- package/build/dist/chunks/{JTPHZCO3.js → AQJLEG6B.js} +1 -1
- package/build/dist/chunks/AZBTNUXF.js +1 -0
- package/build/dist/chunks/{TOIKOIY6.js → B5BU645H.js} +1 -1
- package/build/dist/chunks/{ZX43P4BK.js → B75SS7H6.js} +1 -1
- package/build/dist/chunks/{GBIBRYOV.js → B7HVPHSS.js} +1 -1
- package/build/dist/chunks/{LT5P6PZW.js → B7WZJHIJ.js} +1 -1
- package/build/dist/chunks/{3A2IKFTV.js → BIFANUTV.js} +1 -1
- package/build/dist/chunks/BM4KHOFB.js +1 -0
- package/build/dist/chunks/{N65J3L2H.js → BSV65PCA.js} +1 -1
- package/build/dist/chunks/{ZVY7GGSP.js → BW755PNH.js} +1 -1
- package/build/dist/chunks/{VXCGMALF.js → BWE5PXRE.js} +1 -1
- package/build/dist/chunks/{7U62MMUQ.js → BY2OWKZB.js} +1 -1
- package/build/dist/chunks/{CNDIAF3P.js → C2H3BWN5.js} +1 -1
- package/build/dist/chunks/{F7MGYRPU.js → CCPG6PRL.js} +1 -1
- package/build/dist/chunks/{OI3N4EW4.js → CG7ABZXH.js} +1 -1
- package/build/dist/chunks/CJMVRV34.js +1 -0
- package/build/dist/chunks/CQPIR6ER.js +1 -0
- package/build/dist/chunks/{A4K5GXVO.js → CR7DPGI6.js} +1 -1
- package/build/dist/chunks/{UUF4Z6K6.js → CVVNAFUE.js} +1 -1
- package/build/dist/chunks/{MI5HZDMH.js → D6JOXK7Q.js} +1 -1
- package/build/dist/chunks/{2PS4GCOZ.js → DJRS3TR5.js} +1 -1
- package/build/dist/chunks/{IZFED3R2.js → DLNDJZR4.js} +1 -1
- package/build/dist/chunks/{MQXSCNUL.js → DPSFR3ZS.js} +1 -1
- package/build/dist/chunks/{LKUZAJPZ.js → DV2HVFTM.js} +1 -1
- package/build/dist/chunks/{NMJVQX5M.js → DWRRIFXS.js} +1 -1
- package/build/dist/chunks/{3ZH5SOC2.js → EFOC337C.js} +1 -1
- package/build/dist/chunks/EHQRAA3R.js +1 -0
- package/build/dist/chunks/{A4FLWHLP.js → EJIP7RBG.js} +1 -1
- package/build/dist/chunks/EWZFZUVF.js +1 -0
- package/build/dist/chunks/{OB7BFDOV.js → EYE3ZAJB.js} +1 -1
- package/build/dist/chunks/{MQ5F2VOK.js → EZUQMTLE.js} +1 -1
- package/build/dist/chunks/{O2QBSINK.js → F36IA5RI.js} +1 -1
- package/build/dist/chunks/{XTXXWRN2.js → F74ARK4H.js} +1 -1
- package/build/dist/chunks/{HPS4KOU4.js → FGGDAAHW.js} +1 -1
- package/build/dist/chunks/FMEO7RX7.js +1 -0
- package/build/dist/chunks/{FHB7QYJO.js → FN6XY6ET.js} +1 -1
- package/build/dist/chunks/G4IX4CYN.js +1 -0
- package/build/dist/chunks/G53U6Y4L.js +1 -0
- package/build/dist/chunks/{HDBZZOHJ.js → GBIL2I2K.js} +1 -1
- package/build/dist/chunks/{MJGEGNDU.js → GCFHKJIO.js} +1 -1
- package/build/dist/chunks/{O5QTITN6.js → GRHBE4MQ.js} +1 -1
- package/build/dist/chunks/GTJ6LBGB.js +1 -0
- package/build/dist/chunks/GV6Z3MET.js +1 -0
- package/build/dist/chunks/{GK3D7OKG.js → GVCNTGLC.js} +1 -1
- package/build/dist/chunks/GX2RCAHG.js +1 -0
- package/build/dist/chunks/{7TRO6MBQ.js → H5KU4DUU.js} +1 -1
- package/build/dist/chunks/H7ZJ7LAB.js +1 -0
- package/build/dist/chunks/{DCGNVMKG.js → HC3QFA5I.js} +1 -1
- package/build/dist/chunks/{6CKCZJ3F.js → HEQBTHFS.js} +1 -1
- package/build/dist/chunks/{C76D54YG.js → HGSFRN57.js} +1 -1
- package/build/dist/chunks/HJI7KO6F.js +1 -0
- package/build/dist/chunks/{KO7ANIKY.js → HNBYPHTA.js} +1 -1
- package/build/dist/chunks/{MSRCJ2BS.js → HPBTSJW7.js} +1 -1
- package/build/dist/chunks/HPO673QQ.js +1 -0
- package/build/dist/chunks/{4IOHSX3Z.js → HRGLFGFL.js} +1 -1
- package/build/dist/chunks/{DGDMRATN.js → ICHT3H3W.js} +1 -1
- package/build/dist/chunks/IJVBCEA2.js +1 -0
- package/build/dist/chunks/{N742W5KX.js → IKVRFAUP.js} +1 -1
- package/build/dist/chunks/IM7ZF7XZ.js +1 -0
- package/build/dist/chunks/{I4473OC6.js → IMD33NQS.js} +1 -1
- package/build/dist/chunks/IR7KDBFU.js +1 -0
- package/build/dist/chunks/{X24YTJST.js → IY7FWTAL.js} +1 -1
- package/build/dist/chunks/IYOWMW5B.js +1 -0
- package/build/dist/chunks/J2J73XYU.js +1 -0
- package/build/dist/chunks/JCS24YBB.js +1 -0
- package/build/dist/chunks/JQVTHPUO.js +1 -0
- package/build/dist/chunks/{USGMGKAG.js → JTWJT2O3.js} +1 -1
- package/build/dist/chunks/{W7BFM6CK.js → K4CYAWNL.js} +1 -1
- package/build/dist/chunks/{7VH6JQ2H.js → K5C6QBOO.js} +1 -1
- package/build/dist/chunks/K5OXLIPK.js +1 -0
- package/build/dist/chunks/{ZKBOPZH5.js → K6GECT3F.js} +1 -1
- package/build/dist/chunks/{6LVHN33V.js → KB2JWQZ4.js} +1 -1
- package/build/dist/chunks/{YW4W3LPQ.js → KHLM6NIZ.js} +1 -1
- package/build/dist/chunks/{OIQTZOBN.js → KKGHXNM4.js} +1 -1
- package/build/dist/chunks/{SUNTJ6IU.js → KYANIEPX.js} +1 -1
- package/build/dist/chunks/{JJSCDDQO.js → L3IAEXQR.js} +1 -1
- package/build/dist/chunks/{ZZ6FZGHF.js → L4UFGM7M.js} +1 -1
- package/build/dist/chunks/{YWVPK3DV.js → L76P6WIH.js} +1 -1
- package/build/dist/chunks/{QMNUB2GM.js → LBT6WR4U.js} +1 -1
- package/build/dist/chunks/LD3A2KLN.js +1 -0
- package/build/dist/chunks/{WRUTW6CG.js → LFSNAQ7V.js} +1 -1
- package/build/dist/chunks/{ZQPC54J5.js → LKRAUTYI.js} +1 -1
- package/build/dist/chunks/{23HNDJ76.js → M2SWILNG.js} +1 -1
- package/build/dist/chunks/{IT2JLILU.js → MFKDNAHB.js} +1 -1
- package/build/dist/chunks/MFQTBUSD.js +1 -0
- package/build/dist/chunks/{V4UJMUIB.js → MLN5KTG7.js} +1 -1
- package/build/dist/chunks/{S4JUFCT4.js → MSQNOK3I.js} +1 -1
- package/build/dist/chunks/{O4P5IQCP.js → MXI7LX2F.js} +1 -1
- package/build/dist/chunks/N6YNJGEF.js +1 -0
- package/build/dist/chunks/{DXAPKN7H.js → NLC36QHL.js} +1 -1
- package/build/dist/chunks/NUTTPUYJ.js +1 -0
- package/build/dist/chunks/{O4S6XAYV.js → O7L55XM3.js} +1 -1
- package/build/dist/chunks/{NAO7VWZF.js → OCIEVYPR.js} +1 -1
- package/build/dist/chunks/{4NBXBKOX.js → OD7CY6BY.js} +1 -1
- package/build/dist/chunks/{RUTSEGGD.js → OHZHQSCA.js} +1 -1
- package/build/dist/chunks/{E47UYYK4.js → OIGTTRN5.js} +1 -1
- package/build/dist/chunks/{2I7XHRTI.js → P6JE2NRA.js} +1 -1
- package/build/dist/chunks/PD5NXIRT.js +1 -0
- package/build/dist/chunks/{TXGZ6NWN.js → PG7HZIZL.js} +1 -1
- package/build/dist/chunks/{VREGY7E6.js → PMFR47H3.js} +1 -1
- package/build/dist/chunks/{PV7FEVBD.js → PXVF2SHU.js} +1 -1
- package/build/dist/chunks/{2FOI2625.js → Q43WPRYU.js} +1 -1
- package/build/dist/chunks/QAAKUIWE.js +1 -0
- package/build/dist/chunks/{ZXFJKW6H.js → QAVP3CWL.js} +1 -1
- package/build/dist/chunks/{YXXK6EPI.js → QBHY2QRC.js} +1 -1
- package/build/dist/chunks/{ELHRXA5U.js → QFK335LC.js} +1 -1
- package/build/dist/chunks/{3PHJUFU2.js → QFUSCK5C.js} +1 -1
- package/build/dist/chunks/{IPU656WB.js → QKH7ED6B.js} +1 -1
- package/build/dist/chunks/{XW3VGWXK.js → QMWHQRYC.js} +1 -1
- package/build/dist/chunks/{ZXRIJG6H.js → QP2B7AYX.js} +1 -1
- package/build/dist/chunks/{TJU644I7.js → QZ6V6J6W.js} +1 -1
- package/build/dist/chunks/{MDLJFCT4.js → R5Z4HPCA.js} +1 -1
- package/build/dist/chunks/RKJFSDGV.js +1 -0
- package/build/dist/chunks/RKS3M7L5.js +1 -0
- package/build/dist/chunks/{GDOHHXNH.js → RLX6YTNT.js} +1 -1
- package/build/dist/chunks/{IZP3EKKS.js → RYEQIZ2H.js} +1 -1
- package/build/dist/chunks/{USEF3QKG.js → S432S6NA.js} +1 -1
- package/build/dist/chunks/{2OVJ2BTJ.js → SEXKWYUM.js} +1 -1
- package/build/dist/chunks/{KKTOBXIT.js → SRYX65GZ.js} +1 -1
- package/build/dist/chunks/{GKUPC4DO.js → TMENUIBC.js} +1 -1
- package/build/dist/chunks/{BSX4LFYI.js → TNHU5UBQ.js} +1 -1
- package/build/dist/chunks/{PDPTJMTJ.js → TT2ST3Q3.js} +1 -1
- package/build/dist/chunks/TTBB6EFN.js +1 -0
- package/build/dist/chunks/{FRVCSDKU.js → TWVDWNTG.js} +1 -1
- package/build/dist/chunks/TZG7HTVM.js +1 -0
- package/build/dist/chunks/{OVM4QIET.js → U4MSIH4G.js} +1 -1
- package/build/dist/chunks/{G5AMH4IP.js → UGFRBJDQ.js} +1 -1
- package/build/dist/chunks/{OB3YMTDI.js → UIVOYAO2.js} +1 -1
- package/build/dist/chunks/{XRDLMTBJ.js → UMY6SP7C.js} +1 -1
- package/build/dist/chunks/UNBRUWSV.js +1 -0
- package/build/dist/chunks/{LGLWEGPY.js → UPX3OWKA.js} +1 -1
- package/build/dist/chunks/{TGXEKBLV.js → URTQNYWU.js} +1 -1
- package/build/dist/chunks/{4RCYYN6O.js → V7HTGO23.js} +1 -1
- package/build/dist/chunks/{HZSYMGJ2.js → VS7ZA4OF.js} +1 -1
- package/build/dist/chunks/{BJ2U2VXJ.js → VTWAVH74.js} +1 -1
- package/build/dist/chunks/{LZM3DO5Q.js → W5GWK72I.js} +1 -1
- package/build/dist/chunks/{65OITTDL.js → W73SLWBT.js} +1 -1
- package/build/dist/chunks/{3YH5B5NQ.js → WUONMIA2.js} +1 -1
- package/build/dist/chunks/{XL3W7DAQ.js → X3BB6WME.js} +1 -1
- package/build/dist/chunks/{XADHV2DT.js → X53QVHBC.js} +1 -1
- package/build/dist/chunks/{GBPB7JIB.js → XSQJOOEY.js} +1 -1
- package/build/dist/chunks/XUDQYSPU.js +1 -0
- package/build/dist/chunks/{S37D7HOK.js → XWZ5SL5Q.js} +1 -1
- package/build/dist/chunks/{NIWAVMDR.js → XXLQDQEX.js} +1 -1
- package/build/dist/chunks/{QBNASL3T.js → Y5T36EEU.js} +1 -1
- package/build/dist/chunks/{R73R4KN3.js → YBLJ2MCR.js} +1 -1
- package/build/dist/chunks/ZSGW2ZSO.js +1 -0
- package/build/dist/chunks/{HRAHGYNK.js → ZTNBX4VH.js} +1 -1
- package/package.json +1 -1
- package/build/dist/chunks/5H7NVE6O.js +0 -1
- package/build/dist/chunks/7OOCAZBE.js +0 -1
- package/build/dist/chunks/DFM4T6ZE.js +0 -1
- package/build/dist/chunks/FCVH4FYH.js +0 -1
- package/build/dist/chunks/GDUKZYE2.js +0 -1
- package/build/dist/chunks/GYPMUYB5.js +0 -1
- package/build/dist/chunks/J7OZLXSG.js +0 -1
- package/build/dist/chunks/JFC2QCMW.js +0 -1
- package/build/dist/chunks/M6JNGU4E.js +0 -1
- package/build/dist/chunks/M7OVMIIE.js +0 -1
- package/build/dist/chunks/MQK6OP7S.js +0 -1
- package/build/dist/chunks/N624NR7Y.js +0 -1
- package/build/dist/chunks/OSMOBKRQ.js +0 -1
- package/build/dist/chunks/Q3Q3YHEX.js +0 -1
- package/build/dist/chunks/QQD4PV64.js +0 -1
- package/build/dist/chunks/RN3WUJIO.js +0 -1
- package/build/dist/chunks/RP5VCG54.js +0 -1
- package/build/dist/chunks/TI727O2H.js +0 -1
- package/build/dist/chunks/UHIJMDD2.js +0 -1
- package/build/dist/chunks/W32UECOL.js +0 -1
- package/build/dist/chunks/WWNAGOCD.js +0 -1
- package/build/dist/chunks/XWC6IC5E.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as oe}from"./3CCBUYUM.js";import{a as xt,d as It,e as Tt}from"./ZTKT3ZQK.js";import{a as Ge}from"./7MR37STI.js";import{a as Ze,b as Ee,d as At}from"./X24YTJST.js";import{h as Je,i as St}from"./2GXHYI23.js";import{b as kt,c as yt,d as gt}from"./N624NR7Y.js";import{d as wt,e as te}from"./GYPMUYB5.js";import{a as ht}from"./Z7FGEWO2.js";import{b as bt}from"./SPJCSEKP.js";import{a as q}from"./43LI5NKJ.js";import{a as A,d as W}from"./66F5ZH34.js";import{d as Ne,g as R,i as Oe}from"./NWNYJ26T.js";import{b as Le}from"./IX3GZMTM.js";import{o as ft}from"./MQ5F2VOK.js";import{b as f,j as z}from"./TI727O2H.js";import{a as i,e as ie}from"./XSD5NL7J.js";import{a as Ye}from"./JXOEJPJ4.js";import{encodeFunctionData as be,erc20Abi as Xo,getAddress as ao,parseAbi as pt,zeroAddress as Yo}from"viem";import{decodeAbiParameters as mo,encodeFunctionData as po,getAddress as le,parseAbiParameters as fo,zeroAddress as he,zeroHash as Dt}from"viem";import{decodeAbiParameters as no,encodeFunctionData as so,erc20Abi as io,getAddress as Ct,parseAbi as lo,parseAbiParameters as co,zeroHash as Mt}from"viem";var et=Ct("0xCE29862924756584BBD0D75CA1249d22007E2813"),Lt="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",uo="(uint256 value,uint256 nonce,uint256 deadline,uint8 v,bytes32 r,bytes32 s)",vt=lo(["function BLUE() view returns (address)",`function vaultExitBundlesV1InKindRedemptionVaultV2(address vault,address adapter,${Lt}[] marketParamsList,uint256 exitAssets,${uo} sharesPermit,uint256 deadline)`]);function O(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 Pt=(e,t)=>e<t?e:t;async function la(e,t,s,r,n){q(n);let l=O(r.amount),o=O(r.maxShares),a=O(r.maxPenaltyAssets,!0),u=O(r.deadline),c=e.clientFor(f),m=await At(c,t,s),d=(S,N,Ce,ee=[])=>c.readContract({address:S,abi:N,functionName:Ce,args:ee,blockNumber:m.blockNumber}),[p,h,b,w]=await Promise.all([c.getBlock({blockNumber:m.blockNumber}),d(et,vt,"BLUE"),d(t,io,"balanceOf",[n]),d(t,Ze,"previewRedeem",[o])]);if(typeof h!="string"||Ct(h)!==B)throw new i("VaultExitBundlesV1 does not report the pinned Morpho Blue.");if(u<p.timestamp||u>p.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");if(o>Ee(b))throw new i("maxShares exceeds the wallet share balance.");let k=Pt(m.idle,l),y=m.markets.filter(S=>S.supplied>0n&&j(S.id)),g=l-k,I=y[0]?.penalty??0n,x=g*10n**18n/(10n**18n+I);if(g>0n&&x===0n)throw new i("The penalty-adjusted in-kind amount rounds to zero.");let T=[];for(let S of y){if(x===0n)break;let N=Pt(S.supplied,x);T.push({marketId:S.id,assets:N,penalty:(N*S.penalty+10n**18n-1n)/10n**18n}),x-=N}if(x>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(T.length)>Ee(w))throw new i("maxShares cannot cover the exit and per-market rounding buffer.");if(T.some(S=>S.assets>m.blueCash))throw new i("Morpho Blue cannot fund the largest in-kind callback. Reduce the amount.");let P=T.reduce((S,N)=>S+N.penalty,0n);if(P>a)throw new i("In-kind penalty exceeds maxPenaltyAssets.");let C=[...k?[k]:[],...T.flatMap(S=>[S.assets,S.penalty].filter(N=>N>0n))],v=(await Promise.all(C.map(S=>d(t,Ze,"previewWithdraw",[S])))).reduce((S,N)=>S+Ee(N),0n);if(v===0n||v>o)throw new i("Separately rounded burns exceed maxShares.");let Z=T.map(S=>no(co(Lt),m.markets.find(N=>N.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 ${v} share base units; receive ${k} ${s.symbol} base units and Morpho Blue supply positions ${T.map(S=>`${S.marketId}: ${S.assets} ${s.symbol} base units`).join(", ")||"none"}. Penalty ${P} ${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.`,M=so({abi:vt,functionName:"vaultExitBundlesV1InKindRedemptionVaultV2",args:[t,H,Z,l,{value:0n,nonce:0n,deadline:0n,v:0,r:Mt,s:Mt},u]}),$=[e.approval(t,et,v.toString(),f),e.unsignedTx({to:et,data:M,value:"0",chainId:f,description:F})],U=await e.preview($,n),V=-U.changes.filter(S=>S.token.chainId===f&&R(S.token.address,t)).reduce((S,N)=>{if(N.token.decimals!==18||!/^-?\d+$/.test(N.amount))throw new i("Invalid in-kind share preview.");return S+BigInt(N.amount)},0n);if(V<=0n||V>v)throw new i("In-kind preview exceeds the exact share authorization or burns no shares.");return{txs:$,preview:U,summary:F,receipt:{idleAssets:k.toString(),positions:T.map(S=>({marketId:S.marketId,asset:s,assets:S.assets.toString()})),penaltyAssets:P.toString()}}}var we=le("0x53A1eB6589861F686af7c531211E35Aefe30210f"),Ut=["supply","withdraw","supplyCollateralAndBorrow","repayAndWithdrawCollateral","migrateBorrowPosition"],tt={kind:0,data:"0x"},Re={nonce:0n,deadline:0n,signature:{v:0,r:Dt,s:Dt}},bo=fo("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),$t=e=>({tools:[{name:"morpho_bundle",inputSchema:{type:"object",additionalProperties:!1,required:["operation","marketId","deadline"],properties:{operation:{type:"string",enum:Ut,description:"Bundle: supply, withdraw, supplyCollateralAndBorrow, repayAndWithdrawCollateral, or migrateBorrowPosition (move debt to destinationMarketId)."},marketId:{type:"string",description:"Verified Morpho Blue market id (0x + 64 hex digits); the source market for migrateBorrowPosition."},destinationMarketId:{type:"string",description:"Only for migrateBorrowPosition: verified market id (0x + 64 hex) to move the borrow into; must share the same tokens."},assets:A(`Amount of the market's loan token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`),collateralAssets:A(`Collateral amount in base units of the market's collateral token (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`),shares:A("Market share amount in base units (supply or borrow shares, read the position), instead of assets. Give assets or shares, not both."),maxRepayAssets:A('Most loan token you accept paying to repay, in base units of the loan token (read its decimals). Example: "1000000" = 1 USDG.'),maxLtv:A("Highest loan-to-value allowed after the bundle, as an 18-decimal wad in base units (0.8e18 = 80 percent); cannot exceed the market LLTV."),deadline:A("Absolute Unix seconds deadline, no more than five minutes ahead. Example: 1800000000."),allocations:{type:"array",maxItems:4,description:"Up to four Public Allocator moves that add liquidity to the market before borrowing or withdrawing; one per vault.",items:{type:"object",additionalProperties:!1,required:["vault","assets","maxPenaltyAssets"],properties:{vault:{type:"string",description:"Pinned NetNet or Longbow V2 vault address (0x + 40 hex) to pull liquidity from; one entry per vault."},sourceMarketId:{type:"string",description:"Source market id (0x + 64 hex) to pull from; omit to allocate idle vault assets."},assets:A(`Amount to reallocate, in base units of the vault's asset (USDG 6 decimals, WETH 18). Example: "1000000" = 1 USDG.`),maxPenaltyAssets:A(`Highest allocator penalty you accept, in base units of the vault's asset. Example: "10000" = 0.01 USDG for a 6-decimal asset.`)}}}}},execute:async(t,s)=>{try{q(s);let r=t.operation,n=e.clientFor(f);if(await n.getChainId()!==f||typeof r!="string"||!Ut.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(M=>!l.includes(M)))throw new i("Unexpected argument for this Blue bundle.");let o=await n.getBlock(),a=O(t.deadline);if(a<o.timestamp||a>o.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");let[u,c]=await Promise.all([n.readContract({address:we,abi:Ge,functionName:"BLUE",blockNumber:o.number}),n.readContract({address:we,abi:Ge,functionName:"PUBLIC_ALLOCATOR",blockNumber:o.number})]);if(le(u)!==B||le(c)!==xt)throw new i("BlueBundlesV1 deployment does not match Oak\u2019s pinned Blue and Public Allocator.");let m=async M=>{if(typeof M!="string"||!j(M))throw new i("Choose a verified Morpho market with a supported exit.");let $=await n.readContract({address:B,abi:E,functionName:"idToMarketParams",args:[M],blockNumber:o.number}),U={loanToken:le($[0]),collateralToken:le($[1]),oracle:le($[2]),irm:le($[3]),lltv:$[4]};if(!R(ke({...U,lltv:String(U.lltv)}),M))throw new i("Blue bundle market identity mismatch.");return U},d=await m(t.marketId),p=r==="migrateBorrowPosition"?await m(t.destinationMarketId):d;if(d.loanToken!==p.loanToken||d.collateralToken!==p.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:B,abi:E,functionName:"isAuthorized",args:[s,we],blockNumber:o.number}))throw new i(`Authorize the pinned Blue bundle explicitly with morpho_manage setAuthorization account ${we}, enabled true, then retry. That authority covers all Blue positions. Revoke it with enabled false after the bundle.`);let h=t.assets===void 0?0n:O(t.assets,!0),b=t.shares===void 0?0n:O(t.shares,!0),w=t.collateralAssets===void 0?0n:O(t.collateralAssets,!0),k=r==="supply"||r==="withdraw"?0n:O(t.maxLtv,!0);if(k>p.lltv)throw new i("maxLtv cannot exceed the verified destination market LLTV.");if(r==="supply"&&h===0n||r==="withdraw"&&h===0n==(b===0n)||r==="supplyCollateralAndBorrow"&&w===0n&&h===0n||r==="repayAndWithdrawCollateral"&&(h>0n&&b>0n||h===0n&&b===0n&&w===0n))throw new i("Choose a nonzero amount; assets and shares are mutually exclusive for repayment/withdrawal.");let y=t.allocations??[];if(!Array.isArray(y)||y.length>4||y.length&&r==="supplyCollateralAndBorrow"&&h===0n)throw new i("Provide at most four explicit allocations, only with a borrow or withdrawal.");let g=new Set,I=[],x=0n;for(let M of y){if(!M||typeof M!="object"||Array.isArray(M)||Object.keys(M).some(Xe=>!["vault","sourceMarketId","assets","maxPenaltyAssets"].includes(Xe)))throw new i("Unsupported bundled allocation input.");let $=M,U=await It(e,{vault:$.vault,marketId:r==="migrateBorrowPosition"?t.destinationMarketId:t.marketId});if(g.has(U.definition.vault.toLowerCase()))throw new i("Use each source vault at most once per bundle.");g.add(U.definition.vault.toLowerCase());let V=O($.assets),S=O($.maxPenaltyAssets,!0);if(!U.permission||V>=1n<<128n||V>U.headroom||U.penalty>10n**18n||U.asset.address!==p.loanToken)throw new i("Bundled allocation is disabled, unqualified or exceeds target capacity.");let N=(V*U.penalty+10n**18n-1n)/10n**18n;if(N>S)throw new i("Bundled allocation exceeds maxPenaltyAssets.");x+=N;let Ce=$.sourceMarketId===void 0,ee=Ce?void 0:U.sources.find(Xe=>R(Xe.id,String($.sourceMarketId)));if(Ce?!U.canIdle||V>U.data.idle:!ee||!ee.canPull||V>ee.capacity||V>U.data.blueCash)throw new i("Bundled allocation source cannot cover the requested amount.");I.push({vault:U.definition.vault,adapter:U.target.adapter,marketParams:U.params,sourceAdapter:ee?.adapter??he,sourceMarketParams:ee?mo(bo,ee.data)[0]:U.params,assets:V,penalty:U.penalty,fromIdle:Ce})}let T,P,C,L=0n;if(r==="supply")T="blueBundlesV1Supply",C=d.loanToken,L=h,P=[d,h,tt,0n,he,a];else if(r==="withdraw")T="blueBundlesV1Withdraw",P=[d,h,b,Re,I,0n,he,a];else if(r==="supplyCollateralAndBorrow"){if(T="blueBundlesV1SupplyCollateralAndBorrow",C=d.collateralToken,L=w,x>=h&&x>0n)throw new i("Allocation penalties would consume the borrow proceeds.");P=[d,w,h,k,tt,Re,I,0n,he,a]}else if(r==="repayAndWithdrawCollateral"){if(T="blueBundlesV1RepayAndWithdrawCollateral",C=d.loanToken,L=O(t.maxRepayAssets,!0),h>L||b>0n&&L===0n)throw new i("Repayment requires a sufficient maxRepayAssets budget.");P=[d,h,b,L,w,k,tt,Re,0n,he,a]}else T="blueBundlesV1MigrateBorrowPosition",P=[d,p,k,Re,I,0n,he,a];let v=`Morpho Blue atomic ${r}: ${JSON.stringify(t)}. Allocation penalties ${x} loan-token base units; zero referral fee. Max LTV ${k}; absolute deadline ${a}. Migration adds allocation penalties to destination debt; borrowing deducts them from proceeds. Exact input approval ${L}. Existing Blue bundle authorization remains until explicitly revoked with morpho_manage. No opaque callback, permit or signature is accepted.`,Z=[...C&&L?[e.approval(C,we,L.toString(),f)]:[],e.unsignedTx({to:we,data:po({abi:Ge,functionName:T,args:P}),value:"0",chainId:f,description:v})],H=await e.preview(Z,s),F=new Map;for(let M of H.changes)if(BigInt(M.amount)<0n){let $=M.token.address.toLowerCase();F.set($,(F.get($)??0n)-BigInt(M.amount))}if([...F].some(([M,$])=>!C||M!==C.toLowerCase()||$>L))throw new i("Bundle preview spends outside the exact input budget.");return{txs:Z,preview:H,summary:v}}catch(r){throw new i(e.plainError(r))}}}]});import{concatHex as Bt,decodeAbiParameters as ho,encodeAbiParameters as Rt,encodeFunctionData as ot,erc20Abi as Nt,getAddress as K,keccak256 as rt,zeroAddress as ye,zeroHash as wo}from"viem";var Y=K("0x6120765Ba5336150BbdDdD0Cd9108B5bFD369632"),ko=["0x90B800999e4ACd1bD20283BD450bBd2e06D91F7C","0x708d6Bf6F847202a0755bb5636bE663B174242ea"].map(e=>K(e)),nt=oe.find(e=>e.name==="take"),Ot=[nt.inputs[0]],yo=[nt.inputs[0].components[0]];function Et(e){let t=rt(Bt(["0x600b380380600b5f395ff3",Rt(yo,[e])]));return rt(Bt(["0xff",e.midnight,wo,t]))}var de=10n**18n,Gt=(e,t)=>(e+(t-1n)/2n)/t;function _t(e){if(e<0n)return 10n**36n/_t(-e);let t=693147180559945309n,s=(e+322611214989459870n)/t,r=e-s*t,n=r*r/(2n*de),l=n*r/(3n*de);return de+r+n+l<<s}function go(e){if(e<0n||e>6744n)throw new i("Midnight tick is outside 0..6744.");return Gt(Gt(10n**36n,de+_t(4987541511039073n*(3372n-e))),10n**11n)*10n**11n}function _e(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 at(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 So=e=>JSON.parse(JSON.stringify(e,(t,s)=>typeof s=="bigint"?s.toString():s)),Ht=e=>{async function t(n,l){let o=_e(n,32),a=e.clientFor(f);if(await a.getChainId()!==f)throw new i("Midnight requires chain 4663.");let u=await a.getBlock(),c=(y,g=[])=>a.readContract({address:Y,abi:oe,functionName:y,args:g,blockNumber:u.number}),m=await c("toMarket",[o]);if(m.chainId!==BigInt(f)||K(m.midnight)!==Y||!R(Et(m),o))throw new i("Midnight market identity does not match the pinned chain and contract.");if(![z[f].tokens.USDG.address,z[f].tokens.WETH.address].some(y=>R(y,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[p,h,b,w]=await Promise.all([c("position",[o,l]),c("updatePositionView",[m,o,l]),c("marketState",[o]),c("isHealthy",[m,o,l])]),k=async y=>{let[g,I]=await Promise.all([a.readContract({address:y,abi:Nt,functionName:"decimals",blockNumber:u.number}),a.readContract({address:y,abi:Nt,functionName:"symbol",blockNumber:u.number})]);if(!Number.isInteger(g)||g>36||typeof I!="string")throw new i("Invalid Midnight token metadata.");return{address:K(y),decimals:g,symbol:I.replace(/[^a-zA-Z0-9.$_-]/g,"").slice(0,32),chainId:f}};return{id:o,rpc:a,block:u,market:m,read:c,token:k,loan:await k(m.loanToken),position:at(p,6),updated:at(h,3),state:at(b,13),healthy:w}}let s=(n,l,o,a)=>({name:n,inputSchema:{type:"object",properties:l,required:o,additionalProperties:!1},execute:async(u,c)=>{try{if(q(c),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Midnight argument.");return await a(u,c)}catch(m){throw new i(e.plainError(m))}}});async function r(n,l,o){return{txs:n,preview:await e.preview(n,l),summary:o}}return{tools:[s("morpho_midnight_status",{marketId:{type:"string",description:"Midnight market id: 0x + 64 hex digits (bytes32)."}},["marketId"],async(n,l)=>{let o=await t(n.marketId,l),a=await Promise.all(o.market.collateralParams.map(async(m,d)=>({token:await o.token(m.token),lltvWad:m.lltv.toString(),oracle:m.oracle,assets:String(await o.read("collateral",[o.id,l,BigInt(d)]))}))),u=["configurator","feeSetter","feeClaimer","tickSpacingSetter"],c=await Promise.all(u.map(m=>o.read(m)));return{protocol:Object.fromEntries(u.map((m,d)=>[m,K(String(c[d]))])),continuousFeePerSecondWad:String(o.state[11]),tickSpacing:String(o.state[12]),settlementFeeCbps:o.state.slice(4,11).map(String),settlementFeeCbpWadScale:"1000000000000",chainId:f,midnight:Y,marketId:o.id,blockNumber:String(o.block.number),market:So(o.market),loanToken:o.loan,collaterals:a,debtUnits:String(o.position[4]),creditUnits:String(o.updated[0]),pendingFeeUnits:String(o.updated[1]),withdrawableUnits:String(o.state[2]),healthy:o.healthy,maturity:String(o.market.maturity),matured:o.block.timestamp>o.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",description:"Hex proof data (0x...) that the offer's pinned ratifier uses to confirm the maker approved this offer."},units:A("Fixed debt units to trade, as a decimal string below 2^128. The asset cost or proceeds follow from the offer price; maxAssets and minAssets bound them."),maxAssets:A('Most loan token you will spend when buying credit, in base units of the market loan token (read its decimals). Example: "1000000" = 1 USDG.'),minAssets:A('Least loan token you must receive when selling credit or borrowing, in base units of the market loan token. Example: "1000000" = 1 USDG.')},["offer","ratifierData","units","maxAssets","minAssets"],async(n,l)=>{let o=_e(n.offer),[a]=ho(Ot,o);if(!R(Rt(Ot,[a]),o))throw new i("Offer encoding is not canonical.");let u=await t(Et(a.market),l),c=O(n.units),m=O(n.maxAssets,!0),d=O(n.minAssets,!0),p=_e(n.ratifierData);if(c>=1n<<128n||R(a.maker,l)||a.callback!==ye||a.callbackData!=="0x"||!ko.includes(K(a.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<a.start||u.block.timestamp>a.expiry||a.expiry<a.start)throw new i("The Midnight offer is not currently live.");if(a.buy&&a.receiverIfMakerIsSeller!==ye||!a.buy&&a.receiverIfMakerIsSeller===ye)throw new i("Invalid offer seller receiver.");if(a.buy&&u.block.timestamp>u.market.maturity&&c>u.updated[0])throw new i("Post-maturity sales cannot increase this wallet\u2019s debt.");let h=await u.read("settlementFee",[u.id,u.market.maturity>u.block.timestamp?u.market.maturity-u.block.timestamp:0n]),b=go(a.tick);if(h>b&&a.buy)throw new i("Settlement fee exceeds the offer price.");let w=a.buy?b-h:b,k=w+h,y=M=>a.buy?M/de:(M+de-1n)/de,g=y(c*k),I=y(c*w);if(a.buy?I<d||I===0n:g>m||g===0n)throw new i("Midnight proceeds/spend do not fit the requested bounds.");let x=await u.read("consumed",[a.maker,a.group]);if(a.maxAssets===0n==(a.maxUnits===0n)||x+(a.maxAssets?a.buy?g:I:c)>(a.maxAssets||a.maxUnits))throw new i("Midnight offer capacity is exhausted or invalid.");if(u.state[11]>a.continuousFeeCap||a.tick%u.state[12]!==0n)throw new i("Offer fee cap or market tick spacing no longer permits execution.");let T=await u.read("isAuthorized",[a.maker,a.ratifier]),P=[{type:"function",name:"isRatified",stateMutability:"view",inputs:[nt.inputs[0],{type:"bytes"},{type:"address"}],outputs:[{type:"bytes32"}]}],C=await u.rpc.readContract({address:a.ratifier,abi:P,functionName:"isRatified",args:[a,p,l],blockNumber:u.block.number});if(T!==!0||C!==rt(new TextEncoder().encode("morpho.midnight.callbackSuccess")))throw new i("The maker has not authorized and ratified this exact offer.");let L=ot({abi:oe,functionName:"take",args:[a,p,c,l,a.buy?l:ye,ye,"0x"]}),v=`Midnight ${a.buy?"sell credit or borrow":"buy credit or reduce debt"}: ${c} fixed debt units; ${a.buy?`receive ${I}`:`spend ${g}`} ${u.loan.symbol} base units (token ${u.loan.address}, decimals ${u.loan.decimals}). Maturity ${u.market.maturity} Unix seconds; offer expiry ${a.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=[...a.buy?[]:[e.approval(u.loan.address,Y,g.toString(),f)],e.unsignedTx({to:Y,data:L,value:"0",chainId:f,description:v})],H=await r(Z,l,v),F=H.preview.changes.filter(M=>M.token.chainId===f&&R(M.token.address,u.loan.address)).reduce((M,$)=>M+BigInt($.amount),0n);if(a.buy?F<I:F!==-g)throw new i("Midnight preview does not match the exact quoted cash flow.");return H}),s("morpho_midnight_action",{marketId:{type:"string",description:"Midnight market id: 0x + 64 hex digits (bytes32)."},operation:{enum:["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"],description:"Action: add or remove collateral, repay debt, withdraw matured credit, refresh the position, or claim continuous fees (fee claimer only)."},amount:A('Amount in base units of the relevant token: the collateral token for collateral operations, else the loan token (read decimals). Example: "1000000" = 1 USDG.'),collateralIndex:{type:"integer",minimum:0,maximum:127,description:"Zero-based position of the collateral in the market collateral list; required for supplyCollateral and withdrawCollateral only."}},["marketId","operation"],async(n,l)=>{let o=await t(n.marketId,l),a=n.operation;if(!["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"].includes(String(a)))throw new i("Choose a finite Midnight position operation.");let u,c,m=o.loan,d=0n;if(a==="updatePosition"){if(n.amount!==void 0||n.collateralIndex!==void 0)throw new i("Position update takes no amount or collateral index.");u=[o.market,l]}else if(a==="claimContinuousFee"){if(d=O(n.amount),n.collateralIndex!==void 0||K(String(await o.read("feeClaimer")))!==K(l))throw new i("This wallet lacks the Midnight fee claimer role or supplied an unused collateral index.");u=[o.market,d,l]}else{if(d=O(n.amount),d>=1n<<128n)throw new i("Midnight position amount exceeds uint128.");if(a==="supplyCollateral"||a==="withdrawCollateral"){if(!Number.isInteger(n.collateralIndex)||Number(n.collateralIndex)<0||Number(n.collateralIndex)>=o.market.collateralParams.length)throw new i("Choose a current collateral index.");let b=BigInt(String(n.collateralIndex)),w=await o.token(o.market.collateralParams[Number(b)].token);if(m=w,a==="withdrawCollateral"&&d>await o.read("collateral",[o.id,l,b]))throw new i("Insufficient Midnight collateral.");u=a==="supplyCollateral"?[o.market,b,d,l]:[o.market,b,d,l,l],a==="supplyCollateral"&&(c=w)}else{if(n.collateralIndex!==void 0)throw new i("This operation takes no collateral index.");if(a==="repay"&&d>o.position[4]||a==="withdraw"&&(d>o.updated[0]||d>o.state[2]))throw new i("Amount exceeds current debt, credit or available repayment liquidity.");u=a==="repay"?[o.market,d,l,ye,"0x"]:[o.market,d,l,l],a==="repay"&&(c=o.loan)}}let p=`Midnight ${a}: ${d} ${m.symbol} base units (token ${m.address}, decimals ${m.decimals}) on ${o.id}; beneficiary ${l}; maturity ${o.market.maturity} Unix seconds. No callbacks or delegation. Withdrawal can fail if collateral health or lender liquidity changes.`,h=[...c?[e.approval(c.address,Y,d.toString(),f)]:[],e.unsignedTx({to:Y,data:ot({abi:oe,functionName:String(a),args:u}),value:"0",chainId:f,description:p})];return r(h,l,p)}),s("morpho_midnight_manage",{operation:{type:"string",enum:["setConsumed","setIsAuthorized","setConfigurator","setFeeSetter","setFeeClaimer","setTickSpacingSetter","enableLltv","enableLiquidationCursor","setMarketTickSpacing","setMarketSettlementFee","setMarketContinuousFee","setDefaultSettlementFee","setDefaultContinuousFee","claimSettlementFee"],description:"Midnight management function name; role-gated except setConsumed and setIsAuthorized, which act on this wallet."},values:{type:"array",maxItems:3,description:"Ordered arguments for the chosen operation, as in the Midnight ABI: decimal strings for integers (base units), 0x addresses or bytes32, or booleans.",items:{oneOf:[{type:"string"},{type:"boolean"}]}}},["operation","values"],async(n,l)=>{let o={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(o)].includes(n.operation)||!Array.isArray(n.values))throw new i("Choose a finite Midnight management operation and ordered values.");let a=n.operation,u=oe.find(p=>p.name===a);if(n.values.length!==u.inputs.length)throw new i("Provide the exact ordered operation values.");let c=e.clientFor(f);if(await c.getChainId()!==f)throw new i("Midnight requires chain 4663.");let m=u.inputs.map((p,h)=>{let b=n.values[h];if(p.type==="bool"){if(typeof b!="boolean")throw new i("Use boolean management values.");return b}if(p.type==="address")return Oe(b,"Use explicit management addresses.",Ne);if(p.type==="bytes32")return _e(b,32);if(/^uint/.test(p.type)){let w=O(b,!0);if(w>=1n<<BigInt(p.type.slice(4)))throw new i("Management integer exceeds its ABI width.");return w}throw new i("Unsupported management argument type.")});if(a==="setConsumed"||a==="setIsAuthorized"){if(!R(String(m[2]),l))throw new i("Midnight management is bound to this wallet.")}else{let p=await c.readContract({address:Y,abi:oe,functionName:o[a]});if(typeof p!="string"||K(p)!==K(l))throw new i("This wallet lacks the Midnight configuration, fee or tick role.")}let d=`Midnight ${a}, ordered values ${JSON.stringify(n.values)}. ${a==="setIsAuthorized"&&m[1]?"This grants authority over all Midnight positions, cancellations and further delegation, without an amount cap. Revoke with false when done.":""}${a==="setConsumed"?"Consumption only increases; setting uint128 maximum permanently cancels this offer group.":""}`;return r([e.unsignedTx({to:Y,data:ot({abi:oe,functionName:a,args:m}),value:"0",chainId:f,description:d})],l,d)})]}};import{decodeAbiParameters as re,encodeAbiParameters as Ao,encodeFunctionData as G,erc20Abi as it,getAddress as D,isAddress as Fe,keccak256 as xo,parseAbi as Ve,parseAbiParameters as J}from"viem";var De="morpho",Io="https://api.morpho.org/graphql",B=D(z[f].morpho.morpho_blue.address),To=D(z[f].morpho.adaptive_curve_irm.address),Mo=D(z[f].morpho.USDG.address),me=D(z[f].morpho.WETH.address),vo=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],Po={"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."},lt=[{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"}],Co=new Map(lt.map(e=>[e.marketId.toLowerCase(),e]));function j(e){return Co.get(e.toLowerCase())}function ct(e){let t=j(e);return t?{actions:"enabled",label:t.label,source:Po[t.source]}:{actions:"read-only",reason:"Not in Oak's verified Morpho market registry; Oak builds no transactions for it."}}var qt=20,qe=120n,ze=1000000n,We=1n,Se=10n**18n,Lo=10n**36n,jt=(1n<<128n)-1n,Do=(1n<<256n)-1n,X=Ve(["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)"]),Uo=Ve(["function price() view returns (uint256)"]),$o=Ve(["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)"]),Kt=Ve(["function deposit() payable"]);function pe(e){return{loanToken:e.loanToken,collateralToken:e.collateralToken,oracle:e.oracle,irm:e.irm,lltv:e.lltv.toString()}}function Ue(e,t){return e===0n?0n:(e+t-1n)/t}function Bo(e,t,s){return e*(s+ze)/(t+We)}function No(e,t,s){return Ue(e*(s+ze),t+We)}function ut(e,t,s){return e*(t+We)/(s+ze)}function se(e,t,s){return Ue(e*(t+We),s+ze)}function Ae(e,t,s){return e*t/Lo*s/Se}function Oo(e,t,s){return t.startsWith("-")?`-${e.formatAmount(t.slice(1),s)}`:e.formatAmount(t,s)}function xe(e,t){let s=[],r={};for(let n of t.changes){let l=Oo(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 Qt(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 je(e){if(!e||typeof e!="object")throw new i("Morpho marketParams must be an object.");for(let o of[e.loanToken,e.collateralToken,e.oracle,e.irm])if(typeof o!="string"||!Fe(o,{strict:!1}))throw new i("Morpho marketParams contains an invalid address.");let t=D(e.loanToken),s=D(e.collateralToken),r=D(e.oracle),n=D(e.irm),l=typeof e.lltv=="bigint"?e.lltv:Le(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>=Se)throw new i("Morpho marketParams LLTV must be between 0 and 1e18.");return{loanToken:t,collateralToken:s,oracle:r,irm:n,lltv:l}}function ke(e){let t=je(e),s=Ao(J("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return xo(s)}function dt(e){let t=e.toLowerCase();return t===ht.toLowerCase()||t===wt.toLowerCase()||t===te.toLowerCase()}function Ie(e,t){let s=t??e.wallet;if(!s)throw new i("Provide a valid wallet address.");return q(s),D(s)}async function ne(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 Xt(e){return typeof e=="string"&&/^[A-Za-z0-9$._+-]{1,32}$/.test(e)?e:"UNKNOWN"}async function Q(e,t,s=f){if(q(t),dt(t))return{...kt,chainId:s};let r=D(t),n=r.toLowerCase();if(s===f){if(n===Mo.toLowerCase())return yt;if(n===me.toLowerCase())return gt}let[l,o]=await Promise.all([ne(e,r,G({abi:it,functionName:"symbol"})),ne(e,r,G({abi:it,functionName:"decimals"}))]),[a]=re(J("string"),l),[u]=re(J("uint8"),o);return{address:r,symbol:Xt(a),decimals:Number(u),chainId:s}}async function Yt(e,t){let s=await ne(e,B,G({abi:X,functionName:"idToMarketParams",args:[t]})),[r,n,l,o,a]=re(J("address, address, address, address, uint256"),s);return{loanToken:D(r),collateralToken:D(n),oracle:D(l),irm:D(o),lltv:a}}async function Jt(e,t){let s=await ne(e,B,G({abi:X,functionName:"market",args:[t]})),[r,n,l,o,a,u]=re(J("uint128, uint128, uint128, uint128, uint128, uint128"),s);return{totalSupplyAssets:r,totalSupplyShares:n,totalBorrowAssets:l,totalBorrowShares:o,lastUpdate:a,fee:u}}async function Te(e,t,s){let r=await ne(e,B,G({abi:X,functionName:"position",args:[t,D(s)]})),[n,l,o]=re(J("uint256, uint128, uint128"),r);return{supplyShares:n,borrowShares:l,collateral:o}}async function Ke(e,t){let s=await ne(e,D(t),G({abi:Uo,functionName:"price"})),[r]=re(J("uint256"),s);return r}async function Eo(e,t,s){if(t.irm===te)return 0n;let r=await ne(e,D(t.irm),G({abi:$o,functionName:"borrowRateView",args:[t,s]})),[n]=re(J("uint256"),r);return n}function Qe(e,t,s){let r=s>e.lastUpdate?s-e.lastUpdate:0n,n=t*r,l=Ue(n*n,2n*Se),o=Ue(l*n,3n*Se);return e.totalBorrowAssets+Ue(e.totalBorrowAssets*(n+l+o),Se)}async function $e(e,t,s,r=0n){let[n,l]=await Promise.all([e.getBlock({blockTag:"latest"}),Eo(e,t,s)]),o=BigInt(Math.ceil(Date.now()/1e3)),a=(n.timestamp>o?n.timestamp:o)+r;return{totalBorrowAssets:Qe(s,l,a),accruedThrough:a,rate:l}}async function Zt(e,t,s){let r=await ne(e,D(t),G({abi:it,functionName:"balanceOf",args:[D(s)]})),[n]=re(J("uint256"),r);return n}async function fe(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?je(n):void 0,o=l?ke(l):void 0,a=r!==void 0?Qt(r):void 0;if(a&&o&&a!==o.toLowerCase())throw new i(`MarketParams tuple hash (${o}) does not match marketId (${a}).`);let u=(a??o).toLowerCase();if(s&&!j(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[c,m]=await Promise.all([Yt(e,u),Jt(e,u)]);if(c.loanToken===te||c.collateralToken===te||c.lltv===0n||m.lastUpdate===0n)throw new i(`Morpho market ${u} is not initialized on chain ${f}.`);let d=ke(c);if(d.toLowerCase()!==u.toLowerCase())throw new i(`On-chain idToMarketParams tuple hash (${d}) does not match marketId (${u}).`);if(l&&!(l.loanToken.toLowerCase()===c.loanToken.toLowerCase()&&l.collateralToken.toLowerCase()===c.collateralToken.toLowerCase()&&l.oracle.toLowerCase()===c.oracle.toLowerCase()&&l.irm.toLowerCase()===c.irm.toLowerCase()&&l.lltv===c.lltv))throw new i(`Provided marketParams tuple does not match on-chain idToMarketParams for ${u}.`);return{marketId:u,marketParams:c,marketState:m}}function Me(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=Le(t);if(s<=0n||s>jt)throw new i("Asset amount must be greater than zero and fit in uint128.");return s}function ve(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 Go(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=e.clientFor(f),{marketId:o,marketParams:a}=await fe(l,t,!0),u=await Q(l,a.collateralToken,f),c=a.collateralToken.toLowerCase()===me.toLowerCase(),m=typeof t.collateralToken=="string"?(q(t.collateralToken),D(t.collateralToken)):void 0,d=W("wrapNative",t.wrapNative)===!0||m!==void 0&&dt(m);if(m&&!dt(m)&&m.toLowerCase()!==a.collateralToken.toLowerCase())throw new i(`Collateral token ${m} does not match market collateral ${a.collateralToken}.`);if(d&&!c)throw new i("Native ETH wrapping is only supported when market collateralToken is WETH.");let p=Me(t),h=p.toString(),b=e.formatAmount(h,u.decimals),w=[];d&&w.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:h,description:`Wrap ${b} ETH into WETH at ${me}.`})),w.push(e.approval(a.collateralToken,B,h,f)),w.push(e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"supplyCollateral",args:[a,p,n,"0x"]}),value:"0",description:`Supply ${b} ${u.symbol} (${h} base units) collateral to Morpho market ${o}.`}));let k=await e.preview(w,r),{formattedChanges:y,formattedNetOutflows:g}=xe(e,k);return{action:"morpho_supply_collateral",chainId:f,marketId:o,marketParams:pe(a),collateralToken:u,assets:h,formattedAssets:b,onBehalf:n,txs:w,summary:`${d?`Send ${b} ETH to wrap into WETH. `:""}Supply ${b} ${u.symbol} collateral to Morpho Blue market ${o}.`,preview:k,formattedChanges:y,formattedNetOutflows:g}}async function Ro(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,o=e.clientFor(f),{marketId:a,marketParams:u,marketState:c}=await fe(o,t,!0),[m,d,p,h]=await Promise.all([Q(o,u.loanToken,f),Te(o,a,n),Ke(o,u.oracle),$e(o,u,c,qe)]),b=Me(t),w=b.toString(),k=e.formatAmount(w,m.decimals),y=c.totalSupplyAssets>c.totalBorrowAssets?c.totalSupplyAssets-c.totalBorrowAssets:0n;if(b>y)throw new i(`Insufficient market liquidity: requested ${w} base units, available ${y.toString()} base units.`);let g=Ae(d.collateral,p,u.lltv),I=se(d.borrowShares,h.totalBorrowAssets,c.totalBorrowShares);if(d.collateral===0n||I+b>g)throw new i(`Insufficient collateral or unhealthy borrow: total debt ${(I+b).toString()} exceeds max borrow ${g.toString()} base units.`);let x=No(b,h.totalBorrowAssets,c.totalBorrowShares),P=[e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"borrow",args:[u,b,0n,n,l]}),value:"0",description:`Borrow ${k} ${m.symbol} (${w} base units) from Morpho market ${a}.`})],C=await e.preview(P,r),{formattedChanges:L,formattedNetOutflows:v}=xe(e,C);return{action:"morpho_borrow",chainId:f,marketId:a,marketParams:pe(u),loanToken:m,assets:w,formattedAssets:k,borrowShares:x.toString(),onBehalf:n,receiver:l,txs:P,summary:`Borrow ${k} ${m.symbol} from Morpho Blue market ${a}.`,preview:C,formattedChanges:L,formattedNetOutflows:v}}async function eo(e,t,s,r=qe){let n=Ie(t,s);ve(t,n);let l=n,o=e.clientFor(f);if(t.shares!==void 0){let v=Le(t.shares);if(v<=0n||v===Do||v>jt)throw new i("Morpho Blue core does not accept maxUint256 or out-of-range share sentinels; pass exact position.borrowShares.")}if(W("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:u,marketState:c}=await fe(o,t,!0),[m,d,p]=await Promise.all([Q(o,u.loanToken,f),Te(o,a,l),Zt(o,u.loanToken,n)]);if(d.borrowShares===0n)throw new i(`Position has no active borrow debt on Morpho market ${a}.`);let h=0n,b=0n;if(W("repayAll",t.repayAll)===!0)b=d.borrowShares;else if(t.shares!==void 0){let v=Le(t.shares);if(v>d.borrowShares)throw new i(`Repay shares (${v.toString()}) exceed current position borrowShares (${d.borrowShares.toString()}).`);b=v}else h=Me(t);let w=b>0n?await $e(o,u,c,r):void 0,k=b>0n?se(b,w.totalBorrowAssets,c.totalBorrowShares):h;if(p<k)throw new i(`Insufficient loan token balance for repayment: wallet holds ${p.toString()} base units, but ${k.toString()} base units are required (including accrued interest).`);let y=k.toString(),g=e.formatAmount(y,m.decimals),I=e.approval(u.loanToken,B,y,f),x=e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"repay",args:[u,h,b,l,"0x"]}),value:"0",description:b>0n?`Repay ${b.toString()} borrow shares (${g} ${m.symbol}) on Morpho market ${a}.`:`Repay ${g} ${m.symbol} (${h.toString()} base units) on Morpho market ${a}.`}),T=[I,x],P=await e.preview(T,n),{formattedChanges:C,formattedNetOutflows:L}=xe(e,P);return{action:"morpho_repay",chainId:f,marketId:a,marketParams:pe(u),loanToken:m,repayAssets:h.toString(),repayShares:b.toString(),requiredAssets:y,...w?{accruedThrough:w.accruedThrough.toString(),borrowRatePerSecond:w.rate.toString(),inclusionSeconds:r.toString()}:{},formattedRequiredAssets:g,onBehalf:l,txs:T,summary:b>0n?`Repay ${b.toString()} borrow shares (approval up to ${g} ${m.symbol}) on Morpho Blue market ${a}. Refresh if signing/inclusion takes more than ${qe} seconds.`:`Repay ${g} ${m.symbol} on Morpho Blue market ${a}.`,preview:P,formattedChanges:C,formattedNetOutflows:L}}function Ka(e,t,s){if(t.repayAll!==!0)throw new i("Reviewed debt reconstruction requires repayAll.");return eo(e,t,s,0n)}async function _o(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,o=e.clientFor(f),{marketId:a,marketParams:u,marketState:c}=await fe(o,t,!0),[m,d,p,h]=await Promise.all([Q(o,u.collateralToken,f),Te(o,a,n),Ke(o,u.oracle),$e(o,u,c,qe)]),b=W("withdrawAll",t.withdrawAll)===!0?d.collateral:Me(t);if(b<=0n||b>d.collateral)throw new i(`Insufficient collateral to withdraw: requested ${b.toString()} base units, position holds ${d.collateral.toString()} base units.`);if(d.borrowShares>0n){let P=d.collateral-b,C=Ae(P,p,u.lltv),L=se(d.borrowShares,h.totalBorrowAssets,c.totalBorrowShares);if(L>C)throw new i(`Unhealthy collateral withdrawal: remaining max borrow ${C.toString()} would fall below current debt ${L.toString()} base units.`)}let w=b.toString(),k=e.formatAmount(w,m.decimals),g=[e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"withdrawCollateral",args:[u,b,n,l]}),value:"0",description:`Withdraw ${k} ${m.symbol} (${w} base units) collateral from Morpho market ${a}.`})],I=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:T}=xe(e,I);return{action:"morpho_withdraw_collateral",chainId:f,marketId:a,marketParams:pe(u),collateralToken:m,assets:w,formattedAssets:k,onBehalf:n,receiver:l,txs:g,summary:`Withdraw ${k} ${m.symbol} collateral from Morpho Blue market ${a}.`,preview:I,formattedChanges:x,formattedNetOutflows:T}}async function Ho(e,t,s){let r=Ie(t,s);ve(t,r);let n=e.clientFor(f),{marketId:l,marketParams:o,marketState:a}=await fe(n,t,!0),u=W("wrapNative",t.wrapNative)===!0;if(u&&o.loanToken.toLowerCase()!==me.toLowerCase())throw new i("Native ETH wrapping is only supported when the market loanToken is WETH.");let c=Me(t),m=c.toString(),[d,p]=await Promise.all([Q(n,o.loanToken,f),u?Promise.resolve(c):Zt(n,o.loanToken,r)]);if(p<c)throw new i(`Insufficient ${d.symbol} balance to lend: wallet holds ${p.toString()} base units, requested ${m}.`);let h=e.formatAmount(m,d.decimals),b=[];u&&b.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:m,description:`Wrap ${h} ETH into WETH at ${me}.`})),b.push(e.approval(o.loanToken,B,m,f)),b.push(e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"supply",args:[o,c,0n,r,"0x"]}),value:"0",description:`Lend ${h} ${d.symbol} (${m} base units) to Morpho market ${l}.`}));let w=Bo(c,a.totalSupplyAssets,a.totalSupplyShares),k=await e.preview(b,r),{formattedChanges:y,formattedNetOutflows:g}=xe(e,k);return{action:"morpho_supply",chainId:f,marketId:l,marketParams:pe(o),loanToken:d,assets:m,formattedAssets:h,supplySharesEstimated:w.toString(),onBehalf:r,oak:ct(l),txs:b,summary:`${u?`Send ${h} ETH to wrap into WETH. `:""}Lend ${h} ${d.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:k,formattedChanges:y,formattedNetOutflows:g}}async function qo(e,t,s){let r=Ie(t,s);ve(t,r);let n=e.clientFor(f),l=W("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:o,marketParams:a,marketState:u}=await fe(n,t,!0),[c,m]=await Promise.all([Q(n,a.loanToken,f),Te(n,o,r)]);if(m.supplyShares===0n)throw new i(`This wallet has no lent ${c.symbol} on Morpho market ${o}.`);let d=ut(m.supplyShares,u.totalSupplyAssets,u.totalSupplyShares),p=l?0n:Me(t),h=l?m.supplyShares:0n;if(!l&&p>d)throw new i(`Withdrawal exceeds the lent balance: requested ${p.toString()} base units, position holds about ${d.toString()}. Use withdrawAll for a full exit.`);let b=u.totalSupplyAssets>u.totalBorrowAssets?u.totalSupplyAssets-u.totalBorrowAssets:0n,w=l?d:p;if(w>b)throw new i(`Insufficient market liquidity: withdrawing ${w.toString()} base units needs idle assets, but only ${b.toString()} are available until borrowers repay. Withdraw at most that amount, or retry later.`);let k=e.formatAmount(w.toString(),c.decimals),g=[e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"withdraw",args:[a,p,h,r,r]}),value:"0",description:l?`Withdraw all ${m.supplyShares.toString()} supply shares (about ${k} ${c.symbol}) from Morpho market ${o}.`:`Withdraw ${k} ${c.symbol} (${p.toString()} base units) of lent assets from Morpho market ${o}.`})],I=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:T}=xe(e,I);return{action:"morpho_withdraw",chainId:f,marketId:o,marketParams:pe(a),loanToken:c,withdrawAssets:p.toString(),withdrawShares:h.toString(),estimatedAssets:w.toString(),formattedAssets:k,receiver:r,txs:g,summary:l?`Withdraw all lent ${c.symbol} (about ${k}, including interest) from Morpho Blue market ${o}.`:`Withdraw ${k} lent ${c.symbol} from Morpho Blue market ${o}.`,preview:I,formattedChanges:x,formattedNetOutflows:T}}async function to(e,t,s){let r=await e.http(Io,{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 oo(e){let t=`query Markets($chainId: Int!) {
|
|
1
|
+
import{a as Ge}from"./7MR37STI.js";import{a as oe}from"./3CCBUYUM.js";import{a as xt,d as It,e as Tt}from"./53VBLEYS.js";import{a as Ze,b as Ee,d as At}from"./IY7FWTAL.js";import{h as Je,i as St}from"./2GXHYI23.js";import{b as kt,c as yt,d as gt}from"./5PNFV7HH.js";import{d as wt,e as te}from"./TTBB6EFN.js";import{a as ht}from"./7WXAS54T.js";import{b as bt}from"./SPJCSEKP.js";import{a as q}from"./43LI5NKJ.js";import{a as A,d as W}from"./66F5ZH34.js";import{d as Ne,g as R,i as Oe}from"./NWNYJ26T.js";import{b as Le}from"./IX3GZMTM.js";import{o as ft}from"./EZUQMTLE.js";import{b as f,j as z}from"./EWZFZUVF.js";import{a as i,e as ie}from"./XSD5NL7J.js";import{a as Ye}from"./JXOEJPJ4.js";import{encodeFunctionData as be,erc20Abi as Xo,getAddress as ao,parseAbi as pt,zeroAddress as Yo}from"viem";import{decodeAbiParameters as mo,encodeFunctionData as po,getAddress as le,parseAbiParameters as fo,zeroAddress as he,zeroHash as Dt}from"viem";import{decodeAbiParameters as no,encodeFunctionData as so,erc20Abi as io,getAddress as Ct,parseAbi as lo,parseAbiParameters as co,zeroHash as Mt}from"viem";var et=Ct("0xCE29862924756584BBD0D75CA1249d22007E2813"),Lt="(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)",uo="(uint256 value,uint256 nonce,uint256 deadline,uint8 v,bytes32 r,bytes32 s)",vt=lo(["function BLUE() view returns (address)",`function vaultExitBundlesV1InKindRedemptionVaultV2(address vault,address adapter,${Lt}[] marketParamsList,uint256 exitAssets,${uo} sharesPermit,uint256 deadline)`]);function O(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 Pt=(e,t)=>e<t?e:t;async function la(e,t,s,r,n){q(n);let l=O(r.amount),o=O(r.maxShares),a=O(r.maxPenaltyAssets,!0),u=O(r.deadline),c=e.clientFor(f),m=await At(c,t,s),d=(S,N,Ce,ee=[])=>c.readContract({address:S,abi:N,functionName:Ce,args:ee,blockNumber:m.blockNumber}),[p,h,b,w]=await Promise.all([c.getBlock({blockNumber:m.blockNumber}),d(et,vt,"BLUE"),d(t,io,"balanceOf",[n]),d(t,Ze,"previewRedeem",[o])]);if(typeof h!="string"||Ct(h)!==B)throw new i("VaultExitBundlesV1 does not report the pinned Morpho Blue.");if(u<p.timestamp||u>p.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");if(o>Ee(b))throw new i("maxShares exceeds the wallet share balance.");let k=Pt(m.idle,l),y=m.markets.filter(S=>S.supplied>0n&&j(S.id)),g=l-k,I=y[0]?.penalty??0n,x=g*10n**18n/(10n**18n+I);if(g>0n&&x===0n)throw new i("The penalty-adjusted in-kind amount rounds to zero.");let T=[];for(let S of y){if(x===0n)break;let N=Pt(S.supplied,x);T.push({marketId:S.id,assets:N,penalty:(N*S.penalty+10n**18n-1n)/10n**18n}),x-=N}if(x>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(T.length)>Ee(w))throw new i("maxShares cannot cover the exit and per-market rounding buffer.");if(T.some(S=>S.assets>m.blueCash))throw new i("Morpho Blue cannot fund the largest in-kind callback. Reduce the amount.");let P=T.reduce((S,N)=>S+N.penalty,0n);if(P>a)throw new i("In-kind penalty exceeds maxPenaltyAssets.");let C=[...k?[k]:[],...T.flatMap(S=>[S.assets,S.penalty].filter(N=>N>0n))],v=(await Promise.all(C.map(S=>d(t,Ze,"previewWithdraw",[S])))).reduce((S,N)=>S+Ee(N),0n);if(v===0n||v>o)throw new i("Separately rounded burns exceed maxShares.");let Z=T.map(S=>no(co(Lt),m.markets.find(N=>N.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 ${v} share base units; receive ${k} ${s.symbol} base units and Morpho Blue supply positions ${T.map(S=>`${S.marketId}: ${S.assets} ${s.symbol} base units`).join(", ")||"none"}. Penalty ${P} ${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.`,M=so({abi:vt,functionName:"vaultExitBundlesV1InKindRedemptionVaultV2",args:[t,H,Z,l,{value:0n,nonce:0n,deadline:0n,v:0,r:Mt,s:Mt},u]}),$=[e.approval(t,et,v.toString(),f),e.unsignedTx({to:et,data:M,value:"0",chainId:f,description:F})],U=await e.preview($,n),V=-U.changes.filter(S=>S.token.chainId===f&&R(S.token.address,t)).reduce((S,N)=>{if(N.token.decimals!==18||!/^-?\d+$/.test(N.amount))throw new i("Invalid in-kind share preview.");return S+BigInt(N.amount)},0n);if(V<=0n||V>v)throw new i("In-kind preview exceeds the exact share authorization or burns no shares.");return{txs:$,preview:U,summary:F,receipt:{idleAssets:k.toString(),positions:T.map(S=>({marketId:S.marketId,asset:s,assets:S.assets.toString()})),penaltyAssets:P.toString()}}}var we=le("0x53A1eB6589861F686af7c531211E35Aefe30210f"),Ut=["supply","withdraw","supplyCollateralAndBorrow","repayAndWithdrawCollateral","migrateBorrowPosition"],tt={kind:0,data:"0x"},Re={nonce:0n,deadline:0n,signature:{v:0,r:Dt,s:Dt}},bo=fo("(address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)"),$t=e=>({tools:[{name:"morpho_bundle",inputSchema:{type:"object",additionalProperties:!1,required:["operation","marketId","deadline"],properties:{operation:{type:"string",enum:Ut,description:"Bundle: supply, withdraw, supplyCollateralAndBorrow, repayAndWithdrawCollateral, or migrateBorrowPosition (move debt to destinationMarketId)."},marketId:{type:"string",description:"Verified Morpho Blue market id (0x + 64 hex digits); the source market for migrateBorrowPosition."},destinationMarketId:{type:"string",description:"Only for migrateBorrowPosition: verified market id (0x + 64 hex) to move the borrow into; must share the same tokens."},assets:A(`Amount of the market's loan token in base units (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`),collateralAssets:A(`Collateral amount in base units of the market's collateral token (read its decimals). Example: "1000000" = 1 USDG for a 6-decimal token.`),shares:A("Market share amount in base units (supply or borrow shares, read the position), instead of assets. Give assets or shares, not both."),maxRepayAssets:A('Most loan token you accept paying to repay, in base units of the loan token (read its decimals). Example: "1000000" = 1 USDG.'),maxLtv:A("Highest loan-to-value allowed after the bundle, as an 18-decimal wad in base units (0.8e18 = 80 percent); cannot exceed the market LLTV."),deadline:A("Absolute Unix seconds deadline, no more than five minutes ahead. Example: 1800000000."),allocations:{type:"array",maxItems:4,description:"Up to four Public Allocator moves that add liquidity to the market before borrowing or withdrawing; one per vault.",items:{type:"object",additionalProperties:!1,required:["vault","assets","maxPenaltyAssets"],properties:{vault:{type:"string",description:"Pinned NetNet or Longbow V2 vault address (0x + 40 hex) to pull liquidity from; one entry per vault."},sourceMarketId:{type:"string",description:"Source market id (0x + 64 hex) to pull from; omit to allocate idle vault assets."},assets:A(`Amount to reallocate, in base units of the vault's asset (USDG 6 decimals, WETH 18). Example: "1000000" = 1 USDG.`),maxPenaltyAssets:A(`Highest allocator penalty you accept, in base units of the vault's asset. Example: "10000" = 0.01 USDG for a 6-decimal asset.`)}}}}},execute:async(t,s)=>{try{q(s);let r=t.operation,n=e.clientFor(f);if(await n.getChainId()!==f||typeof r!="string"||!Ut.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(M=>!l.includes(M)))throw new i("Unexpected argument for this Blue bundle.");let o=await n.getBlock(),a=O(t.deadline);if(a<o.timestamp||a>o.timestamp+300n)throw new i("Use an absolute Unix deadline within the next five minutes.");let[u,c]=await Promise.all([n.readContract({address:we,abi:Ge,functionName:"BLUE",blockNumber:o.number}),n.readContract({address:we,abi:Ge,functionName:"PUBLIC_ALLOCATOR",blockNumber:o.number})]);if(le(u)!==B||le(c)!==xt)throw new i("BlueBundlesV1 deployment does not match Oak\u2019s pinned Blue and Public Allocator.");let m=async M=>{if(typeof M!="string"||!j(M))throw new i("Choose a verified Morpho market with a supported exit.");let $=await n.readContract({address:B,abi:E,functionName:"idToMarketParams",args:[M],blockNumber:o.number}),U={loanToken:le($[0]),collateralToken:le($[1]),oracle:le($[2]),irm:le($[3]),lltv:$[4]};if(!R(ke({...U,lltv:String(U.lltv)}),M))throw new i("Blue bundle market identity mismatch.");return U},d=await m(t.marketId),p=r==="migrateBorrowPosition"?await m(t.destinationMarketId):d;if(d.loanToken!==p.loanToken||d.collateralToken!==p.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:B,abi:E,functionName:"isAuthorized",args:[s,we],blockNumber:o.number}))throw new i(`Authorize the pinned Blue bundle explicitly with morpho_manage setAuthorization account ${we}, enabled true, then retry. That authority covers all Blue positions. Revoke it with enabled false after the bundle.`);let h=t.assets===void 0?0n:O(t.assets,!0),b=t.shares===void 0?0n:O(t.shares,!0),w=t.collateralAssets===void 0?0n:O(t.collateralAssets,!0),k=r==="supply"||r==="withdraw"?0n:O(t.maxLtv,!0);if(k>p.lltv)throw new i("maxLtv cannot exceed the verified destination market LLTV.");if(r==="supply"&&h===0n||r==="withdraw"&&h===0n==(b===0n)||r==="supplyCollateralAndBorrow"&&w===0n&&h===0n||r==="repayAndWithdrawCollateral"&&(h>0n&&b>0n||h===0n&&b===0n&&w===0n))throw new i("Choose a nonzero amount; assets and shares are mutually exclusive for repayment/withdrawal.");let y=t.allocations??[];if(!Array.isArray(y)||y.length>4||y.length&&r==="supplyCollateralAndBorrow"&&h===0n)throw new i("Provide at most four explicit allocations, only with a borrow or withdrawal.");let g=new Set,I=[],x=0n;for(let M of y){if(!M||typeof M!="object"||Array.isArray(M)||Object.keys(M).some(Xe=>!["vault","sourceMarketId","assets","maxPenaltyAssets"].includes(Xe)))throw new i("Unsupported bundled allocation input.");let $=M,U=await It(e,{vault:$.vault,marketId:r==="migrateBorrowPosition"?t.destinationMarketId:t.marketId});if(g.has(U.definition.vault.toLowerCase()))throw new i("Use each source vault at most once per bundle.");g.add(U.definition.vault.toLowerCase());let V=O($.assets),S=O($.maxPenaltyAssets,!0);if(!U.permission||V>=1n<<128n||V>U.headroom||U.penalty>10n**18n||U.asset.address!==p.loanToken)throw new i("Bundled allocation is disabled, unqualified or exceeds target capacity.");let N=(V*U.penalty+10n**18n-1n)/10n**18n;if(N>S)throw new i("Bundled allocation exceeds maxPenaltyAssets.");x+=N;let Ce=$.sourceMarketId===void 0,ee=Ce?void 0:U.sources.find(Xe=>R(Xe.id,String($.sourceMarketId)));if(Ce?!U.canIdle||V>U.data.idle:!ee||!ee.canPull||V>ee.capacity||V>U.data.blueCash)throw new i("Bundled allocation source cannot cover the requested amount.");I.push({vault:U.definition.vault,adapter:U.target.adapter,marketParams:U.params,sourceAdapter:ee?.adapter??he,sourceMarketParams:ee?mo(bo,ee.data)[0]:U.params,assets:V,penalty:U.penalty,fromIdle:Ce})}let T,P,C,L=0n;if(r==="supply")T="blueBundlesV1Supply",C=d.loanToken,L=h,P=[d,h,tt,0n,he,a];else if(r==="withdraw")T="blueBundlesV1Withdraw",P=[d,h,b,Re,I,0n,he,a];else if(r==="supplyCollateralAndBorrow"){if(T="blueBundlesV1SupplyCollateralAndBorrow",C=d.collateralToken,L=w,x>=h&&x>0n)throw new i("Allocation penalties would consume the borrow proceeds.");P=[d,w,h,k,tt,Re,I,0n,he,a]}else if(r==="repayAndWithdrawCollateral"){if(T="blueBundlesV1RepayAndWithdrawCollateral",C=d.loanToken,L=O(t.maxRepayAssets,!0),h>L||b>0n&&L===0n)throw new i("Repayment requires a sufficient maxRepayAssets budget.");P=[d,h,b,L,w,k,tt,Re,0n,he,a]}else T="blueBundlesV1MigrateBorrowPosition",P=[d,p,k,Re,I,0n,he,a];let v=`Morpho Blue atomic ${r}: ${JSON.stringify(t)}. Allocation penalties ${x} loan-token base units; zero referral fee. Max LTV ${k}; absolute deadline ${a}. Migration adds allocation penalties to destination debt; borrowing deducts them from proceeds. Exact input approval ${L}. Existing Blue bundle authorization remains until explicitly revoked with morpho_manage. No opaque callback, permit or signature is accepted.`,Z=[...C&&L?[e.approval(C,we,L.toString(),f)]:[],e.unsignedTx({to:we,data:po({abi:Ge,functionName:T,args:P}),value:"0",chainId:f,description:v})],H=await e.preview(Z,s),F=new Map;for(let M of H.changes)if(BigInt(M.amount)<0n){let $=M.token.address.toLowerCase();F.set($,(F.get($)??0n)-BigInt(M.amount))}if([...F].some(([M,$])=>!C||M!==C.toLowerCase()||$>L))throw new i("Bundle preview spends outside the exact input budget.");return{txs:Z,preview:H,summary:v}}catch(r){throw new i(e.plainError(r))}}}]});import{concatHex as Bt,decodeAbiParameters as ho,encodeAbiParameters as Rt,encodeFunctionData as ot,erc20Abi as Nt,getAddress as K,keccak256 as rt,zeroAddress as ye,zeroHash as wo}from"viem";var Y=K("0x6120765Ba5336150BbdDdD0Cd9108B5bFD369632"),ko=["0x90B800999e4ACd1bD20283BD450bBd2e06D91F7C","0x708d6Bf6F847202a0755bb5636bE663B174242ea"].map(e=>K(e)),nt=oe.find(e=>e.name==="take"),Ot=[nt.inputs[0]],yo=[nt.inputs[0].components[0]];function Et(e){let t=rt(Bt(["0x600b380380600b5f395ff3",Rt(yo,[e])]));return rt(Bt(["0xff",e.midnight,wo,t]))}var de=10n**18n,Gt=(e,t)=>(e+(t-1n)/2n)/t;function _t(e){if(e<0n)return 10n**36n/_t(-e);let t=693147180559945309n,s=(e+322611214989459870n)/t,r=e-s*t,n=r*r/(2n*de),l=n*r/(3n*de);return de+r+n+l<<s}function go(e){if(e<0n||e>6744n)throw new i("Midnight tick is outside 0..6744.");return Gt(Gt(10n**36n,de+_t(4987541511039073n*(3372n-e))),10n**11n)*10n**11n}function _e(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 at(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 So=e=>JSON.parse(JSON.stringify(e,(t,s)=>typeof s=="bigint"?s.toString():s)),Ht=e=>{async function t(n,l){let o=_e(n,32),a=e.clientFor(f);if(await a.getChainId()!==f)throw new i("Midnight requires chain 4663.");let u=await a.getBlock(),c=(y,g=[])=>a.readContract({address:Y,abi:oe,functionName:y,args:g,blockNumber:u.number}),m=await c("toMarket",[o]);if(m.chainId!==BigInt(f)||K(m.midnight)!==Y||!R(Et(m),o))throw new i("Midnight market identity does not match the pinned chain and contract.");if(![z[f].tokens.USDG.address,z[f].tokens.WETH.address].some(y=>R(y,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[p,h,b,w]=await Promise.all([c("position",[o,l]),c("updatePositionView",[m,o,l]),c("marketState",[o]),c("isHealthy",[m,o,l])]),k=async y=>{let[g,I]=await Promise.all([a.readContract({address:y,abi:Nt,functionName:"decimals",blockNumber:u.number}),a.readContract({address:y,abi:Nt,functionName:"symbol",blockNumber:u.number})]);if(!Number.isInteger(g)||g>36||typeof I!="string")throw new i("Invalid Midnight token metadata.");return{address:K(y),decimals:g,symbol:I.replace(/[^a-zA-Z0-9.$_-]/g,"").slice(0,32),chainId:f}};return{id:o,rpc:a,block:u,market:m,read:c,token:k,loan:await k(m.loanToken),position:at(p,6),updated:at(h,3),state:at(b,13),healthy:w}}let s=(n,l,o,a)=>({name:n,inputSchema:{type:"object",properties:l,required:o,additionalProperties:!1},execute:async(u,c)=>{try{if(q(c),Object.keys(u).some(m=>!Object.hasOwn(l,m)))throw new i("Unsupported Midnight argument.");return await a(u,c)}catch(m){throw new i(e.plainError(m))}}});async function r(n,l,o){return{txs:n,preview:await e.preview(n,l),summary:o}}return{tools:[s("morpho_midnight_status",{marketId:{type:"string",description:"Midnight market id: 0x + 64 hex digits (bytes32)."}},["marketId"],async(n,l)=>{let o=await t(n.marketId,l),a=await Promise.all(o.market.collateralParams.map(async(m,d)=>({token:await o.token(m.token),lltvWad:m.lltv.toString(),oracle:m.oracle,assets:String(await o.read("collateral",[o.id,l,BigInt(d)]))}))),u=["configurator","feeSetter","feeClaimer","tickSpacingSetter"],c=await Promise.all(u.map(m=>o.read(m)));return{protocol:Object.fromEntries(u.map((m,d)=>[m,K(String(c[d]))])),continuousFeePerSecondWad:String(o.state[11]),tickSpacing:String(o.state[12]),settlementFeeCbps:o.state.slice(4,11).map(String),settlementFeeCbpWadScale:"1000000000000",chainId:f,midnight:Y,marketId:o.id,blockNumber:String(o.block.number),market:So(o.market),loanToken:o.loan,collaterals:a,debtUnits:String(o.position[4]),creditUnits:String(o.updated[0]),pendingFeeUnits:String(o.updated[1]),withdrawableUnits:String(o.state[2]),healthy:o.healthy,maturity:String(o.market.maturity),matured:o.block.timestamp>o.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",description:"Hex proof data (0x...) that the offer's pinned ratifier uses to confirm the maker approved this offer."},units:A("Fixed debt units to trade, as a decimal string below 2^128. The asset cost or proceeds follow from the offer price; maxAssets and minAssets bound them."),maxAssets:A('Most loan token you will spend when buying credit, in base units of the market loan token (read its decimals). Example: "1000000" = 1 USDG.'),minAssets:A('Least loan token you must receive when selling credit or borrowing, in base units of the market loan token. Example: "1000000" = 1 USDG.')},["offer","ratifierData","units","maxAssets","minAssets"],async(n,l)=>{let o=_e(n.offer),[a]=ho(Ot,o);if(!R(Rt(Ot,[a]),o))throw new i("Offer encoding is not canonical.");let u=await t(Et(a.market),l),c=O(n.units),m=O(n.maxAssets,!0),d=O(n.minAssets,!0),p=_e(n.ratifierData);if(c>=1n<<128n||R(a.maker,l)||a.callback!==ye||a.callbackData!=="0x"||!ko.includes(K(a.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<a.start||u.block.timestamp>a.expiry||a.expiry<a.start)throw new i("The Midnight offer is not currently live.");if(a.buy&&a.receiverIfMakerIsSeller!==ye||!a.buy&&a.receiverIfMakerIsSeller===ye)throw new i("Invalid offer seller receiver.");if(a.buy&&u.block.timestamp>u.market.maturity&&c>u.updated[0])throw new i("Post-maturity sales cannot increase this wallet\u2019s debt.");let h=await u.read("settlementFee",[u.id,u.market.maturity>u.block.timestamp?u.market.maturity-u.block.timestamp:0n]),b=go(a.tick);if(h>b&&a.buy)throw new i("Settlement fee exceeds the offer price.");let w=a.buy?b-h:b,k=w+h,y=M=>a.buy?M/de:(M+de-1n)/de,g=y(c*k),I=y(c*w);if(a.buy?I<d||I===0n:g>m||g===0n)throw new i("Midnight proceeds/spend do not fit the requested bounds.");let x=await u.read("consumed",[a.maker,a.group]);if(a.maxAssets===0n==(a.maxUnits===0n)||x+(a.maxAssets?a.buy?g:I:c)>(a.maxAssets||a.maxUnits))throw new i("Midnight offer capacity is exhausted or invalid.");if(u.state[11]>a.continuousFeeCap||a.tick%u.state[12]!==0n)throw new i("Offer fee cap or market tick spacing no longer permits execution.");let T=await u.read("isAuthorized",[a.maker,a.ratifier]),P=[{type:"function",name:"isRatified",stateMutability:"view",inputs:[nt.inputs[0],{type:"bytes"},{type:"address"}],outputs:[{type:"bytes32"}]}],C=await u.rpc.readContract({address:a.ratifier,abi:P,functionName:"isRatified",args:[a,p,l],blockNumber:u.block.number});if(T!==!0||C!==rt(new TextEncoder().encode("morpho.midnight.callbackSuccess")))throw new i("The maker has not authorized and ratified this exact offer.");let L=ot({abi:oe,functionName:"take",args:[a,p,c,l,a.buy?l:ye,ye,"0x"]}),v=`Midnight ${a.buy?"sell credit or borrow":"buy credit or reduce debt"}: ${c} fixed debt units; ${a.buy?`receive ${I}`:`spend ${g}`} ${u.loan.symbol} base units (token ${u.loan.address}, decimals ${u.loan.decimals}). Maturity ${u.market.maturity} Unix seconds; offer expiry ${a.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=[...a.buy?[]:[e.approval(u.loan.address,Y,g.toString(),f)],e.unsignedTx({to:Y,data:L,value:"0",chainId:f,description:v})],H=await r(Z,l,v),F=H.preview.changes.filter(M=>M.token.chainId===f&&R(M.token.address,u.loan.address)).reduce((M,$)=>M+BigInt($.amount),0n);if(a.buy?F<I:F!==-g)throw new i("Midnight preview does not match the exact quoted cash flow.");return H}),s("morpho_midnight_action",{marketId:{type:"string",description:"Midnight market id: 0x + 64 hex digits (bytes32)."},operation:{enum:["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"],description:"Action: add or remove collateral, repay debt, withdraw matured credit, refresh the position, or claim continuous fees (fee claimer only)."},amount:A('Amount in base units of the relevant token: the collateral token for collateral operations, else the loan token (read decimals). Example: "1000000" = 1 USDG.'),collateralIndex:{type:"integer",minimum:0,maximum:127,description:"Zero-based position of the collateral in the market collateral list; required for supplyCollateral and withdrawCollateral only."}},["marketId","operation"],async(n,l)=>{let o=await t(n.marketId,l),a=n.operation;if(!["supplyCollateral","withdrawCollateral","repay","withdraw","updatePosition","claimContinuousFee"].includes(String(a)))throw new i("Choose a finite Midnight position operation.");let u,c,m=o.loan,d=0n;if(a==="updatePosition"){if(n.amount!==void 0||n.collateralIndex!==void 0)throw new i("Position update takes no amount or collateral index.");u=[o.market,l]}else if(a==="claimContinuousFee"){if(d=O(n.amount),n.collateralIndex!==void 0||K(String(await o.read("feeClaimer")))!==K(l))throw new i("This wallet lacks the Midnight fee claimer role or supplied an unused collateral index.");u=[o.market,d,l]}else{if(d=O(n.amount),d>=1n<<128n)throw new i("Midnight position amount exceeds uint128.");if(a==="supplyCollateral"||a==="withdrawCollateral"){if(!Number.isInteger(n.collateralIndex)||Number(n.collateralIndex)<0||Number(n.collateralIndex)>=o.market.collateralParams.length)throw new i("Choose a current collateral index.");let b=BigInt(String(n.collateralIndex)),w=await o.token(o.market.collateralParams[Number(b)].token);if(m=w,a==="withdrawCollateral"&&d>await o.read("collateral",[o.id,l,b]))throw new i("Insufficient Midnight collateral.");u=a==="supplyCollateral"?[o.market,b,d,l]:[o.market,b,d,l,l],a==="supplyCollateral"&&(c=w)}else{if(n.collateralIndex!==void 0)throw new i("This operation takes no collateral index.");if(a==="repay"&&d>o.position[4]||a==="withdraw"&&(d>o.updated[0]||d>o.state[2]))throw new i("Amount exceeds current debt, credit or available repayment liquidity.");u=a==="repay"?[o.market,d,l,ye,"0x"]:[o.market,d,l,l],a==="repay"&&(c=o.loan)}}let p=`Midnight ${a}: ${d} ${m.symbol} base units (token ${m.address}, decimals ${m.decimals}) on ${o.id}; beneficiary ${l}; maturity ${o.market.maturity} Unix seconds. No callbacks or delegation. Withdrawal can fail if collateral health or lender liquidity changes.`,h=[...c?[e.approval(c.address,Y,d.toString(),f)]:[],e.unsignedTx({to:Y,data:ot({abi:oe,functionName:String(a),args:u}),value:"0",chainId:f,description:p})];return r(h,l,p)}),s("morpho_midnight_manage",{operation:{type:"string",enum:["setConsumed","setIsAuthorized","setConfigurator","setFeeSetter","setFeeClaimer","setTickSpacingSetter","enableLltv","enableLiquidationCursor","setMarketTickSpacing","setMarketSettlementFee","setMarketContinuousFee","setDefaultSettlementFee","setDefaultContinuousFee","claimSettlementFee"],description:"Midnight management function name; role-gated except setConsumed and setIsAuthorized, which act on this wallet."},values:{type:"array",maxItems:3,description:"Ordered arguments for the chosen operation, as in the Midnight ABI: decimal strings for integers (base units), 0x addresses or bytes32, or booleans.",items:{oneOf:[{type:"string"},{type:"boolean"}]}}},["operation","values"],async(n,l)=>{let o={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(o)].includes(n.operation)||!Array.isArray(n.values))throw new i("Choose a finite Midnight management operation and ordered values.");let a=n.operation,u=oe.find(p=>p.name===a);if(n.values.length!==u.inputs.length)throw new i("Provide the exact ordered operation values.");let c=e.clientFor(f);if(await c.getChainId()!==f)throw new i("Midnight requires chain 4663.");let m=u.inputs.map((p,h)=>{let b=n.values[h];if(p.type==="bool"){if(typeof b!="boolean")throw new i("Use boolean management values.");return b}if(p.type==="address")return Oe(b,"Use explicit management addresses.",Ne);if(p.type==="bytes32")return _e(b,32);if(/^uint/.test(p.type)){let w=O(b,!0);if(w>=1n<<BigInt(p.type.slice(4)))throw new i("Management integer exceeds its ABI width.");return w}throw new i("Unsupported management argument type.")});if(a==="setConsumed"||a==="setIsAuthorized"){if(!R(String(m[2]),l))throw new i("Midnight management is bound to this wallet.")}else{let p=await c.readContract({address:Y,abi:oe,functionName:o[a]});if(typeof p!="string"||K(p)!==K(l))throw new i("This wallet lacks the Midnight configuration, fee or tick role.")}let d=`Midnight ${a}, ordered values ${JSON.stringify(n.values)}. ${a==="setIsAuthorized"&&m[1]?"This grants authority over all Midnight positions, cancellations and further delegation, without an amount cap. Revoke with false when done.":""}${a==="setConsumed"?"Consumption only increases; setting uint128 maximum permanently cancels this offer group.":""}`;return r([e.unsignedTx({to:Y,data:ot({abi:oe,functionName:a,args:m}),value:"0",chainId:f,description:d})],l,d)})]}};import{decodeAbiParameters as re,encodeAbiParameters as Ao,encodeFunctionData as G,erc20Abi as it,getAddress as D,isAddress as Fe,keccak256 as xo,parseAbi as Ve,parseAbiParameters as J}from"viem";var De="morpho",Io="https://api.morpho.org/graphql",B=D(z[f].morpho.morpho_blue.address),To=D(z[f].morpho.adaptive_curve_irm.address),Mo=D(z[f].morpho.USDG.address),me=D(z[f].morpho.WETH.address),vo=["0x7c820d6a09502d63be80bb8025ec479d29d7c06e70f8df65a92aaeed23a366e2","0x1fa5293f9f60059a7f6a4923022156fcdcc038bd3749be55897000c03afe92d8"],Po={"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."},lt=[{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"}],Co=new Map(lt.map(e=>[e.marketId.toLowerCase(),e]));function j(e){return Co.get(e.toLowerCase())}function ct(e){let t=j(e);return t?{actions:"enabled",label:t.label,source:Po[t.source]}:{actions:"read-only",reason:"Not in Oak's verified Morpho market registry; Oak builds no transactions for it."}}var qt=20,qe=120n,ze=1000000n,We=1n,Se=10n**18n,Lo=10n**36n,jt=(1n<<128n)-1n,Do=(1n<<256n)-1n,X=Ve(["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)"]),Uo=Ve(["function price() view returns (uint256)"]),$o=Ve(["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)"]),Kt=Ve(["function deposit() payable"]);function pe(e){return{loanToken:e.loanToken,collateralToken:e.collateralToken,oracle:e.oracle,irm:e.irm,lltv:e.lltv.toString()}}function Ue(e,t){return e===0n?0n:(e+t-1n)/t}function Bo(e,t,s){return e*(s+ze)/(t+We)}function No(e,t,s){return Ue(e*(s+ze),t+We)}function ut(e,t,s){return e*(t+We)/(s+ze)}function se(e,t,s){return Ue(e*(t+We),s+ze)}function Ae(e,t,s){return e*t/Lo*s/Se}function Oo(e,t,s){return t.startsWith("-")?`-${e.formatAmount(t.slice(1),s)}`:e.formatAmount(t,s)}function xe(e,t){let s=[],r={};for(let n of t.changes){let l=Oo(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 Qt(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 je(e){if(!e||typeof e!="object")throw new i("Morpho marketParams must be an object.");for(let o of[e.loanToken,e.collateralToken,e.oracle,e.irm])if(typeof o!="string"||!Fe(o,{strict:!1}))throw new i("Morpho marketParams contains an invalid address.");let t=D(e.loanToken),s=D(e.collateralToken),r=D(e.oracle),n=D(e.irm),l=typeof e.lltv=="bigint"?e.lltv:Le(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>=Se)throw new i("Morpho marketParams LLTV must be between 0 and 1e18.");return{loanToken:t,collateralToken:s,oracle:r,irm:n,lltv:l}}function ke(e){let t=je(e),s=Ao(J("address, address, address, address, uint256"),[t.loanToken,t.collateralToken,t.oracle,t.irm,t.lltv]);return xo(s)}function dt(e){let t=e.toLowerCase();return t===ht.toLowerCase()||t===wt.toLowerCase()||t===te.toLowerCase()}function Ie(e,t){let s=t??e.wallet;if(!s)throw new i("Provide a valid wallet address.");return q(s),D(s)}async function ne(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 Xt(e){return typeof e=="string"&&/^[A-Za-z0-9$._+-]{1,32}$/.test(e)?e:"UNKNOWN"}async function Q(e,t,s=f){if(q(t),dt(t))return{...kt,chainId:s};let r=D(t),n=r.toLowerCase();if(s===f){if(n===Mo.toLowerCase())return yt;if(n===me.toLowerCase())return gt}let[l,o]=await Promise.all([ne(e,r,G({abi:it,functionName:"symbol"})),ne(e,r,G({abi:it,functionName:"decimals"}))]),[a]=re(J("string"),l),[u]=re(J("uint8"),o);return{address:r,symbol:Xt(a),decimals:Number(u),chainId:s}}async function Yt(e,t){let s=await ne(e,B,G({abi:X,functionName:"idToMarketParams",args:[t]})),[r,n,l,o,a]=re(J("address, address, address, address, uint256"),s);return{loanToken:D(r),collateralToken:D(n),oracle:D(l),irm:D(o),lltv:a}}async function Jt(e,t){let s=await ne(e,B,G({abi:X,functionName:"market",args:[t]})),[r,n,l,o,a,u]=re(J("uint128, uint128, uint128, uint128, uint128, uint128"),s);return{totalSupplyAssets:r,totalSupplyShares:n,totalBorrowAssets:l,totalBorrowShares:o,lastUpdate:a,fee:u}}async function Te(e,t,s){let r=await ne(e,B,G({abi:X,functionName:"position",args:[t,D(s)]})),[n,l,o]=re(J("uint256, uint128, uint128"),r);return{supplyShares:n,borrowShares:l,collateral:o}}async function Ke(e,t){let s=await ne(e,D(t),G({abi:Uo,functionName:"price"})),[r]=re(J("uint256"),s);return r}async function Eo(e,t,s){if(t.irm===te)return 0n;let r=await ne(e,D(t.irm),G({abi:$o,functionName:"borrowRateView",args:[t,s]})),[n]=re(J("uint256"),r);return n}function Qe(e,t,s){let r=s>e.lastUpdate?s-e.lastUpdate:0n,n=t*r,l=Ue(n*n,2n*Se),o=Ue(l*n,3n*Se);return e.totalBorrowAssets+Ue(e.totalBorrowAssets*(n+l+o),Se)}async function $e(e,t,s,r=0n){let[n,l]=await Promise.all([e.getBlock({blockTag:"latest"}),Eo(e,t,s)]),o=BigInt(Math.ceil(Date.now()/1e3)),a=(n.timestamp>o?n.timestamp:o)+r;return{totalBorrowAssets:Qe(s,l,a),accruedThrough:a,rate:l}}async function Zt(e,t,s){let r=await ne(e,D(t),G({abi:it,functionName:"balanceOf",args:[D(s)]})),[n]=re(J("uint256"),r);return n}async function fe(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?je(n):void 0,o=l?ke(l):void 0,a=r!==void 0?Qt(r):void 0;if(a&&o&&a!==o.toLowerCase())throw new i(`MarketParams tuple hash (${o}) does not match marketId (${a}).`);let u=(a??o).toLowerCase();if(s&&!j(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[c,m]=await Promise.all([Yt(e,u),Jt(e,u)]);if(c.loanToken===te||c.collateralToken===te||c.lltv===0n||m.lastUpdate===0n)throw new i(`Morpho market ${u} is not initialized on chain ${f}.`);let d=ke(c);if(d.toLowerCase()!==u.toLowerCase())throw new i(`On-chain idToMarketParams tuple hash (${d}) does not match marketId (${u}).`);if(l&&!(l.loanToken.toLowerCase()===c.loanToken.toLowerCase()&&l.collateralToken.toLowerCase()===c.collateralToken.toLowerCase()&&l.oracle.toLowerCase()===c.oracle.toLowerCase()&&l.irm.toLowerCase()===c.irm.toLowerCase()&&l.lltv===c.lltv))throw new i(`Provided marketParams tuple does not match on-chain idToMarketParams for ${u}.`);return{marketId:u,marketParams:c,marketState:m}}function Me(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=Le(t);if(s<=0n||s>jt)throw new i("Asset amount must be greater than zero and fit in uint128.");return s}function ve(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 Go(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=e.clientFor(f),{marketId:o,marketParams:a}=await fe(l,t,!0),u=await Q(l,a.collateralToken,f),c=a.collateralToken.toLowerCase()===me.toLowerCase(),m=typeof t.collateralToken=="string"?(q(t.collateralToken),D(t.collateralToken)):void 0,d=W("wrapNative",t.wrapNative)===!0||m!==void 0&&dt(m);if(m&&!dt(m)&&m.toLowerCase()!==a.collateralToken.toLowerCase())throw new i(`Collateral token ${m} does not match market collateral ${a.collateralToken}.`);if(d&&!c)throw new i("Native ETH wrapping is only supported when market collateralToken is WETH.");let p=Me(t),h=p.toString(),b=e.formatAmount(h,u.decimals),w=[];d&&w.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:h,description:`Wrap ${b} ETH into WETH at ${me}.`})),w.push(e.approval(a.collateralToken,B,h,f)),w.push(e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"supplyCollateral",args:[a,p,n,"0x"]}),value:"0",description:`Supply ${b} ${u.symbol} (${h} base units) collateral to Morpho market ${o}.`}));let k=await e.preview(w,r),{formattedChanges:y,formattedNetOutflows:g}=xe(e,k);return{action:"morpho_supply_collateral",chainId:f,marketId:o,marketParams:pe(a),collateralToken:u,assets:h,formattedAssets:b,onBehalf:n,txs:w,summary:`${d?`Send ${b} ETH to wrap into WETH. `:""}Supply ${b} ${u.symbol} collateral to Morpho Blue market ${o}.`,preview:k,formattedChanges:y,formattedNetOutflows:g}}async function Ro(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,o=e.clientFor(f),{marketId:a,marketParams:u,marketState:c}=await fe(o,t,!0),[m,d,p,h]=await Promise.all([Q(o,u.loanToken,f),Te(o,a,n),Ke(o,u.oracle),$e(o,u,c,qe)]),b=Me(t),w=b.toString(),k=e.formatAmount(w,m.decimals),y=c.totalSupplyAssets>c.totalBorrowAssets?c.totalSupplyAssets-c.totalBorrowAssets:0n;if(b>y)throw new i(`Insufficient market liquidity: requested ${w} base units, available ${y.toString()} base units.`);let g=Ae(d.collateral,p,u.lltv),I=se(d.borrowShares,h.totalBorrowAssets,c.totalBorrowShares);if(d.collateral===0n||I+b>g)throw new i(`Insufficient collateral or unhealthy borrow: total debt ${(I+b).toString()} exceeds max borrow ${g.toString()} base units.`);let x=No(b,h.totalBorrowAssets,c.totalBorrowShares),P=[e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"borrow",args:[u,b,0n,n,l]}),value:"0",description:`Borrow ${k} ${m.symbol} (${w} base units) from Morpho market ${a}.`})],C=await e.preview(P,r),{formattedChanges:L,formattedNetOutflows:v}=xe(e,C);return{action:"morpho_borrow",chainId:f,marketId:a,marketParams:pe(u),loanToken:m,assets:w,formattedAssets:k,borrowShares:x.toString(),onBehalf:n,receiver:l,txs:P,summary:`Borrow ${k} ${m.symbol} from Morpho Blue market ${a}.`,preview:C,formattedChanges:L,formattedNetOutflows:v}}async function eo(e,t,s,r=qe){let n=Ie(t,s);ve(t,n);let l=n,o=e.clientFor(f);if(t.shares!==void 0){let v=Le(t.shares);if(v<=0n||v===Do||v>jt)throw new i("Morpho Blue core does not accept maxUint256 or out-of-range share sentinels; pass exact position.borrowShares.")}if(W("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:u,marketState:c}=await fe(o,t,!0),[m,d,p]=await Promise.all([Q(o,u.loanToken,f),Te(o,a,l),Zt(o,u.loanToken,n)]);if(d.borrowShares===0n)throw new i(`Position has no active borrow debt on Morpho market ${a}.`);let h=0n,b=0n;if(W("repayAll",t.repayAll)===!0)b=d.borrowShares;else if(t.shares!==void 0){let v=Le(t.shares);if(v>d.borrowShares)throw new i(`Repay shares (${v.toString()}) exceed current position borrowShares (${d.borrowShares.toString()}).`);b=v}else h=Me(t);let w=b>0n?await $e(o,u,c,r):void 0,k=b>0n?se(b,w.totalBorrowAssets,c.totalBorrowShares):h;if(p<k)throw new i(`Insufficient loan token balance for repayment: wallet holds ${p.toString()} base units, but ${k.toString()} base units are required (including accrued interest).`);let y=k.toString(),g=e.formatAmount(y,m.decimals),I=e.approval(u.loanToken,B,y,f),x=e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"repay",args:[u,h,b,l,"0x"]}),value:"0",description:b>0n?`Repay ${b.toString()} borrow shares (${g} ${m.symbol}) on Morpho market ${a}.`:`Repay ${g} ${m.symbol} (${h.toString()} base units) on Morpho market ${a}.`}),T=[I,x],P=await e.preview(T,n),{formattedChanges:C,formattedNetOutflows:L}=xe(e,P);return{action:"morpho_repay",chainId:f,marketId:a,marketParams:pe(u),loanToken:m,repayAssets:h.toString(),repayShares:b.toString(),requiredAssets:y,...w?{accruedThrough:w.accruedThrough.toString(),borrowRatePerSecond:w.rate.toString(),inclusionSeconds:r.toString()}:{},formattedRequiredAssets:g,onBehalf:l,txs:T,summary:b>0n?`Repay ${b.toString()} borrow shares (approval up to ${g} ${m.symbol}) on Morpho Blue market ${a}. Refresh if signing/inclusion takes more than ${qe} seconds.`:`Repay ${g} ${m.symbol} on Morpho Blue market ${a}.`,preview:P,formattedChanges:C,formattedNetOutflows:L}}function Ka(e,t,s){if(t.repayAll!==!0)throw new i("Reviewed debt reconstruction requires repayAll.");return eo(e,t,s,0n)}async function _o(e,t,s){let r=Ie(t,s);ve(t,r);let n=r,l=r,o=e.clientFor(f),{marketId:a,marketParams:u,marketState:c}=await fe(o,t,!0),[m,d,p,h]=await Promise.all([Q(o,u.collateralToken,f),Te(o,a,n),Ke(o,u.oracle),$e(o,u,c,qe)]),b=W("withdrawAll",t.withdrawAll)===!0?d.collateral:Me(t);if(b<=0n||b>d.collateral)throw new i(`Insufficient collateral to withdraw: requested ${b.toString()} base units, position holds ${d.collateral.toString()} base units.`);if(d.borrowShares>0n){let P=d.collateral-b,C=Ae(P,p,u.lltv),L=se(d.borrowShares,h.totalBorrowAssets,c.totalBorrowShares);if(L>C)throw new i(`Unhealthy collateral withdrawal: remaining max borrow ${C.toString()} would fall below current debt ${L.toString()} base units.`)}let w=b.toString(),k=e.formatAmount(w,m.decimals),g=[e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"withdrawCollateral",args:[u,b,n,l]}),value:"0",description:`Withdraw ${k} ${m.symbol} (${w} base units) collateral from Morpho market ${a}.`})],I=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:T}=xe(e,I);return{action:"morpho_withdraw_collateral",chainId:f,marketId:a,marketParams:pe(u),collateralToken:m,assets:w,formattedAssets:k,onBehalf:n,receiver:l,txs:g,summary:`Withdraw ${k} ${m.symbol} collateral from Morpho Blue market ${a}.`,preview:I,formattedChanges:x,formattedNetOutflows:T}}async function Ho(e,t,s){let r=Ie(t,s);ve(t,r);let n=e.clientFor(f),{marketId:l,marketParams:o,marketState:a}=await fe(n,t,!0),u=W("wrapNative",t.wrapNative)===!0;if(u&&o.loanToken.toLowerCase()!==me.toLowerCase())throw new i("Native ETH wrapping is only supported when the market loanToken is WETH.");let c=Me(t),m=c.toString(),[d,p]=await Promise.all([Q(n,o.loanToken,f),u?Promise.resolve(c):Zt(n,o.loanToken,r)]);if(p<c)throw new i(`Insufficient ${d.symbol} balance to lend: wallet holds ${p.toString()} base units, requested ${m}.`);let h=e.formatAmount(m,d.decimals),b=[];u&&b.push(e.unsignedTx({chainId:f,to:me,data:G({abi:Kt,functionName:"deposit"}),value:m,description:`Wrap ${h} ETH into WETH at ${me}.`})),b.push(e.approval(o.loanToken,B,m,f)),b.push(e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"supply",args:[o,c,0n,r,"0x"]}),value:"0",description:`Lend ${h} ${d.symbol} (${m} base units) to Morpho market ${l}.`}));let w=Bo(c,a.totalSupplyAssets,a.totalSupplyShares),k=await e.preview(b,r),{formattedChanges:y,formattedNetOutflows:g}=xe(e,k);return{action:"morpho_supply",chainId:f,marketId:l,marketParams:pe(o),loanToken:d,assets:m,formattedAssets:h,supplySharesEstimated:w.toString(),onBehalf:r,oak:ct(l),txs:b,summary:`${u?`Send ${h} ETH to wrap into WETH. `:""}Lend ${h} ${d.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:k,formattedChanges:y,formattedNetOutflows:g}}async function qo(e,t,s){let r=Ie(t,s);ve(t,r);let n=e.clientFor(f),l=W("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:o,marketParams:a,marketState:u}=await fe(n,t,!0),[c,m]=await Promise.all([Q(n,a.loanToken,f),Te(n,o,r)]);if(m.supplyShares===0n)throw new i(`This wallet has no lent ${c.symbol} on Morpho market ${o}.`);let d=ut(m.supplyShares,u.totalSupplyAssets,u.totalSupplyShares),p=l?0n:Me(t),h=l?m.supplyShares:0n;if(!l&&p>d)throw new i(`Withdrawal exceeds the lent balance: requested ${p.toString()} base units, position holds about ${d.toString()}. Use withdrawAll for a full exit.`);let b=u.totalSupplyAssets>u.totalBorrowAssets?u.totalSupplyAssets-u.totalBorrowAssets:0n,w=l?d:p;if(w>b)throw new i(`Insufficient market liquidity: withdrawing ${w.toString()} base units needs idle assets, but only ${b.toString()} are available until borrowers repay. Withdraw at most that amount, or retry later.`);let k=e.formatAmount(w.toString(),c.decimals),g=[e.unsignedTx({chainId:f,to:B,data:G({abi:X,functionName:"withdraw",args:[a,p,h,r,r]}),value:"0",description:l?`Withdraw all ${m.supplyShares.toString()} supply shares (about ${k} ${c.symbol}) from Morpho market ${o}.`:`Withdraw ${k} ${c.symbol} (${p.toString()} base units) of lent assets from Morpho market ${o}.`})],I=await e.preview(g,r),{formattedChanges:x,formattedNetOutflows:T}=xe(e,I);return{action:"morpho_withdraw",chainId:f,marketId:o,marketParams:pe(a),loanToken:c,withdrawAssets:p.toString(),withdrawShares:h.toString(),estimatedAssets:w.toString(),formattedAssets:k,receiver:r,txs:g,summary:l?`Withdraw all lent ${c.symbol} (about ${k}, including interest) from Morpho Blue market ${o}.`:`Withdraw ${k} lent ${c.symbol} from Morpho Blue market ${o}.`,preview:I,formattedChanges:x,formattedNetOutflows:T}}async function to(e,t,s){let r=await e.http(Io,{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 oo(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
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as p,e as y}from"./
|
|
1
|
+
import{a as p,e as y}from"./BWE5PXRE.js";import{a as m}from"./UNBRUWSV.js";import{r as v}from"./5PNFV7HH.js";import{a as f}from"./66F5ZH34.js";import{b as l}from"./EWZFZUVF.js";import{a as u}from"./XSD5NL7J.js";import{encodeFunctionData as w,getAddress as a,parseAbi as I}from"viem";var P="(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks)",$="(address tokenIn,address tokenOut,uint24 fee,address recipient,uint256 amountIn,uint256 amountOutMinimum,uint160 sqrtPriceLimitX96)",g=I([`function swapExactIn(${P} key,bool zeroForOne,uint128 amountIn,uint256 minOut,uint160 sqrtPriceLimitX96,address to,uint256 deadline) returns (uint256 paid,uint256 out)`,`function exactInputSingle(${$} params) payable returns (uint256 amountOut)`,"function multicall(uint256 deadline,bytes[] data) payable returns (bytes[] results)"]),E=I(["function quoteExactInputSingle((address tokenIn,address tokenOut,uint256 amountIn,uint24 fee,uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut,uint160 sqrtPriceX96After,uint32 initializedTicksCrossed,uint256 gasEstimate)"]),_=I([`function quoteExactInputSingle((${P} poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountOut,uint256 gasEstimate)`]),C="0x0000000000000000000000000000000000000000",h={symbol:{type:"string",enum:m.tokens.map(e=>e.symbol),description:'Official stock ticker with a published Priors pool. Example: "TSLA".'},side:{type:"string",enum:["buy","sell"],description:'Choose "buy": pay USDG for the stock token; "sell": pay the stock token for USDG.'},amountIn:f('Input amount in base units: USDG (6 decimals) to buy, or the stock token (its decimals) to sell. Example: "1000000" = 1 USDG.')};async function O(e,o){let n=m.tokens.find(s=>s.symbol===e.symbol);if(!n||e.side!=="buy"&&e.side!=="sell")throw new u("Choose a published stock symbol and buy or sell.");let t=await v(String(e.symbol),{context:o});if(t.kind!=="official_stock"||t.address!==a(n.token))throw new u("Published Priors stock pool does not match the official stock contract address. Retry after the pool mapping is updated.");let r=y(e.amountIn,"amountIn",128);if(r===0n)throw new u("amountIn must be positive base units.");return{token:n,identity:t,amount:r,input:e.side==="buy"?p.usdg:a(n.token),output:e.side==="buy"?a(n.token):p.usdg}}function x(e,o,n){let[t,r]=BigInt(p.usdg)<BigInt(e)?[p.usdg,e]:[e,p.usdg];return{currency0:t,currency1:r,fee:o,tickSpacing:n,hooks:C}}function R(e){return{tools:[{name:"priors_stock_quote",inputSchema:{type:"object",properties:h,required:Object.keys(h),additionalProperties:!1},async execute(o,n){if(e.network==="testnet")throw new u("Priors stock swaps require mainnet chain 4663.");let t=await O(o,e),r=e.clientFor(l),s=await r.getBlockNumber({cacheTime:0}),k=await Promise.all(t.token.pools.map(async(i,d)=>{try{let c=x(a(t.token.token),i.fee,"tickSpacing"in i?i.tickSpacing:0),b=i.v===3?await r.simulateContract({address:a(m.v3.quoter),abi:E,functionName:"quoteExactInputSingle",args:[{tokenIn:t.input,tokenOut:t.output,amountIn:t.amount,fee:i.fee,sqrtPriceLimitX96:0n}],account:n,blockNumber:s}):await r.simulateContract({address:a(m.v4.quoter),abi:_,functionName:"quoteExactInputSingle",args:[{poolKey:c,zeroForOne:t.input===c.currency0,exactAmount:t.amount,hookData:"0x"}],account:n,blockNumber:s});return{poolIndex:d,version:i.v,amountOut:b.result[0].toString()}}catch(c){return{poolIndex:d,version:i.v,error:e.plainError(c)}}}));return{chainId:l,blockNumber:s.toString(),token:t.identity,quotes:k,warning:"Use explicit minimum output with priors_stock_swap and inspect its preview. Issuer restrictions can prevent sale. Quote is no promise of an exit; local regional eligibility remains required."}}},{name:"priors_stock_swap",inputSchema:{type:"object",properties:{...h,poolIndex:{type:"integer",minimum:0,maximum:2,description:"Index of the published pool to use, from priors_stock_quote (0 to 2)."},minOut:f("Minimum output in base units: the stock token when buying, USDG (6 decimals) when selling. Must be positive."),deadline:f("Deadline in Unix seconds, within the next 30 minutes. Example: 1800000000."),eligible:{type:"boolean",description:"Operator/user affirms eligibility for this stock-token trade in their jurisdiction."}},required:[...Object.keys(h),"poolIndex","minOut","deadline","eligible"],additionalProperties:!1},async execute(o,n){if(e.network==="testnet")throw new u("Priors stock swaps require mainnet chain 4663.");if(n=a(n),o.eligible!==!0)throw new u("Confirm local eligibility for Robinhood stock tokens before trading.");let t=await O(o,e),r=y(o.minOut,"minOut"),s=y(o.deadline,"deadline"),k=BigInt(Math.floor(Date.now()/1e3));if(r===0n||s<=k||s>k+1800n||!Number.isSafeInteger(o.poolIndex))throw new u("Provide positive minOut, poolIndex and a deadline within 30 minutes.");let i=t.token.pools[o.poolIndex];if(!i)throw new u("No published pool at that index. Read priors_stock_quote.");let d=x(a(t.token.token),i.fee,"tickSpacing"in i?i.tickSpacing:0),c=t.input===d.currency0,b=a(i.v===3?m.v3.router:m.v4.swapper),q=i.v===3?w({abi:g,functionName:"multicall",args:[s,[w({abi:g,functionName:"exactInputSingle",args:[{tokenIn:t.input,tokenOut:t.output,fee:i.fee,recipient:n,amountIn:t.amount,amountOutMinimum:r,sqrtPriceLimitX96:0n}]})]]}):w({abi:g,functionName:"swapExactIn",args:[d,c,t.amount,r,c?4295128740n:1461446703485210103287273052203988822378723970341n,n,s]}),S=[e.approval(t.input,b,t.amount.toString(),l),e.unsignedTx({to:b,data:q,value:"0",chainId:l,description:`Priors stock ${o.side}: ${t.amount} input base units; minimum ${r}; pinned V${i.v} pool.`})],A=await e.preview(S,n);return{txs:S,expiresAt:s.toString(),summary:`Stock ${o.side} ${o.symbol}: input ${t.amount} base units (${t.input}), minimum output ${r} (${t.output}), receiver ${n}, deadline ${s}. Issuer transfer/sale restrictions apply. Price impact is not measured by this builder; inspect minOut and the preview. ${A.summary}`}}}]}}export{g as a,R as b};
|
|
@@ -1 +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"./SCG5HWMN.js";import{a as M}from"./5TUXSOMI.js";import{e as c}from"./NWNYJ26T.js";import{b as m,j as x}from"./
|
|
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"./SCG5HWMN.js";import{a as M}from"./5TUXSOMI.js";import{e as c}from"./NWNYJ26T.js";import{b as m,j as x}from"./EWZFZUVF.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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as H}from"./66F5ZH34.js";import{c as B,f as j,g as b,k as F,n as G}from"./NWNYJ26T.js";import{b as k,j as z}from"./TI727O2H.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,T={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 I(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&&b(e.address,p.address)}function ee(e,p){let c=C(e),m=C(c.pickConfig),l=I(c.holder),f=I(m.marketAddress);if(c.chainId!==k||!b(l,p))throw new a("Meridian returned a position for a different wallet or chain.");if(!b(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(!b(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:I(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){I(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||b(I(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:{...T},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:{...T},amount:n.userCollateral},totalPayout:{token:{...T},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:I(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),M=I(i.resolver);if(u!==void 0&&!b(y,u)||d!==void 0&&!b(M,d))throw new a("Meridian returned a different condition or resolver than requested.");return{conditionId:y,resolver:M,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:{...T},totalCount:g.totalCount,markets:w,limit:o,nextCursor:g.nextCursor,complete:g.complete,asOf:String(s)}}async function ie(t,o){let r=I(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 M=y[0];if(M.pickConfig.resolved){let re=D(await n.readContract({address:S,abi:U,functionName:"getClaimableAmount",args:[M.pickConfigId,r,BigInt(s)]}));if(BigInt(re)===0n)throw i}h=[_(M.prediction.predictionId),d],g=await e.preview(h,o)}let w=g.changes.filter(i=>ue(i.token,T)&&i.token.decimals===T.decimals).reduce((i,y)=>i+BigInt(y.amount),0n),x=g.changes.filter(i=>i.token.chainId===k&&b(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),I(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,description:"Search text for open conditions."},cursor:V,limit:{...W,description:"Maximum results per page, from 1 to 25."},conditionId:{...K,description:"Condition identifier as a 0x-prefixed 32-byte hex string."},resolver:{...B,description:"Condition resolver contract address on chain 4663."},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,description:"Maximum results per page, from 1 to 25."}},[],"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,description:"Prediction identifier as a 0x-prefixed 32-byte hex string."}},["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,description:"Meridian position token contract address on chain 4663."},amount:H('Position token amount in base units using its decimals; for an 18-decimal position token, "1000000000000000000" = 1 position token.')},["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
|
+
import{a as H}from"./66F5ZH34.js";import{c as B,f as j,g as b,k as F,n as G}from"./NWNYJ26T.js";import{b as k,j as z}from"./EWZFZUVF.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,T={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 I(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&&b(e.address,p.address)}function ee(e,p){let c=C(e),m=C(c.pickConfig),l=I(c.holder),f=I(m.marketAddress);if(c.chainId!==k||!b(l,p))throw new a("Meridian returned a position for a different wallet or chain.");if(!b(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(!b(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:I(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){I(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||b(I(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:{...T},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:{...T},amount:n.userCollateral},totalPayout:{token:{...T},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:I(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),M=I(i.resolver);if(u!==void 0&&!b(y,u)||d!==void 0&&!b(M,d))throw new a("Meridian returned a different condition or resolver than requested.");return{conditionId:y,resolver:M,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:{...T},totalCount:g.totalCount,markets:w,limit:o,nextCursor:g.nextCursor,complete:g.complete,asOf:String(s)}}async function ie(t,o){let r=I(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 M=y[0];if(M.pickConfig.resolved){let re=D(await n.readContract({address:S,abi:U,functionName:"getClaimableAmount",args:[M.pickConfigId,r,BigInt(s)]}));if(BigInt(re)===0n)throw i}h=[_(M.prediction.predictionId),d],g=await e.preview(h,o)}let w=g.changes.filter(i=>ue(i.token,T)&&i.token.decimals===T.decimals).reduce((i,y)=>i+BigInt(y.amount),0n),x=g.changes.filter(i=>i.token.chainId===k&&b(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),I(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,description:"Search text for open conditions."},cursor:V,limit:{...W,description:"Maximum results per page, from 1 to 25."},conditionId:{...K,description:"Condition identifier as a 0x-prefixed 32-byte hex string."},resolver:{...B,description:"Condition resolver contract address on chain 4663."},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,description:"Maximum results per page, from 1 to 25."}},[],"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,description:"Prediction identifier as a 0x-prefixed 32-byte hex string."}},["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,description:"Meridian position token contract address on chain 4663."},amount:H('Position token amount in base units using its decimals; for an 18-decimal position token, "1000000000000000000" = 1 position token.')},["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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as Se,j as He,l as Re,m as Te}from"./MFQTBUSD.js";import{a as ne,b as ie}from"./AODUTN65.js";import{a as xe,h as Pe}from"./QAAKUIWE.js";import{a as Ae,f as Fe,g as Ee}from"./JCS24YBB.js";import{a as we,g as be}from"./BM4KHOFB.js";import{a as ge,h as ye}from"./ZSGW2ZSO.js";import{a as ke,g as fe}from"./RKJFSDGV.js";import{a as X}from"./TZG7HTVM.js";import{a as Z,j as N,o as J}from"./5Y457HYC.js";import{a as me,b as he}from"./64LAWFBE.js";import{a as ce,b as pe}from"./G53U6Y4L.js";import{a as ue,b as le}from"./FMEO7RX7.js";import{k as ee}from"./G4IX4CYN.js";import{a as Be,c as ve}from"./IJVBCEA2.js";import{b as re,c as se}from"./HPO673QQ.js";import{a as R,b as Ce}from"./JQVTHPUO.js";import{c as te,d as v,e as oe}from"./RKS3M7L5.js";import{d as ae,e as de}from"./5VKVAUFQ.js";import{g as K}from"./3RGED2KO.js";import{a as S,e as H,f as u,i as D,j as w,k as j,m as B,o as V,p as W,r as Y}from"./UMY6SP7C.js";import{b as f,i as O,j as q,k as L}from"./CJMVRV34.js";import{a as d}from"./XSD5NL7J.js";import{decodeAbiParameters as Ue,encodeAbiParameters as Q,formatUnits as Oe,getAddress as Ge,zeroAddress as qe}from"viem";var T=[{type:"tuple",components:[{name:"guardEndBlock",type:"uint40"},{name:"maxFeePips",type:"uint24"},{name:"snipeTaxPips",type:"uint24"},{name:"snipeFloorPips",type:"uint24"},{name:"snipeDecaySeconds",type:"uint16"},{name:"dynamicFeeSens",type:"uint16"},{name:"burnBps",type:"uint16"},{name:"lpBps",type:"uint16"},{name:"potBps",type:"uint16"},{name:"royaltyBps",type:"uint16"},{name:"protocolShareBps",type:"uint16"},{name:"potEveryNBuys",type:"uint32"},{name:"maxBuyQuoteAmount",type:"uint128"},{name:"potMinBuyQuote",type:"uint128"},{name:"royaltyTo",type:"address"},{name:"integrator",type:"address"}]}],Le=Ge("0x84b1B9e5D1cAfD9543E684BB39E9cbD478189EE2"),Ke=["anti-snipe","dynamic-fees","auto-burn","lp-rewards","arb-recapture","buy-sell-block","agent-gate","market-guard","market-hours-fee","managed-fee","zap-source","zap-target","swap-reward-mint","pay-later","exit-clock","holder-pot","storm-fee","wallet-cap","swap-cut","sandwich-guard"],Ve=["anti-snipe","dynamic-fees","auto-burn","lp-rewards","buy-sell-block","exit-clock","storm-fee","wallet-cap","swap-cut","sandwich-guard","holder-pot"],De=Ve,M={"anti-snipe":["guardEndBlock","taxPips","floorPips","decaySeconds","maxBuyQuoteAmount"],"dynamic-fees":["maxFeePips","sensitivity"],"auto-burn":["burnBps"],"lp-rewards":["lpBps"],"buy-sell-block":["buyPause","sellLock"],"exit-clock":["top","floor","horizon","unit","curve"],"storm-fee":["ceiling","floor"],"wallet-cap":["cap"],"swap-cut":["buy","sell","recipient"],"sandwich-guard":["window","maximum","recipient"],"holder-pot":["buy","sell"]},Ie={"market-guard":ge.wiring+" The launch advisory slot is occupied by the agent gate.","market-hours-fee":ke.wiring+" The launch advisory slot is occupied by the agent gate.","managed-fee":we.wiring+" The launch advisory slot is occupied by the agent gate.","zap-source":Z,"zap-target":xe,"swap-reward-mint":Se,"pay-later":X,"holder-pot":Ae.refusal},We={"buy-sell-block":"buyPause 0\u2013300 and sellLock 0\u20135 are twelve-second steps after launch; at least one positive. Requires an Anti-Snipe guard covering the windows. No fee.","wallet-cap":"cap is cumulative subject base units bought per wallet during the Anti-Snipe guard; it must fit the exact decimal mantissa/exponent codec. Sales do not restore it. No fee.","exit-clock":"LP-fee destination only. top 1\u2013100 and floor below top are ten-basis-point steps. horizon is 1\u201363 hours (unit 0) or 3\u201330 days (unit 1). curve 0 linear, 1 eight-segment halving, 2 eight steps. Pinned new-token lots determine holding age.","storm-fee":"LP-fee destination, tempo zero. ceiling 1\u2013200 and floor 0\u2013ceiling are 500-pip steps (0.05%). Cannot combine with Dynamic Fees.","swap-cut":"buy and sell 0\u2013100 are 1000-pip steps (0.1%); at least one positive. recipient is the checksummed named quote-claim payee after the decoded protocol share, shared with Sandwich Guard if combined.","sandwich-guard":"window 0\u20133 means 1\u20134 execution blocks. maximum 5\u201315 is 10000-pip steps (1%). recipient is the checksummed named quote-claim payee after the decoded protocol share, shared with Swap Cut if combined."},A={"market-guard":["terms"],"market-hours-fee":["terms","owner","lastCoveredYear"],"managed-fee":["terms","keeper","owner"],"zap-source":["takePips","vault","route"],"zap-target":["feeders","routes"],"swap-reward-mint":["minter","terms"]},F={type:"string",pattern:"^0x[0-9a-fA-F]{40}$"},Ye=new Set(["feed","factory","poolManager","rules","router","root","gate","sink","quote","subject","protocolRecipient","currency0","currency1","advisory","fixedRecipient","rewardToken","creatorRecipient"]),je={guardEndBlock:"Set the parent block ending the guard.",taxPips:"Set the initial buy surcharge in pips (10000 = 1%).",floorPips:"Set the final buy surcharge in pips (10000 = 1%).",decaySeconds:"Set the surcharge decay duration in seconds.",maxBuyQuoteAmount:"Set the maximum buy amount in quote token base units, using the quote token decimals.",maxFeePips:"Set the maximum pool fee in pips (10000 = 1%).",sensitivity:"Set dynamic fee sensitivity from 1 to 10.",burnBps:"Set the burn rate in basis points (100 = 1%).",lpBps:"Set the LP fee rate in basis points (100 = 1%).",buyPause:"Set the buy pause in twelve-second steps from 0 to 300.",sellLock:"Set the sell lock in twelve-second steps from 0 to 5.",top:"Set the initial LP fee in ten-basis-point steps.",horizon:"Set the exit-clock horizon in the selected unit.",unit:"Choose 0 for hours or 1 for days.",curve:"Choose 0 for linear, 1 for segmented halving, or 2 for stepped decay.",ceiling:"Set the storm fee ceiling in 500-pip steps.",recipient:"Use the intended quote-claim payee address.",window:"Set the sandwich guard window from 0 to 3, representing 1 to 4 execution blocks.",maximum:"Set the sandwich guard maximum in 10000-pip steps.",terms:"Provide the exact configured advisory terms.",route:"Provide the exact configured vault route.",routes:"Provide the exact configured feeder vault routes.",feeders:"Provide the intended feeder vault addresses.",takePips:"Set the quote take in pips (10000 = 1%).",lastCoveredYear:"Provide the last calendar year covered by the advisory.",minDepth:"Set the minimum depth in quote token base units, using the quote token decimals.",threshold:"Provide the vault threshold in quote token base units, using the quote token decimals.",maxPerZap:"Match the vault maximum per zap in quote token base units, or 0 for no cap.",maxRewardPerSwap:"Provide the maximum reward per swap in reward token base units, using the reward token decimals.",lifetimeRewardCap:"Provide the lifetime reward cap in reward token base units, using the reward token decimals.",maxSlicePerSwap:"Provide the maximum quote slice per swap in quote token base units, using the quote token decimals.",rewardPerQuoteWad:"Provide reward token base units per 10^18 quote token base units.",endsAt:"Provide the end timestamp in Unix seconds, or 0 for no time limit."},Ze={feed:"Provide the admitted market price feed address.",bandBps:"Set the market guard band in basis points (100 = 1%).",rampBps:"Set the market guard ramp in basis points (100 = 1%).",staleness:"Set the maximum feed age in seconds.",surchargePips:"Set the maximum market guard surcharge in pips (10000 = 1%).",regularPips:"Set the regular session surcharge in pips (10000 = 1%).",preMarketPips:"Set the pre-market surcharge in pips (10000 = 1%).",afterHoursPips:"Set the after-hours surcharge in pips (10000 = 1%).",overnightPips:"Set the overnight surcharge in pips (10000 = 1%).",closedPips:"Set the closed session surcharge in pips (10000 = 1%).",openRampSeconds:"Set the opening ramp duration in seconds.",closeRampSeconds:"Set the closing ramp duration in seconds.",surcharge:"Set the default managed LP surcharge in pips (10000 = 1%).",premium0:"Set the first directional premium in pips (10000 = 1%).",premium1:"Set the second directional premium in pips (10000 = 1%).",maxStep:"Set the maximum keeper update step in pips (10000 = 1%).",minInterval:"Set the minimum keeper update interval in seconds.",maxTtl:"Set the maximum target lifetime in seconds.",factory:"Provide the factory contract address.",poolManager:"Provide the pool manager contract address.",rules:"Provide the Rules contract address.",router:"Provide the vault router address.",root:"Provide the Hookr root contract address.",gate:"Provide the target gate contract address.",sink:"Provide the intended subject token sink address.",quote:"Provide the quote token address.",subject:"Provide the subject token address.",protocolRecipient:"Provide the intended protocol recipient address.",currency0:"Provide the target pool currency0 address.",currency1:"Provide the target pool currency1 address.",advisory:"Provide the advisory contract address.",fixedRecipient:"Provide the intended fixed reward recipient address, or the zero address in trader mode.",rewardToken:"Provide the reward token address.",creatorRecipient:"Provide the intended creator recipient address.",targetId:"Provide the target pool ID as a 0x-prefixed 32-byte hex string.",poolId:"Provide the pool ID as a 0x-prefixed 32-byte hex string.",accountInitCodeHash:"Provide the account init code hash as a 0x-prefixed 32-byte hex string.",quoteIsCurrency0:"Set whether the quote token is currency0 in the target pool.",tickLower:"Provide the lower liquidity tick as a signed decimal string.",tickUpper:"Provide the upper liquidity tick as a signed decimal string.",tickSpacing:"Provide the target pool tick spacing as a signed decimal string.",fee:"Provide the target pool fee in pips (10000 = 1%).",impactBps:"Provide the vault impact limit in basis points (100 = 1%).",rewardBps:"Provide the zap caller bounty rate in basis points (100 = 1%).",protocolShareBps:"Provide the protocol share in basis points (100 = 1%).",windowBlocks:"Provide the vault impact window in blocks.",windowScope:"Match the existing vault impact-window scope as a decimal uint8 string.",buyTakePips:"Provide the buy quote take in pips (10000 = 1%).",sellTakePips:"Provide the sell quote take in pips (10000 = 1%).",mintGasLimit:"Provide the gas limit for each reward mint."},Je=(e,t)=>e==="mode"?t==="market-guard"?"Choose 1 to refuse or 2 to apply a surcharge.":t==="swap-reward-mint"?"Choose 0 for trader mode or 1 for fixed recipient mode.":"Choose 0 to send bought subject to the sink or 1 for permanent target liquidity.":e==="flags"?t==="market-guard"?"Choose 0 for subject in quote or 1 for quote in subject feed direction.":"Provide schedule flags as a decimal string (0 or 1), controlling weekday surcharges outside calendar coverage.":e==="cap"?"Set the managed LP surcharge cap in pips (10000 = 1%).":Ze[e]??je[e],z=(e,t)=>({type:"object",additionalProperties:!1,required:e,properties:Object.fromEntries(e.map(r=>[r,{...Ye.has(r)?F:["targetId","poolId","accountInitCodeHash"].includes(r)?{type:"string",pattern:"^0x[0-9a-fA-F]{64}$"}:r==="quoteIsCurrency0"?{type:"boolean"}:["tickLower","tickUpper","tickSpacing"].includes(r)?{type:"string",pattern:"^(0|-?[1-9][0-9]*)$"}:S,description:Je(r,t)}]))}),Ne=e=>je[e]??{owner:"Provide the advisory owner address.",keeper:"Provide the admitted keeper address.",vault:"Provide the source vault address.",minter:"Provide the reward minter address."}[e],Xe={"market-guard":["feed","mode","flags","bandBps","rampBps","staleness","surchargePips","minDepth"],"market-hours-fee":["regularPips","preMarketPips","afterHoursPips","overnightPips","closedPips","openRampSeconds","closeRampSeconds","flags"],"managed-fee":["cap","surcharge","premium0","premium1","maxStep","minInterval","maxTtl"],"swap-reward-mint":He},P={"swap-reward-mint":{thirdPartyPayees:{type:"array",minItems:1,maxItems:2,uniqueItems:!0,items:F,description:"List up to two distinct third-party creator or fixed reward payee addresses; omit when all payees are the launching wallet."}}};if(Object.keys(P["swap-reward-mint"]).join()!==Re.optional.join())throw new Error("swap-reward-mint optional fields differ from its validator");var et=e=>({type:"object",additionalProperties:!1,properties:{id:{const:e,description:"Select this Hook Block by its ID."},...Object.fromEntries(A[e].map(t=>[t,{...t==="terms"?z(Xe[e],e):t==="route"?z(N,"vault"):t==="routes"?{type:"array",minItems:1,maxItems:4,items:z(N,"vault")}:t==="feeders"?{type:"array",minItems:1,maxItems:4,items:F}:["owner","keeper","vault","minter","factory"].includes(t)?F:S,description:Ne(t)}])),...Object.hasOwn(P,e)?P[e]:{}},required:["id",...A[e]]}),$e=(e,t)=>({type:"object",description:We[e],additionalProperties:!1,properties:{id:{const:e,description:"Select this Hook Block by its ID."},...Object.fromEntries(t.map(r=>[r,{...r==="recipient"?{type:"string",pattern:"^0x[0-9a-fA-F]{40}$"}:S,description:r==="cap"&&e==="wallet-cap"?"Set the cumulative wallet buy cap in subject token base units, using the subject token decimals.":r==="floor"?e==="storm-fee"?"Set the storm fee floor in 500-pip steps.":"Set the exit-clock floor in ten-basis-point steps.":r==="buy"||r==="sell"?`Set the ${r} quote charge in 1000-pip steps (0.1%) for ${e==="holder-pot"?"the holder pot":"the quote-claim payee"}.`:Ne(r)}]))},required:["id",...t]}),zt={type:"array",maxItems:20,items:{oneOf:[$e("anti-snipe",["guardEndBlock","taxPips","floorPips","decaySeconds","maxBuyQuoteAmount"]),...Object.entries(M).filter(([e])=>e!=="anti-snipe").map(([e,t])=>$e(e,t)),...v.map(et),{type:"object",additionalProperties:!1,properties:{id:{type:"string",description:"Select the Hook Block by its ID.",enum:Ke.filter(e=>!De.includes(e)&&!v.includes(e))}},required:["id"]}]},description:"Explicit Hook Blocks. Unsupported codecs are refused. Arb recapture and agent-gate use their dedicated launch fields. Empty means none beyond those fields."};function tt(e){let t=B(e);if(!Array.isArray(t.blocks)||!t.blocks.length||t.blocks.length>64)throw new d("Hookr block list is unavailable or incomplete; no empty catalog is inferred.");let r=new Set;return t.blocks.map(o=>{let s=B(o);if(typeof s.id!="string"||!/^[a-z][a-z-]{0,63}$/.test(s.id)||r.has(s.id)||typeof s.live!="boolean"||s.openToNewPools!==void 0&&typeof s.openToNewPools!="boolean")throw new d("Hookr block list is malformed or duplicated.");r.add(s.id);let a=s.live&&s.openToNewPools!==!1,n=a&&(De.includes(s.id)||v.includes(s.id));return{id:s.id,...s.address===void 0?{}:{address:D(s.address)},live:s.live,openToNewPools:a,supported:n,refusal:n?null:a?Object.hasOwn(Ie,s.id)?Ie[s.id]:`Hook Block ${s.id} needs a verified field codec and payment terms before Oak can launch it. Use its dedicated launch fields when available.`:`Hook Block ${s.id} is not open to new pools.`}})}async function _(e){return tt(await K(e,"hookr_blocks",{}))}function ot(e){if(e===void 0)return[];if(!Array.isArray(e)||e.length>20)throw new d("Choose at most twenty distinct Hook Blocks.");let t=new Set;return e.map(r=>{let o=B(r);if(typeof o.id!="string"||t.has(o.id))throw new d("Choose distinct Hook Block IDs.");if(t.add(o.id),Object.hasOwn(A,o.id)){let a=A[o.id],n=Object.hasOwn(P,o.id)?Object.keys(P[o.id]):[];return H(o,["id",...a,...n],["id",...a]),o}let s=Object.hasOwn(M,o.id)?M[o.id]:[];H(o,["id",...s],["id",...s]);for(let a of s)a==="recipient"?D(o[a]):u(o[a],["maxBuyQuoteAmount","cap"].includes(a)?128:a==="guardEndBlock"?40:24);return o})}function ze(e){if((e.length-2)/2!==512)throw new d("Hookr Rules terms must contain exactly sixteen words.");let[t]=Ue(T,e);if(Q(T,[t]).toLowerCase()!==e.toLowerCase())throw new d("Hookr Rules terms are not canonical.");return t}function rt(e,t){let r=u(t.guardEndBlock,40),o=Number(u(t.taxPips,24)),s=Number(u(t.floorPips,24)),a=Number(u(t.decaySeconds,16)),n=u(t.maxBuyQuoteAmount,128);if(!r||!o||o>597e3||!n||(a===0?s!==0:s>=o)||a>3600)throw new d("Anti-Snipe needs a future parent-block guard, positive buy cap/tax, a lower floor when decaying, and at most 3600 decay seconds.");return{...e,guardEndBlock:Number(r),snipeTaxPips:o,snipeFloorPips:s,snipeDecaySeconds:a,maxBuyQuoteAmount:n}}function st(e,t){let r=Number(u(t.maxFeePips,24)),o=Number(u(t.sensitivity,16));if(r<=3e3||r>6e5||o<1||o>10)throw new d("Dynamic fees need maxFeePips above 3000 and at most 600000, with sensitivity 1 to 10.");return{...e,maxFeePips:r,dynamicFeeSens:o}}function nt(e,t){let r=Number(u(t.burnBps,16));if(r<1||r>1e3)throw new d("Auto Burn needs burnBps between 1 and 1000.");return{...e,burnBps:r}}function it(e,t){let r=Number(u(t.lpBps,16));if(r<1||r>1e3)throw new d("LP Rewards needs lpBps between 1 and 1000.");if(e.lpBps&&e.lpBps!==r)throw new d("LP Rewards conflicts with lpRewardsBps. Choose the same rate in both fields.");return{...e,lpBps:r}}async function at(e,t,r,o,s){if(r.some(i=>v.includes(i.id)))throw new d("The agent gate and an advisory Hook Block cannot share the one advisory slot. Use an explicit open launch profile.");let a=s??(r.length?await _(e):[]),n=t,p=[...r.filter(i=>i.id==="anti-snipe"),...r.filter(i=>i.id!=="anti-snipe")];for(let i of p){let c=a.find(l=>l.id===i.id);if(!c||!c.openToNewPools)throw new d(`Hook Block ${String(i.id)} is not open to new pools.`);if(!c.supported)throw new d(c.refusal);switch(i.id){case"anti-snipe":n=rt(n,i);break;case"dynamic-fees":n=st(n,i);break;case"auto-burn":n=nt(n,i);break;case"lp-rewards":n=it(n,i);break;case"buy-sell-block":n=re(n,i);break;case"wallet-cap":n=ne(n,i);break;case"exit-clock":{let l=Object.fromEntries(Object.entries(i).filter(([m])=>m!=="id"));n=ae(n,l);break}case"storm-fee":n=ce(n,i);break;case"swap-cut":n=ue(n,i);break;case"sandwich-guard":n=me(n,i);break;case"holder-pot":n=Fe(n,i);break}}if(R(n),r.some(i=>Object.hasOwn(Me,String(i.id)))&&await gt(e,n,o),n.burnBps+n.lpBps>1e3)throw new d("Auto Burn plus LP Rewards must not exceed 1000 bps.");return ze(Q(T,[n]))}function dt(e,t=3e3,r=0n){R(e);let o=Ce(e),s=BigInt(e.protocolShareBps),a=g=>(BigInt(g)*s+99n)/100n,n=a(e.lpBps),p=a(e.burnBps),i=BigInt(e.lpBps)*100n-n,c=BigInt(e.maxFeePips-t),l=BigInt(e.snipeTaxPips),m=BigInt(t)+i+c+l+o.lp,E=n+p+c*s/10000n+l*s/10000n,x=e.lpBps!==0||e.burnBps!==0||c*s>=10000n||l*s>=10000n;return{maxLpFeePips:m,maxQuoteTakePips:(E>(x?0n:r)?E:x?0n:r)+o.quote,maxSubjectTakeBps:(BigInt(e.burnBps)*100n-p)/100n}}var b=e=>`${Oe(BigInt(e),4)}%`;function ct(e,t){return`Anti-Snipe: buys before parent block ${e.guardEndBlock} pay up to ${e.snipeTaxPips} surcharge pips (${b(e.snipeTaxPips)}), decaying to ${e.snipeFloorPips} pips (${b(e.snipeFloorPips)}) over ${e.snipeDecaySeconds} seconds; buy cap ${e.maxBuyQuoteAmount} quote base units. Hookr ${t} gets floor(charged pips * ${e.protocolShareBps}/10000) in quote; in-range LPs get the remaining LP fee. Principal locked until parent block ${e.guardEndBlock}.`}function pt(e,t){return`Dynamic fees: maximum ${e.maxFeePips} pips (${b(e.maxFeePips)}), sensitivity ${e.dynamicFeeSens}; Hookr ${t} gets floor(dynamic surcharge pips * ${e.protocolShareBps}/10000) in quote; in-range LPs get the remaining LP fee. Default tempo 30/120 seconds, carry 7500 bps, move 200 ticks; minimum dynamic liquidity is clamp(floor(launch liquidity/100), 1, 2^96-1).`}function ut(e,t){let r=(BigInt(e.burnBps)*BigInt(e.protocolShareBps)+99n)/100n;return`Auto Burn: configured ${e.burnBps} bps; subject output burn ${(BigInt(e.burnBps)*100n-r)/100n} bps after Hookr's slice. Hookr ${t} gets ${r} pips (${b(r)}) of gross buyer spend in quote; burned subject goes to 0x000000000000000000000000000000000000dEaD.`}function lt(e,t,r){let o=(BigInt(e.lpBps)*BigInt(e.protocolShareBps)+99n)/100n;return`LP Rewards: buys pay ${e.lpBps*100} gross pips (${b(e.lpBps*100)}); Hookr ${t} gets ${o} quote pips (${b(o)}), in-range LPs get ${BigInt(e.lpBps)*100n-o} LP fee pips (${b(BigInt(e.lpBps)*100n-o)}); creator royalty 0${e.integrator===Le?`; Oak ${e.integrator} gets ${r===void 0?"the share of Hookr's part that Hookr lists for it":`${Oe(r,2)}% of Hookr's part`}`:`, integrator ${e.integrator===qe?"0":e.integrator}`}.`}function Mt(e,t,r){let o=ze(e);if(R(o),o.integrator!==qe&&o.integrator!==Le||o.royaltyBps||o.potBps)throw new d("Hookr payment terms include an unsupported integrator, royalty or pot.");return[o.guardEndBlock?ct(o,t):"",o.dynamicFeeSens?pt(o,t):"",o.burnBps?ut(o,t):"",o.lpBps?lt(o,t,r):"",o.potEveryNBuys&1<<23?se(o):"",o.potEveryNBuys&1<<19?ie(o):"",o.potEveryNBuys&1<<20?de(o,t):"",o.potEveryNBuys&1<<22?pe(o,t):"",o.potEveryNBuys&1<<21?Ee(o,t):"",o.potEveryNBuys&16383&&!(o.potEveryNBuys&1<<21)?le(o,t):"",o.potEveryNBuys&1<<17?he(o,t):""].filter(Boolean)}function Qt(e){return[{name:"hookr_blocks",inputSchema:{type:"object",additionalProperties:!1,properties:{}},execute:async t=>(H(t,[]),{blocks:await _(e)})}]}var mt="0x4ff3630dd3d4ca59d00c08a7c8be527f6b90ffd700a7cc6a36a837de2ee4565e",ht="0x53a44e55150d75ad35c98d9b48c13a1ab6f4be9657d74083149e7d992e45e46f",Me={"swap-cut":"0x9394881A6Fe570adEC4480471B4D52652d263878","exit-clock":"0x2b6aB976d05Dcc7Cad53bF9324Fe892511036348","storm-fee":"0xD577087cbf9bEC0Ca0392efD8A83C3fE6A09Bd1f","wallet-cap":"0xfe5c29D2d6B7aC383A63291a771197e4D83E1d9c","buy-sell-block":"0xa64be3B5eC9B7310CBd3F77736ca5D6Fa81C5BCb","holder-pot":"0x740b2Da80eBB44613C2b44f380D55ECBECbFf11f","sandwich-guard":"0xa214e747d1a8E767F88ed2170be62E22ED79a269"};async function gt(e,t,r){let o=e.clientFor(4663),s=r??await q(o);await O(o,s.number,[f.rulesV1,f.launcherV1]);let a=[t.potEveryNBuys&16383?"swap-cut":"",...[[21,"holder-pot"],[20,"exit-clock"],[22,"storm-fee"],[19,"wallet-cap"],[23,"buy-sell-block"],[17,"sandwich-guard"]].filter(([n])=>t.potEveryNBuys&1<<Number(n)).map(([,n])=>String(n))].filter(Boolean);for(let n of a){let p=Me[n],i=B(await W(o,Y,V("registry"),"admission",[f.rulesV1,p],s.number)),c=B(i.caps);if(i.implementation!==p||w(i.kind,8)!==0n||i.codeHash!==mt||i.schemaHash!==ht||w(i.gasLimit,32)===0n||w(i.phaseMask,8)!==1n||j(i.failOpen)||j(i.feeOnly)||w(c.maxLpFeePips,24)||w(c.maxQuoteTakePips,24)||w(c.maxSubjectTakeBps,16))throw new d(`Hook Block ${n} is not admitted on the pinned core with its reviewed key terms.`)}if(t.potEveryNBuys&1<<23){let n=await ee(o,s),p=t.potMinBuyQuote>>85n&511n,i=t.potMinBuyQuote>>94n&7n;if(BigInt(t.guardEndBlock)-n-4n<(p>i?p:i))throw new d("The parent-block guard must cover the complete Buy/Sell Block windows plus four spare parent blocks.")}await L(o,s)}async function _t(e,t,r,o,s,a,n=0n,p){let i=ot(t.hookBlocks),c=oe(t.launchProfile,t.agentGate,i),l=i.filter($=>!v.includes($.id)),m=e.clientFor(4663);if((await q(m,s.number)).hash!==s.hash)throw new d("Hookr launch block changed before block validation.");await O(m,s.number,[f.rootV1,f.rulesV1,f.launcherV1]);let x=p??(i.length?await _(e):[]),g=await at(e,r,l,s,x),U=Q(T,[g]),G=dt(g,3e3,n);if(!c.advisory)return{kind:c.kind,rules:g,blockTerms:U,advisory:null,bounds:G,summaryLines:[]};let y=c.advisory,C=x.find($=>$.id===y.id);if(!C?.openToNewPools)throw new d(`Hook Block ${String(y.id)} is not open to new pools.`);let h=await yt(m,s.number,y,o);y.id==="market-guard"&&!(g.potEveryNBuys&te)&&(h.phases=3);let I="requiredCaps"in h?h.requiredCaps:h.bounds,k=await Be(m,s.number,h.descriptor,h.phases,I);if(C.address!==void 0&&C.address!==k.address)throw new d("Hookr catalog advisory address differs from the source-verified selection.");let Qe=y.id==="zap-source"?a.maxQuoteTakePips+I.maxQuoteTakePips:y.id==="swap-reward-mint"?kt(g,n)+I.maxQuoteTakePips:0n,_e=ve(G,k.caps,a,Qe);return await L(m,s),{kind:c.kind,rules:g,blockTerms:U,advisory:{...k,data:h.data,id:String(y.id),summary:h.summary},bounds:_e,summaryLines:[`No agent identity gate. ${y.id==="zap-target"?"Only the frozen feeder vaults may buy; any wallet may sell.":"Wallets need no agent identity; the selected advisory can impose its own decoded restrictions."} ${h.summary}`,`Advisory ${k.address}, phases ${k.phases}, fail closed, gas ${k.gasLimit}; full admitted reservation ${k.caps.maxLpFeePips} LP pips and ${k.caps.maxQuoteTakePips} quote pips.`]}}async function yt(e,t,r,o){let s=Object.fromEntries(Object.entries(r).filter(([n])=>n!=="id")),a;switch(r.id){case"market-guard":a=await ye(e,t,s,o);break;case"market-hours-fee":a=await fe(e,t,s);break;case"managed-fee":a=await be(e,t,s);break;case"zap-source":a=await J(e,t,s,o);break;case"zap-target":a=await Pe(e,t,s,o);break;case"swap-reward-mint":a=await Te(e,t,s,o);break;default:throw new d("Unknown Hookr advisory profile.")}return a}function kt(e,t){let r=BigInt(e.protocolShareBps),o=(BigInt(e.lpBps)*r+99n)/100n,s=(BigInt(e.lpBps)*100n-o)*BigInt(e.royaltyBps)/10000n,a=o+s+(BigInt(e.burnBps)*r+99n)/100n+BigInt(e.maxFeePips-3e3+e.snipeTaxPips)*r/10000n;return a>s+t?a:s+t}export{T as a,Le as b,Ke as c,Ve as d,A as e,zt as f,tt as g,_ as h,ot as i,ze as j,rt as k,st as l,nt as m,it as n,at as o,dt as p,ct as q,pt as r,ut as s,lt as t,Mt as u,Qt as v,_t as w,yt as x,kt as y};
|