@oracle-agent/oracle 0.28.28 → 0.28.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -3
- package/SETUP.md +3 -0
- package/dist/assets/skills/bankrbot/SKILL.md +24 -0
- package/dist/assets/skills/oracle-agentic-crypto/SKILL.md +39 -0
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/assets/skills/oracle-uniswap-v4-hooks/SKILL.md +31 -0
- package/dist/assets/skills/oracle-x402/SKILL.md +30 -0
- package/dist/bin/desk-server.mjs +28 -26
- package/dist/bin/oracle-data-mcp.mjs +26 -12
- package/dist/bin/oracle-gateway.mjs +39 -27
- package/dist/bin/oracle-mev-arb-shadow.mjs +5 -5
- package/dist/bin/oracle-mev-shadow.mjs +5 -5
- package/dist/bin/oracle-public-server.mjs +4 -4
- package/dist/bin/oracle-route.mjs +15 -15
- package/dist/bin/oracle-scan.mjs +11 -11
- package/dist/bin/oracle.mjs +4 -3
- package/dist/cli/commands/auth.mjs +6 -6
- package/dist/cli/commands/chat.mjs +161 -161
- package/dist/cli/commands/doctor.mjs +1 -1
- package/dist/cli/commands/eval.mjs +138 -139
- package/dist/cli/commands/farm.mjs +22 -22
- package/dist/cli/commands/follow.mjs +14 -14
- package/dist/cli/commands/harness.mjs +4 -4
- package/dist/cli/commands/model.mjs +163 -163
- package/dist/cli/commands/receipt.mjs +1 -1
- package/dist/cli/commands/resolve.mjs +6 -6
- package/dist/cli/commands/setup.mjs +23 -23
- package/dist/cli/commands/snipe.mjs +24 -0
- package/dist/cli/commands/strategy.mjs +3 -3
- package/dist/cli/commands/swap.mjs +25 -25
- package/dist/cli/commands/venues.mjs +1 -1
- package/dist/control/approval-binding.mjs +1 -0
- package/dist/control/finality.mjs +1 -0
- package/dist/control-plane/index.mjs +6 -0
- package/dist/data/desk-data.mjs +27 -25
- package/dist/data/names.mjs +2 -2
- package/dist/data/providers/farming.mjs +2 -2
- package/dist/governance-prepare.mjs +2 -0
- package/dist/index.mjs +44 -31
- package/dist/local-marketplace.mjs +3 -0
- package/dist/local-pack-registry.mjs +3 -0
- package/dist/local-signer/runtime.mjs +7 -7
- package/dist/local-x402.mjs +3 -0
- package/dist/nft/universal-mint-router.mjs +3 -3
- package/dist/notifications/index.mjs +3 -0
- package/dist/position-health.mjs +2 -0
- package/dist/router/index.mjs +2 -2
- package/dist/router/prepare-bridge.mjs +2 -2
- package/dist/safety-intelligence.mjs +1 -0
- package/dist/scanner/index.mjs +3 -3
- package/dist/strategy/index.mjs +3 -3
- package/dist/task.d.mts +130 -0
- package/dist/task.mjs +2 -0
- package/dist/tax-lots.mjs +5 -0
- package/dist/tenant-rbac.mjs +1 -0
- package/dist/workflow-telemetry.mjs +1 -0
- package/package.json +17 -2
- package/public/agent-connect/index.html +2 -2
- package/public/install.sh +2 -2
- package/public/oracle-splash/index.html +2 -2
- package/public/oracle-splash/install.sh +2 -2
package/dist/bin/oracle-scan.mjs
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createHash as
|
|
3
|
-
`),d=He("sha256").update(c).digest("hex").slice(0,32),l=`${r.untrustedUrl?"untrusted":"trusted"}:${r.maxResponseBytes??"unbounded"}`;return`${t} ${e} ${l} ${d}`}function Je(t,e){let n=Number(e);return Number.isFinite(n)&&n>0?Math.min(n*1e3,pe):Math.min(250*2**t,pe)+Math.floor(Math.random()*100)}var Ze=t=>new Promise(e=>setTimeout(e,t));function O(t,e={}){let n=new Error(t);return n.retryable=!1,Object.assign(n,e),n}function re(t,e,n){return O(`HTTP response from ${t} exceeded maxResponseBytes ${n} (${e})`,{oversize:!0})}function F(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function et(t){return t?t.byteLength??t.length??0:0}async function fe(t,e,{url:n,truncate:r=!1,onOversize:a}={}){if(e==null)return await t.text();let o=Number(t.headers?.get?.("content-length"));if(Number.isFinite(o)&&o>e&&(F(t),!r))throw re(n,`content-length ${o}`,e);let s=t.body?.getReader?.();if(!s){let i=await t.text(),p=Buffer.byteLength(i,"utf8");if(p>e){if(!r)throw re(n,`body ${p} bytes`,e);return Buffer.from(i,"utf8").subarray(0,e).toString("utf8")}return i}let c=[],d=0,l=!1;try{for(;;){let{value:i,done:p}=await s.read();if(p)break;if(i&&(c.push(Buffer.from(i)),d+=et(i),d>e)){l=!0;break}}}finally{if(l)try{await s.cancel()}catch{}try{s.releaseLock?.()}catch{}}if(l&&(typeof a=="function"&&a(),!r))throw re(n,`streamed ${d} bytes`,e);let u=Buffer.concat(c);return(l?u.subarray(0,e):u).toString("utf8")}function me(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function tt(t,{fetchImpl:e,method:n,headers:r,body:a,timeoutMs:o,lookupFn:s,realFetch:c,untrustedUrl:d=!1,maxResponseBytes:l=null,importUndici:u,validateResponse:i}){let p=new AbortController,h=setTimeout(()=>p.abort(),o),f=null,v=e,E=s?{lookupFn:s}:{};if(d&&!c&&!te(v))throw O(`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 C=async(g,{status:S=null}={})=>{let x=await J(g,E);if(!x.ok)throw O(S==null?`HTTP refused ${g}: ${x.error}`:`HTTP redirect to ${g} ${x.error}`,S==null?{}:{status:S});let y=new URL(g).hostname;if(c){if(f&&(await f.close(),f=null),!f)try{f=await Z({requireUndici:!0,...u?{importUndici:u}:{}})}catch(I){throw O(S==null?`HTTP refused ${g}: ${I?.message||I}`:`HTTP redirect to ${g} refused: ${I?.message||I}`,S==null?{}:{status:S})}f.pin(y,x.addresses),v=f.fetch}else le(v,y,x.addresses);return x};try{let g=String(t),S={...r||{}};d&&await C(g);for(let x=0;x<=he;x+=1){let y=await v(g,{method:n,headers:S,body:a,signal:p.signal,redirect:"manual"});if(Ke.has(y.status)){if(n!=="GET"&&n!=="HEAD"){let T=await fe(y,l??We,{url:g,truncate:!0}),_=new Error(`HTTP ${y.status} ${n} ${g} redirected non-idempotent request`);throw _.status=y.status,_.body=me(T)??T.slice(0,300),_}if(x===he)throw F(y),new Error(`HTTP redirect loop for ${t}`);let N=y.headers?.get?.("location"),R;try{R=Ye(N,g)}catch(T){throw F(y),T}let j=!Qe(R,g);if(F(y),j&&(S=Ge(S)),d)await C(R,{status:y.status});else if(j){let T=await J(R,E);if(!T.ok){let _=new Error(`HTTP redirect from ${g} ${T.error}`);throw _.status=y.status,_.retryable=!1,_}c&&T.addresses?.length&&(f||(f=await Z(u?{importUndici:u}:{})),f&&(f.pin(new URL(R).hostname,T.addresses),v=f.fetch))}g=R;continue}if(typeof i=="function")try{await i(y,{url:g})}catch(N){throw F(y),O(N?.message||String(N))}let I=await fe(y,l,{url:g,onOversize:()=>p.abort()}),B=me(I);if(!y.ok){let N=new Error(`HTTP ${y.status} ${n} ${g}`);throw N.status=y.status,N.retryAfter=y.headers?.get?.("retry-after")??null,N.body=B??I.slice(0,300),N}return B??I}throw new Error(`HTTP redirect loop for ${t}`)}finally{clearTimeout(h),f&&await f.close()}}async function W(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,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 c=Number.isInteger(e.retries)?Math.max(e.retries,0):je,d=e.lookupFn,l=!e.fetchImpl,u=e.untrustedUrl===!0,i=e.importUndici,p=e.validateResponse,h=Number(e.maxResponseBytes),f=Number.isFinite(h)&&h>0?Math.floor(h):null,v=async()=>{let x;for(let y=0;y<=c;y++)try{return await tt(t,{fetchImpl:n,method:a,headers:o,body:s,timeoutMs:r,lookupFn:d,realFetch:l,untrustedUrl:u,maxResponseBytes:f,importUndici:i,validateResponse:p})}catch(I){x=I;let B=I?.status,N=I?.name==="AbortError",R=new Set([408,425,429]),j=I?.retryable===!1?!1:B!=null?R.has(B)||Me.has(B)&&de.has(a):!N&&de.has(a);if(y===c||!j)throw I;await Ze(Je(y,I?.retryAfter))}throw x};if(!(e.dedupe!==!1&&a==="GET"&&s==null))return v();let C=Xe(a,t,o,{untrustedUrl:u,maxResponseBytes:f}),g=ne.get(C);if(g)return g;let S=v().finally(()=>ne.delete(C));return ne.set(C,S),S}var ve={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}},nt=new Map(Object.values(ve).map(t=>[t.chainId,t]));function ge(t){return nt.get(Number(t))||null}function ye(t,e=process.env){let n=ge(t);if(!n)return null;for(let r of n.rpcEnv){let a=(e[r]||"").trim();if(a)return a}return null}import{Interface as rt,getAddress as ot}from"ethers";var we=new rt(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Ee(t,e){try{return ot(t).toLowerCase()}catch{throw new Error(`${e} must be a valid EVM address`)}}var at={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 it(t,{rpcUrl:e,env:n=process.env}={}){if(e)return e;let r=ye(t,n);return r||at[Number(t)]||null}var st=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function ct(t){let e=String(t||""),n=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!st.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 k(t,e,n=[],r={}){let a=String(e||"");ct(a);let o=it(t,r);if(!o)throw new Error(`No RPC URL for chainId ${t} (set env from chain registry rpcEnv or pass rpcUrl)`);let c=await W(o,{method:"POST",body:{jsonrpc:"2.0",id:1,method:e,params:n},fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3});if(c?.error){let d=new Error(c.error.message||JSON.stringify(c.error));throw d.code=c.error.code,d}return c.result}async function Se(t,e={}){let n=await k(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 k(t,"eth_getBalance",[e,"latest"],n);return{chainId:Number(t),address:e,balanceWei:BigInt(r).toString(),balanceHex:r}}async function xe(t={},e={}){let n=Number(t.chainId??e.chainId??1),r=Ee(t.token||t.tokenAddress,"token"),a=Ee(t.account||t.owner||t.address,"account"),o=we.encodeFunctionData("balanceOf",[a]),s=await k(n,"eth_call",[{to:r,data:o},t.blockTag||"latest"],e),c=we.decodeFunctionResult("balanceOf",s),d=BigInt(c[0]);return{chainId:n,token:r,account:a,balance:d.toString(),balanceHex:`0x${d.toString(16)}`,blockTag:t.blockTag||"latest"}}var ut="https://api.dexscreener.com",$t=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function lt(t={}){return(t.baseUrl||process.env.DEXSCREENER_API_URL||ut).replace(/\/$/,"")}async function Ce(t,e={}){if(!t)throw new Error("tokenAddress required");return W(`${lt(e)}/latest/dex/tokens/${t}`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var D=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),b=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),m=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),dt=/^0x[0-9a-fA-F]{40}$/;function pt(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 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}dt.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||n.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 r=t.capabilities||{};for(let a of Object.keys(r))D.includes(a)?typeof r[a]!="function"&&e.push(`capability "${a}" must be a function`):e.push(`unknown capability "${a}"`);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 ht(t){let{ok:e,errors:n,warnings:r}=pt(t);if(!e)throw new Error(`invalid scanner for ${t?.key??"<unknown>"}:
|
|
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
4
|
- ${n.join(`
|
|
5
|
-
- `)}`);let a=t.capabilities||{},o=D.filter(c=>typeof a[c]=="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(c=>({...c})),warnings:r,capabilities(){return{chainId:t.chainId,key:t.key,supported:[...o],unsupported:D.filter(c=>!o.includes(c))}},supports(c){return o.includes(c)}};for(let c of D)o.includes(c)?s[c]=async(...d)=>a[c](...d,{scanner:s}):s[c]=async()=>{throw new Error(`${t.key} (chain ${t.chainId}) does not implement "${c}". 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 V=new Map;function Ae(t){let e=ht(t);return V.set(e.chainId,e),e}function oe(t){return V.get(Number(t))||null}function z(){return[...V.values()]}function Ne(){let t={};for(let e of V.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:V.size,capabilities:[...D],chains:t}}var ie={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},A=t=>BigInt(t).toString(16).padStart(64,"0"),H=t=>t.slice(2).toLowerCase().padStart(64,"0");function ft(t,e){return`0x${ie.getAmountsOut}`+A(t)+A(64)+A(e.length)+e.map(H).join("")}function mt(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 a=0;a<n;a++){let o=128+a*64;if(e.length<o+64)return null;r.push(BigInt(`0x${e.slice(o,o+64)}`))}return r}function ae(t,e="router"){return(t?.venues||[]).find(r=>r.kind===e)?.address??null}var se=100;function bt(t,e){let n=Number(e);if(!Number.isFinite(n)||n<0)throw new Error("slippageBps must be a non-negative number");if(n>se)throw new Error(`slippageBps ${n} exceeds the ${se} 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 ke(t){let{chainId:e,wrappedNative:n}=t;async function r(a,o,s,c){let d=await k(e,"eth_call",[{to:a,data:ft(o,s)},"latest"],c);return mt(d?.result??d)}return{async quote({tokenIn:a,tokenOut:o,amountIn:s,path:c},d={}){let l=ae(d.scanner);if(!l)return{chainId:e,evidence:b.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let u=c||[a,o];if(u.some(p=>!/^0x[0-9a-fA-F]{40}$/.test(p||"")))throw new Error("quote requires valid 20-byte addresses");let i=await r(l,s,u,d);return i?{chainId:e,router:l,path:u,amountIn:String(s),amountOut:i[i.length-1].toString(),hops:u.length-1,evidence:b.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:e,router:l,path:u,evidence:b.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:a,amountIn:o,base:s},c={}){let d=ae(c.scanner),l=s||n;if(l&&String(a).toLowerCase()===String(l).toLowerCase())return{chainId:e,token:a,verdict:m.UNKNOWN,evidence:b.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||!l)return{chainId:e,token:a,verdict:m.UNKNOWN,evidence:b.UNAVAILABLE,reason:d?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let u=await r(d,o,[l,a],c);if(!u)return{chainId:e,token:a,verdict:m.FAIL,evidence:b.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let i=u[u.length-1];if(i===0n)return{chainId:e,token:a,verdict:m.FAIL,evidence:b.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let p=await r(d,i,[a,l],c);if(!p)return{chainId:e,token:a,verdict:m.FAIL,evidence:b.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,E="round trip completes with expected fee/impact loss";return f<5e3?(v=m.FAIL,E=`round trip returns only ${(f/100).toFixed(2)}% -- punitive tax or no real liquidity`):f<9e3&&(v=m.CAUTION,E=`round trip returns ${(f/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,token:a,base:l,router:d,verdict:v,reason:E,amountIn:String(o),bought:i.toString(),returned:h.toString(),retentionBps:f,evidence:b.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:c,slippageBps:d=50,deadlineSeconds:l=900,path:u},i={}){let p=i.scanner,h=ae(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(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=u||[a,o],v=await this.quote({tokenIn:a,tokenOut:o,amountIn:s,path:f},i);if(v.evidence!==b.LIVE)throw new Error(`cannot prepare without a live quote (${v.evidence}: ${v.reason??"no reason given"})`);let E=bt(v.amountOut,d);if(E<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let C=BigInt(Math.floor(Date.now()/1e3)+Number(l)),g=n&&f[0].toLowerCase()===n.toLowerCase()&&i.useNative,S=g?`0x${ie.swapExactETHForTokens}`+A(E)+A(128)+H(c)+A(C)+A(f.length)+f.map(H).join(""):`0x${ie.swapExactTokensForTokens}`+A(s)+A(E)+A(160)+H(c)+A(C)+A(f.length)+f.map(H).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:e,tx:{to:h,data:S,value:g?`0x${BigInt(s).toString(16)}`:"0x0"},guard:{quotedOut:v.amountOut,minOut:E.toString(),slippageBps:d,maxSlippageBps:se,deadline:C.toString()},requires:g?[]:[{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 vt=[100,500,3e3,1e4],Ue={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},q=t=>BigInt(t).toString(16).padStart(64,"0"),M=t=>t.slice(2).toLowerCase().padStart(64,"0"),Te=/^0x[0-9a-fA-F]{40}$/,ue=100;function gt(t,e){let n=Number(e);if(!Number.isFinite(n)||n<0)throw new Error("slippageBps must be a non-negative number");if(n>ue)throw new Error(`slippageBps ${n} exceeds the ${ue} 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 ce(t,e){return(t?.venues||[]).find(n=>n.kind===e)?.address??null}function Re(t){let{chainId:e,wrappedNative:n}=t;async function r({quoter:o,tokenIn:s,tokenOut:c,amountIn:d,fee:l},u){let i=`0x${Ue.quoteExactInputSingle}`+M(s)+M(c)+q(d)+q(l)+q(0),p=await k(e,"eth_call",[{to:o,data:i},"latest"],u).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 a({quoter:o,tokenIn:s,tokenOut:c,amountIn:d},l){let u=[],i=null;for(let p of vt){let h=await r({quoter:o,tokenIn:s,tokenOut:c,amountIn:d,fee:p},l);u.push({fee:p,amountOut:h?h.toString():null}),h&&(!i||h>i.amountOut)&&(i={fee:p,amountOut:h})}return{best:i,tried:u}}return{async quote({tokenIn:o,tokenOut:s,amountIn:c},d={}){let l=ce(d.scanner,"quoter");if(!l)return{chainId:e,evidence:b.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let p of[o,s])if(!Te.test(p||""))throw new Error("quote requires valid 20-byte addresses");let{best:u,tried:i}=await a({quoter:l,tokenIn:o,tokenOut:s,amountIn:c},d);return u?{chainId:e,venue:"uniswap-v3",quoter:l,tokenIn:o,tokenOut:s,amountIn:String(c),amountOut:u.amountOut.toString(),fee:u.fee,useNative:!!n&&String(o).toLowerCase()===String(n).toLowerCase(),triedFeeTiers:i,evidence:b.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:e,quoter:l,tokenIn:o,tokenOut:s,triedFeeTiers:i,evidence:b.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:o,amountIn:s,base:c},d={}){let l=ce(d.scanner,"quoter"),u=c||n;if(u&&String(o).toLowerCase()===String(u).toLowerCase())return{chainId:e,token:o,verdict:m.UNKNOWN,evidence:b.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||!u)return{chainId:e,token:o,verdict:m.UNKNOWN,evidence:b.UNAVAILABLE,reason:l?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let i=await a({quoter:l,tokenIn:u,tokenOut:o,amountIn:s},d);if(!i.best)return{chainId:e,token:o,verdict:m.FAIL,evidence:b.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier"};let p=await a({quoter:l,tokenIn:o,tokenOut:u,amountIn:i.best.amountOut},d);if(!p.best)return{chainId:e,token:o,verdict:m.FAIL,evidence:b.LIVE,leg:"sell",bought:i.best.amountOut.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let h=p.best.amountOut,f=Number(h*10000n/BigInt(s)),v=m.PASS,E="round trip completes with expected fee/impact loss";return f<5e3?(v=m.FAIL,E=`round trip returns only ${(f/100).toFixed(2)}% -- punitive tax or no real liquidity`):f<9e3&&(v=m.CAUTION,E=`round trip returns ${(f/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:u,verdict:v,reason:E,amountIn:String(s),bought:i.best.amountOut.toString(),returned:h.toString(),retentionBps:f,buyFee:i.best.fee,sellFee:p.best.fee,evidence:b.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:s,amountIn:c,recipient:d,slippageBps:l=50,fee:u},i={}){let p=ce(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(!Te.test(d||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let h=await this.quote({tokenIn:o,tokenOut:s,amountIn:c},i);if(h.evidence!==b.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let f=u??h.fee,v=gt(h.amountOut,l);if(v<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let E=!!(i.useNative||h.useNative)&&n&&String(o).toLowerCase()===String(n).toLowerCase(),C=`0x${Ue.exactInputSingle}`+M(o)+M(s)+q(f)+M(d)+q(c)+q(v)+q(0);return{unsigned:!0,signedBy:"user-wallet",chainId:e,venue:"uniswap-v3",tx:{to:p,data:C,value:E?String(c):"0x0"},guard:{quotedOut:h.amountOut,minOut:v.toString(),slippageBps:l,maxSlippageBps:ue,fee:f},requires:E?[]:[{step:"approve",token:o,spender:p,amount:String(c)}],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 G={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function _e(t){if(!t||t==="0x")return null;try{return BigInt(t)}catch{return null}}function Le(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 a=e.slice(128,128+r*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 yt(t){let{chainId:e}=t;async function n(r,a,o){return k(e,"eth_call",[{to:r,data:a},"latest"],o)}return{async blockNumber(r={}){let a=await Se(e,r);return{chainId:e,blockNumber:a?.blockNumber??a,evidence:b.LIVE}},async nativeBalance(r,a={}){let o=await Ie(e,r,a);return{chainId:e,address:r,wei:o?.wei??o?.balance??null,symbol:t.nativeCurrency?.symbol??null,decimals:t.nativeCurrency?.decimals??18,evidence:b.LIVE}},async tokenBalance({token:r,owner:a},o={}){let s=await xe({chainId:e,token:r,owner:a},o);return{chainId:e,token:r,owner:a,raw:s?.balance??s,evidence:b.LIVE}},async resolveToken(r,a={}){if(!/^0x[0-9a-fA-F]{40}$/.test(r||""))return{chainId:e,token:r,evidence:b.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[o,s,c,d]=await Promise.all([n(r,G.decimals,a).catch(()=>null),n(r,G.symbol,a).catch(()=>null),n(r,G.name,a).catch(()=>null),n(r,G.totalSupply,a).catch(()=>null)]),l=_e(o?.result??o),u=l!==null||s?.result||c?.result;return{chainId:e,address:r,decimals:l===null?null:Number(l),symbol:Le(s?.result??s),name:Le(c?.result??c),totalSupply:(_e(d?.result??d)??null)?.toString()??null,evidence:u?b.LIVE:b.UNKNOWN,warning:u?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(r,a={}){let o=t.dexscreenerSlug;if(!o)return{chainId:e,token:r,pools:[],evidence:b.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let s=await Ce(r,a).catch(()=>null),d=(s?.pairs||s?.data?.pairs||[]).filter(l=>String(l.chainId).toLowerCase()===String(o).toLowerCase()).map(l=>({pair:l.pairAddress,dex:l.dexId,base:l.baseToken?.address,quote:l.quoteToken?.address,liquidityUsd:l.liquidity?.usd??null,priceUsd:l.priceUsd??null,volume24hUsd:l.volume?.h24??null,createdAt:l.pairCreatedAt??null})).sort((l,u)=>(u.liquidityUsd??0)-(l.liquidityUsd??0));return{chainId:e,token:r,pools:d,evidence:d.length?b.LIVE:b.UNKNOWN}},async scanBlocks({fromBlock:r,toBlock:a,address:o,topics:s,chunkSize:c=2e3}={},d={}){if(!Number.isInteger(r)||!Number.isInteger(a))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(a<r)throw new Error("toBlock must be >= fromBlock");let l=[],u=[];for(let i=r;i<=a;i+=c){let p=Math.min(i+c-1,a);u.push([i,p])}for(let[i,p]of u){let h={fromBlock:`0x${i.toString(16)}`,toBlock:`0x${p.toString(16)}`};o&&(h.address=o),s&&(h.topics=s);let f=await k(e,"eth_getLogs",[h],d).catch(v=>({error:String(v?.message||v)}));if(f?.error)return{chainId:e,fromBlock:r,toBlock:a,logs:l,complete:!1,failedAt:[i,p],error:f.error,evidence:b.UNKNOWN};for(let v of f?.result??f??[])l.push(v)}return{chainId:e,fromBlock:r,toBlock:a,logs:l,complete:!0,chunks:u.length,evidence:b.LIVE}},async scoreRisk(r,a={}){let o=[],s=m.PASS,c=u=>{let i={[m.PASS]:0,[m.CAUTION]:1,[m.UNKNOWN]:2,[m.FAIL]:3};i[u]>i[s]&&(s=u)},d=await this.resolveToken(r,a);d.evidence!==b.LIVE?(o.push({check:"erc20-metadata",result:m.UNKNOWN,detail:d.warning}),c(m.UNKNOWN)):o.push({check:"erc20-metadata",result:m.PASS,detail:`${d.symbol} / ${d.decimals}d`});let l=await this.resolvePools(r,a);if(l.evidence===b.UNAVAILABLE)o.push({check:"liquidity",result:m.UNKNOWN,detail:l.reason}),c(m.UNKNOWN);else if(!l.pools.length)o.push({check:"liquidity",result:m.FAIL,detail:"no pool with liquidity found"}),c(m.FAIL);else{let u=l.pools[0],i=u.liquidityUsd??0;i<5e3?(o.push({check:"liquidity",result:m.CAUTION,detail:`top pool only $${i}`}),c(m.CAUTION)):o.push({check:"liquidity",result:m.PASS,detail:`$${i} on ${u.dex}`}),u.createdAt&&Date.now()-u.createdAt<24*3600*1e3&&(o.push({check:"age",result:m.CAUTION,detail:"pool under 24h old"}),c(m.CAUTION))}if(typeof this.sellSimulation=="function"){let u=await this.sellSimulation({token:r,amountIn:(10n**16n).toString()},a).catch(i=>({verdict:m.UNKNOWN,reason:String(i?.message||i)}));o.push({check:"sellability",result:u.verdict,detail:u.retentionBps!=null?`round trip returns ${(u.retentionBps/100).toFixed(2)}% -- ${u.reason}`:u.reason}),c(u.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."}),c(m.UNKNOWN);return{chainId:e,token:r,verdict:s,checks:o,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function qe(t){let n={...yt(t)},r=new Set((t.venues||[]).map(o=>o.kind));t.venueKind==="uniswap-v3"&&r.has("quoter")&&r.has("router")?Object.assign(n,Re({chainId:t.chainId,wrappedNative:t.wrappedNative})):t.venueKind==="uniswap-v2"&&r.has("router")&&Object.assign(n,ke({chainId:t.chainId,wrappedNative:t.wrappedNative}));let a={};for(let[o,s]of Object.entries(n))a[o]=s.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:a}}var wt=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",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",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",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",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",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",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",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",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 $e(){return wt.map(t=>Ae(qe(t)))}$e();var[Be,...Pe]=process.argv.slice(2),Y=Pe.includes("--json"),w=Pe.filter(t=>t!=="--json");function P(t){t||U("missing <chain>");let e=oe(Number(t));if(e)return e;let n=z().find(r=>r.key===String(t).toLowerCase());if(n)return n;U(`unknown chain "${t}". Known: ${z().map(r=>`${r.key}(${r.chainId})`).join(", ")}`)}function U(t){console.error(`error: ${t}`),process.exit(1)}function $(t){process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
6
|
-
`)}function
|
|
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}
|
|
7
7
|
|
|
8
8
|
This chain reads its RPC from: ${t.rpcEnv.join(" or ")}
|
|
9
|
-
Set one, e.g.: export ${t.rpcEnv[0]}=https://...`:n}try{switch(
|
|
10
|
-
`);let e=Object.entries(t.chains).map(([r,
|
|
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
11
|
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=
|
|
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
13
|
`);for(let n of e.checks)console.log(` ${n.result.padEnd(8)} ${n.check.padEnd(16)} ${n.detail??""}`);console.log(`
|
|
14
|
-
${e.note}`);break}case"quote":{let t=
|
|
15
|
-
Add a venue with recorded provenance -- see docs/adding-a-chain.md.`);let e=
|
|
16
|
-
Without it, treat every token on this chain as unproven for exit.`);let e=
|
|
14
|
+
${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
|
+
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
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(
|
|
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))}
|
package/dist/bin/oracle.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{realpathSync as T}from"node:fs";import{fileURLToPath as oe}from"node:url";import h from"node:fs";import g from"node:path";import{pathToFileURL as z}from"node:url";import d from"node:fs";import P from"node:os";import i from"node:path";import{fileURLToPath as $}from"node:url";var M=i.dirname($(import.meta.url)),l=i.resolve(M,"../..");function u(){return process.env.ORACLE_FAKE_HOME||P.homedir()}function R(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function f(){return R()?process.env.ORACLE_CONFIG_DIR||i.join(u(),".config","oracle"):i.join(u(),".config","oracle")}function I(){return i.join(f(),"exec.env")}function
|
|
2
|
+
import{realpathSync as T}from"node:fs";import{fileURLToPath as oe}from"node:url";import h from"node:fs";import g from"node:path";import{pathToFileURL as z}from"node:url";import d from"node:fs";import P from"node:os";import i from"node:path";import{fileURLToPath as $}from"node:url";var M=i.dirname($(import.meta.url)),l=i.resolve(M,"../..");function u(){return process.env.ORACLE_FAKE_HOME||P.homedir()}function R(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function f(){return R()?process.env.ORACLE_CONFIG_DIR||i.join(u(),".config","oracle"):i.join(u(),".config","oracle")}function I(){return i.join(f(),"exec.env")}function k(){return i.join(f(),"desk.json")}function v(){return i.join(f(),"env")}function p({force:e=!1}={}){if(p._done&&!e)return p._result||null;p._done=!0;let o={},n=(c,t)=>{if(t==null)return;let r=String(t).trim();r&&(process.env[c]!=null&&String(process.env[c]).trim()!==""||(process.env[c]=r,o[c]=r))};try{let c=v();if(d.existsSync(c))for(let t of d.readFileSync(c,"utf8").split(/\r?\n/)){let r=t.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!r||r[2].startsWith("#"))continue;let a=r[2];(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),n(r[1],a)}}catch{}try{let c=k();if(d.existsSync(c)){let t=JSON.parse(d.readFileSync(c,"utf8"));t&&typeof t=="object"&&(n("ORACLE_DESK_URL",t.deskUrl||t.dataUrl||t.url),n("ORACLE_DATA_URL",t.dataUrl||t.deskUrl||t.url),n("ORACLE_API_URL",t.apiUrl||t.dataUrl||t.deskUrl),n("ORACLE_PUBLIC_URL",t.publicUrl||t.deskUrl||t.dataUrl),n("ORACLE_EXEC_URL",t.execUrl),n("MAD_DESK_URL",t.deskUrl||t.dataUrl))}}catch{}let s=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return s&&(n("ORACLE_DESK_URL",s),n("ORACLE_DATA_URL",s),n("ORACLE_API_URL",s),n("ORACLE_PUBLIC_URL",s),n("MAD_DESK_URL",s)),p._result=Object.keys(o).length?o:null,p._result}try{p()}catch{}function H(){return process.env.HERMES_HOME?i.resolve(process.env.HERMES_HOME):i.join(u(),".hermes")}function N(){return i.join(u(),".claude.json")}function F(e=process.cwd()){return i.join(e,".mcp.json")}function q(){return process.platform==="darwin"?i.join(u(),"Library","Application Support","Claude","claude_desktop_config.json"):i.join(u(),".config","Claude","claude_desktop_config.json")}function K(){return i.join(u(),".codex","config.toml")}function C(){return i.join(f(),"connectors")}function B(){return i.join(C(),"chatgpt-openapi.json")}function G(){return i.join(f(),"active-chain.json")}function y(e){let o=[i.join(l,"bin",e),i.join(l,"dist","bin",e),i.join(l,"..","bin",e)];return o.find(n=>d.existsSync(n))||o[0]}function V(e){return d.mkdirSync(e,{recursive:!0}),e}var j={homeDir:u,isPublicDesktop:R,oracleConfigDir:f,oracleExecEnvPath:I,oracleDeskJsonPath:k,oracleEnvFilePath:v,loadDeskRouting:p,hermesRoot:H,activeChainPath:G,claudeCodeUserConfigPath:N,claudeCodeProjectMcpPath:F,claudeDesktopConfigPath:q,codexConfigPath:K,chatgptConnectorDir:C,chatgptOpenApiPath:B,packageBin:y,ensureDir:V,PACKAGE_ROOT:l};import{execFile as J}from"node:child_process";import{existsSync as me,mkdirSync as he,readFileSync as W,realpathSync as ge,writeFileSync as ye}from"node:fs";import w from"node:path";import{promisify as Y}from"node:util";var Ae=Y(J);var _e=1440*60*1e3;function L(e,o){let n=t=>String(t).replace(/^v/,"").split("-")[0].split(".").map(r=>Number.parseInt(r,10)||0),s=n(e),c=n(o);for(let t=0;t<Math.max(s.length,c.length);t+=1){let r=s[t]??0,a=c[t]??0;if(r>a)return 1;if(r<a)return-1}return 0}function X(e){let o=e?.stateDir||w.join(process.env.HOME||".",".oracle");return w.join(o,"update-check.json")}function O(e){try{return JSON.parse(W(X(e),"utf8"))}catch{return null}}var Q="\u25C7 ORACLE // self-custody multichain agent control plane",Z=`START
|
|
3
3
|
oracle open the native Oracle chat (TTY)
|
|
4
4
|
oracle chat open chat explicitly
|
|
5
5
|
oracle setup connect a model and optional messaging
|
|
@@ -20,6 +20,7 @@ PREPARE
|
|
|
20
20
|
oracle prepare build an unsigned swap (alias of route prepare)
|
|
21
21
|
oracle strategy draft|validate|backtest|optimize|evidence \xB7 shadow \xB7 prepare
|
|
22
22
|
oracle mev observe \xB7 status \xB7 control \xB7 operator (execute needs --execute)
|
|
23
|
+
oracle snipe twitter CA watch \u2192 USD-book prepare (no broadcast)
|
|
23
24
|
|
|
24
25
|
LOCAL SIGNING (SELF-HOSTED)
|
|
25
26
|
oracle sign init|import|status|lock|doctor
|
|
@@ -46,9 +47,9 @@ BOUNDARY
|
|
|
46
47
|
MEV observe is read-only. Flash-loan execute needs ORACLE_MEV_EXECUTE_ENABLED=1
|
|
47
48
|
and literal --execute. There is no autonomous MEV loop.
|
|
48
49
|
Use oracle <command> --help for command details.
|
|
49
|
-
`;function U(){try{return JSON.parse(h.readFileSync(g.join(l,"package.json"),"utf8")).version||"0.0.0"}catch{return"0.0.0"}}function ee(){let e=g.join(l,"src","cli","commands");return h.existsSync(e)?e:g.join(l,"dist","cli","commands")}async function m(){let e=ee(),o=new Map;if(!h.existsSync(e))return o;let n=h.readdirSync(e).filter(s=>s.endsWith(".mjs")).sort();for(let s of n){let c=g.join(e,s);try{let r=(await import(z(c).href+`?t=${Date.now()}`)).default;if(!r||typeof r!="object"||typeof r.run!="function")continue;let a=r.name||s.replace(/\.mjs$/,""),A={...r,name:a,__file:c};o.set(a,A);for(let _ of Array.isArray(r.aliases)?r.aliases:[])o.set(_,{...A,name:_,aliasFor:a})}catch(t){process.env.ORACLE_CLI_DEBUG&&console.error(`oracle: failed loading command ${s}: ${t.message}`)}}return o}function te(e,o=O()){return!o?.latest||!e||
|
|
50
|
+
`;function U(){try{return JSON.parse(h.readFileSync(g.join(l,"package.json"),"utf8")).version||"0.0.0"}catch{return"0.0.0"}}function ee(){let e=g.join(l,"src","cli","commands");return h.existsSync(e)?e:g.join(l,"dist","cli","commands")}async function m(){let e=ee(),o=new Map;if(!h.existsSync(e))return o;let n=h.readdirSync(e).filter(s=>s.endsWith(".mjs")).sort();for(let s of n){let c=g.join(e,s);try{let r=(await import(z(c).href+`?t=${Date.now()}`)).default;if(!r||typeof r!="object"||typeof r.run!="function")continue;let a=r.name||s.replace(/\.mjs$/,""),A={...r,name:a,__file:c};o.set(a,A);for(let _ of Array.isArray(r.aliases)?r.aliases:[])o.set(_,{...A,name:_,aliasFor:a})}catch(t){process.env.ORACLE_CLI_DEBUG&&console.error(`oracle: failed loading command ${s}: ${t.message}`)}}return o}function te(e,o=O()){return!o?.latest||!e||L(o.latest,e)<=0?"":`
|
|
50
51
|
Update available: ${e} \u2192 ${o.latest}. Run 'oracle update'.
|
|
51
|
-
`}function E(e,o){let n=[];n.push(`${Q} (v${e})`),n.push(""),n.push(Z.trimEnd());let s=[];for(let c of o.values()){if(["help","version"].includes(c.name))continue;!new Set(["init","doctor","chat","model","auth","chain","setup","data","data-mcp","scan","route","prepare","swap","farm","follow","equities","strategy","mev","public","mcp","plugins","harness","clients","upgrade","bootstrap","eval","fees","sign","signer"]).has(c.name)&&c.summary&&s.push(` oracle ${c.name.padEnd(20)} ${c.summary}`)}return s.length&&(n.push(""),n.push("ADDITIONAL"),n.push(...s)),n.join(`
|
|
52
|
+
`}function E(e,o){let n=[];n.push(`${Q} (v${e})`),n.push(""),n.push(Z.trimEnd());let s=[];for(let c of o.values()){if(["help","version"].includes(c.name))continue;!new Set(["init","doctor","chat","model","auth","chain","setup","data","data-mcp","scan","route","prepare","swap","farm","follow","equities","strategy","mev","snipe","public","mcp","plugins","harness","clients","upgrade","bootstrap","eval","fees","sign","signer"]).has(c.name)&&c.summary&&s.push(` oracle ${c.name.padEnd(20)} ${c.summary}`)}return s.length&&(n.push(""),n.push("ADDITIONAL"),n.push(...s)),n.join(`
|
|
52
53
|
`)+`
|
|
53
54
|
`+te(e)}function S(e,o){let n=[...o.keys()].sort(),s=n.length?n.join(", "):"(none loaded yet)";return`oracle: unknown command '${e}'. Known: ${s}
|
|
54
55
|
Try: oracle --help
|
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import T from"node:fs";import F from"node:path";import j from"node:fs";import pe from"node:os";import O from"node:path";import{fileURLToPath as le}from"node:url";var fe=O.dirname(le(import.meta.url)),Ve=O.resolve(fe,"../..");function X(){return process.env.ORACLE_FAKE_HOME||pe.homedir()}function he(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function b(){return he()?process.env.ORACLE_CONFIG_DIR||O.join(X(),".config","oracle"):O.join(X(),".config","oracle")}function me(){return O.join(b(),"desk.json")}function we(){return O.join(b(),"env")}function E({force:e=!1}={}){if(E._done&&!e)return E._result||null;E._done=!0;let t={},r=(n,i)=>{if(i==null)return;let s=String(i).trim();s&&(process.env[n]!=null&&String(process.env[n]).trim()!==""||(process.env[n]=s,t[n]=s))};try{let n=we();if(j.existsSync(n))for(let i of j.readFileSync(n,"utf8").split(/\r?\n/)){let s=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let p=s[2];(p.startsWith('"')&&p.endsWith('"')||p.startsWith("'")&&p.endsWith("'"))&&(p=p.slice(1,-1)),r(s[1],p)}}catch{}try{let n=me();if(j.existsSync(n)){let i=JSON.parse(j.readFileSync(n,"utf8"));i&&typeof i=="object"&&(r("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),r("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),r("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),r("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),r("ORACLE_EXEC_URL",i.execUrl),r("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let o=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return o&&(r("ORACLE_DESK_URL",o),r("ORACLE_DATA_URL",o),r("ORACLE_API_URL",o),r("ORACLE_PUBLIC_URL",o),r("MAD_DESK_URL",o)),E._result=Object.keys(t).length?t:null,E._result}try{E()}catch{}function $(e){return j.mkdirSync(e,{recursive:!0}),e}var ge=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","nous","custom","anthropic-oauth","openai-codex","xai-oauth"]);function I(e){return String(e||"").trim()||void 0}function ye(e,{required:t=!1}={}){let r=I(e)?.toLowerCase();if(!r){if(t)throw new Error("model provider is required");return}if(!ge.has(r))throw new Error(`unsupported provider: ${r}`);return r}function ve(e,{required:t=!1}={}){let r=I(e);if(!r){if(t)throw new Error("model is required");return}if(r.includes("..")||r.startsWith("/")||!/^[a-zA-Z0-9._:/-]{1,200}$/.test(r))throw new Error("invalid model id");return r}function ke(e){let t=I(e);if(!t||t.length>2048)throw new Error("invalid custom base URL");let r;try{r=new URL(t)}catch{throw new Error("invalid custom base URL")}let o=r.hostname.toLowerCase().replace(/^\[|\]$/g,""),n=o==="localhost"||o==="127.0.0.1"||o==="::1";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&n)||r.username||r.password||r.search||r.hash)throw new Error("custom base URL must use HTTPS or loopback HTTP without credentials, query, or fragment");return r.toString().replace(/\/+$/,"")}function L({provider:e,model:t,baseUrl:r}={},{requireModel:o=!1}={}){let n=ye(e),i=ve(t,{required:o});if(n==="custom")return{provider:n,...i?{model:i}:{},baseUrl:ke(r)};if(I(r))throw new Error("baseUrl is only supported for the custom provider");return{...n?{provider:n}:{},...i?{model:i}:{}}}var xe=new Set(["auto","standalone","hermes","remote","arch"]);function _e(){return F.join(b(),"model.json")}function P(e){return String(e||"").trim()||void 0}function Ae(e={}){let t=P(e.backend)?.toLowerCase()||"auto",r=L({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:t==="standalone"}),o=P(e.apiKeyEnv),n=Number.parseInt(String(e.contextLength||""),10),i=P(e.reasoningEffort),s=P(e.computeHost||e.remoteHost),p=P(e.computeUser||e.remoteUser),u=P(e.computePath||e.remotePath);if(!xe.has(t))throw new Error(`unsupported backend: ${t}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(t))throw new Error("remote compute backends are disabled in the public desktop");if(o&&!/^[A-Z][A-Z0-9_]*$/.test(o))throw new Error("api key env must be an uppercase environment variable name");if(t==="remote"&&!s)throw new Error("remote backend requires computeHost");return{backend:t,...r,...o?{apiKeyEnv:o}:{},...Number.isFinite(n)&&n>0?{contextLength:n}:{},...i?{reasoningEffort:i}:{},...s?{computeHost:s}:{},...p?{computeUser:p}:{},...u?{computePath:u}:{}}}function Z(e){let t=Ae(e),r=_e();$(F.dirname(r)),process.platform!=="win32"&&T.chmodSync(F.dirname(r),448);let o=`${r}.${process.pid}.tmp`;return T.writeFileSync(o,`${JSON.stringify(t,null,2)}
|
|
1
|
+
import T from"node:fs";import F from"node:path";import j from"node:fs";import pe from"node:os";import O from"node:path";import{fileURLToPath as le}from"node:url";var fe=O.dirname(le(import.meta.url)),Ve=O.resolve(fe,"../..");function X(){return process.env.ORACLE_FAKE_HOME||pe.homedir()}function he(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function b(){return he()?process.env.ORACLE_CONFIG_DIR||O.join(X(),".config","oracle"):O.join(X(),".config","oracle")}function me(){return O.join(b(),"desk.json")}function we(){return O.join(b(),"env")}function E({force:e=!1}={}){if(E._done&&!e)return E._result||null;E._done=!0;let t={},r=(n,i)=>{if(i==null)return;let s=String(i).trim();s&&(process.env[n]!=null&&String(process.env[n]).trim()!==""||(process.env[n]=s,t[n]=s))};try{let n=we();if(j.existsSync(n))for(let i of j.readFileSync(n,"utf8").split(/\r?\n/)){let s=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let p=s[2];(p.startsWith('"')&&p.endsWith('"')||p.startsWith("'")&&p.endsWith("'"))&&(p=p.slice(1,-1)),r(s[1],p)}}catch{}try{let n=me();if(j.existsSync(n)){let i=JSON.parse(j.readFileSync(n,"utf8"));i&&typeof i=="object"&&(r("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),r("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),r("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),r("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),r("ORACLE_EXEC_URL",i.execUrl),r("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let o=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return o&&(r("ORACLE_DESK_URL",o),r("ORACLE_DATA_URL",o),r("ORACLE_API_URL",o),r("ORACLE_PUBLIC_URL",o),r("MAD_DESK_URL",o)),E._result=Object.keys(t).length?t:null,E._result}try{E()}catch{}function $(e){return j.mkdirSync(e,{recursive:!0}),e}var ge=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","nous","qwen","glm","custom","anthropic-oauth","openai-codex","xai-oauth"]);function I(e){return String(e||"").trim()||void 0}function ye(e,{required:t=!1}={}){let r=I(e)?.toLowerCase();if(!r){if(t)throw new Error("model provider is required");return}if(!ge.has(r))throw new Error(`unsupported provider: ${r}`);return r}function ve(e,{required:t=!1}={}){let r=I(e);if(!r){if(t)throw new Error("model is required");return}if(r.includes("..")||r.startsWith("/")||!/^[a-zA-Z0-9._:/-]{1,200}$/.test(r))throw new Error("invalid model id");return r}function ke(e){let t=I(e);if(!t||t.length>2048)throw new Error("invalid custom base URL");let r;try{r=new URL(t)}catch{throw new Error("invalid custom base URL")}let o=r.hostname.toLowerCase().replace(/^\[|\]$/g,""),n=o==="localhost"||o==="127.0.0.1"||o==="::1";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&n)||r.username||r.password||r.search||r.hash)throw new Error("custom base URL must use HTTPS or loopback HTTP without credentials, query, or fragment");return r.toString().replace(/\/+$/,"")}function L({provider:e,model:t,baseUrl:r}={},{requireModel:o=!1}={}){let n=ye(e),i=ve(t,{required:o});if(n==="custom")return{provider:n,...i?{model:i}:{},baseUrl:ke(r)};if(I(r))throw new Error("baseUrl is only supported for the custom provider");return{...n?{provider:n}:{},...i?{model:i}:{}}}var xe=new Set(["auto","standalone","hermes","remote","arch"]);function _e(){return F.join(b(),"model.json")}function P(e){return String(e||"").trim()||void 0}function Ae(e={}){let t=P(e.backend)?.toLowerCase()||"auto",r=L({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:t==="standalone"}),o=P(e.apiKeyEnv),n=Number.parseInt(String(e.contextLength||""),10),i=P(e.reasoningEffort),s=P(e.computeHost||e.remoteHost),p=P(e.computeUser||e.remoteUser),u=P(e.computePath||e.remotePath);if(!xe.has(t))throw new Error(`unsupported backend: ${t}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(t))throw new Error("remote compute backends are disabled in the public desktop");if(o&&!/^[A-Z][A-Z0-9_]*$/.test(o))throw new Error("api key env must be an uppercase environment variable name");if(t==="remote"&&!s)throw new Error("remote backend requires computeHost");return{backend:t,...r,...o?{apiKeyEnv:o}:{},...Number.isFinite(n)&&n>0?{contextLength:n}:{},...i?{reasoningEffort:i}:{},...s?{computeHost:s}:{},...p?{computeUser:p}:{},...u?{computePath:u}:{}}}function Z(e){let t=Ae(e),r=_e();$(F.dirname(r)),process.platform!=="win32"&&T.chmodSync(F.dirname(r),448);let o=`${r}.${process.pid}.tmp`;return T.writeFileSync(o,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384}),T.renameSync(o,r),process.platform!=="win32"&&T.chmodSync(r,384),t}import{createHash as Se,randomBytes as N,timingSafeEqual as Ee}from"node:crypto";import g from"node:fs";import k from"node:path";import Oe from"node:readline/promises";import{spawn as be,spawnSync as Pe}from"node:child_process";var R=Object.freeze({"anthropic-oauth":{aliases:["anthropic-oauth","anthropic","claude","claude-oauth"],clientId:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",authorizeUrl:"https://claude.ai/oauth/authorize",tokenUrl:"https://platform.claude.com/v1/oauth/token",redirectUri:"https://console.anthropic.com/oauth/code/callback",scope:"org:create_api_key user:profile user:inference",baseUrl:"https://api.anthropic.com/v1",model:"claude-sonnet-4-6",protocol:"anthropic-messages"},"openai-codex":{aliases:["openai-codex","openai-oauth","codex","codex-oauth"],clientId:"app_EMoamEEZ73f0CkXaXp7hrann",issuer:"https://auth.openai.com",tokenUrl:"https://auth.openai.com/oauth/token",baseUrl:"https://chatgpt.com/backend-api/codex",model:"gpt-5.6-sol",protocol:"responses"},"xai-oauth":{aliases:["xai-oauth","xai","grok","grok-oauth"],clientId:"b1a00492-073a-47ea-816f-4c329264a828",issuer:"https://auth.x.ai",discoveryUrl:"https://auth.x.ai/.well-known/openid-configuration",deviceUrl:"https://auth.x.ai/oauth2/device/code",scope:"openid profile email offline_access grok-cli:access api:access",baseUrl:"https://api.x.ai/v1",model:"grok-4.6",protocol:"responses"}}),Ce=12e4;function Re(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function _(e){let t=String(e||"").trim().toLowerCase();for(let[r,o]of Object.entries(R))if(o.aliases.includes(t))return r;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function Y(e){let t=_(e);return{id:t,...R[t]}}function m(e,t={}){if(!g.existsSync(e))return t;try{let r=JSON.parse(g.readFileSync(e,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid object");return r}catch{throw new Error(`credential store is unreadable or corrupt: ${k.basename(e)}`)}}function Q(e){$(e),process.platform!=="win32"&&g.chmodSync(e,448)}function x(e,t){Q(k.dirname(e));let r=`${e}.${process.pid}.${N(4).toString("hex")}.tmp`;g.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
3
3
|
`,{mode:384}),g.renameSync(r,e),process.platform!=="win32"&&g.chmodSync(e,384)}function Ue(e){if(process.platform!=="linux")return!1;let t=e("secret-tool",["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return!t.error&&t.status===0}function D(e){let t=String(e||"").trim().toLowerCase();if(!/^[a-z0-9][a-z0-9._-]*$/.test(t))throw new Error(`invalid API-key provider: ${e||"(empty)"}`);return t}function C(e={}){let t=String(e.accessToken||e.access_token||"").trim(),r=String(e.refreshToken||e.refresh_token||"").trim(),o=Number(e.expiresAt||e.expires_at||0);if(Number.isFinite(o)&&o>=1e9&&o<1e12&&(o=o*1e3),!t)throw new Error("OAuth credential is missing access token");return{accessToken:t,refreshToken:r,expiresAt:Number.isFinite(o)?o:0,tokenType:String(e.tokenType||e.token_type||"Bearer"),source:String(e.source||"oracle"),...e.discovery?{discovery:e.discovery}:{},...e.scope?{scope:e.scope}:{},...e.idToken||e.id_token?{idToken:String(e.idToken||e.id_token)}:{}}}function je(e={}){let t=e.file||k.join(b(),"oauth.json"),r=e.metadataFile||k.join(k.dirname(t),"oauth-meta.json"),o=e.linksFile||k.join(k.dirname(t),"oauth-links.json"),n=()=>typeof e.now=="function"?Number(e.now()):Date.now(),i=e.spawnFn||Pe,s=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&Ue(i),p=s?"linux-secret-service":"private-file",u=`${t}.lock`;async function v(f){Q(k.dirname(u));let l;for(let c=0;c<400;c+=1)try{l=g.openSync(u,"wx",384);break}catch(a){if(a?.code!=="EEXIST")throw a;try{Date.now()-g.statSync(u).mtimeMs>3e5&&g.unlinkSync(u)}catch{}await new Promise(d=>setTimeout(d,25))}if(l===void 0)throw new Error("timed out waiting for OAuth credential lock");try{return await f()}finally{try{g.closeSync(l)}catch{}try{g.unlinkSync(u)}catch{}}}function w(f,l="oauth"){return["application","oracle","kind",l,"provider",f]}function U(f){if(!g.existsSync(o))return null;let c=m(o,{providers:{}}).providers?.[f];if(!Array.isArray(c))return null;let a=[];for(let d of c)if(k.isAbsolute(String(d||"")))try{let h=m(d,{});if(f==="anthropic-oauth"&&h.claudeAiOauth){let S=C(h.claudeAiOauth);a.push({...S,refreshToken:"",source:"external-access-only"});continue}let y=h.credential_pool&&typeof h.credential_pool=="object"?h.credential_pool:null;if(y){let S=y[f]||y[f.replace(/-oauth$/,"")]||[],ue=Array.isArray(S)?S:S?[S]:[];for(let z of ue)if(!(!z||typeof z!="object"))try{let de=C(z);a.push({...de,refreshToken:"",source:"external-access-only"})}catch{}}}catch{}return a.length?a.find(d=>!d.expiresAt||d.expiresAt>n()+Ce)||a[0]:null}function W(f){let l=_(f);if(s){let d=i("secret-tool",["lookup",...w(l)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(!d.error&&d.status===0&&String(d.stdout||"").trim())try{return C(JSON.parse(String(d.stdout).trim()))}catch{}return U(l)}let a=m(t,{providers:{}}).providers?.[l];if(a)try{return C(a)}catch{}return U(l)}function ne(f,l){let c=_(f),a=C(l);if(s){let h=i("secret-tool",["store",`--label=Oracle ${c} OAuth`,...w(c)],{input:JSON.stringify(a),encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(h.error||h.status!==0)throw new Error("OS credential store rejected OAuth credential");let y=m(r,{providers:{}});return y.providers||={},y.providers[c]={expiresAt:a.expiresAt,source:a.source},x(r,y),a}let d=m(t,{providers:{}});return d.providers||={},d.providers[c]=a,x(t,d),a}function ie(f){let l=_(f);if(s){let d=i("secret-tool",["clear",...w(l)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),h=m(r,{providers:{}});return h.providers&&delete h.providers[l],x(r,h),!d.error&&d.status===0}let c=m(t,{providers:{}}),a=!!c.providers?.[l];return c.providers&&delete c.providers[l],x(t,c),a}function V(f){let l=D(f);if(s){let c=i("secret-tool",["lookup",...w(l,"api-key")],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return c.error||c.status!==0?"":String(c.stdout||"").trim()}return String(m(t,{apiKeys:{}}).apiKeys?.[l]||"").trim()}function se(f,l){let c=D(f),a=String(l||"").trim();if(!a)throw new Error("API key is empty");if(s){let h=i("secret-tool",["store",`--label=Oracle ${c} API key`,...w(c,"api-key")],{input:a,encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(h.error||h.status!==0)throw new Error("OS credential store rejected API key");let y=m(r,{providers:{},apiKeys:{}});return y.apiKeys||={},y.apiKeys[c]={configured:!0},x(r,y),!0}let d=m(t,{providers:{},apiKeys:{}});return d.apiKeys||={},d.apiKeys[c]=a,x(t,d),!0}function ce(f){let l=D(f);if(s){let d=i("secret-tool",["clear",...w(l,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),h=m(r,{providers:{},apiKeys:{}});return h.apiKeys&&delete h.apiKeys[l],x(r,h),!d.error&&d.status===0}let c=m(t,{providers:{},apiKeys:{}}),a=!!c.apiKeys?.[l];return c.apiKeys&&delete c.apiKeys[l],x(t,c),a}function ae(){let f={},l={};if(s){let c=m(r,{providers:{},apiKeys:{}});for(let[a,d]of Object.entries(c.providers||{}))f[a]={loggedIn:!!W(a),expiresAt:Number(d.expiresAt||0),source:String(d.source||"oracle"),storage:p};for(let a of Object.keys(c.apiKeys||{}))l[a]={configured:!!V(a),storage:p}}else{let c=m(t,{providers:{},apiKeys:{}});for(let[a,d]of Object.entries(c.providers||{}))f[a]={loggedIn:!!d?.accessToken,expiresAt:Number(d?.expiresAt||0),source:String(d?.source||"oracle"),storage:p};for(let[a,d]of Object.entries(c.apiKeys||{}))l[a]={configured:!!d,storage:p}}for(let c of Object.keys(R)){if(f[c])continue;let a=U(c);a&&(f[c]={loggedIn:!0,expiresAt:a.expiresAt,source:a.source,storage:"external-access-source"})}return{storage:p,providers:f,apiKeys:l}}return Object.freeze({file:t,storage:p,get:W,set:ne,remove:ie,getApiKey:V,setApiKey:se,removeApiKey:ce,status:ae,withLock:v})}var G;function ee(){return G||=je(),G}function M(e){return Buffer.from(e).toString("base64url")}function $e(){let e=M(N(32));return{verifier:e,challenge:M(Se("sha256").update(e).digest()),state:M(N(24))}}function Ie(e,t){let r=Buffer.from(String(e||"")),o=Buffer.from(String(t||""));return r.length===o.length&&Ee(r,o)}function Le(e){let t=String(e),r=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd.exe",["/d","/s","/c","start","",t]]:["xdg-open",[t]];try{return be(r[0],r[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function B(e){return new URLSearchParams(e).toString()}async function A(e,t){if(!e?.ok){let o="";try{o=String((await e.json())?.error||"")}catch{}throw new Error(`${t} failed (HTTP ${e?.status||"unknown"}${o?`, ${o}`:""})`)}let r=await e.json();if(!r||typeof r!="object")throw new Error(`${t} returned invalid JSON`);return r}async function Te(e){if(e)return String(await e()).trim();let t=Oe.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function H(e,t={}){let r=String(e.access_token||"").trim(),o=String(e.refresh_token||t.refreshToken||"").trim();if(!r)throw new Error("OAuth token response is missing access token");let n=Number(e.expires_in||3600);return C({accessToken:r,refreshToken:o,expiresAt:Re(t)+Math.max(1,n)*1e3,tokenType:e.token_type||"Bearer",idToken:e.id_token,source:"oracle",...t.discovery?{discovery:t.discovery}:{},...e.scope?{scope:e.scope}:{}})}async function Ke(e){let t=R["anthropic-oauth"],r=e.pkce||$e(),o=new URLSearchParams({code:"true",client_id:t.clientId,response_type:"code",redirect_uri:t.redirectUri,scope:t.scope,code_challenge:r.challenge,code_challenge_method:"S256",state:r.state}),n=`${t.authorizeUrl}?${o}`;e.output(`Open: ${n}`),e.openFn(n);let i=await Te(e.inputFn),[s,p]=i.split("#",2);if(!s||!Ie(p,r.state))throw new Error("Claude OAuth state mismatch");let u=await e.fetchFn(t.tokenUrl,{method:"POST",headers:{"content-type":"application/json","user-agent":"axios/1.7.9"},body:JSON.stringify({grant_type:"authorization_code",client_id:t.clientId,code:s,state:p,redirect_uri:t.redirectUri,code_verifier:r.verifier})});return H(await A(u,"Claude OAuth token exchange"),e)}async function ze(e){let t=R["openai-codex"],r=await A(await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:t.clientId})}),"Codex device authorization");if(!r.user_code||!r.device_auth_id)throw new Error("Codex device authorization returned incomplete data");let o=`${t.issuer}/codex/device`;e.output(`Open: ${o}`),e.output(`Code: ${r.user_code}`),e.openFn(o);let n=Math.max(3,Number(r.interval||5)),i;for(let p=0;p<Math.ceil(900/n);p+=1){await e.sleepFn(n*1e3);let u=await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_auth_id:r.device_auth_id,user_code:r.user_code})});if(u.ok){i=await A(u,"Codex device authorization");break}if(![403,404].includes(u.status))throw new Error(`Codex device authorization failed (HTTP ${u.status})`)}if(!i)throw new Error("Codex device authorization timed out");let s=await e.fetchFn(t.tokenUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:B({grant_type:"authorization_code",code:i.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:i.code_verifier})});return H(await A(s,"Codex OAuth token exchange"),e)}function K(e){let t=new URL(String(e)),r=t.hostname.toLowerCase();if(t.protocol!=="https:"||r!=="x.ai"&&!r.endsWith(".x.ai"))throw new Error("xAI OAuth discovery returned an untrusted endpoint");return t.toString()}async function Fe(e){let t=R["xai-oauth"],r=await A(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");K(r.authorization_endpoint);let o=K(r.token_endpoint),n=await A(await e.fetchFn(t.deviceUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:B({client_id:t.clientId,scope:t.scope})}),"xAI device authorization");if(!n.device_code||!n.user_code||!n.verification_uri)throw new Error("xAI device authorization returned incomplete data");let i=K(n.verification_uri_complete||n.verification_uri);e.output(`Open: ${i}`),e.output(`Code: ${n.user_code}`),e.openFn(i);let s=Math.max(1,Number(n.interval||5)),p=Math.ceil(Math.max(1,Number(n.expires_in||600))/s);for(let u=0;u<p;u+=1){let v=await e.fetchFn(o,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:B({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:n.device_code})});if(v.ok){let U=await A(v,"xAI OAuth token exchange");return H(U,{...e,discovery:{authorization_endpoint:K(r.authorization_endpoint),token_endpoint:o}})}let w="";try{w=String((await v.json())?.error||"")}catch{}if(w==="slow_down")await e.sleepFn((s+1)*1e3);else if(w==="authorization_pending")await e.sleepFn(s*1e3);else throw new Error(`xAI OAuth token exchange failed (HTTP ${v.status}${w?`, ${w}`:""})`)}throw new Error("xAI device authorization timed out")}async function te(e,t={}){let r=_(e),o={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(n=>new Promise(i=>setTimeout(i,n))),openFn:t.openFn||Le,output:t.output||(n=>process.stdout.write(`${n}
|
|
4
|
-
`)),now:t.now,pkce:t.pkce};return r==="anthropic-oauth"?Ke(o):r==="openai-codex"?ze(o):Fe(o)}var re=Object.freeze({openrouter:{model:"openrouter/auto"},openai:{model:"gpt-4.1-mini"},anthropic:{model:"claude-sonnet-4-6"},xai:{model:"grok-4.6"},deepseek:{model:"deepseek-chat"},gemini:{model:"gemini-2.5-flash"},kimi:{model:"kimi-k3"},mistral:{model:"mistral-large-latest"},nous:{model:"moonshotai/kimi-k3"},custom:{model:""}});function
|
|
4
|
+
`)),now:t.now,pkce:t.pkce};return r==="anthropic-oauth"?Ke(o):r==="openai-codex"?ze(o):Fe(o)}var re=Object.freeze({openrouter:{model:"openrouter/auto"},openai:{model:"gpt-4.1-mini"},anthropic:{model:"claude-sonnet-4-6"},xai:{model:"grok-4.6"},deepseek:{model:"deepseek-chat"},gemini:{model:"gemini-2.5-flash"},kimi:{model:"kimi-k3"},mistral:{model:"mistral-large-latest"},nous:{model:"moonshotai/kimi-k3"},qwen:{model:"qwen-plus"},glm:{model:"glm-4.5"},custom:{model:""}});function q(e,t){let r=e.indexOf(t);return r>=0&&e[r+1]?e[r+1]:""}async function De(){let e="";for await(let t of process.stdin)e+=t;return e.trim()}function Me(e="API key: "){if(!process.stdin.isTTY||!process.stdin.setRawMode)throw new Error("non-interactive API-key input requires --stdin");return process.stdout.write(e),new Promise((t,r)=>{let o="",n=()=>{process.stdin.off("data",i),process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write(`
|
|
5
5
|
`)},i=s=>{let p=String(s);for(let u of p){if(u==="\r"||u===`
|
|
6
|
-
`){n(),t(o.trim());return}if(u===""){n(),r(new Error("cancelled"));return}u==="\x7F"||u==="\b"?o=o.slice(0,-1):o+=u}};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",i)})}function
|
|
6
|
+
`){n(),t(o.trim());return}if(u===""){n(),r(new Error("cancelled"));return}u==="\x7F"||u==="\b"?o=o.slice(0,-1):o+=u}};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",i)})}function J(e,t,{baseUrl:r=""}={}){if(e==="custom"&&!String(r||"").trim())throw new Error("custom provider requires --base-url");return{backend:"standalone",...L({provider:e,model:t,baseUrl:r},{requireModel:!0})}}function oe(e,t,r={}){return Z(J(e,t,r))}function Ne(e){process.stdout.write(`storage: ${e.storage}
|
|
7
7
|
`);let t=Object.entries(e.providers||{}),r=Object.entries(e.apiKeys||{});if(!t.length&&!r.length){process.stdout.write(`no credentials configured
|
|
8
8
|
`);return}for(let[o,n]of t){let i=n.expiresAt?new Date(n.expiresAt).toISOString():"unknown";process.stdout.write(`${o}: ${n.loggedIn?"logged in":"missing"}, expires ${i}
|
|
9
9
|
`)}for(let[o,n]of r)process.stdout.write(`${o}: API key ${n.configured?"configured":"missing"}
|
|
10
|
-
`)}function Be(){return["oracle auth, configure OAuth or API-key authentication",""," oracle auth login claude|codex|grok [--model MODEL] [--no-browser]"," oracle auth api-key PROVIDER [--model MODEL] [--base-url URL]"," PROVIDER: openrouter|openai|anthropic|xai|deepseek|gemini|kimi|mistral|nous|custom",` printf '%s\\n' "$KEY" | oracle auth api-key PROVIDER --stdin`," oracle auth status [--json]"," oracle auth logout PROVIDER","","OAuth and API keys are additive. Select any compatible model with oracle model --provider PROVIDER --model MODEL."].join(`
|
|
10
|
+
`)}function Be(){return["oracle auth, configure OAuth or API-key authentication",""," oracle auth login claude|codex|grok [--model MODEL] [--no-browser]"," oracle auth api-key PROVIDER [--model MODEL] [--base-url URL]"," PROVIDER: openrouter|openai|anthropic|xai|deepseek|gemini|kimi|mistral|nous|qwen|glm|custom",` printf '%s\\n' "$KEY" | oracle auth api-key PROVIDER --stdin`," oracle auth status [--json]"," oracle auth logout PROVIDER","","OAuth and API keys are additive. Select any compatible model with oracle model --provider PROVIDER --model MODEL."].join(`
|
|
11
11
|
`)}var lt={name:"auth",summary:"login with Claude, Codex, or Grok OAuth; store provider API keys",group:"read",usage:Be(),async run(e){let t=[...e.argv],r=t.shift()||"status",o=ee();try{if(r==="status"){let n=o.status();return t.includes("--json")?process.stdout.write(`${JSON.stringify(n,null,2)}
|
|
12
|
-
`):Ne(n),0}if(r==="login"){let n=t.find(u=>!u.startsWith("-"));if(!n)throw new Error("usage: oracle auth login claude|codex|grok");let i=Y(n),s=
|
|
13
|
-
`),0}if(r==="api-key"){let n=String(t.find(u=>!u.startsWith("-"))||"").trim().toLowerCase();if(!n)throw new Error("usage: oracle auth api-key PROVIDER [--stdin]");if(!Object.hasOwn(re,n))throw new Error(`unsupported API-key provider: ${n}`);let i=
|
|
12
|
+
`):Ne(n),0}if(r==="login"){let n=t.find(u=>!u.startsWith("-"));if(!n)throw new Error("usage: oracle auth login claude|codex|grok");let i=Y(n),s=q(t,"--model")||i.model;J(i.id,s);let p=await te(i.id,{openFn:t.includes("--no-browser")?()=>!1:void 0});return await o.withLock(async()=>{let u=o.get(i.id);o.set(i.id,p);try{oe(i.id,s)}catch(v){throw u?o.set(i.id,u):o.remove(i.id),v}}),process.stdout.write(`${i.id}: logged in, stored in ${o.storage}
|
|
13
|
+
`),0}if(r==="api-key"){let n=String(t.find(u=>!u.startsWith("-"))||"").trim().toLowerCase();if(!n)throw new Error("usage: oracle auth api-key PROVIDER [--stdin]");if(!Object.hasOwn(re,n))throw new Error(`unsupported API-key provider: ${n}`);let i=q(t,"--model")||re[n].model,s=q(t,"--base-url");J(n,i,{baseUrl:s});let p=t.includes("--stdin")?await De():await Me();return await o.withLock(async()=>{let u=o.getApiKey(n);o.setApiKey(n,p);try{oe(n,i,{baseUrl:s})}catch(v){throw u?o.setApiKey(n,u):o.removeApiKey(n),v}}),process.stdout.write(`${n}: API key configured in ${o.storage}
|
|
14
14
|
`),0}if(r==="logout"){let n=String(t.find(p=>!p.startsWith("-"))||"").trim().toLowerCase();if(!n)throw new Error("usage: oracle auth logout PROVIDER");let i=!1;try{i=o.remove(_(n))}catch{}let s=o.removeApiKey(n);if(!i&&!s)throw new Error(`${n}: no local credential found`);return process.stdout.write(`${n}: local credential removed
|
|
15
15
|
`),0}throw new Error(`unknown auth action: ${r}`)}catch(n){return process.stderr.write(`oracle auth: ${n.message}
|
|
16
16
|
`),1}}};export{lt as default};
|