@oakagentkit/core 0.2.1 → 0.2.3
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 +93 -0
- package/build/dist/api/addresses.js +1 -1
- package/build/dist/api/chain.js +1 -1
- package/build/dist/api/history.js +1 -1
- package/build/dist/api/identity-link.js +1 -1
- package/build/dist/api/metadata.js +1 -1
- package/build/dist/api/modules/beefy/boosts.js +1 -1
- package/build/dist/api/modules/beefy/clm.js +1 -1
- package/build/dist/api/modules/beefy/guard.js +1 -1
- package/build/dist/api/modules/beefy/index.js +1 -1
- package/build/dist/api/modules/beefy/liquidity.js +1 -1
- package/build/dist/api/modules/beefy/management.js +1 -1
- package/build/dist/api/modules/beefy/vaults.js +1 -1
- package/build/dist/api/modules/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/erc8004/common.js +1 -1
- package/build/dist/api/modules/erc8004/domain.js +1 -1
- package/build/dist/api/modules/erc8004/index.js +1 -1
- package/build/dist/api/modules/erc8004/management.js +1 -1
- package/build/dist/api/modules/erc8004/reputation.js +1 -1
- package/build/dist/api/modules/erc8004/services.js +1 -1
- package/build/dist/api/modules/erc8004/validation.js +1 -1
- package/build/dist/api/modules/grove/index.js +1 -1
- package/build/dist/api/modules/heyresearch/backoff.d.ts +6 -0
- package/build/dist/api/modules/heyresearch/backoff.js +1 -0
- package/build/dist/api/modules/heyresearch/builder-feed.d.ts +62 -0
- package/build/dist/api/modules/heyresearch/builder-feed.js +1 -0
- package/build/dist/api/modules/heyresearch/index.d.ts +3 -0
- package/build/dist/api/modules/heyresearch/index.js +1 -1
- package/build/dist/api/modules/heyresearch/proof-reads.d.ts +7 -0
- package/build/dist/api/modules/heyresearch/proof-reads.js +1 -0
- package/build/dist/api/modules/heyresearch/public-reads.d.ts +1 -0
- package/build/dist/api/modules/heyresearch/public-reads.js +1 -1
- package/build/dist/api/modules/heyresearch/scan.d.ts +31 -0
- package/build/dist/api/modules/heyresearch/scan.js +1 -0
- package/build/dist/api/modules/heyresearch/status-labels.d.ts +5 -0
- package/build/dist/api/modules/heyresearch/status-labels.js +1 -0
- package/build/dist/api/modules/heyresearch/token-facts.d.ts +123 -0
- package/build/dist/api/modules/heyresearch/token-facts.js +1 -0
- 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 +1 -1
- package/build/dist/api/modules/hookr/actions.js +1 -1
- package/build/dist/api/modules/hookr/addons.js +1 -1
- package/build/dist/api/modules/hookr/agent-gate.d.ts +63 -0
- package/build/dist/api/modules/hookr/agent-gate.js +1 -0
- package/build/dist/api/modules/hookr/contracts.js +1 -1
- package/build/dist/api/modules/hookr/create-cancel.js +1 -1
- package/build/dist/api/modules/hookr/discovery.js +1 -1
- package/build/dist/api/modules/hookr/fill-bounty.js +1 -1
- package/build/dist/api/modules/hookr/index.d.ts +1 -0
- package/build/dist/api/modules/hookr/index.js +1 -1
- package/build/dist/api/modules/hookr/launch-options.d.ts +119 -0
- package/build/dist/api/modules/hookr/launch-options.js +1 -0
- package/build/dist/api/modules/hookr/launch-profile.d.ts +5 -0
- package/build/dist/api/modules/hookr/launch-profile.js +1 -0
- package/build/dist/api/modules/hookr/launch-receipt.d.ts +144 -0
- package/build/dist/api/modules/hookr/launch-receipt.js +1 -0
- package/build/dist/api/modules/hookr/launch.d.ts +58 -0
- package/build/dist/api/modules/hookr/launch.js +1 -0
- package/build/dist/api/modules/hookr/liquidity.d.ts +48 -0
- package/build/dist/api/modules/hookr/liquidity.js +1 -0
- package/build/dist/api/modules/hookr/lp-positions.d.ts +2 -0
- package/build/dist/api/modules/hookr/lp-positions.js +1 -0
- package/build/dist/api/modules/hookr/lp-reads.d.ts +52 -0
- package/build/dist/api/modules/hookr/lp-reads.js +1 -0
- package/build/dist/api/modules/hookr/lp-receipt.d.ts +136 -0
- package/build/dist/api/modules/hookr/lp-receipt.js +1 -0
- package/build/dist/api/modules/hookr/lp-state.d.ts +33 -0
- package/build/dist/api/modules/hookr/lp-state.js +1 -0
- package/build/dist/api/modules/hookr/pins.d.ts +43 -0
- package/build/dist/api/modules/hookr/pins.js +1 -0
- package/build/dist/api/modules/hookr/public-reads.js +1 -1
- package/build/dist/api/modules/hookr/read-utils.d.ts +59 -0
- package/build/dist/api/modules/hookr/read-utils.js +1 -0
- package/build/dist/api/modules/hookr/relay.js +1 -1
- package/build/dist/api/modules/hookr/revenue.js +1 -1
- package/build/dist/api/modules/kyberswap/index.js +1 -1
- package/build/dist/api/modules/kyberswap/source-pools.js +1 -1
- package/build/dist/api/modules/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/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/index.js +1 -1
- package/build/dist/api/modules/priors/integration.js +1 -1
- package/build/dist/api/modules/priors/market.js +1 -1
- package/build/dist/api/modules/priors/pt.js +1 -1
- package/build/dist/api/modules/priors/savings-exit.js +1 -1
- package/build/dist/api/modules/priors/starter-line.js +1 -1
- package/build/dist/api/modules/priors/stock-swap.js +1 -1
- package/build/dist/api/modules/relay/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/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/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.d.ts +5 -0
- package/build/dist/api/modules/wormhole/index.js +1 -0
- package/build/dist/api/modules/wormhole/license.d.ts +2 -0
- package/build/dist/api/modules/wormhole/license.js +1 -0
- package/build/dist/api/modules/wormhole/quotetext.d.ts +36 -0
- package/build/dist/api/modules/wormhole/quotetext.js +1 -0
- package/build/dist/api/modules/wormhole/scan-text.d.ts +40 -0
- package/build/dist/api/modules/wormhole/scan-text.js +1 -0
- package/build/dist/api/modules/wormhole/token-check.d.ts +54 -0
- package/build/dist/api/modules/wormhole/token-check.js +1 -0
- package/build/dist/api/positions.js +1 -1
- package/build/dist/api/pricenote.js +1 -1
- package/build/dist/api/prices.js +1 -1
- package/build/dist/api/pricing.js +1 -1
- package/build/dist/api/rpc.js +1 -1
- package/build/dist/api/send.js +1 -1
- package/build/dist/api/signing-registry.js +1 -1
- package/build/dist/api/signing.js +1 -1
- package/build/dist/api/simulate.js +1 -1
- package/build/dist/api/swap.js +1 -1
- package/build/dist/api/tokens.js +1 -1
- package/build/dist/api/tool-policy.js +1 -1
- package/build/dist/api/types.d.ts +7 -0
- package/build/dist/chunks/{QHHZDXRG.js → 2FSX7MMR.js} +1 -1
- package/build/dist/chunks/{RTBOMWCB.js → 2LM7U4S7.js} +1 -1
- package/build/dist/chunks/{BBVKWG65.js → 2MSQ6JII.js} +1 -1
- package/build/dist/chunks/{T6MTTMLQ.js → 2UU5TBBB.js} +1 -1
- package/build/dist/chunks/{OW7GOYKA.js → 2W46IRX6.js} +1 -1
- package/build/dist/chunks/{6LLOTPH2.js → 3EFV4FQF.js} +1 -1
- package/build/dist/chunks/{IAXKPME3.js → 3NDVXEBR.js} +1 -1
- package/build/dist/chunks/3SC5UI35.js +1 -0
- package/build/dist/chunks/{TCS3ICNE.js → 3WBDHUV2.js} +1 -1
- package/build/dist/chunks/{UPPYXY74.js → 4AKIXLXH.js} +1 -1
- package/build/dist/chunks/{ZGXNTWYG.js → 4GHVIBL5.js} +1 -1
- package/build/dist/chunks/{NHCRJC5X.js → 4KQZTPMS.js} +1 -1
- package/build/dist/chunks/{N77ANGBT.js → 4X2JOQ2L.js} +1 -1
- package/build/dist/chunks/{ZPM2MFXZ.js → 52DHGSG4.js} +1 -1
- package/build/dist/chunks/{2CS3M32D.js → 57HAXNQV.js} +1 -1
- package/build/dist/chunks/5IIR3GIN.js +1 -0
- package/build/dist/chunks/{CAU44UWP.js → 5O5ZE3ZV.js} +1 -1
- package/build/dist/chunks/5OEHZJ6X.js +1 -0
- package/build/dist/chunks/{CBA776XQ.js → 5VHH5PW3.js} +1 -1
- package/build/dist/chunks/{6HV5BR7P.js → 6AWTAE4Q.js} +1 -1
- package/build/dist/chunks/{JRVTSGAT.js → 6UPPUHCL.js} +1 -1
- package/build/dist/chunks/{MEMVFR7Z.js → 6ZYLNB2B.js} +1 -1
- package/build/dist/chunks/7XLEYOZH.js +1 -0
- package/build/dist/chunks/{Q4RZQCDS.js → AAGDMH54.js} +1 -1
- package/build/dist/chunks/ACN2BFMA.js +1 -0
- package/build/dist/chunks/{L24EOVLT.js → AJP5LDM2.js} +1 -1
- package/build/dist/chunks/{F2YH72GF.js → ALK6NKFP.js} +1 -1
- package/build/dist/chunks/{EC5W3UZD.js → AMICUXS6.js} +1 -1
- package/build/dist/chunks/{BEPSWFJX.js → ASDKY5NX.js} +1 -1
- package/build/dist/chunks/{5LQBHXFA.js → BX7XQANB.js} +1 -1
- package/build/dist/chunks/{NUTHT4FE.js → CE7D6MUS.js} +1 -1
- package/build/dist/chunks/{QNPEKNWM.js → CEIPDEXZ.js} +1 -1
- package/build/dist/chunks/{HFQS5344.js → CQCVFRQ5.js} +1 -1
- package/build/dist/chunks/{OJLMF5AR.js → CUNQ5RG5.js} +1 -1
- package/build/dist/chunks/{IWALIX7Q.js → CXLEQCP3.js} +1 -1
- package/build/dist/chunks/{VJ3W2V3B.js → CY75R4FK.js} +1 -1
- package/build/dist/chunks/{65QFM4JU.js → DCTUYDWF.js} +1 -1
- package/build/dist/chunks/{N37ZLNCT.js → DRWWPBOQ.js} +1 -1
- package/build/dist/chunks/{7B5UH2VS.js → DZGEQBO7.js} +1 -1
- package/build/dist/chunks/{RFJCG4NA.js → E7R3J4H7.js} +1 -1
- package/build/dist/chunks/{7T4BYFD4.js → EGUMOD3A.js} +1 -1
- package/build/dist/chunks/ELZNT5Q3.js +1 -0
- package/build/dist/chunks/{IUETZH6I.js → EXRKBBX2.js} +1 -1
- package/build/dist/chunks/{K7HIKXNT.js → FBSUTF3B.js} +1 -1
- package/build/dist/chunks/{LFN3OODW.js → FUXT7GRK.js} +1 -1
- package/build/dist/chunks/{7US6PD56.js → G3MHDTGT.js} +1 -1
- package/build/dist/chunks/G6HCV67X.js +1 -0
- package/build/dist/chunks/GCWA4Z3W.js +1 -0
- package/build/dist/chunks/{HNMOB76J.js → GGUEKSR4.js} +1 -1
- package/build/dist/chunks/{GZ5TW3WB.js → GIV5JMTE.js} +1 -1
- package/build/dist/chunks/{OMTCWXQR.js → GJY3P6OG.js} +1 -1
- package/build/dist/chunks/HOEQVPY7.js +1 -0
- package/build/dist/chunks/{3R3C3CU5.js → IBXYIN7Q.js} +1 -1
- package/build/dist/chunks/{SXX52Y27.js → IUE6RASI.js} +1 -1
- package/build/dist/chunks/{AYM5L6L7.js → J3GFCBZZ.js} +1 -1
- package/build/dist/chunks/{T3MGNKA6.js → JPOYTTTW.js} +1 -1
- package/build/dist/chunks/{AZGMF26W.js → JST5JGAP.js} +1 -1
- package/build/dist/chunks/{FBQWTWPT.js → JWCOXLYA.js} +1 -1
- package/build/dist/chunks/{G7UKNO2I.js → KHJFXJBU.js} +1 -1
- package/build/dist/chunks/{HQVC6X3T.js → KSZMMNXK.js} +1 -1
- package/build/dist/chunks/{O7PQDUVT.js → L3ZM77SJ.js} +1 -1
- package/build/dist/chunks/{QRUC7EFE.js → L62M7LOB.js} +1 -1
- package/build/dist/chunks/{22S4SFD5.js → L7YBCMZU.js} +1 -1
- package/build/dist/chunks/LKJBMHCE.js +1 -0
- package/build/dist/chunks/{FKAA7VUR.js → LLM5WDM3.js} +1 -1
- package/build/dist/chunks/{H6ED3RHF.js → LMVB3B6T.js} +1 -1
- package/build/dist/chunks/{UIIJWIR6.js → LQGPMOD2.js} +1 -1
- package/build/dist/chunks/{WLACEU2Y.js → LQUDJCAR.js} +1 -1
- package/build/dist/chunks/LT5P6PZW.js +1 -0
- package/build/dist/chunks/M7U3A4EH.js +3 -0
- package/build/dist/chunks/MKQVS3IO.js +1 -0
- package/build/dist/chunks/{5XFXH2JT.js → NATG6YA6.js} +1 -1
- package/build/dist/chunks/{O47JXRXN.js → NAYRD43N.js} +1 -1
- package/build/dist/chunks/{6L6DSMCU.js → NMYGNJIJ.js} +1 -1
- package/build/dist/chunks/NRBIXV7V.js +1 -0
- package/build/dist/chunks/{D6VP3N27.js → NSOEDRBU.js} +1 -1
- package/build/dist/chunks/{HL2MLC3O.js → NU4K3TEZ.js} +1 -1
- package/build/dist/chunks/NWSPC3NH.js +1 -0
- package/build/dist/chunks/O5IVZHHP.js +1 -0
- package/build/dist/chunks/{I7NUTSSX.js → OE3CLZHR.js} +1 -1
- package/build/dist/chunks/{2NA6JLEC.js → OQVZVR2S.js} +1 -1
- package/build/dist/chunks/{D3OWLDVB.js → OVK4EEOD.js} +1 -1
- package/build/dist/chunks/{Q2VMH2LB.js → PARWLWXW.js} +1 -1
- package/build/dist/chunks/{NCEJZWGX.js → PEA32CWB.js} +1 -1
- package/build/dist/chunks/{DHXVYHT4.js → PTAWEHKB.js} +1 -1
- package/build/dist/chunks/{DVKDWXEJ.js → PWBL4WKB.js} +1 -1
- package/build/dist/chunks/{PR2QED25.js → PZHR4ITH.js} +1 -1
- package/build/dist/chunks/{OG5HRQU4.js → QRDDKA4I.js} +1 -1
- package/build/dist/chunks/{YR3QJVJQ.js → QXNPPCOU.js} +1 -1
- package/build/dist/chunks/{6NR7SVRO.js → QYYFRAWY.js} +1 -1
- package/build/dist/chunks/{QR7ALOR4.js → R53P2K3C.js} +1 -1
- package/build/dist/chunks/{5RKWSFD2.js → R7FXNZRM.js} +1 -1
- package/build/dist/chunks/{CCEWSOBT.js → R7QPJQP6.js} +1 -1
- package/build/dist/chunks/{SLSPWXR6.js → R7SXC74O.js} +1 -1
- package/build/dist/chunks/{IHGVCPVA.js → RAKUK5VR.js} +1 -1
- package/build/dist/chunks/{7LDAJ6BM.js → S3HNPTXA.js} +1 -1
- package/build/dist/chunks/{WIDTTGSH.js → SJPM5ST4.js} +1 -1
- package/build/dist/chunks/{QYHJWU5T.js → SJPYXNOK.js} +1 -1
- package/build/dist/chunks/{VY3P34PY.js → SKQGLGES.js} +1 -1
- package/build/dist/chunks/{ZT67OMLW.js → SOYQOE5P.js} +1 -1
- package/build/dist/chunks/{GUBB5P6V.js → SQZRVIVF.js} +1 -1
- package/build/dist/chunks/{E24S22BZ.js → SSTROLQM.js} +1 -1
- package/build/dist/chunks/{DGGOO4RN.js → SXAIXD56.js} +1 -1
- package/build/dist/chunks/{D4WURN33.js → SXX3VTBP.js} +1 -1
- package/build/dist/chunks/{UXG67LH3.js → TCPPYBGQ.js} +1 -1
- package/build/dist/chunks/{67TJOOBI.js → TLJPVYRJ.js} +1 -1
- package/build/dist/chunks/{ULJ6E4HP.js → TMGWXDCZ.js} +1 -1
- package/build/dist/chunks/TNLHMDWL.js +1 -0
- package/build/dist/chunks/{NMFVXBTL.js → TNSKEHPC.js} +1 -1
- package/build/dist/chunks/TPDOUL4N.js +1 -0
- package/build/dist/chunks/{C2FEXLMA.js → TQL7UDFL.js} +1 -1
- package/build/dist/chunks/{QXFJZGVB.js → TWCSCRFS.js} +1 -1
- package/build/dist/chunks/{2EDXKJ3B.js → TWSTOFN3.js} +1 -1
- package/build/dist/chunks/{X6G4BD35.js → U3F6DDML.js} +1 -1
- package/build/dist/chunks/{XGUKLFBU.js → UFS2RVEZ.js} +1 -1
- package/build/dist/chunks/{RM5W63LO.js → UNZRE3YU.js} +1 -1
- package/build/dist/chunks/{GECX5U3F.js → USSOVTD5.js} +1 -1
- package/build/dist/chunks/V2OOOV6B.js +1 -0
- package/build/dist/chunks/{IRWEY7TQ.js → V5LTA42G.js} +1 -1
- package/build/dist/chunks/{TAI63P6E.js → VC2RCYQE.js} +1 -1
- package/build/dist/chunks/VCLPOU7T.js +1 -0
- package/build/dist/chunks/{BG4S6MSN.js → VFKNXQXI.js} +1 -1
- package/build/dist/chunks/{3ZVGHC6S.js → VFSRRDLY.js} +1 -1
- package/build/dist/chunks/{XW7RH7YY.js → VVEUJ36E.js} +1 -1
- package/build/dist/chunks/{5EHQM6DM.js → WQ6H62DM.js} +1 -1
- package/build/dist/chunks/{TDN3C4IG.js → WQQJ7UPJ.js} +1 -1
- package/build/dist/chunks/{F3TJCOVV.js → WTSMPDT5.js} +1 -1
- package/build/dist/chunks/{BYXBS45D.js → WVXW6VL3.js} +1 -1
- package/build/dist/chunks/WWFOYZT2.js +1 -0
- package/build/dist/chunks/WWNAGOCD.js +1 -0
- package/build/dist/chunks/X2NJSQUY.js +203 -0
- package/build/dist/chunks/{C3ZZSGSP.js → XQUPZ3GU.js} +1 -1
- package/build/dist/chunks/XQXLFF7Y.js +1 -0
- package/build/dist/chunks/XUYHMOHS.js +1 -0
- package/build/dist/chunks/XV2HQKND.js +1 -0
- package/build/dist/chunks/{QZM7CWZW.js → XVFLT275.js} +1 -1
- package/build/dist/chunks/{BV3AHLH5.js → XWEFKXKA.js} +1 -1
- package/build/dist/chunks/{NKY3DT34.js → YA5WWDEW.js} +1 -1
- package/build/dist/chunks/YHB55C5T.js +1 -0
- package/build/dist/chunks/YOENHHKI.js +1 -0
- package/build/dist/chunks/YQUKU2LS.js +1 -0
- package/build/dist/chunks/{72AWP4BM.js → YZSTP2E6.js} +1 -1
- package/build/dist/chunks/{T3NPRRTY.js → Z7RL4NGX.js} +1 -1
- package/build/dist/chunks/{YMB553OJ.js → ZT47KN7A.js} +1 -1
- package/build/dist/chunks/ZXQMF56D.js +1 -0
- package/package.json +1 -1
- package/build/dist/chunks/6SCCW74G.js +0 -1
- package/build/dist/chunks/DD7755AW.js +0 -1
- package/build/dist/chunks/EYYUWFUR.js +0 -1
- package/build/dist/chunks/JG24LNUI.js +0 -1
- package/build/dist/chunks/JRO6WTK4.js +0 -1
- package/build/dist/chunks/MNFU7PO3.js +0 -1
- package/build/dist/chunks/N3GWFLG6.js +0 -1
- package/build/dist/chunks/RRSODRGT.js +0 -1
- package/build/dist/chunks/UMK564HS.js +0 -1
- package/build/dist/chunks/XPFVT2EA.js +0 -1
- package/build/dist/chunks/XUJSQV52.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as pt}from"./OW7GOYKA.js";import{b as gt}from"./H6ED3RHF.js";import{b as ft}from"./FBQWTWPT.js";import{b as ut}from"./QXFJZGVB.js";import{c as ct}from"./6L6DSMCU.js";import{b as mt}from"./NHCRJC5X.js";import{h as lt}from"./HNMOB76J.js";import{a as C,b as x,c as Ie,d as me,e as Ge,g as it,h as Ve,j as U,l as E,o as Fe,p as rt,q as st,r as Me,s as at,t as qe,u as dt}from"./TCS3ICNE.js";import{b as nt,o as ot}from"./CAU44UWP.js";import{b as Qe}from"./AXYOJBX6.js";import{a as z}from"./6IM6A5VA.js";import{a as et,c as tt}from"./MYBDO5SA.js";import{a as Pe}from"./UWOFA6GV.js";import{a as ee}from"./RETS2ZEK.js";import{a as $,d as N,i as le}from"./XPFVT2EA.js";import{a}from"./5YS5V2LK.js";import{a as Ee}from"./JXOEJPJ4.js";import{BaseError as Ht,ContractFunctionRevertedError as ht,decodeEventLog as Wt,decodeFunctionResult as jt,encodeFunctionData as X,erc20Abi as zt,getAddress as B,parseAbi as ke,parseAbiItem as Jt,recoverAddress as Xt,recoverMessageAddress as Yt,recoverTypedDataAddress as Zt}from"viem";var Kt="https://priors.trade/api/check",He=604800n,bt=50n,wt=10000n,We=5000000n,yt=500000000n,je=86400n,$t=2592000n,Ye=`Register one with oak_setup {"mode":"register"}, then open Priors' 5 USDG starter line with priors_starter_line (a refundable 5 USDG bond, an invite from Priors' invite bot, your pool consent; each transaction and signature is confirmed).`,Qt="0x6982e39521a070a3c40782548bfbed6dc8f566ef",en=["0xcbb95bbf36099d34da091dc6fa6f49efa257cee3","0x284358abc07f9359f19f4b5b4ac91901be2597ba"],c={pool:B(le[4663].priors.pool.address),lens:B(le[4663].priors.lens.address),usdg:B(le[4663].priors.usdg.address),registry:B(le[4663].priors.registry.address),stockVault:B(le[4663].priors.stockVault.address)},ce={address:c.usdg,symbol:"USDG",decimals:N,chainId:$},S=ke(["function deposit(uint256 assets, address receiver, uint256 minShares) returns (uint256 minted)","function withdraw(uint256 shares_, address receiver) returns (uint256 out)","function quoteFee(uint256 agentId, uint256 principal, uint64 term) view returns (uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium)","function borrow(uint256 agentId, uint256 amount, uint64 term, address to, uint256 maxFee) returns (uint256 loanId)","function repay(uint256 loanId, uint256 expectedAgentId, uint256 maxDue)","function shares(address lender) view returns (uint256)","function convertToAssets(uint256 shares_) view returns (uint256)","function lastDepositAt(address lender) view returns (uint64)","function isController(uint256 id, address who) view returns (bool)","function delegateOf(uint256 id) view returns (address)","function getAgent(uint256 id) view returns (bool enrolled, bool isRoot, bool defaulted, bool frozen, bool importedFromV1, uint64 enrolledAt, uint64 lastBorrowAt, uint64 lastRepayAt, uint256 sponsor, uint256 delegatedIn, uint256 delegatedOut, uint256 principalOut, uint256 activeLoans, uint256 premiumBps, uint256 premiumCap, uint256 loansRepaid, uint256 volumeRepaid, uint256 feesPaid, uint256 recourseHonored, uint256 childrenDefaulted, uint256 qualifiedRepaid, uint256 dollarSecondsRepaid)","function nonces(uint256 id) view returns (uint256)","function consentDigest((uint256 agentId, uint256 sponsorId, address owner, uint256 maxPremiumBps, uint256 nonce, uint256 deadline) c) view returns (bytes32)","function leave(uint256 agentId)","function loansOf(uint256 id) view returns (uint256[])","function getLoan(uint256 loanId) view returns (uint256 agentId, uint256 sponsorId, uint256 principal, uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium, address owner, uint64 issuedAt, uint64 dueAt, uint64 defaultableAt, uint64 minScoreTerm, uint64 closedAt, uint8 status)","event Borrowed(uint256 indexed loanId, uint256 indexed agentId, uint256 indexed sponsorId, uint256 principal, uint256 fee, uint64 dueAt, address to)"]),St=ke(["function available(uint256 agentId) view returns (uint256)","function score(uint256 id) view returns (uint256)"]),Ct=ke(["function ownerOf(uint256 agentId) view returns (address)","function balanceOf(address owner) view returns (uint256)","function getAgentWallet(uint256 agentId) view returns (address)"]),At=ke(["function borrowRoom(uint256 agentId) view returns (uint256)","function assetList() view returns (address[])","function assets(address token) view returns (address feed, uint32 heartbeat, uint8 tokenDecimals, uint8 feedDecimals, bool enabled, uint16 ltvBps, uint256 lineCap)"]);function Y(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tn(e){return e.chainId===$&&e.address.toLowerCase()===c.usdg.toLowerCase()}function nn(e,i){let g=i.amount.trim(),u=g.startsWith("-"),f=u||g.startsWith("+")?g.slice(1):g,R=e.formatAmount(f,i.token.decimals),A=tn(i.token)?"USDG":i.token.address;return`${u?"-":"+"}${R} ${A}`}function te(e,i,g){if(!g.length)return i;let u=g.map(f=>nn(e,f)).join(", ");return`${i} Preview changes: ${u}.`}function vt(e,i,g,u){let f=e[i]===void 0?void 0:ee(e[i]),R=e[g]===void 0?void 0:ee(e[g]);if(f!==void 0)return f;if(R!==void 0)return R;throw new a(`Provide ${u} as an integer string in base units ("${i}" or "${g}").`)}async function De(e,i,g){try{return B(await e.clientFor($).readContract({address:c.registry,abi:Ct,functionName:"ownerOf",args:[i],blockNumber:g}))}catch{throw new a(`Could not read the owner of ERC-8004 agent ${i} from registry ${c.registry}. Check the agent ID and retry when the registry is available.`)}}function pe(e,i){if(typeof e=="bigint"&&e>0n)return e;if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if(typeof e=="string"&&/^\d+$/.test(e.trim())){let g=BigInt(e.trim());if(g>0n)return g}throw new a(`Provide a positive integer ${i}.`)}function on(e,i){let g=i!==void 0?pe(i,"agentId"):void 0,u=[];for(let f of e)if(!(!f||typeof f.address!="string")&&f.address.toLowerCase()===c.pool.toLowerCase()&&!(!Array.isArray(f.topics)||f.topics.length===0))try{let R=Wt({abi:S,eventName:"Borrowed",data:f.data,topics:f.topics});if(g!==void 0&&R.args.agentId!==g)continue;u.push(R.args.loanId)}catch{continue}return u.length===0?null:u[u.length-1].toString()}function we(e){return{enrolled:!!e[0],isRoot:!!e[1],defaulted:!!e[2],frozen:!!e[3],importedFromV1:!!e[4],enrolledAt:BigInt(e[5]),lastBorrowAt:BigInt(e[6]),lastRepayAt:BigInt(e[7]),sponsor:BigInt(e[8]),delegatedIn:BigInt(e[9]),delegatedOut:BigInt(e[10]),principalOut:BigInt(e[11]),activeLoans:BigInt(e[12]),premiumBps:BigInt(e[13]),premiumCap:BigInt(e[14]),loansRepaid:BigInt(e[15]),volumeRepaid:BigInt(e[16]),feesPaid:BigInt(e[17]),recourseHonored:BigInt(e[18]),childrenDefaulted:BigInt(e[19]),qualifiedRepaid:BigInt(e[20]),dollarSecondsRepaid:BigInt(e[21])}}function Ce(e,i){return{loanId:e,agentId:BigInt(i[0]),sponsorId:BigInt(i[1]),principal:BigInt(i[2]),fee:BigInt(i[3]),sponsorCut:BigInt(i[4]),reserveCut:BigInt(i[5]),premium:BigInt(i[6]),owner:B(String(i[7])),issuedAt:BigInt(i[8]),dueAt:BigInt(i[9]),defaultableAt:BigInt(i[10]),minScoreTerm:BigInt(i[11]),closedAt:BigInt(i[12]),status:Number(i[13])}}async function _e(e,i){let g=e.clientFor($),u=await g.getBlockNumber({cacheTime:0}),f=await g.readContract({address:c.registry,abi:Ct,functionName:"balanceOf",args:[i],blockNumber:u});if(f===0n)return[];if(typeof f!="bigint"||f<0n)throw new a("Registry balance is unavailable. Retry or provide an explicit agentId.");let R=[],A=new Set,L=u;for(;;){let H=L>9999999n?L-9999999n:0n,ne=await g.getLogs({address:c.registry,event:Jt("event Transfer(address indexed from,address indexed to,uint256 indexed tokenId)"),args:{to:i},fromBlock:H,toBlock:L,strict:!0});for(let O of ne){let J=O.args.tokenId;if(O.removed||A.has(J))continue;if(A.add(J),(await De(e,J,u)).toLowerCase()===i.toLowerCase()&&R.push(J),BigInt(R.length)===f)return R.sort((Z,re)=>Z<re?-1:Z>re?1:0)}if(H===0n)throw new a("Owned identities could not all be located. Retry or provide an explicit agentId.");L=H-1n}}async function Re(e,i,g){if(i.agentId!==void 0&&i.agentId!==null&&String(i.agentId).trim()!=="")return pe(i.agentId,"agentId");let u=await _e(e,g);if(u.length===0)throw new a(`Priors borrowing needs an ERC-8004 agent identity with a Priors credit line, and this wallet owns no identity. ${Ye}`);return u[0]}async function ze(e,i,g){let u=e.clientFor($),f=await De(e,i),[R,A]=await Promise.all([u.readContract({address:c.pool,abi:S,functionName:"delegateOf",args:[i]}),u.readContract({address:c.pool,abi:S,functionName:"isController",args:[i,g]})]),L=B(R);if(!A)throw new a(`Wallet ${g} is not an on-chain controller for ERC-8004 agent ${i} (ownerOf=${f}, delegateOf=${L}). An off-chain /api/check paymentWallet match alone does not grant CreditPoolV2 control.`);return{owner:f,delegate:L}}function rn(e,i){if(!i.enrolled||i.isRoot||i.sponsor===0n)throw new a(`ERC-8004 agent ${e} has no sponsor-backed Priors credit line on CreditPoolV2 yet (enrolled=${i.enrolled}, sponsor=${i.sponsor}, isRoot=${i.isRoot}). For an agent with no Priors record, priors_starter_line opens Priors' 5 USDG treasury line (a refundable 5 USDG bond, an invite from Priors' invite bot, your pool consent), then borrow.`);if(i.defaulted||i.frozen)throw new a(`ERC-8004 agent ${e} is not eligible to borrow on CreditPoolV2 (defaulted=${i.defaulted}, frozen=${i.frozen}).`);let g=i.delegatedIn>i.principalOut?i.delegatedIn-i.principalOut:0n;if(g<=0n)throw new a(`ERC-8004 agent ${e} has 0 USDG remaining credit capacity (delegatedIn=${i.delegatedIn}, principalOut=${i.principalOut}).`);return g}function sn(e){let i=e.borrowReceiptLogs??(Y(e.borrowReceipt)?e.borrowReceipt.logs:void 0);if(!Array.isArray(i))return[];let g=[];for(let u of i)Y(u)&&(typeof u.address!="string"||!Array.isArray(u.topics)||typeof u.data!="string"||g.push({address:u.address,topics:u.topics,data:u.data}));return g}var Je="0x0000000000000000000000000000000000000000",ue=()=>Math.floor(Date.now()/1e3),G=e=>new Date(Number(e)*1e3).toISOString(),V=(e,i)=>e.toLowerCase()===i.toLowerCase();function ye(e){let i=(g,u)=>Array.isArray(e)?e[u]:e[g];return{depositor:B(String(i("depositor",0))),at:BigInt(i("at",1)),amount:BigInt(i("amount",2))}}async function he(e,i,g){let u=e.clientFor($),f=await u.getBlockNumber({cacheTime:0}),[R,A,L,H,ne,O,J,ge,Z,re,Te]=await Promise.all([De(e,i,f),u.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[i],blockNumber:f}),u.readContract({address:x,abi:E,functionName:"firstLined",args:[i],blockNumber:f}),u.readContract({address:x,abi:E,functionName:"agentId",blockNumber:f}),u.readContract({address:x,abi:E,functionName:"rules",blockNumber:f}),u.readContract({address:x,abi:E,functionName:"epochRoom",blockNumber:f}),u.readContract({address:C,abi:U,functionName:"bonds",args:[i],blockNumber:f}),u.readContract({address:C,abi:U,functionName:"amount",blockNumber:f}),u.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[i],blockNumber:f}),u.readContract({address:C,abi:U,functionName:"unusedAfter",blockNumber:f}),u.readContract({address:c.usdg,abi:zt,functionName:"balanceOf",args:[g],blockNumber:f})]);return{owner:R,agent:we(A),firstLined:L===!0,root:BigInt(H),firstLineAmount:BigInt(ne[1]),epochRoom:BigInt(O),bond:ye(J),bondAmount:BigInt(ge),releaseAt:BigInt(Z),unusedAfter:BigInt(re),usdg:BigInt(Te)}}function Pt(e,i){return e.enrolled||e.enrolledAt>0n||e.isRoot||e.defaulted||e.importedFromV1||e.loansRepaid>0n||e.sponsor!==0n||i}function It(e,i,g,u){let f=R=>`${e.formatAmount(R.toString(),N)} USDG`;if(i.defaulted)return"it defaulted: the pool marks it, and Priors never lends to it again";if(i.isRoot)return"it is a root: it backs other agents' lines";if(i.delegatedIn>0n){let R=i.sponsor===g?`Priors' treasury (root #${g})`:`root #${i.sponsor}`;return`it has a ${f(i.delegatedIn)} line from ${R}${i.activeLoans>0n?` with ${i.activeLoans} loan(s) open`:""}`}return`it has no line now${i.enrolledAt>0n?` (it enrolled at ${G(i.enrolledAt)})`:""}${u?`; Priors' treasury opened a line for it once, and another needs a person at ${Ge}`:""}`}async function Xe(e,i){let g;try{g=await e.http(me,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(i)})}catch(f){if(!(f instanceof et))throw new a(`Priors' invite bot (${me}) could not be reached: ${e.plainError(f)}`);g=f.response}let u;try{u=JSON.parse(await g.text())}catch{u=void 0}if(!Y(u))throw new a(`Priors' invite bot (${me}) answered HTTP ${g.status} without a readable JSON object.`);return u}var be=e=>Ee(typeof e=="string"&&e?e:"no reason given");function an(e,i){let g=i instanceof Ht?i.walk(L=>L instanceof ht):void 0,u=g instanceof ht?g.data:void 0,f=u?.args??[],R=L=>`${e.formatAmount(String(L),N)} USDG`,A=u?.errorName;switch(A){case"EpochCapReached":return`Priors' treasury has no room for a new line this week (wanted ${R(f[0])}, ${R(f[1])} left); the treasury caps new lines each week, so ask again next week.`;case"InsufficientBacking":return`Priors' treasury root lacks free backing for the line now (requested ${R(f[1])}, free ${R(f[2])}); try again later.`;case"InviteExpired":return"the invite expired; call priors_starter_line again for a new one.";case"InviteUsed":return"the invite was already used.";case"NotInvited":return`the invite's signer ${String(f[1])} is not an inviter TreasurySponsorV4 names.`;case"AlreadyLined":return"the agent is already on a treasury line.";case"OwnerDefaulted":return"a default on this wallet's Priors record stops new treasury lines.";case"BadConsent":return"the pool refused the consent (its owner, nonce or signature no longer matches); call priors_starter_line again.";case"ConsentExpired":return"the consent expired; call priors_starter_line again.";case"Paused":return"the Priors pool is paused for new risk; try again later.";case void 0:return e.plainError(i);default:return`${A}(${f.map(String).join(", ")}).`}}var dn=e=>{let i={name:"priors_lend",inputSchema:{type:"object",properties:{assets:{type:"string",pattern:"^[0-9]+$",description:'USDG deposit amount in 6-decimal base units (e.g. "1000000" for 1 USDG).'},amount:{type:"string",pattern:"^[0-9]+$",description:'Alias for assets: USDG base-unit integer string (e.g. "1000000" for 1 USDG).'},receiver:{type:"string",description:"Optional share receiver address (must be the signing wallet)."},minShares:{type:"string",pattern:"^[0-9]+$",description:"Minimum pool shares in base units; defaults to simulated minted shares less slippage."},slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage in basis points for the simulated share minimum (defaults to 50)."}}},async execute(n,s){z(s);let o=B(s),t=o;if(n.receiver!==void 0&&(typeof n.receiver!="string"||n.receiver.trim().toLowerCase()!==o.toLowerCase()))throw new a("Priors receiver must be the signing wallet.");let r=vt(n,"assets","amount","USDG deposit amount");if(r<=0n)throw new a("Deposit amount must be greater than zero.");let p=n.minShares===void 0?void 0:ee(n.minShares),d=e.approval(c.usdg,c.pool,r.toString(),$);if(p===void 0){let l;try{let v=await e.clientFor($).simulateCalls({account:o,calls:[{to:d.to,data:d.data},{to:c.pool,data:X({abi:S,functionName:"deposit",args:[r,t,0n]})}]}),[P,_]=v.results;if(P?.status!=="success"||_?.status!=="success")throw new a("Approval or deposit simulation failed.");l=jt({abi:S,functionName:"deposit",data:_.data})}catch(v){throw new a(`Could not simulate Priors deposit shares: ${e.plainError(v)}`)}if(p=ee(ot(l.toString(),n.slippageBps??nt)),p===0n)throw new a("The simulated deposit cannot provide a positive minimum share amount.")}let w=e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"deposit",args:[r,t,p]}),value:"0",chainId:$,description:`Deposit ${r} USDG base units into Priors CreditPoolV2 (${c.pool}) for ${t}.`}),b=[d,w],m=await e.preview(b,o),I=`Approve ${e.formatAmount(r.toString(),N)} USDG and deposit into Priors CreditPoolV2 (${c.pool}) for ${t} (minShares=${p}; 7-day MIN_HOLD applies a 0.5% early-exit fee on early withdrawals).`;return{txs:b,summary:te(e,I,m.changes)}}},g={name:"priors_withdraw",inputSchema:{type:"object",properties:{shares:{type:"string",pattern:"^[0-9]+$",description:"Pool share count in base units to redeem (not USDG amount; omit to redeem full wallet share balance)."},receiver:{type:"string",description:"Optional USDG receiver address (must be the signing wallet)."}}},async execute(n,s){z(s);let o=B(s),t=o;if(n.receiver!==void 0&&(typeof n.receiver!="string"||n.receiver.trim().toLowerCase()!==o.toLowerCase()))throw new a("Priors receiver must be the signing wallet.");let r=e.clientFor($),p=n.shares!==void 0?ee(n.shares):await r.readContract({address:c.pool,abi:S,functionName:"shares",args:[o]});if(p<=0n)throw new a(`Wallet ${o} has no Priors CreditPoolV2 shares to withdraw.`);let[d,w,b]=await Promise.all([r.readContract({address:c.pool,abi:S,functionName:"convertToAssets",args:[p]}),r.readContract({address:c.pool,abi:S,functionName:"lastDepositAt",args:[o]}),r.getBlock()]),m=w>0n&&b.timestamp<w+He,h=m?d*bt/wt:0n,I=d-h,v=[e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"withdraw",args:[p,t]}),value:"0",chainId:$,description:`Withdraw ${p} shares from Priors CreditPoolV2 (${c.pool}) to ${t}.`})],P=await e.preview(v,o),_=e.formatAmount(I.toString(),N),F=e.formatAmount(d.toString(),N),k=e.formatAmount(h.toString(),N),D=m?`inside 7-day MIN_HOLD: ${k} USDG (0.5%) early-exit fee stays in pool, net payout ${_} USDG from ${F} USDG gross`:`outside 7-day MIN_HOLD: no early-exit fee, net payout ${_} USDG`,M=`Withdraw ${p} shares from Priors CreditPoolV2 (${c.pool}) to ${t} (${D}).`;return{txs:v,summary:te(e,M,P.changes)}}},u={name:"priors_borrow",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID with an already-funded Priors credit line."},principal:{type:"string",pattern:"^[0-9]+$",description:'Borrow principal in 6-decimal USDG base units (min "5000000" = 5 USDG).'},amount:{type:"string",pattern:"^[0-9]+$",description:'Alias for principal: USDG base-unit integer string (e.g. "5000000" for 5 USDG).'},term:{type:"string",description:'Loan term in seconds (between 86400 and 2592000; defaults to "86400"). The origination fee is pro-rated by term, so a longer term costs more.'},recipient:{type:"string",description:"Optional USDG recipient address (must be the signing wallet)."},maxFee:{type:"string",description:"Optional ceiling on the origination fee, USDG base units; must equal the pool's current quote for this principal and term. Omit to use that quote. The fee is pro-rated by term, not flat: 1666 for 5 USDG over 1 day on the first live run (2026-10-31)."}}},async execute(n,s){z(s);let o=B(s),t=o;if(n.recipient!==void 0&&(typeof n.recipient!="string"||n.recipient.trim().toLowerCase()!==o.toLowerCase()))throw new a("Priors recipient must be the signing wallet.");let r=await Re(e,n,o);await ze(e,r,o);let p=e.clientFor($),d=await p.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[r]}),w=we(d),b=rn(r,w),m=vt(n,"principal","amount","USDG borrow principal");if(m<We||m>yt)throw new a(`Borrow principal must be between ${We} (5 USDG) and ${yt} (500 USDG) base units.`);if(m>b)throw new a(`Borrow principal ${m} exceeds available credit line capacity ${b} USDG base units for agent ${r}.`);let h=n.term!==void 0&&String(n.term).trim()!==""?pe(n.term,"term"):je;if(h<je||h>$t)throw new a(`Loan term must be between ${je} (1 day) and ${$t} (30 days) seconds.`);let I=await p.readContract({address:c.pool,abi:S,functionName:"quoteFee",args:[r,m,h]}),l=I[0],v=n.maxFee!==void 0?ee(n.maxFee):l;if(v<l)throw new a(`Provided maxFee ${v} is below the origination fee the pool quotes for this term, ${l} USDG base units.`);if(v>l)throw new a(`Provided maxFee ${v} is above the quoted origination fee ${l} USDG base units. Use the quoted fee or omit maxFee.`);let P=m+l,_=m+v,k=[e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"borrow",args:[r,m,h,t,v]}),value:"0",chainId:$,description:`Borrow ${m} USDG base units on Priors CreditPoolV2 for agent ${r} to ${t} (quoted fee ${l}, expected debt ${P}, maxFee ${v}, debt ceiling ${_}).`})],D=await e.preview(k,o),M=e.formatAmount(m.toString(),N),W=e.formatAmount(l.toString(),N),se=e.formatAmount(P.toString(),N),j=e.formatAmount(v.toString(),N),$e=e.formatAmount(_.toString(),N),q=I[1]+I[3],K=I[2],ae=l-q-K,oe=`Borrow ${M} USDG for ERC-8004 agent ${r} to recipient ${t} on Priors CreditPoolV2 (${c.pool}) for ${h}s: expected origination fee ${W} USDG (${l} base units; pro-rated by term, set when the loan opens, none refunded on early repayment), expected total repayment due ${se} USDG (${P} base units); fee ceiling ${j} USDG (${v} base units), debt ceiling ${$e} USDG (${_} base units). Fee recipient on repayment: CreditPoolV2 (${c.pool}), allocating the quoted fee to sponsor ${w.sponsor} (${q} base units including premium), reserve (${K} base units), and lenders (${ae} base units).`;return{txs:k,summary:te(e,oe,D.changes)}}},f={name:"priors_repay",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID that owns the active loan."},loanId:{type:"string",description:"Optional explicit per-agent loan ID (otherwise recovered from Borrowed receipt logs or loansOf(agentId))."},borrowReceiptLogs:{type:"array",description:"Optional receipt logs array from the borrow transaction to decode the exact Borrowed(loanId, agentId, ...) event."},maxDue:{type:"string",description:"Optional maximum USDG base units to repay; must equal the exact fixed principal + fee. Omit to use that debt."}}},async execute(n,s){z(s);let o=B(s),t=await Re(e,n,o);await ze(e,t,o);let r=e.clientFor($),p;if(n.loanId!==void 0&&n.loanId!==null&&String(n.loanId).trim()!=="")p=pe(n.loanId,"loanId");else{let k=sn(n);if(k.length>0){let D=on(k,t);D!==null&&(p=BigInt(D))}}let d;if(p!==void 0){let k=await r.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[p]}),D=Ce(p,k);if(D.agentId!==t)throw new a(`Loan ${p} belongs to agent ${D.agentId}, not agent ${t}. Recover loan IDs from the Borrowed receipt or loansOf(agentId), never global loanCount().`);if(D.status!==1)throw new a(`Loan ${p} for agent ${t} is not active (status=${D.status}).`);d=D}else{let k=await r.readContract({address:c.pool,abi:S,functionName:"loansOf",args:[t]});if(k.length===0)throw new a(`ERC-8004 agent ${t} has no recorded loans on Priors CreditPoolV2.`);let M=(await Promise.all(k.map(async W=>{let se=await r.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[W]});return Ce(W,se)}))).filter(W=>W.agentId===t&&W.status===1);if(M.length===0)throw new a(`ERC-8004 agent ${t} has no active loans to repay.`);d=M[M.length-1]}let w=d.principal+d.fee,b=n.maxDue!==void 0?ee(n.maxDue):w;if(b<w)throw new a(`Provided maxDue ${b} is below the exact fixed loan debt ${w} USDG base units (principal ${d.principal} + fixed fee ${d.fee}).`);if(b>w)throw new a(`Provided maxDue ${b} is above the exact fixed loan debt ${w} USDG base units. Use the fixed debt or omit maxDue.`);let m=e.approval(c.usdg,c.pool,w.toString(),$),h=e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"repay",args:[d.loanId,t,b]}),value:"0",chainId:$,description:`Repay fixed debt ${w} USDG base units (principal ${d.principal} + fee ${d.fee}) for loan ${d.loanId} (agent ${t}).`}),I=[m,h],l=await e.preview(I,o),v=e.formatAmount(w.toString(),N),P=e.formatAmount(d.principal.toString(),N),_=e.formatAmount(d.fee.toString(),N),F=`Approve and repay ${v} USDG (${w} base units: ${P} USDG principal + ${_} USDG fixed fee) for Priors loan ${d.loanId} (agent ${t}).`;return{txs:I,summary:te(e,F,l.changes)}}},R={name:"priors_status",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Optional ERC-8004 agent ID to inspect on CreditPoolV2, PriorsLens, and StockVault."},includeApiCheck:{type:"boolean",description:"Optional flag to query https://priors.trade/api/check for supplemental off-chain metadata."}}},async execute(n,s){z(s);let o=B(s),t=e.clientFor($),[r,p,d,w]=await Promise.all([t.readContract({address:c.pool,abi:S,functionName:"shares",args:[o]}),t.readContract({address:c.pool,abi:S,functionName:"lastDepositAt",args:[o]}),t.getBlock(),t.readContract({address:c.stockVault,abi:At,functionName:"assetList"})]),b=r>0n?await t.readContract({address:c.pool,abi:S,functionName:"convertToAssets",args:[r]}):0n,m=r>0n&&p>0n&&d.timestamp<p+He,h=m?b*bt/wt:0n,I=b-h,l=null;if(n.agentId!==void 0&&n.agentId!==null&&String(n.agentId).trim()!=="")l=pe(n.agentId,"agentId");else{let q=await _e(e,o);q.length>0&&(l=q[0])}let v=null,P=!1,_=[],F=null,k=null,D=null,M=null,W=null,se=null,j=`This wallet owns no ERC-8004 agent identity. ${Ye}`;if(l!==null){let[q,K,ae,oe,Lt,xt,Be,Ne,Le]=await Promise.all([t.readContract({address:c.lens,abi:St,functionName:"score",args:[l]}),t.readContract({address:x,abi:E,functionName:"firstLined",args:[l]}),t.readContract({address:x,abi:E,functionName:"agentId"}),t.readContract({address:x,abi:E,functionName:"rules"}),t.readContract({address:x,abi:E,functionName:"epochRoom"}),t.readContract({address:C,abi:U,functionName:"bonds",args:[l]}),t.readContract({address:C,abi:U,functionName:"amount"}),t.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[l]}),t.readContract({address:C,abi:U,functionName:"releasable",args:[l]})]),[Ot,Ut,Et,Gt,Vt,Ft]=await Promise.all([t.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[l]}),t.readContract({address:c.pool,abi:S,functionName:"loansOf",args:[l]}),t.readContract({address:c.lens,abi:St,functionName:"available",args:[l]}),t.readContract({address:c.stockVault,abi:At,functionName:"borrowRoom",args:[l]}),t.readContract({address:c.pool,abi:S,functionName:"delegateOf",args:[l]}),t.readContract({address:c.pool,abi:S,functionName:"isController",args:[l,o]})]),xe=await De(e,l),Mt=B(Vt),Ze=Ft,y=we(Ot),Se=y.delegatedIn>y.principalOut?y.delegatedIn-y.principalOut:0n;P=y.enrolled&&!y.isRoot&&!y.defaulted&&!y.frozen&&y.sponsor>0n&&y.delegatedIn>0n,F=Et.toString(),k=Gt.toString();let qt=await Promise.all(Ut.map(async T=>{let de=await t.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[T]});return Ce(T,de)}));for(let T of qt)if(T.agentId===l&&T.status===1){let de=T.principal+T.fee;_.push({loanId:T.loanId.toString(),agentId:T.agentId.toString(),sponsorId:T.sponsorId.toString(),principal:T.principal.toString(),fee:T.fee.toString(),due:de.toString(),dueAt:T.dueAt.toString(),issuedAt:T.issuedAt.toString(),owner:T.owner,token:ce})}v={agentId:l.toString(),owner:xe,delegate:Mt,isAuthorizedController:Ze,enrolled:y.enrolled,isRoot:y.isRoot,defaulted:y.defaulted,frozen:y.frozen,sponsorId:y.sponsor.toString(),delegatedIn:y.delegatedIn.toString(),delegatedOut:y.delegatedOut.toString(),principalOut:y.principalOut.toString(),availableCapacity:Se.toString(),activeLoansCount:y.activeLoans.toString(),loansRepaid:y.loansRepaid.toString(),volumeRepaid:y.volumeRepaid.toString(),feesPaid:y.feesPaid.toString(),importedFromV1:y.importedFromV1,qualifiedRepaid:y.qualifiedRepaid.toString(),dollarSecondsRepaid:y.dollarSecondsRepaid.toString()};let Ae=BigInt(ae),Oe=K===!0,Q=ye(xt),ie=Q.depositor!==Je,ve=ie&&V(Q.depositor,o),Ke=Pt(y,Oe),Ue=V(xe,o);D={onchain:BigInt(q).toString(),scale:"0-1000",source:`CreditLensV2.score(${l}) at ${c.lens}, the score the pool computes on chain`,scoreV2:null},M={open:y.sponsor!==0n&&y.delegatedIn>0n,amount:y.delegatedIn.toString(),drawn:y.principalOut.toString(),available:Se.toString(),sponsorId:y.sponsor.toString(),backer:y.sponsor===0n?null:y.sponsor===Ae?`Priors' treasury v4 (root #${Ae})`:`root #${y.sponsor}`,token:ce},W={contract:C,posted:ie,depositor:ie?Q.depositor:null,postedByWallet:ve,postedAt:ie?Q.at.toString():null,amount:(ie?Q.amount:BigInt(Be)).toString(),releasable:ie&&Le===!0,releaseAt:ie?BigInt(Ne).toString():null,rule:"Back to its depositor once the agent holds no line and has no loan open, from 4 days after it was posted (close a line first with priors_close_line); a default forfeits it to Priors' Safe."},se={eligible:Ue&&!Ke,firstLined:Oe,lineAmount:BigInt(oe[1]).toString(),bondAmount:BigInt(Be).toString(),treasuryRoot:Ae.toString(),treasuryRoomThisWeek:BigInt(Lt).toString(),note:"Not instant: Priors' invite bot decides each invite, and the treasury caps new lines each week."};let fe=_.map(T=>({id:String(T.loanId),dueAt:BigInt(String(T.dueAt))})).sort((T,de)=>T.dueAt<de.dueAt?-1:T.dueAt>de.dueAt?1:0);y.defaulted?j=`Agent #${l} defaulted; Priors never lends to it again${ve?" and its bond is forfeited":""}.`:!Ze&&!Ue?j=`This wallet does not control agent #${l} on CreditPoolV2 (owner ${xe}); act from its owner or delegate.`:fe.length?j=`Repay loan ${fe[0].id} with priors_repay before it is due at ${G(fe[0].dueAt)}${fe.length>1?` (${fe.length} loans open)`:""}.`:P&&Se>=We?j=`Borrow with priors_borrow (5 USDG minimum, up to ${A(Se)}; the fee is pro-rated by term); Priors counts loans held 7 days or more toward the score.`:!Ke&&Ue?j=ve?`Call priors_starter_line again: the ${A(Q.amount)} bond is posted, and it goes on with the invite bot's ownership proof and the invite's redemption${Le===!0?", or priors_release_bond returns the bond":""}.`:`Call priors_starter_line: a refundable ${A(BigInt(Be))} bond, an invite from Priors' invite bot and your pool consent open a ${A(BigInt(oe[1]))} line from Priors' treasury (each transaction and signature is confirmed).`:ve?j=Le===!0?`Release the ${A(Q.amount)} invite bond with priors_release_bond.`:y.delegatedIn>0n?`The line is open with nothing to draw; to take the bond back, close it with priors_close_line, then priors_release_bond from ${G(BigInt(Ne))}.`:`The ${A(Q.amount)} invite bond comes back with priors_release_bond from ${G(BigInt(Ne))}.`:j=`Agent #${l} has a Priors record but no line to draw now; ${It(e,y,Ae,Oe)}.`}let $e=null;if(n.includeApiCheck){let q=l!==null?`agent=${l.toString()}`:`address=${o}`,K=await tt(e.http,`${Kt}?${q}`,{method:"GET"},Y),ae=Array.isArray(K.agents)?K.agents.find(oe=>Y(oe)&&String(oe.agentId)===String(l)):void 0;D&&Y(ae)&&(D.scoreV2=ae.scoreV2??null),$e={...K,grantsPoolControl:!1,controlRule:"Off-chain /api/check identity or paymentWallet match never grants CreditPoolV2 control; on-chain isController(agentId, wallet) must authorize the caller; stale delegates do not qualify."}}return{chainId:$,blockNumber:d.number?.toString()??null,blockTimestamp:d.timestamp.toString(),wallet:o,token:ce,contracts:c,lender:{shares:r.toString(),grossAssets:b.toString(),earlyExitFeeAssets:h.toString(),netWithdrawAssets:I.toString(),lastDepositAt:p.toString(),withinMinHoldWindow:m,minHoldSeconds:He.toString()},hasFundedLine:P,agentId:l!==null?l.toString():null,nextStep:j,score:D,line:M,bond:W,starterLine:se,agent:v,activeLoans:_,lens:{address:c.lens,available:F,caveat:"PriorsLens.available(agentId) is a status capacity hint for already-funded lines; backer hooks may still refuse borrows."},stockVault:{address:c.stockVault,borrowRoom:k,onchainAssetCount:w.length,hostedMcpStockCount:35,extraNonStockAsset:B(Qt),zeroCapAssets:en.map(q=>B(q)),caveat:"Use priors_stock_assets and priors_stock_asset_state for current collateral rules, then priors_stock_open. This summary is an observed asset-count snapshot, not a fixed allowlist; live caps, lending holds and prices control admission."},apiCheck:$e,limitations:["Borrowing and repayment require a sponsor-backed ERC-8004 credit line (enrolled && !isRoot && sponsor != 0) authorized on-chain by isController(agentId, wallet).","Priors line routes are exposed by priors_line_options and priors_capabilities: treasury starter, V5 move/raise, direct sponsor, stock and owner PRIORS backing. Ethos execution uses Priors own owner workflow because its worker supplies no unsigned final transaction.","score.onchain is the pool's on-chain score (CreditLensV2); score.scoreV2 is Priors Score v2 from /api/check, present only with includeApiCheck.","Loan debt is the principal plus the origination fee the pool quotes for the term. The fee is pro-rated by term, not flat (1666 base units for 5 USDG over 1 day, observed live 2026-10-31; priors_borrow shows the exact quote), and is fixed once the loan opens: variable interest is never invented, and early repayment refunds none of it.","Loan IDs are recovered from decoded Borrowed receipts or per-agent loansOf(agentId), never global loanCount().","Historical archive event queries and zero-position StockVault lines on public RPCs remain subject to archive retention and live backer state."]}}},A=n=>`${e.formatAmount(n.toString(),N)} USDG`;function L(n){let s=V(n.bond.depositor,n.owner)&&n.bond.amount>0n?n.bond.amount:n.bondAmount;return`Bond first: ${A(s)} is locked in Priors' InviteBond for at least ${n.unusedAfter} seconds (${Number(n.unusedAfter)/86400} days) after posting${n.releaseAt>0n?`; unusedReleaseAt is ${G(n.releaseAt)}`:"; the exact release time is read after posting"}. Release requires no line and no open loan; default can forfeit the bond. Invites are not guaranteed. The credit score can lag qualifying repayments. `}function H(n,s,o){if(!V(o.owner,s))throw new a(`This wallet (${s}) does not own ERC-8004 agent ${n} (its owner is ${o.owner}). The bond, the ownership proof and the pool consent are the owner's. Nothing was signed.`);if(o.root!==Ie)throw new a(`TreasurySponsorV4 (${x}) answers root #${o.root}, not the pinned #${Ie}. Nothing was signed; update Oak.`);if(Pt(o.agent,o.firstLined))throw new a(`Agent #${n} already has a Priors record, so priors_starter_line posts no bond and signs nothing: ${It(e,o.agent,o.root,o.firstLined)}; ${o.agent.loansRepaid} loan(s) repaid. The starter line is only for an identity with no record; priors_status shows this one.`)}let ne="stays posted in InviteBond";function O(n){let s=n.agent.delegatedIn>0n?`with a line open it comes back only after priors_close_line (no loan open), then priors_release_bond from ${G(n.releaseAt)} at the earliest`:`while the agent holds no line it comes back with priors_release_bond from ${G(n.releaseAt)} (${Number(n.unusedAfter)/86400} days after it was posted)`;return`The ${A(n.bond.amount>0n?n.bond.amount:n.bondAmount)} bond ${ne} (${C}), posted from this wallet; ${s}, and priors_starter_line never posts a second bond.`}async function J(n,s,o){try{return await o()}catch(t){let r=t instanceof a?t.message:e.plainError(t);if(r.includes(ne)||n===void 0||!/^[0-9]{1,78}$/.test(n))throw t;let p;try{let d=await he(e,BigInt(n),s);p=V(d.bond.depositor,s)?O(d):""}catch{p=`If the bond transactions mined, the invite bond ${ne} (${C}) remains locked until its on-chain release conditions are met; priors_status shows the exact amount and time (its state could not be read just now).`}throw p?new a(`${r} ${p}`):t}}async function ge(n,s,o){let t=at(await Xe(e,{agentId:n}),{agentId:n,owner:s,now:ue()});if(!t.ok&&t.refused)throw new a(`Priors' invite bot gave no ownership proof to sign for agent #${n}: ${be(t.why)}. Nothing was signed. ${o}`.trim());if(!t.ok)throw new a(`Not signed: the invite bot's answer for agent #${n} is not one Oak signs: ${t.why}. Oak signs only the bot's own start-page text, rebuilt locally for this agent and this wallet. ${o}`.trim());if(t.exp-ue()<120)throw new a(`Not signed: the invite bot's proof for agent #${n} expires in under 2 minutes; call priors_starter_line again for a new one. ${o}`.trim());return t}function Z(n,s,o,t){return{steps:[{kind:"message",message:o.message}],continuation:{stage:"proof",wallet:s,chainId:$,agentId:n,n:o.n,exp:o.exp},summary:`${L(t)}Priors starter line for ERC-8004 agent ${n}, step 2 of 3: sign Priors' invite-bot ownership proof. It is a message signature (EIP-191) only: it sends no transaction and moves no funds. The text is the bot's own form, rebuilt locally for agent #${n} and this wallet, request ${o.n}, expiring ${G(o.exp)}. Oak then sends the signature to ${me}, and the bot decides the invite. ${O(t)}`}}function re(n,s,o){if(n.chainId!==$||typeof n.wallet!="string"||!V(n.wallet,s)||typeof n.agentId!="string"||!/^[1-9][0-9]{0,29}$/.test(n.agentId))throw new a("Priors starter-line continuation does not match this wallet or chain 4663; start priors_starter_line again.");if(o.agentId!==void 0&&String(o.agentId)!==n.agentId)throw new a("Priors starter-line continuation is for another agent; start priors_starter_line again.");return BigInt(n.agentId)}async function Te(n,s){let o;if(n.agentId!==void 0&&n.agentId!==null&&String(n.agentId).trim()!=="")o=pe(n.agentId,"agentId");else{let l=await _e(e,s);if(!l.length)throw new a(`Priors' starter line needs an ERC-8004 agent identity, and this wallet owns none. ${Ye}`);o=l[0]}let t=await he(e,o,s);H(o,s,t);let r=o.toString(),p=V(t.bond.depositor,s);if(!p){if(t.usdg<t.bondAmount)throw new a(`This wallet holds ${A(t.usdg)} on Robinhood Chain, and Priors' treasury invite asks a ${A(t.bondAmount)} bond first (InviteBond ${C}), posted from this wallet. Nothing was signed: add USDG, then call priors_starter_line again.`);if(t.epochRoom<t.firstLineAmount)return{summary:`${L(t)}Not submitted. Priors' treasury has ${A(t.epochRoom)} of room left this week and a first line is ${A(t.firstLineAmount)}, so priors_starter_line posted no bond and signed nothing. The treasury caps new lines each week: ask again next week.`,starterLine:{agentId:r,open:!1,reason:"room",epochRoom:t.epochRoom.toString()}};let l=await Xe(e,{check:!0,owner:s.toLowerCase()});if(l.check!==!0)throw new a("Priors' invite bot did not answer its check, so whether an invite is open cannot be told. Nothing was signed.");if(l.ok!==!0)throw new a(`Whether an automatic invite is open could not be told: Priors' invite bot says ${be(l.error)}. Nothing was signed; try again later.`);if(l.open!==!0){let v=typeof l.reason=="string"?l.reason.replace(/[^a-z-]/g,"").slice(0,24):"",P=typeof l.reopensAt=="number"&&Number.isSafeInteger(l.reopensAt)&&l.reopensAt>0?l.reopensAt:null;return{summary:`${L(t)}Not submitted. No automatic invite is open to this wallet right now, so priors_starter_line posted no bond and signed nothing. Priors' invite bot answers: closed, reason ${Ee(v||"none given")}${P?`, reopens ${G(P)}`:""}. ${dt({...l,reason:v})} Priors lists its other ways to a first line (the Ethos lane, a stock line, the owner's $PRIORS stake) at https://priors.trade/skill.md.`,starterLine:{agentId:r,open:!1,reason:v||null,reopensAt:P}}}}let d=await ge(r,s,p?O(t):"");if(p)return Z(r,s,d,t);let w=[e.approval(c.usdg,C,t.bondAmount.toString(),$),e.unsignedTx({to:C,data:X({abi:U,functionName:"deposit",args:[o]}),value:"0",chainId:$,description:`Post the ${t.bondAmount} USDG base-unit Priors invite bond for agent ${r} in InviteBond (${C}).`})],b=await e.preview(w,s),m=t.bond.depositor!==Je?` This deposit replaces the bond ${t.bond.depositor} posted for this agent; InviteBond returns that bond to it in the same transaction.`:"",h=`${L(t)}Priors starter line for ERC-8004 agent ${r}, step 1 of 3: approve exactly ${A(t.bondAmount)} to Priors' InviteBond (${C}) and post it as the agent's refundable invite bond (InviteBond.deposit).${m} Priors' invite bot says an automatic invite is open now and gave the ownership proof to sign next. Step 2 signs that proof (a message, no transaction); step 3 signs your pool consent and redeems the invite (TreasurySponsorV4.firstLine, ${x}) for a ${A(t.firstLineAmount)} line from Priors' treasury (root #${t.root}). The invite is the bot's decision, not a promise: if it refuses, or any later step fails, the bond stays posted and comes back with priors_release_bond after the on-chain lock and release conditions are met. With a line, the bond comes back only once the line is closed with no loan open (priors_close_line, then priors_release_bond); a default forfeits it to Priors' Safe.`;return{steps:w.map(l=>({kind:"tx",tx:l})),continuation:{stage:"bond",wallet:s,chainId:$,agentId:r,n:d.n,exp:d.exp},summary:te(e,h,b.changes)}}async function Rt(n,s,o){let t=await he(e,n,s);H(n,s,t);let r=n.toString();if(!V(t.bond.depositor,s))throw new a(`The invite bond for agent #${r} is not on chain from this wallet, so nothing more was signed. Check the deposit transaction, then call priors_starter_line again.`);return typeof o.n=="string"&&Ve.test(o.n)&&typeof o.exp=="number"&&Number.isSafeInteger(o.exp)&&o.exp-ue()>=300?Z(r,s,{n:o.n,exp:o.exp,message:Me(r,o.n,o.exp)},t):Z(r,s,await ge(r,s,O(t)),t)}async function _t(n,s,o,t){let r=n.toString();if(typeof o.n!="string"||!Ve.test(o.n)||typeof o.exp!="number"||!Number.isSafeInteger(o.exp))throw new a("Invalid Priors starter-line proof continuation; start priors_starter_line again.");if(typeof t!="string"||!/^0x[0-9a-fA-F]{130}$/.test(t))throw new a("Provide this wallet's signature of the invite bot's ownership proof.");if(o.exp<=ue())throw new a(`The invite bot's proof for agent #${r} expired before it reached the bot; nothing was sent to it. Call priors_starter_line again for a fresh proof (the bond is not posted again).`);let p=Me(r,o.n,o.exp);if(!V(await Yt({message:p,signature:t}),s))throw new a("The ownership-proof signature is not this wallet's; nothing was sent to the invite bot.");let d=await he(e,n,s);if(H(n,s,d),!V(d.bond.depositor,s))throw new a(`The invite bond for agent #${r} is not on chain from this wallet; nothing was sent to the invite bot. Call priors_starter_line again.`);let w=await Xe(e,{n:o.n,signature:t});if(w.ok!==!0)throw new a(`Priors' invite bot gave no invite for agent #${r}: ${be(w.error)}. ${O(d)}`);if(typeof w.code!="string")throw new a(`Priors' invite bot gave no invite for agent #${r}${w.reason?`: ${be(w.reason)}`:""}${typeof w.decided=="string"?` (its decision: ${be(w.decided)})`:""}. ${O(d)}`);let b=qe(w.code,r,ue()+60);if(!b.ok)throw new a(`Priors' invite bot's code for agent #${r} is not one Oak redeems: ${b.why}. Nothing more was signed. ${O(d)}`);let m=e.clientFor($),h=await m.readContract({address:x,abi:E,functionName:"inviteDigest",args:[n,b.expiry]});if(h.toLowerCase()!==st(n,b.expiry).toLowerCase())throw new a("TreasurySponsorV4's invite digest differs from its pinned EIP-712 domain; nothing more was signed. Update Oak.");let I=await Xt({hash:h,signature:b.signature}),[l,v]=await Promise.all([m.readContract({address:x,abi:E,functionName:"inviters",args:[I]}),m.readContract({address:x,abi:E,functionName:"inviteUsed",args:[h]})]);if(l!==!0)throw new a(`Priors' invite for agent #${r} was signed by ${I}, which TreasurySponsorV4 does not name an inviter, so the treasury would refuse it. Nothing more was signed. ${O(d)}`);if(v===!0)throw new a(`Priors' invite for agent #${r} was already used. Nothing more was signed. ${O(d)}`);let[P,_]=await Promise.all([m.readContract({address:c.pool,abi:S,functionName:"nonces",args:[n]}),m.getBlock()]),F=_.timestamp+BigInt(it),k=Fe({agentId:r,owner:s,nonce:P.toString(),deadline:F.toString()}),D=await m.readContract({address:c.pool,abi:S,functionName:"consentDigest",args:[{agentId:n,sponsorId:d.root,owner:s,maxPremiumBps:0n,nonce:P,deadline:F}]});if(D.toLowerCase()!==rt(k).toLowerCase())throw new a(`The pool's consentDigest (${D}) differs from the consent Oak builds for CreditPoolV2 (${c.pool}), so the pool would refuse it. Nothing more was signed. ${O(d)}`);return{steps:[{kind:"typedData",request:k}],continuation:{stage:"consent",wallet:s,chainId:$,agentId:r,invite:w.code,request:k},summary:`Priors starter line for ERC-8004 agent ${r}, step 3 of 3: Priors' invite bot gave an invite (signed by ${I}, an inviter TreasurySponsorV4 names; it expires ${G(b.expiry)}). Sign your pool consent (EIP-712 "Priors Credit" version 2 on CreditPoolV2 ${c.pool}): it lets Priors' treasury (root #${d.root}) back a line for agent #${r} with premium 0, nonce ${P}, valid until ${G(F)}. A transaction redeeming the invite (TreasurySponsorV4.firstLine) follows for your confirmation. ${O(d)}`}}async function kt(n,s,o,t){let r=n.toString();if(typeof t!="string"||!/^0x[0-9a-fA-F]{130}$/.test(t))throw new a("Provide this wallet's signature of the Priors pool consent.");let p=qe(o.invite,r,ue()+60);if(!p.ok)throw new a(`The invite for agent #${r} is not one Oak redeems now: ${p.why}. Call priors_starter_line again for a new one.`);let d=Y(o.request)&&Y(o.request.message)?o.request.message:void 0;if(!d||typeof d.nonce!="string"||!/^[0-9]{1,78}$/.test(d.nonce)||typeof d.deadline!="string"||!/^[0-9]{1,20}$/.test(d.deadline))throw new a("Invalid Priors starter-line consent continuation; start priors_starter_line again.");let w=Fe({agentId:r,owner:s,nonce:d.nonce,deadline:d.deadline});if(!V(await Zt({...w,signature:t}),s))throw new a("The pool-consent signature is not this wallet's for the consent Oak built; nothing was offered.");let b=await he(e,n,s);H(n,s,b);let m=e.clientFor($),[h,I]=await Promise.all([m.readContract({address:c.pool,abi:S,functionName:"nonces",args:[n]}),m.getBlock()]);if(h.toString()!==d.nonce)throw new a(`Agent #${r}'s consent nonce moved on chain since it was signed; nothing was offered. Call priors_starter_line again.`);if(I.timestamp>=BigInt(d.deadline))throw new a(`The pool consent for agent #${r} expired at ${G(BigInt(d.deadline))}; nothing was offered. Call priors_starter_line again.`);let l={agentId:n,sponsorId:Ie,owner:s,maxPremiumBps:0n,nonce:h,deadline:BigInt(d.deadline)},v=[n,p.expiry,p.signature,l,t];try{await m.simulateContract({address:x,abi:E,functionName:"firstLine",args:v,account:s})}catch(k){throw new a(`TreasurySponsorV4.firstLine for agent #${r} would be refused: ${an(e,k)} Nothing was offered. ${O(b)}`)}let P=e.unsignedTx({to:x,data:X({abi:E,functionName:"firstLine",args:v}),value:"0",chainId:$,description:`Redeem Priors' invite for agent ${r}: TreasurySponsorV4.firstLine opens a ${b.firstLineAmount} USDG base-unit line from root ${b.root} with the owner's consent.`}),_=await e.preview([P],s),F=`Redeem agent #${r}'s Priors invite: TreasurySponsorV4.firstLine (${x}) opens a ${A(b.firstLineAmount)} line from Priors' treasury (root #${b.root}) with your signed consent. No USDG moves in this transaction. Then priors_status shows the line and priors_borrow draws it (5 USDG minimum; the fee is pro-rated by term; Priors counts loans held 7 days or more toward the score). The ${A(b.bondAmount)} bond stays in InviteBond until the line is closed with no loan open (priors_close_line, then priors_release_bond, from ${G(b.releaseAt)} at the earliest); a default forfeits it.`;return{txs:[P],summary:te(e,F,_.changes)}}let Dt={name:"priors_starter_line",inputSchema:{description:"Bond first: the launch bond is 5 USDG, locked at least 4 days. The first result reads amount(), unusedAfter() and unusedReleaseAt(agentId) for current terms before any approval. Invites are not guaranteed; the credit score can lag. Release needs no line or open loan; default can forfeit the bond.",type:"object",additionalProperties:!1,properties:{agentId:Pe("ERC-8004 agent ID this wallet owns, with no Priors record yet (default: the first identity this wallet owns)."),continuation:{type:"object"},signature:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"}}},async execute(n,s){z(s);let o=B(s);if(n.continuation===void 0){if(n.signature!==void 0)throw new a("A signature needs its Priors starter-line continuation; start priors_starter_line again.");return J(typeof n.agentId=="string"?n.agentId:void 0,o,()=>Te(n,o))}if(!Y(n.continuation))throw new a("Invalid Priors starter-line continuation; start priors_starter_line again.");let t=n.continuation,r=re(t,o,n),p=d=>J(r.toString(),o,d);if(t.stage==="bond"){if(n.signature!==void 0)throw new a("The bond stage takes no signature; start priors_starter_line again.");return p(()=>Rt(r,o,t))}if(t.stage==="proof")return p(()=>_t(r,o,t,n.signature));if(t.stage==="consent")return p(()=>kt(r,o,t,n.signature));throw new a("Unknown Priors starter-line stage; start priors_starter_line again.")}},Tt={name:"priors_close_line",inputSchema:{type:"object",properties:{agentId:Pe("ERC-8004 agent ID whose Priors line to close (default: the first identity this wallet owns).")}},async execute(n,s){z(s);let o=B(s),t=await Re(e,n,o);await ze(e,t,o);let r=e.clientFor($),[p,d,w,b]=await Promise.all([r.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[t]}),r.readContract({address:C,abi:U,functionName:"bonds",args:[t]}),r.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[t]}),r.readContract({address:x,abi:E,functionName:"agentId"})]),m=we(p);if(m.sponsor===0n)throw new a(`Agent #${t} has no Priors line to close (no sponsor on CreditPoolV2).`);if(m.activeLoans>0n)throw new a(`Agent #${t} has ${m.activeLoans} loan(s) open; repay them with priors_repay first. The pool's leave refuses while a loan is open.`);let h=ye(d),I=m.sponsor===BigInt(b),l=e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"leave",args:[t]}),value:"0",chainId:$,description:`Close agent ${t}'s Priors line on CreditPoolV2 (leave): the ${m.delegatedIn} USDG base-unit line returns to root ${m.sponsor}.`}),v=await e.preview([l],o),P=V(h.depositor,o)?` Its ${A(h.amount)} invite bond can then come back with priors_release_bond from ${G(w)} (4 days after it was posted).`:"",_=`Close agent #${t}'s Priors line (CreditPoolV2.leave, ${c.pool}): the whole ${A(m.delegatedIn)} line goes back to its backer (${I?`Priors' treasury, root #${b}`:`root #${m.sponsor}`}) and the agent can no longer borrow on it. This does not reopen: ${I?`priors_starter_line opens no second treasury line for an agent with a Priors record; another needs a person at ${Ge}.`:"a new line needs a backer's new consent."}${P} No USDG moves in this transaction.`;return{txs:[l],summary:te(e,_,v.changes)}}},Bt={name:"priors_release_bond",inputSchema:{type:"object",properties:{agentId:Pe("ERC-8004 agent ID whose InviteBond bond this wallet posted (default: the first identity this wallet owns).")}},async execute(n,s){z(s);let o=B(s),t=await Re(e,n,o),r=e.clientFor($),[p,d,w,b,m]=await Promise.all([r.readContract({address:C,abi:U,functionName:"bonds",args:[t]}),r.readContract({address:C,abi:U,functionName:"releasable",args:[t]}),r.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[t]}),r.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[t]}),r.getBlock()]),h=ye(p);if(h.depositor===Je)throw new a(`Agent #${t} has no bond in Priors' InviteBond (${C}).`);if(!V(h.depositor,o))throw new a(`Agent #${t}'s InviteBond bond was posted by ${h.depositor}, not this wallet, and InviteBond.release pays the depositor. Oak releases only a bond this wallet posted.`);if(d!==!0){let P=we(b),_=P.defaulted?"the agent defaulted, so the bond is forfeited to Priors' Safe (InviteBond.slash)":P.activeLoans>0n?`the agent has ${P.activeLoans} loan(s) open: repay with priors_repay, close the line with priors_close_line, then release`:P.delegatedIn>0n?`the agent still holds a ${A(P.delegatedIn)} line: close it with priors_close_line (no loan may be open), then release`:m.timestamp<w?`it comes back 4 days after it was posted, from ${G(w)}`:"InviteBond does not release it yet";throw new a(`Agent #${t}'s ${A(h.amount)} invite bond cannot be released now: ${_}. Nothing was signed.`)}let I=e.unsignedTx({to:C,data:X({abi:U,functionName:"release",args:[t]}),value:"0",chainId:$,description:`Release agent ${t}'s ${h.amount} USDG base-unit Priors invite bond from InviteBond (${C}) to its depositor ${h.depositor}.`}),l=await e.preview([I],o),v=`Release agent #${t}'s ${A(h.amount)} invite bond from Priors' InviteBond (${C}): InviteBond.release returns it to its depositor, this wallet (${o}).`;return{txs:[I],summary:te(e,v,l.changes)}}};async function Nt(n){z(n);let s=B(n),o=e.clientFor($),[t,r]=await Promise.all([o.readContract({address:c.pool,abi:S,functionName:"shares",args:[s]}),_e(e,s)]),p=[];if(t>0n){let d=await o.readContract({address:c.pool,abi:S,functionName:"convertToAssets",args:[t]});p.push({module:"priors",id:`priors:lender:${s.toLowerCase()}`,chainId:$,assets:[{token:ce,amount:d.toString()}],description:`Priors CreditPoolV2 lender position (${t} shares = ${e.formatAmount(d.toString(),N)} USDG gross).`})}for(let d of r){let w=await o.readContract({address:c.pool,abi:S,functionName:"loansOf",args:[d]}),b=await Promise.all(w.map(async h=>{let I=await o.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[h]});return Ce(h,I)}));for(let h of b)if(h.agentId===d&&h.status===1){let I=h.principal+h.fee;p.push({module:"priors",id:`priors:loan:${h.loanId.toString()}`,chainId:$,assets:[{token:ce,amount:I.toString()}],description:`Priors CreditPoolV2 active loan ${h.loanId} for agent ${d} (fixed due ${e.formatAmount(I.toString(),N)} USDG = ${h.principal} principal + ${h.fee} fee).`})}let m=ye(await o.readContract({address:C,abi:U,functionName:"bonds",args:[d]}));m.amount>0n&&V(m.depositor,s)&&p.push({module:"priors",id:`priors:bond:${d.toString()}`,chainId:$,assets:[{token:ce,amount:m.amount.toString()}],description:`Priors invite bond for agent ${d} in InviteBond (${C}): ${A(m.amount)}, back with priors_release_bond once the agent holds no line and no loan, from 4 days after posting; a default forfeits it.`})}return p}return{tools:[i,g,u,f,R,Dt,Tt,Bt],positions:Nt}},ln=e=>{let i=dn(e),g=[i,lt(e),ct(e),pt(e),gt(e),ft(e),mt(e),ut()];return{...i,tools:g.flatMap(u=>u.tools)}},_n=e=>Qe("priors",[ln(e)]);export{Kt as a,He as b,bt as c,wt as d,We as e,yt as f,je as g,$t as h,c as i,ce as j,on as k,ln as l,_n as m};
|
|
1
|
+
import{b as mt}from"./4KQZTPMS.js";import{c as pt}from"./2W46IRX6.js";import{b as gt}from"./LMVB3B6T.js";import{b as ft}from"./JWCOXLYA.js";import{b as ut}from"./TWCSCRFS.js";import{c as ct}from"./NMYGNJIJ.js";import{h as lt}from"./GGUEKSR4.js";import{a as C,b as x,c as Ie,d as me,e as Ge,g as it,h as Ve,j as U,l as E,o as Fe,p as rt,q as st,r as Me,s as at,t as qe,u as dt}from"./3WBDHUV2.js";import{b as nt,o as ot}from"./5O5ZE3ZV.js";import{b as Qe}from"./AXYOJBX6.js";import{a as z}from"./6IM6A5VA.js";import{a as et,c as tt}from"./MYBDO5SA.js";import{a as Pe}from"./UWOFA6GV.js";import{a as ee}from"./RETS2ZEK.js";import{a as $,d as N,i as le}from"./G6HCV67X.js";import{a}from"./5YS5V2LK.js";import{a as Ee}from"./JXOEJPJ4.js";import{BaseError as Ht,ContractFunctionRevertedError as ht,decodeEventLog as Wt,decodeFunctionResult as jt,encodeFunctionData as X,erc20Abi as zt,getAddress as B,parseAbi as ke,parseAbiItem as Jt,recoverAddress as Xt,recoverMessageAddress as Yt,recoverTypedDataAddress as Zt}from"viem";var Kt="https://priors.trade/api/check",He=604800n,bt=50n,wt=10000n,We=5000000n,yt=500000000n,je=86400n,$t=2592000n,Ye=`Register one with oak_setup {"mode":"register"}, then open Priors' 5 USDG starter line with priors_starter_line (a refundable 5 USDG bond, an invite from Priors' invite bot, your pool consent; each transaction and signature is confirmed).`,Qt="0x6982e39521a070a3c40782548bfbed6dc8f566ef",en=["0xcbb95bbf36099d34da091dc6fa6f49efa257cee3","0x284358abc07f9359f19f4b5b4ac91901be2597ba"],c={pool:B(le[4663].priors.pool.address),lens:B(le[4663].priors.lens.address),usdg:B(le[4663].priors.usdg.address),registry:B(le[4663].priors.registry.address),stockVault:B(le[4663].priors.stockVault.address)},ce={address:c.usdg,symbol:"USDG",decimals:N,chainId:$},S=ke(["function deposit(uint256 assets, address receiver, uint256 minShares) returns (uint256 minted)","function withdraw(uint256 shares_, address receiver) returns (uint256 out)","function quoteFee(uint256 agentId, uint256 principal, uint64 term) view returns (uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium)","function borrow(uint256 agentId, uint256 amount, uint64 term, address to, uint256 maxFee) returns (uint256 loanId)","function repay(uint256 loanId, uint256 expectedAgentId, uint256 maxDue)","function shares(address lender) view returns (uint256)","function convertToAssets(uint256 shares_) view returns (uint256)","function lastDepositAt(address lender) view returns (uint64)","function isController(uint256 id, address who) view returns (bool)","function delegateOf(uint256 id) view returns (address)","function getAgent(uint256 id) view returns (bool enrolled, bool isRoot, bool defaulted, bool frozen, bool importedFromV1, uint64 enrolledAt, uint64 lastBorrowAt, uint64 lastRepayAt, uint256 sponsor, uint256 delegatedIn, uint256 delegatedOut, uint256 principalOut, uint256 activeLoans, uint256 premiumBps, uint256 premiumCap, uint256 loansRepaid, uint256 volumeRepaid, uint256 feesPaid, uint256 recourseHonored, uint256 childrenDefaulted, uint256 qualifiedRepaid, uint256 dollarSecondsRepaid)","function nonces(uint256 id) view returns (uint256)","function consentDigest((uint256 agentId, uint256 sponsorId, address owner, uint256 maxPremiumBps, uint256 nonce, uint256 deadline) c) view returns (bytes32)","function leave(uint256 agentId)","function loansOf(uint256 id) view returns (uint256[])","function getLoan(uint256 loanId) view returns (uint256 agentId, uint256 sponsorId, uint256 principal, uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium, address owner, uint64 issuedAt, uint64 dueAt, uint64 defaultableAt, uint64 minScoreTerm, uint64 closedAt, uint8 status)","event Borrowed(uint256 indexed loanId, uint256 indexed agentId, uint256 indexed sponsorId, uint256 principal, uint256 fee, uint64 dueAt, address to)"]),St=ke(["function available(uint256 agentId) view returns (uint256)","function score(uint256 id) view returns (uint256)"]),Ct=ke(["function ownerOf(uint256 agentId) view returns (address)","function balanceOf(address owner) view returns (uint256)","function getAgentWallet(uint256 agentId) view returns (address)"]),At=ke(["function borrowRoom(uint256 agentId) view returns (uint256)","function assetList() view returns (address[])","function assets(address token) view returns (address feed, uint32 heartbeat, uint8 tokenDecimals, uint8 feedDecimals, bool enabled, uint16 ltvBps, uint256 lineCap)"]);function Y(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tn(e){return e.chainId===$&&e.address.toLowerCase()===c.usdg.toLowerCase()}function nn(e,i){let g=i.amount.trim(),u=g.startsWith("-"),f=u||g.startsWith("+")?g.slice(1):g,R=e.formatAmount(f,i.token.decimals),A=tn(i.token)?"USDG":i.token.address;return`${u?"-":"+"}${R} ${A}`}function te(e,i,g){if(!g.length)return i;let u=g.map(f=>nn(e,f)).join(", ");return`${i} Preview changes: ${u}.`}function vt(e,i,g,u){let f=e[i]===void 0?void 0:ee(e[i]),R=e[g]===void 0?void 0:ee(e[g]);if(f!==void 0)return f;if(R!==void 0)return R;throw new a(`Provide ${u} as an integer string in base units ("${i}" or "${g}").`)}async function De(e,i,g){try{return B(await e.clientFor($).readContract({address:c.registry,abi:Ct,functionName:"ownerOf",args:[i],blockNumber:g}))}catch{throw new a(`Could not read the owner of ERC-8004 agent ${i} from registry ${c.registry}. Check the agent ID and retry when the registry is available.`)}}function pe(e,i){if(typeof e=="bigint"&&e>0n)return e;if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if(typeof e=="string"&&/^\d+$/.test(e.trim())){let g=BigInt(e.trim());if(g>0n)return g}throw new a(`Provide a positive integer ${i}.`)}function on(e,i){let g=i!==void 0?pe(i,"agentId"):void 0,u=[];for(let f of e)if(!(!f||typeof f.address!="string")&&f.address.toLowerCase()===c.pool.toLowerCase()&&!(!Array.isArray(f.topics)||f.topics.length===0))try{let R=Wt({abi:S,eventName:"Borrowed",data:f.data,topics:f.topics});if(g!==void 0&&R.args.agentId!==g)continue;u.push(R.args.loanId)}catch{continue}return u.length===0?null:u[u.length-1].toString()}function we(e){return{enrolled:!!e[0],isRoot:!!e[1],defaulted:!!e[2],frozen:!!e[3],importedFromV1:!!e[4],enrolledAt:BigInt(e[5]),lastBorrowAt:BigInt(e[6]),lastRepayAt:BigInt(e[7]),sponsor:BigInt(e[8]),delegatedIn:BigInt(e[9]),delegatedOut:BigInt(e[10]),principalOut:BigInt(e[11]),activeLoans:BigInt(e[12]),premiumBps:BigInt(e[13]),premiumCap:BigInt(e[14]),loansRepaid:BigInt(e[15]),volumeRepaid:BigInt(e[16]),feesPaid:BigInt(e[17]),recourseHonored:BigInt(e[18]),childrenDefaulted:BigInt(e[19]),qualifiedRepaid:BigInt(e[20]),dollarSecondsRepaid:BigInt(e[21])}}function Ce(e,i){return{loanId:e,agentId:BigInt(i[0]),sponsorId:BigInt(i[1]),principal:BigInt(i[2]),fee:BigInt(i[3]),sponsorCut:BigInt(i[4]),reserveCut:BigInt(i[5]),premium:BigInt(i[6]),owner:B(String(i[7])),issuedAt:BigInt(i[8]),dueAt:BigInt(i[9]),defaultableAt:BigInt(i[10]),minScoreTerm:BigInt(i[11]),closedAt:BigInt(i[12]),status:Number(i[13])}}async function _e(e,i){let g=e.clientFor($),u=await g.getBlockNumber({cacheTime:0}),f=await g.readContract({address:c.registry,abi:Ct,functionName:"balanceOf",args:[i],blockNumber:u});if(f===0n)return[];if(typeof f!="bigint"||f<0n)throw new a("Registry balance is unavailable. Retry or provide an explicit agentId.");let R=[],A=new Set,L=u;for(;;){let H=L>9999999n?L-9999999n:0n,ne=await g.getLogs({address:c.registry,event:Jt("event Transfer(address indexed from,address indexed to,uint256 indexed tokenId)"),args:{to:i},fromBlock:H,toBlock:L,strict:!0});for(let O of ne){let J=O.args.tokenId;if(O.removed||A.has(J))continue;if(A.add(J),(await De(e,J,u)).toLowerCase()===i.toLowerCase()&&R.push(J),BigInt(R.length)===f)return R.sort((Z,re)=>Z<re?-1:Z>re?1:0)}if(H===0n)throw new a("Owned identities could not all be located. Retry or provide an explicit agentId.");L=H-1n}}async function Re(e,i,g){if(i.agentId!==void 0&&i.agentId!==null&&String(i.agentId).trim()!=="")return pe(i.agentId,"agentId");let u=await _e(e,g);if(u.length===0)throw new a(`Priors borrowing needs an ERC-8004 agent identity with a Priors credit line, and this wallet owns no identity. ${Ye}`);return u[0]}async function ze(e,i,g){let u=e.clientFor($),f=await De(e,i),[R,A]=await Promise.all([u.readContract({address:c.pool,abi:S,functionName:"delegateOf",args:[i]}),u.readContract({address:c.pool,abi:S,functionName:"isController",args:[i,g]})]),L=B(R);if(!A)throw new a(`Wallet ${g} is not an on-chain controller for ERC-8004 agent ${i} (ownerOf=${f}, delegateOf=${L}). An off-chain /api/check paymentWallet match alone does not grant CreditPoolV2 control.`);return{owner:f,delegate:L}}function rn(e,i){if(!i.enrolled||i.isRoot||i.sponsor===0n)throw new a(`ERC-8004 agent ${e} has no sponsor-backed Priors credit line on CreditPoolV2 yet (enrolled=${i.enrolled}, sponsor=${i.sponsor}, isRoot=${i.isRoot}). For an agent with no Priors record, priors_starter_line opens Priors' 5 USDG treasury line (a refundable 5 USDG bond, an invite from Priors' invite bot, your pool consent), then borrow.`);if(i.defaulted||i.frozen)throw new a(`ERC-8004 agent ${e} is not eligible to borrow on CreditPoolV2 (defaulted=${i.defaulted}, frozen=${i.frozen}).`);let g=i.delegatedIn>i.principalOut?i.delegatedIn-i.principalOut:0n;if(g<=0n)throw new a(`ERC-8004 agent ${e} has 0 USDG remaining credit capacity (delegatedIn=${i.delegatedIn}, principalOut=${i.principalOut}).`);return g}function sn(e){let i=e.borrowReceiptLogs??(Y(e.borrowReceipt)?e.borrowReceipt.logs:void 0);if(!Array.isArray(i))return[];let g=[];for(let u of i)Y(u)&&(typeof u.address!="string"||!Array.isArray(u.topics)||typeof u.data!="string"||g.push({address:u.address,topics:u.topics,data:u.data}));return g}var Je="0x0000000000000000000000000000000000000000",ue=()=>Math.floor(Date.now()/1e3),G=e=>new Date(Number(e)*1e3).toISOString(),V=(e,i)=>e.toLowerCase()===i.toLowerCase();function ye(e){let i=(g,u)=>Array.isArray(e)?e[u]:e[g];return{depositor:B(String(i("depositor",0))),at:BigInt(i("at",1)),amount:BigInt(i("amount",2))}}async function he(e,i,g){let u=e.clientFor($),f=await u.getBlockNumber({cacheTime:0}),[R,A,L,H,ne,O,J,ge,Z,re,Te]=await Promise.all([De(e,i,f),u.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[i],blockNumber:f}),u.readContract({address:x,abi:E,functionName:"firstLined",args:[i],blockNumber:f}),u.readContract({address:x,abi:E,functionName:"agentId",blockNumber:f}),u.readContract({address:x,abi:E,functionName:"rules",blockNumber:f}),u.readContract({address:x,abi:E,functionName:"epochRoom",blockNumber:f}),u.readContract({address:C,abi:U,functionName:"bonds",args:[i],blockNumber:f}),u.readContract({address:C,abi:U,functionName:"amount",blockNumber:f}),u.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[i],blockNumber:f}),u.readContract({address:C,abi:U,functionName:"unusedAfter",blockNumber:f}),u.readContract({address:c.usdg,abi:zt,functionName:"balanceOf",args:[g],blockNumber:f})]);return{owner:R,agent:we(A),firstLined:L===!0,root:BigInt(H),firstLineAmount:BigInt(ne[1]),epochRoom:BigInt(O),bond:ye(J),bondAmount:BigInt(ge),releaseAt:BigInt(Z),unusedAfter:BigInt(re),usdg:BigInt(Te)}}function Pt(e,i){return e.enrolled||e.enrolledAt>0n||e.isRoot||e.defaulted||e.importedFromV1||e.loansRepaid>0n||e.sponsor!==0n||i}function It(e,i,g,u){let f=R=>`${e.formatAmount(R.toString(),N)} USDG`;if(i.defaulted)return"it defaulted: the pool marks it, and Priors never lends to it again";if(i.isRoot)return"it is a root: it backs other agents' lines";if(i.delegatedIn>0n){let R=i.sponsor===g?`Priors' treasury (root #${g})`:`root #${i.sponsor}`;return`it has a ${f(i.delegatedIn)} line from ${R}${i.activeLoans>0n?` with ${i.activeLoans} loan(s) open`:""}`}return`it has no line now${i.enrolledAt>0n?` (it enrolled at ${G(i.enrolledAt)})`:""}${u?`; Priors' treasury opened a line for it once, and another needs a person at ${Ge}`:""}`}async function Xe(e,i){let g;try{g=await e.http(me,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(i)})}catch(f){if(!(f instanceof et))throw new a(`Priors' invite bot (${me}) could not be reached: ${e.plainError(f)}`);g=f.response}let u;try{u=JSON.parse(await g.text())}catch{u=void 0}if(!Y(u))throw new a(`Priors' invite bot (${me}) answered HTTP ${g.status} without a readable JSON object.`);return u}var be=e=>Ee(typeof e=="string"&&e?e:"no reason given");function an(e,i){let g=i instanceof Ht?i.walk(L=>L instanceof ht):void 0,u=g instanceof ht?g.data:void 0,f=u?.args??[],R=L=>`${e.formatAmount(String(L),N)} USDG`,A=u?.errorName;switch(A){case"EpochCapReached":return`Priors' treasury has no room for a new line this week (wanted ${R(f[0])}, ${R(f[1])} left); the treasury caps new lines each week, so ask again next week.`;case"InsufficientBacking":return`Priors' treasury root lacks free backing for the line now (requested ${R(f[1])}, free ${R(f[2])}); try again later.`;case"InviteExpired":return"the invite expired; call priors_starter_line again for a new one.";case"InviteUsed":return"the invite was already used.";case"NotInvited":return`the invite's signer ${String(f[1])} is not an inviter TreasurySponsorV4 names.`;case"AlreadyLined":return"the agent is already on a treasury line.";case"OwnerDefaulted":return"a default on this wallet's Priors record stops new treasury lines.";case"BadConsent":return"the pool refused the consent (its owner, nonce or signature no longer matches); call priors_starter_line again.";case"ConsentExpired":return"the consent expired; call priors_starter_line again.";case"Paused":return"the Priors pool is paused for new risk; try again later.";case void 0:return e.plainError(i);default:return`${A}(${f.map(String).join(", ")}).`}}var dn=e=>{let i={name:"priors_lend",inputSchema:{type:"object",properties:{assets:{type:"string",pattern:"^[0-9]+$",description:'USDG deposit amount in 6-decimal base units (e.g. "1000000" for 1 USDG).'},amount:{type:"string",pattern:"^[0-9]+$",description:'Alias for assets: USDG base-unit integer string (e.g. "1000000" for 1 USDG).'},receiver:{type:"string",description:"Optional share receiver address (must be the signing wallet)."},minShares:{type:"string",pattern:"^[0-9]+$",description:"Minimum pool shares in base units; defaults to simulated minted shares less slippage."},slippageBps:{type:"integer",minimum:0,maximum:9999,description:"Slippage in basis points for the simulated share minimum (defaults to 50)."}}},async execute(n,s){z(s);let o=B(s),t=o;if(n.receiver!==void 0&&(typeof n.receiver!="string"||n.receiver.trim().toLowerCase()!==o.toLowerCase()))throw new a("Priors receiver must be the signing wallet.");let r=vt(n,"assets","amount","USDG deposit amount");if(r<=0n)throw new a("Deposit amount must be greater than zero.");let p=n.minShares===void 0?void 0:ee(n.minShares),d=e.approval(c.usdg,c.pool,r.toString(),$);if(p===void 0){let l;try{let v=await e.clientFor($).simulateCalls({account:o,calls:[{to:d.to,data:d.data},{to:c.pool,data:X({abi:S,functionName:"deposit",args:[r,t,0n]})}]}),[P,_]=v.results;if(P?.status!=="success"||_?.status!=="success")throw new a("Approval or deposit simulation failed.");l=jt({abi:S,functionName:"deposit",data:_.data})}catch(v){throw new a(`Could not simulate Priors deposit shares: ${e.plainError(v)}`)}if(p=ee(ot(l.toString(),n.slippageBps??nt)),p===0n)throw new a("The simulated deposit cannot provide a positive minimum share amount.")}let w=e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"deposit",args:[r,t,p]}),value:"0",chainId:$,description:`Deposit ${r} USDG base units into Priors CreditPoolV2 (${c.pool}) for ${t}.`}),b=[d,w],m=await e.preview(b,o),I=`Approve ${e.formatAmount(r.toString(),N)} USDG and deposit into Priors CreditPoolV2 (${c.pool}) for ${t} (minShares=${p}; 7-day MIN_HOLD applies a 0.5% early-exit fee on early withdrawals).`;return{txs:b,summary:te(e,I,m.changes)}}},g={name:"priors_withdraw",inputSchema:{type:"object",properties:{shares:{type:"string",pattern:"^[0-9]+$",description:"Pool share count in base units to redeem (not USDG amount; omit to redeem full wallet share balance)."},receiver:{type:"string",description:"Optional USDG receiver address (must be the signing wallet)."}}},async execute(n,s){z(s);let o=B(s),t=o;if(n.receiver!==void 0&&(typeof n.receiver!="string"||n.receiver.trim().toLowerCase()!==o.toLowerCase()))throw new a("Priors receiver must be the signing wallet.");let r=e.clientFor($),p=n.shares!==void 0?ee(n.shares):await r.readContract({address:c.pool,abi:S,functionName:"shares",args:[o]});if(p<=0n)throw new a(`Wallet ${o} has no Priors CreditPoolV2 shares to withdraw.`);let[d,w,b]=await Promise.all([r.readContract({address:c.pool,abi:S,functionName:"convertToAssets",args:[p]}),r.readContract({address:c.pool,abi:S,functionName:"lastDepositAt",args:[o]}),r.getBlock()]),m=w>0n&&b.timestamp<w+He,h=m?d*bt/wt:0n,I=d-h,v=[e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"withdraw",args:[p,t]}),value:"0",chainId:$,description:`Withdraw ${p} shares from Priors CreditPoolV2 (${c.pool}) to ${t}.`})],P=await e.preview(v,o),_=e.formatAmount(I.toString(),N),F=e.formatAmount(d.toString(),N),k=e.formatAmount(h.toString(),N),D=m?`inside 7-day MIN_HOLD: ${k} USDG (0.5%) early-exit fee stays in pool, net payout ${_} USDG from ${F} USDG gross`:`outside 7-day MIN_HOLD: no early-exit fee, net payout ${_} USDG`,M=`Withdraw ${p} shares from Priors CreditPoolV2 (${c.pool}) to ${t} (${D}).`;return{txs:v,summary:te(e,M,P.changes)}}},u={name:"priors_borrow",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID with an already-funded Priors credit line."},principal:{type:"string",pattern:"^[0-9]+$",description:'Borrow principal in 6-decimal USDG base units (min "5000000" = 5 USDG).'},amount:{type:"string",pattern:"^[0-9]+$",description:'Alias for principal: USDG base-unit integer string (e.g. "5000000" for 5 USDG).'},term:{type:"string",description:'Loan term in seconds (between 86400 and 2592000; defaults to "86400"). The origination fee is pro-rated by term, so a longer term costs more.'},recipient:{type:"string",description:"Optional USDG recipient address (must be the signing wallet)."},maxFee:{type:"string",description:"Optional ceiling on the origination fee, USDG base units; must equal the pool's current quote for this principal and term. Omit to use that quote. The fee is pro-rated by term, not flat: 1666 for 5 USDG over 1 day on the first live run (2026-10-31)."}}},async execute(n,s){z(s);let o=B(s),t=o;if(n.recipient!==void 0&&(typeof n.recipient!="string"||n.recipient.trim().toLowerCase()!==o.toLowerCase()))throw new a("Priors recipient must be the signing wallet.");let r=await Re(e,n,o);await ze(e,r,o);let p=e.clientFor($),d=await p.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[r]}),w=we(d),b=rn(r,w),m=vt(n,"principal","amount","USDG borrow principal");if(m<We||m>yt)throw new a(`Borrow principal must be between ${We} (5 USDG) and ${yt} (500 USDG) base units.`);if(m>b)throw new a(`Borrow principal ${m} exceeds available credit line capacity ${b} USDG base units for agent ${r}.`);let h=n.term!==void 0&&String(n.term).trim()!==""?pe(n.term,"term"):je;if(h<je||h>$t)throw new a(`Loan term must be between ${je} (1 day) and ${$t} (30 days) seconds.`);let I=await p.readContract({address:c.pool,abi:S,functionName:"quoteFee",args:[r,m,h]}),l=I[0],v=n.maxFee!==void 0?ee(n.maxFee):l;if(v<l)throw new a(`Provided maxFee ${v} is below the origination fee the pool quotes for this term, ${l} USDG base units.`);if(v>l)throw new a(`Provided maxFee ${v} is above the quoted origination fee ${l} USDG base units. Use the quoted fee or omit maxFee.`);let P=m+l,_=m+v,k=[e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"borrow",args:[r,m,h,t,v]}),value:"0",chainId:$,description:`Borrow ${m} USDG base units on Priors CreditPoolV2 for agent ${r} to ${t} (quoted fee ${l}, expected debt ${P}, maxFee ${v}, debt ceiling ${_}).`})],D=await e.preview(k,o),M=e.formatAmount(m.toString(),N),W=e.formatAmount(l.toString(),N),se=e.formatAmount(P.toString(),N),j=e.formatAmount(v.toString(),N),$e=e.formatAmount(_.toString(),N),q=I[1]+I[3],K=I[2],ae=l-q-K,oe=`Borrow ${M} USDG for ERC-8004 agent ${r} to recipient ${t} on Priors CreditPoolV2 (${c.pool}) for ${h}s: expected origination fee ${W} USDG (${l} base units; pro-rated by term, set when the loan opens, none refunded on early repayment), expected total repayment due ${se} USDG (${P} base units); fee ceiling ${j} USDG (${v} base units), debt ceiling ${$e} USDG (${_} base units). Fee recipient on repayment: CreditPoolV2 (${c.pool}), allocating the quoted fee to sponsor ${w.sponsor} (${q} base units including premium), reserve (${K} base units), and lenders (${ae} base units).`;return{txs:k,summary:te(e,oe,D.changes)}}},f={name:"priors_repay",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"ERC-8004 agent token ID that owns the active loan."},loanId:{type:"string",description:"Optional explicit per-agent loan ID (otherwise recovered from Borrowed receipt logs or loansOf(agentId))."},borrowReceiptLogs:{type:"array",description:"Optional receipt logs array from the borrow transaction to decode the exact Borrowed(loanId, agentId, ...) event."},maxDue:{type:"string",description:"Optional maximum USDG base units to repay; must equal the exact fixed principal + fee. Omit to use that debt."}}},async execute(n,s){z(s);let o=B(s),t=await Re(e,n,o);await ze(e,t,o);let r=e.clientFor($),p;if(n.loanId!==void 0&&n.loanId!==null&&String(n.loanId).trim()!=="")p=pe(n.loanId,"loanId");else{let k=sn(n);if(k.length>0){let D=on(k,t);D!==null&&(p=BigInt(D))}}let d;if(p!==void 0){let k=await r.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[p]}),D=Ce(p,k);if(D.agentId!==t)throw new a(`Loan ${p} belongs to agent ${D.agentId}, not agent ${t}. Recover loan IDs from the Borrowed receipt or loansOf(agentId), never global loanCount().`);if(D.status!==1)throw new a(`Loan ${p} for agent ${t} is not active (status=${D.status}).`);d=D}else{let k=await r.readContract({address:c.pool,abi:S,functionName:"loansOf",args:[t]});if(k.length===0)throw new a(`ERC-8004 agent ${t} has no recorded loans on Priors CreditPoolV2.`);let M=(await Promise.all(k.map(async W=>{let se=await r.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[W]});return Ce(W,se)}))).filter(W=>W.agentId===t&&W.status===1);if(M.length===0)throw new a(`ERC-8004 agent ${t} has no active loans to repay.`);d=M[M.length-1]}let w=d.principal+d.fee,b=n.maxDue!==void 0?ee(n.maxDue):w;if(b<w)throw new a(`Provided maxDue ${b} is below the exact fixed loan debt ${w} USDG base units (principal ${d.principal} + fixed fee ${d.fee}).`);if(b>w)throw new a(`Provided maxDue ${b} is above the exact fixed loan debt ${w} USDG base units. Use the fixed debt or omit maxDue.`);let m=e.approval(c.usdg,c.pool,w.toString(),$),h=e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"repay",args:[d.loanId,t,b]}),value:"0",chainId:$,description:`Repay fixed debt ${w} USDG base units (principal ${d.principal} + fee ${d.fee}) for loan ${d.loanId} (agent ${t}).`}),I=[m,h],l=await e.preview(I,o),v=e.formatAmount(w.toString(),N),P=e.formatAmount(d.principal.toString(),N),_=e.formatAmount(d.fee.toString(),N),F=`Approve and repay ${v} USDG (${w} base units: ${P} USDG principal + ${_} USDG fixed fee) for Priors loan ${d.loanId} (agent ${t}).`;return{txs:I,summary:te(e,F,l.changes)}}},R={name:"priors_status",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Optional ERC-8004 agent ID to inspect on CreditPoolV2, PriorsLens, and StockVault."},includeApiCheck:{type:"boolean",description:"Optional flag to query https://priors.trade/api/check for supplemental off-chain metadata."}}},async execute(n,s){z(s);let o=B(s),t=e.clientFor($),[r,p,d,w]=await Promise.all([t.readContract({address:c.pool,abi:S,functionName:"shares",args:[o]}),t.readContract({address:c.pool,abi:S,functionName:"lastDepositAt",args:[o]}),t.getBlock(),t.readContract({address:c.stockVault,abi:At,functionName:"assetList"})]),b=r>0n?await t.readContract({address:c.pool,abi:S,functionName:"convertToAssets",args:[r]}):0n,m=r>0n&&p>0n&&d.timestamp<p+He,h=m?b*bt/wt:0n,I=b-h,l=null;if(n.agentId!==void 0&&n.agentId!==null&&String(n.agentId).trim()!=="")l=pe(n.agentId,"agentId");else{let q=await _e(e,o);q.length>0&&(l=q[0])}let v=null,P=!1,_=[],F=null,k=null,D=null,M=null,W=null,se=null,j=`This wallet owns no ERC-8004 agent identity. ${Ye}`;if(l!==null){let[q,K,ae,oe,Lt,xt,Be,Ne,Le]=await Promise.all([t.readContract({address:c.lens,abi:St,functionName:"score",args:[l]}),t.readContract({address:x,abi:E,functionName:"firstLined",args:[l]}),t.readContract({address:x,abi:E,functionName:"agentId"}),t.readContract({address:x,abi:E,functionName:"rules"}),t.readContract({address:x,abi:E,functionName:"epochRoom"}),t.readContract({address:C,abi:U,functionName:"bonds",args:[l]}),t.readContract({address:C,abi:U,functionName:"amount"}),t.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[l]}),t.readContract({address:C,abi:U,functionName:"releasable",args:[l]})]),[Ot,Ut,Et,Gt,Vt,Ft]=await Promise.all([t.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[l]}),t.readContract({address:c.pool,abi:S,functionName:"loansOf",args:[l]}),t.readContract({address:c.lens,abi:St,functionName:"available",args:[l]}),t.readContract({address:c.stockVault,abi:At,functionName:"borrowRoom",args:[l]}),t.readContract({address:c.pool,abi:S,functionName:"delegateOf",args:[l]}),t.readContract({address:c.pool,abi:S,functionName:"isController",args:[l,o]})]),xe=await De(e,l),Mt=B(Vt),Ze=Ft,y=we(Ot),Se=y.delegatedIn>y.principalOut?y.delegatedIn-y.principalOut:0n;P=y.enrolled&&!y.isRoot&&!y.defaulted&&!y.frozen&&y.sponsor>0n&&y.delegatedIn>0n,F=Et.toString(),k=Gt.toString();let qt=await Promise.all(Ut.map(async T=>{let de=await t.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[T]});return Ce(T,de)}));for(let T of qt)if(T.agentId===l&&T.status===1){let de=T.principal+T.fee;_.push({loanId:T.loanId.toString(),agentId:T.agentId.toString(),sponsorId:T.sponsorId.toString(),principal:T.principal.toString(),fee:T.fee.toString(),due:de.toString(),dueAt:T.dueAt.toString(),issuedAt:T.issuedAt.toString(),owner:T.owner,token:ce})}v={agentId:l.toString(),owner:xe,delegate:Mt,isAuthorizedController:Ze,enrolled:y.enrolled,isRoot:y.isRoot,defaulted:y.defaulted,frozen:y.frozen,sponsorId:y.sponsor.toString(),delegatedIn:y.delegatedIn.toString(),delegatedOut:y.delegatedOut.toString(),principalOut:y.principalOut.toString(),availableCapacity:Se.toString(),activeLoansCount:y.activeLoans.toString(),loansRepaid:y.loansRepaid.toString(),volumeRepaid:y.volumeRepaid.toString(),feesPaid:y.feesPaid.toString(),importedFromV1:y.importedFromV1,qualifiedRepaid:y.qualifiedRepaid.toString(),dollarSecondsRepaid:y.dollarSecondsRepaid.toString()};let Ae=BigInt(ae),Oe=K===!0,Q=ye(xt),ie=Q.depositor!==Je,ve=ie&&V(Q.depositor,o),Ke=Pt(y,Oe),Ue=V(xe,o);D={onchain:BigInt(q).toString(),scale:"0-1000",source:`CreditLensV2.score(${l}) at ${c.lens}, the score the pool computes on chain`,scoreV2:null},M={open:y.sponsor!==0n&&y.delegatedIn>0n,amount:y.delegatedIn.toString(),drawn:y.principalOut.toString(),available:Se.toString(),sponsorId:y.sponsor.toString(),backer:y.sponsor===0n?null:y.sponsor===Ae?`Priors' treasury v4 (root #${Ae})`:`root #${y.sponsor}`,token:ce},W={contract:C,posted:ie,depositor:ie?Q.depositor:null,postedByWallet:ve,postedAt:ie?Q.at.toString():null,amount:(ie?Q.amount:BigInt(Be)).toString(),releasable:ie&&Le===!0,releaseAt:ie?BigInt(Ne).toString():null,rule:"Back to its depositor once the agent holds no line and has no loan open, from 4 days after it was posted (close a line first with priors_close_line); a default forfeits it to Priors' Safe."},se={eligible:Ue&&!Ke,firstLined:Oe,lineAmount:BigInt(oe[1]).toString(),bondAmount:BigInt(Be).toString(),treasuryRoot:Ae.toString(),treasuryRoomThisWeek:BigInt(Lt).toString(),note:"Not instant: Priors' invite bot decides each invite, and the treasury caps new lines each week."};let fe=_.map(T=>({id:String(T.loanId),dueAt:BigInt(String(T.dueAt))})).sort((T,de)=>T.dueAt<de.dueAt?-1:T.dueAt>de.dueAt?1:0);y.defaulted?j=`Agent #${l} defaulted; Priors never lends to it again${ve?" and its bond is forfeited":""}.`:!Ze&&!Ue?j=`This wallet does not control agent #${l} on CreditPoolV2 (owner ${xe}); act from its owner or delegate.`:fe.length?j=`Repay loan ${fe[0].id} with priors_repay before it is due at ${G(fe[0].dueAt)}${fe.length>1?` (${fe.length} loans open)`:""}.`:P&&Se>=We?j=`Borrow with priors_borrow (5 USDG minimum, up to ${A(Se)}; the fee is pro-rated by term); Priors counts loans held 7 days or more toward the score.`:!Ke&&Ue?j=ve?`Call priors_starter_line again: the ${A(Q.amount)} bond is posted, and it goes on with the invite bot's ownership proof and the invite's redemption${Le===!0?", or priors_release_bond returns the bond":""}.`:`Call priors_starter_line: a refundable ${A(BigInt(Be))} bond, an invite from Priors' invite bot and your pool consent open a ${A(BigInt(oe[1]))} line from Priors' treasury (each transaction and signature is confirmed).`:ve?j=Le===!0?`Release the ${A(Q.amount)} invite bond with priors_release_bond.`:y.delegatedIn>0n?`The line is open with nothing to draw; to take the bond back, close it with priors_close_line, then priors_release_bond from ${G(BigInt(Ne))}.`:`The ${A(Q.amount)} invite bond comes back with priors_release_bond from ${G(BigInt(Ne))}.`:j=`Agent #${l} has a Priors record but no line to draw now; ${It(e,y,Ae,Oe)}.`}let $e=null;if(n.includeApiCheck){let q=l!==null?`agent=${l.toString()}`:`address=${o}`,K=await tt(e.http,`${Kt}?${q}`,{method:"GET"},Y),ae=Array.isArray(K.agents)?K.agents.find(oe=>Y(oe)&&String(oe.agentId)===String(l)):void 0;D&&Y(ae)&&(D.scoreV2=ae.scoreV2??null),$e={...K,grantsPoolControl:!1,controlRule:"Off-chain /api/check identity or paymentWallet match never grants CreditPoolV2 control; on-chain isController(agentId, wallet) must authorize the caller; stale delegates do not qualify."}}return{chainId:$,blockNumber:d.number?.toString()??null,blockTimestamp:d.timestamp.toString(),wallet:o,token:ce,contracts:c,lender:{shares:r.toString(),grossAssets:b.toString(),earlyExitFeeAssets:h.toString(),netWithdrawAssets:I.toString(),lastDepositAt:p.toString(),withinMinHoldWindow:m,minHoldSeconds:He.toString()},hasFundedLine:P,agentId:l!==null?l.toString():null,nextStep:j,score:D,line:M,bond:W,starterLine:se,agent:v,activeLoans:_,lens:{address:c.lens,available:F,caveat:"PriorsLens.available(agentId) is a status capacity hint for already-funded lines; backer hooks may still refuse borrows."},stockVault:{address:c.stockVault,borrowRoom:k,onchainAssetCount:w.length,hostedMcpStockCount:35,extraNonStockAsset:B(Qt),zeroCapAssets:en.map(q=>B(q)),caveat:"Use priors_stock_assets and priors_stock_asset_state for current collateral rules, then priors_stock_open. This summary is an observed asset-count snapshot, not a fixed allowlist; live caps, lending holds and prices control admission."},apiCheck:$e,limitations:["Borrowing and repayment require a sponsor-backed ERC-8004 credit line (enrolled && !isRoot && sponsor != 0) authorized on-chain by isController(agentId, wallet).","Priors line routes are exposed by priors_line_options and priors_capabilities: treasury starter, V5 move/raise, direct sponsor, stock and owner PRIORS backing. Ethos execution uses Priors own owner workflow because its worker supplies no unsigned final transaction.","score.onchain is the pool's on-chain score (CreditLensV2); score.scoreV2 is Priors Score v2 from /api/check, present only with includeApiCheck.","Loan debt is the principal plus the origination fee the pool quotes for the term. The fee is pro-rated by term, not flat (1666 base units for 5 USDG over 1 day, observed live 2026-10-31; priors_borrow shows the exact quote), and is fixed once the loan opens: variable interest is never invented, and early repayment refunds none of it.","Loan IDs are recovered from decoded Borrowed receipts or per-agent loansOf(agentId), never global loanCount().","Historical archive event queries and zero-position StockVault lines on public RPCs remain subject to archive retention and live backer state."]}}},A=n=>`${e.formatAmount(n.toString(),N)} USDG`;function L(n){let s=V(n.bond.depositor,n.owner)&&n.bond.amount>0n?n.bond.amount:n.bondAmount;return`Bond first: ${A(s)} is locked in Priors' InviteBond for at least ${n.unusedAfter} seconds (${Number(n.unusedAfter)/86400} days) after posting${n.releaseAt>0n?`; unusedReleaseAt is ${G(n.releaseAt)}`:"; the exact release time is read after posting"}. Release requires no line and no open loan; default can forfeit the bond. Invites are not guaranteed. The credit score can lag qualifying repayments. `}function H(n,s,o){if(!V(o.owner,s))throw new a(`This wallet (${s}) does not own ERC-8004 agent ${n} (its owner is ${o.owner}). The bond, the ownership proof and the pool consent are the owner's. Nothing was signed.`);if(o.root!==Ie)throw new a(`TreasurySponsorV4 (${x}) answers root #${o.root}, not the pinned #${Ie}. Nothing was signed; update Oak.`);if(Pt(o.agent,o.firstLined))throw new a(`Agent #${n} already has a Priors record, so priors_starter_line posts no bond and signs nothing: ${It(e,o.agent,o.root,o.firstLined)}; ${o.agent.loansRepaid} loan(s) repaid. The starter line is only for an identity with no record; priors_status shows this one.`)}let ne="stays posted in InviteBond";function O(n){let s=n.agent.delegatedIn>0n?`with a line open it comes back only after priors_close_line (no loan open), then priors_release_bond from ${G(n.releaseAt)} at the earliest`:`while the agent holds no line it comes back with priors_release_bond from ${G(n.releaseAt)} (${Number(n.unusedAfter)/86400} days after it was posted)`;return`The ${A(n.bond.amount>0n?n.bond.amount:n.bondAmount)} bond ${ne} (${C}), posted from this wallet; ${s}, and priors_starter_line never posts a second bond.`}async function J(n,s,o){try{return await o()}catch(t){let r=t instanceof a?t.message:e.plainError(t);if(r.includes(ne)||n===void 0||!/^[0-9]{1,78}$/.test(n))throw t;let p;try{let d=await he(e,BigInt(n),s);p=V(d.bond.depositor,s)?O(d):""}catch{p=`If the bond transactions mined, the invite bond ${ne} (${C}) remains locked until its on-chain release conditions are met; priors_status shows the exact amount and time (its state could not be read just now).`}throw p?new a(`${r} ${p}`):t}}async function ge(n,s,o){let t=at(await Xe(e,{agentId:n}),{agentId:n,owner:s,now:ue()});if(!t.ok&&t.refused)throw new a(`Priors' invite bot gave no ownership proof to sign for agent #${n}: ${be(t.why)}. Nothing was signed. ${o}`.trim());if(!t.ok)throw new a(`Not signed: the invite bot's answer for agent #${n} is not one Oak signs: ${t.why}. Oak signs only the bot's own start-page text, rebuilt locally for this agent and this wallet. ${o}`.trim());if(t.exp-ue()<120)throw new a(`Not signed: the invite bot's proof for agent #${n} expires in under 2 minutes; call priors_starter_line again for a new one. ${o}`.trim());return t}function Z(n,s,o,t){return{steps:[{kind:"message",message:o.message}],continuation:{stage:"proof",wallet:s,chainId:$,agentId:n,n:o.n,exp:o.exp},summary:`${L(t)}Priors starter line for ERC-8004 agent ${n}, step 2 of 3: sign Priors' invite-bot ownership proof. It is a message signature (EIP-191) only: it sends no transaction and moves no funds. The text is the bot's own form, rebuilt locally for agent #${n} and this wallet, request ${o.n}, expiring ${G(o.exp)}. Oak then sends the signature to ${me}, and the bot decides the invite. ${O(t)}`}}function re(n,s,o){if(n.chainId!==$||typeof n.wallet!="string"||!V(n.wallet,s)||typeof n.agentId!="string"||!/^[1-9][0-9]{0,29}$/.test(n.agentId))throw new a("Priors starter-line continuation does not match this wallet or chain 4663; start priors_starter_line again.");if(o.agentId!==void 0&&String(o.agentId)!==n.agentId)throw new a("Priors starter-line continuation is for another agent; start priors_starter_line again.");return BigInt(n.agentId)}async function Te(n,s){let o;if(n.agentId!==void 0&&n.agentId!==null&&String(n.agentId).trim()!=="")o=pe(n.agentId,"agentId");else{let l=await _e(e,s);if(!l.length)throw new a(`Priors' starter line needs an ERC-8004 agent identity, and this wallet owns none. ${Ye}`);o=l[0]}let t=await he(e,o,s);H(o,s,t);let r=o.toString(),p=V(t.bond.depositor,s);if(!p){if(t.usdg<t.bondAmount)throw new a(`This wallet holds ${A(t.usdg)} on Robinhood Chain, and Priors' treasury invite asks a ${A(t.bondAmount)} bond first (InviteBond ${C}), posted from this wallet. Nothing was signed: add USDG, then call priors_starter_line again.`);if(t.epochRoom<t.firstLineAmount)return{summary:`${L(t)}Not submitted. Priors' treasury has ${A(t.epochRoom)} of room left this week and a first line is ${A(t.firstLineAmount)}, so priors_starter_line posted no bond and signed nothing. The treasury caps new lines each week: ask again next week.`,starterLine:{agentId:r,open:!1,reason:"room",epochRoom:t.epochRoom.toString()}};let l=await Xe(e,{check:!0,owner:s.toLowerCase()});if(l.check!==!0)throw new a("Priors' invite bot did not answer its check, so whether an invite is open cannot be told. Nothing was signed.");if(l.ok!==!0)throw new a(`Whether an automatic invite is open could not be told: Priors' invite bot says ${be(l.error)}. Nothing was signed; try again later.`);if(l.open!==!0){let v=typeof l.reason=="string"?l.reason.replace(/[^a-z-]/g,"").slice(0,24):"",P=typeof l.reopensAt=="number"&&Number.isSafeInteger(l.reopensAt)&&l.reopensAt>0?l.reopensAt:null;return{summary:`${L(t)}Not submitted. No automatic invite is open to this wallet right now, so priors_starter_line posted no bond and signed nothing. Priors' invite bot answers: closed, reason ${Ee(v||"none given")}${P?`, reopens ${G(P)}`:""}. ${dt({...l,reason:v})} Priors lists its other ways to a first line (the Ethos lane, a stock line, the owner's $PRIORS stake) at https://priors.trade/skill.md.`,starterLine:{agentId:r,open:!1,reason:v||null,reopensAt:P}}}}let d=await ge(r,s,p?O(t):"");if(p)return Z(r,s,d,t);let w=[e.approval(c.usdg,C,t.bondAmount.toString(),$),e.unsignedTx({to:C,data:X({abi:U,functionName:"deposit",args:[o]}),value:"0",chainId:$,description:`Post the ${t.bondAmount} USDG base-unit Priors invite bond for agent ${r} in InviteBond (${C}).`})],b=await e.preview(w,s),m=t.bond.depositor!==Je?` This deposit replaces the bond ${t.bond.depositor} posted for this agent; InviteBond returns that bond to it in the same transaction.`:"",h=`${L(t)}Priors starter line for ERC-8004 agent ${r}, step 1 of 3: approve exactly ${A(t.bondAmount)} to Priors' InviteBond (${C}) and post it as the agent's refundable invite bond (InviteBond.deposit).${m} Priors' invite bot says an automatic invite is open now and gave the ownership proof to sign next. Step 2 signs that proof (a message, no transaction); step 3 signs your pool consent and redeems the invite (TreasurySponsorV4.firstLine, ${x}) for a ${A(t.firstLineAmount)} line from Priors' treasury (root #${t.root}). The invite is the bot's decision, not a promise: if it refuses, or any later step fails, the bond stays posted and comes back with priors_release_bond after the on-chain lock and release conditions are met. With a line, the bond comes back only once the line is closed with no loan open (priors_close_line, then priors_release_bond); a default forfeits it to Priors' Safe.`;return{steps:w.map(l=>({kind:"tx",tx:l})),continuation:{stage:"bond",wallet:s,chainId:$,agentId:r,n:d.n,exp:d.exp},summary:te(e,h,b.changes)}}async function Rt(n,s,o){let t=await he(e,n,s);H(n,s,t);let r=n.toString();if(!V(t.bond.depositor,s))throw new a(`The invite bond for agent #${r} is not on chain from this wallet, so nothing more was signed. Check the deposit transaction, then call priors_starter_line again.`);return typeof o.n=="string"&&Ve.test(o.n)&&typeof o.exp=="number"&&Number.isSafeInteger(o.exp)&&o.exp-ue()>=300?Z(r,s,{n:o.n,exp:o.exp,message:Me(r,o.n,o.exp)},t):Z(r,s,await ge(r,s,O(t)),t)}async function _t(n,s,o,t){let r=n.toString();if(typeof o.n!="string"||!Ve.test(o.n)||typeof o.exp!="number"||!Number.isSafeInteger(o.exp))throw new a("Invalid Priors starter-line proof continuation; start priors_starter_line again.");if(typeof t!="string"||!/^0x[0-9a-fA-F]{130}$/.test(t))throw new a("Provide this wallet's signature of the invite bot's ownership proof.");if(o.exp<=ue())throw new a(`The invite bot's proof for agent #${r} expired before it reached the bot; nothing was sent to it. Call priors_starter_line again for a fresh proof (the bond is not posted again).`);let p=Me(r,o.n,o.exp);if(!V(await Yt({message:p,signature:t}),s))throw new a("The ownership-proof signature is not this wallet's; nothing was sent to the invite bot.");let d=await he(e,n,s);if(H(n,s,d),!V(d.bond.depositor,s))throw new a(`The invite bond for agent #${r} is not on chain from this wallet; nothing was sent to the invite bot. Call priors_starter_line again.`);let w=await Xe(e,{n:o.n,signature:t});if(w.ok!==!0)throw new a(`Priors' invite bot gave no invite for agent #${r}: ${be(w.error)}. ${O(d)}`);if(typeof w.code!="string")throw new a(`Priors' invite bot gave no invite for agent #${r}${w.reason?`: ${be(w.reason)}`:""}${typeof w.decided=="string"?` (its decision: ${be(w.decided)})`:""}. ${O(d)}`);let b=qe(w.code,r,ue()+60);if(!b.ok)throw new a(`Priors' invite bot's code for agent #${r} is not one Oak redeems: ${b.why}. Nothing more was signed. ${O(d)}`);let m=e.clientFor($),h=await m.readContract({address:x,abi:E,functionName:"inviteDigest",args:[n,b.expiry]});if(h.toLowerCase()!==st(n,b.expiry).toLowerCase())throw new a("TreasurySponsorV4's invite digest differs from its pinned EIP-712 domain; nothing more was signed. Update Oak.");let I=await Xt({hash:h,signature:b.signature}),[l,v]=await Promise.all([m.readContract({address:x,abi:E,functionName:"inviters",args:[I]}),m.readContract({address:x,abi:E,functionName:"inviteUsed",args:[h]})]);if(l!==!0)throw new a(`Priors' invite for agent #${r} was signed by ${I}, which TreasurySponsorV4 does not name an inviter, so the treasury would refuse it. Nothing more was signed. ${O(d)}`);if(v===!0)throw new a(`Priors' invite for agent #${r} was already used. Nothing more was signed. ${O(d)}`);let[P,_]=await Promise.all([m.readContract({address:c.pool,abi:S,functionName:"nonces",args:[n]}),m.getBlock()]),F=_.timestamp+BigInt(it),k=Fe({agentId:r,owner:s,nonce:P.toString(),deadline:F.toString()}),D=await m.readContract({address:c.pool,abi:S,functionName:"consentDigest",args:[{agentId:n,sponsorId:d.root,owner:s,maxPremiumBps:0n,nonce:P,deadline:F}]});if(D.toLowerCase()!==rt(k).toLowerCase())throw new a(`The pool's consentDigest (${D}) differs from the consent Oak builds for CreditPoolV2 (${c.pool}), so the pool would refuse it. Nothing more was signed. ${O(d)}`);return{steps:[{kind:"typedData",request:k}],continuation:{stage:"consent",wallet:s,chainId:$,agentId:r,invite:w.code,request:k},summary:`Priors starter line for ERC-8004 agent ${r}, step 3 of 3: Priors' invite bot gave an invite (signed by ${I}, an inviter TreasurySponsorV4 names; it expires ${G(b.expiry)}). Sign your pool consent (EIP-712 "Priors Credit" version 2 on CreditPoolV2 ${c.pool}): it lets Priors' treasury (root #${d.root}) back a line for agent #${r} with premium 0, nonce ${P}, valid until ${G(F)}. A transaction redeeming the invite (TreasurySponsorV4.firstLine) follows for your confirmation. ${O(d)}`}}async function kt(n,s,o,t){let r=n.toString();if(typeof t!="string"||!/^0x[0-9a-fA-F]{130}$/.test(t))throw new a("Provide this wallet's signature of the Priors pool consent.");let p=qe(o.invite,r,ue()+60);if(!p.ok)throw new a(`The invite for agent #${r} is not one Oak redeems now: ${p.why}. Call priors_starter_line again for a new one.`);let d=Y(o.request)&&Y(o.request.message)?o.request.message:void 0;if(!d||typeof d.nonce!="string"||!/^[0-9]{1,78}$/.test(d.nonce)||typeof d.deadline!="string"||!/^[0-9]{1,20}$/.test(d.deadline))throw new a("Invalid Priors starter-line consent continuation; start priors_starter_line again.");let w=Fe({agentId:r,owner:s,nonce:d.nonce,deadline:d.deadline});if(!V(await Zt({...w,signature:t}),s))throw new a("The pool-consent signature is not this wallet's for the consent Oak built; nothing was offered.");let b=await he(e,n,s);H(n,s,b);let m=e.clientFor($),[h,I]=await Promise.all([m.readContract({address:c.pool,abi:S,functionName:"nonces",args:[n]}),m.getBlock()]);if(h.toString()!==d.nonce)throw new a(`Agent #${r}'s consent nonce moved on chain since it was signed; nothing was offered. Call priors_starter_line again.`);if(I.timestamp>=BigInt(d.deadline))throw new a(`The pool consent for agent #${r} expired at ${G(BigInt(d.deadline))}; nothing was offered. Call priors_starter_line again.`);let l={agentId:n,sponsorId:Ie,owner:s,maxPremiumBps:0n,nonce:h,deadline:BigInt(d.deadline)},v=[n,p.expiry,p.signature,l,t];try{await m.simulateContract({address:x,abi:E,functionName:"firstLine",args:v,account:s})}catch(k){throw new a(`TreasurySponsorV4.firstLine for agent #${r} would be refused: ${an(e,k)} Nothing was offered. ${O(b)}`)}let P=e.unsignedTx({to:x,data:X({abi:E,functionName:"firstLine",args:v}),value:"0",chainId:$,description:`Redeem Priors' invite for agent ${r}: TreasurySponsorV4.firstLine opens a ${b.firstLineAmount} USDG base-unit line from root ${b.root} with the owner's consent.`}),_=await e.preview([P],s),F=`Redeem agent #${r}'s Priors invite: TreasurySponsorV4.firstLine (${x}) opens a ${A(b.firstLineAmount)} line from Priors' treasury (root #${b.root}) with your signed consent. No USDG moves in this transaction. Then priors_status shows the line and priors_borrow draws it (5 USDG minimum; the fee is pro-rated by term; Priors counts loans held 7 days or more toward the score). The ${A(b.bondAmount)} bond stays in InviteBond until the line is closed with no loan open (priors_close_line, then priors_release_bond, from ${G(b.releaseAt)} at the earliest); a default forfeits it.`;return{txs:[P],summary:te(e,F,_.changes)}}let Dt={name:"priors_starter_line",inputSchema:{description:"Bond first: the launch bond is 5 USDG, locked at least 4 days. The first result reads amount(), unusedAfter() and unusedReleaseAt(agentId) for current terms before any approval. Invites are not guaranteed; the credit score can lag. Release needs no line or open loan; default can forfeit the bond.",type:"object",additionalProperties:!1,properties:{agentId:Pe("ERC-8004 agent ID this wallet owns, with no Priors record yet (default: the first identity this wallet owns)."),continuation:{type:"object"},signature:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$"}}},async execute(n,s){z(s);let o=B(s);if(n.continuation===void 0){if(n.signature!==void 0)throw new a("A signature needs its Priors starter-line continuation; start priors_starter_line again.");return J(typeof n.agentId=="string"?n.agentId:void 0,o,()=>Te(n,o))}if(!Y(n.continuation))throw new a("Invalid Priors starter-line continuation; start priors_starter_line again.");let t=n.continuation,r=re(t,o,n),p=d=>J(r.toString(),o,d);if(t.stage==="bond"){if(n.signature!==void 0)throw new a("The bond stage takes no signature; start priors_starter_line again.");return p(()=>Rt(r,o,t))}if(t.stage==="proof")return p(()=>_t(r,o,t,n.signature));if(t.stage==="consent")return p(()=>kt(r,o,t,n.signature));throw new a("Unknown Priors starter-line stage; start priors_starter_line again.")}},Tt={name:"priors_close_line",inputSchema:{type:"object",properties:{agentId:Pe("ERC-8004 agent ID whose Priors line to close (default: the first identity this wallet owns).")}},async execute(n,s){z(s);let o=B(s),t=await Re(e,n,o);await ze(e,t,o);let r=e.clientFor($),[p,d,w,b]=await Promise.all([r.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[t]}),r.readContract({address:C,abi:U,functionName:"bonds",args:[t]}),r.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[t]}),r.readContract({address:x,abi:E,functionName:"agentId"})]),m=we(p);if(m.sponsor===0n)throw new a(`Agent #${t} has no Priors line to close (no sponsor on CreditPoolV2).`);if(m.activeLoans>0n)throw new a(`Agent #${t} has ${m.activeLoans} loan(s) open; repay them with priors_repay first. The pool's leave refuses while a loan is open.`);let h=ye(d),I=m.sponsor===BigInt(b),l=e.unsignedTx({to:c.pool,data:X({abi:S,functionName:"leave",args:[t]}),value:"0",chainId:$,description:`Close agent ${t}'s Priors line on CreditPoolV2 (leave): the ${m.delegatedIn} USDG base-unit line returns to root ${m.sponsor}.`}),v=await e.preview([l],o),P=V(h.depositor,o)?` Its ${A(h.amount)} invite bond can then come back with priors_release_bond from ${G(w)} (4 days after it was posted).`:"",_=`Close agent #${t}'s Priors line (CreditPoolV2.leave, ${c.pool}): the whole ${A(m.delegatedIn)} line goes back to its backer (${I?`Priors' treasury, root #${b}`:`root #${m.sponsor}`}) and the agent can no longer borrow on it. This does not reopen: ${I?`priors_starter_line opens no second treasury line for an agent with a Priors record; another needs a person at ${Ge}.`:"a new line needs a backer's new consent."}${P} No USDG moves in this transaction.`;return{txs:[l],summary:te(e,_,v.changes)}}},Bt={name:"priors_release_bond",inputSchema:{type:"object",properties:{agentId:Pe("ERC-8004 agent ID whose InviteBond bond this wallet posted (default: the first identity this wallet owns).")}},async execute(n,s){z(s);let o=B(s),t=await Re(e,n,o),r=e.clientFor($),[p,d,w,b,m]=await Promise.all([r.readContract({address:C,abi:U,functionName:"bonds",args:[t]}),r.readContract({address:C,abi:U,functionName:"releasable",args:[t]}),r.readContract({address:C,abi:U,functionName:"unusedReleaseAt",args:[t]}),r.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[t]}),r.getBlock()]),h=ye(p);if(h.depositor===Je)throw new a(`Agent #${t} has no bond in Priors' InviteBond (${C}).`);if(!V(h.depositor,o))throw new a(`Agent #${t}'s InviteBond bond was posted by ${h.depositor}, not this wallet, and InviteBond.release pays the depositor. Oak releases only a bond this wallet posted.`);if(d!==!0){let P=we(b),_=P.defaulted?"the agent defaulted, so the bond is forfeited to Priors' Safe (InviteBond.slash)":P.activeLoans>0n?`the agent has ${P.activeLoans} loan(s) open: repay with priors_repay, close the line with priors_close_line, then release`:P.delegatedIn>0n?`the agent still holds a ${A(P.delegatedIn)} line: close it with priors_close_line (no loan may be open), then release`:m.timestamp<w?`it comes back 4 days after it was posted, from ${G(w)}`:"InviteBond does not release it yet";throw new a(`Agent #${t}'s ${A(h.amount)} invite bond cannot be released now: ${_}. Nothing was signed.`)}let I=e.unsignedTx({to:C,data:X({abi:U,functionName:"release",args:[t]}),value:"0",chainId:$,description:`Release agent ${t}'s ${h.amount} USDG base-unit Priors invite bond from InviteBond (${C}) to its depositor ${h.depositor}.`}),l=await e.preview([I],o),v=`Release agent #${t}'s ${A(h.amount)} invite bond from Priors' InviteBond (${C}): InviteBond.release returns it to its depositor, this wallet (${o}).`;return{txs:[I],summary:te(e,v,l.changes)}}};async function Nt(n){z(n);let s=B(n),o=e.clientFor($),[t,r]=await Promise.all([o.readContract({address:c.pool,abi:S,functionName:"shares",args:[s]}),_e(e,s)]),p=[];if(t>0n){let d=await o.readContract({address:c.pool,abi:S,functionName:"convertToAssets",args:[t]});p.push({module:"priors",id:`priors:lender:${s.toLowerCase()}`,chainId:$,assets:[{token:ce,amount:d.toString()}],description:`Priors CreditPoolV2 lender position (${t} shares = ${e.formatAmount(d.toString(),N)} USDG gross).`})}for(let d of r){let w=await o.readContract({address:c.pool,abi:S,functionName:"loansOf",args:[d]}),b=await Promise.all(w.map(async h=>{let I=await o.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[h]});return Ce(h,I)}));for(let h of b)if(h.agentId===d&&h.status===1){let I=h.principal+h.fee;p.push({module:"priors",id:`priors:loan:${h.loanId.toString()}`,chainId:$,assets:[{token:ce,amount:I.toString()}],description:`Priors CreditPoolV2 active loan ${h.loanId} for agent ${d} (fixed due ${e.formatAmount(I.toString(),N)} USDG = ${h.principal} principal + ${h.fee} fee).`})}let m=ye(await o.readContract({address:C,abi:U,functionName:"bonds",args:[d]}));m.amount>0n&&V(m.depositor,s)&&p.push({module:"priors",id:`priors:bond:${d.toString()}`,chainId:$,assets:[{token:ce,amount:m.amount.toString()}],description:`Priors invite bond for agent ${d} in InviteBond (${C}): ${A(m.amount)}, back with priors_release_bond once the agent holds no line and no loan, from 4 days after posting; a default forfeits it.`})}return p}return{tools:[i,g,u,f,R,Dt,Tt,Bt],positions:Nt}},ln=e=>{let i=dn(e),g=[i,lt(e),ct(e),pt(e),gt(e),ft(e),mt(e),ut()];return{...i,tools:g.flatMap(u=>u.tools)}},_n=e=>Qe("priors",[ln(e)]);export{Kt as a,He as b,bt as c,wt as d,We as e,yt as f,je as g,$t as h,c as i,ce as j,on as k,ln as l,_n as m};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as f}from"./
|
|
1
|
+
import{b as f}from"./AMICUXS6.js";import{a as p}from"./6IM6A5VA.js";import{a as u}from"./G6HCV67X.js";import{a as r}from"./5YS5V2LK.js";import{encodeFunctionData as A,getAddress as w,parseAbi as T,parseAbiItem as F}from"viem";var R=[["setOwner(address newOwner)","owner"],["setCurator(address newCurator)","owner"],["setIsSentinel(address account,bool enabled)","owner"],["setName(string name)","owner"],["setSymbol(string symbol)","owner"],["setIsAllocator(address account,bool enabled)","timelock"],["setReceiveSharesGate(address gate)","timelock"],["setSendSharesGate(address gate)","timelock"],["setReceiveAssetsGate(address gate)","timelock"],["setSendAssetsGate(address gate)","timelock"],["setAdapterRegistry(address registry)","timelock"],["addAdapter(address adapter)","timelock"],["removeAdapter(address adapter)","timelock"],["increaseTimelock(bytes4 selector,uint256 duration)","timelock"],["decreaseTimelock(bytes4 selector,uint256 duration)","timelock"],["abdicate(bytes4 selector)","timelock"],["setPerformanceFee(uint256 fee)","timelock"],["setManagementFee(uint256 fee)","timelock"],["setPerformanceFeeRecipient(address recipient)","timelock"],["setManagementFeeRecipient(address recipient)","timelock"],["increaseAbsoluteCap(bytes idData,uint256 cap)","timelock"],["increaseRelativeCap(bytes idData,uint256 cap)","timelock"],["decreaseAbsoluteCap(bytes idData,uint256 cap)","curatorOrSentinel"],["decreaseRelativeCap(bytes idData,uint256 cap)","curatorOrSentinel"],["setForceDeallocatePenalty(address adapter,uint256 penalty)","timelock"],["allocate(address adapter,bytes data,uint256 assets)","allocator"],["deallocate(address adapter,bytes data,uint256 assets)","allocatorOrSentinel"],["setLiquidityAdapterAndData(address adapter,bytes data)","allocator"],["setMaxRate(uint256 rate)","allocator"],["accrueInterest()","any"]],S=R.map(([a,t])=>({abi:F(`function ${a}`),authority:t})),x=T(["function asset() view returns (address)","function owner() view returns (address)","function curator() view returns (address)","function isSentinel(address) view returns (bool)","function isAllocator(address) view returns (bool)","function executableAt(bytes) view returns (uint256)","function abdicated(bytes4) view returns (bool)","function submit(bytes data)","function revoke(bytes data)"]);function M(a,t){if(a==="bool"){if(typeof t!="boolean")throw new r("Boolean operation values must be booleans.");return t}if(typeof t!="string")throw new r("All address, byte, text and integer operation values must be strings.");if(a==="address")return p(t),w(t);if(a==="uint256"){if(!/^\d+$/.test(t)||BigInt(t)>=1n<<256n)throw new r("Integer operation values must be uint256 decimal base-unit strings.");return BigInt(t)}if((a==="bytes"||a==="bytes4")&&!(a==="bytes4"?/^0x[0-9a-f]{8}$/i:/^0x(?:[0-9a-f]{2})*$/i).test(t))throw new r("Invalid hexadecimal operation bytes.");return t}function E(a,t,m,O){return{name:t,inputSchema:{type:"object",additionalProperties:!1,required:["operation","values"],properties:{operation:{type:"string",enum:S.map(i=>i.abi.name)},values:{type:"array",maxItems:3,items:{oneOf:[{type:"string"},{type:"boolean"}]},description:"Ordered ABI values. Integers are decimal base-unit strings; addresses and bytes are explicit strings."},mode:{enum:["call","submit","revoke"],default:"call",description:"Submit/revoke only for timelocked curator operations. Execution is a separate call after the delay."}}},execute:async(i,c)=>{try{if(p(c),Object.keys(i).some(e=>!["operation","values","mode"].includes(e)))throw new r("Unexpected vault management argument.");let n=S.find(e=>e.abi.name===i.operation);if(!n||!Array.isArray(i.values)||i.values.length!==n.abi.inputs.length)throw new r("Provide a supported operation and its exact ordered values.");let o=i.mode??"call";if(!["call","submit","revoke"].includes(String(o))||o!=="call"&&n.authority!=="timelock")throw new r("Submit/revoke is available only for timelocked curator operations.");let I=n.abi.inputs.map((e,d)=>M(e.type,i.values[d])),l=A({abi:[n.abi],functionName:n.abi.name,args:I}),b=a.clientFor(u);if(await b.getChainId()!==u)throw new r("Vault management requires chain 4663.");let s=(e,d=[])=>b.readContract({address:m,abi:x,functionName:e,args:d}),y=await s("asset");if(typeof y!="string"||w(y)!==w(O.address))throw new r("Vault management requires the pinned vault asset.");let g=e=>typeof e=="string"&&e.toLowerCase()===c.toLowerCase(),C=async e=>e==="any"?!0:e==="owner"?g(await s("owner")):e==="allocator"?await s("isAllocator",[c])===!0:e==="allocatorOrSentinel"?await s("isAllocator",[c])===!0||await s("isSentinel",[c])===!0:g(await s("curator"))||e==="curatorOrSentinel"&&await s("isSentinel",[c])===!0;if(n.authority==="timelock"&&o==="call"){let[e,d,D]=await Promise.all([s("executableAt",[l]),s("abdicated",[l.slice(0,10)]),b.getBlock()]);if(f(e)===0n||f(e)>D.timestamp||d!==!1)throw new r("This exact operation has not matured or its selector is abdicated. Submit it with the curator, then wait for its executable time.")}else if(!await C(o==="submit"?"timelock":o==="revoke"?"curatorOrSentinel":n.authority))throw new r("This wallet does not hold the required vault management role. No transaction was built.");let $=o==="call"?l:A({abi:x,functionName:o==="submit"?"submit":"revoke",args:[l]}),k=`${o} ${n.abi.name} on ${m}; ordered values ${JSON.stringify(i.values)}. ${n.abi.name==="abdicate"?"Abdication is irreversible.":""}`,h=[a.unsignedTx({to:m,data:$,value:"0",chainId:u,description:k})],v=await a.preview(h,c);return{txs:h,preview:v,summary:`${k} ${v.summary} ${o==="submit"?"Submission schedules this exact operation; it does not execute the configuration change.":"Role, cap and timing checks can change before execution."}`}}catch(n){throw new r(a.plainError(n))}}}}export{S as a,M as b,E as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as R,s as g}from"./XPFVT2EA.js";import{a as w}from"./5YS5V2LK.js";import{isDeepStrictEqual as b}from"node:util";import{isAddress as x}from"viem";var O=2592e3,v=1n<<128n,m=new Set(["order","offer","link","consent"]),y=new Set(["order","offer","consent"]),E=new Set(["order","offer","link"]),I=3600,S=1e11;function l(e){return new w(`Local signing guard: ${e}; nothing was signed.`)}var V=e=>m.has(e.class);function T(e,r){let t=new Map,n=(s,a,o)=>{let u=e[s];if(!u||o>8)throw l("typed-data types changed");for(let c of u){let f=c.type.replace(/(\[[0-9]*\])+$/,""),i=`${a}${c.name}${c.type===f?"":"[]"}`;e[f]?n(f,`${i}.`,o+1):t.set(i,c.type)}};return n(r,"",0),t}function N(e,r){let t=new Set,n=s=>{if(!(t.has(s)||!e[s])){t.add(s);for(let a of e[s])n(a.type.replace(/(\[[0-9]*\])+$/,""))}};return n(r),t}function A(e=[]){let r=new Set(e.map(n=>n.toLowerCase())),t=(n,s)=>{if(!(s>12)){if(typeof n=="string"){x(n,{strict:!1})&&r.add(n.toLowerCase());return}if(n&&typeof n=="object")for(let a of Object.values(n))t(a,s+1)}};return t(R,0),t(g,0),r}function j(e,r=A()){let t=[],n=(i,d)=>t.push(`${i} ${e.id}: ${d}`),s=Object.entries(e.fields),a=i=>s.filter(([,d])=>d.role===i),o=i=>s.filter(([,d])=>d.role==="derived"&&d.yields?.includes(i)).length;["order","cancel","link","offer","consent","auth","relayed"].includes(e.class)||n("R5","unknown signature class; link-accept is a display role only"),e.expiryBinding&&!["signed","program-link","auth-window","cancel-only"].includes(e.expiryBinding)&&n("R5","unknown expiry binding"),(!e.id||!/^[a-z0-9]+(?:[.-][a-z0-9]+)+$/.test(e.id))&&n("ID","id must be dotted lower-case"),(!e.tools.length||new Set(e.tools).size!==e.tools.length)&&n("ID","tools must be a non-empty unique list");let u=e.network==="testnet"?g.testnet.chainId:g.mainnet.chainId;if(e.encoding==="eip712"){let i=e.domain;i?(Object.hasOwn(i,"salt")&&n("R1","domain must not carry a salt"),i.name||n("R1","domain name is missing"),!i.version&&e.class!=="relayed"&&n("R1","domain version is missing"),i.chainId!==u&&n("R1",`domain chain must be ${u}`),i.verifyingContract?r.has(i.verifyingContract.toLowerCase())||n("R1","verifying contract is not a pinned address"):e.class!=="cancel"&&e.class!=="auth"&&n("R1","verifying contract is missing")):n("R1","EIP-712 spec has no domain")}else e.domain&&n("R1","only EIP-712 specs carry a domain");if(e.encoding==="eip191-packed-hash"){let i=a("pinned").map(([,d])=>d.value);i.some(d=>d===u||d===String(u))||n("R1","packed layout must pin the chain id"),i.some(d=>typeof d=="string"&&r.has(d.toLowerCase()))||n("R1","packed layout must pin the verifying contract")}let c=new Map,f=e.class==="relayed"&&!Object.keys(e.types).length;if(e.encoding==="eip712"&&!f){Object.hasOwn(e.types,"EIP712Domain")&&n("R2","types must never carry EIP712Domain");try{c=T(e.types,e.primaryType);let i=N(e.types,e.primaryType);for(let d of Object.keys(e.types))i.has(d)||n("R2",`type ${d} is not reachable from ${e.primaryType}`)}catch{n("R2",`types do not resolve from ${e.primaryType}`)}for(let i of c.keys())Object.hasOwn(e.fields,i)||n("R3",`message path ${i} has no role`);for(let[i]of s)c.has(i)||n("R3",`declared field ${i} is not in the typed struct`)}else e.encoding!=="eip712"&&Object.keys(e.types).length&&n("R2","only EIP-712 specs carry types");for(let[i,d]of s)(!d.meaning||d.meaning.length>160)&&n("R3",`field ${i} needs a plain-English meaning`);(e.class==="order"||e.class==="offer")&&!s.some(([,i])=>i.role==="amount"&&i.side==="out")&&!o("amount-out")&&n("R4",`${e.class} must show the most that can leave`);for(let[i,d]of s){if(d.role==="amount"||d.role==="fee"){let h=d.token;(x(h,{strict:!1})?r.has(h.toLowerCase()):e.fields[h]?.role==="token")||n("R4",`amount ${i} does not name a token field or a pinned token`)}c.get(i)==="bytes"&&d.role!=="pinned"&&d.role!=="derived"&&n("R4",`bytes field ${i} must be pinned or derived`)}if(e.maxLifetimeSeconds>0&&e.maxLifetimeSeconds<=O||n("R5","maxLifetimeSeconds must be within 30 days"),y.has(e.class)){let i=a("expiry").length+o("expiry");i!==1&&n("R5",`${e.class} needs exactly one expiry (found ${i})`),e.expiry&&n("R5","API-only expiry is not a signed expiry"),e.expiryBinding&&e.expiryBinding!=="signed"&&n("R5",`${e.class} requires signed expiry`)}if(e.expiryBinding==="program-link"&&e.class!=="link"&&n("R5","only link can use program-link"),e.class==="link"&&e.expiryBinding!=="program-link"&&a("expiry").length+o("expiry")!==1&&n("R5","link needs signed expiry or program-link binding"),e.expiryBinding==="auth-window"){let i=e.authWindow;(e.class!=="auth"||!i||!c.has(i.field)||!Number.isSafeInteger(i.maxAgeSeconds)||i.maxAgeSeconds<=0||i.maxAgeSeconds>e.maxLifetimeSeconds||!Number.isSafeInteger(i.maxFutureSeconds)||i.maxFutureSeconds<0||i.maxFutureSeconds>e.maxLifetimeSeconds)&&n("R5","auth-window needs a signed timestamp and pinned acceptance window")}else e.authWindow&&n("R5","authWindow requires auth-window binding");return e.expiryBinding==="cancel-only"&&(e.class!=="cancel"||!a("nonce").length&&!o("nonce")&&!e.revoke?.staysExecutableUntilExpiry)&&n("R5","cancel-only needs a single-use nonce or targeted non-revoking hide"),(e.class==="auth"||e.class==="cancel")&&(s.some(([,i])=>i.role==="amount"&&i.side==="out")||o("amount-out"))&&n("R4","auth and cancel cannot grant spending authority"),E.has(e.class)&&!(e.revoke?.onchainTool||e.revoke?.offchainSpec)&&!(e.revoke?.none&&e.maxLifetimeSeconds<=I)&&n("R6",`${e.class} needs a revocation path (only a one-shot approval of at most one hour may declare none)`),e.submit.by==="addon"&&(!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(e.submit.host)||!/^\/[A-Za-z0-9/_.-]*$/.test(e.submit.path))&&n("R9","add-on submission needs a bare HTTPS host and a fixed path"),e.submit.by==="server-continuation"&&!e.submit.reason&&n("R9","server-continuation needs its recorded reason"),e.submit.by==="transaction"&&e.class!=="relayed"&&e.class!=="consent"&&n("R9","only relayed and consent signatures are consumed by a transaction"),(!/^[A-Za-z0-9 .'-]{1,40}$/.test(e.program)||!/^[A-Za-z0-9 .'-]{1,60}$/.test(e.purpose))&&n("R10","program and purpose must be short constant text"),m.has(e.class)&&!e.requireHuman&&!e.humanException&&n("C13",`${e.class} must require a human`),!m.has(e.class)&&e.humanException&&n("C13","only a value class can name a human exception"),e.relayedPaths&&e.class!=="relayed"&&n("ID","only relayed specs accept caller signatures"),e.enabled===!1&&!e.disabledReason&&n("ID","a disabled spec states why"),t}function z(e,r=A()){let t=e.filter(a=>a.enabled!==!1).flatMap(a=>j(a,r)),n=new Set,s=new Set;for(let a of e){n.has(a.id)&&t.push(`ID ${a.id}: duplicate spec id`),n.add(a.id);let o=C(a);s.has(o)&&t.push(`ID ${a.id}: another spec already covers ${o}`),s.add(o)}return t}function C(e){return`${e.network??"mainnet"}:${e.encoding}:${(e.domain?.verifyingContract??"-").toLowerCase()}:${e.primaryType}`}function k(e,r,t,n,s){let a=r.replace(/(\[[0-9]*\])+$/,"");if(a!==r){if(!Array.isArray(t))throw l(`message field ${n||r} is not declared`);for(let i of t)k(e,r.replace(/\[[0-9]*\]$/,""),i,`${n}[]`,s+1);return}let o=e[a];if(!o)return;if(s>8||!t||typeof t!="object"||Array.isArray(t))throw l(`message field ${n||r} is not declared`);let u=Object.keys(t),c=o.map(i=>i.name);if(u.find(i=>!c.includes(i))!==void 0)throw l(`an undeclared message field${n?` under ${n}`:""} is present`);for(let i of o){if(!Object.hasOwn(t,i.name))throw l(`message field ${n?`${n}.`:""}${i.name} is missing`);k(e,i.type,t[i.name],`${n?`${n}.`:""}${i.name}`,s+1)}}function W(e,r){if(e.encoding!=="eip712"||!e.domain)throw l("Oak has no signing contract for this request");if(!r||typeof r!="object"||!r.domain||typeof r.domain!="object")throw l("domain, chain or verifying contract is not the pinned one");let t=Object.fromEntries(Object.entries(e.domain).filter(([,n])=>n!==void 0));if(!b(Object.keys(r.domain).sort(),Object.keys(t).sort())||!b({...r.domain},t))throw l("domain, chain or verifying contract is not the pinned one");if(!r.types||typeof r.types!="object"||Object.hasOwn(r.types,"EIP712Domain")||!b(r.types,e.types)||r.primaryType!==e.primaryType)throw l("typed-data types changed");k(e.types,e.primaryType,r.message,"",0)}function p(e,r){let t=e;for(let n of r.split(".")){if(n.endsWith("[]")||!t||typeof t!="object"||Array.isArray(t))return;t=t[n]}return t}var $=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="bigint"?String(e):void 0;function D(e,r){let t={},n=s=>x(s,{strict:!1})?s:$(p(r,s));for(let[s,a]of Object.entries(e.fields)){let o=$(p(r,s));if(o!==void 0)switch(a.role){case"signer":t.signer=o;break;case"account":t.account=o;break;case"recipient":t.recipient=o;break;case"delegate":t.delegate=o;break;case"counterparty":t.counterparty=o;break;case"token":a.side==="out"?t.tokenOut=o:t.tokenIn=o;break;case"amount":a.side==="out"?(t.amountOut=o,t.tokenOut??=n(a.token)):(t.minAmountIn=o,t.tokenIn??=n(a.token));break;case"fee":(t.fees??=[]).push({token:n(a.token)??a.token,value:o});break;case"expiry":t.expiry=/^[0-9]+$/.test(o)?Number(o):Number.NaN;break;case"nonce":t.nonce=o;break;default:break}}return t}function L(e,r,t){let n=Math.min(e.maxLifetimeSeconds,O),s=y.has(e.class)||e.humanException?60:1;if(!Number.isSafeInteger(t)||t<0||!Number.isFinite(n)||n<=0||r===void 0||!Number.isSafeInteger(r)||r<=0||r>=S||r<t+s||r>t+n)throw l(`expiry is missing, past or beyond ${n>=86400?`${Math.floor(n/86400)} days`:`${Math.ceil(n/60)} minutes`}`)}function U(e,r,t,n){if(e.enabled===!1)throw l("Oak has no signing contract for this request");if(!Number.isSafeInteger(t)||t<0||t>=S)throw l("signing time is unavailable");if(e.expiryBinding==="auth-window"){let o=e.authWindow,u=o&&p(r,o.field),c=typeof u=="number"?u:typeof u=="string"&&/^[0-9]+$/.test(u)?Number(u):NaN;if(e.class!=="auth"||!o||!Number.isSafeInteger(c)||c<=0||c>=S||c<t-o.maxAgeSeconds||c>t+o.maxFutureSeconds)throw l("authentication time is outside the pinned window");return c+o.maxAgeSeconds}if(e.expiryBinding==="cancel-only"){if(e.class!=="cancel")throw l("Oak has no signing contract for this request");return n}if(e.expiryBinding==="program-link")throw l("program link authority is not configured");if(y.has(e.class)&&(e.expiry||e.expiryBinding&&e.expiryBinding!=="signed"))throw l("order expiry must be signed");let s=D(e,r).expiry??n,a=Object.values(e.fields).some(o=>o.role==="expiry"||o.role==="derived"&&o.yields?.includes("expiry"));if(y.has(e.class)&&!a)throw l("order expiry must be signed");return(a||m.has(e.class))&&L(e,s,t),s}function H(e){if(e===void 0||!/^[0-9]{1,78}$/.test(e))throw l("open-ended or out-of-range amount");let r=BigInt(e);if(r<=0n||r>=v)throw l("open-ended or out-of-range amount");return r}function J(e,r){return Object.entries(e.fields).map(([t,n])=>{let s=t.includes("[]")?"(each item, listed below)":p(r,t),a=typeof s=="object"&&s!==null?JSON.stringify(s):String(s);a.length>200&&(a=`${a.slice(0,200)}\u2026`);let o=JSON.stringify(a).replace(/[\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g,u=>`\\u${u.charCodeAt(0).toString(16).padStart(4,"0")}`);return`${t} = ${o} - ${n.meaning}`})}export{O as a,v as b,m as c,l as d,V as e,T as f,A as g,j as h,z as i,C as j,W as k,p as l,D as m,L as n,U as o,H as p,J as q};
|
|
1
|
+
import{i as R,s as g}from"./G6HCV67X.js";import{a as w}from"./5YS5V2LK.js";import{isDeepStrictEqual as b}from"node:util";import{isAddress as x}from"viem";var O=2592e3,v=1n<<128n,m=new Set(["order","offer","link","consent"]),y=new Set(["order","offer","consent"]),E=new Set(["order","offer","link"]),I=3600,S=1e11;function l(e){return new w(`Local signing guard: ${e}; nothing was signed.`)}var V=e=>m.has(e.class);function T(e,r){let t=new Map,n=(s,a,o)=>{let u=e[s];if(!u||o>8)throw l("typed-data types changed");for(let c of u){let f=c.type.replace(/(\[[0-9]*\])+$/,""),i=`${a}${c.name}${c.type===f?"":"[]"}`;e[f]?n(f,`${i}.`,o+1):t.set(i,c.type)}};return n(r,"",0),t}function N(e,r){let t=new Set,n=s=>{if(!(t.has(s)||!e[s])){t.add(s);for(let a of e[s])n(a.type.replace(/(\[[0-9]*\])+$/,""))}};return n(r),t}function A(e=[]){let r=new Set(e.map(n=>n.toLowerCase())),t=(n,s)=>{if(!(s>12)){if(typeof n=="string"){x(n,{strict:!1})&&r.add(n.toLowerCase());return}if(n&&typeof n=="object")for(let a of Object.values(n))t(a,s+1)}};return t(R,0),t(g,0),r}function j(e,r=A()){let t=[],n=(i,d)=>t.push(`${i} ${e.id}: ${d}`),s=Object.entries(e.fields),a=i=>s.filter(([,d])=>d.role===i),o=i=>s.filter(([,d])=>d.role==="derived"&&d.yields?.includes(i)).length;["order","cancel","link","offer","consent","auth","relayed"].includes(e.class)||n("R5","unknown signature class; link-accept is a display role only"),e.expiryBinding&&!["signed","program-link","auth-window","cancel-only"].includes(e.expiryBinding)&&n("R5","unknown expiry binding"),(!e.id||!/^[a-z0-9]+(?:[.-][a-z0-9]+)+$/.test(e.id))&&n("ID","id must be dotted lower-case"),(!e.tools.length||new Set(e.tools).size!==e.tools.length)&&n("ID","tools must be a non-empty unique list");let u=e.network==="testnet"?g.testnet.chainId:g.mainnet.chainId;if(e.encoding==="eip712"){let i=e.domain;i?(Object.hasOwn(i,"salt")&&n("R1","domain must not carry a salt"),i.name||n("R1","domain name is missing"),!i.version&&e.class!=="relayed"&&n("R1","domain version is missing"),i.chainId!==u&&n("R1",`domain chain must be ${u}`),i.verifyingContract?r.has(i.verifyingContract.toLowerCase())||n("R1","verifying contract is not a pinned address"):e.class!=="cancel"&&e.class!=="auth"&&n("R1","verifying contract is missing")):n("R1","EIP-712 spec has no domain")}else e.domain&&n("R1","only EIP-712 specs carry a domain");if(e.encoding==="eip191-packed-hash"){let i=a("pinned").map(([,d])=>d.value);i.some(d=>d===u||d===String(u))||n("R1","packed layout must pin the chain id"),i.some(d=>typeof d=="string"&&r.has(d.toLowerCase()))||n("R1","packed layout must pin the verifying contract")}let c=new Map,f=e.class==="relayed"&&!Object.keys(e.types).length;if(e.encoding==="eip712"&&!f){Object.hasOwn(e.types,"EIP712Domain")&&n("R2","types must never carry EIP712Domain");try{c=T(e.types,e.primaryType);let i=N(e.types,e.primaryType);for(let d of Object.keys(e.types))i.has(d)||n("R2",`type ${d} is not reachable from ${e.primaryType}`)}catch{n("R2",`types do not resolve from ${e.primaryType}`)}for(let i of c.keys())Object.hasOwn(e.fields,i)||n("R3",`message path ${i} has no role`);for(let[i]of s)c.has(i)||n("R3",`declared field ${i} is not in the typed struct`)}else e.encoding!=="eip712"&&Object.keys(e.types).length&&n("R2","only EIP-712 specs carry types");for(let[i,d]of s)(!d.meaning||d.meaning.length>160)&&n("R3",`field ${i} needs a plain-English meaning`);(e.class==="order"||e.class==="offer")&&!s.some(([,i])=>i.role==="amount"&&i.side==="out")&&!o("amount-out")&&n("R4",`${e.class} must show the most that can leave`);for(let[i,d]of s){if(d.role==="amount"||d.role==="fee"){let h=d.token;(x(h,{strict:!1})?r.has(h.toLowerCase()):e.fields[h]?.role==="token")||n("R4",`amount ${i} does not name a token field or a pinned token`)}c.get(i)==="bytes"&&d.role!=="pinned"&&d.role!=="derived"&&n("R4",`bytes field ${i} must be pinned or derived`)}if(e.maxLifetimeSeconds>0&&e.maxLifetimeSeconds<=O||n("R5","maxLifetimeSeconds must be within 30 days"),y.has(e.class)){let i=a("expiry").length+o("expiry");i!==1&&n("R5",`${e.class} needs exactly one expiry (found ${i})`),e.expiry&&n("R5","API-only expiry is not a signed expiry"),e.expiryBinding&&e.expiryBinding!=="signed"&&n("R5",`${e.class} requires signed expiry`)}if(e.expiryBinding==="program-link"&&e.class!=="link"&&n("R5","only link can use program-link"),e.class==="link"&&e.expiryBinding!=="program-link"&&a("expiry").length+o("expiry")!==1&&n("R5","link needs signed expiry or program-link binding"),e.expiryBinding==="auth-window"){let i=e.authWindow;(e.class!=="auth"||!i||!c.has(i.field)||!Number.isSafeInteger(i.maxAgeSeconds)||i.maxAgeSeconds<=0||i.maxAgeSeconds>e.maxLifetimeSeconds||!Number.isSafeInteger(i.maxFutureSeconds)||i.maxFutureSeconds<0||i.maxFutureSeconds>e.maxLifetimeSeconds)&&n("R5","auth-window needs a signed timestamp and pinned acceptance window")}else e.authWindow&&n("R5","authWindow requires auth-window binding");return e.expiryBinding==="cancel-only"&&(e.class!=="cancel"||!a("nonce").length&&!o("nonce")&&!e.revoke?.staysExecutableUntilExpiry)&&n("R5","cancel-only needs a single-use nonce or targeted non-revoking hide"),(e.class==="auth"||e.class==="cancel")&&(s.some(([,i])=>i.role==="amount"&&i.side==="out")||o("amount-out"))&&n("R4","auth and cancel cannot grant spending authority"),E.has(e.class)&&!(e.revoke?.onchainTool||e.revoke?.offchainSpec)&&!(e.revoke?.none&&e.maxLifetimeSeconds<=I)&&n("R6",`${e.class} needs a revocation path (only a one-shot approval of at most one hour may declare none)`),e.submit.by==="addon"&&(!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(e.submit.host)||!/^\/[A-Za-z0-9/_.-]*$/.test(e.submit.path))&&n("R9","add-on submission needs a bare HTTPS host and a fixed path"),e.submit.by==="server-continuation"&&!e.submit.reason&&n("R9","server-continuation needs its recorded reason"),e.submit.by==="transaction"&&e.class!=="relayed"&&e.class!=="consent"&&n("R9","only relayed and consent signatures are consumed by a transaction"),(!/^[A-Za-z0-9 .'-]{1,40}$/.test(e.program)||!/^[A-Za-z0-9 .'-]{1,60}$/.test(e.purpose))&&n("R10","program and purpose must be short constant text"),m.has(e.class)&&!e.requireHuman&&!e.humanException&&n("C13",`${e.class} must require a human`),!m.has(e.class)&&e.humanException&&n("C13","only a value class can name a human exception"),e.relayedPaths&&e.class!=="relayed"&&n("ID","only relayed specs accept caller signatures"),e.enabled===!1&&!e.disabledReason&&n("ID","a disabled spec states why"),t}function z(e,r=A()){let t=e.filter(a=>a.enabled!==!1).flatMap(a=>j(a,r)),n=new Set,s=new Set;for(let a of e){n.has(a.id)&&t.push(`ID ${a.id}: duplicate spec id`),n.add(a.id);let o=C(a);s.has(o)&&t.push(`ID ${a.id}: another spec already covers ${o}`),s.add(o)}return t}function C(e){return`${e.network??"mainnet"}:${e.encoding}:${(e.domain?.verifyingContract??"-").toLowerCase()}:${e.primaryType}`}function k(e,r,t,n,s){let a=r.replace(/(\[[0-9]*\])+$/,"");if(a!==r){if(!Array.isArray(t))throw l(`message field ${n||r} is not declared`);for(let i of t)k(e,r.replace(/\[[0-9]*\]$/,""),i,`${n}[]`,s+1);return}let o=e[a];if(!o)return;if(s>8||!t||typeof t!="object"||Array.isArray(t))throw l(`message field ${n||r} is not declared`);let u=Object.keys(t),c=o.map(i=>i.name);if(u.find(i=>!c.includes(i))!==void 0)throw l(`an undeclared message field${n?` under ${n}`:""} is present`);for(let i of o){if(!Object.hasOwn(t,i.name))throw l(`message field ${n?`${n}.`:""}${i.name} is missing`);k(e,i.type,t[i.name],`${n?`${n}.`:""}${i.name}`,s+1)}}function W(e,r){if(e.encoding!=="eip712"||!e.domain)throw l("Oak has no signing contract for this request");if(!r||typeof r!="object"||!r.domain||typeof r.domain!="object")throw l("domain, chain or verifying contract is not the pinned one");let t=Object.fromEntries(Object.entries(e.domain).filter(([,n])=>n!==void 0));if(!b(Object.keys(r.domain).sort(),Object.keys(t).sort())||!b({...r.domain},t))throw l("domain, chain or verifying contract is not the pinned one");if(!r.types||typeof r.types!="object"||Object.hasOwn(r.types,"EIP712Domain")||!b(r.types,e.types)||r.primaryType!==e.primaryType)throw l("typed-data types changed");k(e.types,e.primaryType,r.message,"",0)}function p(e,r){let t=e;for(let n of r.split(".")){if(n.endsWith("[]")||!t||typeof t!="object"||Array.isArray(t))return;t=t[n]}return t}var $=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="bigint"?String(e):void 0;function D(e,r){let t={},n=s=>x(s,{strict:!1})?s:$(p(r,s));for(let[s,a]of Object.entries(e.fields)){let o=$(p(r,s));if(o!==void 0)switch(a.role){case"signer":t.signer=o;break;case"account":t.account=o;break;case"recipient":t.recipient=o;break;case"delegate":t.delegate=o;break;case"counterparty":t.counterparty=o;break;case"token":a.side==="out"?t.tokenOut=o:t.tokenIn=o;break;case"amount":a.side==="out"?(t.amountOut=o,t.tokenOut??=n(a.token)):(t.minAmountIn=o,t.tokenIn??=n(a.token));break;case"fee":(t.fees??=[]).push({token:n(a.token)??a.token,value:o});break;case"expiry":t.expiry=/^[0-9]+$/.test(o)?Number(o):Number.NaN;break;case"nonce":t.nonce=o;break;default:break}}return t}function L(e,r,t){let n=Math.min(e.maxLifetimeSeconds,O),s=y.has(e.class)||e.humanException?60:1;if(!Number.isSafeInteger(t)||t<0||!Number.isFinite(n)||n<=0||r===void 0||!Number.isSafeInteger(r)||r<=0||r>=S||r<t+s||r>t+n)throw l(`expiry is missing, past or beyond ${n>=86400?`${Math.floor(n/86400)} days`:`${Math.ceil(n/60)} minutes`}`)}function U(e,r,t,n){if(e.enabled===!1)throw l("Oak has no signing contract for this request");if(!Number.isSafeInteger(t)||t<0||t>=S)throw l("signing time is unavailable");if(e.expiryBinding==="auth-window"){let o=e.authWindow,u=o&&p(r,o.field),c=typeof u=="number"?u:typeof u=="string"&&/^[0-9]+$/.test(u)?Number(u):NaN;if(e.class!=="auth"||!o||!Number.isSafeInteger(c)||c<=0||c>=S||c<t-o.maxAgeSeconds||c>t+o.maxFutureSeconds)throw l("authentication time is outside the pinned window");return c+o.maxAgeSeconds}if(e.expiryBinding==="cancel-only"){if(e.class!=="cancel")throw l("Oak has no signing contract for this request");return n}if(e.expiryBinding==="program-link")throw l("program link authority is not configured");if(y.has(e.class)&&(e.expiry||e.expiryBinding&&e.expiryBinding!=="signed"))throw l("order expiry must be signed");let s=D(e,r).expiry??n,a=Object.values(e.fields).some(o=>o.role==="expiry"||o.role==="derived"&&o.yields?.includes("expiry"));if(y.has(e.class)&&!a)throw l("order expiry must be signed");return(a||m.has(e.class))&&L(e,s,t),s}function H(e){if(e===void 0||!/^[0-9]{1,78}$/.test(e))throw l("open-ended or out-of-range amount");let r=BigInt(e);if(r<=0n||r>=v)throw l("open-ended or out-of-range amount");return r}function J(e,r){return Object.entries(e.fields).map(([t,n])=>{let s=t.includes("[]")?"(each item, listed below)":p(r,t),a=typeof s=="object"&&s!==null?JSON.stringify(s):String(s);a.length>200&&(a=`${a.slice(0,200)}\u2026`);let o=JSON.stringify(a).replace(/[\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g,u=>`\\u${u.charCodeAt(0).toString(16).padStart(4,"0")}`);return`${t} = ${o} - ${n.meaning}`})}export{O as a,v as b,m as c,l as d,V as e,T as f,A as g,j as h,z as i,C as j,W as k,p as l,D as m,L as n,U as o,H as p,J as q};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as G}from"./LFN3OODW.js";import{b as j,c as V,d as W}from"./T3MGNKA6.js";import{d as ae,e as L}from"./CAU44UWP.js";import{a as N}from"./VJ3W2V3B.js";import{a as v}from"./6IM6A5VA.js";import{a as R,b as ie,c as se,d as U}from"./RETS2ZEK.js";import{a as S,i as x}from"./XPFVT2EA.js";import{a as o}from"./5YS5V2LK.js";import{decodeEventLog as He,encodeAbiParameters as fe,encodeFunctionData as ye,erc20Abi as Q,getAddress as l,isAddress as $,keccak256 as $e,parseAbi as Ee,parseAbiParameters as pe,toEventSelector as we}from"viem";var A=l(x[4663].hookr.HookrLimitOrders.address),_e=l(x[4663].hookr.HookrRoot.address),ve=l(x[4663].hookr.HookrRouter.address),kt=l(x[4663].hookr.HookrRegistry.address),Ne=l(x[4663].hookr.HookrForwarder.address),Be=l(x[4663].hookr.PoolManager.address),Ot=l(x[4663].hookr.HOOKR_Token.address),Fe=l("0x000000000000000000000000000000000000dEaD"),Me=8388608,ze=200,de=60n,qe=604800n,ce=31536000n,It=10,At=100,ht="500000000000000",St="10000000000000000",ue=4096n,Y=32n,Xe=1e4,Ke=(1n<<127n)-1n,me=(1n<<128n)-1n,Ue=(1n<<160n)-1n,je=(1n<<40n)-1n,Ve=16777215,We=8388607,le=1n<<192n,J=0,F=1,Ge=2,Ye=3,Qe=we("OrderCreated(uint256,address,bytes32,bool,uint128,uint128,uint128,uint40,address)"),Ct=we("OrderCancelled(uint256,address,address,uint256,uint256)"),D=Ee(["function bountyBounds((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, bool zeroForOne, uint128 amountIn, uint128 minAmountOut) view returns (uint128 minBounty, uint128 defaultBounty, uint128 maxBounty)","function createOrder(((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, bool zeroForOne, uint128 amountIn, uint128 minAmountOut, uint160 sqrtPriceLimitX96, address recipient, uint40 expiry, uint128 bounty) params) payable returns (uint256 orderId)","function cancel(uint256 orderId, address to)","function getOrder(uint256 orderId) view returns (((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, address owner, uint40 createdAt, uint40 expiry, bool zeroForOne, uint8 status, address recipient, uint128 amountIn, uint128 minAmountOut, uint128 bounty, uint160 sqrtPriceLimitX96))","function quoteFill(uint256 orderId) view returns (bool fillable, uint256 amountOut)","function lastOrderId() view returns (uint256)","function liabilities(address currency) view returns (uint256)","function router() view returns (address)","function registry() view returns (address)","function poolManager() view returns (address)","function forwarder() view returns (address)","event OrderCreated(uint256 indexed orderId, address indexed owner, bytes32 indexed poolId, bool zeroForOne, uint128 amountIn, uint128 minAmountOut, uint128 bounty, uint40 expiry, address recipient)","event OrderCancelled(uint256 indexed orderId, address indexed owner, address indexed to, uint256 amountIn, uint256 bounty)"]);function B(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ge(e){let t=e.toLowerCase();return t===L.toLowerCase()||t===N.toLowerCase()||t===ae.toLowerCase()}function H(e,t){if(typeof e!="string"||!e.trim())throw new o(`Provide a valid contract address for ${t}. Identify tokens by chain and address, never by symbol.`);let n=e.trim();if(!$(n,{strict:!1}))throw new o(`Invalid token address "${n}" for ${t}. Identify tokens by chain and address, never by symbol.`);return ge(n)?L:l(n)}function be(e){let t=e===void 0?S:Number(e);if(!Number.isSafeInteger(t)||t!==S)throw new o(`Hookr limit orders are only supported on Robinhood Chain (${S}).`);return S}function Ze(e){switch(e){case J:return"None";case F:return"Open";case Ge:return"Filled";case Ye:return"Cancelled";default:return"Unknown"}}function Je(e,t,n=se){if(typeof e!="string"||!/^-?\d+$/.test(e.trim()))throw new o("Signed amount must be an integer string in base units.");let r=e.trim();if(r.startsWith("-")){let i=r.slice(1),u=n(i,t);return u==="0"?"0":`-${u}`}return n(r,t)}function xt(e,t,n="floor"){return ie(e,t,n)}function ke(e){return $e(fe(pe("address, address, uint24, int24, address"),[l(e.currency0),l(e.currency1),e.fee,e.tickSpacing,l(e.hooks)]))}function Oe(e,t){let n=e.toLowerCase();if(new Set([L.toLowerCase(),Fe.toLowerCase(),A.toLowerCase(),ve.toLowerCase(),Ne.toLowerCase(),Be.toLowerCase(),t.toLowerCase()]).has(n))throw new o(`Recipient ${e} is a reserved address and cannot receive Hookr limit order funds.`)}async function Z(e,t,n,r){if(ge(e))return{address:N,symbol:j.symbol,decimals:j.decimals,chainId:t};let i=l(e),u=i.toLowerCase();if(B(r)){let s=typeof r.decimals=="number"&&Number.isInteger(r.decimals)&&r.decimals>=0&&r.decimals<=255?r.decimals:void 0,a=typeof r.symbol=="string"&&r.symbol.trim()?r.symbol.trim():void 0;if(s!==void 0&&a!==void 0)return{address:i,symbol:a,decimals:s,chainId:t}}if(u===V.address.toLowerCase())return{...V,chainId:t};if(u===W.address.toLowerCase())return{...W,chainId:t};try{let[s,a]=await Promise.all([n.readContract({address:i,abi:Q,functionName:"symbol"}),n.readContract({address:i,abi:Q,functionName:"decimals"})]);if(typeof s!="string"||!s.trim()||typeof a!="number"||!Number.isInteger(a)||a<0||a>255)throw new o(`Invalid token metadata for ${i}.`);return{address:i,symbol:s.trim(),decimals:a,chainId:t}}catch{throw new o(`Could not read valid token metadata for ${i}. Refusing to guess token decimals.`)}}function et(e){let t=B(e.key)?e.key:B(e.poolKey)?e.poolKey:void 0,n=t?.fee??e.fee??Me,r=(typeof n=="string"&&/^\d+$/.test(n),Number(n));if(!Number.isInteger(r)||r<0||r>Ve)throw new o("Pool fee must be a valid uint24 integer (default 8388608 for Hookr dynamic fee pools).");let i=t?.tickSpacing??e.tickSpacing??ze,u=(typeof i=="string"&&/^-?\d+$/.test(i),Number(i));if(!Number.isInteger(u)||u<=0||u>We)throw new o("Pool tickSpacing must be a positive int24 integer.");let s=t?.hooks??e.hooks??_e;if(typeof s!="string"||!$(s,{strict:!1}))throw new o("Provide a valid Hookr root contract address for hooks.");let a=l(s);if(t?.currency0!==void 0&&t?.currency1!==void 0||e.currency0!==void 0&&e.currency1!==void 0){let m=H(t?.currency0??e.currency0,"currency0"),I=H(t?.currency1??e.currency1,"currency1");if(m.toLowerCase()===I.toLowerCase())throw new o("Pool currency0 and currency1 must be distinct token addresses.");if(BigInt(m)>=BigInt(I))throw new o("Pool currency0 must sort strictly before currency1 by address.");let k;if(typeof e.zeroForOne=="boolean")k=e.zeroForOne;else if(e.tokenIn!==void 0||e.from!==void 0){let C=H(e.tokenIn??e.from,"tokenIn");if(C.toLowerCase()===m.toLowerCase())k=!0;else if(C.toLowerCase()===I.toLowerCase())k=!1;else throw new o("tokenIn does not match currency0 or currency1 of the pool key.")}else throw new o("Provide zeroForOne (boolean) or tokenIn when specifying a pool key.");return{key:{currency0:m,currency1:I,fee:r,tickSpacing:u,hooks:a},zeroForOne:k}}let w=e.tokenIn??e.from,f=e.tokenOut??e.to;if(w===void 0||f===void 0)throw new o("Provide either key ({ currency0, currency1, fee, tickSpacing, hooks }) with zeroForOne or tokenIn and tokenOut addresses.");let g=H(w,"tokenIn"),b=H(f,"tokenOut");if(g.toLowerCase()===b.toLowerCase())throw new o("Input and output tokens must have distinct addresses.");let y=BigInt(g)<BigInt(b),p=y?g:b,d=y?b:g;if(typeof e.zeroForOne=="boolean"&&e.zeroForOne!==y)throw new o("zeroForOne conflicts with the canonical sorting of tokenIn and tokenOut.");return{key:{currency0:p,currency1:d,fee:r,tickSpacing:u,hooks:a},zeroForOne:y}}function tt(e,t,n){let r=G(t),i=r*r;if(n){let s=U(e.toString(),i.toString(),le.toString(),"ceil");return BigInt(s)}let u=U(e.toString(),le.toString(),i.toString(),"ceil");return BigInt(u)}function T(e,t){if(typeof e=="bigint"){if(e<0n)throw new o(`${t} must be a non-negative integer.`);return e}if(typeof e=="number"){if(!Number.isSafeInteger(e)||e<0)throw new o(`${t} must be a non-negative safe integer.`);return BigInt(e)}if(typeof e=="string")return R(e.trim());throw new o(`Provide ${t} as a decimal base-unit string.`)}async function nt(e,t){if(t!==void 0)return T(t,"now");if(typeof e.getBlock=="function"){let n=await e.getBlock().catch(()=>{throw new o("Could not read the chain timestamp for Hookr order expiry.")});return BigInt(n.timestamp)}throw new o("Could not read the chain timestamp for Hookr order expiry.")}function Ie(e,t){return!e.changes||e.changes.length===0?"no net ERC-20 transfer deltas":e.changes.map(n=>`${Je(n.amount,n.token.decimals,t.formatAmount)} ${n.token.symbol}`).join(", ")}function ot(e,t,n,r){if(!e||!Array.isArray(e.logs))throw new o("Provide a transaction receipt with a logs array.");for(let i of e.logs){if(!i||typeof i.address!="string"||!$(i.address,{strict:!1})||!Array.isArray(i.topics)||typeof i.data!="string"||i.topics.some(u=>typeof u!="string"||!/^0x[0-9a-fA-F]{64}$/.test(u)))throw new o(`Malformed Hookr ${t} receipt log.`);if(i.address.toLowerCase()===A.toLowerCase()&&i.topics[0]?.toLowerCase()===n.toLowerCase()){if(i.topics.length!==4||!/^0x0{24}/i.test(i.topics[2])||t==="OrderCancelled"&&!/^0x0{24}/i.test(i.topics[3])||!/^0x[0-9a-fA-F]*$/.test(i.data)||i.data.length!==2+r*64)throw new o(`Malformed Hookr ${t} receipt log.`);return{topics:i.topics,data:i.data}}}throw new o(`Could not find Hookr ${t} event in transaction receipt logs.`)}function Ae(e){if(e.receipt!==void 0){if(!B(e.receipt)||!Array.isArray(e.receipt.logs))throw new o("Provide a transaction receipt with a logs array.");return it({logs:e.receipt.logs})}if(e.logs!==void 0){if(!Array.isArray(e.logs))throw new o("Provide receipt logs as an array.");return rt(e.logs)}}function he(e){let t=ot(e,"OrderCreated",Qe,6);try{let n=He({abi:D,eventName:"OrderCreated",...t,strict:!0});if(fe(pe("bool, uint128, uint128, uint128, uint40, address"),[n.args.zeroForOne,n.args.amountIn,n.args.minAmountOut,n.args.bounty,n.args.expiry,n.args.recipient]).toLowerCase()!==t.data.toLowerCase())throw new o("Noncanonical Hookr OrderCreated event data.");return{orderId:n.args.orderId.toString(),owner:l(n.args.owner),poolId:n.args.poolId,zeroForOne:n.args.zeroForOne,amountIn:n.args.amountIn.toString(),minAmountOut:n.args.minAmountOut.toString(),bounty:n.args.bounty.toString(),expiry:n.args.expiry.toString(),recipient:l(n.args.recipient)}}catch{throw new o("Malformed Hookr OrderCreated receipt log.")}}function rt(e){return he({logs:e}).orderId}function it(e){return he(e).orderId}function Se(e){if(Array.isArray(e)){let[n,r,i,u,s,a,c,w,f,g,b]=e;return{key:Array.isArray(n)?{currency0:n[0],currency1:n[1],fee:Number(n[2]),tickSpacing:Number(n[3]),hooks:n[4]}:n,owner:r,createdAt:i,expiry:u,zeroForOne:s,status:a,recipient:c,amountIn:BigInt(w),minAmountOut:BigInt(f),bounty:BigInt(g),sqrtPriceLimitX96:BigInt(b)}}let t=e;return{key:{currency0:t.key.currency0,currency1:t.key.currency1,fee:Number(t.key.fee),tickSpacing:Number(t.key.tickSpacing),hooks:t.key.hooks},owner:t.owner,createdAt:t.createdAt,expiry:t.expiry,zeroForOne:!!t.zeroForOne,status:Number(t.status),recipient:t.recipient,amountIn:BigInt(t.amountIn),minAmountOut:BigInt(t.minAmountOut),bounty:BigInt(t.bounty),sqrtPriceLimitX96:BigInt(t.sqrtPriceLimitX96)}}async function Ce(e,t,n){let r=T(t,"orderId");if(r<=0n)throw new o("Order ID must be a positive integer.");let i=e.clientFor(S),u=n?.order??await i.readContract({address:A,abi:D,functionName:"getOrder",args:[r]}).catch(()=>{throw new o(`Could not read Hookr order #${r}. Order coverage is incomplete.`)}),s=Se(u),a=Number(s.status);if(s.owner.toLowerCase()===L.toLowerCase()||a===J)throw new o(`Hookr order #${r} does not exist.`);let c={currency0:l(s.key.currency0),currency1:l(s.key.currency1),fee:Number(s.key.fee),tickSpacing:Number(s.key.tickSpacing),hooks:l(s.key.hooks)},w=s.zeroForOne?c.currency0:c.currency1,f=s.zeroForOne?c.currency1:c.currency0,g=m=>{let I=m.toLowerCase(),k=n?.tokens.get(I);if(k)return k;let C=Z(m,S,i);return n?.tokens.set(I,C),C},[b,y]=await Promise.all([g(w),g(f)]),p=!1,d=0n;if(a===F)try{let m=await i.readContract({address:A,abi:D,functionName:"quoteFill",args:[r]});if(typeof m[0]!="boolean"||typeof m[1]!="bigint"||m[1]<0n)throw new o(`Invalid quote for Hookr order #${r}.`);p=m[0],d=m[1]}catch{throw new o(`Could not quote Hookr order #${r}. Fillability and output amount are unknown.`)}return{orderId:r.toString(),poolId:ke(c),key:c,owner:l(s.owner),recipient:l(s.recipient),createdAt:BigInt(s.createdAt).toString(),expiry:BigInt(s.expiry).toString(),zeroForOne:s.zeroForOne,status:a,statusLabel:Ze(a),amountIn:s.amountIn.toString(),minAmountOut:s.minAmountOut.toString(),bounty:s.bounty.toString(),sqrtPriceLimitX96:s.sqrtPriceLimitX96.toString(),tokenIn:b,tokenOut:y,fillable:p,quotedAmountOut:d.toString()}}function st(e){return{name:"hookr_create",inputSchema:{type:"object",properties:{key:{type:"object",properties:{currency0:{type:"string"},currency1:{type:"string"},fee:{type:"number"},tickSpacing:{type:"number"},hooks:{type:"string"}}},tokenIn:{type:"string",description:"Input token address on chain 4663."},tokenOut:{type:"string",description:"Output token address on chain 4663."},zeroForOne:{type:"boolean",description:"True when selling currency0 for currency1."},amountIn:{type:"string",description:"Input amount in base units (uint128)."},minAmountOut:{type:"string",description:"Minimum net output amount in base units (uint128)."},tick:{type:"number",description:"Optional limit tick in [-887272, 887272]."},expiry:{type:"string",description:"Order expiry unix timestamp in seconds (uint40)."},deadline:{type:"string",description:"Alias for expiry unix timestamp in seconds."},bounty:{type:"string",description:"Keeper bounty in native ETH wei (uint128)."},recipient:{type:"string",description:"Order output recipient address (must be the signing wallet)."},sqrtPriceLimitX96:{type:"string",description:"Optional sqrtPriceLimitX96 (defaults to 0)."},chainId:{type:"number",description:"Must be 4663 (Robinhood Chain)."}},required:["amountIn"]},async execute(t,n){v(n);let r=l(n),i=be(t.chainId),u=e.clientFor(i),s=Ae(t),{key:a,zeroForOne:c}=et(t),w=c?a.currency0:a.currency1,f=c?a.currency1:a.currency0,[g,b]=await Promise.all([Z(w,i,u,t.tokenInMeta),Z(f,i,u,t.tokenOutMeta)]),y=t.recipient??r;if(typeof y!="string"||!$(y,{strict:!1}))throw new o("Provide a valid recipient address for the Hookr limit order.");let p=l(y);if(Oe(p,a.hooks),p!==r)throw new o("Hookr recipient must be the signing wallet.");if(typeof t.amountIn!="string")throw new o("Provide amountIn as an integer string in base units.");let d=R(t.amountIn);if(d<=0n||d>Ke)throw new o("amountIn must be between 1 and int128.max base units.");if(t.tick!==void 0){let P=Number(t.tick);G(P)}let m;if(t.minAmountOut!==void 0){if(typeof t.minAmountOut!="string")throw new o("Provide minAmountOut as an integer string in base units.");m=R(t.minAmountOut)}else if(t.tick!==void 0)m=tt(d,Number(t.tick),c);else throw new o("Provide minAmountOut in base units (or tick to derive minAmountOut).");if(m<=0n||m>me)throw new o("minAmountOut must be between 1 and uint128.max base units.");let I=t.sqrtPriceLimitX96!==void 0?T(t.sqrtPriceLimitX96,"sqrtPriceLimitX96"):0n;if(I>Ue)throw new o("sqrtPriceLimitX96 exceeds uint160 bounds.");let k=await nt(u,t.now),C=t.expiry??t.deadline,O;if(C!==void 0)O=T(C,"expiry");else if(t.lifetime!==void 0||t.ttlSeconds!==void 0){let P=T(t.lifetime??t.ttlSeconds,"lifetime");O=k+P}else O=k+qe;if(O<k+de)throw new o(`Order expiry (${O}) is expired or below the minimum lifetime of ${de} seconds from block timestamp ${k}.`);if(O>k+ce||O>je)throw new o(`Order expiry (${O}) exceeds the maximum lifetime of ${ce} seconds (365 days).`);let M=await u.readContract({address:A,abi:D,functionName:"bountyBounds",args:[a,c,d,m]}).catch(()=>{throw new o("Could not read Hookr bounty bounds.")}),E=BigInt(M[0]),z=BigInt(M[1]),q=BigInt(M[2]);if(t.bounty!==void 0&&typeof t.bounty!="string")throw new o("Provide bounty as an integer string in base units.");let h=t.bounty!==void 0?R(t.bounty):z,X=E>0n?E:z;if(h<E||X>0n&&h<X)throw new o(`Order keeper bounty (${h} wei) is underbounty: must be at least ${X} wei (default keeper bounty floor).`);if(h>q||h>me)throw new o(`Order keeper bounty (${h} wei) exceeds the maximum allowed bounty of ${q} wei.`);let ee=w.toLowerCase()===L.toLowerCase(),_=[];if(!ee){let P;try{let K=await u.readContract({address:w,abi:Q,functionName:"allowance",args:[r,A]});if(typeof K!="bigint"||K<0n)throw new o("Invalid token allowance.");P=K}catch{throw new o(`Could not read token allowance for ${w}. No approval was prepared.`)}P<d&&_.push(e.approval(w,A,d.toString(),i))}let De=ee?d+h:h,Le=ye({abi:D,functionName:"createOrder",args:[{key:a,zeroForOne:c,amountIn:d,minAmountOut:m,sqrtPriceLimitX96:I,recipient:p,expiry:Number(O),bounty:h}]}),te=e.formatAmount(d.toString(),g.decimals),ne=e.formatAmount(m.toString(),b.decimals),oe=e.formatAmount(h.toString(),18),Pe=e.unsignedTx({to:A,data:Le,value:De.toString(),chainId:i,description:`Create Hookr limit order on ${A}: sell ${te} ${g.symbol} (${g.address}) for at least ${ne} ${b.symbol} (${b.address}) with ${oe} ETH keeper bounty (fee=${a.fee}, tickSpacing=${a.tickSpacing}, expiry=${O}).`});_.push(Pe);let re=await e.preview(_,r),Te=Ie(re,e),Re=ke(a);return{txs:_,summary:`Hookr limit order prepared: sell ${te} ${g.symbol} for at least ${ne} ${b.symbol} (bounty ${oe} ETH, expiry ${O}; preview deltas: ${Te}).`,preview:re,poolId:Re,key:a,zeroForOne:c,amountIn:d.toString(),minAmountOut:m.toString(),bounty:h.toString(),bountyBounds:{minBounty:E.toString(),defaultBounty:z.toString(),maxBounty:q.toString()},expiry:O.toString(),recipient:p,sqrtPriceLimitX96:I.toString(),tokenIn:g,tokenOut:b,...s!==void 0?{orderId:s}:{}}}}}function at(e){return{name:"hookr_cancel",inputSchema:{type:"object",properties:{orderId:{type:"string",description:"Hookr order ID to cancel (uint256 decimal string)."},to:{type:"string",description:"Recipient address for the refunded principal and bounty (must be the signing wallet)."},chainId:{type:"number",description:"Must be 4663 (Robinhood Chain)."}},required:["orderId"]},async execute(t,n){v(n);let r=l(n),i=be(t.chainId),u=Ae(t),s=t.orderId??t.id??u;if(s===void 0)throw new o("Provide orderId to cancel a Hookr limit order.");let a=T(s,"orderId");if(a<=0n)throw new o("orderId must be a positive integer.");let c=await Ce(e,a);if(c.owner.toLowerCase()!==r.toLowerCase())throw new o(`Unauthorized cancellation: only the order owner (${c.owner}) can cancel Hookr order #${a} (caller is ${r}).`);if(c.status!==F)throw new o(`Hookr order #${a} is not open (current status: ${c.statusLabel}).`);let w=t.to??r;if(typeof w!="string"||!$(w,{strict:!1}))throw new o("Provide a valid refund recipient address for cancel.");let f=l(w);if(Oe(f,c.key.hooks),f!==r)throw new o("Hookr refund recipient must be the signing wallet.");let g=ye({abi:D,functionName:"cancel",args:[a,f]}),b=e.formatAmount(c.amountIn,c.tokenIn.decimals),y=e.formatAmount(c.bounty,18),p=e.unsignedTx({to:A,data:g,value:"0",chainId:i,description:`Cancel Hookr limit order #${a} on ${A} and refund ${b} ${c.tokenIn.symbol} plus ${y} ETH bounty to ${f}.`}),d=await e.preview([p],r),m=Ie(d,e);return{txs:[p],summary:`Cancel Hookr limit order #${a}: refund ${b} ${c.tokenIn.symbol} and ${y} ETH bounty to ${f} (preview deltas: ${m}).`,preview:d,orderId:a.toString(),to:f,refundedAmountIn:c.amountIn,refundedBounty:c.bounty,tokenIn:c.tokenIn,tokenOut:c.tokenOut}}}}function dt(e){let t=performance.now()+Xe;return new Proxy(e,{get(n,r,i){return r!=="readContract"?Reflect.get(n,r,i):async(...u)=>{let s=t-performance.now(),a=()=>new o("Hookr scan deadline exceeded. Order coverage is incomplete; retry later.");if(s<=0)throw a();let c;try{return await Promise.race([n.readContract(...u),new Promise((w,f)=>{c=setTimeout(()=>f(a()),s)})])}finally{c!==void 0&&clearTimeout(c)}}}})}function ct(e){return async t=>{v(t);let n=l(t),r=dt(e.clientFor(S)),i={...e,clientFor:()=>r},u=await r.readContract({address:A,abi:D,functionName:"lastOrderId"}).catch(()=>{throw new o("Could not read the last Hookr order ID. Order coverage is incomplete.")});if(typeof u!="bigint"||u<0n)throw new o("Could not read a valid last Hookr order ID. Order coverage is incomplete.");let s=u,a=s>ue?s-ue+1n:1n;if(s<=0n)return[];let c=[],w=new Map;for(let f=a;f<=s;f+=Y){let g=Array.from({length:Number(s-f+1n<Y?s-f+1n:Y)},(y,p)=>f+BigInt(p)),b=await Promise.all(g.map(async y=>{let p=await r.readContract({address:A,abi:D,functionName:"getOrder",args:[y]}).catch(()=>{throw new o(`Could not read Hookr order #${y}. Order coverage is incomplete.`)}),d=Se(p);if(d.owner.toLowerCase()===L||Number(d.status)===J)throw new o(`Hookr order #${y} does not exist. Order coverage is incomplete.`);return{id:y,order:d}}));for(let{id:y,order:p}of b){if(p.owner.toLowerCase()!==n.toLowerCase()||Number(p.status)!==F)continue;let d=await Ce(i,y,{order:p,tokens:w}),m=[{token:d.tokenIn,amount:d.amountIn}];BigInt(d.bounty)>0n&&m.push({token:{address:N,symbol:"ETH",decimals:18,chainId:S},amount:d.bounty});let I=e.formatAmount(d.amountIn,d.tokenIn.decimals),k=e.formatAmount(d.minAmountOut,d.tokenOut.decimals),C=e.formatAmount(d.bounty,18),O=e.formatAmount(d.quotedAmountOut,d.tokenOut.decimals);c.push({module:"hookr",id:d.orderId,chainId:S,assets:m,description:`Hookr open limit order #${d.orderId}: sell ${I} ${d.tokenIn.symbol} (${d.tokenIn.address}) for at least ${k} ${d.tokenOut.symbol} (${d.tokenOut.address}), bounty ${C} ETH, expiry ${d.expiry}, fillable=${d.fillable} (quoted output ${O} ${d.tokenOut.symbol}).`})}}return a>1n&&c.push({module:"hookr",id:"coverage",chainId:S,assets:[],description:`Hookr order coverage is incomplete: scanned IDs ${a}-${s}. Older orders require an explicit order ID.`}),c}}var xe=e=>{let t=[st(e),at(e)],n=ct(e);return{tools:t,positions:n}},Dt=xe,Lt=xe;export{A as a,_e as b,ve as c,kt as d,Ne as e,Be as f,Ot as g,Fe as h,Me as i,ze as j,de as k,qe as l,ce as m,It as n,At as o,ht as p,St as q,ue as r,Xe as s,J as t,F as u,Ge as v,Ye as w,Qe as x,Ct as y,D as z,Je as A,xt as B,ke as C,ot as D,he as E,rt as F,it as G,Se as H,Ce as I,st as J,at as K,dt as L,ct as M,xe as N,Dt as O,Lt as P};
|
|
1
|
+
import{i as G}from"./FUXT7GRK.js";import{b as j,c as V,d as W}from"./JPOYTTTW.js";import{d as ae,e as L}from"./5O5ZE3ZV.js";import{a as N}from"./CY75R4FK.js";import{a as v}from"./6IM6A5VA.js";import{a as R,b as ie,c as se,d as U}from"./RETS2ZEK.js";import{a as S,i as x}from"./G6HCV67X.js";import{a as o}from"./5YS5V2LK.js";import{decodeEventLog as He,encodeAbiParameters as fe,encodeFunctionData as ye,erc20Abi as Q,getAddress as l,isAddress as $,keccak256 as $e,parseAbi as Ee,parseAbiParameters as pe,toEventSelector as we}from"viem";var A=l(x[4663].hookr.HookrLimitOrders.address),_e=l(x[4663].hookr.HookrRoot.address),ve=l(x[4663].hookr.HookrRouter.address),kt=l(x[4663].hookr.HookrRegistry.address),Ne=l(x[4663].hookr.HookrForwarder.address),Be=l(x[4663].hookr.PoolManager.address),Ot=l(x[4663].hookr.HOOKR_Token.address),Fe=l("0x000000000000000000000000000000000000dEaD"),Me=8388608,ze=200,de=60n,qe=604800n,ce=31536000n,It=10,At=100,ht="500000000000000",St="10000000000000000",ue=4096n,Y=32n,Xe=1e4,Ke=(1n<<127n)-1n,me=(1n<<128n)-1n,Ue=(1n<<160n)-1n,je=(1n<<40n)-1n,Ve=16777215,We=8388607,le=1n<<192n,J=0,F=1,Ge=2,Ye=3,Qe=we("OrderCreated(uint256,address,bytes32,bool,uint128,uint128,uint128,uint40,address)"),Ct=we("OrderCancelled(uint256,address,address,uint256,uint256)"),D=Ee(["function bountyBounds((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, bool zeroForOne, uint128 amountIn, uint128 minAmountOut) view returns (uint128 minBounty, uint128 defaultBounty, uint128 maxBounty)","function createOrder(((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, bool zeroForOne, uint128 amountIn, uint128 minAmountOut, uint160 sqrtPriceLimitX96, address recipient, uint40 expiry, uint128 bounty) params) payable returns (uint256 orderId)","function cancel(uint256 orderId, address to)","function getOrder(uint256 orderId) view returns (((address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks) key, address owner, uint40 createdAt, uint40 expiry, bool zeroForOne, uint8 status, address recipient, uint128 amountIn, uint128 minAmountOut, uint128 bounty, uint160 sqrtPriceLimitX96))","function quoteFill(uint256 orderId) view returns (bool fillable, uint256 amountOut)","function lastOrderId() view returns (uint256)","function liabilities(address currency) view returns (uint256)","function router() view returns (address)","function registry() view returns (address)","function poolManager() view returns (address)","function forwarder() view returns (address)","event OrderCreated(uint256 indexed orderId, address indexed owner, bytes32 indexed poolId, bool zeroForOne, uint128 amountIn, uint128 minAmountOut, uint128 bounty, uint40 expiry, address recipient)","event OrderCancelled(uint256 indexed orderId, address indexed owner, address indexed to, uint256 amountIn, uint256 bounty)"]);function B(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ge(e){let t=e.toLowerCase();return t===L.toLowerCase()||t===N.toLowerCase()||t===ae.toLowerCase()}function H(e,t){if(typeof e!="string"||!e.trim())throw new o(`Provide a valid contract address for ${t}. Identify tokens by chain and address, never by symbol.`);let n=e.trim();if(!$(n,{strict:!1}))throw new o(`Invalid token address "${n}" for ${t}. Identify tokens by chain and address, never by symbol.`);return ge(n)?L:l(n)}function be(e){let t=e===void 0?S:Number(e);if(!Number.isSafeInteger(t)||t!==S)throw new o(`Hookr limit orders are only supported on Robinhood Chain (${S}).`);return S}function Ze(e){switch(e){case J:return"None";case F:return"Open";case Ge:return"Filled";case Ye:return"Cancelled";default:return"Unknown"}}function Je(e,t,n=se){if(typeof e!="string"||!/^-?\d+$/.test(e.trim()))throw new o("Signed amount must be an integer string in base units.");let r=e.trim();if(r.startsWith("-")){let i=r.slice(1),u=n(i,t);return u==="0"?"0":`-${u}`}return n(r,t)}function xt(e,t,n="floor"){return ie(e,t,n)}function ke(e){return $e(fe(pe("address, address, uint24, int24, address"),[l(e.currency0),l(e.currency1),e.fee,e.tickSpacing,l(e.hooks)]))}function Oe(e,t){let n=e.toLowerCase();if(new Set([L.toLowerCase(),Fe.toLowerCase(),A.toLowerCase(),ve.toLowerCase(),Ne.toLowerCase(),Be.toLowerCase(),t.toLowerCase()]).has(n))throw new o(`Recipient ${e} is a reserved address and cannot receive Hookr limit order funds.`)}async function Z(e,t,n,r){if(ge(e))return{address:N,symbol:j.symbol,decimals:j.decimals,chainId:t};let i=l(e),u=i.toLowerCase();if(B(r)){let s=typeof r.decimals=="number"&&Number.isInteger(r.decimals)&&r.decimals>=0&&r.decimals<=255?r.decimals:void 0,a=typeof r.symbol=="string"&&r.symbol.trim()?r.symbol.trim():void 0;if(s!==void 0&&a!==void 0)return{address:i,symbol:a,decimals:s,chainId:t}}if(u===V.address.toLowerCase())return{...V,chainId:t};if(u===W.address.toLowerCase())return{...W,chainId:t};try{let[s,a]=await Promise.all([n.readContract({address:i,abi:Q,functionName:"symbol"}),n.readContract({address:i,abi:Q,functionName:"decimals"})]);if(typeof s!="string"||!s.trim()||typeof a!="number"||!Number.isInteger(a)||a<0||a>255)throw new o(`Invalid token metadata for ${i}.`);return{address:i,symbol:s.trim(),decimals:a,chainId:t}}catch{throw new o(`Could not read valid token metadata for ${i}. Refusing to guess token decimals.`)}}function et(e){let t=B(e.key)?e.key:B(e.poolKey)?e.poolKey:void 0,n=t?.fee??e.fee??Me,r=(typeof n=="string"&&/^\d+$/.test(n),Number(n));if(!Number.isInteger(r)||r<0||r>Ve)throw new o("Pool fee must be a valid uint24 integer (default 8388608 for Hookr dynamic fee pools).");let i=t?.tickSpacing??e.tickSpacing??ze,u=(typeof i=="string"&&/^-?\d+$/.test(i),Number(i));if(!Number.isInteger(u)||u<=0||u>We)throw new o("Pool tickSpacing must be a positive int24 integer.");let s=t?.hooks??e.hooks??_e;if(typeof s!="string"||!$(s,{strict:!1}))throw new o("Provide a valid Hookr root contract address for hooks.");let a=l(s);if(t?.currency0!==void 0&&t?.currency1!==void 0||e.currency0!==void 0&&e.currency1!==void 0){let m=H(t?.currency0??e.currency0,"currency0"),I=H(t?.currency1??e.currency1,"currency1");if(m.toLowerCase()===I.toLowerCase())throw new o("Pool currency0 and currency1 must be distinct token addresses.");if(BigInt(m)>=BigInt(I))throw new o("Pool currency0 must sort strictly before currency1 by address.");let k;if(typeof e.zeroForOne=="boolean")k=e.zeroForOne;else if(e.tokenIn!==void 0||e.from!==void 0){let C=H(e.tokenIn??e.from,"tokenIn");if(C.toLowerCase()===m.toLowerCase())k=!0;else if(C.toLowerCase()===I.toLowerCase())k=!1;else throw new o("tokenIn does not match currency0 or currency1 of the pool key.")}else throw new o("Provide zeroForOne (boolean) or tokenIn when specifying a pool key.");return{key:{currency0:m,currency1:I,fee:r,tickSpacing:u,hooks:a},zeroForOne:k}}let w=e.tokenIn??e.from,f=e.tokenOut??e.to;if(w===void 0||f===void 0)throw new o("Provide either key ({ currency0, currency1, fee, tickSpacing, hooks }) with zeroForOne or tokenIn and tokenOut addresses.");let g=H(w,"tokenIn"),b=H(f,"tokenOut");if(g.toLowerCase()===b.toLowerCase())throw new o("Input and output tokens must have distinct addresses.");let y=BigInt(g)<BigInt(b),p=y?g:b,d=y?b:g;if(typeof e.zeroForOne=="boolean"&&e.zeroForOne!==y)throw new o("zeroForOne conflicts with the canonical sorting of tokenIn and tokenOut.");return{key:{currency0:p,currency1:d,fee:r,tickSpacing:u,hooks:a},zeroForOne:y}}function tt(e,t,n){let r=G(t),i=r*r;if(n){let s=U(e.toString(),i.toString(),le.toString(),"ceil");return BigInt(s)}let u=U(e.toString(),le.toString(),i.toString(),"ceil");return BigInt(u)}function T(e,t){if(typeof e=="bigint"){if(e<0n)throw new o(`${t} must be a non-negative integer.`);return e}if(typeof e=="number"){if(!Number.isSafeInteger(e)||e<0)throw new o(`${t} must be a non-negative safe integer.`);return BigInt(e)}if(typeof e=="string")return R(e.trim());throw new o(`Provide ${t} as a decimal base-unit string.`)}async function nt(e,t){if(t!==void 0)return T(t,"now");if(typeof e.getBlock=="function"){let n=await e.getBlock().catch(()=>{throw new o("Could not read the chain timestamp for Hookr order expiry.")});return BigInt(n.timestamp)}throw new o("Could not read the chain timestamp for Hookr order expiry.")}function Ie(e,t){return!e.changes||e.changes.length===0?"no net ERC-20 transfer deltas":e.changes.map(n=>`${Je(n.amount,n.token.decimals,t.formatAmount)} ${n.token.symbol}`).join(", ")}function ot(e,t,n,r){if(!e||!Array.isArray(e.logs))throw new o("Provide a transaction receipt with a logs array.");for(let i of e.logs){if(!i||typeof i.address!="string"||!$(i.address,{strict:!1})||!Array.isArray(i.topics)||typeof i.data!="string"||i.topics.some(u=>typeof u!="string"||!/^0x[0-9a-fA-F]{64}$/.test(u)))throw new o(`Malformed Hookr ${t} receipt log.`);if(i.address.toLowerCase()===A.toLowerCase()&&i.topics[0]?.toLowerCase()===n.toLowerCase()){if(i.topics.length!==4||!/^0x0{24}/i.test(i.topics[2])||t==="OrderCancelled"&&!/^0x0{24}/i.test(i.topics[3])||!/^0x[0-9a-fA-F]*$/.test(i.data)||i.data.length!==2+r*64)throw new o(`Malformed Hookr ${t} receipt log.`);return{topics:i.topics,data:i.data}}}throw new o(`Could not find Hookr ${t} event in transaction receipt logs.`)}function Ae(e){if(e.receipt!==void 0){if(!B(e.receipt)||!Array.isArray(e.receipt.logs))throw new o("Provide a transaction receipt with a logs array.");return it({logs:e.receipt.logs})}if(e.logs!==void 0){if(!Array.isArray(e.logs))throw new o("Provide receipt logs as an array.");return rt(e.logs)}}function he(e){let t=ot(e,"OrderCreated",Qe,6);try{let n=He({abi:D,eventName:"OrderCreated",...t,strict:!0});if(fe(pe("bool, uint128, uint128, uint128, uint40, address"),[n.args.zeroForOne,n.args.amountIn,n.args.minAmountOut,n.args.bounty,n.args.expiry,n.args.recipient]).toLowerCase()!==t.data.toLowerCase())throw new o("Noncanonical Hookr OrderCreated event data.");return{orderId:n.args.orderId.toString(),owner:l(n.args.owner),poolId:n.args.poolId,zeroForOne:n.args.zeroForOne,amountIn:n.args.amountIn.toString(),minAmountOut:n.args.minAmountOut.toString(),bounty:n.args.bounty.toString(),expiry:n.args.expiry.toString(),recipient:l(n.args.recipient)}}catch{throw new o("Malformed Hookr OrderCreated receipt log.")}}function rt(e){return he({logs:e}).orderId}function it(e){return he(e).orderId}function Se(e){if(Array.isArray(e)){let[n,r,i,u,s,a,c,w,f,g,b]=e;return{key:Array.isArray(n)?{currency0:n[0],currency1:n[1],fee:Number(n[2]),tickSpacing:Number(n[3]),hooks:n[4]}:n,owner:r,createdAt:i,expiry:u,zeroForOne:s,status:a,recipient:c,amountIn:BigInt(w),minAmountOut:BigInt(f),bounty:BigInt(g),sqrtPriceLimitX96:BigInt(b)}}let t=e;return{key:{currency0:t.key.currency0,currency1:t.key.currency1,fee:Number(t.key.fee),tickSpacing:Number(t.key.tickSpacing),hooks:t.key.hooks},owner:t.owner,createdAt:t.createdAt,expiry:t.expiry,zeroForOne:!!t.zeroForOne,status:Number(t.status),recipient:t.recipient,amountIn:BigInt(t.amountIn),minAmountOut:BigInt(t.minAmountOut),bounty:BigInt(t.bounty),sqrtPriceLimitX96:BigInt(t.sqrtPriceLimitX96)}}async function Ce(e,t,n){let r=T(t,"orderId");if(r<=0n)throw new o("Order ID must be a positive integer.");let i=e.clientFor(S),u=n?.order??await i.readContract({address:A,abi:D,functionName:"getOrder",args:[r]}).catch(()=>{throw new o(`Could not read Hookr order #${r}. Order coverage is incomplete.`)}),s=Se(u),a=Number(s.status);if(s.owner.toLowerCase()===L.toLowerCase()||a===J)throw new o(`Hookr order #${r} does not exist.`);let c={currency0:l(s.key.currency0),currency1:l(s.key.currency1),fee:Number(s.key.fee),tickSpacing:Number(s.key.tickSpacing),hooks:l(s.key.hooks)},w=s.zeroForOne?c.currency0:c.currency1,f=s.zeroForOne?c.currency1:c.currency0,g=m=>{let I=m.toLowerCase(),k=n?.tokens.get(I);if(k)return k;let C=Z(m,S,i);return n?.tokens.set(I,C),C},[b,y]=await Promise.all([g(w),g(f)]),p=!1,d=0n;if(a===F)try{let m=await i.readContract({address:A,abi:D,functionName:"quoteFill",args:[r]});if(typeof m[0]!="boolean"||typeof m[1]!="bigint"||m[1]<0n)throw new o(`Invalid quote for Hookr order #${r}.`);p=m[0],d=m[1]}catch{throw new o(`Could not quote Hookr order #${r}. Fillability and output amount are unknown.`)}return{orderId:r.toString(),poolId:ke(c),key:c,owner:l(s.owner),recipient:l(s.recipient),createdAt:BigInt(s.createdAt).toString(),expiry:BigInt(s.expiry).toString(),zeroForOne:s.zeroForOne,status:a,statusLabel:Ze(a),amountIn:s.amountIn.toString(),minAmountOut:s.minAmountOut.toString(),bounty:s.bounty.toString(),sqrtPriceLimitX96:s.sqrtPriceLimitX96.toString(),tokenIn:b,tokenOut:y,fillable:p,quotedAmountOut:d.toString()}}function st(e){return{name:"hookr_create",inputSchema:{type:"object",properties:{key:{type:"object",properties:{currency0:{type:"string"},currency1:{type:"string"},fee:{type:"number"},tickSpacing:{type:"number"},hooks:{type:"string"}}},tokenIn:{type:"string",description:"Input token address on chain 4663."},tokenOut:{type:"string",description:"Output token address on chain 4663."},zeroForOne:{type:"boolean",description:"True when selling currency0 for currency1."},amountIn:{type:"string",description:"Input amount in base units (uint128)."},minAmountOut:{type:"string",description:"Minimum net output amount in base units (uint128)."},tick:{type:"number",description:"Optional limit tick in [-887272, 887272]."},expiry:{type:"string",description:"Order expiry unix timestamp in seconds (uint40)."},deadline:{type:"string",description:"Alias for expiry unix timestamp in seconds."},bounty:{type:"string",description:"Keeper bounty in native ETH wei (uint128)."},recipient:{type:"string",description:"Order output recipient address (must be the signing wallet)."},sqrtPriceLimitX96:{type:"string",description:"Optional sqrtPriceLimitX96 (defaults to 0)."},chainId:{type:"number",description:"Must be 4663 (Robinhood Chain)."}},required:["amountIn"]},async execute(t,n){v(n);let r=l(n),i=be(t.chainId),u=e.clientFor(i),s=Ae(t),{key:a,zeroForOne:c}=et(t),w=c?a.currency0:a.currency1,f=c?a.currency1:a.currency0,[g,b]=await Promise.all([Z(w,i,u,t.tokenInMeta),Z(f,i,u,t.tokenOutMeta)]),y=t.recipient??r;if(typeof y!="string"||!$(y,{strict:!1}))throw new o("Provide a valid recipient address for the Hookr limit order.");let p=l(y);if(Oe(p,a.hooks),p!==r)throw new o("Hookr recipient must be the signing wallet.");if(typeof t.amountIn!="string")throw new o("Provide amountIn as an integer string in base units.");let d=R(t.amountIn);if(d<=0n||d>Ke)throw new o("amountIn must be between 1 and int128.max base units.");if(t.tick!==void 0){let P=Number(t.tick);G(P)}let m;if(t.minAmountOut!==void 0){if(typeof t.minAmountOut!="string")throw new o("Provide minAmountOut as an integer string in base units.");m=R(t.minAmountOut)}else if(t.tick!==void 0)m=tt(d,Number(t.tick),c);else throw new o("Provide minAmountOut in base units (or tick to derive minAmountOut).");if(m<=0n||m>me)throw new o("minAmountOut must be between 1 and uint128.max base units.");let I=t.sqrtPriceLimitX96!==void 0?T(t.sqrtPriceLimitX96,"sqrtPriceLimitX96"):0n;if(I>Ue)throw new o("sqrtPriceLimitX96 exceeds uint160 bounds.");let k=await nt(u,t.now),C=t.expiry??t.deadline,O;if(C!==void 0)O=T(C,"expiry");else if(t.lifetime!==void 0||t.ttlSeconds!==void 0){let P=T(t.lifetime??t.ttlSeconds,"lifetime");O=k+P}else O=k+qe;if(O<k+de)throw new o(`Order expiry (${O}) is expired or below the minimum lifetime of ${de} seconds from block timestamp ${k}.`);if(O>k+ce||O>je)throw new o(`Order expiry (${O}) exceeds the maximum lifetime of ${ce} seconds (365 days).`);let M=await u.readContract({address:A,abi:D,functionName:"bountyBounds",args:[a,c,d,m]}).catch(()=>{throw new o("Could not read Hookr bounty bounds.")}),E=BigInt(M[0]),z=BigInt(M[1]),q=BigInt(M[2]);if(t.bounty!==void 0&&typeof t.bounty!="string")throw new o("Provide bounty as an integer string in base units.");let h=t.bounty!==void 0?R(t.bounty):z,X=E>0n?E:z;if(h<E||X>0n&&h<X)throw new o(`Order keeper bounty (${h} wei) is underbounty: must be at least ${X} wei (default keeper bounty floor).`);if(h>q||h>me)throw new o(`Order keeper bounty (${h} wei) exceeds the maximum allowed bounty of ${q} wei.`);let ee=w.toLowerCase()===L.toLowerCase(),_=[];if(!ee){let P;try{let K=await u.readContract({address:w,abi:Q,functionName:"allowance",args:[r,A]});if(typeof K!="bigint"||K<0n)throw new o("Invalid token allowance.");P=K}catch{throw new o(`Could not read token allowance for ${w}. No approval was prepared.`)}P<d&&_.push(e.approval(w,A,d.toString(),i))}let De=ee?d+h:h,Le=ye({abi:D,functionName:"createOrder",args:[{key:a,zeroForOne:c,amountIn:d,minAmountOut:m,sqrtPriceLimitX96:I,recipient:p,expiry:Number(O),bounty:h}]}),te=e.formatAmount(d.toString(),g.decimals),ne=e.formatAmount(m.toString(),b.decimals),oe=e.formatAmount(h.toString(),18),Pe=e.unsignedTx({to:A,data:Le,value:De.toString(),chainId:i,description:`Create Hookr limit order on ${A}: sell ${te} ${g.symbol} (${g.address}) for at least ${ne} ${b.symbol} (${b.address}) with ${oe} ETH keeper bounty (fee=${a.fee}, tickSpacing=${a.tickSpacing}, expiry=${O}).`});_.push(Pe);let re=await e.preview(_,r),Te=Ie(re,e),Re=ke(a);return{txs:_,summary:`Hookr limit order prepared: sell ${te} ${g.symbol} for at least ${ne} ${b.symbol} (bounty ${oe} ETH, expiry ${O}; preview deltas: ${Te}).`,preview:re,poolId:Re,key:a,zeroForOne:c,amountIn:d.toString(),minAmountOut:m.toString(),bounty:h.toString(),bountyBounds:{minBounty:E.toString(),defaultBounty:z.toString(),maxBounty:q.toString()},expiry:O.toString(),recipient:p,sqrtPriceLimitX96:I.toString(),tokenIn:g,tokenOut:b,...s!==void 0?{orderId:s}:{}}}}}function at(e){return{name:"hookr_cancel",inputSchema:{type:"object",properties:{orderId:{type:"string",description:"Hookr order ID to cancel (uint256 decimal string)."},to:{type:"string",description:"Recipient address for the refunded principal and bounty (must be the signing wallet)."},chainId:{type:"number",description:"Must be 4663 (Robinhood Chain)."}},required:["orderId"]},async execute(t,n){v(n);let r=l(n),i=be(t.chainId),u=Ae(t),s=t.orderId??t.id??u;if(s===void 0)throw new o("Provide orderId to cancel a Hookr limit order.");let a=T(s,"orderId");if(a<=0n)throw new o("orderId must be a positive integer.");let c=await Ce(e,a);if(c.owner.toLowerCase()!==r.toLowerCase())throw new o(`Unauthorized cancellation: only the order owner (${c.owner}) can cancel Hookr order #${a} (caller is ${r}).`);if(c.status!==F)throw new o(`Hookr order #${a} is not open (current status: ${c.statusLabel}).`);let w=t.to??r;if(typeof w!="string"||!$(w,{strict:!1}))throw new o("Provide a valid refund recipient address for cancel.");let f=l(w);if(Oe(f,c.key.hooks),f!==r)throw new o("Hookr refund recipient must be the signing wallet.");let g=ye({abi:D,functionName:"cancel",args:[a,f]}),b=e.formatAmount(c.amountIn,c.tokenIn.decimals),y=e.formatAmount(c.bounty,18),p=e.unsignedTx({to:A,data:g,value:"0",chainId:i,description:`Cancel Hookr limit order #${a} on ${A} and refund ${b} ${c.tokenIn.symbol} plus ${y} ETH bounty to ${f}.`}),d=await e.preview([p],r),m=Ie(d,e);return{txs:[p],summary:`Cancel Hookr limit order #${a}: refund ${b} ${c.tokenIn.symbol} and ${y} ETH bounty to ${f} (preview deltas: ${m}).`,preview:d,orderId:a.toString(),to:f,refundedAmountIn:c.amountIn,refundedBounty:c.bounty,tokenIn:c.tokenIn,tokenOut:c.tokenOut}}}}function dt(e){let t=performance.now()+Xe;return new Proxy(e,{get(n,r,i){return r!=="readContract"?Reflect.get(n,r,i):async(...u)=>{let s=t-performance.now(),a=()=>new o("Hookr scan deadline exceeded. Order coverage is incomplete; retry later.");if(s<=0)throw a();let c;try{return await Promise.race([n.readContract(...u),new Promise((w,f)=>{c=setTimeout(()=>f(a()),s)})])}finally{c!==void 0&&clearTimeout(c)}}}})}function ct(e){return async t=>{v(t);let n=l(t),r=dt(e.clientFor(S)),i={...e,clientFor:()=>r},u=await r.readContract({address:A,abi:D,functionName:"lastOrderId"}).catch(()=>{throw new o("Could not read the last Hookr order ID. Order coverage is incomplete.")});if(typeof u!="bigint"||u<0n)throw new o("Could not read a valid last Hookr order ID. Order coverage is incomplete.");let s=u,a=s>ue?s-ue+1n:1n;if(s<=0n)return[];let c=[],w=new Map;for(let f=a;f<=s;f+=Y){let g=Array.from({length:Number(s-f+1n<Y?s-f+1n:Y)},(y,p)=>f+BigInt(p)),b=await Promise.all(g.map(async y=>{let p=await r.readContract({address:A,abi:D,functionName:"getOrder",args:[y]}).catch(()=>{throw new o(`Could not read Hookr order #${y}. Order coverage is incomplete.`)}),d=Se(p);if(d.owner.toLowerCase()===L||Number(d.status)===J)throw new o(`Hookr order #${y} does not exist. Order coverage is incomplete.`);return{id:y,order:d}}));for(let{id:y,order:p}of b){if(p.owner.toLowerCase()!==n.toLowerCase()||Number(p.status)!==F)continue;let d=await Ce(i,y,{order:p,tokens:w}),m=[{token:d.tokenIn,amount:d.amountIn}];BigInt(d.bounty)>0n&&m.push({token:{address:N,symbol:"ETH",decimals:18,chainId:S},amount:d.bounty});let I=e.formatAmount(d.amountIn,d.tokenIn.decimals),k=e.formatAmount(d.minAmountOut,d.tokenOut.decimals),C=e.formatAmount(d.bounty,18),O=e.formatAmount(d.quotedAmountOut,d.tokenOut.decimals);c.push({module:"hookr",id:d.orderId,chainId:S,assets:m,description:`Hookr open limit order #${d.orderId}: sell ${I} ${d.tokenIn.symbol} (${d.tokenIn.address}) for at least ${k} ${d.tokenOut.symbol} (${d.tokenOut.address}), bounty ${C} ETH, expiry ${d.expiry}, fillable=${d.fillable} (quoted output ${O} ${d.tokenOut.symbol}).`})}}return a>1n&&c.push({module:"hookr",id:"coverage",chainId:S,assets:[],description:`Hookr order coverage is incomplete: scanned IDs ${a}-${s}. Older orders require an explicit order ID.`}),c}}var xe=e=>{let t=[st(e),at(e)],n=ct(e);return{tools:t,positions:n}},Dt=xe,Lt=xe;export{A as a,_e as b,ve as c,kt as d,Ne as e,Be as f,Ot as g,Fe as h,Me as i,ze as j,de as k,qe as l,ce as m,It as n,At as o,ht as p,St as q,ue as r,Xe as s,J as t,F as u,Ge as v,Ye as w,Qe as x,Ct as y,D as z,Je as A,xt as B,ke as C,ot as D,he as E,rt as F,it as G,Se as H,Ce as I,st as J,at as K,dt as L,ct as M,xe as N,Dt as O,Lt as P};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as _}from"./MYBDO5SA.js";import{e as y}from"./73N3TOJL.js";import{a as c,i as x}from"./G6HCV67X.js";import{a}from"./5YS5V2LK.js";import{getAddress as A,isAddress as b}from"viem";function I(p){if(typeof p!="string"||!p.trim()||p.length>200)throw new a("Provide nonempty filter text of at most 200 characters.");return p}function P(p,f){if(typeof p!="number"||!Number.isSafeInteger(p)||p<0||p>f)throw new a(`Choose a pagination integer from 0 to ${f}.`);return p}var w={morpho:{assess:"morpho_status",enter:"morpho_supply_collateral",exit:"morpho_withdraw_collateral"},steakhouse:{assess:"steakhouse_list",enter:"steakhouse_deposit",exit:"steakhouse_withdraw"},spark:{assess:"spark_list",enter:"spark_deposit",exit:"spark_withdraw"},netnet:{assess:"netnet_list",enter:"netnet_deposit",exit:"netnet_withdraw"},longbow:{assess:"longbow_list",enter:"longbow_deposit",exit:"longbow_withdraw"},grove:{assess:"grove_list",enter:"grove_deposit",exit:"grove_withdraw"},beefy:{assess:"beefy_list",enter:"beefy_deposit",exit:"beefy_withdraw"},uniswap:{assess:"uniswap_list_positions",enter:"uniswap_add",exit:"uniswap_remove"}},M=p=>{let f=(e,i,n)=>({name:`merkl_${e}`,inputSchema:{type:"object",properties:i,additionalProperties:!1},execute:async(d,t)=>{try{let o=Object.keys(d).find(s=>!Object.hasOwn(i,s));if(o)throw new a(`Unsupported Merkl input: ${o}.`);return await n(d,t)}catch(o){throw new a(p.plainError(o))}}}),g={page:{type:"integer",minimum:0,maximum:1e4},items:{type:"integer",minimum:1,maximum:100}},k=async(e,i)=>{let n=new URL(`https://api.merkl.xyz/v4/${e}`);for(let[d,t]of Object.entries(i))n.searchParams.set(d,t);return _(p.http,n.toString(),{method:"GET",headers:{"User-Agent":"oak-core/merkl"}},d=>Array.isArray(d)||y(d))},h=e=>{let i=P(e.items??20,100);if(!i)throw new a("Choose at least one item per page.");return{page:String(P(e.page??0,1e4)),items:String(i)}};return{tools:[f("opportunities",{...g,protocol:{type:"string"},name:{type:"string"},explorerAddress:{type:"string"}},async e=>{let i={chainId:String(c),campaigns:"true",...h(e)};if(e.protocol!==void 0&&(i.mainProtocolId=I(e.protocol)),e.name!==void 0&&(i.name=I(e.name)),e.explorerAddress!==void 0){if(typeof e.explorerAddress!="string"||!b(e.explorerAddress,{strict:!1}))throw new a("Provide a pool or market explorer address.");i.explorerAddress=A(e.explorerAddress)}let n=await k("opportunities",i);if(!Array.isArray(n)||!n.every(t=>y(t)&&typeof t.id=="string"&&Number.isSafeInteger(t.chainId)))throw new a("Merkl returned unexpected opportunities.");return{opportunities:n.filter(t=>t.chainId===c).map(t=>{let o=(y(t.protocol)?t.protocol.id:void 0)??t.mainProtocolId??t.mainProtocol,s=typeof o=="string"?o.toLowerCase():"",r;return s==="morpho"&&t.action==="LEND"?t.type==="MORPHOCOLLATERAL"?r=w.morpho:typeof t.type=="string"&&(t.type==="ERC20LOGPROCESSOR"||t.type.includes("MORPHOVAULT"))&&typeof t.explorerAddress=="string"&&b(t.explorerAddress,{strict:!1})&&A(t.explorerAddress)===x[c].vaults.steakhouse.address&&(r=w.steakhouse):s==="uniswap"?t.type==="UNISWAP_V4"&&t.action==="POOL"&&(r=w.uniswap):s!=="morpho"&&Object.hasOwn(w,s)&&(t.action==="LEND"||t.action==="STAKE")&&(r=w[s]),{...t,oak:{...r?{candidateTools:r}:{},destinationVerificationRequired:!0,eligibility:"Read campaign conditions; no wallet eligibility has been verified."}}}),...h(e),hasMore:n.length===Number(i.items),summary:"Powered by Merkl \u2014 https://app.merkl.xyz. Public, untrusted campaign data includes conditions and destinations. Candidate Oak tools require a matching verified market/vault and a supported entry AND exit. APR is indicative; no rewards are promised."}}),f("campaigns",{...g,creator:{type:"string"},tokenSymbol:{type:"string"},opportunityId:{type:"string",pattern:"^\\d{1,30}$"}},async e=>{if(e.opportunityId!==void 0&&(e.creator!==void 0||e.tokenSymbol!==void 0))throw new a("Use creator and tokenSymbol without opportunityId; the opportunity endpoint does not support those filters.");if(e.opportunityId!==void 0&&(typeof e.opportunityId!="string"||!/^\d{1,30}$/.test(e.opportunityId)||e.opportunityId.trim()!==e.opportunityId))throw new a("Provide an opportunityId as a decimal string of 1 to 30 digits.");let i={chainId:String(c),withOpportunity:"true",...h(e)};if(e.creator!==void 0){if(typeof e.creator!="string"||!b(e.creator,{strict:!1}))throw new a("Provide a creator address.");i.creatorAddress=A(e.creator)}e.tokenSymbol!==void 0&&(i.tokenSymbol=I(e.tokenSymbol));let n=e.opportunityId===void 0?"campaigns":`opportunities/${e.opportunityId}/campaigns`,d=await k(n,e.opportunityId===void 0?i:{}),t=e.opportunityId!==void 0&&y(d)?d:void 0;if(t&&t.chainId!==c)throw new a(`Merkl opportunity must be on chain ${c}.`);let o=e.opportunityId===void 0?d:t?.campaigns;if(!Array.isArray(o)||!o.every(l=>y(l)&&(typeof l.id=="string"||typeof l.id=="number")))throw new a("Merkl returned unexpected campaigns.");let s=t?o.filter(l=>l.distributionChainId===c):o,r=Number(i.page)*Number(i.items),u=e.opportunityId===void 0?s:s.slice(r,r+Number(i.items)),m=e.opportunityId===void 0?s.length===Number(i.items):r+Number(i.items)<s.length;return{campaigns:u,...t?{opportunity:{id:t.id,name:t.name,chainId:t.chainId,protocol:t.protocol,explorerAddress:t.explorerAddress,identifier:t.identifier}}:{},chainId:c,...h(e),hasMore:m,summary:"Powered by Merkl \u2014 https://app.merkl.xyz. Campaign rules, budgets, timing, exclusions and configuration are public API data; verify the reward distribution chain and destination before entering."}}),f("earning_status",{view:{enum:["active","breakdowns","stats","claims"]},...g},async(e,i)=>{if(!b(i,{strict:!1}))throw new a("Provide a valid connected wallet address.");let n=e.view??"active";if(!["active","breakdowns","stats","claims"].includes(String(n)))throw new a("Choose active, breakdowns, stats or claims.");let d=n==="claims"?"claims":n==="breakdowns"?`users/${i}/rewards/chains/${c}/breakdowns`:`users/${i}/rewards/${n==="active"?"active-opportunities":"stats"}`,{page:t,items:o}=h(e),s=n==="breakdowns"?{}:{chainId:String(c)};n==="claims"&&(s.recipient=i);let r=await k(d,s),u=Number(t)*Number(o),m=Array.isArray(r)?r:n==="breakdowns"&&y(r)&&Array.isArray(r.opportunities)?r.opportunities:void 0,l=m?Array.isArray(r)?m.slice(u,u+Number(o)):{...r,opportunities:m.slice(u,u+Number(o))}:r;return{view:n,chainId:c,wallet:i,data:l,...m?{page:t,items:o,hasMore:u+Number(o)<m.length}:{},summary:"Powered by Merkl \u2014 https://app.merkl.xyz. API earning attribution and history can lag onchain state; pending earnings are not claimable. Private or restricted attribution may be omitted by Merkl. Recheck merkl_rewards before a claim."}})]}};export{M as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as m,h as t}from"./73N3TOJL.js";import{b as E}from"./
|
|
1
|
+
import{e as m,h as t}from"./73N3TOJL.js";import{b as E}from"./CXLEQCP3.js";import{i as C}from"./G6HCV67X.js";import{a as v,b as g}from"./5YS5V2LK.js";import{keccak256 as j,parseAbi as D}from"viem";var A=Object.freeze({robinswapV2:Object.freeze({factory:"0xa95DA9b9fCef09A07F99444fE9304457d6ECdccA",kind:"v2",kyberswap:"robinswap-v2",velora:void 0}),uniswapV2:Object.freeze({factory:"0x8BcEAA40b9aCDfAedf85ADf4fF01f5ad6517937F",kind:"v2",kyberswap:"uniswap",velora:"uniswapv2"}),uniswapV3:Object.freeze({factory:C[4663].uniswap.v3_factory.address,kind:"v3",kyberswap:"uniswapv3",velora:"uniswapv3"})}),L=Object.freeze(Object.fromEntries(Object.entries(A).map(([r,n])=>[r,n.factory])));function V(r){return Object.values(A).flatMap(n=>n[r]??[])}var P=D(["function token0() view returns (address)","function token1() view returns (address)","function factory() view returns (address)","function fee() view returns (uint24)"]),S=D(["function getPair(address,address) view returns (address)","function getPool(address,address,uint24) view returns (address)"]),a=new Map;function M(r,n,i){let d=a.get(j(i));return!!d&&d.expires>Date.now()&&t(d.token,r)&&d.pools.some(u=>t(u,n))}async function B(r,n,i,d,u,z){let w=[...new Set(d.filter(o=>!t(o,u)).map(o=>o.toLowerCase()))];if(!w.length)return;let k=j(z);a.delete(k);let f=await r.getBlockNumber();for(let o of w){let s=e=>new v(`KyberSwap source receiver ${o} is not a verified input pool: ${e}.`),l=Array.isArray(n)?n.map(e=>Array.isArray(e)?e[0]:void 0).find(e=>m(e)&&t(e.pool,o)&&t(e.tokenIn,i)):void 0;if(!m(l)||typeof l.tokenOut!="string")throw s("not named as an input hop in the accepted route");let O=await r.getCode({address:o,blockNumber:f});if(!O||O==="0x")throw s("no deployed code");try{let[e,p,y]=await Promise.all(["token0","token1","factory"].map(c=>r.readContract({address:o,abi:P,functionName:c,blockNumber:f}))),h=t(e,i)?p:t(p,i)?e:void 0;if(!h||!t(h,l.tokenOut))throw s("tokens do not match the input route");let x=Object.values(A).find(c=>t(y,c.factory));if(!x)throw s("factory is not pinned");let b;if(x.kind==="v2")b=await r.readContract({address:y,abi:S,functionName:"getPair",args:[e,p],blockNumber:f});else{let c=await r.readContract({address:o,abi:P,functionName:"fee",blockNumber:f});b=await r.readContract({address:y,abi:S,functionName:"getPool",args:[e,p,c],blockNumber:f})}if(!t(b,o))throw s("not registered by the pinned factory")}catch(e){throw e instanceof v||E(e)?e:g(e,3)?s("pool token or factory read reverted; this pool interface is not supported by Oak"):s("on-chain verification unavailable")}}for(let[o,s]of a)s.expires<=Date.now()&&a.delete(o);a.size>=1e3&&a.delete(a.keys().next().value),a.set(k,{token:i,pools:w,expires:Date.now()+6e4})}export{A as a,L as b,V as c,M as d,B as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as Y,e as Z}from"./WQQJ7UPJ.js";import{a as U,b as L,c as D,d as G,e as _,f as W,g as J}from"./3NDVXEBR.js";import{d as C,e as $,v as H}from"./YOENHHKI.js";import{a as K}from"./EG6M6SSO.js";import{a as S}from"./UWOFA6GV.js";import{c as h,g as Q}from"./73N3TOJL.js";import{a as I,i as T}from"./G6HCV67X.js";import{a as o}from"./5YS5V2LK.js";import{encodeAbiParameters as b,encodeFunctionData as ee,encodePacked as de,erc20Abi as me,getAddress as ue,parseAbi as N,parseAbiParameters as A,zeroAddress as v}from"viem";var te=ue("0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7"),ne=ue(T[4663].ponsTrade.quoter.address),fe=N(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),le=N(["function approve(address token,address spender,uint160 amount,uint48 expiration)"]),oe=N(["function factory() view returns (address)","function quoteExactInput(bytes path,uint256 amountIn) returns (uint256,uint160[],uint32[],uint256)","function quoteExactOutput(bytes path,uint256 amountOut) returns (uint256,uint160[],uint32[],uint256)"]),F="(address intermediateCurrency,uint24 fee,int24 tickSpacing,address hooks,bytes hookData)",M="(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks)",re=N([`function quoteExactInput((address exactCurrency,${F}[] path,uint128 exactAmount) params) returns (uint256,uint256)`,`function quoteExactOutput((address exactCurrency,${F}[] path,uint128 exactAmount) params) returns (uint256,uint256)`,`function quoteExactInputSingle((${M} poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256,uint256)`,`function quoteExactOutputSingle((${M} poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256,uint256)`]),ye=A(`(address exactCurrency,${F}[] path,uint256[] minHopPriceX36,uint128 amount,uint128 limit)`);function he(u,t,r,d){let a=[],e=d?r:t,i=new Set([e]);for(let n of d?[...u].reverse():u){let s=n.currency0===e?n.currency1:n.currency1===e?n.currency0:void 0;if(!s||i.has(s))throw new o("V4 poolKeys must form a continuous route without repeated currencies.");a.push({intermediateCurrency:s,fee:n.fee,tickSpacing:n.tickSpacing,hooks:n.hooks,hookData:"0x"}),e=s,i.add(e)}if(e!==(d?t:r))throw new o("V4 route does not end at the requested currency.");return a}var xe=A(`(${M} poolKey,bool zeroForOne,uint128 amount,uint128 limit,uint256 minHopPriceX36,bytes hookData)`),be=A("address recipient,uint256 amount,uint256 limit,bytes path,bool payerIsUser,uint256[] minHopPriceX36"),we=A("address recipient,uint256 amount,uint256 limit,address[] path,bool payerIsUser,uint256[] minHopPriceX36"),ie=A("address,uint256"),ve=A("bytes,bytes[]");function Ae(u,t,r){let d=r?[...u].reverse():u,a=r?[...t].reverse():t,e=d[0];return a.forEach((i,n)=>{e=`${e}${de(["uint24","address"],[i,d[n+1]]).slice(2)}`}),e}var ae={version:{type:"string",enum:["v2","v3","v4"]},tokenIn:h,tokenOut:h,path:{type:"array",minItems:2,maxItems:6,items:h},fees:{type:"array",items:{type:"integer",minimum:0,maximum:1e6}},poolKeys:{type:"array",minItems:1,maxItems:5,items:{type:"object",required:["currency0","currency1","fee","tickSpacing","hooks"],properties:{currency0:h,currency1:h,fee:{type:"integer"},tickSpacing:{type:"integer"},hooks:h},additionalProperties:!1}},poolKey:{type:"object",properties:{currency0:h,currency1:h,fee:{type:"integer"},tickSpacing:{type:"integer"},hooks:h},required:["currency0","currency1","fee","tickSpacing","hooks"],additionalProperties:!1},amountIn:S(),amountOut:S(),minAmountOut:S(),maxAmountIn:S(),slippageBps:{type:"integer",minimum:0,maximum:9999}};async function ke(u,t,r,d=!1){J(t,Object.keys(ae));let a=t.version;if(!["v2","v3","v4"].includes(String(a)))throw new o("Provide version v2, v3 or v4.");let e=t.amountOut!==void 0;if(t.amountIn!==void 0===e)throw new o("Provide exactly one of amountIn or amountOut.");if(e&&t.minAmountOut!==void 0||!e&&t.maxAmountIn!==void 0)throw new o("Use maxAmountIn for exact output, minAmountOut for exact input.");let i=U(e?t.amountOut:t.amountIn,e?"amountOut":"amountIn",a==="v4"?128:160),n=D(t.tokenIn),s=D(t.tokenOut);if(n===s)throw new o("Swap requires different input and output currencies.");let w=u.clientFor(I),m=await w.getBlock(),z=G(t.slippageBps),g,f,q,k,x,p,R;if(a==="v4"){if(t.path!==void 0||t.fees!==void 0)throw new o("V4 uses poolKey or poolKeys; omit path and fees.");if(t.poolKey===void 0==(t.poolKeys===void 0))throw new o("Provide poolKey or poolKeys, not both.");if(t.poolKeys!==void 0){if(!Array.isArray(t.poolKeys)||t.poolKeys.length<1||t.poolKeys.length>5)throw new o("Provide 1 to 5 v4 poolKeys.");let c=t.poolKeys.map(P=>H(P));g=he(c,n,s,e),f=(await w.simulateContract({address:ne,abi:re,functionName:e?"quoteExactOutput":"quoteExactInput",args:[{exactCurrency:e?s:n,path:g,exactAmount:i}],account:r,gas:K,blockNumber:m.number})).result[0]}else{if(x=H(t.poolKey),![x.currency0,x.currency1].includes(n)||![x.currency0,x.currency1].includes(s))throw new o("PoolKey currencies differ from the requested swap.");f=(await w.simulateContract({address:ne,abi:re,functionName:e?"quoteExactOutputSingle":"quoteExactInputSingle",args:[{poolKey:x,zeroForOne:n===x.currency0,exactAmount:i,hookData:"0x"}],account:r,gas:K,blockNumber:m.number})).result[0]}k="0x10"}else{if(t.poolKey!==void 0||t.poolKeys!==void 0||n===v||s===v)throw new o("V2/v3 routes use ERC-20 tokens; wrap ETH to WETH first.");if(p=Array.isArray(t.path)?t.path.map(L):[n,s],p.length<2||p.length>6||p[0]!==n||p.at(-1)!==s||new Set(p).size!==p.length||p.includes(v))throw new o("Path must contain 2 to 6 distinct ERC-20 tokens in input-to-output order.");if(a==="v2"){if(t.fees!==void 0)throw new o("V2 fees are fixed by the pair; omit fees.");let c=await w.readContract({address:Y,abi:Z,functionName:e?"getAmountsIn":"getAmountsOut",args:[i,p],blockNumber:m.number});f=e?c[0]:c.at(-1),k=e?"0x09":"0x08"}else{let c=t.fees;if(!Array.isArray(c)||c.length!==p.length-1||c.some(P=>typeof P!="number"||!Number.isInteger(P)||P<0||P>1e6))throw new o("Provide one integer v3 fee in pips per path hop.");if(!Q(await w.readContract({address:te,abi:oe,functionName:"factory",blockNumber:m.number}),T[4663].uniswap.v3_factory.address))throw new o("V3 quoter is not configured for the pinned factory.");R=Ae(p,c,e),f=(await w.simulateContract({address:te,abi:oe,functionName:e?"quoteExactOutput":"quoteExactInput",args:[R,i],account:r,gas:K,blockNumber:m.number})).result[0],k=e?"0x01":"0x00"}}if(f<=0n)throw new o("No positive Uniswap quote is available.");let V=e?t.maxAmountIn:t.minAmountOut;if(!d&&V===void 0)throw new o(`Provide ${e?"maxAmountIn":"minAmountOut"} from uniswap_quote to confirm the trade bound.`);let l=V===void 0?e?(f*BigInt(1e4+z)+9999n)/10000n:f*BigInt(1e4-z)/10000n:U(V,e?"maxAmountIn":"minAmountOut",a==="v4"?128:160);if(l<=0n||(e?l<f:l>f))throw new o("The fresh quote does not satisfy the confirmed swap bound.");let y=e?l:i;if(y>=1n<<160n||a==="v4"&&(y>=1n<<128n||l>=1n<<128n))throw new o("Swap bounds exceed the router amount range.");let[se,ce]=await Promise.all([_(u,n,m.number),_(u,s,m.number)]),j={version:a,input:{token:se,amount:(e?f:i).toString()},output:{token:ce,amount:(e?i:f).toString()},[e?"maxAmountIn":"minAmountOut"]:l.toString(),blockNumber:m.number.toString(),expiresAt:(m.timestamp+60n).toString()};if(d)return{quote:j,summary:"Read-only on-chain quote. Repeat the same route with the returned bound in uniswap_swap; execution gets a fresh quote and preview."};let O=m.timestamp+300n,E=[],X="Native ETH input; no token approvals.";if(n!==v){let c=await w.readContract({address:n,abi:me,functionName:"allowance",args:[r,C],blockNumber:m.number});c!==y&&E.push(u.approval(n,C,y.toString(),I)),X=`${c===y?"Reuse existing exact ERC-20 allowance of":"Set ERC-20 allowance to exactly"} ${y} input base units to Permit2; exact router permit.`,E.push(u.unsignedTx({to:C,data:ee({abi:le,functionName:"approve",args:[n,$,y,Number(O)]}),value:"0",chainId:I,description:`Permit exactly ${y} input base units to Universal Router until ${O}.`}))}if(a==="v4"){let c=g?b(ye,[{exactCurrency:e?s:n,path:g,minHopPriceX36:[],amount:i,limit:l}]):b(xe,[{poolKey:x,zeroForOne:n===x.currency0,amount:i,limit:l,minHopPriceX36:0n,hookData:"0x"}]);q=b(ve,[g?e?"0x090c0f":"0x070c0f":e?"0x080c0f":"0x060c0f",[c,b(ie,[n,y]),b(ie,[s,e?i:l])]])}else a==="v2"?q=b(we,[r,i,l,p,!0,[]]):q=b(be,[r,i,l,R,!0,[]]);let B=[q];return n===v&&e&&(k=`${k}04`,B.push(b(A("address,address,uint256"),[v,r,0n]))),E.push(u.unsignedTx({to:$,data:ee({abi:fe,functionName:"execute",args:[k,B,O]}),value:n===v?y.toString():"0",chainId:I,description:`Uniswap ${a} ${e?"exact output":"exact input"} swap; recipient ${r}; deadline ${O}.`})),{...await W(u,E,r,`Swap through Universal Router 2.1.2. ${X} Fixed output/input bound and five-minute on-chain deadline. Venue fees included; gas excluded.`),quote:j}}function Ne(u){return{tools:[!0,!1].map(t=>({name:t?"uniswap_quote":"uniswap_swap",inputSchema:{type:"object",additionalProperties:!1,required:["version","tokenIn","tokenOut"],properties:ae},execute:(r,d)=>ke(u,r,d,t)}))}}export{te as a,ne as b,fe as c,le as d,oe as e,re as f,ye as g,he as h,xe as i,be as j,we as k,Ae as l,ke as m,Ne as n};
|