@oracle-agent/oracle 0.35.4 → 0.35.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
  3. package/dist/bin/desk-server.mjs +25 -23
  4. package/dist/bin/oracle-data-mcp.mjs +13 -11
  5. package/dist/bin/oracle-gateway.mjs +35 -35
  6. package/dist/bin/oracle-mev-arb-shadow.mjs +7 -5
  7. package/dist/bin/oracle-mev-shadow.mjs +7 -5
  8. package/dist/bin/oracle-public-server.mjs +6 -4
  9. package/dist/bin/oracle-route.mjs +22 -20
  10. package/dist/bin/oracle-scan.mjs +14 -12
  11. package/dist/bin/oracle-telegram-mcp.mjs +10 -10
  12. package/dist/bin/oracle.mjs +7 -5
  13. package/dist/cli/commands/chat.mjs +166 -164
  14. package/dist/cli/commands/doctor.mjs +3 -3
  15. package/dist/cli/commands/eval.mjs +113 -113
  16. package/dist/cli/commands/farm.mjs +14 -14
  17. package/dist/cli/commands/follow.mjs +16 -14
  18. package/dist/cli/commands/model.mjs +170 -168
  19. package/dist/cli/commands/project.mjs +17 -0
  20. package/dist/cli/commands/resolve.mjs +8 -6
  21. package/dist/cli/commands/shadow.mjs +21 -0
  22. package/dist/cli/commands/signer.mjs +10 -10
  23. package/dist/cli/commands/snipe.mjs +10 -8
  24. package/dist/cli/commands/strategy.mjs +5 -5
  25. package/dist/cli/commands/swap.mjs +27 -25
  26. package/dist/cli/commands/telegram.mjs +10 -10
  27. package/dist/cli/commands/venues.mjs +2 -2
  28. package/dist/data/desk-data.mjs +23 -21
  29. package/dist/data/names.mjs +4 -2
  30. package/dist/data/providers/farming.mjs +2 -2
  31. package/dist/index.mjs +37 -35
  32. package/dist/local-signer/index.mjs +3 -3
  33. package/dist/local-signer/runtime.mjs +9 -9
  34. package/dist/nft/universal-mint-router.mjs +5 -3
  35. package/dist/router/index.mjs +4 -2
  36. package/dist/router/prepare-bridge.mjs +2 -2
  37. package/dist/scanner/index.mjs +5 -3
  38. package/dist/strategy/index.mjs +3 -3
  39. package/package.json +1 -1
  40. package/public/oracle-splash/index.html +2 -2
@@ -1,18 +1,20 @@
1
1
  #!/usr/bin/env node
2
- import{createHash as Qe}from"node:crypto";import B from"node:net";import je from"node:dns";var We=new Set(["localhost","metadata.google.internal","metadata.goog"]);function z(t){let e=String(t).toLowerCase().split("%")[0];if((e.match(/::/g)||[]).length>1)return null;let n=c=>{if(!c)return[];let i=c.split(":"),p=i.at(-1);if(p?.includes(".")){let h=p.split(".").map(Number);if(h.length!==4||h.some(f=>!Number.isInteger(f)||f<0||f>255))return null;i.splice(i.length-1,1,(h[0]<<8|h[1]).toString(16),(h[2]<<8|h[3]).toString(16))}return i.some(h=>!/^[0-9a-f]{1,4}$/.test(h))?null:i.map(h=>Number.parseInt(h,16))},[r,s]=e.split("::"),o=n(r),a=n(s);if(!o||!a)return null;let u=e.includes("::"),l=8-o.length-a.length;if(!u&&l!==0||u&&l<1)return null;let d=[...o,...Array(Math.max(0,l)).fill(0),...a];return d.length!==8?null:Uint8Array.from(d.flatMap(c=>[c>>8,c&255]))}function J(t,e,n){let r=Math.floor(n/8),s=n%8;for(let a=0;a<r;a+=1)if(t[a]!==e[a])return!1;if(!s)return!0;let o=255<<8-s;return(t[r]&o)===(e[r]&o)}function Z(t){if(B.isIPv4(t)){let e=t.split(".").map(Number);return!(e[0]===0||e[0]===10||e[0]===127||e[0]>=224||e[0]===100&&e[1]>=64&&e[1]<=127||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&(e[1]===0||e[1]===2||e[1]===168)||e[0]===192&&e[1]===88&&e[2]===99||e[0]===198&&(e[1]===18||e[1]===19||e[1]===51)||e[0]===203&&e[1]===0&&e[2]===113)}if(B.isIPv6(t)){let e=z(t);if(!e)return!1;let n=z("::ffff:0:0");return J(e,n,96)?Z([...e.slice(12)].join(".")):J(e,z("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([s,o])=>J(e,z(s),o)):!1}return!1}function Ke(t){let e;try{e=new URL(String(t))}catch{return{ok:!1,error:`not a valid URL: ${String(t).slice(0,120)}`}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{ok:!1,error:`refused protocol ${e.protocol} (only http/https)`};let n=e.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(We.has(n)||n.endsWith(".localhost")||n.endsWith(".internal"))return{ok:!1,error:`refused internal host ${n}`};let r=B.isIP(n);return r!==0&&!Z(n)?{ok:!1,error:`refused private address ${n}`}:{ok:!0,url:e,host:n,isLiteralIp:r!==0}}async function ee(t,{lookupFn:e=je.promises.lookup}={}){let n=Ke(t);if(!n.ok)return n;if(n.isLiteralIp)return{ok:!0,url:n.url,addresses:[{address:n.host,family:B.isIPv6(n.host)?6:4}]};let r;try{r=await e(n.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${n.host} did not resolve`}}return!Array.isArray(r)||r.length===0||r.some(s=>!Z(s.address))?{ok:!1,error:`refused: ${n.host} resolves to a non-public address`}:{ok:!0,url:n.url,addresses:r}}async function te({requireUndici:t=!1,importUndici:e=()=>import("undici")}={}){let n,r;try{let i=await e();n=i.Agent,r=i.fetch}catch(i){if(t)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${i?.message||i}`);return null}if(typeof n!="function"||typeof r!="function"){if(t)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let s=i=>String(i).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),o=new Map,a=i=>(Array.isArray(i)?i:[i]).map(p=>typeof p=="string"?{address:p}:p).filter(p=>p&&p.address).map(p=>({address:p.address,family:p.family||(B.isIPv6(p.address)?6:4)})),u=(i,p,h)=>{o.set(s(i),a(typeof p=="string"?[{address:p,family:h}]:p))},l=i=>{let p=s(i);if(B.isIP(p))return[{address:p,family:B.isIPv6(p)?6:4}];let h=o.get(p);if(!h||!h.length)throw new Error(`refused: unpinned host ${i} during pinned fetch`);return h},d=new n({connect:{lookup(i,p,h){let f;try{f=l(i)}catch(v){return h(v)}return p?.all?h(null,f):h(null,f[0].address,f[0].family)}}}),c=ze((i,p={})=>r(i,{...p,dispatcher:d}),u);return{dispatcher:d,fetch:c,pin:u,resolve:l,async close(){try{await d.destroy()}catch{}}}}var ne=Symbol.for("oracle.egressGuard.pinCapableFetch");function ze(t,e){if(typeof t!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof e!="function")throw new Error("markPinCapableFetch: pin must be a function");return t[ne]=Object.freeze({pin:e}),t}function re(t){return typeof t=="function"&&typeof t[ne]?.pin=="function"}function he(t,e,n){if(!re(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[ne].pin(e,n)}var Ge=new Set([408,425,429,500,502,503,504]),fe=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Ye=2,me=4e3,ge=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],Xe=new Set([301,302,303,307,308]),be=3,Je=64*1024;function Ze(t){let e=String(t||"").toLowerCase();return ge.includes(e)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(e)}function et(t){let e={};for(let[n,r]of Object.entries(t||{}))Ze(n)||(e[n]=r);return e}function tt(t,e){if(!t)throw new Error(`HTTP redirect from ${e} missing Location`);let n=new URL(String(t),String(e));if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`HTTP redirect from ${e} used unsupported protocol ${n.protocol}`);return n.toString()}function nt(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var oe=new Map;function rt(t,e,n,r={}){let s={};for(let[c,i]of Object.entries(n||{}))s[c.toLowerCase()]=i;let o=Object.keys(s).filter(c=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(c)),u=[...new Set([...ge,...o])].sort().map(c=>`${c}=${s[c]??""}`).join(`
3
- `),l=Qe("sha256").update(u).digest("hex").slice(0,32),d=`${r.untrustedUrl?"untrusted":"trusted"}:${r.maxResponseBytes??"unbounded"}`;return`${t} ${e} ${d} ${l}`}function ot(t,e){let n=Number(e);return Number.isFinite(n)&&n>0?Math.min(n*1e3,me):Math.min(250*2**t,me)+Math.floor(Math.random()*100)}var st=t=>new Promise(e=>setTimeout(e,t));function V(t,e={}){let n=new Error(t);return n.retryable=!1,Object.assign(n,e),n}function se(t,e,n){return V(`HTTP response from ${t} exceeded maxResponseBytes ${n} (${e})`,{oversize:!0})}function H(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function at(t){return t?t.byteLength??t.length??0:0}async function ve(t,e,{url:n,truncate:r=!1,onOversize:s}={}){if(e==null)return await t.text();let o=Number(t.headers?.get?.("content-length"));if(Number.isFinite(o)&&o>e&&(H(t),!r))throw se(n,`content-length ${o}`,e);let a=t.body?.getReader?.();if(!a){let i=await t.text(),p=Buffer.byteLength(i,"utf8");if(p>e){if(!r)throw se(n,`body ${p} bytes`,e);return Buffer.from(i,"utf8").subarray(0,e).toString("utf8")}return i}let u=[],l=0,d=!1;try{for(;;){let{value:i,done:p}=await a.read();if(p)break;if(i&&(u.push(Buffer.from(i)),l+=at(i),l>e)){d=!0;break}}}finally{if(d)try{await a.cancel()}catch{}try{a.releaseLock?.()}catch{}}if(d&&(typeof s=="function"&&s(),!r))throw se(n,`streamed ${l} bytes`,e);let c=Buffer.concat(u);return(d?c.subarray(0,e):c).toString("utf8")}function ye(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function it(t,{fetchImpl:e,method:n,headers:r,body:s,timeoutMs:o,lookupFn:a,realFetch:u,untrustedUrl:l=!1,maxResponseBytes:d=null,importUndici:c,validateResponse:i,signal:p}){let h=new AbortController,f=setTimeout(()=>h.abort(),o),v=p?typeof AbortSignal.any=="function"?AbortSignal.any([p,h.signal]):p:h.signal,b=null,T=e,I=a?{lookupFn:a}:{};if(l&&!u&&!re(T))throw V(`HTTP refused ${t}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let q=async(S,{status:E=null}={})=>{let w=await ee(S,I);if(!w.ok)throw V(E==null?`HTTP refused ${S}: ${w.error}`:`HTTP redirect to ${S} ${w.error}`,E==null?{}:{status:E});let g=new URL(S).hostname;if(u){if(b&&(await b.close(),b=null),!b)try{b=await te({requireUndici:!0,...c?{importUndici:c}:{}})}catch(x){throw V(E==null?`HTTP refused ${S}: ${x?.message||x}`:`HTTP redirect to ${S} refused: ${x?.message||x}`,E==null?{}:{status:E})}b.pin(g,w.addresses),T=b.fetch}else he(T,g,w.addresses);return w};try{let S=String(t),E={...r||{}};l&&await q(S);for(let w=0;w<=be;w+=1){let g=await T(S,{method:n,headers:E,body:s,signal:v,redirect:"manual"});if(Xe.has(g.status)){if(n!=="GET"&&n!=="HEAD"){let U=await ve(g,d??Je,{url:S,truncate:!0}),$=new Error(`HTTP ${g.status} ${n} ${S} redirected non-idempotent request`);throw $.status=g.status,$.body=ye(U)??U.slice(0,300),$}if(w===be)throw H(g),new Error(`HTTP redirect loop for ${t}`);let A=g.headers?.get?.("location"),N;try{N=tt(A,S)}catch(U){throw H(g),U}let D=!nt(N,S);if(H(g),D&&(E=et(E)),l)await q(N,{status:g.status});else if(D){let U=await ee(N,I);if(!U.ok){let $=new Error(`HTTP redirect from ${S} ${U.error}`);throw $.status=g.status,$.retryable=!1,$}u&&U.addresses?.length&&(b||(b=await te(c?{importUndici:c}:{})),b&&(b.pin(new URL(N).hostname,U.addresses),T=b.fetch))}S=N;continue}if(typeof i=="function")try{await i(g,{url:S})}catch(A){throw H(g),V(A?.message||String(A))}let x=await ve(g,d,{url:S,onOversize:()=>h.abort()}),k=ye(x);if(!g.ok){let A=new Error(`HTTP ${g.status} ${n} ${S}`);throw A.status=g.status,A.retryAfter=g.headers?.get?.("retry-after")??null,A.body=k??x.slice(0,300),A}return k??x}throw new Error(`HTTP redirect loop for ${t}`)}finally{clearTimeout(f),b&&await b.close()}}async function Q(t,e={}){let n=e.fetchImpl||globalThis.fetch;if(typeof n!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let r=e.timeoutMs??12e3,s=(e.method||"GET").toUpperCase(),o={Accept:"application/json",...e.headers||{}},a=e.body;a!=null&&typeof a!="string"&&(o["Content-Type"]=o["Content-Type"]||"application/json",a=JSON.stringify(a));let u=Number.isInteger(e.retries)?Math.max(e.retries,0):Ye,l=e.lookupFn,d=!e.fetchImpl,c=e.untrustedUrl===!0,i=e.importUndici,p=e.validateResponse,h=e.signal,f=Number(e.maxResponseBytes),v=Number.isFinite(f)&&f>0?Math.floor(f):null,b=async()=>{let E;for(let w=0;w<=u;w++){h?.throwIfAborted?.();try{return await it(t,{fetchImpl:n,method:s,headers:o,body:a,timeoutMs:r,lookupFn:l,realFetch:d,untrustedUrl:c,maxResponseBytes:v,importUndici:i,validateResponse:p,signal:h})}catch(g){E=g;let x=g?.status,k=g?.name==="AbortError"||g?.name==="TimeoutError"||h?.aborted,A=new Set([408,425,429]),N=g?.retryable===!1?!1:x!=null?A.has(x)||Ge.has(x)&&fe.has(s):!k&&fe.has(s);if(w===u||!N)throw g;let D=ot(w,g?.retryAfter);h?await new Promise((U,$)=>{let Me=setTimeout(U,D);h.addEventListener("abort",()=>{clearTimeout(Me),$(h.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await st(D)}}throw E};if(!(e.dedupe!==!1&&!h&&s==="GET"&&a==null))return b();let I=rt(s,t,o,{untrustedUrl:c,maxResponseBytes:v}),q=oe.get(I);if(q)return q;let S=b().finally(()=>oe.delete(I));return oe.set(I,S),S}var we={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},ct=new Map(Object.values(we).map(t=>[t.chainId,t]));function Ee(t){return ct.get(Number(t))||null}function Se(t,e=process.env){let n=Ee(t);if(!n)return null;for(let r of n.rpcEnv){let s=(e[r]||"").trim();if(s)return s}return null}import{Interface as ut,getAddress as lt}from"ethers";var Ce=new ut(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Ae(t,e){try{return lt(t).toLowerCase()}catch{throw new Error(`${e} must be a valid EVM address`)}}var dt={1:"https://ethereum.publicnode.com",137:"https://polygon-bor-rpc.publicnode.com",42161:"https://arbitrum-one-rpc.publicnode.com",8453:"https://base-rpc.publicnode.com",10:"https://optimism-rpc.publicnode.com",988:"https://rpc.stable.xyz",56:"https://bsc-rpc.publicnode.com",43114:"https://avalanche-c-chain-rpc.publicnode.com",999:"https://rpc.hyperliquid.xyz/evm",2741:"https://api.mainnet.abs.xyz",4663:"https://rpc.mainnet.chain.robinhood.com"};function pt(t,{rpcUrl:e,env:n=process.env}={}){if(e)return e;let r=Se(t,n);return r||dt[Number(t)]||null}var ht=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function ft(t){let e=String(t||""),n=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!ht.test(n))throw new Error(`evm-rpc: ${e} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return n}async function _(t,e,n=[],r={}){let s=String(e||"");ft(s);let o=pt(t,r);if(!o)throw new Error(`No RPC URL for chainId ${t} (set env from chain registry rpcEnv or pass rpcUrl)`);let u=await Q(o,{method:"POST",body:{jsonrpc:"2.0",id:1,method:e,params:n},fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal});if(u?.error){let l=new Error(u.error.message||JSON.stringify(u.error));throw l.code=u.error.code,l}return u.result}async function xe(t,e={}){let n=await _(t,"eth_blockNumber",[],e);return parseInt(n,16)}async function Ie(t,e,n={}){if(!e)throw new Error("rpcGetBalance requires address");let r=await _(t,"eth_getBalance",[e,"latest"],n);return{chainId:Number(t),address:e,balanceWei:BigInt(r).toString(),balanceHex:r}}async function ke(t={},e={}){let n=Number(t.chainId??e.chainId??1),r=Ae(t.token||t.tokenAddress,"token"),s=Ae(t.account||t.owner||t.address,"account"),o=Ce.encodeFunctionData("balanceOf",[s]),a=await _(n,"eth_call",[{to:r,data:o},t.blockTag||"latest"],e),u=Ce.decodeFunctionResult("balanceOf",a),l=BigInt(u[0]);return{chainId:n,token:r,account:s,balance:l.toString(),balanceHex:`0x${l.toString(16)}`,blockTag:t.blockTag||"latest"}}var mt=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"]);function Ne(t,e){let n=String(t||"").toLowerCase(),r=String(e?.quote||e?.quoteToken?.address||"").toLowerCase(),s=String(e?.base||e?.baseToken?.address||"").toLowerCase();return r===n?{address:e.base||e.baseToken?.address,symbol:e.baseToken?.symbol}:s===n?{address:e.quote||e.quoteToken?.address,symbol:e.quoteToken?.symbol}:{address:e.quote||e.quoteToken?.address,symbol:e.quoteToken?.symbol}}function ae(t,e=[],{stables:n=[],wrappedNative:r=null}={}){let s=String(t||"").toLowerCase(),o=new Set((n||[]).map(l=>String(l).toLowerCase())),a=String(r||"").toLowerCase(),u=(e||[]).map((l,d)=>{let c=Ne(s,l),i=String(c.address||"").toLowerCase(),p=String(c.symbol||"").toLowerCase(),h=Number(l.liquidityUsd??l.liquidity?.usd),f=Number.isFinite(h)?h:0,v=String(l.dex||l.dexId||"").toLowerCase(),b=0;return o.has(i)||mt.has(p)?b=300:a&&i===a&&(b=100),v.includes("v4")?b+=20:v.includes("v3")?b+=10:(v.includes("v2")||v.includes("raydium")||v.includes("orca")||v.includes("meteora"))&&(b+=8),{pool:l,score:b*1e12+f,index:d,otherAddr:i,liquidityUsd:f}});return u.sort((l,d)=>d.score-l.score||l.index-d.index),u.map(l=>l.pool)}function Te(t,e=[]){let n=Array.isArray(e)?e:[];return n.length&&Ne(t,n[0]).address||null}var bt="https://api.dexscreener.com",jt=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function vt(t={}){return(t.baseUrl||process.env.DEXSCREENER_API_URL||bt).replace(/\/$/,"")}async function Le(t,e={}){if(!t)throw new Error("tokenAddress required");return Q(`${vt(e)}/latest/dex/tokens/${t}`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var M=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),y=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),m=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),yt=/^0x[0-9a-fA-F]{40}$/;function gt(t={}){let e=[],n=[];if(!t||typeof t!="object")return{ok:!1,errors:["definition must be an object"],warnings:n};if((!Number.isInteger(t.chainId)||t.chainId<=0)&&e.push("chainId must be a positive integer"),(typeof t.key!="string"||!/^[a-z][a-z0-9-]*$/.test(t.key||""))&&e.push('key must be a lowercase slug (e.g. "base")'),(typeof t.name!="string"||!t.name.trim())&&e.push("name is required"),!Array.isArray(t.rpcEnv)||t.rpcEnv.length===0)e.push("rpcEnv must list at least one environment variable name");else for(let s of t.rpcEnv)(typeof s!="string"||!/^[A-Z][A-Z0-9_]*$/.test(s))&&e.push(`rpcEnv entry "${s}" should be an UPPER_SNAKE env var name`);if(t.nativeCurrency){let s=t.nativeCurrency;(typeof s.symbol!="string"||!s.symbol)&&e.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(s.decimals)||e.push("nativeCurrency.decimals must be an integer")}for(let[s,o]of(t.venues||[]).entries()){let a=`venues[${s}]`;if(!o||typeof o!="object"){e.push(`${a} must be an object`);continue}yt.test(o.address||"")||e.push(`${a}.address is not a valid 20-byte address`),/^0x0{40}$/.test(o.address||"")&&e.push(`${a}.address is the zero address -- placeholder left in place?`),o.kind||e.push(`${a}.kind is required (router|quoter|factory|...)`),o.verified?(o.verified.method||e.push(`${a}.verified.method is required`),o.verified.source||e.push(`${a}.verified.source is required`),o.verified.date||n.push(`${a}.verified.date missing -- add one so staleness is visible`)):e.push(`${a} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let r=t.capabilities||{};for(let s of Object.keys(r))M.includes(s)?typeof r[s]!="function"&&e.push(`capability "${s}" must be a function`):e.push(`unknown capability "${s}"`);return Object.keys(r).length===0&&n.push("scanner implements no capabilities -- it can only be registered, not used"),r.prepareUnsignedTx&&!r.quote&&n.push("prepareUnsignedTx without quote: no priced expectation to validate the built tx against"),r.prepareUnsignedTx&&!r.sellSimulation&&n.push("prepareUnsignedTx without sellSimulation: cannot prove an asset is exitable before buying"),{ok:e.length===0,errors:e,warnings:n}}function wt(t){let{ok:e,errors:n,warnings:r}=gt(t);if(!e)throw new Error(`invalid scanner for ${t?.key??"<unknown>"}:
4
- - ${n.join(`
5
- - `)}`);let s=t.capabilities||{},o=M.filter(u=>typeof s[u]=="function"),a={key:t.key,chainId:t.chainId,name:t.name,rpcEnv:[...t.rpcEnv],nativeCurrency:t.nativeCurrency?{...t.nativeCurrency}:null,wrappedNative:t.wrappedNative||null,explorer:t.explorer||null,venues:(t.venues||[]).map(u=>({...u})),warnings:r,capabilities(){return{chainId:t.chainId,key:t.key,supported:[...o],unsupported:M.filter(u=>!o.includes(u))}},supports(u){return o.includes(u)}};for(let u of M)o.includes(u)?a[u]=async(...l)=>s[u](...l,{scanner:a}):a[u]=async()=>{throw new Error(`${t.key} (chain ${t.chainId}) does not implement "${u}". Supported: ${o.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(a)}var j=new Map;function qe(t){let e=wt(t);return j.set(e.chainId,e),e}function ie(t){return j.get(Number(t))||null}function G(){return[...j.values()]}function Ue(){let t={};for(let e of j.values())t[e.chainId]={key:e.key,name:e.name,...e.capabilities(),venueCount:e.venues.length,failClosed:e.venues.length===0};return{generatedAt:new Date().toISOString(),chainCount:j.size,capabilities:[...M],chains:t}}var ue={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},L=t=>BigInt(t).toString(16).padStart(64,"0"),W=t=>t.slice(2).toLowerCase().padStart(64,"0");function Et(t,e){return`0x${ue.getAmountsOut}`+L(t)+L(64)+L(e.length)+e.map(W).join("")}function St(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length<128)return null;let n=Number(BigInt(`0x${e.slice(64,128)}`));if(!Number.isFinite(n)||n<1||n>16)return null;let r=[];for(let s=0;s<n;s++){let o=128+s*64;if(e.length<o+64)return null;r.push(BigInt(`0x${e.slice(o,o+64)}`))}return r}function ce(t,e="router"){return(t?.venues||[]).find(r=>r.kind===e)?.address??null}var le=100;function Ct(t,e){let n=Number(e);if(!Number.isFinite(n)||n<0)throw new Error("slippageBps must be a non-negative number");if(n>le)throw new Error(`slippageBps ${n} exceeds the ${le} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(n))/10000n}function _e(t){let{chainId:e,wrappedNative:n}=t;async function r(s,o,a,u){let l=await _(e,"eth_call",[{to:s,data:Et(o,a)},"latest"],u);return St(l?.result??l)}return{async quote({tokenIn:s,tokenOut:o,amountIn:a,path:u},l={}){let d=ce(l.scanner);if(!d)return{chainId:e,evidence:y.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let c=u||[s,o];if(c.some(p=>!/^0x[0-9a-fA-F]{40}$/.test(p||"")))throw new Error("quote requires valid 20-byte addresses");let i=await r(d,a,c,l);return i?{chainId:e,router:d,path:c,amountIn:String(a),amountOut:i[i.length-1].toString(),hops:c.length-1,evidence:y.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:e,router:d,path:c,evidence:y.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:s,amountIn:o,base:a},u={}){let l=ce(u.scanner),d=a||n;if(d&&String(s).toLowerCase()===String(d).toLowerCase())return{chainId:e,token:s,verdict:m.UNKNOWN,evidence:y.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!l||!d)return{chainId:e,token:s,verdict:m.UNKNOWN,evidence:y.UNAVAILABLE,reason:l?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let c=await r(l,o,[d,s],u);if(!c)return{chainId:e,token:s,verdict:m.FAIL,evidence:y.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let i=c[c.length-1];if(i===0n)return{chainId:e,token:s,verdict:m.FAIL,evidence:y.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let p=await r(l,i,[s,d],u);if(!p)return{chainId:e,token:s,verdict:m.FAIL,evidence:y.LIVE,leg:"sell",bought:i.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let h=p[p.length-1],f=Number(h*10000n/BigInt(o)),v=m.PASS,b="round trip completes with expected fee/impact loss";return f<5e3?(v=m.FAIL,b=`round trip returns only ${(f/100).toFixed(2)}% -- punitive tax or no real liquidity`):f<9e3&&(v=m.CAUTION,b=`round trip returns ${(f/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,token:s,base:d,router:l,verdict:v,reason:b,amountIn:String(o),bought:i.toString(),returned:h.toString(),retentionBps:f,evidence:y.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:s,tokenOut:o,amountIn:a,recipient:u,slippageBps:l=50,deadlineSeconds:d=900,path:c},i={}){let p=i.scanner,h=ce(p);if(!h)throw new Error(`chain ${e} has no verified router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!/^0x[0-9a-fA-F]{40}$/.test(u||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=c||[s,o],v=await this.quote({tokenIn:s,tokenOut:o,amountIn:a,path:f},i);if(v.evidence!==y.LIVE)throw new Error(`cannot prepare without a live quote (${v.evidence}: ${v.reason??"no reason given"})`);let b=Ct(v.amountOut,l);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let T=BigInt(Math.floor(Date.now()/1e3)+Number(d)),I=n&&f[0].toLowerCase()===n.toLowerCase()&&i.useNative,q=I?`0x${ue.swapExactETHForTokens}`+L(b)+L(128)+W(u)+L(T)+L(f.length)+f.map(W).join(""):`0x${ue.swapExactTokensForTokens}`+L(a)+L(b)+L(160)+W(u)+L(T)+L(f.length)+f.map(W).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:e,tx:{to:h,data:q,value:I?`0x${BigInt(a).toString(16)}`:"0x0"},guard:{quotedOut:v.amountOut,minOut:b.toString(),slippageBps:l,maxSlippageBps:le,deadline:T.toString()},requires:I?[]:[{step:"approve",token:f[0],spender:h,amount:String(a)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var At=[100,500,3e3,1e4],Re={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},P=t=>BigInt(t).toString(16).padStart(64,"0"),K=t=>t.slice(2).toLowerCase().padStart(64,"0"),$e=/^0x[0-9a-fA-F]{40}$/,pe=100;function xt(t,e){let n=Number(e);if(!Number.isFinite(n)||n<0)throw new Error("slippageBps must be a non-negative number");if(n>pe)throw new Error(`slippageBps ${n} exceeds the ${pe} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(n))/10000n}function de(t,e){return(t?.venues||[]).find(n=>n.kind===e)?.address??null}function Be(t){let{chainId:e,wrappedNative:n}=t;async function r({quoter:o,tokenIn:a,tokenOut:u,amountIn:l,fee:d},c){let i=`0x${Re.quoteExactInputSingle}`+K(a)+K(u)+P(l)+P(d)+P(0),p=await _(e,"eth_call",[{to:o,data:i},"latest"],c).catch(()=>null),h=p?.result??p;if(!h||h==="0x"||h.length<66)return null;let f=BigInt(`0x${h.slice(2,66)}`);return f>0n?f:null}async function s({quoter:o,tokenIn:a,tokenOut:u,amountIn:l},d){let c=[],i=null;for(let p of At){let h=await r({quoter:o,tokenIn:a,tokenOut:u,amountIn:l,fee:p},d);c.push({fee:p,amountOut:h?h.toString():null}),h&&(!i||h>i.amountOut)&&(i={fee:p,amountOut:h})}return{best:i,tried:c}}return{async quote({tokenIn:o,tokenOut:a,amountIn:u},l={}){let d=de(l.scanner,"quoter");if(!d)return{chainId:e,evidence:y.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let p of[o,a])if(!$e.test(p||""))throw new Error("quote requires valid 20-byte addresses");let{best:c,tried:i}=await s({quoter:d,tokenIn:o,tokenOut:a,amountIn:u},l);return c?{chainId:e,venue:"uniswap-v3",quoter:d,tokenIn:o,tokenOut:a,amountIn:String(u),amountOut:c.amountOut.toString(),fee:c.fee,useNative:!!n&&String(o).toLowerCase()===String(n).toLowerCase(),triedFeeTiers:i,evidence:y.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:e,quoter:d,tokenIn:o,tokenOut:a,triedFeeTiers:i,evidence:y.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:o,amountIn:a,base:u},l={}){let d=de(l.scanner,"quoter"),c=(t.stableQuoteAssets||[]).map(E=>String(E).toLowerCase()),i=null;!u&&typeof t.resolveQuoteAsset=="function"&&(i=await t.resolveQuoteAsset(o,l).catch(()=>null));let p=String(o).toLowerCase(),h=String(n||"").toLowerCase();if(h&&p===h)return{chainId:e,token:o,verdict:m.UNKNOWN,evidence:y.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};let f=u||i||(c[0]&&p!==c[0]?c[0]:null)||n;if(f&&p===String(f).toLowerCase())return{chainId:e,token:o,verdict:m.UNKNOWN,evidence:y.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!d||!f)return{chainId:e,token:o,verdict:m.UNKNOWN,evidence:y.UNAVAILABLE,reason:d?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let v=await s({quoter:d,tokenIn:f,tokenOut:o,amountIn:a},l);if(!v.best){let E=c.find(w=>w&&w!==String(f).toLowerCase()&&w!==String(o).toLowerCase());if(E){let w=await s({quoter:d,tokenIn:E,tokenOut:o,amountIn:a},l);if(w.best){let g=await s({quoter:d,tokenIn:o,tokenOut:E,amountIn:w.best.amountOut},l);if(g.best){let x=g.best.amountOut,k=Number(x*10000n/BigInt(a)),A=m.PASS,N="round trip vs dollar book completes with expected fee/impact loss";return k<5e3?(A=m.FAIL,N=`round trip vs dollar book returns only ${(k/100).toFixed(2)}% -- punitive tax or no real liquidity`):k<9e3&&(A=m.CAUTION,N=`round trip vs dollar book returns ${(k/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:E,quoteAsset:E,verdict:A,reason:N,amountIn:String(a),bought:w.best.amountOut.toString(),returned:x.toString(),retentionBps:k,buyFee:w.best.fee,sellFee:g.best.fee,evidence:y.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:e,token:o,verdict:m.FAIL,evidence:y.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let b=await s({quoter:d,tokenIn:o,tokenOut:f,amountIn:v.best.amountOut},l);if(!b.best){let E=c.find(w=>w&&w!==String(f).toLowerCase()&&w!==String(o).toLowerCase());if(E){let w=await s({quoter:d,tokenIn:E,tokenOut:o,amountIn:a},l),g=w.best?await s({quoter:d,tokenIn:o,tokenOut:E,amountIn:w.best.amountOut},l):{best:null};if(w.best&&g.best){let x=g.best.amountOut,k=Number(x*10000n/BigInt(a)),A=m.PASS,N="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return k<5e3?(A=m.FAIL,N=`dollar-book round trip returns only ${(k/100).toFixed(2)}%`):k<9e3&&(A=m.CAUTION,N=`dollar-book round trip returns ${(k/100).toFixed(2)}%`),{chainId:e,venue:"uniswap-v3",token:o,base:E,quoteAsset:E,verdict:A,reason:N,amountIn:String(a),bought:w.best.amountOut.toString(),returned:x.toString(),retentionBps:k,buyFee:w.best.fee,sellFee:g.best.fee,evidence:y.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:e,token:o,verdict:m.FAIL,evidence:y.LIVE,leg:"sell",bought:v.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let T=b.best.amountOut,I=Number(T*10000n/BigInt(a)),q=m.PASS,S="round trip completes with expected fee/impact loss";return I<5e3?(q=m.FAIL,S=`round trip returns only ${(I/100).toFixed(2)}% -- punitive tax or no real liquidity`):I<9e3&&(q=m.CAUTION,S=`round trip returns ${(I/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:f,verdict:q,reason:S,amountIn:String(a),bought:v.best.amountOut.toString(),returned:T.toString(),retentionBps:I,buyFee:v.best.fee,sellFee:b.best.fee,evidence:y.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:a,amountIn:u,recipient:l,slippageBps:d=50,fee:c},i={}){let p=de(i.scanner,"router");if(!p)throw new Error(`chain ${e} has no verified V3 router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!$e.test(l||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let h=await this.quote({tokenIn:o,tokenOut:a,amountIn:u},i);if(h.evidence!==y.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let f=c??h.fee,v=xt(h.amountOut,d);if(v<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=!!(i.useNative||h.useNative)&&n&&String(o).toLowerCase()===String(n).toLowerCase(),T=`0x${Re.exactInputSingle}`+K(o)+K(a)+P(f)+K(l)+P(u)+P(v)+P(0);return{unsigned:!0,signedBy:"user-wallet",chainId:e,venue:"uniswap-v3",tx:{to:p,data:T,value:b?String(u):"0x0"},guard:{quotedOut:h.amountOut,minOut:v.toString(),slippageBps:d,maxSlippageBps:pe,fee:f},requires:b?[]:[{step:"approve",token:o,spender:p,amount:String(u)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var Y={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function Pe(t){if(!t||t==="0x")return null;try{return BigInt(t)}catch{return null}}function Fe(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length>=128){let r=Number(BigInt(`0x${e.slice(64,128)}`));if(r>0&&r<=256&&e.length>=128+r*2){let s=e.slice(128,128+r*2),o=Buffer.from(s,"hex").toString("utf8").replace(/\0+$/,"");if(o)return o}}return Buffer.from(e.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function It(t){let{chainId:e}=t;async function n(r,s,o){return _(e,"eth_call",[{to:r,data:s},"latest"],o)}return{async blockNumber(r={}){let s=await xe(e,r);return{chainId:e,blockNumber:s?.blockNumber??s,evidence:y.LIVE}},async nativeBalance(r,s={}){let o=await Ie(e,r,s);return{chainId:e,address:r,wei:o?.wei??o?.balance??null,symbol:t.nativeCurrency?.symbol??null,decimals:t.nativeCurrency?.decimals??18,evidence:y.LIVE}},async tokenBalance({token:r,owner:s},o={}){let a=await ke({chainId:e,token:r,owner:s},o);return{chainId:e,token:r,owner:s,raw:a?.balance??a,evidence:y.LIVE}},async resolveToken(r,s={}){if(!/^0x[0-9a-fA-F]{40}$/.test(r||""))return{chainId:e,token:r,evidence:y.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[o,a,u,l]=await Promise.all([n(r,Y.decimals,s).catch(()=>null),n(r,Y.symbol,s).catch(()=>null),n(r,Y.name,s).catch(()=>null),n(r,Y.totalSupply,s).catch(()=>null)]),d=Pe(o?.result??o),c=d!==null||a?.result||u?.result;return{chainId:e,address:r,decimals:d===null?null:Number(d),symbol:Fe(a?.result??a),name:Fe(u?.result??u),totalSupply:(Pe(l?.result??l)??null)?.toString()??null,evidence:c?y.LIVE:y.UNKNOWN,warning:c?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(r,s={}){let o=t.dexscreenerSlug;if(!o)return{chainId:e,token:r,pools:[],evidence:y.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let a=await Le(r,s).catch(()=>null),l=(a?.pairs||a?.data?.pairs||[]).filter(c=>String(c.chainId).toLowerCase()===String(o).toLowerCase()).map(c=>({pair:c.pairAddress,dex:c.dexId,base:c.baseToken?.address,quote:c.quoteToken?.address,liquidityUsd:c.liquidity?.usd??null,priceUsd:c.priceUsd??null,volume24hUsd:c.volume?.h24??null,createdAt:c.pairCreatedAt??null})).sort((c,i)=>(i.liquidityUsd??0)-(c.liquidityUsd??0)),d=ae(r,l,{stables:t.stableQuoteAssets||[],wrappedNative:t.wrappedNative});return{chainId:e,token:r,pools:d,topPool:d[0]||null,quoteAsset:Te(r,d),evidence:d.length?y.LIVE:y.UNKNOWN}},async scanBlocks({fromBlock:r,toBlock:s,address:o,topics:a,chunkSize:u=2e3}={},l={}){if(!Number.isInteger(r)||!Number.isInteger(s))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(s<r)throw new Error("toBlock must be >= fromBlock");let d=[],c=[];for(let i=r;i<=s;i+=u){let p=Math.min(i+u-1,s);c.push([i,p])}for(let[i,p]of c){let h={fromBlock:`0x${i.toString(16)}`,toBlock:`0x${p.toString(16)}`};o&&(h.address=o),a&&(h.topics=a);let f=await _(e,"eth_getLogs",[h],l).catch(v=>({error:String(v?.message||v)}));if(f?.error)return{chainId:e,fromBlock:r,toBlock:s,logs:d,complete:!1,failedAt:[i,p],error:f.error,evidence:y.UNKNOWN};for(let v of f?.result??f??[])d.push(v)}return{chainId:e,fromBlock:r,toBlock:s,logs:d,complete:!0,chunks:c.length,evidence:y.LIVE}},async scoreRisk(r,s={}){let o=[],a=m.PASS,u=c=>{let i={[m.PASS]:0,[m.CAUTION]:1,[m.UNKNOWN]:2,[m.FAIL]:3};i[c]>i[a]&&(a=c)},l=await this.resolveToken(r,s);l.evidence!==y.LIVE?(o.push({check:"erc20-metadata",result:m.UNKNOWN,detail:l.warning}),u(m.UNKNOWN)):o.push({check:"erc20-metadata",result:m.PASS,detail:`${l.symbol} / ${l.decimals}d`});let d=await this.resolvePools(r,s);if(d.evidence===y.UNAVAILABLE)o.push({check:"liquidity",result:m.UNKNOWN,detail:d.reason}),u(m.UNKNOWN);else if(!d.pools.length)o.push({check:"liquidity",result:m.FAIL,detail:"no pool with liquidity found"}),u(m.FAIL);else{let c=d.pools[0],i=c.liquidityUsd??0;i<5e3?(o.push({check:"liquidity",result:m.CAUTION,detail:`top pool only $${i}`}),u(m.CAUTION)):o.push({check:"liquidity",result:m.PASS,detail:`$${i} on ${c.dex}`}),c.createdAt&&Date.now()-c.createdAt<24*3600*1e3&&(o.push({check:"age",result:m.CAUTION,detail:"pool under 24h old"}),u(m.CAUTION))}if(typeof this.sellSimulation=="function"){let c=await this.sellSimulation({token:r,amountIn:(10n**16n).toString()},s).catch(i=>({verdict:m.UNKNOWN,reason:String(i?.message||i)}));o.push({check:"sellability",result:c.verdict,detail:c.retentionBps!=null?`round trip returns ${(c.retentionBps/100).toFixed(2)}% -- ${c.reason}`:c.reason}),u(c.verdict)}else o.push({check:"sellability",result:m.UNKNOWN,detail:"no verified router on this chain, so a round-trip sell simulation cannot run. Treat as unproven -- a buy path is not an exit path."}),u(m.UNKNOWN);return{chainId:e,token:r,verdict:a,checks:o,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function Oe(t){let n={...It(t)},r=new Set((t.venues||[]).map(o=>o.kind));t.venueKind==="uniswap-v3"&&r.has("quoter")&&r.has("router")?Object.assign(n,Be({chainId:t.chainId,wrappedNative:t.wrappedNative,stableQuoteAssets:t.stableQuoteAssets||[],resolveQuoteAsset:async(o,a)=>(await n.resolvePools(o,a)).quoteAsset||null})):t.venueKind==="uniswap-v2"&&r.has("router")&&Object.assign(n,_e({chainId:t.chainId,wrappedNative:t.wrappedNative}));let s={};for(let[o,a]of Object.entries(n))s[o]=a.bind(n);return{key:t.key,chainId:t.chainId,name:t.name,rpcEnv:t.rpcEnv,nativeCurrency:t.nativeCurrency,explorer:t.explorer,venues:t.venues||[],capabilities:s}}var kt=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",stableQuoteAssets:["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48","0xdAC17F958D2ee523a2206206994597C13D831ec7"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85","0x94b008aA00579c1307B0EF2c499aD98a8ce58e58"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",stableQuoteAssets:["0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d","0x55d398326f99059fF775485246999027B3197955"],venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",stableQuoteAssets:["0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359","0xc2132D05D31c914a87C6611C10748AEb04B58e8F"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",stableQuoteAssets:["0x5fc5360d0400a0fd4f2af552add042d716f1d168"],venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",stableQuoteAssets:["0xaf88d065e77c8cC2239327C5EDb3A432268e5831","0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",stableQuoteAssets:["0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"],venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);function De(){return kt.map(t=>qe(Oe(t)))}De();var[Ve,...He]=process.argv.slice(2),X=He.includes("--json"),C=He.filter(t=>t!=="--json");function O(t){t||R("missing <chain>");let e=ie(Number(t));if(e)return e;let n=G().find(r=>r.key===String(t).toLowerCase());if(n)return n;R(`unknown chain "${t}". Known: ${G().map(r=>`${r.key}(${r.chainId})`).join(", ")}`)}function R(t){console.error(`error: ${t}`),process.exit(1)}function F(t){process.stdout.write(`${JSON.stringify(t,null,2)}
6
- `)}function Nt(t,e){let n=String(e?.message||e);return/rpc|fetch|ECONN|timeout|provider/i.test(n)?`${n}
2
+ import{createHash as me}from"node:crypto";import B from"node:net";import Ge from"node:dns";var Ye=new Set(["localhost","metadata.google.internal","metadata.goog"]);function Q(t){let e=String(t).toLowerCase().split("%")[0];if((e.match(/::/g)||[]).length>1)return null;let r=c=>{if(!c)return[];let i=c.split(":"),l=i.at(-1);if(l?.includes(".")){let h=l.split(".").map(Number);if(h.length!==4||h.some(f=>!Number.isInteger(f)||f<0||f>255))return null;i.splice(i.length-1,1,(h[0]<<8|h[1]).toString(16),(h[2]<<8|h[3]).toString(16))}return i.some(h=>!/^[0-9a-f]{1,4}$/.test(h))?null:i.map(h=>Number.parseInt(h,16))},[n,a]=e.split("::"),o=r(n),s=r(a);if(!o||!s)return null;let d=e.includes("::"),u=8-o.length-s.length;if(!d&&u!==0||d&&u<1)return null;let p=[...o,...Array(Math.max(0,u)).fill(0),...s];return p.length!==8?null:Uint8Array.from(p.flatMap(c=>[c>>8,c&255]))}function Z(t,e,r){let n=Math.floor(r/8),a=r%8;for(let s=0;s<n;s+=1)if(t[s]!==e[s])return!1;if(!a)return!0;let o=255<<8-a;return(t[n]&o)===(e[n]&o)}function ee(t){if(B.isIPv4(t)){let e=t.split(".").map(Number);return!(e[0]===0||e[0]===10||e[0]===127||e[0]>=224||e[0]===100&&e[1]>=64&&e[1]<=127||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&(e[1]===0||e[1]===2||e[1]===168)||e[0]===192&&e[1]===88&&e[2]===99||e[0]===198&&(e[1]===18||e[1]===19||e[1]===51)||e[0]===203&&e[1]===0&&e[2]===113)}if(B.isIPv6(t)){let e=Q(t);if(!e)return!1;let r=Q("::ffff:0:0");return Z(e,r,96)?ee([...e.slice(12)].join(".")):Z(e,Q("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([a,o])=>Z(e,Q(a),o)):!1}return!1}function Je(t){let e;try{e=new URL(String(t))}catch{return{ok:!1,error:`not a valid URL: ${String(t).slice(0,120)}`}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{ok:!1,error:`refused protocol ${e.protocol} (only http/https)`};let r=e.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(Ye.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=B.isIP(r);return n!==0&&!ee(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:e,host:r,isLiteralIp:n!==0}}async function te(t,{lookupFn:e=Ge.promises.lookup}={}){let r=Je(t);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:B.isIPv6(r.host)?6:4}]};let n;try{n=await e(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(a=>!ee(a.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function re({requireUndici:t=!1,importUndici:e=()=>import("undici")}={}){let r,n;try{let i=await e();r=i.Agent,n=i.fetch}catch(i){if(t)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${i?.message||i}`);return null}if(typeof r!="function"||typeof n!="function"){if(t)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let a=i=>String(i).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),o=new Map,s=i=>(Array.isArray(i)?i:[i]).map(l=>typeof l=="string"?{address:l}:l).filter(l=>l&&l.address).map(l=>({address:l.address,family:l.family||(B.isIPv6(l.address)?6:4)})),d=(i,l,h)=>{o.set(a(i),s(typeof l=="string"?[{address:l,family:h}]:l))},u=i=>{let l=a(i);if(B.isIP(l))return[{address:l,family:B.isIPv6(l)?6:4}];let h=o.get(l);if(!h||!h.length)throw new Error(`refused: unpinned host ${i} during pinned fetch`);return h},p=new r({connect:{lookup(i,l,h){let f;try{f=u(i)}catch(g){return h(g)}return l?.all?h(null,f):h(null,f[0].address,f[0].family)}}}),c=Xe((i,l={})=>n(i,{...l,dispatcher:p}),d);return{dispatcher:p,fetch:c,pin:d,resolve:u,async close(){try{await p.destroy()}catch{}}}}var ne=Symbol.for("oracle.egressGuard.pinCapableFetch");function Xe(t,e){if(typeof t!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof e!="function")throw new Error("markPinCapableFetch: pin must be a function");return t[ne]=Object.freeze({pin:e}),t}function oe(t){return typeof t=="function"&&typeof t[ne]?.pin=="function"}function fe(t,e,r){if(!oe(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[ne].pin(e,r)}var Ze=new Set([408,425,429,500,502,503,504]),be=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),et=2,ve=4e3,Ee=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],tt=new Set([301,302,303,307,308]),ge=3,rt=64*1024;function nt(t){let e=String(t||"").toLowerCase();return Ee.includes(e)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(e)}function ot(t){let e={};for(let[r,n]of Object.entries(t||{}))nt(r)||(e[r]=n);return e}function at(t,e){if(!t)throw new Error(`HTTP redirect from ${e} missing Location`);let r=new URL(String(t),String(e));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${e} used unsupported protocol ${r.protocol}`);return r.toString()}function st(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var ae=new Map,it=/(?:^|_)(send|submit|broadcast|sign|requestAirdrop)(?=[A-Z_]|$)/i,ct=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function ye(t){let e=String(t?.method||"");return e?!it.test(e):!1}function ut(t,e){if(t==="GET"&&e==null)return!0;if(t!=="POST"||e==null)return!1;let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{return!1}return Array.isArray(r)?r.length>0&&r.every(ye):!r||typeof r!="object"?!1:r.jsonrpc&&r.method?ye(r):typeof r.type=="string"&&ct.has(r.type)&&r.action==null&&r.signature==null&&r.nonce==null}function lt(t,e,r,n={},a=null){let o={};for(let[l,h]of Object.entries(r||{}))o[l.toLowerCase()]=h;let s=Object.keys(o).filter(l=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(l)),u=[...new Set([...Ee,...s])].sort().map(l=>`${l}=${o[l]??""}`).join(`
3
+ `),p=me("sha256").update(u).digest("hex").slice(0,32),c=`${n.untrustedUrl?"untrusted":"trusted"}:${n.maxResponseBytes??"unbounded"}`,i=a==null?"-":me("sha256").update(String(a)).digest("hex").slice(0,32);return`${t} ${e} ${c} ${p} ${i}`}function dt(t,e){let r=Number(e);return Number.isFinite(r)&&r>0?Math.min(r*1e3,ve):Math.min(250*2**t,ve)+Math.floor(Math.random()*100)}var pt=t=>new Promise(e=>setTimeout(e,t));function V(t,e={}){let r=new Error(t);return r.retryable=!1,Object.assign(r,e),r}function se(t,e,r){return V(`HTTP response from ${t} exceeded maxResponseBytes ${r} (${e})`,{oversize:!0})}function H(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function ht(t){return t?t.byteLength??t.length??0:0}async function we(t,e,{url:r,truncate:n=!1,onOversize:a}={}){if(e==null)return await t.text();let o=Number(t.headers?.get?.("content-length"));if(Number.isFinite(o)&&o>e&&(H(t),!n))throw se(r,`content-length ${o}`,e);let s=t.body?.getReader?.();if(!s){let i=await t.text(),l=Buffer.byteLength(i,"utf8");if(l>e){if(!n)throw se(r,`body ${l} bytes`,e);return Buffer.from(i,"utf8").subarray(0,e).toString("utf8")}return i}let d=[],u=0,p=!1;try{for(;;){let{value:i,done:l}=await s.read();if(l)break;if(i&&(d.push(Buffer.from(i)),u+=ht(i),u>e)){p=!0;break}}}finally{if(p)try{await s.cancel()}catch{}try{s.releaseLock?.()}catch{}}if(p&&(typeof a=="function"&&a(),!n))throw se(r,`streamed ${u} bytes`,e);let c=Buffer.concat(d);return(p?c.subarray(0,e):c).toString("utf8")}function Se(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function ft(t,{fetchImpl:e,method:r,headers:n,body:a,timeoutMs:o,lookupFn:s,realFetch:d,untrustedUrl:u=!1,maxResponseBytes:p=null,importUndici:c,validateResponse:i,signal:l}){let h=new AbortController,f=setTimeout(()=>h.abort(),o),g=l?typeof AbortSignal.any=="function"?AbortSignal.any([l,h.signal]):l:h.signal,b=null,T=e,I=s?{lookupFn:s}:{};if(u&&!d&&!oe(T))throw V(`HTTP refused ${t}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let q=async(E,{status:S=null}={})=>{let w=await te(E,I);if(!w.ok)throw V(S==null?`HTTP refused ${E}: ${w.error}`:`HTTP redirect to ${E} ${w.error}`,S==null?{}:{status:S});let y=new URL(E).hostname;if(d){if(b&&(await b.close(),b=null),!b)try{b=await re({requireUndici:!0,...c?{importUndici:c}:{}})}catch(x){throw V(S==null?`HTTP refused ${E}: ${x?.message||x}`:`HTTP redirect to ${E} refused: ${x?.message||x}`,S==null?{}:{status:S})}b.pin(y,w.addresses),T=b.fetch}else fe(T,y,w.addresses);return w};try{let E=String(t),S={...n||{}};u&&await q(E);for(let w=0;w<=ge;w+=1){let y=await T(E,{method:r,headers:S,body:a,signal:g,redirect:"manual"});if(tt.has(y.status)){if(r!=="GET"&&r!=="HEAD"){let U=await we(y,p??rt,{url:E,truncate:!0}),$=new Error(`HTTP ${y.status} ${r} ${E} redirected non-idempotent request`);throw $.status=y.status,$.body=Se(U)??U.slice(0,300),$}if(w===ge)throw H(y),new Error(`HTTP redirect loop for ${t}`);let A=y.headers?.get?.("location"),N;try{N=at(A,E)}catch(U){throw H(y),U}let D=!st(N,E);if(H(y),D&&(S=ot(S)),u)await q(N,{status:y.status});else if(D){let U=await te(N,I);if(!U.ok){let $=new Error(`HTTP redirect from ${E} ${U.error}`);throw $.status=y.status,$.retryable=!1,$}d&&U.addresses?.length&&(b||(b=await re(c?{importUndici:c}:{})),b&&(b.pin(new URL(N).hostname,U.addresses),T=b.fetch))}E=N;continue}if(typeof i=="function")try{await i(y,{url:E})}catch(A){throw H(y),V(A?.message||String(A))}let x=await we(y,p,{url:E,onOversize:()=>h.abort()}),k=Se(x);if(!y.ok){let A=new Error(`HTTP ${y.status} ${r} ${E}`);throw A.status=y.status,A.retryAfter=y.headers?.get?.("retry-after")??null,A.body=k??x.slice(0,300),A}return k??x}throw new Error(`HTTP redirect loop for ${t}`)}finally{clearTimeout(f),b&&await b.close()}}async function G(t,e={}){let r=e.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=e.timeoutMs??12e3,a=(e.method||"GET").toUpperCase(),o={Accept:"application/json",...e.headers||{}},s=e.body;s!=null&&typeof s!="string"&&(o["Content-Type"]=o["Content-Type"]||"application/json",s=JSON.stringify(s));let d=Number.isInteger(e.retries)?Math.max(e.retries,0):et,u=e.lookupFn,p=!e.fetchImpl,c=e.untrustedUrl===!0,i=e.importUndici,l=e.validateResponse,h=e.signal,f=Number(e.maxResponseBytes),g=Number.isFinite(f)&&f>0?Math.floor(f):null,b=async()=>{let S;for(let w=0;w<=d;w++){h?.throwIfAborted?.();try{return await ft(t,{fetchImpl:r,method:a,headers:o,body:s,timeoutMs:n,lookupFn:u,realFetch:p,untrustedUrl:c,maxResponseBytes:g,importUndici:i,validateResponse:l,signal:h})}catch(y){S=y;let x=y?.status,k=y?.name==="AbortError"||y?.name==="TimeoutError"||h?.aborted,A=new Set([408,425,429]),N=y?.retryable===!1?!1:x!=null?A.has(x)||Ze.has(x)&&be.has(a):!k&&be.has(a);if(w===d||!N)throw y;let D=dt(w,y?.retryAfter);h?await new Promise((U,$)=>{let Qe=setTimeout(U,D);h.addEventListener("abort",()=>{clearTimeout(Qe),$(h.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await pt(D)}}throw S};if(!(e.dedupe!==!1&&!h&&ut(a,s)))return b();let I=lt(a,t,o,{untrustedUrl:c,maxResponseBytes:g},s),q=ae.get(I);if(q)return q;let E=b().finally(()=>ae.delete(I));return ae.set(I,E),E}async function Ce(t,e,r){let n=Array.from(t),a=Math.max(1,Math.min(Number(e)||1,n.length||1)),o=new Array(n.length),s=0;return await Promise.all(Array.from({length:a},async()=>{for(;s<n.length;){let d=s++;o[d]=await r(n[d],d)}})),o}var Ae={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},mt=new Map(Object.values(Ae).map(t=>[t.chainId,t]));function xe(t){return mt.get(Number(t))||null}function Ie(t,e=process.env){let r=xe(t);if(!r)return null;for(let n of r.rpcEnv){let a=(e[n]||"").trim();if(a)return a}return null}import{Interface as bt,getAddress as vt}from"ethers";var ke=new bt(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Ne(t,e){try{return vt(t).toLowerCase()}catch{throw new Error(`${e} must be a valid EVM address`)}}var gt={1:"https://ethereum.publicnode.com",137:"https://polygon-bor-rpc.publicnode.com",42161:"https://arbitrum-one-rpc.publicnode.com",8453:"https://base-rpc.publicnode.com",10:"https://optimism-rpc.publicnode.com",988:"https://rpc.stable.xyz",56:"https://bsc-rpc.publicnode.com",43114:"https://avalanche-c-chain-rpc.publicnode.com",999:"https://rpc.hyperliquid.xyz/evm",2741:"https://api.mainnet.abs.xyz",4663:"https://rpc.mainnet.chain.robinhood.com"};function yt(t,{rpcUrl:e,env:r=process.env}={}){if(e)return e;let n=Ie(t,r);return n||gt[Number(t)]||null}var wt=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function St(t){let e=String(t||""),r=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!wt.test(r))throw new Error(`evm-rpc: ${e} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}var M=new Map,Te=new Map;function Et(t){let e=new Error(t?.message||JSON.stringify(t));return e.code=t?.code,e}function Ct(t){if(t?.error)throw Et(t.error);return t?.result}function At(t,e,r){return`${t}
4
+ ${e}
5
+ ${JSON.stringify(r??[])}`}async function xt(t,e,r){return G(t,{method:"POST",body:e,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function _(t,e,r=[],n={}){let a=String(e||""),o=St(a),s=yt(t,n);if(!s)throw new Error(`No RPC URL for chainId ${t} (set env from chain registry rpcEnv or pass rpcUrl)`);if(o==="eth_chainid"&&n.cacheChainId!==!1){let c=Te.get(s);if(c!=null)return c}let u=n.dedupe!==!1&&!n.signal?At(s,a,r):null;if(u&&M.has(u))return M.get(u);let p=(async()=>{let c=await xt(s,{jsonrpc:"2.0",id:1,method:e,params:r},n),i=Ct(c);return o==="eth_chainid"&&typeof i=="string"&&Te.set(s,i),i})();return u&&(M.set(u,p),p.finally(()=>{M.get(u)===p&&M.delete(u)}).catch(()=>{})),p}async function Le(t,e={}){let r=await _(t,"eth_blockNumber",[],e);return parseInt(r,16)}async function qe(t,e,r={}){if(!e)throw new Error("rpcGetBalance requires address");let n=await _(t,"eth_getBalance",[e,"latest"],r);return{chainId:Number(t),address:e,balanceWei:BigInt(n).toString(),balanceHex:n}}async function Ue(t={},e={}){let r=Number(t.chainId??e.chainId??1),n=Ne(t.token||t.tokenAddress,"token"),a=Ne(t.account||t.owner||t.address,"account"),o=ke.encodeFunctionData("balanceOf",[a]),s=await _(r,"eth_call",[{to:n,data:o},t.blockTag||"latest"],e),d=ke.decodeFunctionResult("balanceOf",s),u=BigInt(d[0]);return{chainId:r,token:n,account:a,balance:u.toString(),balanceHex:`0x${u.toString(16)}`,blockTag:t.blockTag||"latest"}}var It=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"]);function _e(t,e){let r=String(t||"").toLowerCase(),n=String(e?.quote||e?.quoteToken?.address||"").toLowerCase(),a=String(e?.base||e?.baseToken?.address||"").toLowerCase();return n===r?{address:e.base||e.baseToken?.address,symbol:e.baseToken?.symbol}:a===r?{address:e.quote||e.quoteToken?.address,symbol:e.quoteToken?.symbol}:{address:e.quote||e.quoteToken?.address,symbol:e.quoteToken?.symbol}}function ie(t,e=[],{stables:r=[],wrappedNative:n=null}={}){let a=String(t||"").toLowerCase(),o=new Set((r||[]).map(u=>String(u).toLowerCase())),s=String(n||"").toLowerCase(),d=(e||[]).map((u,p)=>{let c=_e(a,u),i=String(c.address||"").toLowerCase(),l=String(c.symbol||"").toLowerCase(),h=Number(u.liquidityUsd??u.liquidity?.usd),f=Number.isFinite(h)?h:0,g=String(u.dex||u.dexId||"").toLowerCase(),b=0;return o.has(i)||It.has(l)?b=300:s&&i===s&&(b=100),g.includes("v4")?b+=20:g.includes("v3")?b+=10:(g.includes("v2")||g.includes("raydium")||g.includes("orca")||g.includes("meteora"))&&(b+=8),{pool:u,score:b*1e12+f,index:p,otherAddr:i,liquidityUsd:f}});return d.sort((u,p)=>p.score-u.score||u.index-p.index),d.map(u=>u.pool)}function Re(t,e=[]){let r=Array.isArray(e)?e:[];return r.length&&_e(t,r[0]).address||null}var kt="https://api.dexscreener.com",tr=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function Nt(t={}){return(t.baseUrl||process.env.DEXSCREENER_API_URL||kt).replace(/\/$/,"")}async function $e(t,e={}){if(!t)throw new Error("tokenAddress required");return G(`${Nt(e)}/latest/dex/tokens/${t}`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var j=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),v=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),m=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),Tt=/^0x[0-9a-fA-F]{40}$/;function Lt(t={}){let e=[],r=[];if(!t||typeof t!="object")return{ok:!1,errors:["definition must be an object"],warnings:r};if((!Number.isInteger(t.chainId)||t.chainId<=0)&&e.push("chainId must be a positive integer"),(typeof t.key!="string"||!/^[a-z][a-z0-9-]*$/.test(t.key||""))&&e.push('key must be a lowercase slug (e.g. "base")'),(typeof t.name!="string"||!t.name.trim())&&e.push("name is required"),!Array.isArray(t.rpcEnv)||t.rpcEnv.length===0)e.push("rpcEnv must list at least one environment variable name");else for(let a of t.rpcEnv)(typeof a!="string"||!/^[A-Z][A-Z0-9_]*$/.test(a))&&e.push(`rpcEnv entry "${a}" should be an UPPER_SNAKE env var name`);if(t.nativeCurrency){let a=t.nativeCurrency;(typeof a.symbol!="string"||!a.symbol)&&e.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(a.decimals)||e.push("nativeCurrency.decimals must be an integer")}for(let[a,o]of(t.venues||[]).entries()){let s=`venues[${a}]`;if(!o||typeof o!="object"){e.push(`${s} must be an object`);continue}Tt.test(o.address||"")||e.push(`${s}.address is not a valid 20-byte address`),/^0x0{40}$/.test(o.address||"")&&e.push(`${s}.address is the zero address -- placeholder left in place?`),o.kind||e.push(`${s}.kind is required (router|quoter|factory|...)`),o.verified?(o.verified.method||e.push(`${s}.verified.method is required`),o.verified.source||e.push(`${s}.verified.source is required`),o.verified.date||r.push(`${s}.verified.date missing -- add one so staleness is visible`)):e.push(`${s} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let n=t.capabilities||{};for(let a of Object.keys(n))j.includes(a)?typeof n[a]!="function"&&e.push(`capability "${a}" must be a function`):e.push(`unknown capability "${a}"`);return Object.keys(n).length===0&&r.push("scanner implements no capabilities -- it can only be registered, not used"),n.prepareUnsignedTx&&!n.quote&&r.push("prepareUnsignedTx without quote: no priced expectation to validate the built tx against"),n.prepareUnsignedTx&&!n.sellSimulation&&r.push("prepareUnsignedTx without sellSimulation: cannot prove an asset is exitable before buying"),{ok:e.length===0,errors:e,warnings:r}}function qt(t){let{ok:e,errors:r,warnings:n}=Lt(t);if(!e)throw new Error(`invalid scanner for ${t?.key??"<unknown>"}:
6
+ - ${r.join(`
7
+ - `)}`);let a=t.capabilities||{},o=j.filter(d=>typeof a[d]=="function"),s={key:t.key,chainId:t.chainId,name:t.name,rpcEnv:[...t.rpcEnv],nativeCurrency:t.nativeCurrency?{...t.nativeCurrency}:null,wrappedNative:t.wrappedNative||null,explorer:t.explorer||null,venues:(t.venues||[]).map(d=>({...d})),warnings:n,capabilities(){return{chainId:t.chainId,key:t.key,supported:[...o],unsupported:j.filter(d=>!o.includes(d))}},supports(d){return o.includes(d)}};for(let d of j)o.includes(d)?s[d]=async(...u)=>a[d](...u,{scanner:s}):s[d]=async()=>{throw new Error(`${t.key} (chain ${t.chainId}) does not implement "${d}". Supported: ${o.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(s)}var W=new Map;function Be(t){let e=qt(t);return W.set(e.chainId,e),e}function ce(t){return W.get(Number(t))||null}function Y(){return[...W.values()]}function Pe(){let t={};for(let e of W.values())t[e.chainId]={key:e.key,name:e.name,...e.capabilities(),venueCount:e.venues.length,failClosed:e.venues.length===0};return{generatedAt:new Date().toISOString(),chainCount:W.size,capabilities:[...j],chains:t}}var le={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},L=t=>BigInt(t).toString(16).padStart(64,"0"),K=t=>t.slice(2).toLowerCase().padStart(64,"0");function Ut(t,e){return`0x${le.getAmountsOut}`+L(t)+L(64)+L(e.length)+e.map(K).join("")}function _t(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length<128)return null;let r=Number(BigInt(`0x${e.slice(64,128)}`));if(!Number.isFinite(r)||r<1||r>16)return null;let n=[];for(let a=0;a<r;a++){let o=128+a*64;if(e.length<o+64)return null;n.push(BigInt(`0x${e.slice(o,o+64)}`))}return n}function ue(t,e="router"){return(t?.venues||[]).find(n=>n.kind===e)?.address??null}var de=100;function Rt(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>de)throw new Error(`slippageBps ${r} exceeds the ${de} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(r))/10000n}function Fe(t){let{chainId:e,wrappedNative:r}=t;async function n(a,o,s,d){let u=await _(e,"eth_call",[{to:a,data:Ut(o,s)},"latest"],d);return _t(u?.result??u)}return{async quote({tokenIn:a,tokenOut:o,amountIn:s,path:d},u={}){let p=ue(u.scanner);if(!p)return{chainId:e,evidence:v.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let c=d||[a,o];if(c.some(l=>!/^0x[0-9a-fA-F]{40}$/.test(l||"")))throw new Error("quote requires valid 20-byte addresses");let i=await n(p,s,c,u);return i?{chainId:e,router:p,path:c,amountIn:String(s),amountOut:i[i.length-1].toString(),hops:c.length-1,evidence:v.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:e,router:p,path:c,evidence:v.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:a,amountIn:o,base:s},d={}){let u=ue(d.scanner),p=s||r;if(p&&String(a).toLowerCase()===String(p).toLowerCase())return{chainId:e,token:a,verdict:m.UNKNOWN,evidence:v.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!u||!p)return{chainId:e,token:a,verdict:m.UNKNOWN,evidence:v.UNAVAILABLE,reason:u?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let c=await n(u,o,[p,a],d);if(!c)return{chainId:e,token:a,verdict:m.FAIL,evidence:v.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let i=c[c.length-1];if(i===0n)return{chainId:e,token:a,verdict:m.FAIL,evidence:v.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let l=await n(u,i,[a,p],d);if(!l)return{chainId:e,token:a,verdict:m.FAIL,evidence:v.LIVE,leg:"sell",bought:i.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let h=l[l.length-1],f=Number(h*10000n/BigInt(o)),g=m.PASS,b="round trip completes with expected fee/impact loss";return f<5e3?(g=m.FAIL,b=`round trip returns only ${(f/100).toFixed(2)}% -- punitive tax or no real liquidity`):f<9e3&&(g=m.CAUTION,b=`round trip returns ${(f/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,token:a,base:p,router:u,verdict:g,reason:b,amountIn:String(o),bought:i.toString(),returned:h.toString(),retentionBps:f,evidence:v.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:a,tokenOut:o,amountIn:s,recipient:d,slippageBps:u=50,deadlineSeconds:p=900,path:c},i={}){let l=i.scanner,h=ue(l);if(!h)throw new Error(`chain ${e} has no verified router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!/^0x[0-9a-fA-F]{40}$/.test(d||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=c||[a,o],g=await this.quote({tokenIn:a,tokenOut:o,amountIn:s,path:f},i);if(g.evidence!==v.LIVE)throw new Error(`cannot prepare without a live quote (${g.evidence}: ${g.reason??"no reason given"})`);let b=Rt(g.amountOut,u);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let T=BigInt(Math.floor(Date.now()/1e3)+Number(p)),I=r&&f[0].toLowerCase()===r.toLowerCase()&&i.useNative,q=I?`0x${le.swapExactETHForTokens}`+L(b)+L(128)+K(d)+L(T)+L(f.length)+f.map(K).join(""):`0x${le.swapExactTokensForTokens}`+L(s)+L(b)+L(160)+K(d)+L(T)+L(f.length)+f.map(K).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:e,tx:{to:h,data:q,value:I?`0x${BigInt(s).toString(16)}`:"0x0"},guard:{quotedOut:g.amountOut,minOut:b.toString(),slippageBps:u,maxSlippageBps:de,deadline:T.toString()},requires:I?[]:[{step:"approve",token:f[0],spender:h,amount:String(s)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var $t=[100,500,3e3,1e4],Oe={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},P=t=>BigInt(t).toString(16).padStart(64,"0"),z=t=>t.slice(2).toLowerCase().padStart(64,"0"),De=/^0x[0-9a-fA-F]{40}$/,he=100;function Bt(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>he)throw new Error(`slippageBps ${r} exceeds the ${he} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(r))/10000n}function pe(t,e){return(t?.venues||[]).find(r=>r.kind===e)?.address??null}function Ve(t){let{chainId:e,wrappedNative:r}=t;async function n({quoter:o,tokenIn:s,tokenOut:d,amountIn:u,fee:p},c){let i=`0x${Oe.quoteExactInputSingle}`+z(s)+z(d)+P(u)+P(p)+P(0),l=await _(e,"eth_call",[{to:o,data:i},"latest"],c).catch(()=>null),h=l?.result??l;if(!h||h==="0x"||h.length<66)return null;let f=BigInt(`0x${h.slice(2,66)}`);return f>0n?f:null}async function a({quoter:o,tokenIn:s,tokenOut:d,amountIn:u},p){let c=await Promise.all($t.map(async l=>{let h=await n({quoter:o,tokenIn:s,tokenOut:d,amountIn:u,fee:l},p);return{fee:l,amountOut:h?h.toString():null,out:h}})),i=null;for(let l of c)l.out&&(!i||l.out>i.amountOut)&&(i={fee:l.fee,amountOut:l.out});return{best:i,tried:c.map(({fee:l,amountOut:h})=>({fee:l,amountOut:h}))}}return{async quote({tokenIn:o,tokenOut:s,amountIn:d},u={}){let p=pe(u.scanner,"quoter");if(!p)return{chainId:e,evidence:v.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let l of[o,s])if(!De.test(l||""))throw new Error("quote requires valid 20-byte addresses");let{best:c,tried:i}=await a({quoter:p,tokenIn:o,tokenOut:s,amountIn:d},u);return c?{chainId:e,venue:"uniswap-v3",quoter:p,tokenIn:o,tokenOut:s,amountIn:String(d),amountOut:c.amountOut.toString(),fee:c.fee,useNative:!!r&&String(o).toLowerCase()===String(r).toLowerCase(),triedFeeTiers:i,evidence:v.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:e,quoter:p,tokenIn:o,tokenOut:s,triedFeeTiers:i,evidence:v.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:o,amountIn:s,base:d},u={}){let p=pe(u.scanner,"quoter"),c=(t.stableQuoteAssets||[]).map(S=>String(S).toLowerCase()),i=null;!d&&typeof t.resolveQuoteAsset=="function"&&(i=await t.resolveQuoteAsset(o,u).catch(()=>null));let l=String(o).toLowerCase(),h=String(r||"").toLowerCase();if(h&&l===h)return{chainId:e,token:o,verdict:m.UNKNOWN,evidence:v.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};let f=d||i||(c[0]&&l!==c[0]?c[0]:null)||r;if(f&&l===String(f).toLowerCase())return{chainId:e,token:o,verdict:m.UNKNOWN,evidence:v.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!p||!f)return{chainId:e,token:o,verdict:m.UNKNOWN,evidence:v.UNAVAILABLE,reason:p?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let g=await a({quoter:p,tokenIn:f,tokenOut:o,amountIn:s},u);if(!g.best){let S=c.find(w=>w&&w!==String(f).toLowerCase()&&w!==String(o).toLowerCase());if(S){let w=await a({quoter:p,tokenIn:S,tokenOut:o,amountIn:s},u);if(w.best){let y=await a({quoter:p,tokenIn:o,tokenOut:S,amountIn:w.best.amountOut},u);if(y.best){let x=y.best.amountOut,k=Number(x*10000n/BigInt(s)),A=m.PASS,N="round trip vs dollar book completes with expected fee/impact loss";return k<5e3?(A=m.FAIL,N=`round trip vs dollar book returns only ${(k/100).toFixed(2)}% -- punitive tax or no real liquidity`):k<9e3&&(A=m.CAUTION,N=`round trip vs dollar book returns ${(k/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:S,quoteAsset:S,verdict:A,reason:N,amountIn:String(s),bought:w.best.amountOut.toString(),returned:x.toString(),retentionBps:k,buyFee:w.best.fee,sellFee:y.best.fee,evidence:v.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:e,token:o,verdict:m.FAIL,evidence:v.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let b=await a({quoter:p,tokenIn:o,tokenOut:f,amountIn:g.best.amountOut},u);if(!b.best){let S=c.find(w=>w&&w!==String(f).toLowerCase()&&w!==String(o).toLowerCase());if(S){let w=await a({quoter:p,tokenIn:S,tokenOut:o,amountIn:s},u),y=w.best?await a({quoter:p,tokenIn:o,tokenOut:S,amountIn:w.best.amountOut},u):{best:null};if(w.best&&y.best){let x=y.best.amountOut,k=Number(x*10000n/BigInt(s)),A=m.PASS,N="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return k<5e3?(A=m.FAIL,N=`dollar-book round trip returns only ${(k/100).toFixed(2)}%`):k<9e3&&(A=m.CAUTION,N=`dollar-book round trip returns ${(k/100).toFixed(2)}%`),{chainId:e,venue:"uniswap-v3",token:o,base:S,quoteAsset:S,verdict:A,reason:N,amountIn:String(s),bought:w.best.amountOut.toString(),returned:x.toString(),retentionBps:k,buyFee:w.best.fee,sellFee:y.best.fee,evidence:v.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:e,token:o,verdict:m.FAIL,evidence:v.LIVE,leg:"sell",bought:g.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let T=b.best.amountOut,I=Number(T*10000n/BigInt(s)),q=m.PASS,E="round trip completes with expected fee/impact loss";return I<5e3?(q=m.FAIL,E=`round trip returns only ${(I/100).toFixed(2)}% -- punitive tax or no real liquidity`):I<9e3&&(q=m.CAUTION,E=`round trip returns ${(I/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:f,verdict:q,reason:E,amountIn:String(s),bought:g.best.amountOut.toString(),returned:T.toString(),retentionBps:I,buyFee:g.best.fee,sellFee:b.best.fee,evidence:v.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:s,amountIn:d,recipient:u,slippageBps:p=50,fee:c},i={}){let l=pe(i.scanner,"router");if(!l)throw new Error(`chain ${e} has no verified V3 router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!De.test(u||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let h=await this.quote({tokenIn:o,tokenOut:s,amountIn:d},i);if(h.evidence!==v.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let f=c??h.fee,g=Bt(h.amountOut,p);if(g<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=!!(i.useNative||h.useNative)&&r&&String(o).toLowerCase()===String(r).toLowerCase(),T=`0x${Oe.exactInputSingle}`+z(o)+z(s)+P(f)+z(u)+P(d)+P(g)+P(0);return{unsigned:!0,signedBy:"user-wallet",chainId:e,venue:"uniswap-v3",tx:{to:l,data:T,value:b?String(d):"0x0"},guard:{quotedOut:h.amountOut,minOut:g.toString(),slippageBps:p,maxSlippageBps:he,fee:f},requires:b?[]:[{step:"approve",token:o,spender:l,amount:String(d)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var J={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function He(t){if(!t||t==="0x")return null;try{return BigInt(t)}catch{return null}}function Me(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length>=128){let n=Number(BigInt(`0x${e.slice(64,128)}`));if(n>0&&n<=256&&e.length>=128+n*2){let a=e.slice(128,128+n*2),o=Buffer.from(a,"hex").toString("utf8").replace(/\0+$/,"");if(o)return o}}return Buffer.from(e.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function Pt(t){let{chainId:e}=t;async function r(n,a,o){return _(e,"eth_call",[{to:n,data:a},"latest"],o)}return{async blockNumber(n={}){let a=await Le(e,n);return{chainId:e,blockNumber:a?.blockNumber??a,evidence:v.LIVE}},async nativeBalance(n,a={}){let o=await qe(e,n,a);return{chainId:e,address:n,wei:o?.wei??o?.balance??null,symbol:t.nativeCurrency?.symbol??null,decimals:t.nativeCurrency?.decimals??18,evidence:v.LIVE}},async tokenBalance({token:n,owner:a},o={}){let s=await Ue({chainId:e,token:n,owner:a},o);return{chainId:e,token:n,owner:a,raw:s?.balance??s,evidence:v.LIVE}},async resolveToken(n,a={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:e,token:n,evidence:v.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[o,s,d,u]=await Promise.all([r(n,J.decimals,a).catch(()=>null),r(n,J.symbol,a).catch(()=>null),r(n,J.name,a).catch(()=>null),r(n,J.totalSupply,a).catch(()=>null)]),p=He(o?.result??o),c=p!==null||s?.result||d?.result;return{chainId:e,address:n,decimals:p===null?null:Number(p),symbol:Me(s?.result??s),name:Me(d?.result??d),totalSupply:(He(u?.result??u)??null)?.toString()??null,evidence:c?v.LIVE:v.UNKNOWN,warning:c?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(n,a={}){let o=t.dexscreenerSlug;if(!o)return{chainId:e,token:n,pools:[],evidence:v.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let s=await $e(n,a).catch(()=>null),u=(s?.pairs||s?.data?.pairs||[]).filter(c=>String(c.chainId).toLowerCase()===String(o).toLowerCase()).map(c=>({pair:c.pairAddress,dex:c.dexId,base:c.baseToken?.address,quote:c.quoteToken?.address,liquidityUsd:c.liquidity?.usd??null,priceUsd:c.priceUsd??null,volume24hUsd:c.volume?.h24??null,createdAt:c.pairCreatedAt??null})).sort((c,i)=>(i.liquidityUsd??0)-(c.liquidityUsd??0)),p=ie(n,u,{stables:t.stableQuoteAssets||[],wrappedNative:t.wrappedNative});return{chainId:e,token:n,pools:p,topPool:p[0]||null,quoteAsset:Re(n,p),evidence:p.length?v.LIVE:v.UNKNOWN}},async scanBlocks({fromBlock:n,toBlock:a,address:o,topics:s,chunkSize:d=2e3}={},u={}){if(!Number.isInteger(n)||!Number.isInteger(a))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(a<n)throw new Error("toBlock must be >= fromBlock");let p=[],c=[];for(let l=n;l<=a;l+=d){let h=Math.min(l+d-1,a);c.push([l,h])}let i=await Ce(c,4,async([l,h])=>{let f={fromBlock:`0x${l.toString(16)}`,toBlock:`0x${h.toString(16)}`};o&&(f.address=o),s&&(f.topics=s);let g=await _(e,"eth_getLogs",[f],u).catch(b=>({error:String(b?.message||b)}));return{start:l,end:h,res:g}});for(let{start:l,end:h,res:f}of i){if(f?.error)return{chainId:e,fromBlock:n,toBlock:a,logs:p,complete:!1,failedAt:[l,h],error:f.error,evidence:v.UNKNOWN};for(let g of f?.result??f??[])p.push(g)}return{chainId:e,fromBlock:n,toBlock:a,logs:p,complete:!0,chunks:c.length,evidence:v.LIVE}},async scoreRisk(n,a={}){let o=[],s=m.PASS,d=c=>{let i={[m.PASS]:0,[m.CAUTION]:1,[m.UNKNOWN]:2,[m.FAIL]:3};i[c]>i[s]&&(s=c)},[u,p]=await Promise.all([this.resolveToken(n,a),this.resolvePools(n,a)]);if(u.evidence!==v.LIVE?(o.push({check:"erc20-metadata",result:m.UNKNOWN,detail:u.warning}),d(m.UNKNOWN)):o.push({check:"erc20-metadata",result:m.PASS,detail:`${u.symbol} / ${u.decimals}d`}),p.evidence===v.UNAVAILABLE)o.push({check:"liquidity",result:m.UNKNOWN,detail:p.reason}),d(m.UNKNOWN);else if(!p.pools.length)o.push({check:"liquidity",result:m.FAIL,detail:"no pool with liquidity found"}),d(m.FAIL);else{let c=p.pools[0],i=c.liquidityUsd??0;i<5e3?(o.push({check:"liquidity",result:m.CAUTION,detail:`top pool only $${i}`}),d(m.CAUTION)):o.push({check:"liquidity",result:m.PASS,detail:`$${i} on ${c.dex}`}),c.createdAt&&Date.now()-c.createdAt<24*3600*1e3&&(o.push({check:"age",result:m.CAUTION,detail:"pool under 24h old"}),d(m.CAUTION))}if(typeof this.sellSimulation=="function"){let c=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},a).catch(i=>({verdict:m.UNKNOWN,reason:String(i?.message||i)}));o.push({check:"sellability",result:c.verdict,detail:c.retentionBps!=null?`round trip returns ${(c.retentionBps/100).toFixed(2)}% -- ${c.reason}`:c.reason}),d(c.verdict)}else o.push({check:"sellability",result:m.UNKNOWN,detail:"no verified router on this chain, so a round-trip sell simulation cannot run. Treat as unproven -- a buy path is not an exit path."}),d(m.UNKNOWN);return{chainId:e,token:n,verdict:s,checks:o,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function je(t){let r={...Pt(t)},n=new Set((t.venues||[]).map(o=>o.kind));t.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,Ve({chainId:t.chainId,wrappedNative:t.wrappedNative,stableQuoteAssets:t.stableQuoteAssets||[],resolveQuoteAsset:async(o,s)=>(await r.resolvePools(o,s)).quoteAsset||null})):t.venueKind==="uniswap-v2"&&n.has("router")&&Object.assign(r,Fe({chainId:t.chainId,wrappedNative:t.wrappedNative}));let a={};for(let[o,s]of Object.entries(r))a[o]=s.bind(r);return{key:t.key,chainId:t.chainId,name:t.name,rpcEnv:t.rpcEnv,nativeCurrency:t.nativeCurrency,explorer:t.explorer,venues:t.venues||[],capabilities:a}}var Ft=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",stableQuoteAssets:["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48","0xdAC17F958D2ee523a2206206994597C13D831ec7"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85","0x94b008aA00579c1307B0EF2c499aD98a8ce58e58"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",stableQuoteAssets:["0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d","0x55d398326f99059fF775485246999027B3197955"],venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",stableQuoteAssets:["0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359","0xc2132D05D31c914a87C6611C10748AEb04B58e8F"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",stableQuoteAssets:["0x5fc5360d0400a0fd4f2af552add042d716f1d168"],venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",stableQuoteAssets:["0xaf88d065e77c8cC2239327C5EDb3A432268e5831","0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",stableQuoteAssets:["0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"],venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);function We(){return Ft.map(t=>Be(je(t)))}We();var[Ke,...ze]=process.argv.slice(2),X=ze.includes("--json"),C=ze.filter(t=>t!=="--json");function O(t){t||R("missing <chain>");let e=ce(Number(t));if(e)return e;let r=Y().find(n=>n.key===String(t).toLowerCase());if(r)return r;R(`unknown chain "${t}". Known: ${Y().map(n=>`${n.key}(${n.chainId})`).join(", ")}`)}function R(t){console.error(`error: ${t}`),process.exit(1)}function F(t){process.stdout.write(`${JSON.stringify(t,null,2)}
8
+ `)}function Ot(t,e){let r=String(e?.message||e);return/rpc|fetch|ECONN|timeout|provider/i.test(r)?`${r}
7
9
 
8
10
  This chain reads its RPC from: ${t.rpcEnv.join(" or ")}
9
- Set one, e.g.: export ${t.rpcEnv[0]}=https://...`:n}try{switch(Ve){case"chains":{let t=Ue();if(X){F(t);break}console.log(`${t.chainCount} chains registered
10
- `);let e=Object.entries(t.chains).map(([r,s])=>({chain:`${s.key} (${r})`,caps:s.supported.length,routing:s.failClosed?"fail-closed (no verified venue)":`${s.venueCount} venue(s)`})),n=Math.max(...e.map(r=>r.chain.length));for(let r of e)console.log(` ${r.chain.padEnd(n)} ${String(r.caps).padStart(2)} caps ${r.routing}`);console.log(`
11
+ Set one, e.g.: export ${t.rpcEnv[0]}=https://...`:r}try{switch(Ke){case"chains":{let t=Pe();if(X){F(t);break}console.log(`${t.chainCount} chains registered
12
+ `);let e=Object.entries(t.chains).map(([n,a])=>({chain:`${a.key} (${n})`,caps:a.supported.length,routing:a.failClosed?"fail-closed (no verified venue)":`${a.venueCount} venue(s)`})),r=Math.max(...e.map(n=>n.chain.length));for(let n of e)console.log(` ${n.chain.padEnd(r)} ${String(n.caps).padStart(2)} caps ${n.routing}`);console.log(`
11
13
  Every chain is read/research capable. Routing value requires a verified
12
- venue -- see CONTRIBUTING.md for the verification rule.`);break}case"head":{let t=O(C[0]);F(await t.blockNumber());break}case"token":{let t=O(C[0]);C[1]||R("usage: oracle-scan token <chain> <address>"),F(await t.resolveToken(C[1]));break}case"pools":{let t=O(C[0]);C[1]||R("usage: oracle-scan pools <chain> <address>");let e=await t.resolvePools(C[1]);if(X){F(e);break}console.log(`evidence: ${e.evidence}`),e.reason&&console.log(`reason: ${e.reason}`);for(let n of e.pools.slice(0,10)){let r=n.liquidityUsd==null?"?":`$${Math.round(n.liquidityUsd).toLocaleString()}`;console.log(` ${n.dex.padEnd(12)} ${r.padStart(14)} ${n.pair}`)}e.pools.length||console.log(" (no pools with liquidity found)");break}case"risk":{let t=O(C[0]);C[1]||R("usage: oracle-scan risk <chain> <address>");let e=await t.scoreRisk(C[1]);if(X){F(e);break}console.log(`verdict: ${e.verdict}
13
- `);for(let n of e.checks)console.log(` ${n.result.padEnd(8)} ${n.check.padEnd(16)} ${n.detail??""}`);console.log(`
14
+ venue -- see CONTRIBUTING.md for the verification rule.`);break}case"head":{let t=O(C[0]);F(await t.blockNumber());break}case"token":{let t=O(C[0]);C[1]||R("usage: oracle-scan token <chain> <address>"),F(await t.resolveToken(C[1]));break}case"pools":{let t=O(C[0]);C[1]||R("usage: oracle-scan pools <chain> <address>");let e=await t.resolvePools(C[1]);if(X){F(e);break}console.log(`evidence: ${e.evidence}`),e.reason&&console.log(`reason: ${e.reason}`);for(let r of e.pools.slice(0,10)){let n=r.liquidityUsd==null?"?":`$${Math.round(r.liquidityUsd).toLocaleString()}`;console.log(` ${r.dex.padEnd(12)} ${n.padStart(14)} ${r.pair}`)}e.pools.length||console.log(" (no pools with liquidity found)");break}case"risk":{let t=O(C[0]);C[1]||R("usage: oracle-scan risk <chain> <address>");let e=await t.scoreRisk(C[1]);if(X){F(e);break}console.log(`verdict: ${e.verdict}
15
+ `);for(let r of e.checks)console.log(` ${r.result.padEnd(8)} ${r.check.padEnd(16)} ${r.detail??""}`);console.log(`
14
16
  ${e.note}`);break}case"quote":{let t=O(C[0]);(!C[1]||!C[2])&&R("usage: oracle-scan quote <chain> <tokenIn> <tokenOut> [amountIn]"),t.supports("quote")||R(`${t.key} has no verified router, so quoting stays fail-closed.
15
17
  Add a venue with recorded provenance -- see docs/adding-a-chain.md.`);let e=C[3]||(10n**18n).toString();F(await t.quote({tokenIn:C[1],tokenOut:C[2],amountIn:e}));break}case"sell":{let t=O(C[0]);C[1]||R("usage: oracle-scan sell <chain> <token> [amountIn]"),t.supports("sellSimulation")||R(`${t.key} has no verified router, so sell simulation is unavailable.
16
- Without it, treat every token on this chain as unproven for exit.`);let e=C[2]||(10n**16n).toString(),n=await t.sellSimulation({token:C[1],amountIn:e});if(X){F(n);break}console.log(`verdict: ${n.verdict}`),console.log(`reason: ${n.reason??""}`),n.retentionBps!=null&&console.log(`retention: ${(n.retentionBps/100).toFixed(2)}%`),n.leg&&console.log(`failed at: ${n.leg} leg`),n.note&&console.log(`
17
- ${n.note}`);break}default:console.log(["oracle-scan -- chain scanner CLI",""," oracle-scan chains coverage matrix"," oracle-scan head <chain> current block"," oracle-scan token <chain> <address> ERC-20 identity"," oracle-scan pools <chain> <address> pools by liquidity"," oracle-scan risk <chain> <address> structural risk checks"," oracle-scan quote <chain> <tIn> <tOut> [amt] live exact-input quote"," oracle-scan sell <chain> <token> [amt] round-trip: can you exit?",""," <chain> is an id (8453) or key (base). --json for machine output."," quote/sell need a chain with a verified router (see: oracle-scan chains)."].join(`
18
- `)),process.exit(Ve?1:0)}}catch(t){let e=C[0]?ie(Number(C[0]))||G().find(n=>n.key===C[0]):null;R(e?Nt(e,t):String(t?.message||t))}
18
+ Without it, treat every token on this chain as unproven for exit.`);let e=C[2]||(10n**16n).toString(),r=await t.sellSimulation({token:C[1],amountIn:e});if(X){F(r);break}console.log(`verdict: ${r.verdict}`),console.log(`reason: ${r.reason??""}`),r.retentionBps!=null&&console.log(`retention: ${(r.retentionBps/100).toFixed(2)}%`),r.leg&&console.log(`failed at: ${r.leg} leg`),r.note&&console.log(`
19
+ ${r.note}`);break}default:console.log(["oracle-scan -- chain scanner CLI",""," oracle-scan chains coverage matrix"," oracle-scan head <chain> current block"," oracle-scan token <chain> <address> ERC-20 identity"," oracle-scan pools <chain> <address> pools by liquidity"," oracle-scan risk <chain> <address> structural risk checks"," oracle-scan quote <chain> <tIn> <tOut> [amt] live exact-input quote"," oracle-scan sell <chain> <token> [amt] round-trip: can you exit?",""," <chain> is an id (8453) or key (base). --json for machine output."," quote/sell need a chain with a verified router (see: oracle-scan chains)."].join(`
20
+ `)),process.exit(Ke?1:0)}}catch(t){let e=C[0]?ce(Number(C[0]))||Y().find(r=>r.key===C[0]):null;R(e?Ot(e,t):String(t?.message||t))}
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import{createInterface as Ae}from"node:readline";var S=Object.freeze({maxRequestBytes:256*1024,maxResponseBytes:2*1024*1024,maxTools:256,maxToolNameLength:64,maxArgumentBytes:128*1024,defaultCallTimeoutMs:3e4,maxCallTimeoutMs:6e4,maxConcurrentCalls:32}),Ce=/^[A-Za-z0-9_-]{1,64}$/;function q(t,e){return{jsonrpc:"2.0",id:t??null,result:e}}function g(t,e,r){return{jsonrpc:"2.0",id:t??null,error:{code:e,message:r}}}function Re(t){return!!(t&&typeof t=="object"&&!Array.isArray(t)&&t.jsonrpc==="2.0"&&typeof t.method=="string"&&t.method.length>0)}function _e(t){if(!Array.isArray(t))return[];let e=[],r=new Set;for(let n of t){if(e.length>=S.maxTools)break;if(!n||typeof n!="object"||Array.isArray(n))continue;let o=typeof n.name=="string"?n.name.trim():"";if(!Ce.test(o)||r.has(o))continue;r.add(o);let a=n.inputSchema&&typeof n.inputSchema=="object"&&!Array.isArray(n.inputSchema)?{...n.inputSchema}:{type:"object",properties:{},additionalProperties:!1};a.type==="object"&&a.additionalProperties===void 0&&(a.additionalProperties=!1),e.push({...n,name:o,inputSchema:a})}return e}function Oe(t){let e=Number(t)||S.defaultCallTimeoutMs;return Math.min(Math.max(e,1),S.maxCallTimeoutMs)}async function Ne(t,e,r){let n;try{return await Promise.race([t,new Promise((o,a)=>{n=setTimeout(()=>{let i=new Error("tool call timed out");i.code="ORACLE_MCP_TIMEOUT",a(i);try{r?.()}catch{}},e)})])}finally{clearTimeout(n)}}function Ee(t){return t===null?"null":Array.isArray(t)?"array":Number.isInteger(t)?"integer":typeof t}function j(t,e,r="arguments",n=0){if(!e||typeof e!="object"||Array.isArray(e))return null;if(n>12)return`${r} exceeded the nesting limit`;if(Array.isArray(e.oneOf)&&e.oneOf.length&&!e.oneOf.some(a=>j(t,a,r,n+1)===null))return`${r} did not match an allowed shape`;if(Array.isArray(e.anyOf)&&e.anyOf.length&&!e.anyOf.some(a=>j(t,a,r,n+1)===null))return`${r} did not match a required alternative`;if(Array.isArray(e.enum)&&!e.enum.some(o=>Object.is(o,t)))return`${r} must be one of the allowed values`;if(Object.hasOwn(e,"const")&&!Object.is(e.const,t))return`${r} must equal the required constant`;if(e.type){let o=Ee(t);if(!(e.type==="number"?typeof t=="number"&&Number.isFinite(t):e.type==="integer"?Number.isSafeInteger(t):o===e.type))return`${r} must be ${e.type}`}if(typeof t=="string"){let o=Math.min(Number.isSafeInteger(e.maxLength)?e.maxLength:16384,16384);if(t.length>o)return`${r} exceeded the string limit`;if(Number.isSafeInteger(e.minLength)&&t.length<e.minLength)return`${r} is too short`}if(Array.isArray(t)){let o=Math.min(Number.isSafeInteger(e.maxItems)?e.maxItems:1e3,1e3);if(t.length>o)return`${r} exceeded the array limit`;if(Number.isSafeInteger(e.minItems)&&t.length<e.minItems)return`${r} has too few items`;if(e.items)for(let a=0;a<t.length;a+=1){let i=j(t[a],e.items,`${r}[${a}]`,n+1);if(i)return i}}if(t&&typeof t=="object"&&!Array.isArray(t)){let o=Object.keys(t);if(o.length>256)return`${r} exceeded the property limit`;let a=e.properties&&typeof e.properties=="object"?e.properties:{};for(let i of Array.isArray(e.required)?e.required:[])if(!Object.hasOwn(t,i))return`${r}.${i} is required`;if(e.additionalProperties===!1){let i=o.find(l=>!Object.hasOwn(a,l));if(i)return`${r}.${i} is not allowed`}for(let i of o){if(!Object.hasOwn(a,i))continue;let l=j(t[i],a[i],`${r}.${i}`,n+1);if(l)return l}}return null}function Ie(t,e={}){let r=_e(t?.tools),n=new Set(r.map(c=>c.name)),o=new Map(r.map(c=>[c.name,c])),a=typeof t?.name=="string"&&t.name?t.name.slice(0,80):"oracle-mcp",i=typeof t?.version=="string"&&t.version?t.version.slice(0,40):"1",l=Oe(e.callTimeoutMs),d=!1;return async function(f){let p=f?.id??null;if(!Re(f))return g(p,-32600,"invalid request");if(f.method==="initialize")return d=!0,q(p,{protocolVersion:f.params?.protocolVersion??"2025-03-26",capabilities:{tools:{}},serverInfo:{name:a,version:i}});if(f.method==="notifications/initialized")return null;if(f.method==="ping")return q(p,{});if(!d)return g(p,-32002,"server not initialized");if(f.method==="tools/list")return q(p,{tools:r});if(f.method==="tools/call"){let $=f.params?.name,w=f.params?.arguments??{};if(typeof $!="string"||!n.has($))return g(p,-32602,"unknown tool");if(!w||typeof w!="object"||Array.isArray(w))return g(p,-32602,"tool arguments must be an object");let O;try{O=JSON.stringify(w)}catch{return g(p,-32602,"tool arguments are not serializable")}if(Buffer.byteLength(O)>S.maxArgumentBytes)return g(p,-32602,"tool arguments exceeded the size limit");let v=j(w,o.get($)?.inputSchema);if(v)return g(p,-32602,v);try{let x=new AbortController,N=await Ne(Promise.resolve(t.call($,w,{signal:x.signal})),l,()=>x.abort(new Error("tool call timed out")));return q(p,N)}catch(x){if(x?.code==="ORACLE_MCP_TIMEOUT")return g(p,-32001,"tool call timed out");let N=typeof x?.message=="string"?x.message.replace(/\s+/g," ").trim():"",B=/\b(requires?|must be|missing|unknown|invalid|expected|unsupported|out of range|too (?:large|small|long|many)|not a|cannot convert)\b/i.test(N),F=/https?:\/\/|[/~][\w.-]+\/|0x[0-9a-fA-F]{8,}|[A-Za-z0-9+/_-]{24,}={0,2}|\b(?:secret|apikey|api[-_ ]key|private[-_ ]?key|token|password|credential|seed|mnemonic)s?\b/i.test(N.replace(/\btoken(?:In|Out|s\b)/g,"asset"));return B&&!F&&N.length<=200?g(p,-32e3,`tool call failed: ${N}`):g(p,-32e3,"tool call failed")}}return g(p,-32601,"method not found")}}function te(t,e={}){let r=e.input||process.stdin,n=e.output||process.stdout,o=Math.min(Math.max(Number(e.maxRequestBytes)||S.maxRequestBytes,64),S.maxRequestBytes),a=Math.min(Math.max(Number(e.maxResponseBytes)||S.maxResponseBytes,256),S.maxResponseBytes),i=Math.min(Math.max(Number(e.maxConcurrentCalls)||S.maxConcurrentCalls,1),S.maxConcurrentCalls),l=i*8,d=Ie(t,e),c={closed:!1,inflight:0},f=Ae({input:r,terminal:!1,crlfDelay:1/0}),p=0,$=[],w=!1,O=!1;function v(){if(c.closed||c.readerClosed)return;let y=c.inflight>=i||$.length>0||O;y&&!w?(w=!0,f.pause(),typeof r.pause=="function"&&r.pause()):!y&&w&&(w=!1,typeof r.resume=="function"&&r.resume(),f.resume())}function x(y){if(!y||c.closed)return;let k=JSON.stringify(y);Buffer.byteLength(k)>a&&(k=JSON.stringify(g(y.id,-32003,"response exceeded the size limit"))),n.write(`${k}
3
- `)===!1&&!O&&(O=!0,v(),n.once("drain",()=>{O=!1,B()}))}function N(y){c.inflight+=1,v(),Promise.resolve(d(y)).then(x).catch(()=>x(g(y?.id,-32603,"internal error"))).finally(()=>{c.inflight-=1,B()})}function B(){for(;!c.closed&&!O&&c.inflight<i&&$.length>0;)N($.shift());v()}function F(){c.closed||(x(g(null,-32700,"request exceeded the size limit")),c.closed=!0,f.close(),typeof r.destroy=="function"&&r.destroy())}return r.on("data",y=>{if(c.closed)return;let k=String(y).split(`
4
- `);for(let U=0;U<k.length;U+=1){if(p+=Buffer.byteLength(k[U]),p>o){F();return}U<k.length-1&&(p=0)}}),f.on("line",y=>{if(c.closed)return;if(Buffer.byteLength(y)>o){F();return}let k;try{k=JSON.parse(y)}catch{x(g(null,-32700,"parse error"));return}if($.length>=l){x(g(k?.id,-32e3,"server busy"));return}$.push(k),B()}),f.on("close",()=>{c.readerClosed=!0,e.exitOnClose!==!1&&(process.exitCode=0)}),c}import{createHash as Ye,randomBytes as Xe}from"node:crypto";import{mkdirSync as Ze,readFileSync as Qe,writeFileSync as et}from"node:fs";import{homedir as tt}from"node:os";import{dirname as rt,join as ae}from"node:path";var Le=/^[A-Z0-9][A-Z0-9._-]{0,11}$/;function re(t,{coin:e,side:r,sizeUsd:n,leverage:o,venue:a,confirm:i,user:l}={}){let d=String(t||"").trim();if(!d||d.includes("ts.net")||!/^https:\/\//i.test(d))return null;let c=new URL(d);if(e&&Le.test(String(e).toUpperCase())&&c.searchParams.set("coin",String(e).toUpperCase()),(r==="long"||r==="short")&&c.searchParams.set("side",r),Number.isFinite(Number(n))&&Number(n)>=1&&c.searchParams.set("size",String(Math.min(1e5,Math.round(Number(n))))),Number.isInteger(Number(o))&&Number(o)>=1&&c.searchParams.set("lev",String(Math.min(50,Number(o)))),a){let f=String(a).toLowerCase()==="hl"?"hyperliquid":String(a).toLowerCase();c.searchParams.set("venue",f)}else c.searchParams.get("venue")||c.searchParams.set("venue","hyperliquid");return c.searchParams.set("view","perps"),c.searchParams.set("build","1"),i&&/^[0-9a-f]{32}$/i.test(String(i))&&c.searchParams.set("confirm",String(i).toLowerCase()),l&&/^0x[0-9a-fA-F]{40}$/.test(String(l))&&c.searchParams.set("user",String(l).toLowerCase()),c.toString()}var Te={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},ve=new Map(Object.values(Te).map(t=>[t.chainId,t]));function ne(t){return ve.get(Number(t))||null}var u="UNKNOWN",St=Object.freeze(["token","launch","hip3","hip4","polymarket","twap","bridge","swap","approve"]),Pe=/[_*[\]`]/g;function s(t){return m(t)?String(t).replace(Pe,e=>`\\${e}`):u}function m(t){return t==null?!1:typeof t=="number"?Number.isFinite(t):typeof t=="string"?t.trim()!=="":!0}function A(t){if(!m(t))return u;let e=String(t).replace(/`/g,"");return e===""?u:`\`${e}\``}function L(t,{decimals:e=2}={}){if(!m(t))return u;let r=Number(t);return Number.isFinite(r)?r.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:e}):u}function h(t,{decimals:e=2}={}){let r=L(t,{decimals:e});return r===u?u:`${r} USD`}function W(t,{decimals:e=2}={}){let r=L(t,{decimals:e});return r===u?u:`${r}%`}function z(t){let e=L(t,{decimals:0});return e===u?u:`${e} bps`}function T(t,e){if(!m(t))return u;let r=Number(e);if(!Number.isInteger(r)||r<0||r>77)return u;let n;try{n=BigInt(typeof t=="string"?t.trim():t)}catch{return u}let o=n<0n,a=o?-n:n,i=10n**BigInt(r),l=(a/i).toString(),d=(a%i).toString().padStart(r,"0").replace(/0+$/,"");return`${o?"-":""}${l}${d?`.${d}`:""}`}function K(t){if(typeof t=="number"&&Number.isFinite(t))return t<0||t>1?u:t>=.75?"HIGH":t>=.4?"MEDIUM":"LOW";if(typeof t=="string"){let e=t.trim().toUpperCase();if(e==="HIGH"||e==="MEDIUM"||e==="LOW")return e}return u}function E(t={}){let e=t.chainId;if(!m(e)||!Number.isFinite(Number(e)))return m(t.chain)?s(t.chain):u;let n=ne(e)?.name||(m(t.chain)?String(t.chain):u);return`${s(n)} (chainId ${Number(e)})`}function ie(t={}){return s(t.venue??t.dex??t.pool?.venue)}function Me(t){return t==null?"NONE (text card only)":typeof t=="string"?t.trim()?A(t):"NONE (text card only)":t.error||t.ok===!1||t.available===!1?`UNAVAILABLE${m(t.error)?` \u2014 ${s(t.error)}`:""} (text card stands)`:m(t.url)?A(t.url):"NONE (text card only)"}function D(t={},{now:e=Date.now()}={}){let r=t.grant??t.session??null;if(!r||typeof r!="object")return{allowed:!1,reason:"no local grant/session",actions:[]};if(r.local===!1)return{allowed:!1,reason:"grant is not local",actions:[]};if(r.revoked===!0)return{allowed:!1,reason:"grant revoked",actions:[]};let n=r.expiresAt??r.expiry;if(m(n)){let a=typeof n=="number"?n:Date.parse(n);if(!Number.isFinite(a))return{allowed:!1,reason:"grant expiry unreadable",actions:[]};if(a<=e)return{allowed:!1,reason:"grant expired",actions:[]}}return{allowed:!0,reason:"valid local grant",actions:Array.isArray(r.actions)&&r.actions.length?r.actions.slice():["BUY","SELL"]}}function Be(t){let e=D(t);return e.allowed?`${e.actions.map(r=>s(r)).join(" / ")} (${s(e.reason)})`:`prepare-only \u2014 ${s(e.reason)}`}function C(t,e,r={}){let n=[`*${t}*`];for(let[o,a]of e)n.push(`${o}: ${a==null||a===""?u:a}`);return n.push(`Chart: ${Me(r.chart)}`),n.push(`Actions: ${Be(r)}`),Array.isArray(r.warnings)&&r.warnings.length&&n.push(`Warnings: ${r.warnings.map(o=>s(o)).join("; ")}`),(m(r.source)||m(r.fetchedAt))&&n.push(`Source: ${s(r.source)} at ${s(r.fetchedAt)}`),n.join(`
5
- `)}function R(t){return["Confidence",K(t.confidence)]}function Ue(t){let e=t.quote;if(!e||typeof e!="object")return[];let r=m(e.decimals)?T(e.amountOutRaw??e.out??e.raw,e.decimals):u;return[["Quote out (raw)",A(e.amountOutRaw??e.out??e.raw)],["Quote out",r===u?u:`${s(r)} ${s(e.symbol??"")}`.trim()]]}function oe(t){let e=t.autoSlippage;if(!e||typeof e!="object")return["Auto-slippage",u];let r=z(e.selectedBps),n=z(e.capBps);return["Auto-slippage",r===u&&n===u?u:`${r} selected, cap ${n}`]}function je(t={}){let e=t||{};return C(`ORACLE TOKEN \u2014 ${s(e.symbol??e.token??e.name)}`,[["Chain",E(e)],["Venue",ie(e)],["Name",s(e.name)],["Address",A(e.address??e.mint??e.contract)],["Price",h(e.priceUsd,{decimals:8})],["Market cap",h(e.marketCapUsd)],["Liquidity",h(e.liquidityUsd)],["Volume 24h",h(e.volume24hUsd)],["Change 24h",W(e.priceChange24h)],["Fee tier",m(e.feeTier)?`${z(Number(e.feeTier)/100)} (${L(e.feeTier,{decimals:0})})`:u],["Age",s(e.age)],...Ue(e),oe(e),R(e)],e)}function De(t={}){let e=t||{};return C(`ORACLE LAUNCH \u2014 ${s(e.symbol??e.token??e.name)}`,[["Chain",E(e)],["Venue",ie(e)],["Address",A(e.address??e.mint??e.contract)],["Pool",A(e.pool?.address??e.poolAddress??e.pool)],["Liquidity",h(e.liquidityUsd)],["Route ready",s(e.routeReady)],["Sellable",s(e.sellable)],["Sell sim",s(e.sellSimulation??e.sellSim)],["Smart wallets",s(e.smartWalletOverlap)],["Risk",s(e.risk??e.riskStatus)],["Prepared ticket",s(e.preparedTicket??e.ticketStatus)],oe(e),R(e)],e)}function He(t={}){let e=t||{};return C(`ORACLE HIP-3 \u2014 ${s(e.market??e.coin??e.name)}`,[["Venue",`Hyperliquid builder-dex ${s(e.dex)}`],["Market",s(e.market??e.coin)],["Mark",h(e.markPx,{decimals:6})],["Oracle",h(e.oraclePx,{decimals:6})],["Funding",W(e.funding,{decimals:6})],["Open interest",h(e.openInterestUsd)],["Depth",s(e.depth)],["Liquidation notes",s(e.liquidationNotes??e.riskNotes)],["Account context",s(e.accountContext)],R(e)],e)}function Fe(t={}){let e=t||{};return C(`ORACLE HIP-4 \u2014 ${s(e.event??e.market??e.name)}`,[["Venue",`Hyperliquid HIP-4 ${s(e.dex??"outcome")}`],["Event",s(e.event)],["Outcome",s(e.outcome)],["Market id",A(e.marketId??e.market)],["Bid",h(e.bid,{decimals:6})],["Ask",h(e.ask,{decimals:6})],["Depth",s(e.depth)],["Edge",W(e.edge)],["Position",s(e.position)],R(e)],e)}function qe(t={}){let e=t||{};return C(`ORACLE POLYMARKET \u2014 ${s(e.event??e.market??e.name)}`,[["Venue","Polymarket CLOB"],["Event",s(e.event)],["Market",s(e.market)],["Market id",A(e.marketId??e.conditionId??e.tokenId)],["Yes",h(e.yesPrice,{decimals:4})],["No",h(e.noPrice,{decimals:4})],["Best bid / ask",`${h(e.bestBid,{decimals:4})} / ${h(e.bestAsk,{decimals:4})}`],["Volume",h(e.volumeUsd)],["Resolution risk",s(e.resolutionRisk)],["Order intent",s(e.orderIntent)],R(e)],e)}function ze(t={}){let e=t||{},r=m(e.completedSplits)&&m(e.totalSplits)?`${L(e.completedSplits,{decimals:0})} / ${L(e.totalSplits,{decimals:0})}`:u;return C(`ORACLE TWAP \u2014 ${s(e.pair??e.symbol??e.name)}`,[["Chain",E(e)],["Side",s(e.side??e.direction)],["Amount",`${s(T(e.amountTotal??e.amount,e.decimals??18))} ${s(e.symbol??"")}`.trim()],["Splits",`${L(e.totalSplits,{decimals:0})} over ${s(e.window)}`],["Progress",r],["Avg price",h(e.averagePrice,{decimals:6})],["Next split",s(e.nextSplitAt)],["Slippage cap",z(e.slippageBps)],["Status",s(e.status)],R(e)],e)}function Ve(t={}){let e=t||{},r=e.approval??e.revokeCheck??{},n=r.needsRevoke&&r.spender?`revoke.cash \u2014 ${s(r.spender)}`:r.needsRevoke===!1?"revoke.cash \u2014 clean":"revoke.cash \u2014 unchecked";return C(`ORACLE BRIDGE \u2014 ${s(e.pair??e.fromSymbol)} \u2192 ${s(e.toSymbol??"")}`.replace(/→ $/,""),[["Bridging","deBridge \xB7 LI.FI \u2014 best route wins"],["From chain",E({chainId:e.fromChainId,chain:e.fromChain})],["To chain",E({chainId:e.toChainId,chain:e.toChain})],["Amount",`${s(T(e.amount,e.fromDecimals??18))} ${s(e.fromSymbol??"")}`.trim()],["Best route",s(e.bestRoute??e.winner)],["Est. received",`${s(T(e.amountOut,e.toDecimals??18))} ${s(e.toSymbol??"")}`.trim()],["Fee",h(e.feeUsd)],["Est. time",s(e.estimatedTime)],["Revoke check",n],["All providers",s(e.providers?.join(", "))],["Preparable",s(e.preparable)],R(e)],e)}function We(t){let r=(Array.isArray(t)?t:[]).slice(1,4).map(n=>{let o=s(n.source??n.venue??n.name),a=n.improvementBps==null&&n.deltaBps==null?null:Number(n.improvementBps??n.deltaBps),i=Number.isFinite(a)?`${Math.abs(a).toFixed(0)} bps behind`:"spread UNKNOWN";return`${o} (${i})`});return r.length?r.join("; "):u}function Ke(t){let e=t.rankedOn??t.swap?.rankedOn??t.best?.rankedOn;return m(e)?s(e):u}function Je(t={}){let e=t||{},r=e.swap&&typeof e.swap=="object"?e.swap:e,n=e.bridge&&typeof e.bridge=="object"?e.bridge:null,o=r.best??r.winner??{},a=`${s(e.tokenInSymbol??e.fromSymbol??"IN")} \u2192 ${s(e.tokenOutSymbol??e.toSymbol??"OUT")}`,i=[["Intent",s(e.intent??"swap")],["Chain",E({chainId:e.chainId??r.chainId,chain:e.chain??r.chain})],["Pair",a],["Amount in",`${s(T(e.amountIn??r.amountIn,e.decimalsIn??18))} ${s(e.tokenInSymbol??"")}`.trim()],["Best swap",s(o.source??o.venue??r.bestRoute??e.bestRoute)],["Net out",`${s(T(o.netOut??o.amountOut??r.amountOut,e.decimalsOut??18))} ${s(e.tokenOutSymbol??"")}`.trim()],["Ranked on",Ke(r)],["Gas accounted",s(o.costAccounted===!0?"yes":o.costAccounted===!1?"no \u2014 gross ranking may flatter this route":null)],["Spread vs next",m(r.improvementBps)?`${s(r.improvementBps)} bps`:u],["Runners-up",We(r.routes??e.routes)]];if(n){let l=n.best??n.winner??{};i.push(["Best bridge",s(l.source??n.bestRoute??e.bestBridge)],["Bridge out",`${s(T(l.netOut??l.amountOut??n.amountOut,e.bridgeDecimalsOut??e.decimalsOut??18))} ${s(e.bridgeOutSymbol??e.tokenOutSymbol??"")}`.trim()],["Bridge to",E({chainId:n.toChainId??e.toChainId,chain:n.toChain??e.toChain})],["Est. time",s(n.estimatedTime??l.meta?.durationSeconds)])}else i.push(["Best bridge","same-chain \u2014 use Best swap"]);return i.push(["Preparable",s(e.preparable??o.executionReady)],R(e)),C(`ORACLE SWAP \u2014 ${a}`,i,e)}function Ge(t={}){let e=t||{};return C("ORACLE APPROVE \u2014 local signer",[["Pending id",A(e.id??(typeof e.digest=="string"?e.digest.slice(0,8):null))],["Surface",s(e.surface)],["Action",s(e.action)],["Chain",E({chainId:e.chain??e.chainId,chain:e.chainName})],["To",A(e.to??e.destination)],["Value",m(e.value)?s(e.value):u],["Signer",s(e.armed===!0?"running + armed":e.armed===!1?"running, disarmed":"not running")],R({confidence:e.confidence??(e.armed===!0?"high":"low")})],e)}var At=Object.freeze({token:je,launch:De,hip3:He,hip4:Fe,polymarket:qe,twap:ze,bridge:Ve,swap:Je,approve:Ge});var nt=Object.freeze(["deepen","refresh","prepare","ta","fa","long","short","allow","deny"]),it=new Set(nt),G=/^[a-z0-9-]{4,40}$/i,se=/^[0-9a-f]{32}$/,ce=/^\d+$/;function Y(t=process.env){return ae(t.ORACLE_CONFIG_DIR||ae(tt(),".config","oracle"),"telegram-cards.json")}function P(){return{links:{},artifacts:{},threads:{}}}var H=P();function X(){return H}function le(t,{readFile:e=Qe}={}){try{let r=JSON.parse(String(e(t)));H={links:r.links&&typeof r.links=="object"?r.links:{},artifacts:r.artifacts&&typeof r.artifacts=="object"?r.artifacts:{},threads:r.threads&&typeof r.threads=="object"?r.threads:{}}}catch{H=P()}return H}function ue(t,e=H,{writeFile:r=et,mkdir:n=Ze}={}){n(rt(t),{recursive:!0,mode:448}),r(t,JSON.stringify(e),{mode:384})}function I(t){return t==null?!1:typeof t=="string"?t.trim()!=="":!0}function de(t){return Ye("sha256").update(String(t)).digest("hex")}function J(t){if(Array.isArray(t))return t.map(J);if(!t||typeof t!="object")return t;let e={};for(let[r,n]of Object.entries(t))/(secret|token|key|seed|private|password|mnemonic|auth)/i.test(r)||(e[r]=J(n));return e}function ot(t){let r=String(t||"").trim().match(/^oracle:card:(deepen|refresh|prepare|ta|fa|long|short|allow|deny):([a-z0-9-]{4,40})$/i);return r?{action:r[1].toLowerCase(),artifactId:r[2].toLowerCase()}:null}function fe({platform:t="telegram",artifactId:e,openUrl:r,hasGrant:n=!1}={}){let o=String(e||"").trim().toLowerCase();if(!G.test(o))return{kind:"text_menu",text:"no artifact to continue",cancelHint:""};let a=[],i=[{text:"TA",callback_data:`oracle:card:ta:${o}`},{text:"FA",callback_data:`oracle:card:fa:${o}`}],l=p=>re(r,{side:p}),d=l("long"),c=l("short"),f=d&&c?[{text:"LONG",url:d},{text:"SHORT",url:c}]:[{text:"LONG",callback_data:`oracle:card:long:${o}`},{text:"SHORT",callback_data:`oracle:card:short:${o}`}];return I(r)?(a.push([{text:"Open",url:String(r)},i[0]]),a.push(f),a.push(n?[i[1],{text:"Prep",callback_data:`oracle:card:prepare:${o}`}]:[i[1]])):(a.push(i),a.push(f),n&&a.push([{text:"Prep",callback_data:`oracle:card:prepare:${o}`}])),String(t)==="telegram"?{kind:"inline_keyboard",replyMarkup:{inline_keyboard:a.filter(p=>p.length>0)},cancelHint:"LONG/SHORT open the graph. CONFIRM there. Telegram never sends."}:{kind:"text_menu",text:"TA / FA / LONG / SHORT",cancelHint:""}}function pe(t={}){let r=[`*${I(t.title)?s(t.title):"Oracle artifact"}*`,`Kind: ${I(t.kind)?s(t.kind):u}`,`Id: ${I(t.id)?`\`${String(t.id).replace(/`/g,"")}\``:u}`,`Summary: ${I(t.summary)?s(t.summary):u}`,`Confidence: ${K(t.confidence)}`];(I(t.source)||I(t.fetchedAt))&&r.push(`Source: ${s(t.source)} at ${s(t.fetchedAt)}`),Array.isArray(t.warnings)&&t.warnings.length&&r.push(`Warnings: ${t.warnings.map(o=>s(o)).join("; ")}`);let n=D(t);return r.push(n.allowed?"Actions: TA / FA / LONG / SHORT open the graph. Execute on CONFIRM there.":`Actions: TA / FA / LONG / SHORT \u2014 ${s(n.reason)}`),r.join(`
6
- `)}function at(t,e={},{now:r=Date.now()}={}){let n=t||P(),o=String(e.id||"").trim().toLowerCase();if(!G.test(o))throw new TypeError("artifact id required");let a={id:o,kind:String(e.kind||"thesis"),title:String(e.title||"Oracle artifact"),summary:String(e.summary||""),openUrl:I(e.openUrl)?String(e.openUrl):null,confidence:e.confidence,source:e.source||"oracle",fetchedAt:e.fetchedAt||new Date(r).toISOString(),warnings:Array.isArray(e.warnings)?e.warnings.map(String):[],payload:J(e.payload||{}),createdAt:new Date(r).toISOString()};return n.artifacts[o]=a,a}function Z(t,{chatId:e,artifactId:r,now:n=Date.now()}={}){let o=t||P(),a=String(e||"").trim(),i=String(r||"").trim().toLowerCase();if(!a)throw new TypeError("chat id required");if(!G.test(i))throw new TypeError("artifact id required");return o.threads[a]={artifactId:i,updatedAt:n},o.threads[a]}function me(t,{chatId:e,text:r}={}){let n=String(e||"").trim(),o=String(r||"").trim();if(!n||!o||/^\//.test(o))return null;let a=t?.threads?.[n];if(!a?.artifactId)return null;let i=t.artifacts?.[a.artifactId];return i?`Continue artifact ${i.id} (${i.kind}). Prior: ${i.summary||i.title}. User: ${o}`:null}function he(t,{ownerId:e,botUsername:r,now:n=Date.now(),ttlMs:o=600*1e3,token:a,randomBytes:i=Xe}={}){let l=t||P(),d=String(e||"").trim(),c=String(r||"").replace(/^@/,"").trim();if(!ce.test(d))throw new TypeError("owner Telegram id required");if(!/^[A-Za-z0-9_]{5,32}$/.test(c))throw new TypeError("bot username required");let f=a||i(16).toString("hex");if(!se.test(f))throw new TypeError("link token must be 32 hex chars");return l.links[de(f)]={ownerId:d,expiresAt:n+Number(o)},{token:f,url:`https://t.me/${c}?start=${f}`,expiresAt:n+Number(o)}}function ge(t,{token:e,telegramUserId:r,now:n=Date.now()}={}){let o=t||P(),a=String(e||"").trim(),i=String(r||"").trim();if(!se.test(a))return{ok:!1,error:"invalid start token"};if(!ce.test(i))return{ok:!1,error:"invalid telegram user"};let l=de(a),d=o.links[l];return d?(delete o.links[l],Number(d.expiresAt)<=n?{ok:!1,error:"start token expired"}:String(d.ownerId)!==i?{ok:!1,error:"start token is bound to a different owner"}:{ok:!0,ownerId:i}):{ok:!1,error:"unknown or already used start token"}}function ye(t,{data:e,chatId:r,grant:n=null,now:o=Date.now()}={}){let a=ot(e);if(!a)return null;if(!it.has(a.action))return{text:"That card action is not available.",buttons:null};let i=t?.artifacts?.[a.artifactId];if(!i)return{text:"That artifact is gone. Ask again and I will issue a new card.",buttons:null};r&&Z(t,{chatId:r,artifactId:i.id,now:o});let l=D({grant:n},{now:o}),d=fe({artifactId:i.id,openUrl:i.openUrl,hasGrant:l.allowed});return a.action==="refresh"?{text:pe(i),buttons:d,prompt:null}:a.action==="deepen"?{text:null,buttons:null,prompt:`Deepen artifact ${i.id} (${i.kind}). Prior: ${i.summary||i.title}. Be terse. Do not sign or broadcast.`}:a.action==="ta"?{text:null,buttons:null,prompt:`TA artifact ${i.id}. Prior: ${i.summary||i.title}. Run deterministic TA on the coin/venue in the artifact (RSI divergence, S/R, candle patterns). Reply in this Telegram chat with the verdict rows and say what was drawn. Do not sign or broadcast.`}:a.action==="fa"?{text:null,buttons:null,prompt:`FA artifact ${i.id}. Prior: ${i.summary||i.title}. Run per-coin FA (funding, OI, book, premium) plus the separate MACRO thesis (M1/M2/Fed BS/net liquidity) if relevant. Cite receipts. Stay in this Telegram chat. Do not sign or broadcast.`}:a.action==="allow"?{text:"Allow is the graph. Open the ticket there and CONFIRM. Telegram did not send.",buttons:null,prompt:null}:a.action==="deny"?{text:`Denied ${i.id}. Ticket cancelled. Nothing signed.`,buttons:null,prompt:null}:a.action==="long"||a.action==="short"?{text:null,buttons:null,prompt:`Open the live graph ticket for a ${a.action} on artifact ${i.id}. Prior: ${i.summary||i.title}. Size from the connected HL account. Execute only on CONFIRM on the graph. Never sign from Telegram.`}:l.allowed?{text:`Queued unsigned prepare for ${i.id}. Nothing signed. Allow/Deny still required.`,buttons:d,prompt:null,prepare:{artifactId:i.id,unsigned:!0,broadcast:!1}}:{text:`Prepare blocked \u2014 ${l.reason}. Deepen and Refresh still work.`,buttons:d,prompt:null}}function be(t={},{grant:e=null,now:r=Date.now(),state:n}={}){let o=n||X(),a=String(t.id||`art-${Math.abs(Number(r)).toString(36)}`).toLowerCase().slice(0,40),i=at(o,{...t,id:a},{now:r}),l=D({grant:e},{now:r});return{text:pe({...i,grant:e}),replyMarkup:fe({artifactId:i.id,openUrl:i.openUrl,hasGrant:l.allowed}).replyMarkup,artifact:i,state:o}}var xe=`oracle telegram \u2014 TrueNorth-style interactive cards (native, no Hermes)
2
+ import{createInterface as Ce}from"node:readline";var S=Object.freeze({maxRequestBytes:256*1024,maxResponseBytes:2*1024*1024,maxTools:256,maxToolNameLength:64,maxArgumentBytes:128*1024,defaultCallTimeoutMs:3e4,maxCallTimeoutMs:6e4,maxConcurrentCalls:32}),Ae=/^[A-Za-z0-9_-]{1,64}$/;function q(t,e){return{jsonrpc:"2.0",id:t??null,result:e}}function g(t,e,r){return{jsonrpc:"2.0",id:t??null,error:{code:e,message:r}}}function Re(t){return!!(t&&typeof t=="object"&&!Array.isArray(t)&&t.jsonrpc==="2.0"&&typeof t.method=="string"&&t.method.length>0)}function _e(t){if(!Array.isArray(t))return[];let e=[],r=new Set;for(let n of t){if(e.length>=S.maxTools)break;if(!n||typeof n!="object"||Array.isArray(n))continue;let o=typeof n.name=="string"?n.name.trim():"";if(!Ae.test(o)||r.has(o))continue;r.add(o);let a=n.inputSchema&&typeof n.inputSchema=="object"&&!Array.isArray(n.inputSchema)?{...n.inputSchema}:{type:"object",properties:{},additionalProperties:!1};a.type==="object"&&a.additionalProperties===void 0&&(a.additionalProperties=!1),e.push({...n,name:o,inputSchema:a})}return e}function Ne(t){let e=Number(t)||S.defaultCallTimeoutMs;return Math.min(Math.max(e,1),S.maxCallTimeoutMs)}async function Oe(t,e,r){let n;try{return await Promise.race([t,new Promise((o,a)=>{n=setTimeout(()=>{let i=new Error("tool call timed out");i.code="ORACLE_MCP_TIMEOUT",a(i);try{r?.()}catch{}},e)})])}finally{clearTimeout(n)}}function Ee(t){return t===null?"null":Array.isArray(t)?"array":Number.isInteger(t)?"integer":typeof t}function j(t,e,r="arguments",n=0){if(!e||typeof e!="object"||Array.isArray(e))return null;if(n>12)return`${r} exceeded the nesting limit`;if(Array.isArray(e.oneOf)&&e.oneOf.length&&!e.oneOf.some(a=>j(t,a,r,n+1)===null))return`${r} did not match an allowed shape`;if(Array.isArray(e.anyOf)&&e.anyOf.length&&!e.anyOf.some(a=>j(t,a,r,n+1)===null))return`${r} did not match a required alternative`;if(Array.isArray(e.enum)&&!e.enum.some(o=>Object.is(o,t)))return`${r} must be one of the allowed values`;if(Object.hasOwn(e,"const")&&!Object.is(e.const,t))return`${r} must equal the required constant`;if(e.type){let o=Ee(t);if(!(e.type==="number"?typeof t=="number"&&Number.isFinite(t):e.type==="integer"?Number.isSafeInteger(t):o===e.type))return`${r} must be ${e.type}`}if(typeof t=="string"){let o=Math.min(Number.isSafeInteger(e.maxLength)?e.maxLength:16384,16384);if(t.length>o)return`${r} exceeded the string limit`;if(Number.isSafeInteger(e.minLength)&&t.length<e.minLength)return`${r} is too short`}if(Array.isArray(t)){let o=Math.min(Number.isSafeInteger(e.maxItems)?e.maxItems:1e3,1e3);if(t.length>o)return`${r} exceeded the array limit`;if(Number.isSafeInteger(e.minItems)&&t.length<e.minItems)return`${r} has too few items`;if(e.items)for(let a=0;a<t.length;a+=1){let i=j(t[a],e.items,`${r}[${a}]`,n+1);if(i)return i}}if(t&&typeof t=="object"&&!Array.isArray(t)){let o=Object.keys(t);if(o.length>256)return`${r} exceeded the property limit`;let a=e.properties&&typeof e.properties=="object"?e.properties:{};for(let i of Array.isArray(e.required)?e.required:[])if(!Object.hasOwn(t,i))return`${r}.${i} is required`;if(e.additionalProperties===!1){let i=o.find(c=>!Object.hasOwn(a,c));if(i)return`${r}.${i} is not allowed`}for(let i of o){if(!Object.hasOwn(a,i))continue;let c=j(t[i],a[i],`${r}.${i}`,n+1);if(c)return c}}return null}function Ie(t,e={}){let r=_e(t?.tools),n=new Set(r.map(d=>d.name)),o=new Map(r.map(d=>[d.name,d])),a=typeof t?.name=="string"&&t.name?t.name.slice(0,80):"oracle-mcp",i=typeof t?.version=="string"&&t.version?t.version.slice(0,40):"1",c=Ne(e.callTimeoutMs),u=!1;return async function(f){let p=f?.id??null;if(!Re(f))return g(p,-32600,"invalid request");if(f.method==="initialize")return u=!0,q(p,{protocolVersion:f.params?.protocolVersion??"2025-03-26",capabilities:{tools:{}},serverInfo:{name:a,version:i}});if(f.method==="notifications/initialized")return null;if(f.method==="ping")return q(p,{});if(!u)return g(p,-32002,"server not initialized");if(f.method==="tools/list")return q(p,{tools:r});if(f.method==="tools/call"){let $=f.params?.name,w=f.params?.arguments??{};if(typeof $!="string"||!n.has($))return g(p,-32602,"unknown tool");if(!w||typeof w!="object"||Array.isArray(w))return g(p,-32602,"tool arguments must be an object");let N;try{N=JSON.stringify(w)}catch{return g(p,-32602,"tool arguments are not serializable")}if(Buffer.byteLength(N)>S.maxArgumentBytes)return g(p,-32602,"tool arguments exceeded the size limit");let P=j(w,o.get($)?.inputSchema);if(P)return g(p,-32602,P);try{let x=new AbortController,O=await Oe(Promise.resolve(t.call($,w,{signal:x.signal})),c,()=>x.abort(new Error("tool call timed out")));return q(p,O)}catch(x){if(x?.code==="ORACLE_MCP_TIMEOUT")return g(p,-32001,"tool call timed out");let O=typeof x?.message=="string"?x.message.replace(/\s+/g," ").trim():"",B=/\b(requires?|must be|missing|unknown|invalid|expected|unsupported|out of range|too (?:large|small|long|many)|not a|cannot convert)\b/i.test(O),F=/https?:\/\/|[/~][\w.-]+\/|0x[0-9a-fA-F]{8,}|[A-Za-z0-9+/_-]{24,}={0,2}|\b(?:secret|apikey|api[-_ ]key|private[-_ ]?key|token|password|credential|seed|mnemonic)s?\b/i.test(O.replace(/\btoken(?:In|Out|s\b)/g,"asset"));return B&&!F&&O.length<=200?g(p,-32e3,`tool call failed: ${O}`):g(p,-32e3,"tool call failed")}}return g(p,-32601,"method not found")}}function te(t,e={}){let r=e.input||process.stdin,n=e.output||process.stdout,o=Math.min(Math.max(Number(e.maxRequestBytes)||S.maxRequestBytes,64),S.maxRequestBytes),a=Math.min(Math.max(Number(e.maxResponseBytes)||S.maxResponseBytes,256),S.maxResponseBytes),i=Math.min(Math.max(Number(e.maxConcurrentCalls)||S.maxConcurrentCalls,1),S.maxConcurrentCalls),c=i*8,u=Ie(t,e),d={closed:!1,inflight:0},f=Ce({input:r,terminal:!1,crlfDelay:1/0}),p=0,$=[],w=!1,N=!1;function P(){if(d.closed||d.readerClosed)return;let y=d.inflight>=i||$.length>0||N;y&&!w?(w=!0,f.pause(),typeof r.pause=="function"&&r.pause()):!y&&w&&(w=!1,typeof r.resume=="function"&&r.resume(),f.resume())}function x(y){if(!y||d.closed)return;let k=JSON.stringify(y);Buffer.byteLength(k)>a&&(k=JSON.stringify(g(y.id,-32003,"response exceeded the size limit"))),n.write(`${k}
3
+ `)===!1&&!N&&(N=!0,P(),n.once("drain",()=>{N=!1,B()}))}function O(y){d.inflight+=1,P(),Promise.resolve(u(y)).then(x).catch(()=>x(g(y?.id,-32603,"internal error"))).finally(()=>{d.inflight-=1,B()})}function B(){for(;!d.closed&&!N&&d.inflight<i&&$.length>0;)O($.shift());P()}function F(){d.closed||(x(g(null,-32700,"request exceeded the size limit")),d.closed=!0,f.close(),typeof r.destroy=="function"&&r.destroy())}return r.on("data",y=>{if(d.closed)return;let k=String(y).split(`
4
+ `);for(let U=0;U<k.length;U+=1){if(p+=Buffer.byteLength(k[U]),p>o){F();return}U<k.length-1&&(p=0)}}),f.on("line",y=>{if(d.closed)return;if(Buffer.byteLength(y)>o){F();return}let k;try{k=JSON.parse(y)}catch{x(g(null,-32700,"parse error"));return}if($.length>=c){x(g(k?.id,-32e3,"server busy"));return}$.push(k),B()}),f.on("close",()=>{d.readerClosed=!0,e.exitOnClose!==!1&&(process.exitCode=0)}),d}import{createHash as Xe,randomBytes as Ze}from"node:crypto";import{mkdirSync as Qe,readFileSync as et,writeFileSync as tt}from"node:fs";import{homedir as rt}from"node:os";import{dirname as nt,join as ae}from"node:path";var Le=/^[A-Z0-9][A-Z0-9._-]{0,11}$/;function Te(t){let e=String(t||"").trim();if(!e||e.includes("ts.net")||!/^https:\/\//i.test(e))return null;try{return new URL(e)}catch{return null}}function re(t,{coin:e,side:r,sizeUsd:n,leverage:o,venue:a,confirm:i,user:c}={}){let u=Te(t);if(!u)return null;if(e&&Le.test(String(e).toUpperCase())&&u.searchParams.set("coin",String(e).toUpperCase()),(r==="long"||r==="short")&&u.searchParams.set("side",r),Number.isFinite(Number(n))&&Number(n)>=1&&u.searchParams.set("size",String(Math.min(1e5,Math.round(Number(n))))),Number.isInteger(Number(o))&&Number(o)>=1&&u.searchParams.set("lev",String(Math.min(50,Number(o)))),a){let d=String(a).toLowerCase()==="hl"?"hyperliquid":String(a).toLowerCase();u.searchParams.set("venue",d)}else u.searchParams.get("venue")||u.searchParams.set("venue","hyperliquid");return u.searchParams.set("view","perps"),u.searchParams.set("build","1"),i&&/^[0-9a-f]{32}$/i.test(String(i))&&u.searchParams.set("confirm",String(i).toLowerCase()),c&&/^0x[0-9a-fA-F]{40}$/.test(String(c))&&u.searchParams.set("user",String(c).toLowerCase()),u.toString()}var Pe={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},Me=new Map(Object.values(Pe).map(t=>[t.chainId,t]));function ne(t){return Me.get(Number(t))||null}var At=Object.freeze([100,50,25]),Rt=Object.freeze([100,50,25,10]);var l="UNKNOWN",It=Object.freeze(["token","launch","hip3","hip4","polymarket","twap","bridge","swap","approve"]),ve=/[_*[\]`]/g;function s(t){return m(t)?String(t).replace(ve,e=>`\\${e}`):l}function m(t){return t==null?!1:typeof t=="number"?Number.isFinite(t):typeof t=="string"?t.trim()!=="":!0}function C(t){if(!m(t))return l;let e=String(t).replace(/`/g,"");return e===""?l:`\`${e}\``}function L(t,{decimals:e=2}={}){if(!m(t))return l;let r=Number(t);return Number.isFinite(r)?r.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:e}):l}function h(t,{decimals:e=2}={}){let r=L(t,{decimals:e});return r===l?l:`${r} USD`}function W(t,{decimals:e=2}={}){let r=L(t,{decimals:e});return r===l?l:`${r}%`}function z(t){let e=L(t,{decimals:0});return e===l?l:`${e} bps`}function T(t,e){if(!m(t))return l;let r=Number(e);if(!Number.isInteger(r)||r<0||r>77)return l;let n;try{n=BigInt(typeof t=="string"?t.trim():t)}catch{return l}let o=n<0n,a=o?-n:n,i=10n**BigInt(r),c=(a/i).toString(),u=(a%i).toString().padStart(r,"0").replace(/0+$/,"");return`${o?"-":""}${c}${u?`.${u}`:""}`}function K(t){if(typeof t=="number"&&Number.isFinite(t))return t<0||t>1?l:t>=.75?"HIGH":t>=.4?"MEDIUM":"LOW";if(typeof t=="string"){let e=t.trim().toUpperCase();if(e==="HIGH"||e==="MEDIUM"||e==="LOW")return e}return l}function E(t={}){let e=t.chainId;if(!m(e)||!Number.isFinite(Number(e)))return m(t.chain)?s(t.chain):l;let n=ne(e)?.name||(m(t.chain)?String(t.chain):l);return`${s(n)} (chainId ${Number(e)})`}function ie(t={}){return s(t.venue??t.dex??t.pool?.venue)}function Be(t){return t==null?"NONE (text card only)":typeof t=="string"?t.trim()?C(t):"NONE (text card only)":t.error||t.ok===!1||t.available===!1?`UNAVAILABLE${m(t.error)?` \u2014 ${s(t.error)}`:""} (text card stands)`:m(t.url)?C(t.url):"NONE (text card only)"}function H(t={},{now:e=Date.now()}={}){let r=t.grant??t.session??null;if(!r||typeof r!="object")return{allowed:!1,reason:"no local grant/session",actions:[]};if(r.local===!1)return{allowed:!1,reason:"grant is not local",actions:[]};if(r.revoked===!0)return{allowed:!1,reason:"grant revoked",actions:[]};let n=r.expiresAt??r.expiry;if(m(n)){let a=typeof n=="number"?n:Date.parse(n);if(!Number.isFinite(a))return{allowed:!1,reason:"grant expiry unreadable",actions:[]};if(a<=e)return{allowed:!1,reason:"grant expired",actions:[]}}return{allowed:!0,reason:"valid local grant",actions:Array.isArray(r.actions)&&r.actions.length?r.actions.slice():["BUY","SELL"]}}function Ue(t){let e=H(t);return e.allowed?`${e.actions.map(r=>s(r)).join(" / ")} (${s(e.reason)})`:`prepare-only \u2014 ${s(e.reason)}`}function A(t,e,r={}){let n=[`*${t}*`];for(let[o,a]of e)n.push(`${o}: ${a==null||a===""?l:a}`);return n.push(`Chart: ${Be(r.chart)}`),n.push(`Actions: ${Ue(r)}`),Array.isArray(r.warnings)&&r.warnings.length&&n.push(`Warnings: ${r.warnings.map(o=>s(o)).join("; ")}`),(m(r.source)||m(r.fetchedAt))&&n.push(`Source: ${s(r.source)} at ${s(r.fetchedAt)}`),n.join(`
5
+ `)}function R(t){return["Confidence",K(t.confidence)]}function je(t){let e=t.quote;if(!e||typeof e!="object")return[];let r=m(e.decimals)?T(e.amountOutRaw??e.out??e.raw,e.decimals):l;return[["Quote out (raw)",C(e.amountOutRaw??e.out??e.raw)],["Quote out",r===l?l:`${s(r)} ${s(e.symbol??"")}`.trim()]]}function oe(t){let e=t.autoSlippage;if(!e||typeof e!="object")return["Auto-slippage",l];let r=z(e.selectedBps),n=z(e.capBps);return["Auto-slippage",r===l&&n===l?l:`${r} selected, cap ${n}`]}function He(t={}){let e=t||{};return A(`ORACLE TOKEN \u2014 ${s(e.symbol??e.token??e.name)}`,[["Chain",E(e)],["Venue",ie(e)],["Name",s(e.name)],["Address",C(e.address??e.mint??e.contract)],["Price",h(e.priceUsd,{decimals:8})],["Market cap",h(e.marketCapUsd)],["Liquidity",h(e.liquidityUsd)],["Volume 24h",h(e.volume24hUsd)],["Change 24h",W(e.priceChange24h)],["Fee tier",m(e.feeTier)?`${z(Number(e.feeTier)/100)} (${L(e.feeTier,{decimals:0})})`:l],["Age",s(e.age)],...je(e),oe(e),R(e)],e)}function De(t={}){let e=t||{};return A(`ORACLE LAUNCH \u2014 ${s(e.symbol??e.token??e.name)}`,[["Chain",E(e)],["Venue",ie(e)],["Address",C(e.address??e.mint??e.contract)],["Pool",C(e.pool?.address??e.poolAddress??e.pool)],["Liquidity",h(e.liquidityUsd)],["Route ready",s(e.routeReady)],["Sellable",s(e.sellable)],["Sell sim",s(e.sellSimulation??e.sellSim)],["Smart wallets",s(e.smartWalletOverlap)],["Risk",s(e.risk??e.riskStatus)],["Prepared ticket",s(e.preparedTicket??e.ticketStatus)],oe(e),R(e)],e)}function Fe(t={}){let e=t||{};return A(`ORACLE HIP-3 \u2014 ${s(e.market??e.coin??e.name)}`,[["Venue",`Hyperliquid builder-dex ${s(e.dex)}`],["Market",s(e.market??e.coin)],["Mark",h(e.markPx,{decimals:6})],["Oracle",h(e.oraclePx,{decimals:6})],["Funding",W(e.funding,{decimals:6})],["Open interest",h(e.openInterestUsd)],["Depth",s(e.depth)],["Liquidation notes",s(e.liquidationNotes??e.riskNotes)],["Account context",s(e.accountContext)],R(e)],e)}function qe(t={}){let e=t||{};return A(`ORACLE HIP-4 \u2014 ${s(e.event??e.market??e.name)}`,[["Venue",`Hyperliquid HIP-4 ${s(e.dex??"outcome")}`],["Event",s(e.event)],["Outcome",s(e.outcome)],["Market id",C(e.marketId??e.market)],["Bid",h(e.bid,{decimals:6})],["Ask",h(e.ask,{decimals:6})],["Depth",s(e.depth)],["Edge",W(e.edge)],["Position",s(e.position)],R(e)],e)}function ze(t={}){let e=t||{};return A(`ORACLE POLYMARKET \u2014 ${s(e.event??e.market??e.name)}`,[["Venue","Polymarket CLOB"],["Event",s(e.event)],["Market",s(e.market)],["Market id",C(e.marketId??e.conditionId??e.tokenId)],["Yes",h(e.yesPrice,{decimals:4})],["No",h(e.noPrice,{decimals:4})],["Best bid / ask",`${h(e.bestBid,{decimals:4})} / ${h(e.bestAsk,{decimals:4})}`],["Volume",h(e.volumeUsd)],["Resolution risk",s(e.resolutionRisk)],["Order intent",s(e.orderIntent)],R(e)],e)}function Ve(t={}){let e=t||{},r=m(e.completedSplits)&&m(e.totalSplits)?`${L(e.completedSplits,{decimals:0})} / ${L(e.totalSplits,{decimals:0})}`:l;return A(`ORACLE TWAP \u2014 ${s(e.pair??e.symbol??e.name)}`,[["Chain",E(e)],["Side",s(e.side??e.direction)],["Amount",`${s(T(e.amountTotal??e.amount,e.decimals??18))} ${s(e.symbol??"")}`.trim()],["Splits",`${L(e.totalSplits,{decimals:0})} over ${s(e.window)}`],["Progress",r],["Avg price",h(e.averagePrice,{decimals:6})],["Next split",s(e.nextSplitAt)],["Slippage cap",z(e.slippageBps)],["Status",s(e.status)],R(e)],e)}function We(t={}){let e=t||{},r=e.approval??e.revokeCheck??{},n=r.needsRevoke&&r.spender?`revoke.cash \u2014 ${s(r.spender)}`:r.needsRevoke===!1?"revoke.cash \u2014 clean":"revoke.cash \u2014 unchecked";return A(`ORACLE BRIDGE \u2014 ${s(e.pair??e.fromSymbol)} \u2192 ${s(e.toSymbol??"")}`.replace(/→ $/,""),[["Bridging","deBridge \xB7 LI.FI \u2014 best route wins"],["From chain",E({chainId:e.fromChainId,chain:e.fromChain})],["To chain",E({chainId:e.toChainId,chain:e.toChain})],["Amount",`${s(T(e.amount,e.fromDecimals??18))} ${s(e.fromSymbol??"")}`.trim()],["Best route",s(e.bestRoute??e.winner)],["Est. received",`${s(T(e.amountOut,e.toDecimals??18))} ${s(e.toSymbol??"")}`.trim()],["Fee",h(e.feeUsd)],["Est. time",s(e.estimatedTime)],["Revoke check",n],["All providers",s(e.providers?.join(", "))],["Preparable",s(e.preparable)],R(e)],e)}function Ke(t){let r=(Array.isArray(t)?t:[]).slice(1,4).map(n=>{let o=s(n.source??n.venue??n.name),a=n.improvementBps==null&&n.deltaBps==null?null:Number(n.improvementBps??n.deltaBps),i=Number.isFinite(a)?`${Math.abs(a).toFixed(0)} bps behind`:"spread UNKNOWN";return`${o} (${i})`});return r.length?r.join("; "):l}function Je(t){let e=t.rankedOn??t.swap?.rankedOn??t.best?.rankedOn;return m(e)?s(e):l}function Ye(t={}){let e=t||{},r=e.swap&&typeof e.swap=="object"?e.swap:e,n=e.bridge&&typeof e.bridge=="object"?e.bridge:null,o=r.best??r.winner??{},a=`${s(e.tokenInSymbol??e.fromSymbol??"IN")} \u2192 ${s(e.tokenOutSymbol??e.toSymbol??"OUT")}`,i=[["Intent",s(e.intent??"swap")],["Chain",E({chainId:e.chainId??r.chainId,chain:e.chain??r.chain})],["Pair",a],["Amount in",`${s(T(e.amountIn??r.amountIn,e.decimalsIn??18))} ${s(e.tokenInSymbol??"")}`.trim()],["Best swap",s(o.source??o.venue??r.bestRoute??e.bestRoute)],["Net out",`${s(T(o.netOut??o.amountOut??r.amountOut,e.decimalsOut??18))} ${s(e.tokenOutSymbol??"")}`.trim()],["Ranked on",Je(r)],["Gas accounted",s(o.costAccounted===!0?"yes":o.costAccounted===!1?"no \u2014 gross ranking may flatter this route":null)],["Spread vs next",m(r.improvementBps)?`${s(r.improvementBps)} bps`:l],["Runners-up",Ke(r.routes??e.routes)]];if(n){let c=n.best??n.winner??{};i.push(["Best bridge",s(c.source??n.bestRoute??e.bestBridge)],["Bridge out",`${s(T(c.netOut??c.amountOut??n.amountOut,e.bridgeDecimalsOut??e.decimalsOut??18))} ${s(e.bridgeOutSymbol??e.tokenOutSymbol??"")}`.trim()],["Bridge to",E({chainId:n.toChainId??e.toChainId,chain:n.toChain??e.toChain})],["Est. time",s(n.estimatedTime??c.meta?.durationSeconds)])}else i.push(["Best bridge","same-chain \u2014 use Best swap"]);return i.push(["Preparable",s(e.preparable??o.executionReady)],R(e)),A(`ORACLE SWAP \u2014 ${a}`,i,e)}function Ge(t={}){let e=t||{};return A("ORACLE APPROVE \u2014 local signer",[["Pending id",C(e.id??(typeof e.digest=="string"?e.digest.slice(0,8):null))],["Surface",s(e.surface)],["Action",s(e.action)],["Chain",E({chainId:e.chain??e.chainId,chain:e.chainName})],["To",C(e.to??e.destination)],["Value",m(e.value)?s(e.value):l],["Signer",s(e.armed===!0?"running + armed":e.armed===!1?"running, disarmed":"not running")],R({confidence:e.confidence??(e.armed===!0?"high":"low")})],e)}var Lt=Object.freeze({token:He,launch:De,hip3:Fe,hip4:qe,polymarket:ze,twap:Ve,bridge:We,swap:Ye,approve:Ge});var it=Object.freeze(["deepen","refresh","prepare","ta","fa","long","short","allow","deny"]),ot=new Set(it),Y=/^[a-z0-9-]{4,40}$/i,se=/^[0-9a-f]{32}$/,ce=/^\d+$/;function G(t=process.env){return ae(t.ORACLE_CONFIG_DIR||ae(rt(),".config","oracle"),"telegram-cards.json")}function M(){return{links:{},artifacts:{},threads:{}}}var D=M();function X(){return D}function le(t,{readFile:e=et}={}){try{let r=JSON.parse(String(e(t)));D={links:r.links&&typeof r.links=="object"?r.links:{},artifacts:r.artifacts&&typeof r.artifacts=="object"?r.artifacts:{},threads:r.threads&&typeof r.threads=="object"?r.threads:{}}}catch{D=M()}return D}function ue(t,e=D,{writeFile:r=tt,mkdir:n=Qe}={}){n(nt(t),{recursive:!0,mode:448}),r(t,JSON.stringify(e),{mode:384})}function I(t){return t==null?!1:typeof t=="string"?t.trim()!=="":!0}function de(t){return Xe("sha256").update(String(t)).digest("hex")}function J(t){if(Array.isArray(t))return t.map(J);if(!t||typeof t!="object")return t;let e={};for(let[r,n]of Object.entries(t))/(secret|token|key|seed|private|password|mnemonic|auth)/i.test(r)||(e[r]=J(n));return e}function at(t){let r=String(t||"").trim().match(/^oracle:card:(deepen|refresh|prepare|ta|fa|long|short|allow|deny):([a-z0-9-]{4,40})$/i);return r?{action:r[1].toLowerCase(),artifactId:r[2].toLowerCase()}:null}function fe({platform:t="telegram",artifactId:e,openUrl:r,hasGrant:n=!1}={}){let o=String(e||"").trim().toLowerCase();if(!Y.test(o))return{kind:"text_menu",text:"no artifact to continue",cancelHint:""};let a=[],i=[{text:"TA",callback_data:`oracle:card:ta:${o}`},{text:"FA",callback_data:`oracle:card:fa:${o}`}],c=p=>re(r,{side:p}),u=c("long"),d=c("short"),f=u&&d?[{text:"LONG",url:u},{text:"SHORT",url:d}]:[{text:"LONG",callback_data:`oracle:card:long:${o}`},{text:"SHORT",callback_data:`oracle:card:short:${o}`}];return I(r)?(a.push([{text:"Open",url:String(r)},i[0]]),a.push(f),a.push(n?[i[1],{text:"Prep",callback_data:`oracle:card:prepare:${o}`}]:[i[1]])):(a.push(i),a.push(f),n&&a.push([{text:"Prep",callback_data:`oracle:card:prepare:${o}`}])),String(t)==="telegram"?{kind:"inline_keyboard",replyMarkup:{inline_keyboard:a.filter(p=>p.length>0)},cancelHint:"LONG/SHORT open the graph. CONFIRM there. Telegram never sends."}:{kind:"text_menu",text:"TA / FA / LONG / SHORT",cancelHint:""}}function pe(t={}){let r=[`*${I(t.title)?s(t.title):"Oracle artifact"}*`,`Kind: ${I(t.kind)?s(t.kind):l}`,`Id: ${I(t.id)?`\`${String(t.id).replace(/`/g,"")}\``:l}`,`Summary: ${I(t.summary)?s(t.summary):l}`,`Confidence: ${K(t.confidence)}`];(I(t.source)||I(t.fetchedAt))&&r.push(`Source: ${s(t.source)} at ${s(t.fetchedAt)}`),Array.isArray(t.warnings)&&t.warnings.length&&r.push(`Warnings: ${t.warnings.map(o=>s(o)).join("; ")}`);let n=H(t);return r.push(n.allowed?"Actions: TA / FA / LONG / SHORT open the graph. Execute on CONFIRM there.":`Actions: TA / FA / LONG / SHORT \u2014 ${s(n.reason)}`),r.join(`
6
+ `)}function st(t,e={},{now:r=Date.now()}={}){let n=t||M(),o=String(e.id||"").trim().toLowerCase();if(!Y.test(o))throw new TypeError("artifact id required");let a={id:o,kind:String(e.kind||"thesis"),title:String(e.title||"Oracle artifact"),summary:String(e.summary||""),openUrl:I(e.openUrl)?String(e.openUrl):null,confidence:e.confidence,source:e.source||"oracle",fetchedAt:e.fetchedAt||new Date(r).toISOString(),warnings:Array.isArray(e.warnings)?e.warnings.map(String):[],payload:J(e.payload||{}),createdAt:new Date(r).toISOString()};return n.artifacts[o]=a,a}function Z(t,{chatId:e,artifactId:r,now:n=Date.now()}={}){let o=t||M(),a=String(e||"").trim(),i=String(r||"").trim().toLowerCase();if(!a)throw new TypeError("chat id required");if(!Y.test(i))throw new TypeError("artifact id required");return o.threads[a]={artifactId:i,updatedAt:n},o.threads[a]}function me(t,{chatId:e,text:r}={}){let n=String(e||"").trim(),o=String(r||"").trim();if(!n||!o||/^\//.test(o))return null;let a=t?.threads?.[n];if(!a?.artifactId)return null;let i=t.artifacts?.[a.artifactId];return i?`Continue artifact ${i.id} (${i.kind}). Prior: ${i.summary||i.title}. User: ${o}`:null}function he(t,{ownerId:e,botUsername:r,now:n=Date.now(),ttlMs:o=600*1e3,token:a,randomBytes:i=Ze}={}){let c=t||M(),u=String(e||"").trim(),d=String(r||"").replace(/^@/,"").trim();if(!ce.test(u))throw new TypeError("owner Telegram id required");if(!/^[A-Za-z0-9_]{5,32}$/.test(d))throw new TypeError("bot username required");let f=a||i(16).toString("hex");if(!se.test(f))throw new TypeError("link token must be 32 hex chars");return c.links[de(f)]={ownerId:u,expiresAt:n+Number(o)},{token:f,url:`https://t.me/${d}?start=${f}`,expiresAt:n+Number(o)}}function ge(t,{token:e,telegramUserId:r,now:n=Date.now()}={}){let o=t||M(),a=String(e||"").trim(),i=String(r||"").trim();if(!se.test(a))return{ok:!1,error:"invalid start token"};if(!ce.test(i))return{ok:!1,error:"invalid telegram user"};let c=de(a),u=o.links[c];return u?(delete o.links[c],Number(u.expiresAt)<=n?{ok:!1,error:"start token expired"}:String(u.ownerId)!==i?{ok:!1,error:"start token is bound to a different owner"}:{ok:!0,ownerId:i}):{ok:!1,error:"unknown or already used start token"}}function ye(t,{data:e,chatId:r,grant:n=null,now:o=Date.now()}={}){let a=at(e);if(!a)return null;if(!ot.has(a.action))return{text:"That card action is not available.",buttons:null};let i=t?.artifacts?.[a.artifactId];if(!i)return{text:"That artifact is gone. Ask again and I will issue a new card.",buttons:null};r&&Z(t,{chatId:r,artifactId:i.id,now:o});let c=H({grant:n},{now:o}),u=fe({artifactId:i.id,openUrl:i.openUrl,hasGrant:c.allowed});return a.action==="refresh"?{text:pe(i),buttons:u,prompt:null}:a.action==="deepen"?{text:null,buttons:null,prompt:`Deepen artifact ${i.id} (${i.kind}). Prior: ${i.summary||i.title}. Be terse. Do not sign or broadcast.`}:a.action==="ta"?{text:null,buttons:null,prompt:`TA artifact ${i.id}. Prior: ${i.summary||i.title}. Run deterministic TA on the coin/venue in the artifact (RSI divergence, S/R, candle patterns). Reply in this Telegram chat with the verdict rows and say what was drawn. Do not sign or broadcast.`}:a.action==="fa"?{text:null,buttons:null,prompt:`FA artifact ${i.id}. Prior: ${i.summary||i.title}. Run per-coin FA (funding, OI, book, premium) plus the separate MACRO thesis (M1/M2/Fed BS/net liquidity) if relevant. Cite receipts. Stay in this Telegram chat. Do not sign or broadcast.`}:a.action==="allow"?{text:"Allow is the graph. Open the ticket there and CONFIRM. Telegram did not send.",buttons:null,prompt:null}:a.action==="deny"?{text:`Denied ${i.id}. Ticket cancelled. Nothing signed.`,buttons:null,prompt:null}:a.action==="long"||a.action==="short"?{text:null,buttons:null,prompt:`Open the live graph ticket for a ${a.action} on artifact ${i.id}. Prior: ${i.summary||i.title}. Size from the connected HL account. Execute only on CONFIRM on the graph. Never sign from Telegram.`}:c.allowed?{text:`Queued unsigned prepare for ${i.id}. Nothing signed. Allow/Deny still required.`,buttons:u,prompt:null,prepare:{artifactId:i.id,unsigned:!0,broadcast:!1}}:{text:`Prepare blocked \u2014 ${c.reason}. Deepen and Refresh still work.`,buttons:u,prompt:null}}function be(t={},{grant:e=null,now:r=Date.now(),state:n}={}){let o=n||X(),a=String(t.id||`art-${Math.abs(Number(r)).toString(36)}`).toLowerCase().slice(0,40),i=st(o,{...t,id:a},{now:r}),c=H({grant:e},{now:r});return{text:pe({...i,grant:e}),replyMarkup:fe({artifactId:i.id,openUrl:i.openUrl,hasGrant:c.allowed}).replyMarkup,artifact:i,state:o}}var xe=`oracle telegram \u2014 TrueNorth-style interactive cards (native, no Hermes)
7
7
 
8
8
  oracle telegram link --owner <tg-id> --bot <username>
9
9
  oracle telegram redeem --token <32hex> --user <tg-id>
@@ -13,10 +13,10 @@ import{createInterface as Ae}from"node:readline";var S=Object.freeze({maxRequest
13
13
 
14
14
  Native oracle-gateway uses the same module. Hermes is an optional adapter that
15
15
  must call this CLI instead of owning card state. Prepare is unsigned. Execute
16
- stays on Allow/Deny.`;function b(t,e){let r=t.indexOf(e);return r<0||r+1>=t.length?null:t[r+1]}function we(t,e){return t.includes(e)}function st(){return le(Y()),X()}function V(t){ue(Y(),t)}function M(t,e){t.write(JSON.stringify(e)+`
16
+ stays on Allow/Deny.`;function b(t,e){let r=t.indexOf(e);return r<0||r+1>=t.length?null:t[r+1]}function we(t,e){return t.includes(e)}function ct(){return le(G()),X()}function V(t){ue(G(),t)}function v(t,e){t.write(JSON.stringify(e)+`
17
17
  `)}async function ke(t=[],e={}){let r=e.out??process.stdout,n=e.err??process.stderr,o=t[0];if(!o||o==="--help"||o==="-h"||o==="help")return r.write(xe+`
18
- `),0;let a=st();if(o==="link")try{let i=he(a,{ownerId:b(t,"--owner"),botUsername:b(t,"--bot")});return V(a),M(r,{ok:!0,...i}),0}catch(i){return n.write(String(i.message||i)+`
19
- `),1}if(o==="redeem"){let i=ge(a,{token:b(t,"--token"),telegramUserId:b(t,"--user")});return V(a),M(r,i),i.ok?0:1}if(o==="wrap")try{let i=be({id:b(t,"--id"),kind:b(t,"--kind")||"thesis",title:b(t,"--title")||"Oracle artifact",summary:b(t,"--summary")||"",openUrl:b(t,"--url"),source:"oracle-telegram"},{grant:we(t,"--grant")?{local:!0}:null,state:a}),l=b(t,"--chat");return l&&Z(a,{chatId:l,artifactId:i.artifact.id}),V(a),M(r,{ok:!0,text:i.text,replyMarkup:i.replyMarkup||null,artifactId:i.artifact.id,fallback:`Reply: deepen ${i.artifact.id} | refresh ${i.artifact.id}`}),0}catch(i){return n.write(String(i.message||i)+`
20
- `),1}if(o==="callback"){let i=ye(a,{data:b(t,"--data"),chatId:b(t,"--chat"),grant:we(t,"--grant")?{local:!0}:null});return V(a),i?(M(r,{ok:!0,...i}),0):(M(r,{ok:!1,error:"not an interactive card callback"}),1)}if(o==="continue"){let i=me(a,{chatId:b(t,"--chat"),text:b(t,"--text")});return M(r,{ok:!0,prompt:i}),0}return n.write(`unknown telegram verb '${o}'
18
+ `),0;let a=ct();if(o==="link")try{let i=he(a,{ownerId:b(t,"--owner"),botUsername:b(t,"--bot")});return V(a),v(r,{ok:!0,...i}),0}catch(i){return n.write(String(i.message||i)+`
19
+ `),1}if(o==="redeem"){let i=ge(a,{token:b(t,"--token"),telegramUserId:b(t,"--user")});return V(a),v(r,i),i.ok?0:1}if(o==="wrap")try{let i=be({id:b(t,"--id"),kind:b(t,"--kind")||"thesis",title:b(t,"--title")||"Oracle artifact",summary:b(t,"--summary")||"",openUrl:b(t,"--url"),source:"oracle-telegram"},{grant:we(t,"--grant")?{local:!0}:null,state:a}),c=b(t,"--chat");return c&&Z(a,{chatId:c,artifactId:i.artifact.id}),V(a),v(r,{ok:!0,text:i.text,replyMarkup:i.replyMarkup||null,artifactId:i.artifact.id,fallback:`Reply: deepen ${i.artifact.id} | refresh ${i.artifact.id}`}),0}catch(i){return n.write(String(i.message||i)+`
20
+ `),1}if(o==="callback"){let i=ye(a,{data:b(t,"--data"),chatId:b(t,"--chat"),grant:we(t,"--grant")?{local:!0}:null});return V(a),i?(v(r,{ok:!0,...i}),0):(v(r,{ok:!1,error:"not an interactive card callback"}),1)}if(o==="continue"){let i=me(a,{chatId:b(t,"--chat"),text:b(t,"--text")});return v(r,{ok:!0,prompt:i}),0}return n.write(`unknown telegram verb '${o}'
21
21
  ${xe}
22
- `),1}var ct=40,lt=200,ut=4e3,dt=4e3,ft=128,$e=/^[a-z0-9][a-z0-9-]{3,39}$/i,Q=/^\d{1,20}$/,pt=/^oracle:card:(deepen|refresh|prepare|ta|fa|long|short|allow|deny):[a-z0-9][a-z0-9-]{3,39}$/i;function mt(t=process.env){return t.ORACLE_TELEGRAM_CARD_GRANT==="1"?{local:!0}:null}function _(t,{field:e,max:r,pattern:n}){if(typeof t!="string")throw new Error(`${e} must be a string`);let o=t.trim();if(!o)throw new Error(`${e} is required`);if(o.length>r)throw new Error(`${e} exceeds ${r} chars`);if(n&&!n.test(o))throw new Error(`${e} is malformed`);return o}function ht(){let t="",e="";return{io:{out:{write(r){return t+=String(r),!0}},err:{write(r){return e+=String(r),!0}}},stdout(){return t},stderr(){return e}}}async function ee(t){let e=ht(),r=await ke(t,e.io),n;try{n=JSON.parse(e.stdout()||"{}")}catch{n={text:e.stdout()}}return r!==0&&!n.error&&(n.error=e.stderr()||"telegram command failed"),{content:[{type:"text",text:JSON.stringify({code:r,...n})}]}}function Se(t){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:t})}]}}var gt=[{name:"telegram_wrap",description:"Wrap a scan/quote/thesis as a TrueNorth-style Oracle artifact card. Prepare stays unsigned. No Execute button.",inputSchema:{type:"object",required:["id","title","summary"],properties:{id:{type:"string",description:"artifact id, [a-z0-9-]{4,40}"},title:{type:"string"},summary:{type:"string"},kind:{type:"string"},chat:{type:"string",description:"Telegram chat id, digits only"}}}},{name:"telegram_callback",description:"Handle deepen/refresh/prepare on an Oracle artifact card. Prepare is unsigned. Execute stays on Allow/Deny.",inputSchema:{type:"object",required:["data","chat"],properties:{data:{type:"string",description:"oracle:card:<action>:<id>"},chat:{type:"string"}}}},{name:"telegram_continue",description:"Continue the last artifact thread for this Telegram chat.",inputSchema:{type:"object",required:["chat","text"],properties:{chat:{type:"string"},text:{type:"string"}}}}],yt={name:"oracle-telegram",version:"2",tools:gt,async call(t,e={},{env:r=process.env}={}){let n=mt(r);try{if(t==="telegram_wrap"){let o=["wrap","--id",_(e.id,{field:"id",max:ct,pattern:$e}),"--title",_(e.title,{field:"title",max:lt}),"--summary",_(e.summary,{field:"summary",max:ut})];return e.kind!==void 0&&o.push("--kind",_(e.kind,{field:"kind",max:40,pattern:$e})),e.chat!==void 0&&o.push("--chat",_(e.chat,{field:"chat",max:20,pattern:Q})),n&&o.push("--grant"),await ee(o)}if(t==="telegram_callback"){let o=["callback","--data",_(e.data,{field:"data",max:ft,pattern:pt}),"--chat",_(e.chat,{field:"chat",max:20,pattern:Q})];return n&&o.push("--grant"),await ee(o)}if(t==="telegram_continue")return await ee(["continue","--chat",_(e.chat,{field:"chat",max:20,pattern:Q}),"--text",_(e.text,{field:"text",max:dt})])}catch(o){return Se(o.message)}return Se("unknown tool")}};process.argv[1]&&process.argv[1].endsWith("oracle-telegram-mcp.mjs")&&te(yt);export{mt as grantFromEnv,yt as server};
22
+ `),1}var lt=40,ut=200,dt=4e3,ft=4e3,pt=128,$e=/^[a-z0-9][a-z0-9-]{3,39}$/i,Q=/^\d{1,20}$/,mt=/^oracle:card:(deepen|refresh|prepare|ta|fa|long|short|allow|deny):[a-z0-9][a-z0-9-]{3,39}$/i;function ht(t=process.env){return t.ORACLE_TELEGRAM_CARD_GRANT==="1"?{local:!0}:null}function _(t,{field:e,max:r,pattern:n}){if(typeof t!="string")throw new Error(`${e} must be a string`);let o=t.trim();if(!o)throw new Error(`${e} is required`);if(o.length>r)throw new Error(`${e} exceeds ${r} chars`);if(n&&!n.test(o))throw new Error(`${e} is malformed`);return o}function gt(){let t="",e="";return{io:{out:{write(r){return t+=String(r),!0}},err:{write(r){return e+=String(r),!0}}},stdout(){return t},stderr(){return e}}}async function ee(t){let e=gt(),r=await ke(t,e.io),n;try{n=JSON.parse(e.stdout()||"{}")}catch{n={text:e.stdout()}}return r!==0&&!n.error&&(n.error=e.stderr()||"telegram command failed"),{content:[{type:"text",text:JSON.stringify({code:r,...n})}]}}function Se(t){return{isError:!0,content:[{type:"text",text:JSON.stringify({error:t})}]}}var yt=[{name:"telegram_wrap",description:"Wrap a scan/quote/thesis as a TrueNorth-style Oracle artifact card. Prepare stays unsigned. No Execute button.",inputSchema:{type:"object",required:["id","title","summary"],properties:{id:{type:"string",description:"artifact id, [a-z0-9-]{4,40}"},title:{type:"string"},summary:{type:"string"},kind:{type:"string"},chat:{type:"string",description:"Telegram chat id, digits only"}}}},{name:"telegram_callback",description:"Handle deepen/refresh/prepare on an Oracle artifact card. Prepare is unsigned. Execute stays on Allow/Deny.",inputSchema:{type:"object",required:["data","chat"],properties:{data:{type:"string",description:"oracle:card:<action>:<id>"},chat:{type:"string"}}}},{name:"telegram_continue",description:"Continue the last artifact thread for this Telegram chat.",inputSchema:{type:"object",required:["chat","text"],properties:{chat:{type:"string"},text:{type:"string"}}}}],bt={name:"oracle-telegram",version:"2",tools:yt,async call(t,e={},{env:r=process.env}={}){let n=ht(r);try{if(t==="telegram_wrap"){let o=["wrap","--id",_(e.id,{field:"id",max:lt,pattern:$e}),"--title",_(e.title,{field:"title",max:ut}),"--summary",_(e.summary,{field:"summary",max:dt})];return e.kind!==void 0&&o.push("--kind",_(e.kind,{field:"kind",max:40,pattern:$e})),e.chat!==void 0&&o.push("--chat",_(e.chat,{field:"chat",max:20,pattern:Q})),n&&o.push("--grant"),await ee(o)}if(t==="telegram_callback"){let o=["callback","--data",_(e.data,{field:"data",max:pt,pattern:mt}),"--chat",_(e.chat,{field:"chat",max:20,pattern:Q})];return n&&o.push("--grant"),await ee(o)}if(t==="telegram_continue")return await ee(["continue","--chat",_(e.chat,{field:"chat",max:20,pattern:Q}),"--text",_(e.text,{field:"text",max:ft})])}catch(o){return Se(o.message)}return Se("unknown tool")}};process.argv[1]&&process.argv[1].endsWith("oracle-telegram-mcp.mjs")&&te(bt);export{ht as grantFromEnv,bt as server};