@oakagentkit/core 0.3.6 → 0.3.7
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/history.js +1 -1
- package/build/dist/api/modules/borro/index.js +1 -1
- package/build/dist/api/modules/borro/positions.js +1 -1
- package/build/dist/api/modules/borro/reader.js +1 -1
- package/build/dist/api/modules/chop/display.js +1 -1
- package/build/dist/api/modules/chop/index.js +1 -1
- package/build/dist/api/modules/earn/index.js +1 -1
- package/build/dist/api/modules/erc8004/index.js +1 -1
- package/build/dist/api/modules/grove/index.js +1 -1
- package/build/dist/api/modules/hoodlock/airdrop.js +1 -1
- package/build/dist/api/modules/hoodlock/fee.js +1 -1
- package/build/dist/api/modules/hoodlock/guard.js +1 -1
- package/build/dist/api/modules/hoodlock/index.js +1 -1
- package/build/dist/api/modules/hoodlock/lifecycle.js +1 -1
- package/build/dist/api/modules/hoodlock/locks-burn.js +1 -1
- package/build/dist/api/modules/hoodlock/public.js +1 -1
- package/build/dist/api/modules/hookr/actions.js +1 -1
- package/build/dist/api/modules/hookr/agent-gate.js +1 -1
- package/build/dist/api/modules/hookr/blocks/pay-later.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/hook-blocks.js +1 -1
- package/build/dist/api/modules/hookr/index.js +1 -1
- package/build/dist/api/modules/hookr/launch-options.js +1 -1
- package/build/dist/api/modules/hookr/launch-receipt.js +1 -1
- package/build/dist/api/modules/hookr/launch.js +1 -1
- package/build/dist/api/modules/hookr/liquidity.js +1 -1
- package/build/dist/api/modules/hookr/lp-positions.js +1 -1
- package/build/dist/api/modules/hookr/lp-reads.js +1 -1
- package/build/dist/api/modules/hookr/lp-receipt.js +1 -1
- package/build/dist/api/modules/hookr/lp-state.js +1 -1
- package/build/dist/api/modules/hookr/pay-later-actions.js +1 -1
- package/build/dist/api/modules/hookr/pm-liquidity.js +1 -1
- package/build/dist/api/modules/hookr/relay.js +1 -1
- package/build/dist/api/modules/layerbank/actions.js +1 -1
- package/build/dist/api/modules/layerbank/index.js +1 -1
- package/build/dist/api/modules/layerbank/reader.js +1 -1
- package/build/dist/api/modules/longbow/administration.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/meridian/index.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/stock-lp.d.ts +51 -0
- package/build/dist/api/modules/merkl/stock-lp.js +1 -0
- 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-tools.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/financial.js +1 -1
- package/build/dist/api/modules/netnet/index.js +1 -1
- package/build/dist/api/modules/pendle/index.js +1 -1
- package/build/dist/api/modules/pendle/reader.js +1 -1
- package/build/dist/api/modules/pendle/trade.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/index.js +1 -1
- package/build/dist/api/modules/priors/integration.js +1 -1
- package/build/dist/api/modules/priors/stock-swap.js +1 -1
- package/build/dist/api/modules/raeto/index.js +1 -1
- package/build/dist/api/modules/relay/index.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/exit-preview.js +1 -1
- package/build/dist/api/modules/tickerspring/guards.js +1 -1
- package/build/dist/api/modules/tickerspring/index.js +1 -1
- package/build/dist/api/modules/tickerspring/journeys.js +1 -1
- package/build/dist/api/modules/tickerspring/ladder.js +1 -1
- package/build/dist/api/modules/tickerspring/maker.js +1 -1
- package/build/dist/api/modules/tickerspring/order-accounting.js +1 -1
- package/build/dist/api/modules/tickerspring/research.js +1 -1
- package/build/dist/api/modules/tickerspring/strategies.js +1 -1
- package/build/dist/api/modules/uniswap/auction-create.js +1 -1
- package/build/dist/api/modules/uniswap/auction.js +1 -1
- package/build/dist/api/modules/uniswap/batch.js +1 -1
- package/build/dist/api/modules/uniswap/common.js +1 -1
- package/build/dist/api/modules/uniswap/fees.js +1 -1
- package/build/dist/api/modules/uniswap/index.js +1 -1
- package/build/dist/api/modules/uniswap/local-guard.js +1 -1
- package/build/dist/api/modules/uniswap/oracle.js +1 -1
- package/build/dist/api/modules/uniswap/pool-math.js +1 -1
- package/build/dist/api/modules/uniswap/pools.js +1 -1
- package/build/dist/api/modules/uniswap/position.js +1 -1
- package/build/dist/api/modules/uniswap/protocol.js +1 -1
- package/build/dist/api/modules/uniswap/quote-guard.js +1 -1
- package/build/dist/api/modules/uniswap/token-jar.js +1 -1
- package/build/dist/api/modules/uniswap/trade-batch.js +1 -1
- package/build/dist/api/modules/uniswap/trade.js +1 -1
- package/build/dist/api/modules/uniswap/v2.js +1 -1
- package/build/dist/api/modules/uniswap/v3.js +1 -1
- package/build/dist/api/modules/uniswap/v4.js +1 -1
- package/build/dist/api/modules/uniswap/wrap.js +1 -1
- package/build/dist/api/modules/velora/index.js +1 -1
- package/build/dist/api/modules/wormhole/index.js +1 -1
- package/build/dist/api/prices.js +1 -1
- package/build/dist/api/send.js +1 -1
- package/build/dist/api/signing-registry.js +1 -1
- package/build/dist/api/tokens.js +1 -1
- package/build/dist/api/tool-policy.d.ts +1 -0
- package/build/dist/api/tool-policy.js +1 -1
- package/build/dist/api/usd-estimate.js +1 -1
- package/build/dist/chunks/{GBIL2I2K.js → 2GYL3N2O.js} +1 -1
- package/build/dist/chunks/{5677LZOV.js → 2ZYFBBOE.js} +1 -1
- package/build/dist/chunks/{X53QVHBC.js → 35DTANJW.js} +1 -1
- package/build/dist/chunks/{HRGLFGFL.js → 37UBQQWL.js} +1 -1
- package/build/dist/chunks/{5DWQUEBA.js → 4JU23O3Z.js} +1 -1
- package/build/dist/chunks/{C2H3BWN5.js → 4WYTIM4T.js} +1 -1
- package/build/dist/chunks/{FGGDAAHW.js → 52AEVHKJ.js} +1 -1
- package/build/dist/chunks/{5RAZFRO4.js → 5EQTOA5F.js} +1 -1
- package/build/dist/chunks/{SRYX65GZ.js → 5VA66LFF.js} +1 -1
- package/build/dist/chunks/{IM7ZF7XZ.js → 627SGCTU.js} +1 -1
- package/build/dist/chunks/{OIGTTRN5.js → 7KK3OC7Q.js} +1 -1
- package/build/dist/chunks/{RYEQIZ2H.js → 7PBCV7VS.js} +1 -1
- package/build/dist/chunks/{P6JE2NRA.js → AOTTQPK7.js} +1 -1
- package/build/dist/chunks/{EHQRAA3R.js → B4U43D5Z.js} +1 -1
- package/build/dist/chunks/B5B7U3NZ.js +1 -0
- package/build/dist/chunks/{XWZ5SL5Q.js → CITHH7NK.js} +1 -1
- package/build/dist/chunks/{L3IAEXQR.js → CLHA557R.js} +1 -1
- package/build/dist/chunks/{CVVNAFUE.js → DUTAMN3F.js} +1 -1
- package/build/dist/chunks/{DJRS3TR5.js → EKHNXPWO.js} +1 -1
- package/build/dist/chunks/EXKV6QJD.js +1 -0
- package/build/dist/chunks/{LKRAUTYI.js → FYWK3UK6.js} +1 -1
- package/build/dist/chunks/GV6FZ6UG.js +1 -0
- package/build/dist/chunks/{TZG7HTVM.js → H5J2LFPZ.js} +1 -1
- package/build/dist/chunks/{UGFRBJDQ.js → HN5RBTNE.js} +1 -1
- package/build/dist/chunks/{3HF6WE4L.js → HTOP2OKU.js} +1 -1
- package/build/dist/chunks/ILTGXU6G.js +1 -0
- package/build/dist/chunks/{B5BU645H.js → J5624CVF.js} +1 -1
- package/build/dist/chunks/JFYC2LVI.js +1 -0
- package/build/dist/chunks/{URTQNYWU.js → JUVY6PCR.js} +1 -1
- package/build/dist/chunks/{GX2RCAHG.js → JYED2PZ3.js} +1 -1
- package/build/dist/chunks/{HNBYPHTA.js → K3HCSCXE.js} +1 -1
- package/build/dist/chunks/{K4CYAWNL.js → KAXLZJU6.js} +1 -1
- package/build/dist/chunks/{6QXTL65K.js → KW5LJGNY.js} +1 -1
- package/build/dist/chunks/{XUDQYSPU.js → LHC2YV2U.js} +1 -1
- package/build/dist/chunks/{2BKZLF5A.js → LHVGWNMW.js} +1 -1
- package/build/dist/chunks/{6Y2546JA.js → LOH6LUVT.js} +1 -1
- package/build/dist/chunks/{GTJ6LBGB.js → MFRKZOU4.js} +1 -1
- package/build/dist/chunks/{QZ6V6J6W.js → MSIT5Q3M.js} +1 -1
- package/build/dist/chunks/{G4IX4CYN.js → NCCKCGKL.js} +1 -1
- package/build/dist/chunks/{N6YNJGEF.js → NGHRUNXO.js} +1 -1
- package/build/dist/chunks/{BSV65PCA.js → NIGRNLNM.js} +1 -1
- package/build/dist/chunks/{4SXRXNHG.js → NWW6GY5E.js} +1 -1
- package/build/dist/chunks/{CR7DPGI6.js → ORKXBYVC.js} +1 -1
- package/build/dist/chunks/{IR7KDBFU.js → OUXPOFY2.js} +1 -1
- package/build/dist/chunks/{XXLQDQEX.js → OWHXYE2G.js} +1 -1
- package/build/dist/chunks/{J2J73XYU.js → PLEJPTTK.js} +1 -1
- package/build/dist/chunks/{QP2B7AYX.js → PX2G2H6G.js} +1 -1
- package/build/dist/chunks/{7X5JVF3F.js → QCPJZBEO.js} +1 -1
- package/build/dist/chunks/{7JTXYMNP.js → QGO4EKXZ.js} +1 -1
- package/build/dist/chunks/{JTWJT2O3.js → QXBQ7WPB.js} +1 -1
- package/build/dist/chunks/{DPSFR3ZS.js → R5UOFPDO.js} +1 -1
- package/build/dist/chunks/{EJIP7RBG.js → REXGROOD.js} +1 -1
- package/build/dist/chunks/{PXVF2SHU.js → RWEA4SWP.js} +1 -1
- package/build/dist/chunks/{K6GECT3F.js → RWUF6T4I.js} +1 -1
- package/build/dist/chunks/{F74ARK4H.js → SDDYM2H3.js} +1 -1
- package/build/dist/chunks/{3M7RMROZ.js → TKJ4GFUP.js} +1 -1
- package/build/dist/chunks/{DV2HVFTM.js → UCMOQAVD.js} +1 -1
- package/build/dist/chunks/{WUONMIA2.js → UL4DY6GX.js} +1 -1
- package/build/dist/chunks/{GCFHKJIO.js → UYYYSFMQ.js} +1 -1
- package/build/dist/chunks/{F36IA5RI.js → V7P4PCLL.js} +1 -1
- package/build/dist/chunks/{TWVDWNTG.js → VMSGNN3D.js} +1 -1
- package/build/dist/chunks/VQMBPY2P.js +1 -0
- package/build/dist/chunks/{K5OXLIPK.js → W3M4KAPX.js} +1 -1
- package/build/dist/chunks/{Q43WPRYU.js → W7BTXU3F.js} +1 -1
- package/build/dist/chunks/{KB2JWQZ4.js → WADRRW3E.js} +1 -1
- package/build/dist/chunks/{QAVP3CWL.js → WG7PMGTJ.js} +1 -1
- package/build/dist/chunks/{IKVRFAUP.js → WRNPYW47.js} +1 -1
- package/build/dist/chunks/{4GAU3JLN.js → XD4JA43O.js} +1 -1
- package/build/dist/chunks/{6EWSLHXL.js → Y7SKGRWC.js} +1 -1
- package/build/dist/chunks/{HEQBTHFS.js → YDJHXSS7.js} +1 -1
- package/build/dist/chunks/{TMENUIBC.js → YLU5JVRI.js} +1 -1
- package/build/dist/chunks/{IYOWMW5B.js → YR6Y6UIR.js} +1 -1
- package/build/dist/chunks/{FN6XY6ET.js → Z5WRTISY.js} +1 -1
- package/build/dist/chunks/{45QP74CE.js → ZB67QDN2.js} +1 -1
- package/build/dist/chunks/{MXI7LX2F.js → ZRG34Y7Q.js} +1 -1
- package/package.json +1 -1
- package/build/dist/chunks/5PNFV7HH.js +0 -1
- package/build/dist/chunks/H5KU4DUU.js +0 -1
- package/build/dist/chunks/H7ZJ7LAB.js +0 -1
- package/build/dist/chunks/M267JEDO.js +0 -1
- package/build/dist/chunks/Y5T36EEU.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as wt}from"./RLX6YTNT.js";import{c as mt}from"./O7L55XM3.js";import{b as ht}from"./W73SLWBT.js";import{b as bt}from"./DV2HVFTM.js";import{b as gt}from"./2BKZLF5A.js";import{c as pt}from"./4GAU3JLN.js";import{b as ft}from"./2H2OZE6X.js";import{h as ut}from"./BWE5PXRE.js";import{a as C,b as L,c as Ie,d as me,e as Ge,g as st,h as Ve,j as U,l as E,o as Fe,p as at,q as dt,r as Me,s as lt,t as qe,u as ct}from"./OD7CY6BY.js";import{i as rt}from"./2GXHYI23.js";import{b as ot,o as it}from"./TTBB6EFN.js";import{b as et}from"./SPJCSEKP.js";import{a as z}from"./43LI5NKJ.js";import{a as tt,c as nt}from"./SCG5HWMN.js";import{a as Pe}from"./66F5ZH34.js";import{b as ee}from"./IX3GZMTM.js";import{b as $,e as N,j as ce}from"./EWZFZUVF.js";import{a}from"./XSD5NL7J.js";import{a as Ee}from"./JXOEJPJ4.js";import{BaseError as _t,ContractFunctionRevertedError as Ye,decodeEventLog as zt,decodeFunctionResult as Jt,encodeFunctionData as X,erc20Abi as Xt,getAddress as B,parseAbi as ke,parseAbiItem as Yt,recoverAddress as Zt,recoverMessageAddress as Kt,recoverTypedDataAddress as Qt}from"viem";var en="https://priors.trade/api/check",He=604800n,yt=50n,$t=10000n,We=5000000n,St=500000000n,je=86400n,At=2592000n,Ze=`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).`,tn="0x6982e39521a070a3c40782548bfbed6dc8f566ef",nn=["0xcbb95bbf36099d34da091dc6fa6f49efa257cee3","0x284358abc07f9359f19f4b5b4ac91901be2597ba"],c={pool:B(ce[4663].priors.pool.address),lens:B(ce[4663].priors.lens.address),usdg:B(ce[4663].priors.usdg.address),registry:B(ce[4663].priors.registry.address),stockVault:B(ce[4663].priors.stockVault.address)},te={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)"]),vt=ke(["function available(uint256 agentId) view returns (uint256)","function score(uint256 id) view returns (uint256)"]),kt=ke(["function ownerOf(uint256 agentId) view returns (address)","function balanceOf(address owner) view returns (uint256)","function getAgentWallet(uint256 agentId) view returns (address)"]),Pt=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 on(e){return e.chainId===$&&e.address.toLowerCase()===c.usdg.toLowerCase()}function rn(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=on(i.token)?"USDG":i.token.address;return`${u?"-":"+"}${R} ${A}`}function ne(e,i,g){if(!g.length)return i;let u=g.map(f=>rn(e,f)).join(", ");return`${i} Preview changes: ${u}.`}function It(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:kt,functionName:"ownerOf",args:[i],blockNumber:g}))}catch(u){throw u instanceof _t&&u.walk(f=>f instanceof Ye)?new a(`ERC-8004 agent ${i} does not exist in registry ${c.registry}: it has no owner. Check the agent ID.`):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 sn(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=zt({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:kt,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,x=u;for(;;){let H=x>9999999n?x-9999999n:0n,oe=await g.getLogs({address:c.registry,event:Yt("event Transfer(address indexed from,address indexed to,uint256 indexed tokenId)"),args:{to:i},fromBlock:H,toBlock:x,strict:!0});for(let O of oe){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,se)=>Z<se?-1:Z>se?1:0)}if(H===0n)throw new a("Owned identities could not all be located. Retry or provide an explicit agentId.");x=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. ${Ze}`);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]})]),x=B(R);if(!A)throw new a(`Wallet ${g} is not an on-chain controller for ERC-8004 agent ${i} (ownerOf=${f}, delegateOf=${x}). An off-chain /api/check paymentWallet match alone does not grant CreditPoolV2 control.`);return{owner:f,delegate:x}}function an(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 dn(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,x,H,oe,O,J,ge,Z,se,Te]=await Promise.all([De(e,i,f),u.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[i],blockNumber:f}),u.readContract({address:L,abi:E,functionName:"firstLined",args:[i],blockNumber:f}),u.readContract({address:L,abi:E,functionName:"agentId",blockNumber:f}),u.readContract({address:L,abi:E,functionName:"rules",blockNumber:f}),u.readContract({address:L,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:Xt,functionName:"balanceOf",args:[g],blockNumber:f})]);return{owner:R,agent:we(A),firstLined:x===!0,root:BigInt(H),firstLineAmount:BigInt(oe[1]),epochRoom:BigInt(O),bond:ye(J),bondAmount:BigInt(ge),releaseAt:BigInt(Z),unusedAfter:BigInt(se),usdg:BigInt(Te)}}function Ct(e,i){return e.enrolled||e.enrolledAt>0n||e.isRoot||e.defaulted||e.importedFromV1||e.loansRepaid>0n||e.sponsor!==0n||i}function Rt(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 tt))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 ln(e,i){let g=i instanceof _t?i.walk(x=>x instanceof Ye):void 0,u=g instanceof Ye?g.data:void 0,f=u?.args??[],R=x=>`${e.formatAmount(String(x),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 cn=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 amount in base units (6 decimals). Example: "1000000" = 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=It(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]})}]}),[I,_]=v.results;if(I?.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(it(l.toString(),n.slippageBps??ot)),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),P=`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:ne(e,P,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*yt/$t:0n,P=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}.`})],I=await e.preview(v,o),_=e.formatAmount(P.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:ne(e,M,I.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 amount in base units (6 decimals). Example: "5000000" = 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 fee ceiling in USDG base units (6 decimals); must equal the pool quote for this principal and term. Omit to use it. The fee is pro-rated by term, not flat: 1666 for 5 USDG over 1 day."}}},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=an(r,w),m=It(n,"principal","amount","USDG borrow principal");if(m<We||m>St)throw new a(`Borrow principal must be between ${We} (5 USDG) and ${St} (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>At)throw new a(`Loan term must be between ${je} (1 day) and ${At} (30 days) seconds.`);let P=await p.readContract({address:c.pool,abi:S,functionName:"quoteFee",args:[r,m,h]}),l=P[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 I=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 ${I}, maxFee ${v}, debt ceiling ${_}).`})],D=await e.preview(k,o),M=e.formatAmount(m.toString(),N),W=e.formatAmount(l.toString(),N),ae=e.formatAmount(I.toString(),N),j=e.formatAmount(v.toString(),N),$e=e.formatAmount(_.toString(),N),q=P[1]+P[3],K=P[2],de=l-q-K,ie=`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 ${ae} USDG (${I} 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 (${de} base units).`;return{txs:k,summary:ne(e,ie,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=dn(n);if(k.length>0){let D=sn(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 ae=await r.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[W]});return Ce(W,ae)}))).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}).`}),P=[m,h],l=await e.preview(P,o),v=e.formatAmount(w.toString(),N),I=e.formatAmount(d.principal.toString(),N),_=e.formatAmount(d.fee.toString(),N),F=`Approve and repay ${v} USDG (${w} base units: ${I} USDG principal + ${_} USDG fixed fee) for Priors loan ${d.loanId} (agent ${t}).`;return{txs:P,summary:ne(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:Pt,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*yt/$t:0n,P=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,I=!1,_=[],F=null,k=null,D=null,M=null,W=null,ae=null,j=`This wallet owns no ERC-8004 agent identity. ${Ze}`;if(l!==null){let[q,K,de,ie,Ut,Et,Be,Ne,xe]=await Promise.all([t.readContract({address:c.lens,abi:vt,functionName:"score",args:[l]}),t.readContract({address:L,abi:E,functionName:"firstLined",args:[l]}),t.readContract({address:L,abi:E,functionName:"agentId"}),t.readContract({address:L,abi:E,functionName:"rules"}),t.readContract({address:L,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]})]),[Gt,Vt,Ft,Mt,qt,Ht]=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:vt,functionName:"available",args:[l]}),t.readContract({address:c.stockVault,abi:Pt,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]})]),Le=await De(e,l),Wt=B(qt),Ke=Ht,y=we(Gt),Se=y.delegatedIn>y.principalOut?y.delegatedIn-y.principalOut:0n;I=y.enrolled&&!y.isRoot&&!y.defaulted&&!y.frozen&&y.sponsor>0n&&y.delegatedIn>0n,F=Ft.toString(),k=Mt.toString();let jt=await Promise.all(Vt.map(async T=>{let le=await t.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[T]});return Ce(T,le)}));for(let T of jt)if(T.agentId===l&&T.status===1){let le=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:le.toString(),dueAt:T.dueAt.toString(),issuedAt:T.issuedAt.toString(),owner:T.owner,token:te})}v={agentId:l.toString(),owner:Le,delegate:Wt,isAuthorizedController:Ke,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(de),Oe=K===!0,Q=ye(Et),re=Q.depositor!==Je,ve=re&&V(Q.depositor,o),Qe=Ct(y,Oe),Ue=V(Le,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:te},W={contract:C,posted:re,depositor:re?Q.depositor:null,postedByWallet:ve,postedAt:re?Q.at.toString():null,amount:(re?Q.amount:BigInt(Be)).toString(),releasable:re&&xe===!0,releaseAt:re?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."},ae={eligible:Ue&&!Qe,firstLined:Oe,lineAmount:BigInt(ie[1]).toString(),bondAmount:BigInt(Be).toString(),treasuryRoot:Ae.toString(),treasuryRoomThisWeek:BigInt(Ut).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,le)=>T.dueAt<le.dueAt?-1:T.dueAt>le.dueAt?1:0);y.defaulted?j=`Agent #${l} defaulted; Priors never lends to it again${ve?" and its bond is forfeited":""}.`:!Ke&&!Ue?j=`This wallet does not control agent #${l} on CreditPoolV2 (owner ${Le}); 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)`:""}.`:I&&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.`:!Qe&&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${xe===!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(ie[1]))} line from Priors' treasury (each transaction and signature is confirmed).`:ve?j=xe===!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; ${Rt(e,y,Ae,Oe)}.`}let $e=null;if(n.includeApiCheck){let q=l!==null?`agent=${l.toString()}`:`address=${o}`,K=await nt(e.http,`${en}?${q}`,{method:"GET"},Y),de=Array.isArray(K.agents)?K.agents.find(ie=>Y(ie)&&String(ie.agentId)===String(l)):void 0;D&&Y(de)&&(D.scoreV2=de.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:te,contracts:c,lender:{shares:r.toString(),grossAssets:b.toString(),earlyExitFeeAssets:h.toString(),netWithdrawAssets:P.toString(),lastDepositAt:p.toString(),withinMinHoldWindow:m,minHoldSeconds:He.toString()},hasFundedLine:I,agentId:l!==null?l.toString():null,nextStep:j,score:D,line:M,bond:W,starterLine:ae,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(tn),zeroCapAssets:nn.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 x(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 (${L}) answers root #${o.root}, not the pinned #${Ie}. Nothing was signed; update Oak.`);if(Ct(o.agent,o.firstLined))throw new a(`Agent #${n} already has a Priors record, so priors_starter_line posts no bond and signs nothing: ${Rt(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 oe="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 ${oe} (${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(oe)||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 ${oe} (${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=lt(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:`${x(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 se(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. ${Ze}`);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:`${x(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):"",I=typeof l.reopensAt=="number"&&Number.isSafeInteger(l.reopensAt)&&l.reopensAt>0?l.reopensAt:null;return{summary:`${x(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")}${I?`, reopens ${G(I)}`:""}. ${ct({...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:I}}}}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=`${x(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, ${L}) 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:ne(e,h,b.changes)}}async function Dt(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 Tt(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 Kt({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:L,abi:E,functionName:"inviteDigest",args:[n,b.expiry]});if(h.toLowerCase()!==dt(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 P=await Zt({hash:h,signature:b.signature}),[l,v]=await Promise.all([m.readContract({address:L,abi:E,functionName:"inviters",args:[P]}),m.readContract({address:L,abi:E,functionName:"inviteUsed",args:[h]})]);if(l!==!0)throw new a(`Priors' invite for agent #${r} was signed by ${P}, 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[I,_]=await Promise.all([m.readContract({address:c.pool,abi:S,functionName:"nonces",args:[n]}),m.getBlock()]),F=_.timestamp+BigInt(st),k=Fe({agentId:r,owner:s,nonce:I.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:I,deadline:F}]});if(D.toLowerCase()!==at(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 ${P}, 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 ${I}, valid until ${G(F)}. A transaction redeeming the invite (TreasurySponsorV4.firstLine) follows for your confirmation. ${O(d)}`}}async function Bt(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 Qt({...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,P]=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(P.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:L,abi:E,functionName:"firstLine",args:v,account:s})}catch(k){throw new a(`TreasurySponsorV4.firstLine for agent #${r} would be refused: ${ln(e,k)} Nothing was offered. ${O(b)}`)}let I=e.unsignedTx({to:L,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([I],s),F=`Redeem agent #${r}'s Priors invite: TreasurySponsorV4.firstLine (${L}) 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:[I],summary:ne(e,F,_.changes)}}let Nt={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",description:"Opaque state from the previous starter-line step; pass it back unchanged. Omit on the first call; never build it by hand."},signature:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$",description:"Local signature for the confirmed starter-line step, as 0x hex; the bridge supplies it. Never a key."}}},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=se(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(()=>Dt(r,o,t))}if(t.stage==="proof")return p(()=>Tt(r,o,t,n.signature));if(t.stage==="consent")return p(()=>Bt(r,o,t,n.signature));throw new a("Unknown Priors starter-line stage; start priors_starter_line again.")}},xt={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:L,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),P=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),I=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 (${P?`Priors' treasury, root #${b}`:`root #${m.sponsor}`}) and the agent can no longer borrow on it. This does not reopen: ${P?`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."}${I} No USDG moves in this transaction.`;return{txs:[l],summary:ne(e,_,v.changes)}}},Lt={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 I=we(b),_=I.defaulted?"the agent defaulted, so the bond is forfeited to Priors' Safe (InviteBond.slash)":I.activeLoans>0n?`the agent has ${I.activeLoans} loan(s) open: repay with priors_repay, close the line with priors_close_line, then release`:I.delegatedIn>0n?`the agent still holds a ${A(I.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 P=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([P],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:[P],summary:ne(e,v,l.changes)}}};async function Ot(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:te,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 P=await o.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[h]});return Ce(h,P)}));for(let h of b)if(h.agentId===d&&h.status===1){let P=h.principal+h.fee;p.push({module:"priors",id:`priors:loan:${h.loanId.toString()}`,chainId:$,assets:[],liabilities:[{token:te,amount:P.toString()}],economics:{principal:[],debt:[rt({token:te,amount:P.toString(),source:"priors.loan.fixedDue",dueAt:h.dueAt.toString()})],rewards:[],backing:[],coverage:{complete:!0}},description:`Priors CreditPoolV2 active loan ${h.loanId} for agent ${d} (fixed due ${e.formatAmount(P.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:te,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.push(...await ft(e,s,r,te)),p}return{tools:[i,g,u,f,R,Nt,xt,Lt],positions:Ot}},un=e=>{let i=cn(e),g=[i,ut(e),pt(e),mt(e),ht(e),bt(e),wt(e),gt()];return{...i,tools:g.flatMap(u=>u.tools)}},Bn=e=>et("priors",[un(e)]);export{en as a,He as b,yt as c,$t as d,We as e,St as f,je as g,At as h,c as i,te as j,sn as k,un as l,Bn as m};
|
|
1
|
+
import{b as ft}from"./2H2OZE6X.js";import{b as wt}from"./RLX6YTNT.js";import{c as mt}from"./O7L55XM3.js";import{b as ht}from"./W73SLWBT.js";import{b as bt}from"./UCMOQAVD.js";import{b as gt}from"./LHVGWNMW.js";import{c as pt}from"./XD4JA43O.js";import{h as ut}from"./BWE5PXRE.js";import{a as C,b as L,c as Ie,d as me,e as Ge,g as st,h as Ve,j as U,l as E,o as Fe,p as at,q as dt,r as Me,s as lt,t as qe,u as ct}from"./OD7CY6BY.js";import{i as rt}from"./2GXHYI23.js";import{b as ot,o as it}from"./TTBB6EFN.js";import{b as et}from"./SPJCSEKP.js";import{a as z}from"./43LI5NKJ.js";import{a as tt,c as nt}from"./SCG5HWMN.js";import{a as Pe}from"./66F5ZH34.js";import{b as ee}from"./IX3GZMTM.js";import{b as $,e as N,j as ce}from"./EWZFZUVF.js";import{a}from"./XSD5NL7J.js";import{a as Ee}from"./JXOEJPJ4.js";import{BaseError as _t,ContractFunctionRevertedError as Ye,decodeEventLog as zt,decodeFunctionResult as Jt,encodeFunctionData as X,erc20Abi as Xt,getAddress as B,parseAbi as ke,parseAbiItem as Yt,recoverAddress as Zt,recoverMessageAddress as Kt,recoverTypedDataAddress as Qt}from"viem";var en="https://priors.trade/api/check",He=604800n,yt=50n,$t=10000n,We=5000000n,St=500000000n,je=86400n,At=2592000n,Ze=`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).`,tn="0x6982e39521a070a3c40782548bfbed6dc8f566ef",nn=["0xcbb95bbf36099d34da091dc6fa6f49efa257cee3","0x284358abc07f9359f19f4b5b4ac91901be2597ba"],c={pool:B(ce[4663].priors.pool.address),lens:B(ce[4663].priors.lens.address),usdg:B(ce[4663].priors.usdg.address),registry:B(ce[4663].priors.registry.address),stockVault:B(ce[4663].priors.stockVault.address)},te={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)"]),vt=ke(["function available(uint256 agentId) view returns (uint256)","function score(uint256 id) view returns (uint256)"]),kt=ke(["function ownerOf(uint256 agentId) view returns (address)","function balanceOf(address owner) view returns (uint256)","function getAgentWallet(uint256 agentId) view returns (address)"]),Pt=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 on(e){return e.chainId===$&&e.address.toLowerCase()===c.usdg.toLowerCase()}function rn(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=on(i.token)?"USDG":i.token.address;return`${u?"-":"+"}${R} ${A}`}function ne(e,i,g){if(!g.length)return i;let u=g.map(f=>rn(e,f)).join(", ");return`${i} Preview changes: ${u}.`}function It(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:kt,functionName:"ownerOf",args:[i],blockNumber:g}))}catch(u){throw u instanceof _t&&u.walk(f=>f instanceof Ye)?new a(`ERC-8004 agent ${i} does not exist in registry ${c.registry}: it has no owner. Check the agent ID.`):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 sn(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=zt({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:kt,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,x=u;for(;;){let H=x>9999999n?x-9999999n:0n,oe=await g.getLogs({address:c.registry,event:Yt("event Transfer(address indexed from,address indexed to,uint256 indexed tokenId)"),args:{to:i},fromBlock:H,toBlock:x,strict:!0});for(let O of oe){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,se)=>Z<se?-1:Z>se?1:0)}if(H===0n)throw new a("Owned identities could not all be located. Retry or provide an explicit agentId.");x=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. ${Ze}`);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]})]),x=B(R);if(!A)throw new a(`Wallet ${g} is not an on-chain controller for ERC-8004 agent ${i} (ownerOf=${f}, delegateOf=${x}). An off-chain /api/check paymentWallet match alone does not grant CreditPoolV2 control.`);return{owner:f,delegate:x}}function an(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 dn(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,x,H,oe,O,J,ge,Z,se,Te]=await Promise.all([De(e,i,f),u.readContract({address:c.pool,abi:S,functionName:"getAgent",args:[i],blockNumber:f}),u.readContract({address:L,abi:E,functionName:"firstLined",args:[i],blockNumber:f}),u.readContract({address:L,abi:E,functionName:"agentId",blockNumber:f}),u.readContract({address:L,abi:E,functionName:"rules",blockNumber:f}),u.readContract({address:L,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:Xt,functionName:"balanceOf",args:[g],blockNumber:f})]);return{owner:R,agent:we(A),firstLined:x===!0,root:BigInt(H),firstLineAmount:BigInt(oe[1]),epochRoom:BigInt(O),bond:ye(J),bondAmount:BigInt(ge),releaseAt:BigInt(Z),unusedAfter:BigInt(se),usdg:BigInt(Te)}}function Ct(e,i){return e.enrolled||e.enrolledAt>0n||e.isRoot||e.defaulted||e.importedFromV1||e.loansRepaid>0n||e.sponsor!==0n||i}function Rt(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 tt))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 ln(e,i){let g=i instanceof _t?i.walk(x=>x instanceof Ye):void 0,u=g instanceof Ye?g.data:void 0,f=u?.args??[],R=x=>`${e.formatAmount(String(x),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 cn=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 amount in base units (6 decimals). Example: "1000000" = 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=It(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]})}]}),[I,_]=v.results;if(I?.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(it(l.toString(),n.slippageBps??ot)),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),P=`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:ne(e,P,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*yt/$t:0n,P=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}.`})],I=await e.preview(v,o),_=e.formatAmount(P.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:ne(e,M,I.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 amount in base units (6 decimals). Example: "5000000" = 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 fee ceiling in USDG base units (6 decimals); must equal the pool quote for this principal and term. Omit to use it. The fee is pro-rated by term, not flat: 1666 for 5 USDG over 1 day."}}},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=an(r,w),m=It(n,"principal","amount","USDG borrow principal");if(m<We||m>St)throw new a(`Borrow principal must be between ${We} (5 USDG) and ${St} (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>At)throw new a(`Loan term must be between ${je} (1 day) and ${At} (30 days) seconds.`);let P=await p.readContract({address:c.pool,abi:S,functionName:"quoteFee",args:[r,m,h]}),l=P[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 I=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 ${I}, maxFee ${v}, debt ceiling ${_}).`})],D=await e.preview(k,o),M=e.formatAmount(m.toString(),N),W=e.formatAmount(l.toString(),N),ae=e.formatAmount(I.toString(),N),j=e.formatAmount(v.toString(),N),$e=e.formatAmount(_.toString(),N),q=P[1]+P[3],K=P[2],de=l-q-K,ie=`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 ${ae} USDG (${I} 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 (${de} base units).`;return{txs:k,summary:ne(e,ie,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=dn(n);if(k.length>0){let D=sn(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 ae=await r.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[W]});return Ce(W,ae)}))).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}).`}),P=[m,h],l=await e.preview(P,o),v=e.formatAmount(w.toString(),N),I=e.formatAmount(d.principal.toString(),N),_=e.formatAmount(d.fee.toString(),N),F=`Approve and repay ${v} USDG (${w} base units: ${I} USDG principal + ${_} USDG fixed fee) for Priors loan ${d.loanId} (agent ${t}).`;return{txs:P,summary:ne(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:Pt,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*yt/$t:0n,P=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,I=!1,_=[],F=null,k=null,D=null,M=null,W=null,ae=null,j=`This wallet owns no ERC-8004 agent identity. ${Ze}`;if(l!==null){let[q,K,de,ie,Ut,Et,Be,Ne,xe]=await Promise.all([t.readContract({address:c.lens,abi:vt,functionName:"score",args:[l]}),t.readContract({address:L,abi:E,functionName:"firstLined",args:[l]}),t.readContract({address:L,abi:E,functionName:"agentId"}),t.readContract({address:L,abi:E,functionName:"rules"}),t.readContract({address:L,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]})]),[Gt,Vt,Ft,Mt,qt,Ht]=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:vt,functionName:"available",args:[l]}),t.readContract({address:c.stockVault,abi:Pt,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]})]),Le=await De(e,l),Wt=B(qt),Ke=Ht,y=we(Gt),Se=y.delegatedIn>y.principalOut?y.delegatedIn-y.principalOut:0n;I=y.enrolled&&!y.isRoot&&!y.defaulted&&!y.frozen&&y.sponsor>0n&&y.delegatedIn>0n,F=Ft.toString(),k=Mt.toString();let jt=await Promise.all(Vt.map(async T=>{let le=await t.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[T]});return Ce(T,le)}));for(let T of jt)if(T.agentId===l&&T.status===1){let le=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:le.toString(),dueAt:T.dueAt.toString(),issuedAt:T.issuedAt.toString(),owner:T.owner,token:te})}v={agentId:l.toString(),owner:Le,delegate:Wt,isAuthorizedController:Ke,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(de),Oe=K===!0,Q=ye(Et),re=Q.depositor!==Je,ve=re&&V(Q.depositor,o),Qe=Ct(y,Oe),Ue=V(Le,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:te},W={contract:C,posted:re,depositor:re?Q.depositor:null,postedByWallet:ve,postedAt:re?Q.at.toString():null,amount:(re?Q.amount:BigInt(Be)).toString(),releasable:re&&xe===!0,releaseAt:re?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."},ae={eligible:Ue&&!Qe,firstLined:Oe,lineAmount:BigInt(ie[1]).toString(),bondAmount:BigInt(Be).toString(),treasuryRoot:Ae.toString(),treasuryRoomThisWeek:BigInt(Ut).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,le)=>T.dueAt<le.dueAt?-1:T.dueAt>le.dueAt?1:0);y.defaulted?j=`Agent #${l} defaulted; Priors never lends to it again${ve?" and its bond is forfeited":""}.`:!Ke&&!Ue?j=`This wallet does not control agent #${l} on CreditPoolV2 (owner ${Le}); 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)`:""}.`:I&&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.`:!Qe&&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${xe===!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(ie[1]))} line from Priors' treasury (each transaction and signature is confirmed).`:ve?j=xe===!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; ${Rt(e,y,Ae,Oe)}.`}let $e=null;if(n.includeApiCheck){let q=l!==null?`agent=${l.toString()}`:`address=${o}`,K=await nt(e.http,`${en}?${q}`,{method:"GET"},Y),de=Array.isArray(K.agents)?K.agents.find(ie=>Y(ie)&&String(ie.agentId)===String(l)):void 0;D&&Y(de)&&(D.scoreV2=de.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:te,contracts:c,lender:{shares:r.toString(),grossAssets:b.toString(),earlyExitFeeAssets:h.toString(),netWithdrawAssets:P.toString(),lastDepositAt:p.toString(),withinMinHoldWindow:m,minHoldSeconds:He.toString()},hasFundedLine:I,agentId:l!==null?l.toString():null,nextStep:j,score:D,line:M,bond:W,starterLine:ae,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(tn),zeroCapAssets:nn.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 x(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 (${L}) answers root #${o.root}, not the pinned #${Ie}. Nothing was signed; update Oak.`);if(Ct(o.agent,o.firstLined))throw new a(`Agent #${n} already has a Priors record, so priors_starter_line posts no bond and signs nothing: ${Rt(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 oe="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 ${oe} (${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(oe)||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 ${oe} (${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=lt(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:`${x(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 se(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. ${Ze}`);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:`${x(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):"",I=typeof l.reopensAt=="number"&&Number.isSafeInteger(l.reopensAt)&&l.reopensAt>0?l.reopensAt:null;return{summary:`${x(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")}${I?`, reopens ${G(I)}`:""}. ${ct({...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:I}}}}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=`${x(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, ${L}) 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:ne(e,h,b.changes)}}async function Dt(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 Tt(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 Kt({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:L,abi:E,functionName:"inviteDigest",args:[n,b.expiry]});if(h.toLowerCase()!==dt(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 P=await Zt({hash:h,signature:b.signature}),[l,v]=await Promise.all([m.readContract({address:L,abi:E,functionName:"inviters",args:[P]}),m.readContract({address:L,abi:E,functionName:"inviteUsed",args:[h]})]);if(l!==!0)throw new a(`Priors' invite for agent #${r} was signed by ${P}, 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[I,_]=await Promise.all([m.readContract({address:c.pool,abi:S,functionName:"nonces",args:[n]}),m.getBlock()]),F=_.timestamp+BigInt(st),k=Fe({agentId:r,owner:s,nonce:I.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:I,deadline:F}]});if(D.toLowerCase()!==at(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 ${P}, 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 ${I}, valid until ${G(F)}. A transaction redeeming the invite (TreasurySponsorV4.firstLine) follows for your confirmation. ${O(d)}`}}async function Bt(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 Qt({...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,P]=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(P.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:L,abi:E,functionName:"firstLine",args:v,account:s})}catch(k){throw new a(`TreasurySponsorV4.firstLine for agent #${r} would be refused: ${ln(e,k)} Nothing was offered. ${O(b)}`)}let I=e.unsignedTx({to:L,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([I],s),F=`Redeem agent #${r}'s Priors invite: TreasurySponsorV4.firstLine (${L}) 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:[I],summary:ne(e,F,_.changes)}}let Nt={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",description:"Opaque state from the previous starter-line step; pass it back unchanged. Omit on the first call; never build it by hand."},signature:{type:"string",pattern:"^0x([0-9a-fA-F]{2})+$",description:"Local signature for the confirmed starter-line step, as 0x hex; the bridge supplies it. Never a key."}}},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=se(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(()=>Dt(r,o,t))}if(t.stage==="proof")return p(()=>Tt(r,o,t,n.signature));if(t.stage==="consent")return p(()=>Bt(r,o,t,n.signature));throw new a("Unknown Priors starter-line stage; start priors_starter_line again.")}},xt={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:L,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),P=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),I=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 (${P?`Priors' treasury, root #${b}`:`root #${m.sponsor}`}) and the agent can no longer borrow on it. This does not reopen: ${P?`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."}${I} No USDG moves in this transaction.`;return{txs:[l],summary:ne(e,_,v.changes)}}},Lt={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 I=we(b),_=I.defaulted?"the agent defaulted, so the bond is forfeited to Priors' Safe (InviteBond.slash)":I.activeLoans>0n?`the agent has ${I.activeLoans} loan(s) open: repay with priors_repay, close the line with priors_close_line, then release`:I.delegatedIn>0n?`the agent still holds a ${A(I.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 P=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([P],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:[P],summary:ne(e,v,l.changes)}}};async function Ot(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:te,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 P=await o.readContract({address:c.pool,abi:S,functionName:"getLoan",args:[h]});return Ce(h,P)}));for(let h of b)if(h.agentId===d&&h.status===1){let P=h.principal+h.fee;p.push({module:"priors",id:`priors:loan:${h.loanId.toString()}`,chainId:$,assets:[],liabilities:[{token:te,amount:P.toString()}],economics:{principal:[],debt:[rt({token:te,amount:P.toString(),source:"priors.loan.fixedDue",dueAt:h.dueAt.toString()})],rewards:[],backing:[],coverage:{complete:!0}},description:`Priors CreditPoolV2 active loan ${h.loanId} for agent ${d} (fixed due ${e.formatAmount(P.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:te,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.push(...await ft(e,s,r,te)),p}return{tools:[i,g,u,f,R,Nt,xt,Lt],positions:Ot}},un=e=>{let i=cn(e),g=[i,ut(e),pt(e),mt(e),ht(e),bt(e),wt(e),gt()];return{...i,tools:g.flatMap(u=>u.tools)}},Bn=e=>et("priors",[un(e)]);export{en as a,He as b,yt as c,$t as d,We as e,St as f,je as g,At as h,c as i,te as j,sn as k,un as l,Bn as m};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as F}from"./G2LAO23N.js";import{c as A,d as _,e as S}from"./HRGLFGFL.js";import{d as j,e as U,g as K}from"./LD3A2KLN.js";import{a as f}from"./66F5ZH34.js";import{c as l,f as q,g as d,i as L}from"./NWNYJ26T.js";import{b as v}from"./EWZFZUVF.js";import{a as i}from"./XSD5NL7J.js";import{decodeEventLog as ce,encodeAbiParameters as de,encodeFunctionData as ue,getAddress as pe,hashStruct as me,isHex as le,keccak256 as ye,parseAbi as fe,parseAbiParameters as ge,zeroAddress as m}from"viem";var he="struct HookrSwapIntent { PoolKey key; bool zeroForOne; int128 amountSpecified; uint128 amountBound; uint160 sqrtPriceLimitX96; address recipient; address relayer; uint256 relayerFee; address engagement; uint256[] campaigns; uint256 nonce; uint256 deadline; }",O=fe(["struct PoolKey { address currency0; address currency1; uint24 fee; int24 tickSpacing; address hooks; }",he,"function execute(HookrSwapIntent intent, address owner, bytes signature) returns (uint256 amountIn, uint256 amountOut)","function hashIntent(HookrSwapIntent intent) pure returns (bytes32)","function pullOf(HookrSwapIntent intent) view returns (address token, uint256 amount, bool feeFromInput)","function isNonceUsed(address owner, uint256 intentNonce) view returns (bool)","function router() view returns (address)","function registry() view returns (address)","function permit2() view returns (address)","event IntentExecuted(bytes32 indexed intentHash,address indexed owner,address indexed relayer,bytes32 poolId,uint256 amountIn,uint256 amountOut,uint256 relayerFee,bool feeFromInput)"]),ke={PoolKey:[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],HookrSwapIntent:[{name:"key",type:"PoolKey"},{name:"zeroForOne",type:"bool"},{name:"amountSpecified",type:"int128"},{name:"amountBound",type:"uint128"},{name:"sqrtPriceLimitX96",type:"uint160"},{name:"recipient",type:"address"},{name:"relayer",type:"address"},{name:"relayerFee",type:"uint256"},{name:"engagement",type:"address"},{name:"campaigns",type:"uint256[]"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},we=ge("(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks)"),be=pe("0x000000000022D473030F116dDEE9F6B43aC78BA3"),R={key:{type:"object",description:"Uniswap v4 PoolKey of the pool to swap in.",properties:{currency0:{...l,description:"Lower-sorted pool token address; the zero address is native ETH, which cannot be the relay input."},currency1:{...l,description:"Higher-sorted pool token address; must be greater than currency0."},fee:{type:"integer",description:F.pips()},tickSpacing:{type:"integer",description:"Pool tick spacing, a positive integer."},hooks:{...l,description:"Address of the pool hook contract."}},required:["currency0","currency1","fee","tickSpacing","hooks"],additionalProperties:!1},zeroForOne:{type:"boolean",description:"True swaps currency0 for currency1 (input is currency0); false swaps currency1 for currency0."},amountSpecified:{type:"string",pattern:"^-?[0-9]+$",description:'Signed amount in base units: negative = exact input of the input token, positive = exact output of the output token. Example: "-1000000" = 1 USDG in, if USDG (6 decimals) is the input.'},amountBound:{...f(),description:"Slippage bound in base units: minimum output token if amountSpecified is negative, maximum input token if positive. Must be nonzero; read that token's decimals."},sqrtPriceLimitX96:{...f(),description:"Swap price limit as a Q64.96 sqrt price, decimal string."},recipient:{...l,description:F.recipient("account that receives the swap output")},relayer:{...l,description:"Address of the relayer allowed to submit this intent (must be the submitting wallet), or the zero address for an open relay with no fee."},relayerFee:{...f(),description:"Fee paid to the relayer in base units of the fee token (the input token if charged on input, else the output token); read its decimals. Must be 0 for an open relay."},engagement:{...l,description:"Address of the Hookr engagement contract for campaign credit, or the zero address when campaigns is empty."},campaigns:{type:"array",items:f(),maxItems:8,description:"Up to eight campaign IDs (decimal strings) to credit; empty when engagement is the zero address."},nonce:{...f(),description:"Unique Permit2-style intent nonce of the trader, a decimal string; each nonce can execute once."},deadline:{...f(),description:"Intent expiry as a Unix seconds timestamp; the relay fails after this time."}},T={owner:{...l,description:F.recipient("trader who signed the intent and supplies the input funds")},signature:{type:"string",pattern:"^0x[0-9a-fA-F]+$",description:"The trader's Permit2 witness signature over the intent, as 0x-prefixed hex."},intent:{type:"object",description:"The complete trader-signed Hookr swap intent.",properties:R,required:Object.keys(R),additionalProperties:!1}};function C(r){return q(r,"Provide a complete trader-signed Hookr intent.")}function g(r,o=256,e=!1){if(typeof r!="string"||!/^-?\d+$/.test(r)||r.length>79)throw new i("Hookr intent amounts, nonce and deadline must be decimal base-unit strings.");let n=BigInt(r);if(e?n<=-(1n<<BigInt(o-1))||n>=1n<<BigInt(o-1):n<0n||n>=1n<<BigInt(o))throw new i("Hookr intent integer is outside its ABI range.");return n}function h(r){return L(r,"Provide valid Hookr intent addresses.")}function G(r,o){if(Object.keys(r).some(s=>!Object.hasOwn(T,s)))throw new i("Provide only owner, intent and the trader signature for Hookr relay.");let e=C(r.intent);if(Object.keys(e).some(s=>!Object.hasOwn(R,s)))throw new i("Hookr intent contains an undocumented field.");let n=C(e.key);if(Object.keys(n).some(s=>!["currency0","currency1","fee","tickSpacing","hooks"].includes(s))||typeof n.fee!="number"||!Number.isInteger(n.fee)||n.fee<0||n.fee>16777215||typeof n.tickSpacing!="number"||!Number.isInteger(n.tickSpacing)||n.tickSpacing<=0||n.tickSpacing>8388607||typeof e.zeroForOne!="boolean")throw new i("Provide a valid canonical v4 pool key and direction.");let a={currency0:h(n.currency0),currency1:h(n.currency1),fee:n.fee,tickSpacing:n.tickSpacing,hooks:h(n.hooks)};if(BigInt(a.currency0)>=BigInt(a.currency1))throw new i("Hookr pool currencies must sort strictly by address.");let t=h(r.owner);if(t===m||d(t,o))throw new i("Hookr relay requires another trader as owner; the relayer funds gas only.");if(!Array.isArray(e.campaigns)||e.campaigns.length>8)throw new i("Provide at most eight Hookr campaign IDs.");let c={key:a,zeroForOne:e.zeroForOne,amountSpecified:g(e.amountSpecified,128,!0),amountBound:g(e.amountBound,128),sqrtPriceLimitX96:g(e.sqrtPriceLimitX96,160),recipient:h(e.recipient),relayer:h(e.relayer),relayerFee:g(e.relayerFee),engagement:h(e.engagement),campaigns:e.campaigns.map(s=>g(s)),nonce:g(e.nonce),deadline:g(e.deadline)};if(c.amountSpecified===0n||c.amountBound===0n)throw new i("Hookr intent input/output amounts and bound must be nonzero.");if([m,S,A].some(s=>d(s,c.recipient)))throw new i("Hookr intent recipient is reserved.");if(c.relayer!==m&&!d(c.relayer,o)||c.relayer===m&&c.relayerFee!==0n)throw new i("Hookr intent names a different relayer or an open relay with a fee.");if(c.engagement===m!=(c.campaigns.length===0))throw new i("Hookr engagement and campaigns must be supplied together.");let k=c.zeroForOne?a.currency0:a.currency1;if(k===m)throw new i("Hookr Permit2 relay cannot pull native ETH input.");if(typeof r.signature!="string"||!le(r.signature,{strict:!0})||r.signature.length<4||r.signature.length%2!==0||r.signature.length>16386)throw new i("Provide the trader-signed Permit2 witness signature, never a private key.");let x=r.signature,y=me({data:c,primaryType:"HookrSwapIntent",types:ke});return{owner:t,intent:c,signature:x,input:k,intentHash:y}}function M(r,o){let{owner:e,intent:n,signature:a}=G(r,o);return{chainId:v,to:S,value:"0",data:ue({abi:O,functionName:"execute",args:[n,e,a]}),description:`Relay Hookr trader ${e} to recipient ${n.recipient}; relayer fee ${n.relayerFee} in pool quote currency. Relayer pays gas; owner supplies Permit2 funds.`}}function Ae(r,o,e){let n=M(o,e);if(r.length!==1||r[0].chainId!==n.chainId||!d(r[0].to,n.to)||r[0].value!=="0"||!d(r[0].data,n.data))throw new i("Hookr relay calldata differs from the locally requested signed intent.")}function Re(r){return[{name:"hookr_relay",inputSchema:{type:"object",description:"Preview a trader-signed Permit2 swap for local human-confirmed submission. Relayer pays gas; the trader supplies input. No signature is created by this tool.",properties:T,required:Object.keys(T),additionalProperties:!1},execute:async(o,e)=>{let n=G(o,e),{owner:a,intent:t,signature:c,input:k,intentHash:x}=n,y=r.clientFor(v),s=await y.getBlock();if(typeof s.number!="bigint"||typeof s.timestamp!="bigint"||s.timestamp<=0n||s.timestamp>t.deadline)throw new i("Hookr signed intent expired or the chain timestamp is unavailable.");let w=(ae,se=[])=>y.readContract({address:S,abi:O,functionName:ae,args:se,blockNumber:s.number}),[W,u,X,J,Q,V]=await Promise.all([w("hashIntent",[t]),w("pullOf",[t]),w("isNonceUsed",[a,t.nonce]),w("router"),w("registry"),w("permit2")]);if(W!==x||X!==!1||J!==A||Q!==_||V!==be)throw new i("Hookr intent hash, nonce or forwarder deployment is invalid. Ask the trader for a fresh signed intent.");if(!Array.isArray(u)||u.length!==3||typeof u[0]!="string"||!d(u[0],k)||typeof u[1]!="bigint"||typeof u[2]!="boolean")throw new i("Hookr Permit2 pull could not be verified.");let b=u[2],E=t.amountSpecified<0n?-t.amountSpecified:t.amountBound;if(u[1]!==E+(b?t.relayerFee:0n)||t.amountSpecified>0n&&!b&&t.relayerFee>t.amountSpecified)throw new i("Hookr Permit2 pull or output-side fee differs from the signed terms.");let Y=await y.simulateContract({address:S,abi:O,functionName:"execute",args:[t,a,c],account:e,blockNumber:s.number}),[$,B]=Y.result,D=t.amountSpecified<0n?t.amountBound:t.amountSpecified-(b?0n:t.relayerFee);if($>E||B<D)throw new i("Hookr relay simulation did not satisfy the signed input/output bounds.");let Z=ye(de(we,[t.key])),ee=await U(r,Z,s.number),I=M(o,e),te=await y.estimateGas({account:e,to:I.to,data:I.data,value:0n,blockNumber:s.number}),ne=j(te,ee),H=b?k:t.zeroForOne?t.key.currency1:t.key.currency0,p=await K(y,ne,d(H,m)?t.relayerFee:void 0),N=d(H,m)?"ETH":`token ${H}`,z=`${t.relayerFee} base units ${N}`,re=`Relayer fee ${z}; gas limit ${p.gasLimit}, gas ceiling at current gas price ${p.gasCostEth} ETH; ${p.netWei===null?`net unknown because the reward is denominated in ${N} while gas is ETH`:`net ${p.netWei} wei (${p.netWei} base units ETH)`}. Fee is paid only on success; someone may get there first.`,ie={summary:`${I.description} Relayer fee ${z}; gas limit ${p.gasLimit}. Fee is paid only on success; someone may get there first.`,rewardWei:d(H,m)?t.relayerFee.toString():null,facts:{intentHash:x,feeToken:H,relayerFee:t.relayerFee.toString(),feeFromInput:b,gasLimit:p.gasLimit}},P=[{...r.unsignedTx({...I,description:`${I.description} ${re}`}),gasLimit:p.gasLimit}],oe=await r.preview(P,e);return{txs:P,preview:oe,summary:P[0].description,consent:ie,intentHash:x,owner:a,recipient:t.recipient,relayer:e,inputToken:k,maximumPull:u[1].toString(),feeToken:H,relayerFee:t.relayerFee.toString(),feeFromInput:b,minimumOutput:D.toString(),simulatedAmountIn:$.toString(),simulatedAmountOut:B.toString(),gas:p,note:"Verify IntentExecuted in the receipt and your fee balance after submission."}}},{name:"hookr_relay_receipt",inputSchema:{type:"object",description:"Read the executed intent and fee from a mined Hookr relay receipt.",properties:{transactionHash:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$",description:"Hash of the mined relay transaction: 32 bytes, 0x followed by 64 hex digits."}},required:["transactionHash"],additionalProperties:!1},execute:async o=>{if(Object.keys(o).some(a=>a!=="transactionHash")||typeof o.transactionHash!="string"||!/^0x[0-9a-fA-F]{64}$/.test(o.transactionHash))throw new i("Provide a Hookr relay transactionHash.");let e=await r.clientFor(v).getTransactionReceipt({hash:o.transactionHash});if(e.status!=="success")throw new i("Hookr relay reverted. No fee is proven paid.");let n=e.logs.filter(a=>d(a.address,S)).flatMap(a=>{try{let t=ce({abi:O,eventName:"IntentExecuted",topics:a.topics,data:a.data});return[{...t.args,amountIn:t.args.amountIn.toString(),amountOut:t.args.amountOut.toString(),relayerFee:t.args.relayerFee.toString()}]}catch{return[]}});if(!n.length)throw new i("Receipt contains no verified Hookr IntentExecuted event.");return{chainId:v,transactionHash:e.transactionHash,blockNumber:e.blockNumber.toString(),intents:n,note:"Event evidence at this mined block; check balances and finality."}}}]}export{O as a,G as b,M as c,Ae as d,Re as e};
|
|
1
|
+
import{a as F}from"./G2LAO23N.js";import{c as A,d as _,e as S}from"./37UBQQWL.js";import{d as j,e as U,g as K}from"./LD3A2KLN.js";import{a as f}from"./66F5ZH34.js";import{c as l,f as q,g as d,i as L}from"./NWNYJ26T.js";import{b as v}from"./EWZFZUVF.js";import{a as i}from"./XSD5NL7J.js";import{decodeEventLog as ce,encodeAbiParameters as de,encodeFunctionData as ue,getAddress as pe,hashStruct as me,isHex as le,keccak256 as ye,parseAbi as fe,parseAbiParameters as ge,zeroAddress as m}from"viem";var he="struct HookrSwapIntent { PoolKey key; bool zeroForOne; int128 amountSpecified; uint128 amountBound; uint160 sqrtPriceLimitX96; address recipient; address relayer; uint256 relayerFee; address engagement; uint256[] campaigns; uint256 nonce; uint256 deadline; }",O=fe(["struct PoolKey { address currency0; address currency1; uint24 fee; int24 tickSpacing; address hooks; }",he,"function execute(HookrSwapIntent intent, address owner, bytes signature) returns (uint256 amountIn, uint256 amountOut)","function hashIntent(HookrSwapIntent intent) pure returns (bytes32)","function pullOf(HookrSwapIntent intent) view returns (address token, uint256 amount, bool feeFromInput)","function isNonceUsed(address owner, uint256 intentNonce) view returns (bool)","function router() view returns (address)","function registry() view returns (address)","function permit2() view returns (address)","event IntentExecuted(bytes32 indexed intentHash,address indexed owner,address indexed relayer,bytes32 poolId,uint256 amountIn,uint256 amountOut,uint256 relayerFee,bool feeFromInput)"]),ke={PoolKey:[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],HookrSwapIntent:[{name:"key",type:"PoolKey"},{name:"zeroForOne",type:"bool"},{name:"amountSpecified",type:"int128"},{name:"amountBound",type:"uint128"},{name:"sqrtPriceLimitX96",type:"uint160"},{name:"recipient",type:"address"},{name:"relayer",type:"address"},{name:"relayerFee",type:"uint256"},{name:"engagement",type:"address"},{name:"campaigns",type:"uint256[]"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},we=ge("(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks)"),be=pe("0x000000000022D473030F116dDEE9F6B43aC78BA3"),R={key:{type:"object",description:"Uniswap v4 PoolKey of the pool to swap in.",properties:{currency0:{...l,description:"Lower-sorted pool token address; the zero address is native ETH, which cannot be the relay input."},currency1:{...l,description:"Higher-sorted pool token address; must be greater than currency0."},fee:{type:"integer",description:F.pips()},tickSpacing:{type:"integer",description:"Pool tick spacing, a positive integer."},hooks:{...l,description:"Address of the pool hook contract."}},required:["currency0","currency1","fee","tickSpacing","hooks"],additionalProperties:!1},zeroForOne:{type:"boolean",description:"True swaps currency0 for currency1 (input is currency0); false swaps currency1 for currency0."},amountSpecified:{type:"string",pattern:"^-?[0-9]+$",description:'Signed amount in base units: negative = exact input of the input token, positive = exact output of the output token. Example: "-1000000" = 1 USDG in, if USDG (6 decimals) is the input.'},amountBound:{...f(),description:"Slippage bound in base units: minimum output token if amountSpecified is negative, maximum input token if positive. Must be nonzero; read that token's decimals."},sqrtPriceLimitX96:{...f(),description:"Swap price limit as a Q64.96 sqrt price, decimal string."},recipient:{...l,description:F.recipient("account that receives the swap output")},relayer:{...l,description:"Address of the relayer allowed to submit this intent (must be the submitting wallet), or the zero address for an open relay with no fee."},relayerFee:{...f(),description:"Fee paid to the relayer in base units of the fee token (the input token if charged on input, else the output token); read its decimals. Must be 0 for an open relay."},engagement:{...l,description:"Address of the Hookr engagement contract for campaign credit, or the zero address when campaigns is empty."},campaigns:{type:"array",items:f(),maxItems:8,description:"Up to eight campaign IDs (decimal strings) to credit; empty when engagement is the zero address."},nonce:{...f(),description:"Unique Permit2-style intent nonce of the trader, a decimal string; each nonce can execute once."},deadline:{...f(),description:"Intent expiry as a Unix seconds timestamp; the relay fails after this time."}},T={owner:{...l,description:F.recipient("trader who signed the intent and supplies the input funds")},signature:{type:"string",pattern:"^0x[0-9a-fA-F]+$",description:"The trader's Permit2 witness signature over the intent, as 0x-prefixed hex."},intent:{type:"object",description:"The complete trader-signed Hookr swap intent.",properties:R,required:Object.keys(R),additionalProperties:!1}};function C(r){return q(r,"Provide a complete trader-signed Hookr intent.")}function g(r,o=256,e=!1){if(typeof r!="string"||!/^-?\d+$/.test(r)||r.length>79)throw new i("Hookr intent amounts, nonce and deadline must be decimal base-unit strings.");let n=BigInt(r);if(e?n<=-(1n<<BigInt(o-1))||n>=1n<<BigInt(o-1):n<0n||n>=1n<<BigInt(o))throw new i("Hookr intent integer is outside its ABI range.");return n}function h(r){return L(r,"Provide valid Hookr intent addresses.")}function G(r,o){if(Object.keys(r).some(s=>!Object.hasOwn(T,s)))throw new i("Provide only owner, intent and the trader signature for Hookr relay.");let e=C(r.intent);if(Object.keys(e).some(s=>!Object.hasOwn(R,s)))throw new i("Hookr intent contains an undocumented field.");let n=C(e.key);if(Object.keys(n).some(s=>!["currency0","currency1","fee","tickSpacing","hooks"].includes(s))||typeof n.fee!="number"||!Number.isInteger(n.fee)||n.fee<0||n.fee>16777215||typeof n.tickSpacing!="number"||!Number.isInteger(n.tickSpacing)||n.tickSpacing<=0||n.tickSpacing>8388607||typeof e.zeroForOne!="boolean")throw new i("Provide a valid canonical v4 pool key and direction.");let a={currency0:h(n.currency0),currency1:h(n.currency1),fee:n.fee,tickSpacing:n.tickSpacing,hooks:h(n.hooks)};if(BigInt(a.currency0)>=BigInt(a.currency1))throw new i("Hookr pool currencies must sort strictly by address.");let t=h(r.owner);if(t===m||d(t,o))throw new i("Hookr relay requires another trader as owner; the relayer funds gas only.");if(!Array.isArray(e.campaigns)||e.campaigns.length>8)throw new i("Provide at most eight Hookr campaign IDs.");let c={key:a,zeroForOne:e.zeroForOne,amountSpecified:g(e.amountSpecified,128,!0),amountBound:g(e.amountBound,128),sqrtPriceLimitX96:g(e.sqrtPriceLimitX96,160),recipient:h(e.recipient),relayer:h(e.relayer),relayerFee:g(e.relayerFee),engagement:h(e.engagement),campaigns:e.campaigns.map(s=>g(s)),nonce:g(e.nonce),deadline:g(e.deadline)};if(c.amountSpecified===0n||c.amountBound===0n)throw new i("Hookr intent input/output amounts and bound must be nonzero.");if([m,S,A].some(s=>d(s,c.recipient)))throw new i("Hookr intent recipient is reserved.");if(c.relayer!==m&&!d(c.relayer,o)||c.relayer===m&&c.relayerFee!==0n)throw new i("Hookr intent names a different relayer or an open relay with a fee.");if(c.engagement===m!=(c.campaigns.length===0))throw new i("Hookr engagement and campaigns must be supplied together.");let k=c.zeroForOne?a.currency0:a.currency1;if(k===m)throw new i("Hookr Permit2 relay cannot pull native ETH input.");if(typeof r.signature!="string"||!le(r.signature,{strict:!0})||r.signature.length<4||r.signature.length%2!==0||r.signature.length>16386)throw new i("Provide the trader-signed Permit2 witness signature, never a private key.");let x=r.signature,y=me({data:c,primaryType:"HookrSwapIntent",types:ke});return{owner:t,intent:c,signature:x,input:k,intentHash:y}}function M(r,o){let{owner:e,intent:n,signature:a}=G(r,o);return{chainId:v,to:S,value:"0",data:ue({abi:O,functionName:"execute",args:[n,e,a]}),description:`Relay Hookr trader ${e} to recipient ${n.recipient}; relayer fee ${n.relayerFee} in pool quote currency. Relayer pays gas; owner supplies Permit2 funds.`}}function Ae(r,o,e){let n=M(o,e);if(r.length!==1||r[0].chainId!==n.chainId||!d(r[0].to,n.to)||r[0].value!=="0"||!d(r[0].data,n.data))throw new i("Hookr relay calldata differs from the locally requested signed intent.")}function Re(r){return[{name:"hookr_relay",inputSchema:{type:"object",description:"Preview a trader-signed Permit2 swap for local human-confirmed submission. Relayer pays gas; the trader supplies input. No signature is created by this tool.",properties:T,required:Object.keys(T),additionalProperties:!1},execute:async(o,e)=>{let n=G(o,e),{owner:a,intent:t,signature:c,input:k,intentHash:x}=n,y=r.clientFor(v),s=await y.getBlock();if(typeof s.number!="bigint"||typeof s.timestamp!="bigint"||s.timestamp<=0n||s.timestamp>t.deadline)throw new i("Hookr signed intent expired or the chain timestamp is unavailable.");let w=(ae,se=[])=>y.readContract({address:S,abi:O,functionName:ae,args:se,blockNumber:s.number}),[W,u,X,J,Q,V]=await Promise.all([w("hashIntent",[t]),w("pullOf",[t]),w("isNonceUsed",[a,t.nonce]),w("router"),w("registry"),w("permit2")]);if(W!==x||X!==!1||J!==A||Q!==_||V!==be)throw new i("Hookr intent hash, nonce or forwarder deployment is invalid. Ask the trader for a fresh signed intent.");if(!Array.isArray(u)||u.length!==3||typeof u[0]!="string"||!d(u[0],k)||typeof u[1]!="bigint"||typeof u[2]!="boolean")throw new i("Hookr Permit2 pull could not be verified.");let b=u[2],E=t.amountSpecified<0n?-t.amountSpecified:t.amountBound;if(u[1]!==E+(b?t.relayerFee:0n)||t.amountSpecified>0n&&!b&&t.relayerFee>t.amountSpecified)throw new i("Hookr Permit2 pull or output-side fee differs from the signed terms.");let Y=await y.simulateContract({address:S,abi:O,functionName:"execute",args:[t,a,c],account:e,blockNumber:s.number}),[$,B]=Y.result,D=t.amountSpecified<0n?t.amountBound:t.amountSpecified-(b?0n:t.relayerFee);if($>E||B<D)throw new i("Hookr relay simulation did not satisfy the signed input/output bounds.");let Z=ye(de(we,[t.key])),ee=await U(r,Z,s.number),I=M(o,e),te=await y.estimateGas({account:e,to:I.to,data:I.data,value:0n,blockNumber:s.number}),ne=j(te,ee),H=b?k:t.zeroForOne?t.key.currency1:t.key.currency0,p=await K(y,ne,d(H,m)?t.relayerFee:void 0),N=d(H,m)?"ETH":`token ${H}`,z=`${t.relayerFee} base units ${N}`,re=`Relayer fee ${z}; gas limit ${p.gasLimit}, gas ceiling at current gas price ${p.gasCostEth} ETH; ${p.netWei===null?`net unknown because the reward is denominated in ${N} while gas is ETH`:`net ${p.netWei} wei (${p.netWei} base units ETH)`}. Fee is paid only on success; someone may get there first.`,ie={summary:`${I.description} Relayer fee ${z}; gas limit ${p.gasLimit}. Fee is paid only on success; someone may get there first.`,rewardWei:d(H,m)?t.relayerFee.toString():null,facts:{intentHash:x,feeToken:H,relayerFee:t.relayerFee.toString(),feeFromInput:b,gasLimit:p.gasLimit}},P=[{...r.unsignedTx({...I,description:`${I.description} ${re}`}),gasLimit:p.gasLimit}],oe=await r.preview(P,e);return{txs:P,preview:oe,summary:P[0].description,consent:ie,intentHash:x,owner:a,recipient:t.recipient,relayer:e,inputToken:k,maximumPull:u[1].toString(),feeToken:H,relayerFee:t.relayerFee.toString(),feeFromInput:b,minimumOutput:D.toString(),simulatedAmountIn:$.toString(),simulatedAmountOut:B.toString(),gas:p,note:"Verify IntentExecuted in the receipt and your fee balance after submission."}}},{name:"hookr_relay_receipt",inputSchema:{type:"object",description:"Read the executed intent and fee from a mined Hookr relay receipt.",properties:{transactionHash:{type:"string",pattern:"^0x[0-9a-fA-F]{64}$",description:"Hash of the mined relay transaction: 32 bytes, 0x followed by 64 hex digits."}},required:["transactionHash"],additionalProperties:!1},execute:async o=>{if(Object.keys(o).some(a=>a!=="transactionHash")||typeof o.transactionHash!="string"||!/^0x[0-9a-fA-F]{64}$/.test(o.transactionHash))throw new i("Provide a Hookr relay transactionHash.");let e=await r.clientFor(v).getTransactionReceipt({hash:o.transactionHash});if(e.status!=="success")throw new i("Hookr relay reverted. No fee is proven paid.");let n=e.logs.filter(a=>d(a.address,S)).flatMap(a=>{try{let t=ce({abi:O,eventName:"IntentExecuted",topics:a.topics,data:a.data});return[{...t.args,amountIn:t.args.amountIn.toString(),amountOut:t.args.amountOut.toString(),relayerFee:t.args.relayerFee.toString()}]}catch{return[]}});if(!n.length)throw new i("Receipt contains no verified Hookr IntentExecuted event.");return{chainId:v,transactionHash:e.transactionHash,blockNumber:e.blockNumber.toString(),intents:n,note:"Event evidence at this mined block; check balances and finality."}}}]}export{O as a,G as b,M as c,Ae as d,Re as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as T}from"./LBT6WR4U.js";import{c as A}from"./5UWVXEPD.js";import{i as b}from"./DWRRIFXS.js";import{o as P}from"./
|
|
1
|
+
import{b as T}from"./LBT6WR4U.js";import{c as A}from"./5UWVXEPD.js";import{i as b}from"./DWRRIFXS.js";import{o as P}from"./OUXPOFY2.js";import{b as f,j as g}from"./EWZFZUVF.js";var U=.5,E=394930n,C=315200n,R=1000000000n,x=10000n*10n**18n,M="fees estimated high because the live price was unavailable";function I(s,r){if(s.impliedApy===void 0)return{reason:"Pendle's service gave no rate, so Oak won't show one."};let t=Math.expm1(Number(r)/1e18)*100,n=s.impliedApy*100;return!Number.isFinite(t)||!Number.isFinite(n)?{reason:"the rate could not be checked against the chain, so Oak won't show one."}:Math.abs(n-t)>U?{reason:`The rate Pendle's service lists (${n.toFixed(2)}% a year) differs from the chain's (${t.toFixed(2)}% a year) by more than ${U} points, so Oak won't show one.`}:{ratePct:n}}async function S(s,r){let t=s.clientFor(f),n=await t.getGasPrice().catch(()=>{}),i=r;i===void 0&&(i=await P(g[f].tokens.WETH.address,{client:t}).then(a=>BigInt(a.usdE18),()=>{}));let o=n!==void 0&&n>0n&&i!==void 0&&i>0n?{gasPrice:n,ethUsd:i}:void 0,{gasPrice:u,ethUsd:h}=o??{gasPrice:R,ethUsd:x},m=a=>Number(a*u*h)/1e36;return{inUsd:m(E),outUsd:m(C),checks:o?[]:[M]}}async function v(s,r,t={}){let n=s.clientFor(f),i=t.now??Math.floor(Date.now()/1e3),o=await b(s,{allowChain:!1}),u=await T(n,r,o.rows),h=e=>(u.get(e.pt.toLowerCase())??0n)>0n,m=o.rows.filter(e=>e.active&&e.expiry>i||h(e)),[{ok:a,dropped:_},p]=await Promise.all([A(n,m,{now:i}),S(s,t.ethUsdE18)]),y=[...o.dropped,..._],l=[];for(let{row:e,facts:d}of a){let c=d.verified,k={market:e.market,kind:c.kind,unitSymbol:c.inputSymbol,unitDecimals:c.inputDecimals,endsAt:c.expiry,liquidityUsd:e.liquidityUsd??0,ptBalanceBase:u.get(e.pt.toLowerCase())??0n,gasInUsd:p.inUsd,gasOutUsd:p.outUsd};if(c.expired){k.ptBalanceBase>0n&&l.push({...k,ratePct:0,matured:!0,checks:["this term has ended",...p.checks]});continue}if(!e.active)continue;let w=I(e,d.lnImpliedRate);if("reason"in w){y.push(`${e.market}: ${w.reason}`);continue}l.push({...k,ratePct:w.ratePct,matured:!1,checks:[...e.liquidityUsd===void 0?["liquidity was not reported"]:[],...p.checks]})}return l.sort((e,d)=>e.kind===d.kind?e.endsAt-d.endsAt:e.kind==="stable"?-1:1),{terms:l,dropped:y}}async function L(s,r,t={}){return(await v(s,r,t)).terms}export{I as a,v as b,L as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as he,f as pt,h as lt,i as mt,u as ht,w as kt}from"./EHQRAA3R.js";import{a as ve,c as ct}from"./3M7RMROZ.js";import{i as dt}from"./JCS24YBB.js";import{k as rt}from"./G4IX4CYN.js";import{B as nt,t as Re,y as ot}from"./5677LZOV.js";import{c as me,h as Ze,k as et,l as tt}from"./7GL547YZ.js";import{b as ut}from"./IJVBCEA2.js";import{a as l,b as it,c as at,e as st}from"./RKS3M7L5.js";import{a as le}from"./G2LAO23N.js";import{m as Le}from"./IR7KDBFU.js";import{a as Ve}from"./3RGED2KO.js";import{a as w,b as Se,d as Je,e as _,f as m,h as pe,i as A,j as h,k as Q,l as M,m as G,n as Be,o as T,p,q as W,r as He,s as Ye}from"./UMY6SP7C.js";import{b as de,i as qe,j as Qe,k as We}from"./CJMVRV34.js";import{a as Xe}from"./7WXAS54T.js";import{t as De}from"./EWZFZUVF.js";import{a as r}from"./XSD5NL7J.js";import{encodeFunctionData as Lt,erc20Abi as Rt,formatUnits as J,getAddress as $e,parseAbi as fe,zeroAddress as k,zeroHash as ge}from"viem";var vt="hookr_launch",y=$e(de.launcherV1),Y=$e(de.rulesV1),At=720*60*60,ke=(i,t=Object.keys(i))=>({type:"object",properties:i,required:t,additionalProperties:!1}),ft={type:"string",pattern:"^0x[0-9a-fA-F]{40}$"},Ae={...ke({launchProfile:{type:"string",enum:["agents-only","open"],description:"Choose agents-only (default, requires agentGate) or open (requires one advisory Hook Block and omits agentGate)."},token:{description:'Token to launch: kind "new" creates a fresh token; kind "existing" is reserved and currently refused.',oneOf:[ke({kind:{const:"new",type:"string",description:le.enumValues({new:"create and launch a fresh token"})},name:{type:"string",minLength:1,maxLength:48,description:"Public token name, 1 to 48 UTF-8 bytes, no control characters."},symbol:{type:"string",minLength:1,maxLength:12,description:"Public token ticker symbol, 1 to 12 UTF-8 bytes, no control characters."},supply:{...w,description:'Total supply of the new token in base units (18 decimals: "1000000000000000000" = 1 token); positive, below 2^108.'},salt:{...Se,description:"Bytes32 hex salt (0x plus 64 hex digits) that fixes the new token address."}}),ke({kind:{const:"existing",type:"string",description:le.enumValues({existing:"reserved for an already deployed token; launching it is not supported yet"})},address:{...ft,description:le.address("existing token contract")}})]},quote:{...ft,description:"Qualified ETH (zero address) or pinned USDG quote. Other quote funding routes await qualification."},sqrtPriceX96:{...w,description:"Integer sqrt(currency1/currency0) times 2^96 for the sorted PoolKey."},tickLower:{type:"integer",minimum:-887272,maximum:887272,description:"Lower tick of the launch range, a signed integer and a multiple of the tick spacing 200; below tickUpper."},tickUpper:{type:"integer",minimum:-887272,maximum:887272,description:"Upper tick of the launch range, a signed integer and a multiple of the tick spacing 200; above tickLower."},liquidity:{...w,description:"Set the initial liquidity in v4 liquidity units, positive and below 2^127, with rounded-up token debts within both funding caps."},amount0Max:{...w,description:"Set the maximum currency0 funding in that token\u2019s base units, using its decimals."},amount1Max:{...w,description:"Set the maximum currency1 funding in that token\u2019s base units, using its decimals."},agentGate:{description:"Set identity and score requirements for entrants; creator family liquidity is exempt from score and age requirements.",...ke({minAgeSeconds:{...w,description:"Explicit minimum live link age in seconds for buys and other LPs, 0 to 2592000; the creator family liquidity is exempt."},minScore:{...w,description:"Minimum agent reputation score required to buy; 0 means no minimum."},tierScore:{...w,description:"Set the score at which the base fee applies, or 0 when tierPips is 0; lower scores pay the surcharge."},tierPips:{...w,description:"LP fee surcharge in pips for agents below tierScore (3000 = 0.3%); at most 50000, and 0 only when tierScore is 0."},reviewerSetId:{...Se,description:"Bytes32 id of a registered reviewer set that scores agents; all zeros unless the gate uses a score."}})},hookBlocks:pt,lpRewardsBps:{...w,description:"Set the LP Rewards rate in basis points (50 = 0.5%), at most 1000; this profile has zero burn."},arbRecapture:{type:"boolean",description:"Arb recapture, permanent either way: true turns it on (25% executor, 15% Hookr, 60% LPs; swaps need a high gas limit), false launches without it. Defaults to true when omitted."},deadline:{...w,description:"Set the latest launch execution time in Unix seconds, within the next 300 seconds of chain time."}},["token","quote","sqrtPriceX96","tickLower","tickUpper","liquidity","amount0Max","amount1Max","lpRewardsBps","deadline"]),allOf:[{if:{properties:{launchProfile:{const:"open",description:"Select the open launch profile."}},required:["launchProfile"]},then:{not:{required:["agentGate"]}},else:{required:["agentGate"]}}]};function $t(i){let t=_(i,Object.keys(Ae.properties),Ae.required),a=mt(t.hookBlocks),e=st(t.launchProfile,t.agentGate,a),o=G(t.token);if(o.kind==="existing")throw _(o,["kind","address"],["kind","address"]),A(o.address),new r("Existing-token Hookr launches await a qualified funding route. Use token.kind new.");if(_(o,["kind","name","symbol","supply","salt"],["kind","name","symbol","supply","salt"]),o.kind!=="new")throw new r("Choose token.kind new; existing tokens are not supported yet.");let n=(R,oe)=>{if(typeof R!="string"||!R.trim()||new TextEncoder().encode(R).length>oe||[...R].some(we=>we.codePointAt(0)<32)||/[\u007f-\u009f\u2028-\u202e\u2066-\u2069\ud800-\udfff]/u.test(R))throw new r(`Use nonempty public token text within ${oe} UTF-8 bytes without control characters.`);return R},x=m(o.supply,108);if(!x)throw new r("Hookr new-token supply must be positive and at most 2^108-1 base units.");let q=A(t.quote);if(![k,$e(De.mainnet.usdg)].includes(q))throw new r("Use native ETH (zero address) or the pinned USDG quote; other quote funding routes await qualification.");let s=t.tickLower,c=t.tickUpper;if(typeof s!="number"||typeof c!="number")throw new r("Provide integer aligned Hookr ticks.");ot(s,c,l.tickSpacing);let u=m(t.sqrtPriceX96,160);if(u<=Le(s)||u>=Le(c))throw new r("Hookr opening price must be strictly inside the aligned tick range.");let S=m(t.liquidity,127);if(!S)throw new r("Hookr liquidity must be positive and at most int128 max.");let P=m(t.amount0Max,128),$=m(t.amount1Max,128),B=nt({liquidity:S,tickLower:s,tickUpper:c,sqrtPriceX96:u,roundUp:!0});if(B.amount0>=1n<<127n||B.amount1>=1n<<127n||!B.amount0||!B.amount1||B.amount0>P||B.amount1>$)throw new r("Hookr exact rounded-up debts must be positive and fit both approved funding caps. Reduce liquidity or increase the caps.");let f=e.kind==="agents-only"?_(t.agentGate,["minAgeSeconds","minScore","tierScore","tierPips","reviewerSetId"],["minAgeSeconds","minScore","tierScore","tierPips","reviewerSetId"]):{minAgeSeconds:"0",minScore:"0",tierScore:"0",tierPips:"0",reviewerSetId:ge},K=Number(m(f.minScore,32)),C=Number(m(f.tierScore,32)),N=Number(m(f.tierPips,24)),Z=pe(f.reviewerSetId),ee=Number(m(f.minAgeSeconds,32));if(ee>At)throw new r("Hookr minAgeSeconds must be at most 2592000.");if(N>5e4||N===0!=(C===0)||Z===ge!=(K===0&&C===0))throw new r("Hookr gate scores, tier and reviewer set must agree; tier surcharge is at most 50000 pips.");let te=Number(m(t.lpRewardsBps,16));if(te>1e3)throw new r("Hookr LP Rewards plus burn must not exceed 1000 bps; this profile has zero burn.");if(t.arbRecapture!==void 0&&typeof t.arbRecapture!="boolean")throw new r("Use arbRecapture true or false; omitted defaults to true.");return{token:{existing:k,name:n(o.name,48),symbol:n(o.symbol,12),supply:x,salt:pe(o.salt)},quote:q,sqrtPriceX96:u,tickLower:s,tickUpper:c,liquidity:S,amount0Max:P,amount1Max:$,debts:B,launchProfile:e.kind,gateTerms:{flags:e.kind==="agents-only"?1:0,minScore:K,tierScore:C,tierPips:N,reviewers:Z,minAge:ee},hookBlocks:a,lpRewardsBps:te,arbRecapture:t.arbRecapture!==!1,arbRecaptureOmitted:t.arbRecapture===void 0,deadline:m(t.deadline,64)}}async function Ot(i,t,a,e){return A(await p(i,y,T("launcherV1"),"predictToken",[t,a],e))}async function Ft(i,t,a,e,o){let n=a.gate;if(!n.walletAgent||!(e?n.healthyForScores:n.healthyIdentityOnly))throw new r("Hookr needs a healthy on-chain agent identity. Own an ERC-8004 identity or link its current agent wallet on the Hookr gate; Oak setup linking alone is insufficient.");let x=(c,u)=>p(i,n.identity,fe(["function balanceOf(address) view returns (uint256)","function ownerOf(uint256) view returns (address)","function getAgentWallet(uint256) view returns (address)"]),c,u,o),q=h(await x("balanceOf",[t])),s=!1;if(n.link.linked){let c=BigInt(n.link.agentId);s=A(await x("getAgentWallet",[c]))===t,!s&&q>0n&&(s=A(await x("ownerOf",[c]))===t)}if(!q&&!s)throw new r("Hookr on-chain identity ownership or gate link is missing or stale. Own an ERC-8004 identity or link its current agent wallet on the Hookr gate before launching.")}function to(i){let t=JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"hookr_blocks",arguments:{}}});return(async(a,e)=>{if(a!==Ve||e?.method!=="POST"||e.body!==t)throw new r("The local Hookr launch rebuild may only read the public Hook Block catalog.");return i(a,{...e,headers:{"content-type":"application/json","user-agent":"Mozilla/5.0"}})})}async function It(i,t,a){let e=$t(t);if(i.network==="testnet")throw new r("Hookr launch requires Robinhood Chain 4663.");let o=i.clientFor(4663),n=await Qe(o);if(e.deadline<=n.timestamp||e.deadline>n.timestamp+l.deadlineSeconds)throw new r("Set a fresh Hookr deadline within the next 300 seconds of chain time.");let x=[],q="";try{x=await lt(i)}catch(d){if(e.hookBlocks.length)throw d;q="Hookr gate hint unavailable; checking the shipped current gate against the chain."}let s,c=null;if(e.launchProfile==="agents-only"){let d=e.gateTerms.reviewers!==ge,L=x.find(I=>I.id==="agent-gate"&&I.openToNewPools)?.address??me,ue=d?[e.gateTerms.reviewers]:[],F;try{F=await ve(o,a,n.number,ue,L)}catch(I){if(L===me)throw I;F=await ve(o,a,n.number,ue,me),q=`Hookr gate hint ${L} refused by the chain; using the listed gate.`}await Ft(o,a,F,d,n.number),s=F,c=F.gate}else s=await ct(o,a,n.number);if(!s.rootOpenForWallet||s.newMarketsPaused||!s.launcherAdmitted)throw new r("Hookr new markets or the reviewed Launcher are closed. Retry only after registry admission is restored.");let u=await Ot(o,a,e.token,n.number);if(u===k||u===e.quote)throw new r("Hookr predicted token collides with its quote. Choose a fresh salt.");let S={currency0:BigInt(u)<BigInt(e.quote)?u:e.quote,currency1:BigInt(u)<BigInt(e.quote)?e.quote:u,fee:8388608,tickSpacing:l.tickSpacing,hooks:W},P=Re(S),$=S.currency0===u,B=$?e.amount0Max:e.amount1Max,f=$?e.amount1Max:e.amount0Max,K=$?e.debts.amount0:e.debts.amount1,C=$?e.debts.amount1:e.debts.amount0;if(B>e.token.supply)throw new r("Hookr new-token deposit cap exceeds its fixed supply.");let[N,Z,ee,te,R,oe,we,gt]=await Promise.all([o.getCode({address:u,blockNumber:n.number}),o.getTransactionCount({address:u,blockNumber:n.number}),p(o,y,T("launcherV1"),"memberKey",[u,e.quote,l.tickSpacing,W],n.number),p(o,W,T("rootV1"),"knownPool",[P],n.number),p(o,y,T("launcherV1"),"SKIP_TAKEN",[],n.number),p(o,He,T("registry"),"isQuote",[e.quote],n.number),p(o,He,T("registry"),"quoteIsBraked",[e.quote],n.number),p(o,Y,T("rulesV1"),"minProtocolShareBps",[],n.number)]),[wt,yt]=M(ee,2);if(e.token.salt===pe(R))throw new r("SKIP_TAKEN is unsupported. Choose an ordinary new-token salt.");if(N&&N!=="0x"||Z!==0||Q(te)||!Q(yt)||Re(G(wt))!==P)throw new r("Hookr token address or pool is already taken or its predicted key differs. Choose a fresh salt and rebuild.");if(!Q(oe)||Q(M(we,2)[0]))throw new r("The Hookr quote is not currently qualified or is braked. Choose an admitted quote.");let ye=c?G(c.admission):null,z=ye?m(G(ye.caps).maxLpFeePips,24):0n,be=BigInt(s.coreAdmission.caps.maxLpFeePips);if(c&&(BigInt(e.gateTerms.tierPips)>z||BigInt(l.baseLpFeePips)+z>be))throw new r("Hookr gate tier or total LP fee exceeds the live admission cap. Lower the tier or wait for compatible admission.");let U=A(await p(o,Y,T("rulesV1"),"protocolRecipient",[],n.number));await qe(o,n.number,[U]);let xe=fe(["function feeTerms(address,bool,bytes32) view returns (uint16,uint16,uint16)","function integrator(address) view returns (uint16,uint16,uint256)","function integratorMinFee(address) view returns (uint16,uint16,uint256)","function MAX_INTEGRATOR_BPS() view returns (uint16)"]),Oe=async d=>M(await p(o,U,xe,"feeTerms",[d,e.arbRecapture,P],n.number),3),[Fe,Ie]=await Promise.all([Oe(k),Oe(he)]),b=h(Ie[1],16);if(b!==0n){let d=async j=>M(await p(o,U,xe,j,[he],n.number),3),[L,ue,F]=await Promise.all([d("integrator"),d("integratorMinFee"),p(o,U,xe,"MAX_INTEGRATOR_BPS",[],n.number)]);if(h(L[0],16)!==b)throw new r("Hookr's listing for Oak and its fee terms for this pool disagree on Oak's rate. Request a fresh launch preview.");let I=h(F,16);if(b>I)throw new r(`Hookr lists Oak at ${b} bps, above its on-chain maximum integrator rate of ${I} bps. Oak will not launch on a listing outside Hookr's own limit.`);if([L[2],ue[2]].map(j=>h(j)).some(j=>j!==0n&&j<=e.deadline))throw new r("Oak's Hookr listing has a change that can take effect before this launch opens. Request a fresh launch preview after it settles.")}let E=b===0n?k:he,[bt,xt,Pt]=b===0n?Fe:Ie,Me=h(bt,16),ne=h(Pt,16);if(h(Fe[1],16)!==0n||h(xt,16)!==b||ne>10000n)throw new r("Hookr treasury minimum or integrator terms exceed the reviewed profile.");let Ce=h(gt,16),re=Me>Ce?Me:Ce;if(re<2000n||re>5000n)throw new r("Hookr protocol share is outside the reviewed 2000\u20135000 bps profile.");let Tt={guardEndBlock:0,maxFeePips:l.baseLpFeePips,snipeTaxPips:0,snipeFloorPips:0,snipeDecaySeconds:0,dynamicFeeSens:0,burnBps:0,lpBps:e.lpRewardsBps,potBps:0,royaltyBps:0,protocolShareBps:Number(re),potEveryNBuys:e.arbRecapture?0:at,maxBuyQuoteAmount:0n,potMinBuyQuote:0n,royaltyTo:k,integrator:E},g=await kt(i,{launchProfile:e.launchProfile,...c?{agentGate:t.agentGate}:{},hookBlocks:e.hookBlocks},Tt,{poolId:P,subject:u,quote:e.quote,tickSpacing:l.tickSpacing,sqrtPriceX96:e.sqrtPriceX96,rules:Y,launcher:y,wallet:a},n,{maxLpFeePips:be,maxQuoteTakePips:BigInt(s.coreAdmission.caps.maxQuoteTakePips),maxSubjectTakeBps:BigInt(s.coreAdmission.caps.maxSubjectTakeBps)},e.arbRecapture?0n:ne,x),{rules:H,blockTerms:Ne,bounds:ie}=g;if(H.guardEndBlock){let d=await rt(o,n);if(BigInt(H.guardEndBlock)<=d+4n||BigInt(H.guardEndBlock)>d+100000n)throw new r("Anti-Snipe guardEndBlock must be more than four and at most 100000 parent blocks ahead.")}let D=ie.maxLpFeePips+z,ae=ie.maxQuoteTakePips;if(D>be||D>600000n||c&&(ae>BigInt(s.coreAdmission.caps.maxQuoteTakePips)||ie.maxSubjectTakeBps>BigInt(s.coreAdmission.caps.maxSubjectTakeBps)))throw new r("Hookr selected blocks exceed the live core fee caps. Lower their rates.");let X=d=>`${J(BigInt(d),4)}%`,Ue=dt(H,e.arbRecapture?0n:ne,U,l.baseLpFeePips),qt=Ue?` ${Ue}`:"",Ee=ht(Ne,U,E===k?void 0:b).join(" "),se=`${J(b,2)}%`,St=E===k?"":` Oak receives ${se} of Hookr's cut on this pool, paid to Oak's wallet ${E}: ${se} of everything Hookr is paid from this pool's fees${e.arbRecapture?`, and ${se} of Hookr's 15% arb recapture cut (${J(b*15n,4)}% of recaptured profit)`:""}. Oak read the ${se} rate on chain; it is frozen when the pool opens. That it comes out of Hookr's part, so traders and LPs pay the same, is Hookr's published rule, not read by Oak.`,ce={on:e.arbRecapture,traderBps:0,lpBps:e.arbRecapture?1e4:0,period:0,maxPrizeBps:0,potReleaseBps:0,minBuyQuote:0n,releaseBlocks:0},je=null;if(e.arbRecapture){let[d,L]=await Promise.all([p(o,Y,fe(["function recaptureDefaults() view returns ((bool on,uint16 traderBps,uint16 lpBps,uint32 period,uint16 maxPrizeBps,uint16 potReleaseBps,uint128 minBuyQuote,uint32 releaseBlocks) rc,uint16 potBps)"]),"recaptureDefaults",[],n.number),tt(o,n.number,{required:!0})]);if(ce.releaseBlocks=Number(h(G(M(d,2)[0]).releaseBlocks,32)),!ce.releaseBlocks)throw new r("Hookr recapture release schedule is unavailable. Use arbRecapture false.");if(L.partnerBps!=="2500")throw new r("Hookr recapture split differs from the disclosed 25% executor profile. Use arbRecapture false.");je=Be(L)}let _e={quote:e.quote,tickSpacing:l.tickSpacing,sqrtPriceX96:e.sqrtPriceX96,tickLower:e.tickLower,tickUpper:e.tickUpper,liquidity:e.liquidity,amount0Max:e.amount0Max,amount1Max:e.amount1Max,config:{subject:u,quote:e.quote,rules:Y,advisory:g.advisory?.address??c.address,liquidityOwner:y,baseLpFeePips:l.baseLpFeePips,caps:{maxLpFeePips:Number(D),maxQuoteTakePips:Number(ae),maxSubjectTakeBps:Number(ie.maxSubjectTakeBps)},rulesGasLimit:Number(s.coreAdmission.gasLimit),advisoryGasLimit:g.advisory?Number(g.advisory.gasLimit):Number(m(ye.gasLimit,32)),advisoryPhases:g.advisory?.phases??1,advisoryFailOpen:g.advisory?g.advisory.failOpen:!1,policyId:ge},rules:H,recapture:ce},O=BigInt(s.launchFee.amount);if(O>10000000000000000n)throw new r("Hookr launch fee exceeds the reviewed 0.01 ETH maximum.");let v=k;if(O&&(await qe(o,n.number,[s.launchFee.treasury]),v=A(await p(o,s.launchFee.treasury,fe(["function target() view returns (address)"]),"target",[],n.number)),v===k||v===y||v===a||v===Ye))throw new r("Hookr launch fee recipient is outside the reviewed payment profile.");let Pe=O+(e.quote===k?f:0n),Te=[],V=[];if(e.quote!==k){let d=h(await p(o,e.quote,Rt,"allowance",[a,y],n.number));d!==0n&&d!==f&&V.push(i.approval(e.quote,y,"0",4663)),V.push(i.approval(e.quote,y,f.toString(),4663)),Te.push({token:e.quote,amount:f})}Pe&&Te.push({token:Xe,amount:Pe,to:y});let Ge=`Launch public, permanent token ${JSON.stringify(e.token.name)} (${JSON.stringify(e.token.symbol)}), fixed supply ${J(e.token.supply,18)} (18 decimals). ${c?c.listed?"Create one agents-only pool (identity check on every buy).":`Create one pool behind a gate Oak has not read: that gate alone decides who may buy and what surcharge applies. Oak knows only its frozen caps: LP fee surcharge at most ${z} pips (${X(z)}), zero quote and subject take.`:g.summaryLines.join(" ")} Price currency1/currency0 = ${e.sqrtPriceX96*e.sqrtPriceX96}/${1n<<192n}; sqrtPriceX96 ${e.sqrtPriceX96}, ticks ${e.tickLower} to ${e.tickUpper}, spacing ${l.tickSpacing}. Deposit at most ${e.amount0Max} currency0 and ${e.amount1Max} currency1 base units; exact launch debts ${e.debts.amount0} and ${e.debts.amount1}. Currency0 ${S.currency0}; currency1 ${S.currency1}. Launch fee ${O} wei to ${v} (${J(O,18)} ETH). Unused quote funding (${f-C} base units) and retained token supply (${e.token.supply-K} base units) return to ${a} in this transaction. Family owner ${a}; token ${u}; pool ${P}. LP base fee ${l.baseLpFeePips} pips (${X(l.baseLpFeePips)}); total LP fee cap ${D} pips (${X(D)}), frozen at launch; ${c?`gate flags 1, scores ${e.gateTerms.minScore}/${e.gateTerms.tierScore}, tier surcharge ${e.gateTerms.tierPips} pips (${X(e.gateTerms.tierPips)}) below tier score, paid to in-range LPs; reviewer set ${e.gateTerms.reviewers}; gate takes zero quote and subject.`:""} LP Rewards ${H.lpBps} bps; configured burn ${H.burnBps} bps; quote-take cap ${ae} pips (${X(ae)}); protocol share ${re} bps.${qt}${St} ${c?`${q} Gate ${c.address}: ${c.listed?"listed":"new gate, Oak has not read its code; it can refuse trades at any time"}. Minimum link age ${e.gateTerms.minAge} seconds (creator family liquidity exempt).`:""} ${it(e.arbRecapture)}${e.arbRecapture?`; recapture pot releases over ${ce.releaseBlocks} blocks`:""}; deadline ${e.deadline}.${e.arbRecaptureOmitted?" Arb recapture is on because arbRecapture was left out; pass arbRecapture false to launch without it.":""} ${H.guardEndBlock?`Principal locked until parent block ${H.guardEndBlock}.`:"No lock."} ${Ee}`,Ke=Lt({abi:T("launcherV1"),functionName:"launchAdvised",args:[e.token,W,[_e],[g.advisory?g.advisory.data:et(Ze(c.address,c.schemaHash),e.gateTerms)],e.deadline]});ut(Ke),V.push(i.unsignedTx({to:y,data:Ke,value:Pe.toString(),chainId:4663,description:Ge}));let[ze,Bt,Ht]=await Promise.all([o.getCode({address:u}),o.getTransactionCount({address:u}),o.readContract({address:y,abi:Je,functionName:"launchFee"})]);if(ze&&ze!=="0x"||Bt!==0||h(M(Ht,5)[0])!==O)throw new r("Hookr collision state or launch fee changed. Request a fresh launch preview.");return await We(o,n),{txs:V,inputs:Te,summary:Ge,tokenAddress:u,poolId:P,feeTarget:v,feeTreasury:s.launchFee.treasury,terms:Be({request:t,blockNumber:n.number,blockHash:n.hash,owner:a,tokenAddress:u,poolId:P,poolKey:S,member:_e,launchProfile:g.kind,advisory:g.advisory,gateTerms:c?e.gateTerms:null,blockTerms:Ne,blockSummary:Ee,launchFee:O,feeTarget:v,feeTreasury:s.launchFee.treasury,hookrMinimumPips:ne,oakIntegrator:E===k?null:{address:E,rateBps:b},exactApprovals:V.slice(0,-1),refunds:{quote:f-C,retainedSupply:e.token.supply-K},gasEstimate:null,gasEstimateReason:"The local sender estimates the ordered exact calls after funding approvals and confirms the gas limit and maximum fee.",lane:je,pins:de})}}function Mt(i){if(!Array.isArray(i)||i.length<1||i.length>3)throw new r("Hookr launch requires only the locally reconstructed finite approvals and one launch transaction.");for(let t of i)_(t,["to","data","value","chainId","description"],["to","data","value","chainId","description"])}function oo(i,t){if(Mt(i),i.length!==t.length||i.some((a,e)=>a.to.toLowerCase()!==t[e].to.toLowerCase()||a.data.toLowerCase()!==t[e].data.toLowerCase()||a.value!==t[e].value||a.chainId!==4663))throw new r("Hookr launch differs from the locally reconstructed exact parameters, approvals and funding.")}function no(i){return[{name:vt,inputSchema:Ae,execute:async(t,a)=>{let e=await It(i,t,a);return{txs:e.txs,preview:await i.preview(e.txs,a),terms:e.terms,summary:e.summary}}}]}export{vt as a,y as b,Y as c,Ae as d,$t as e,to as f,It as g,Mt as h,oo as i,no as j};
|
|
1
|
+
import{b as he,f as pt,h as lt,i as mt,u as ht,w as kt}from"./B4U43D5Z.js";import{a as ve,c as ct}from"./TKJ4GFUP.js";import{i as dt}from"./JCS24YBB.js";import{k as rt}from"./NCCKCGKL.js";import{B as nt,t as Re,y as ot}from"./2ZYFBBOE.js";import{c as me,h as Ze,k as et,l as tt}from"./7GL547YZ.js";import{b as ut}from"./IJVBCEA2.js";import{a as l,b as it,c as at,e as st}from"./RKS3M7L5.js";import{a as le}from"./G2LAO23N.js";import{m as Le}from"./OUXPOFY2.js";import{a as Ve}from"./3RGED2KO.js";import{a as w,b as Se,d as Je,e as _,f as m,h as pe,i as A,j as h,k as Q,l as M,m as G,n as Be,o as T,p,q as W,r as He,s as Ye}from"./UMY6SP7C.js";import{b as de,i as qe,j as Qe,k as We}from"./CJMVRV34.js";import{a as Xe}from"./7WXAS54T.js";import{t as De}from"./EWZFZUVF.js";import{a as r}from"./XSD5NL7J.js";import{encodeFunctionData as Lt,erc20Abi as Rt,formatUnits as J,getAddress as $e,parseAbi as fe,zeroAddress as k,zeroHash as ge}from"viem";var vt="hookr_launch",y=$e(de.launcherV1),Y=$e(de.rulesV1),At=720*60*60,ke=(i,t=Object.keys(i))=>({type:"object",properties:i,required:t,additionalProperties:!1}),ft={type:"string",pattern:"^0x[0-9a-fA-F]{40}$"},Ae={...ke({launchProfile:{type:"string",enum:["agents-only","open"],description:"Choose agents-only (default, requires agentGate) or open (requires one advisory Hook Block and omits agentGate)."},token:{description:'Token to launch: kind "new" creates a fresh token; kind "existing" is reserved and currently refused.',oneOf:[ke({kind:{const:"new",type:"string",description:le.enumValues({new:"create and launch a fresh token"})},name:{type:"string",minLength:1,maxLength:48,description:"Public token name, 1 to 48 UTF-8 bytes, no control characters."},symbol:{type:"string",minLength:1,maxLength:12,description:"Public token ticker symbol, 1 to 12 UTF-8 bytes, no control characters."},supply:{...w,description:'Total supply of the new token in base units (18 decimals: "1000000000000000000" = 1 token); positive, below 2^108.'},salt:{...Se,description:"Bytes32 hex salt (0x plus 64 hex digits) that fixes the new token address."}}),ke({kind:{const:"existing",type:"string",description:le.enumValues({existing:"reserved for an already deployed token; launching it is not supported yet"})},address:{...ft,description:le.address("existing token contract")}})]},quote:{...ft,description:"Qualified ETH (zero address) or pinned USDG quote. Other quote funding routes await qualification."},sqrtPriceX96:{...w,description:"Integer sqrt(currency1/currency0) times 2^96 for the sorted PoolKey."},tickLower:{type:"integer",minimum:-887272,maximum:887272,description:"Lower tick of the launch range, a signed integer and a multiple of the tick spacing 200; below tickUpper."},tickUpper:{type:"integer",minimum:-887272,maximum:887272,description:"Upper tick of the launch range, a signed integer and a multiple of the tick spacing 200; above tickLower."},liquidity:{...w,description:"Set the initial liquidity in v4 liquidity units, positive and below 2^127, with rounded-up token debts within both funding caps."},amount0Max:{...w,description:"Set the maximum currency0 funding in that token\u2019s base units, using its decimals."},amount1Max:{...w,description:"Set the maximum currency1 funding in that token\u2019s base units, using its decimals."},agentGate:{description:"Set identity and score requirements for entrants; creator family liquidity is exempt from score and age requirements.",...ke({minAgeSeconds:{...w,description:"Explicit minimum live link age in seconds for buys and other LPs, 0 to 2592000; the creator family liquidity is exempt."},minScore:{...w,description:"Minimum agent reputation score required to buy; 0 means no minimum."},tierScore:{...w,description:"Set the score at which the base fee applies, or 0 when tierPips is 0; lower scores pay the surcharge."},tierPips:{...w,description:"LP fee surcharge in pips for agents below tierScore (3000 = 0.3%); at most 50000, and 0 only when tierScore is 0."},reviewerSetId:{...Se,description:"Bytes32 id of a registered reviewer set that scores agents; all zeros unless the gate uses a score."}})},hookBlocks:pt,lpRewardsBps:{...w,description:"Set the LP Rewards rate in basis points (50 = 0.5%), at most 1000; this profile has zero burn."},arbRecapture:{type:"boolean",description:"Arb recapture, permanent either way: true turns it on (25% executor, 15% Hookr, 60% LPs; swaps need a high gas limit), false launches without it. Defaults to true when omitted."},deadline:{...w,description:"Set the latest launch execution time in Unix seconds, within the next 300 seconds of chain time."}},["token","quote","sqrtPriceX96","tickLower","tickUpper","liquidity","amount0Max","amount1Max","lpRewardsBps","deadline"]),allOf:[{if:{properties:{launchProfile:{const:"open",description:"Select the open launch profile."}},required:["launchProfile"]},then:{not:{required:["agentGate"]}},else:{required:["agentGate"]}}]};function $t(i){let t=_(i,Object.keys(Ae.properties),Ae.required),a=mt(t.hookBlocks),e=st(t.launchProfile,t.agentGate,a),o=G(t.token);if(o.kind==="existing")throw _(o,["kind","address"],["kind","address"]),A(o.address),new r("Existing-token Hookr launches await a qualified funding route. Use token.kind new.");if(_(o,["kind","name","symbol","supply","salt"],["kind","name","symbol","supply","salt"]),o.kind!=="new")throw new r("Choose token.kind new; existing tokens are not supported yet.");let n=(R,oe)=>{if(typeof R!="string"||!R.trim()||new TextEncoder().encode(R).length>oe||[...R].some(we=>we.codePointAt(0)<32)||/[\u007f-\u009f\u2028-\u202e\u2066-\u2069\ud800-\udfff]/u.test(R))throw new r(`Use nonempty public token text within ${oe} UTF-8 bytes without control characters.`);return R},x=m(o.supply,108);if(!x)throw new r("Hookr new-token supply must be positive and at most 2^108-1 base units.");let q=A(t.quote);if(![k,$e(De.mainnet.usdg)].includes(q))throw new r("Use native ETH (zero address) or the pinned USDG quote; other quote funding routes await qualification.");let s=t.tickLower,c=t.tickUpper;if(typeof s!="number"||typeof c!="number")throw new r("Provide integer aligned Hookr ticks.");ot(s,c,l.tickSpacing);let u=m(t.sqrtPriceX96,160);if(u<=Le(s)||u>=Le(c))throw new r("Hookr opening price must be strictly inside the aligned tick range.");let S=m(t.liquidity,127);if(!S)throw new r("Hookr liquidity must be positive and at most int128 max.");let P=m(t.amount0Max,128),$=m(t.amount1Max,128),B=nt({liquidity:S,tickLower:s,tickUpper:c,sqrtPriceX96:u,roundUp:!0});if(B.amount0>=1n<<127n||B.amount1>=1n<<127n||!B.amount0||!B.amount1||B.amount0>P||B.amount1>$)throw new r("Hookr exact rounded-up debts must be positive and fit both approved funding caps. Reduce liquidity or increase the caps.");let f=e.kind==="agents-only"?_(t.agentGate,["minAgeSeconds","minScore","tierScore","tierPips","reviewerSetId"],["minAgeSeconds","minScore","tierScore","tierPips","reviewerSetId"]):{minAgeSeconds:"0",minScore:"0",tierScore:"0",tierPips:"0",reviewerSetId:ge},K=Number(m(f.minScore,32)),C=Number(m(f.tierScore,32)),N=Number(m(f.tierPips,24)),Z=pe(f.reviewerSetId),ee=Number(m(f.minAgeSeconds,32));if(ee>At)throw new r("Hookr minAgeSeconds must be at most 2592000.");if(N>5e4||N===0!=(C===0)||Z===ge!=(K===0&&C===0))throw new r("Hookr gate scores, tier and reviewer set must agree; tier surcharge is at most 50000 pips.");let te=Number(m(t.lpRewardsBps,16));if(te>1e3)throw new r("Hookr LP Rewards plus burn must not exceed 1000 bps; this profile has zero burn.");if(t.arbRecapture!==void 0&&typeof t.arbRecapture!="boolean")throw new r("Use arbRecapture true or false; omitted defaults to true.");return{token:{existing:k,name:n(o.name,48),symbol:n(o.symbol,12),supply:x,salt:pe(o.salt)},quote:q,sqrtPriceX96:u,tickLower:s,tickUpper:c,liquidity:S,amount0Max:P,amount1Max:$,debts:B,launchProfile:e.kind,gateTerms:{flags:e.kind==="agents-only"?1:0,minScore:K,tierScore:C,tierPips:N,reviewers:Z,minAge:ee},hookBlocks:a,lpRewardsBps:te,arbRecapture:t.arbRecapture!==!1,arbRecaptureOmitted:t.arbRecapture===void 0,deadline:m(t.deadline,64)}}async function Ot(i,t,a,e){return A(await p(i,y,T("launcherV1"),"predictToken",[t,a],e))}async function Ft(i,t,a,e,o){let n=a.gate;if(!n.walletAgent||!(e?n.healthyForScores:n.healthyIdentityOnly))throw new r("Hookr needs a healthy on-chain agent identity. Own an ERC-8004 identity or link its current agent wallet on the Hookr gate; Oak setup linking alone is insufficient.");let x=(c,u)=>p(i,n.identity,fe(["function balanceOf(address) view returns (uint256)","function ownerOf(uint256) view returns (address)","function getAgentWallet(uint256) view returns (address)"]),c,u,o),q=h(await x("balanceOf",[t])),s=!1;if(n.link.linked){let c=BigInt(n.link.agentId);s=A(await x("getAgentWallet",[c]))===t,!s&&q>0n&&(s=A(await x("ownerOf",[c]))===t)}if(!q&&!s)throw new r("Hookr on-chain identity ownership or gate link is missing or stale. Own an ERC-8004 identity or link its current agent wallet on the Hookr gate before launching.")}function to(i){let t=JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"hookr_blocks",arguments:{}}});return(async(a,e)=>{if(a!==Ve||e?.method!=="POST"||e.body!==t)throw new r("The local Hookr launch rebuild may only read the public Hook Block catalog.");return i(a,{...e,headers:{"content-type":"application/json","user-agent":"Mozilla/5.0"}})})}async function It(i,t,a){let e=$t(t);if(i.network==="testnet")throw new r("Hookr launch requires Robinhood Chain 4663.");let o=i.clientFor(4663),n=await Qe(o);if(e.deadline<=n.timestamp||e.deadline>n.timestamp+l.deadlineSeconds)throw new r("Set a fresh Hookr deadline within the next 300 seconds of chain time.");let x=[],q="";try{x=await lt(i)}catch(d){if(e.hookBlocks.length)throw d;q="Hookr gate hint unavailable; checking the shipped current gate against the chain."}let s,c=null;if(e.launchProfile==="agents-only"){let d=e.gateTerms.reviewers!==ge,L=x.find(I=>I.id==="agent-gate"&&I.openToNewPools)?.address??me,ue=d?[e.gateTerms.reviewers]:[],F;try{F=await ve(o,a,n.number,ue,L)}catch(I){if(L===me)throw I;F=await ve(o,a,n.number,ue,me),q=`Hookr gate hint ${L} refused by the chain; using the listed gate.`}await Ft(o,a,F,d,n.number),s=F,c=F.gate}else s=await ct(o,a,n.number);if(!s.rootOpenForWallet||s.newMarketsPaused||!s.launcherAdmitted)throw new r("Hookr new markets or the reviewed Launcher are closed. Retry only after registry admission is restored.");let u=await Ot(o,a,e.token,n.number);if(u===k||u===e.quote)throw new r("Hookr predicted token collides with its quote. Choose a fresh salt.");let S={currency0:BigInt(u)<BigInt(e.quote)?u:e.quote,currency1:BigInt(u)<BigInt(e.quote)?e.quote:u,fee:8388608,tickSpacing:l.tickSpacing,hooks:W},P=Re(S),$=S.currency0===u,B=$?e.amount0Max:e.amount1Max,f=$?e.amount1Max:e.amount0Max,K=$?e.debts.amount0:e.debts.amount1,C=$?e.debts.amount1:e.debts.amount0;if(B>e.token.supply)throw new r("Hookr new-token deposit cap exceeds its fixed supply.");let[N,Z,ee,te,R,oe,we,gt]=await Promise.all([o.getCode({address:u,blockNumber:n.number}),o.getTransactionCount({address:u,blockNumber:n.number}),p(o,y,T("launcherV1"),"memberKey",[u,e.quote,l.tickSpacing,W],n.number),p(o,W,T("rootV1"),"knownPool",[P],n.number),p(o,y,T("launcherV1"),"SKIP_TAKEN",[],n.number),p(o,He,T("registry"),"isQuote",[e.quote],n.number),p(o,He,T("registry"),"quoteIsBraked",[e.quote],n.number),p(o,Y,T("rulesV1"),"minProtocolShareBps",[],n.number)]),[wt,yt]=M(ee,2);if(e.token.salt===pe(R))throw new r("SKIP_TAKEN is unsupported. Choose an ordinary new-token salt.");if(N&&N!=="0x"||Z!==0||Q(te)||!Q(yt)||Re(G(wt))!==P)throw new r("Hookr token address or pool is already taken or its predicted key differs. Choose a fresh salt and rebuild.");if(!Q(oe)||Q(M(we,2)[0]))throw new r("The Hookr quote is not currently qualified or is braked. Choose an admitted quote.");let ye=c?G(c.admission):null,z=ye?m(G(ye.caps).maxLpFeePips,24):0n,be=BigInt(s.coreAdmission.caps.maxLpFeePips);if(c&&(BigInt(e.gateTerms.tierPips)>z||BigInt(l.baseLpFeePips)+z>be))throw new r("Hookr gate tier or total LP fee exceeds the live admission cap. Lower the tier or wait for compatible admission.");let U=A(await p(o,Y,T("rulesV1"),"protocolRecipient",[],n.number));await qe(o,n.number,[U]);let xe=fe(["function feeTerms(address,bool,bytes32) view returns (uint16,uint16,uint16)","function integrator(address) view returns (uint16,uint16,uint256)","function integratorMinFee(address) view returns (uint16,uint16,uint256)","function MAX_INTEGRATOR_BPS() view returns (uint16)"]),Oe=async d=>M(await p(o,U,xe,"feeTerms",[d,e.arbRecapture,P],n.number),3),[Fe,Ie]=await Promise.all([Oe(k),Oe(he)]),b=h(Ie[1],16);if(b!==0n){let d=async j=>M(await p(o,U,xe,j,[he],n.number),3),[L,ue,F]=await Promise.all([d("integrator"),d("integratorMinFee"),p(o,U,xe,"MAX_INTEGRATOR_BPS",[],n.number)]);if(h(L[0],16)!==b)throw new r("Hookr's listing for Oak and its fee terms for this pool disagree on Oak's rate. Request a fresh launch preview.");let I=h(F,16);if(b>I)throw new r(`Hookr lists Oak at ${b} bps, above its on-chain maximum integrator rate of ${I} bps. Oak will not launch on a listing outside Hookr's own limit.`);if([L[2],ue[2]].map(j=>h(j)).some(j=>j!==0n&&j<=e.deadline))throw new r("Oak's Hookr listing has a change that can take effect before this launch opens. Request a fresh launch preview after it settles.")}let E=b===0n?k:he,[bt,xt,Pt]=b===0n?Fe:Ie,Me=h(bt,16),ne=h(Pt,16);if(h(Fe[1],16)!==0n||h(xt,16)!==b||ne>10000n)throw new r("Hookr treasury minimum or integrator terms exceed the reviewed profile.");let Ce=h(gt,16),re=Me>Ce?Me:Ce;if(re<2000n||re>5000n)throw new r("Hookr protocol share is outside the reviewed 2000\u20135000 bps profile.");let Tt={guardEndBlock:0,maxFeePips:l.baseLpFeePips,snipeTaxPips:0,snipeFloorPips:0,snipeDecaySeconds:0,dynamicFeeSens:0,burnBps:0,lpBps:e.lpRewardsBps,potBps:0,royaltyBps:0,protocolShareBps:Number(re),potEveryNBuys:e.arbRecapture?0:at,maxBuyQuoteAmount:0n,potMinBuyQuote:0n,royaltyTo:k,integrator:E},g=await kt(i,{launchProfile:e.launchProfile,...c?{agentGate:t.agentGate}:{},hookBlocks:e.hookBlocks},Tt,{poolId:P,subject:u,quote:e.quote,tickSpacing:l.tickSpacing,sqrtPriceX96:e.sqrtPriceX96,rules:Y,launcher:y,wallet:a},n,{maxLpFeePips:be,maxQuoteTakePips:BigInt(s.coreAdmission.caps.maxQuoteTakePips),maxSubjectTakeBps:BigInt(s.coreAdmission.caps.maxSubjectTakeBps)},e.arbRecapture?0n:ne,x),{rules:H,blockTerms:Ne,bounds:ie}=g;if(H.guardEndBlock){let d=await rt(o,n);if(BigInt(H.guardEndBlock)<=d+4n||BigInt(H.guardEndBlock)>d+100000n)throw new r("Anti-Snipe guardEndBlock must be more than four and at most 100000 parent blocks ahead.")}let D=ie.maxLpFeePips+z,ae=ie.maxQuoteTakePips;if(D>be||D>600000n||c&&(ae>BigInt(s.coreAdmission.caps.maxQuoteTakePips)||ie.maxSubjectTakeBps>BigInt(s.coreAdmission.caps.maxSubjectTakeBps)))throw new r("Hookr selected blocks exceed the live core fee caps. Lower their rates.");let X=d=>`${J(BigInt(d),4)}%`,Ue=dt(H,e.arbRecapture?0n:ne,U,l.baseLpFeePips),qt=Ue?` ${Ue}`:"",Ee=ht(Ne,U,E===k?void 0:b).join(" "),se=`${J(b,2)}%`,St=E===k?"":` Oak receives ${se} of Hookr's cut on this pool, paid to Oak's wallet ${E}: ${se} of everything Hookr is paid from this pool's fees${e.arbRecapture?`, and ${se} of Hookr's 15% arb recapture cut (${J(b*15n,4)}% of recaptured profit)`:""}. Oak read the ${se} rate on chain; it is frozen when the pool opens. That it comes out of Hookr's part, so traders and LPs pay the same, is Hookr's published rule, not read by Oak.`,ce={on:e.arbRecapture,traderBps:0,lpBps:e.arbRecapture?1e4:0,period:0,maxPrizeBps:0,potReleaseBps:0,minBuyQuote:0n,releaseBlocks:0},je=null;if(e.arbRecapture){let[d,L]=await Promise.all([p(o,Y,fe(["function recaptureDefaults() view returns ((bool on,uint16 traderBps,uint16 lpBps,uint32 period,uint16 maxPrizeBps,uint16 potReleaseBps,uint128 minBuyQuote,uint32 releaseBlocks) rc,uint16 potBps)"]),"recaptureDefaults",[],n.number),tt(o,n.number,{required:!0})]);if(ce.releaseBlocks=Number(h(G(M(d,2)[0]).releaseBlocks,32)),!ce.releaseBlocks)throw new r("Hookr recapture release schedule is unavailable. Use arbRecapture false.");if(L.partnerBps!=="2500")throw new r("Hookr recapture split differs from the disclosed 25% executor profile. Use arbRecapture false.");je=Be(L)}let _e={quote:e.quote,tickSpacing:l.tickSpacing,sqrtPriceX96:e.sqrtPriceX96,tickLower:e.tickLower,tickUpper:e.tickUpper,liquidity:e.liquidity,amount0Max:e.amount0Max,amount1Max:e.amount1Max,config:{subject:u,quote:e.quote,rules:Y,advisory:g.advisory?.address??c.address,liquidityOwner:y,baseLpFeePips:l.baseLpFeePips,caps:{maxLpFeePips:Number(D),maxQuoteTakePips:Number(ae),maxSubjectTakeBps:Number(ie.maxSubjectTakeBps)},rulesGasLimit:Number(s.coreAdmission.gasLimit),advisoryGasLimit:g.advisory?Number(g.advisory.gasLimit):Number(m(ye.gasLimit,32)),advisoryPhases:g.advisory?.phases??1,advisoryFailOpen:g.advisory?g.advisory.failOpen:!1,policyId:ge},rules:H,recapture:ce},O=BigInt(s.launchFee.amount);if(O>10000000000000000n)throw new r("Hookr launch fee exceeds the reviewed 0.01 ETH maximum.");let v=k;if(O&&(await qe(o,n.number,[s.launchFee.treasury]),v=A(await p(o,s.launchFee.treasury,fe(["function target() view returns (address)"]),"target",[],n.number)),v===k||v===y||v===a||v===Ye))throw new r("Hookr launch fee recipient is outside the reviewed payment profile.");let Pe=O+(e.quote===k?f:0n),Te=[],V=[];if(e.quote!==k){let d=h(await p(o,e.quote,Rt,"allowance",[a,y],n.number));d!==0n&&d!==f&&V.push(i.approval(e.quote,y,"0",4663)),V.push(i.approval(e.quote,y,f.toString(),4663)),Te.push({token:e.quote,amount:f})}Pe&&Te.push({token:Xe,amount:Pe,to:y});let Ge=`Launch public, permanent token ${JSON.stringify(e.token.name)} (${JSON.stringify(e.token.symbol)}), fixed supply ${J(e.token.supply,18)} (18 decimals). ${c?c.listed?"Create one agents-only pool (identity check on every buy).":`Create one pool behind a gate Oak has not read: that gate alone decides who may buy and what surcharge applies. Oak knows only its frozen caps: LP fee surcharge at most ${z} pips (${X(z)}), zero quote and subject take.`:g.summaryLines.join(" ")} Price currency1/currency0 = ${e.sqrtPriceX96*e.sqrtPriceX96}/${1n<<192n}; sqrtPriceX96 ${e.sqrtPriceX96}, ticks ${e.tickLower} to ${e.tickUpper}, spacing ${l.tickSpacing}. Deposit at most ${e.amount0Max} currency0 and ${e.amount1Max} currency1 base units; exact launch debts ${e.debts.amount0} and ${e.debts.amount1}. Currency0 ${S.currency0}; currency1 ${S.currency1}. Launch fee ${O} wei to ${v} (${J(O,18)} ETH). Unused quote funding (${f-C} base units) and retained token supply (${e.token.supply-K} base units) return to ${a} in this transaction. Family owner ${a}; token ${u}; pool ${P}. LP base fee ${l.baseLpFeePips} pips (${X(l.baseLpFeePips)}); total LP fee cap ${D} pips (${X(D)}), frozen at launch; ${c?`gate flags 1, scores ${e.gateTerms.minScore}/${e.gateTerms.tierScore}, tier surcharge ${e.gateTerms.tierPips} pips (${X(e.gateTerms.tierPips)}) below tier score, paid to in-range LPs; reviewer set ${e.gateTerms.reviewers}; gate takes zero quote and subject.`:""} LP Rewards ${H.lpBps} bps; configured burn ${H.burnBps} bps; quote-take cap ${ae} pips (${X(ae)}); protocol share ${re} bps.${qt}${St} ${c?`${q} Gate ${c.address}: ${c.listed?"listed":"new gate, Oak has not read its code; it can refuse trades at any time"}. Minimum link age ${e.gateTerms.minAge} seconds (creator family liquidity exempt).`:""} ${it(e.arbRecapture)}${e.arbRecapture?`; recapture pot releases over ${ce.releaseBlocks} blocks`:""}; deadline ${e.deadline}.${e.arbRecaptureOmitted?" Arb recapture is on because arbRecapture was left out; pass arbRecapture false to launch without it.":""} ${H.guardEndBlock?`Principal locked until parent block ${H.guardEndBlock}.`:"No lock."} ${Ee}`,Ke=Lt({abi:T("launcherV1"),functionName:"launchAdvised",args:[e.token,W,[_e],[g.advisory?g.advisory.data:et(Ze(c.address,c.schemaHash),e.gateTerms)],e.deadline]});ut(Ke),V.push(i.unsignedTx({to:y,data:Ke,value:Pe.toString(),chainId:4663,description:Ge}));let[ze,Bt,Ht]=await Promise.all([o.getCode({address:u}),o.getTransactionCount({address:u}),o.readContract({address:y,abi:Je,functionName:"launchFee"})]);if(ze&&ze!=="0x"||Bt!==0||h(M(Ht,5)[0])!==O)throw new r("Hookr collision state or launch fee changed. Request a fresh launch preview.");return await We(o,n),{txs:V,inputs:Te,summary:Ge,tokenAddress:u,poolId:P,feeTarget:v,feeTreasury:s.launchFee.treasury,terms:Be({request:t,blockNumber:n.number,blockHash:n.hash,owner:a,tokenAddress:u,poolId:P,poolKey:S,member:_e,launchProfile:g.kind,advisory:g.advisory,gateTerms:c?e.gateTerms:null,blockTerms:Ne,blockSummary:Ee,launchFee:O,feeTarget:v,feeTreasury:s.launchFee.treasury,hookrMinimumPips:ne,oakIntegrator:E===k?null:{address:E,rateBps:b},exactApprovals:V.slice(0,-1),refunds:{quote:f-C,retainedSupply:e.token.supply-K},gasEstimate:null,gasEstimateReason:"The local sender estimates the ordered exact calls after funding approvals and confirms the gas limit and maximum fee.",lane:je,pins:de})}}function Mt(i){if(!Array.isArray(i)||i.length<1||i.length>3)throw new r("Hookr launch requires only the locally reconstructed finite approvals and one launch transaction.");for(let t of i)_(t,["to","data","value","chainId","description"],["to","data","value","chainId","description"])}function oo(i,t){if(Mt(i),i.length!==t.length||i.some((a,e)=>a.to.toLowerCase()!==t[e].to.toLowerCase()||a.data.toLowerCase()!==t[e].data.toLowerCase()||a.value!==t[e].value||a.chainId!==4663))throw new r("Hookr launch differs from the locally reconstructed exact parameters, approvals and funding.")}function no(i){return[{name:vt,inputSchema:Ae,execute:async(t,a)=>{let e=await It(i,t,a);return{txs:e.txs,preview:await i.preview(e.txs,a),terms:e.terms,summary:e.summary}}}]}export{vt as a,y as b,Y as c,Ae as d,$t as e,to as f,It as g,Mt as h,oo as i,no as j};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as y,b as P,d as I,e as q,f as T,g as L}from"./
|
|
1
|
+
import{a as y,b as P,d as I,e as q,f as T,g as L}from"./PX2G2H6G.js";import{a as w}from"./66F5ZH34.js";import{c as k,g as D}from"./NWNYJ26T.js";import{b as f}from"./EWZFZUVF.js";import{a as c}from"./XSD5NL7J.js";import{encodeFunctionData as U,erc20Abi as $,getAddress as O,parseAbi as S,zeroAddress as g}from"viem";var _=O("0x8bceaa40b9acdfaedf85adf4ff01f5ad6517937f"),h=O("0x89e5db8b5aa49aa85ac63f691524311aeb649eba"),F=S(["function getPair(address,address) view returns (address)"]),N=S(["function token0() view returns (address)","function token1() view returns (address)","function getReserves() view returns (uint112,uint112,uint32)","function totalSupply() view returns (uint256)","function balanceOf(address) view returns (uint256)"]),E=S(["function factory() view returns (address)","function addLiquidity(address tokenA,address tokenB,uint256 amountADesired,uint256 amountBDesired,uint256 amountAMin,uint256 amountBMin,address to,uint256 deadline) returns (uint256,uint256,uint256)","function removeLiquidity(address tokenA,address tokenB,uint256 liquidity,uint256 amountAMin,uint256 amountBMin,address to,uint256 deadline) returns (uint256,uint256)","function getAmountsOut(uint256 amountIn,address[] path) view returns (uint256[] amounts)","function getAmountsIn(uint256 amountOut,address[] path) view returns (uint256[] amounts)"]);async function z(s,p,t,n){if(p===g||t===g||p===t)throw new c("Provide two different ERC-20 tokens; use WETH for native ETH.");let r=s.clientFor(f),i=await r.getBlockNumber(),a=await r.readContract({address:_,abi:F,functionName:"getPair",args:[p,t],blockNumber:i}),[e,A]=await Promise.all([q(s,p,i),q(s,t,i)]);if(a===g)return{pair:a,tokenA:e,tokenB:A,reserveA:0n,reserveB:0n,supply:0n,balance:0n,blockNumber:i};let[M,l,v,B]=await Promise.all([r.readContract({address:a,abi:N,functionName:"token0",blockNumber:i}),r.readContract({address:a,abi:N,functionName:"getReserves",blockNumber:i}),r.readContract({address:a,abi:N,functionName:"totalSupply",blockNumber:i}),r.readContract({address:a,abi:$,functionName:"balanceOf",args:[n],blockNumber:i})]),[b,o]=D(M,p)?l:[l[1],l[0]];return{pair:a,tokenA:e,tokenB:A,reserveA:b,reserveB:o,supply:v,balance:B,blockNumber:i}}var H={tokenA:{...k,description:"Address of the first ERC-20 token."},tokenB:{...k,description:"Address of the second ERC-20 token."},amountADesired:w('Desired amount of tokenA in base units; use tokenA decimals. Example: "1000000" = 1 tokenA at 6 decimals.'),amountBDesired:w('Desired amount of tokenB in base units; use tokenB decimals. Example: "1000000" = 1 tokenB at 6 decimals.'),liquidity:{description:'LP token amount in base units (18 decimals), or "all" for the wallet balance. Example: "1000000000000000000" = 1 LP token.',type:"string",pattern:"^(?:[0-9]+|all)$"},slippageBps:{description:"Slippage tolerance in basis points (50 = 0.5%).",type:"integer",minimum:0,maximum:9999},amountAMin:w('Minimum amount of tokenA in base units; use tokenA decimals. Example: "1000000" = 1 tokenA at 6 decimals.'),amountBMin:w('Minimum amount of tokenB in base units; use tokenB decimals. Example: "1000000" = 1 tokenB at 6 decimals.')};function J(s){let p=async(t,n,r)=>{L(n,t==="pool"?["tokenA","tokenB"]:["tokenA","tokenB","slippageBps","amountAMin","amountBMin",...t==="add"?["amountADesired","amountBDesired"]:["liquidity"]]);let i=P(n.tokenA),a=P(n.tokenB),e=await z(s,i,a,r);if(t==="pool")return{pair:e.pair,tokenA:e.tokenA,tokenB:e.tokenB,reserveA:e.reserveA.toString(),reserveB:e.reserveB.toString(),totalSupply:e.supply.toString(),balance:e.balance.toString(),blockNumber:e.blockNumber.toString(),initialized:e.pair!==g};let A=s.clientFor(f),M=I(n.slippageBps);if(!D(await A.readContract({address:h,abi:E,functionName:"factory"}),_))throw new c("Uniswap v2 router factory differs from its pinned deployment.");let l=(await A.getBlock()).timestamp+300n,v=[],B=(o,d,m)=>{let u=o===void 0?d*BigInt(1e4-M)/10000n:y(o,m,256,!0);if(u>d||d>0n&&u===0n)throw new c(`${m} must be positive and no more than the reserve-ratio estimate.`);return u},b;if(t==="add"){let o=y(n.amountADesired,"amountADesired"),d=y(n.amountBDesired,"amountBDesired");if(e.reserveA===0n!=(e.reserveB===0n))throw new c("Uniswap v2 pair reserves are inconsistent.");let m=o,u=d;if(e.reserveA>0n&&e.reserveB>0n){let R=o*e.reserveB/e.reserveA;R<=d?u=R:m=d*e.reserveA/e.reserveB}if(m===0n||u===0n)throw new c("Liquidity amounts round to zero at the pool reserve ratio.");let x=B(n.amountAMin,m,"amountAMin"),C=B(n.amountBMin,u,"amountBMin");v.push(s.approval(i,h,o.toString(),f),s.approval(a,h,d.toString(),f)),b=U({abi:E,functionName:"addLiquidity",args:[i,a,o,d,x,C,r,l]})}else{if(e.pair===g||e.supply===0n)throw new c("No Uniswap v2 liquidity exists for this pair.");let o=n.liquidity==="all"?e.balance:y(n.liquidity,"liquidity");if(o===0n||o>e.balance)throw new c("Removal exceeds the wallet LP token balance or is zero.");let[d,m]=await Promise.all([i,a].map(C=>A.readContract({address:C,abi:$,functionName:"balanceOf",args:[e.pair]}))),u=B(n.amountAMin,o*d/e.supply,"amountAMin"),x=B(n.amountBMin,o*m/e.supply,"amountBMin");v.push(s.approval(e.pair,h,o.toString(),f)),b=U({abi:E,functionName:"removeLiquidity",args:[i,a,o,u,x,r,l]})}return v.push(s.unsignedTx({to:h,data:b,value:"0",chainId:f,description:`${t} Uniswap v2 liquidity for ${i}/${a}; recipient ${r}; deadline ${l}.`})),T(s,v,r,`${t==="add"?"Add":"Remove"} v2 liquidity. Review exact approvals, token minimums and wallet recipient. The first deposit sets the price; v2 locks MINIMUM_LIQUIDITY permanently.`)};return{tools:["pool","add","remove"].map(t=>({name:`uniswap_v2_${t}`,inputSchema:{type:"object",additionalProperties:!1,required:["tokenA","tokenB",...t==="add"?["amountADesired","amountBDesired"]:t==="remove"?["liquidity"]:[]],properties:t==="pool"?{tokenA:{...k,description:"Address of the first ERC-20 token."},tokenB:{...k,description:"Address of the second ERC-20 token."}}:H},execute:(n,r)=>p(t,n,r)}))}}export{_ as a,h as b,F as c,N as d,E as e,z as f,J as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as c}from"./
|
|
1
|
+
import{a as c}from"./W3M4KAPX.js";import{o as d}from"./S65KXMZ7.js";import{h as r}from"./QA6Z2CYP.js";import{a as i}from"./CFPJDLTZ.js";import{getAddress as h}from"viem";var u=t=>BigInt(t.replace(".","")),C=t=>`${t/100n}.${(t%100n).toString().padStart(2,"0")}`;async function B(t,p,l,m){let e=await d(t,p,l,m),s=await c({clientFor:t.clientFor,oakTokenAddress:h(i.oak)},[e.net,...e.stakedBacking.assets,e.pendingChop,e.claimableChop]),a=s.slice(1,1+e.stakedBacking.assets.length),o=a.length>0&&a.every(n=>n.usdEstimate!==null),g=o?C(a.reduce((n,k)=>n+u(k.usdEstimate),0n)):null;return{...e,net:s[0],chopSwapNotice:r,stakedBacking:{...e.stakedBacking,assets:a},stakedLp:{...e.stakedLp,usdEstimate:g,estimateLabel:o?"estimate, not a quote":"price unavailable",...o?{estimateSource:"Chop LP reserves and caller-bound net log backing; locks and gas excluded"}:{estimateReason:e.stakedBacking.estimateReason??"A Chop LP reserve has no USD estimate."}},pendingChop:s.at(-2),claimableChop:s.at(-1)}}export{B as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as v,h as W,i as j,n as z}from"./
|
|
1
|
+
import{e as v,h as W,i as j,n as z}from"./4JU23O3Z.js";import{a as B,e as F,g as R}from"./PX2G2H6G.js";import{A as D,b as C,c as O,t as X}from"./2ZYFBBOE.js";import{a as H}from"./66F5ZH34.js";import{g as U}from"./NWNYJ26T.js";import{b as L}from"./EWZFZUVF.js";import{a as c}from"./XSD5NL7J.js";import{decodeEventLog as J,parseAbi as V,toEventSelector as Z,toHex as x}from"viem";var K=V(["function getPositionInfo(bytes32 poolId,address owner,int24 tickLower,int24 tickUpper,bytes32 salt) view returns (uint128 liquidity,uint256 feeGrowthInside0LastX128,uint256 feeGrowthInside1LastX128)","function getFeeGrowthInside(bytes32 poolId,int24 tickLower,int24 tickUpper) view returns (uint256,uint256)"]),Q=V(["function ownerOf(uint256) view returns (address)","function getPoolAndPositionInfo(uint256) view returns ((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks),uint256)"]),P=V(["function slot0() view returns (uint160,int24,uint16,uint16,uint16,uint8,bool)","function feeGrowthGlobal0X128() view returns (uint256)","function feeGrowthGlobal1X128() view returns (uint256)","function ticks(int24) view returns (uint128,int128,uint256,uint256,int56,uint160,uint32,bool)"]),$=(1n<<256n)-1n,ee=1n<<128n,A=(s,t)=>s-t&$;function G(s,t,r,n=0n){return A(s,t)*r/ee+n}function ue(s){return{tools:[{name:"uniswap_fees",inputSchema:{type:"object",additionalProperties:!1,required:["version","tokenId"],properties:{includeHistory:{type:"boolean",description:"V3 only: read the complete NFT collect/decrease event history for lifetime fees. This can require multiple RPC log windows."},version:{description:'Uniswap version: "v3" for concentrated liquidity or "v4" for PoolManager.',type:"string",enum:["v3","v4"]},tokenId:H('Identifier of the position NFT, as a decimal string. Example: "1".')}},async execute(t){if(R(t,["version","tokenId","includeHistory"]),t.includeHistory!==void 0&&typeof t.includeHistory!="boolean")throw new c("includeHistory must be a boolean.");if(t.includeHistory===!0&&t.version!=="v3")throw new c("V4 position lifetime fees need historical liquidity/fee-growth checkpoints; no verified history source is configured.");let r=B(t.tokenId,"tokenId"),n=s.clientFor(L),i=await n.getBlockNumber();if(t.version!=="v3"&&t.version!=="v4")throw new c("Provide version v3 or v4 for fee reads.");let _=await n.readContract({address:t.version==="v4"?C:v.positionManager,abi:Q,functionName:"ownerOf",args:[r],blockNumber:i}),b,m,a,d,u,w=0n,p=0n;if(t.version==="v4"){let[e,f]=await n.readContract({address:C,abi:Q,functionName:"getPoolAndPositionInfo",args:[r],blockNumber:i}),{tickLower:h,tickUpper:N}=D(f),S=X(e),[k,I]=await Promise.all([n.readContract({address:O,abi:K,functionName:"getPositionInfo",args:[S,C,h,N,x(r,{size:32})],blockNumber:i}),n.readContract({address:O,abi:K,functionName:"getFeeGrowthInside",args:[S,h,N],blockNumber:i})]);[b,m,a]=[e.currency0,e.currency1,k[0]],[d,u]=[G(I[0],k[1],a),G(I[1],k[2],a)]}else if(t.version==="v3"){let e=z(await n.readContract({address:v.positionManager,abi:W,functionName:"positions",args:[r],blockNumber:i})),f=await n.readContract({address:v.factory,abi:j,functionName:"getPool",args:[e.token0,e.token1,e.fee],blockNumber:i}),[h,N,S,k,I]=await Promise.all([n.readContract({address:f,abi:P,functionName:"slot0",blockNumber:i}),n.readContract({address:f,abi:P,functionName:"feeGrowthGlobal0X128",blockNumber:i}),n.readContract({address:f,abi:P,functionName:"feeGrowthGlobal1X128",blockNumber:i}),n.readContract({address:f,abi:P,functionName:"ticks",args:[e.tickLower],blockNumber:i}),n.readContract({address:f,abi:P,functionName:"ticks",args:[e.tickUpper],blockNumber:i})]),M=(q,E,T)=>A(A(q,h[1]>=e.tickLower?E:A(q,E)),h[1]<e.tickUpper?T:A(q,T));[b,m,a]=[e.token0,e.token1,e.liquidity],[w,p]=[e.tokensOwed0,e.tokensOwed1],[d,u]=[G(M(N,k[2],I[2]),e.feeGrowthInside0LastX128,a,e.tokensOwed0),G(M(S,k[3],I[3]),e.feeGrowthInside1LastX128,a,e.tokensOwed1)]}else throw new c('Provide version "v3" or "v4" for fee reads.');let[o,g]=await Promise.all([F(s,b,i),F(s,m,i)]),y=[{token:o,amount:d.toString()},{token:g,amount:u.toString()}],l=t.includeHistory===!0?await te(s,r,i,d,u):void 0;return{version:t.version,tokenId:r.toString(),owner:_,blockNumber:i.toString(),liquidity:a.toString(),...t.version==="v4"?{uncollected:y}:{},collectable:y,feeGrowthAccrual:[{token:o,amount:(d-w).toString()},{token:g,amount:(u-p).toString()}],tokensOwed:[{token:o,amount:w.toString()},{token:g,amount:p.toString()}],...l?{lifetimeFees:[{token:o,amount:l[0].toString()},{token:g,amount:l[1].toString()}]}:{},summary:"One-block collectable estimate, excluding gas. V3 tokensOwed may include withdrawn principal; feeGrowthAccrual excludes those stored amounts. V4 hook accounting can change actual collections. V4 current liquidity times lifetime range growth is not lifetime position earnings."}}}]}}var Y=V(["event IncreaseLiquidity(uint256 indexed tokenId,uint128 liquidity,uint256 amount0,uint256 amount1)","event DecreaseLiquidity(uint256 indexed tokenId,uint128 liquidity,uint256 amount0,uint256 amount1)","event Collect(uint256 indexed tokenId,address recipient,uint256 amount0,uint256 amount1)"]);async function te(s,t,r,n,i){let _=s.clientFor(L),b=Y.map(o=>Z(o)),m=0n,a=0n,d=0n,u=0n,w=0;for(let o=0n;o<=r;o+=10000000n){let g=o+9999999n<r?o+9999999n:r,y=await _.request({method:"eth_getLogs",params:[{address:v.positionManager,topics:[b,x(t,{size:32})],fromBlock:x(o),toBlock:x(g)}]});if(!Array.isArray(y))throw new c("V3 lifetime fee history is unavailable; do not treat missing history as zero earnings.");for(let l of y){if(!U(l.address,v.positionManager))throw new c("Unexpected contract in v3 lifetime fee history.");let e=J({abi:Y,data:l.data,topics:l.topics});if(e.args.tokenId!==t)throw new c("Unexpected NFT in v3 fee history.");e.eventName==="Collect"?(m+=e.args.amount0,a+=e.args.amount1):e.eventName==="DecreaseLiquidity"?(d+=e.args.amount0,u+=e.args.amount1):w++}}if(w===0)throw new c("V3 mint/increase history is missing for this existing NFT; lifetime earnings are unknown.");let p=[m+n-d,a+i-u];if(p.some(o=>o<0n))throw new c("V3 fee history is incomplete or inconsistent; lifetime earnings are unknown.");return p}export{K as a,A as b,G as c,ue as d};
|