@oracle-agent/oracle 0.16.0 → 0.18.0
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/dist/assets/profiles/oracle/SOUL.md +14 -0
- package/dist/bin/desk-server.mjs +16 -16
- package/dist/bin/oracle-data-mcp.mjs +7 -7
- package/dist/bin/oracle-gateway.mjs +21 -0
- package/dist/bin/oracle-public-server.mjs +4 -4
- package/dist/bin/oracle-route.mjs +9 -9
- package/dist/bin/oracle-scan.mjs +9 -9
- package/dist/bin/oracle.mjs +19 -18
- package/dist/cli/commands/auth.mjs +12 -12
- package/dist/cli/commands/bootstrap.mjs +7 -7
- package/dist/cli/commands/chain.mjs +15 -15
- package/dist/cli/commands/chat.mjs +36 -36
- package/dist/cli/commands/data.mjs +12 -7
- package/dist/cli/commands/doctor.mjs +5 -5
- package/dist/cli/commands/eval.mjs +18 -0
- package/dist/cli/commands/fees.mjs +4 -4
- package/dist/cli/commands/harness.mjs +6 -12
- package/dist/cli/commands/mcp.mjs +46 -22
- package/dist/cli/commands/model.mjs +42 -42
- package/dist/cli/commands/plugins.mjs +35 -35
- package/dist/cli/commands/setup.mjs +27 -27
- package/dist/cli/commands/sign.mjs +23 -2
- package/dist/cli/commands/swap.mjs +19 -19
- package/dist/data/desk-data.mjs +13 -13
- package/dist/index.mjs +18 -18
- package/dist/router/index.mjs +2 -2
- package/dist/scanner/index.mjs +4 -4
- package/package.json +26 -6
- package/public/oracle-splash/_variants/ice.html +3 -3
- package/public/oracle-splash/_variants/ivory.html +3 -3
- package/public/oracle-splash/index.html +3 -3
package/dist/bin/oracle-scan.mjs
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createHash as me}from"node:crypto";var
|
|
3
|
-
`),s=me("sha256").update(i).digest("hex").slice(0,32);return`${e} ${t} ${s}`}function
|
|
2
|
+
import{createHash as me}from"node:crypto";var be=new Set([408,425,429,500,502,503,504]),j=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),ve=2,K=4e3,z=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],ye=new Set([301,302,303,307,308]),W=3;function ge(e){let t=String(e||"").toLowerCase();return z.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function we(e){let t={};for(let[n,r]of Object.entries(e||{}))ge(n)||(t[n]=r);return t}function Ee(e,t){if(!e)throw new Error(`HTTP redirect from ${t} missing Location`);let n=new URL(String(e),String(t));if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`HTTP redirect from ${t} used unsupported protocol ${n.protocol}`);return n.toString()}function Se(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}var O=new Map;function Ie(e,t,n){let r={};for(let[c,u]of Object.entries(n||{}))r[c.toLowerCase()]=u;let o=Object.keys(r).filter(c=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(c)),i=[...new Set([...z,...o])].sort().map(c=>`${c}=${r[c]??""}`).join(`
|
|
3
|
+
`),s=me("sha256").update(i).digest("hex").slice(0,32);return`${e} ${t} ${s}`}function xe(e,t){let n=Number(t);return Number.isFinite(n)&&n>0?Math.min(n*1e3,K):Math.min(250*2**e,K)+Math.floor(Math.random()*100)}var Ce=e=>new Promise(t=>setTimeout(t,e));async function Ae(e,{fetchImpl:t,method:n,headers:r,body:o,timeoutMs:a}){let i=new AbortController,s=setTimeout(()=>i.abort(),a);try{let c=String(e),u={...r||{}};for(let l=0;l<=W;l+=1){let d=await t(c,{method:n,headers:u,body:o,signal:i.signal,redirect:"manual"}),f=await d.text(),h=null;if(f)try{h=JSON.parse(f)}catch{h=null}if(ye.has(d.status)){if(n!=="GET"&&n!=="HEAD"){let v=new Error(`HTTP ${d.status} ${n} ${c} redirected non-idempotent request`);throw v.status=d.status,v.body=h??f.slice(0,300),v}if(l===W)throw new Error(`HTTP redirect loop for ${e}`);let p=Ee(d.headers?.get?.("location"),c);Se(p,c)||(u=we(u)),c=p;continue}if(!d.ok){let p=new Error(`HTTP ${d.status} ${n} ${c}`);throw p.status=d.status,p.retryAfter=d.headers?.get?.("retry-after")??null,p.body=h??f.slice(0,300),p}return h??f}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(s)}}async function R(e,t={}){let n=t.fetchImpl||globalThis.fetch;if(typeof n!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let r=t.timeoutMs??12e3,o=(t.method||"GET").toUpperCase(),a={Accept:"application/json",...t.headers||{}},i=t.body;i!=null&&typeof i!="string"&&(a["Content-Type"]=a["Content-Type"]||"application/json",i=JSON.stringify(i));let s=Number.isInteger(t.retries)?Math.max(t.retries,0):ve,c=async()=>{let h;for(let p=0;p<=s;p++)try{return await Ae(e,{fetchImpl:n,method:o,headers:a,body:i,timeoutMs:r})}catch(v){h=v;let g=v?.status,A=v?.name==="AbortError",N=new Set([408,425,429]),$=g!=null?N.has(g)||be.has(g)&&j.has(o):!A&&j.has(o);if(p===s||!$)throw v;await Ce(xe(p,v?.retryAfter))}throw h};if(!(t.dedupe!==!1&&o==="GET"&&i==null))return c();let l=Ie(o,e,a),d=O.get(l);if(d)return d;let f=c().finally(()=>O.delete(l));return O.set(l,f),f}var G={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}},Ne=new Map(Object.values(G).map(e=>[e.chainId,e]));function Y(e){return Ne.get(Number(e))||null}function Q(e,t=process.env){let n=Y(e);if(!n)return null;for(let r of n.rpcEnv){let o=(t[r]||"").trim();if(o)return o}return null}import{Interface as ke,getAddress as Ue}from"ethers";var X=new ke(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function J(e,t){try{return Ue(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}var _e={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 qe(e,{rpcUrl:t,env:n=process.env}={}){if(t)return t;let r=Q(e,n);return r||_e[Number(e)]||null}var Re=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Te(e){let t=String(e||""),n=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!Re.test(n))throw new Error(`evm-rpc: ${t} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return n}async function E(e,t,n=[],r={}){let o=String(t||"");Te(o);let a=qe(e,r);if(!a)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let s=await R(a,{method:"POST",body:{jsonrpc:"2.0",id:1,method:t,params:n},fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3});if(s?.error){let c=new Error(s.error.message||JSON.stringify(s.error));throw c.code=s.error.code,c}return s.result}async function Z(e,t={}){let n=await E(e,"eth_blockNumber",[],t);return parseInt(n,16)}async function ee(e,t,n={}){if(!t)throw new Error("rpcGetBalance requires address");let r=await E(e,"eth_getBalance",[t,"latest"],n);return{chainId:Number(e),address:t,balanceWei:BigInt(r).toString(),balanceHex:r}}async function te(e={},t={}){let n=Number(e.chainId??t.chainId??1),r=J(e.token||e.tokenAddress,"token"),o=J(e.account||e.owner||e.address,"account"),a=X.encodeFunctionData("balanceOf",[o]),i=await E(n,"eth_call",[{to:r,data:a},e.blockTag||"latest"],t),s=X.decodeFunctionResult("balanceOf",i),c=BigInt(s[0]);return{chainId:n,token:r,account:o,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:e.blockTag||"latest"}}var Le="https://api.dexscreener.com",nt=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function Be(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||Le).replace(/\/$/,"")}async function ne(e,t={}){if(!e)throw new Error("tokenAddress required");return R(`${Be(t)}/latest/dex/tokens/${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}var k=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"}),$e=/^0x[0-9a-fA-F]{40}$/;function Oe(e={}){let t=[],n=[];if(!e||typeof e!="object")return{ok:!1,errors:["definition must be an object"],warnings:n};if((!Number.isInteger(e.chainId)||e.chainId<=0)&&t.push("chainId must be a positive integer"),(typeof e.key!="string"||!/^[a-z][a-z0-9-]*$/.test(e.key||""))&&t.push('key must be a lowercase slug (e.g. "base")'),(typeof e.name!="string"||!e.name.trim())&&t.push("name is required"),!Array.isArray(e.rpcEnv)||e.rpcEnv.length===0)t.push("rpcEnv must list at least one environment variable name");else for(let o of e.rpcEnv)(typeof o!="string"||!/^[A-Z][A-Z0-9_]*$/.test(o))&&t.push(`rpcEnv entry "${o}" should be an UPPER_SNAKE env var name`);if(e.nativeCurrency){let o=e.nativeCurrency;(typeof o.symbol!="string"||!o.symbol)&&t.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(o.decimals)||t.push("nativeCurrency.decimals must be an integer")}for(let[o,a]of(e.venues||[]).entries()){let i=`venues[${o}]`;if(!a||typeof a!="object"){t.push(`${i} must be an object`);continue}$e.test(a.address||"")||t.push(`${i}.address is not a valid 20-byte address`),/^0x0{40}$/.test(a.address||"")&&t.push(`${i}.address is the zero address -- placeholder left in place?`),a.kind||t.push(`${i}.kind is required (router|quoter|factory|...)`),a.verified?(a.verified.method||t.push(`${i}.verified.method is required`),a.verified.source||t.push(`${i}.verified.source is required`),a.verified.date||n.push(`${i}.verified.date missing -- add one so staleness is visible`)):t.push(`${i} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let r=e.capabilities||{};for(let o of Object.keys(r))k.includes(o)?typeof r[o]!="function"&&t.push(`capability "${o}" must be a function`):t.push(`unknown capability "${o}"`);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:t.length===0,errors:t,warnings:n}}function Pe(e){let{ok:t,errors:n,warnings:r}=Oe(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
|
|
4
4
|
- ${n.join(`
|
|
5
|
-
- `)}`);let o=e.capabilities||{},a=k.filter(s=>typeof o[s]=="function"),i={key:e.key,chainId:e.chainId,name:e.name,rpcEnv:[...e.rpcEnv],nativeCurrency:e.nativeCurrency?{...e.nativeCurrency}:null,explorer:e.explorer||null,venues:(e.venues||[]).map(s=>({...s})),warnings:r,capabilities(){return{chainId:e.chainId,key:e.key,supported:[...a],unsupported:k.filter(s=>!a.includes(s))}},supports(s){return a.includes(s)}};for(let s of k)a.includes(s)?i[s]=async(...c)=>o[s](...c,{scanner:i}):i[s]=async()=>{throw new Error(`${e.key} (chain ${e.chainId}) does not implement "${s}". Supported: ${a.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(i)}var U=new Map;function re(e){let t=Pe(e);return U.set(t.chainId,t),t}function P(e){return U.get(Number(e))||null}function q(){return[...U.values()]}function ae(){let e={};for(let t of U.values())e[t.chainId]={key:t.key,name:t.name,...t.capabilities(),venueCount:t.venues.length,failClosed:t.venues.length===0};return{generatedAt:new Date().toISOString(),chainCount:U.size,capabilities:[...k],chains:e}}var D={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},w=e=>BigInt(e).toString(16).padStart(64,"0"),_=e=>e.slice(2).toLowerCase().padStart(64,"0");function Fe(e,t){return`0x${D.getAmountsOut}`+w(e)+w(64)+w(t.length)+t.map(_).join("")}function De(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length<128)return null;let n=Number(BigInt(`0x${t.slice(64,128)}`));if(!Number.isFinite(n)||n<1||n>16)return null;let r=[];for(let o=0;o<n;o++){let a=128+o*64;if(t.length<a+64)return null;r.push(BigInt(`0x${t.slice(a,a+64)}`))}return r}function F(e,t="router"){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}var V=100;function Ve(e,t){let n=Number(t);if(!Number.isFinite(n)||n<0)throw new Error("slippageBps must be a non-negative number");if(n>V)throw new Error(`slippageBps ${n} exceeds the ${V} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(n))/10000n}function oe(e){let{chainId:t,wrappedNative:n}=e;async function r(o,a,i,s){let c=await E(t,"eth_call",[{to:o,data:Fe(a,i)},"latest"],s);return De(c?.result??c)}return{async quote({tokenIn:o,tokenOut:a,amountIn:i,path:s},c={}){let u=F(c.scanner);if(!u)return{chainId:t,evidence:v.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let l=s||[o,a];if(l.some(f=>!/^0x[0-9a-fA-F]{40}$/.test(f||"")))throw new Error("quote requires valid 20-byte addresses");let d=await r(u,i,l,c);return d?{chainId:t,router:u,path:l,amountIn:String(i),amountOut:d[d.length-1].toString(),hops:l.length-1,evidence:v.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:u,path:l,evidence:v.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:o,amountIn:a,base:i},s={}){let c=F(s.scanner),u=i||n;if(u&&String(o).toLowerCase()===String(u).toLowerCase())return{chainId:t,token:o,verdict:m.UNKNOWN,evidence:v.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!c||!u)return{chainId:t,token:o,verdict:m.UNKNOWN,evidence:v.UNAVAILABLE,reason:c?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let l=await r(c,a,[u,o],s);if(!l)return{chainId:t,token:o,verdict:m.FAIL,evidence:v.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let d=l[l.length-1];if(d===0n)return{chainId:t,token:o,verdict:m.FAIL,evidence:v.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let f=await r(c,d,[o,u],s);if(!f)return{chainId:t,token:o,verdict:m.FAIL,evidence:v.LIVE,leg:"sell",bought:d.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let h=f[f.length-1],p=Number(h*10000n/BigInt(a)),b=m.PASS,y="round trip completes with expected fee/impact loss";return p<5e3?(b=m.FAIL,y=`round trip returns only ${(p/100).toFixed(2)}% -- punitive tax or no real liquidity`):p<9e3&&(b=m.CAUTION,y=`round trip returns ${(p/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:o,base:u,router:c,verdict:b,reason:y,amountIn:String(a),bought:d.toString(),returned:h.toString(),retentionBps:p,evidence:v.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:a,amountIn:i,recipient:s,slippageBps:c=50,deadlineSeconds:u=900,path:l},d={}){let f=d.scanner,h=F(f);if(!h)throw new Error(`chain ${t} 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(s||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let p=l||[o,a],b=await this.quote({tokenIn:o,tokenOut:a,amountIn:i,path:p},d);if(b.evidence!==v.LIVE)throw new Error(`cannot prepare without a live quote (${b.evidence}: ${b.reason??"no reason given"})`);let y=Ve(b.amountOut,c);if(y<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let A=BigInt(Math.floor(Date.now()/1e3)+Number(u)),N=n&&p[0].toLowerCase()===n.toLowerCase()&&d.useNative,$=N?`0x${D.swapExactETHForTokens}`+w(y)+w(128)+_(s)+w(A)+w(p.length)+p.map(_).join(""):`0x${D.swapExactTokensForTokens}`+w(i)+w(y)+w(160)+_(s)+w(A)+w(p.length)+p.map(_).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:h,data:$,value:N?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:b.amountOut,minOut:y.toString(),slippageBps:c,maxSlippageBps:V,deadline:A.toString()},requires:N?[]:[{step:"approve",token:p[0],spender:h,amount:String(i)}],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 He=[100,500,3e3,1e4],ie={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},I=e=>BigInt(e).toString(16).padStart(64,"0"),R=e=>e.slice(2).toLowerCase().padStart(64,"0"),se=/^0x[0-9a-fA-F]{40}$/,M=100;function Me(e,t){let n=Number(t);if(!Number.isFinite(n)||n<0)throw new Error("slippageBps must be a non-negative number");if(n>M)throw new Error(`slippageBps ${n} exceeds the ${M} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(n))/10000n}function H(e,t){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}function ce(e){let{chainId:t,wrappedNative:n}=e;async function r({quoter:a,tokenIn:i,tokenOut:s,amountIn:c,fee:u},l){let d=`0x${ie.quoteExactInputSingle}`+R(i)+R(s)+I(c)+I(u)+I(0),f=await E(t,"eth_call",[{to:a,data:d},"latest"],l).catch(()=>null),h=f?.result??f;if(!h||h==="0x"||h.length<66)return null;let p=BigInt(`0x${h.slice(2,66)}`);return p>0n?p:null}async function o({quoter:a,tokenIn:i,tokenOut:s,amountIn:c},u){let l=[],d=null;for(let f of He){let h=await r({quoter:a,tokenIn:i,tokenOut:s,amountIn:c,fee:f},u);l.push({fee:f,amountOut:h?h.toString():null}),h&&(!d||h>d.amountOut)&&(d={fee:f,amountOut:h})}return{best:d,tried:l}}return{async quote({tokenIn:a,tokenOut:i,amountIn:s},c={}){let u=H(c.scanner,"quoter");if(!u)return{chainId:t,evidence:v.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let f of[a,i])if(!se.test(f||""))throw new Error("quote requires valid 20-byte addresses");let{best:l,tried:d}=await o({quoter:u,tokenIn:a,tokenOut:i,amountIn:s},c);return l?{chainId:t,venue:"uniswap-v3",quoter:u,tokenIn:a,tokenOut:i,amountIn:String(s),amountOut:l.amountOut.toString(),fee:l.fee,triedFeeTiers:d,evidence:v.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:u,tokenIn:a,tokenOut:i,triedFeeTiers:d,evidence:v.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:a,amountIn:i,base:s},c={}){let u=H(c.scanner,"quoter"),l=s||n;if(l&&String(a).toLowerCase()===String(l).toLowerCase())return{chainId:t,token:a,verdict:m.UNKNOWN,evidence:v.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!u||!l)return{chainId:t,token:a,verdict:m.UNKNOWN,evidence:v.UNAVAILABLE,reason:u?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let d=await o({quoter:u,tokenIn:l,tokenOut:a,amountIn:i},c);if(!d.best)return{chainId:t,token:a,verdict:m.FAIL,evidence:v.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier"};let f=await o({quoter:u,tokenIn:a,tokenOut:l,amountIn:d.best.amountOut},c);if(!f.best)return{chainId:t,token:a,verdict:m.FAIL,evidence:v.LIVE,leg:"sell",bought:d.best.amountOut.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let h=f.best.amountOut,p=Number(h*10000n/BigInt(i)),b=m.PASS,y="round trip completes with expected fee/impact loss";return p<5e3?(b=m.FAIL,y=`round trip returns only ${(p/100).toFixed(2)}% -- punitive tax or no real liquidity`):p<9e3&&(b=m.CAUTION,y=`round trip returns ${(p/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:a,base:l,verdict:b,reason:y,amountIn:String(i),bought:d.best.amountOut.toString(),returned:h.toString(),retentionBps:p,buyFee:d.best.fee,sellFee:f.best.fee,evidence:v.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:a,tokenOut:i,amountIn:s,recipient:c,slippageBps:u=50,fee:l},d={}){let f=H(d.scanner,"router");if(!f)throw new Error(`chain ${t} 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(!se.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let h=await this.quote({tokenIn:a,tokenOut:i,amountIn:s},d);if(h.evidence!==v.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let p=l??h.fee,b=Me(h.amountOut,u);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let y=`0x${ie.exactInputSingle}`+R(a)+R(i)+I(p)+R(c)+I(s)+I(b)+I(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:f,data:y,value:"0x0"},guard:{quotedOut:h.amountOut,minOut:b.toString(),slippageBps:u,maxSlippageBps:M,fee:p},requires:[{step:"approve",token:a,spender:f,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 L={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function ue(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function de(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length>=128){let r=Number(BigInt(`0x${t.slice(64,128)}`));if(r>0&&r<=256&&t.length>=128+r*2){let o=t.slice(128,128+r*2),a=Buffer.from(o,"hex").toString("utf8").replace(/\0+$/,"");if(a)return a}}return Buffer.from(t.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function je(e){let{chainId:t}=e;async function n(r,o,a){return E(t,"eth_call",[{to:r,data:o},"latest"],a)}return{async blockNumber(r={}){let o=await Z(t,r);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:v.LIVE}},async nativeBalance(r,o={}){let a=await ee(t,r,o);return{chainId:t,address:r,wei:a?.wei??a?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:v.LIVE}},async tokenBalance({token:r,owner:o},a={}){let i=await te({chainId:t,token:r,owner:o},a);return{chainId:t,token:r,owner:o,raw:i?.balance??i,evidence:v.LIVE}},async resolveToken(r,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(r||""))return{chainId:t,token:r,evidence:v.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[a,i,s,c]=await Promise.all([n(r,L.decimals,o).catch(()=>null),n(r,L.symbol,o).catch(()=>null),n(r,L.name,o).catch(()=>null),n(r,L.totalSupply,o).catch(()=>null)]),u=ue(a?.result??a),l=u!==null||i?.result||s?.result;return{chainId:t,address:r,decimals:u===null?null:Number(u),symbol:de(i?.result??i),name:de(s?.result??s),totalSupply:(ue(c?.result??c)??null)?.toString()??null,evidence:l?v.LIVE:v.UNKNOWN,warning:l?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(r,o={}){let a=e.dexscreenerSlug;if(!a)return{chainId:t,token:r,pools:[],evidence:v.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await ne(r,o).catch(()=>null),c=(i?.pairs||i?.data?.pairs||[]).filter(u=>String(u.chainId).toLowerCase()===String(a).toLowerCase()).map(u=>({pair:u.pairAddress,dex:u.dexId,base:u.baseToken?.address,quote:u.quoteToken?.address,liquidityUsd:u.liquidity?.usd??null,priceUsd:u.priceUsd??null,volume24hUsd:u.volume?.h24??null,createdAt:u.pairCreatedAt??null})).sort((u,l)=>(l.liquidityUsd??0)-(u.liquidityUsd??0));return{chainId:t,token:r,pools:c,evidence:c.length?v.LIVE:v.UNKNOWN}},async scanBlocks({fromBlock:r,toBlock:o,address:a,topics:i,chunkSize:s=2e3}={},c={}){if(!Number.isInteger(r)||!Number.isInteger(o))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(o<r)throw new Error("toBlock must be >= fromBlock");let u=[],l=[];for(let d=r;d<=o;d+=s){let f=Math.min(d+s-1,o);l.push([d,f])}for(let[d,f]of l){let h={fromBlock:`0x${d.toString(16)}`,toBlock:`0x${f.toString(16)}`};a&&(h.address=a),i&&(h.topics=i);let p=await E(t,"eth_getLogs",[h],c).catch(b=>({error:String(b?.message||b)}));if(p?.error)return{chainId:t,fromBlock:r,toBlock:o,logs:u,complete:!1,failedAt:[d,f],error:p.error,evidence:v.UNKNOWN};for(let b of p?.result??p??[])u.push(b)}return{chainId:t,fromBlock:r,toBlock:o,logs:u,complete:!0,chunks:l.length,evidence:v.LIVE}},async scoreRisk(r,o={}){let a=[],i=m.PASS,s=l=>{let d={[m.PASS]:0,[m.CAUTION]:1,[m.UNKNOWN]:2,[m.FAIL]:3};d[l]>d[i]&&(i=l)},c=await this.resolveToken(r,o);c.evidence!==v.LIVE?(a.push({check:"erc20-metadata",result:m.UNKNOWN,detail:c.warning}),s(m.UNKNOWN)):a.push({check:"erc20-metadata",result:m.PASS,detail:`${c.symbol} / ${c.decimals}d`});let u=await this.resolvePools(r,o);if(u.evidence===v.UNAVAILABLE)a.push({check:"liquidity",result:m.UNKNOWN,detail:u.reason}),s(m.UNKNOWN);else if(!u.pools.length)a.push({check:"liquidity",result:m.FAIL,detail:"no pool with liquidity found"}),s(m.FAIL);else{let l=u.pools[0],d=l.liquidityUsd??0;d<5e3?(a.push({check:"liquidity",result:m.CAUTION,detail:`top pool only $${d}`}),s(m.CAUTION)):a.push({check:"liquidity",result:m.PASS,detail:`$${d} on ${l.dex}`}),l.createdAt&&Date.now()-l.createdAt<24*3600*1e3&&(a.push({check:"age",result:m.CAUTION,detail:"pool under 24h old"}),s(m.CAUTION))}if(typeof this.sellSimulation=="function"){let l=await this.sellSimulation({token:r,amountIn:(10n**16n).toString()},o).catch(d=>({verdict:m.UNKNOWN,reason:String(d?.message||d)}));a.push({check:"sellability",result:l.verdict,detail:l.retentionBps!=null?`round trip returns ${(l.retentionBps/100).toFixed(2)}% -- ${l.reason}`:l.reason}),s(l.verdict)}else a.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."}),s(m.UNKNOWN);return{chainId:t,token:r,verdict:i,checks:a,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function le(e){let n={...je(e)},r=new Set((e.venues||[]).map(a=>a.kind));e.venueKind==="uniswap-v3"&&r.has("quoter")&&r.has("router")?Object.assign(n,ce({chainId:e.chainId,wrappedNative:e.wrappedNative})):e.venueKind==="uniswap-v2"&&r.has("router")&&Object.assign(n,oe({chainId:e.chainId,wrappedNative:e.wrappedNative}));let o={};for(let[a,i]of Object.entries(n))o[a]=i.bind(n);return{key:e.key,chainId:e.chainId,name:e.name,rpcEnv:e.rpcEnv,nativeCurrency:e.nativeCurrency,explorer:e.explorer,venues:e.venues||[],capabilities:o}}var Ke=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 pe(){return Ke.map(e=>re(le(e)))}pe();var[he,...fe]=process.argv.slice(2),B=fe.includes("--json"),g=fe.filter(e=>e!=="--json");function x(e){e||S("missing <chain>");let t=P(Number(e));if(t)return t;let n=q().find(r=>r.key===String(e).toLowerCase());if(n)return n;S(`unknown chain "${e}". Known: ${q().map(r=>`${r.key}(${r.chainId})`).join(", ")}`)}function S(e){console.error(`error: ${e}`),process.exit(1)}function C(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
5
|
+
- `)}`);let o=e.capabilities||{},a=k.filter(s=>typeof o[s]=="function"),i={key:e.key,chainId:e.chainId,name:e.name,rpcEnv:[...e.rpcEnv],nativeCurrency:e.nativeCurrency?{...e.nativeCurrency}:null,explorer:e.explorer||null,venues:(e.venues||[]).map(s=>({...s})),warnings:r,capabilities(){return{chainId:e.chainId,key:e.key,supported:[...a],unsupported:k.filter(s=>!a.includes(s))}},supports(s){return a.includes(s)}};for(let s of k)a.includes(s)?i[s]=async(...c)=>o[s](...c,{scanner:i}):i[s]=async()=>{throw new Error(`${e.key} (chain ${e.chainId}) does not implement "${s}". Supported: ${a.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(i)}var U=new Map;function re(e){let t=Pe(e);return U.set(t.chainId,t),t}function P(e){return U.get(Number(e))||null}function T(){return[...U.values()]}function ae(){let e={};for(let t of U.values())e[t.chainId]={key:t.key,name:t.name,...t.capabilities(),venueCount:t.venues.length,failClosed:t.venues.length===0};return{generatedAt:new Date().toISOString(),chainCount:U.size,capabilities:[...k],chains:e}}var F={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},w=e=>BigInt(e).toString(16).padStart(64,"0"),_=e=>e.slice(2).toLowerCase().padStart(64,"0");function De(e,t){return`0x${F.getAmountsOut}`+w(e)+w(64)+w(t.length)+t.map(_).join("")}function Fe(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length<128)return null;let n=Number(BigInt(`0x${t.slice(64,128)}`));if(!Number.isFinite(n)||n<1||n>16)return null;let r=[];for(let o=0;o<n;o++){let a=128+o*64;if(t.length<a+64)return null;r.push(BigInt(`0x${t.slice(a,a+64)}`))}return r}function D(e,t="router"){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}var V=100;function Ve(e,t){let n=Number(t);if(!Number.isFinite(n)||n<0)throw new Error("slippageBps must be a non-negative number");if(n>V)throw new Error(`slippageBps ${n} exceeds the ${V} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(n))/10000n}function oe(e){let{chainId:t,wrappedNative:n}=e;async function r(o,a,i,s){let c=await E(t,"eth_call",[{to:o,data:De(a,i)},"latest"],s);return Fe(c?.result??c)}return{async quote({tokenIn:o,tokenOut:a,amountIn:i,path:s},c={}){let u=D(c.scanner);if(!u)return{chainId:t,evidence:b.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let l=s||[o,a];if(l.some(f=>!/^0x[0-9a-fA-F]{40}$/.test(f||"")))throw new Error("quote requires valid 20-byte addresses");let d=await r(u,i,l,c);return d?{chainId:t,router:u,path:l,amountIn:String(i),amountOut:d[d.length-1].toString(),hops:l.length-1,evidence:b.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:u,path:l,evidence:b.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:o,amountIn:a,base:i},s={}){let c=D(s.scanner),u=i||n;if(u&&String(o).toLowerCase()===String(u).toLowerCase())return{chainId:t,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(!c||!u)return{chainId:t,token:o,verdict:m.UNKNOWN,evidence:b.UNAVAILABLE,reason:c?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let l=await r(c,a,[u,o],s);if(!l)return{chainId:t,token:o,verdict:m.FAIL,evidence:b.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let d=l[l.length-1];if(d===0n)return{chainId:t,token:o,verdict:m.FAIL,evidence:b.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let f=await r(c,d,[o,u],s);if(!f)return{chainId:t,token:o,verdict:m.FAIL,evidence:b.LIVE,leg:"sell",bought:d.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let h=f[f.length-1],p=Number(h*10000n/BigInt(a)),v=m.PASS,g="round trip completes with expected fee/impact loss";return p<5e3?(v=m.FAIL,g=`round trip returns only ${(p/100).toFixed(2)}% -- punitive tax or no real liquidity`):p<9e3&&(v=m.CAUTION,g=`round trip returns ${(p/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:o,base:u,router:c,verdict:v,reason:g,amountIn:String(a),bought:d.toString(),returned:h.toString(),retentionBps:p,evidence:b.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:a,amountIn:i,recipient:s,slippageBps:c=50,deadlineSeconds:u=900,path:l},d={}){let f=d.scanner,h=D(f);if(!h)throw new Error(`chain ${t} 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(s||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let p=l||[o,a],v=await this.quote({tokenIn:o,tokenOut:a,amountIn:i,path:p},d);if(v.evidence!==b.LIVE)throw new Error(`cannot prepare without a live quote (${v.evidence}: ${v.reason??"no reason given"})`);let g=Ve(v.amountOut,c);if(g<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let A=BigInt(Math.floor(Date.now()/1e3)+Number(u)),N=n&&p[0].toLowerCase()===n.toLowerCase()&&d.useNative,$=N?`0x${F.swapExactETHForTokens}`+w(g)+w(128)+_(s)+w(A)+w(p.length)+p.map(_).join(""):`0x${F.swapExactTokensForTokens}`+w(i)+w(g)+w(160)+_(s)+w(A)+w(p.length)+p.map(_).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:h,data:$,value:N?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:v.amountOut,minOut:g.toString(),slippageBps:c,maxSlippageBps:V,deadline:A.toString()},requires:N?[]:[{step:"approve",token:p[0],spender:h,amount:String(i)}],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 He=[100,500,3e3,1e4],ie={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},I=e=>BigInt(e).toString(16).padStart(64,"0"),q=e=>e.slice(2).toLowerCase().padStart(64,"0"),se=/^0x[0-9a-fA-F]{40}$/,M=100;function Me(e,t){let n=Number(t);if(!Number.isFinite(n)||n<0)throw new Error("slippageBps must be a non-negative number");if(n>M)throw new Error(`slippageBps ${n} exceeds the ${M} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(n))/10000n}function H(e,t){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}function ce(e){let{chainId:t,wrappedNative:n}=e;async function r({quoter:a,tokenIn:i,tokenOut:s,amountIn:c,fee:u},l){let d=`0x${ie.quoteExactInputSingle}`+q(i)+q(s)+I(c)+I(u)+I(0),f=await E(t,"eth_call",[{to:a,data:d},"latest"],l).catch(()=>null),h=f?.result??f;if(!h||h==="0x"||h.length<66)return null;let p=BigInt(`0x${h.slice(2,66)}`);return p>0n?p:null}async function o({quoter:a,tokenIn:i,tokenOut:s,amountIn:c},u){let l=[],d=null;for(let f of He){let h=await r({quoter:a,tokenIn:i,tokenOut:s,amountIn:c,fee:f},u);l.push({fee:f,amountOut:h?h.toString():null}),h&&(!d||h>d.amountOut)&&(d={fee:f,amountOut:h})}return{best:d,tried:l}}return{async quote({tokenIn:a,tokenOut:i,amountIn:s},c={}){let u=H(c.scanner,"quoter");if(!u)return{chainId:t,evidence:b.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let f of[a,i])if(!se.test(f||""))throw new Error("quote requires valid 20-byte addresses");let{best:l,tried:d}=await o({quoter:u,tokenIn:a,tokenOut:i,amountIn:s},c);return l?{chainId:t,venue:"uniswap-v3",quoter:u,tokenIn:a,tokenOut:i,amountIn:String(s),amountOut:l.amountOut.toString(),fee:l.fee,triedFeeTiers:d,evidence:b.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:u,tokenIn:a,tokenOut:i,triedFeeTiers:d,evidence:b.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:a,amountIn:i,base:s},c={}){let u=H(c.scanner,"quoter"),l=s||n;if(l&&String(a).toLowerCase()===String(l).toLowerCase())return{chainId:t,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(!u||!l)return{chainId:t,token:a,verdict:m.UNKNOWN,evidence:b.UNAVAILABLE,reason:u?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let d=await o({quoter:u,tokenIn:l,tokenOut:a,amountIn:i},c);if(!d.best)return{chainId:t,token:a,verdict:m.FAIL,evidence:b.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier"};let f=await o({quoter:u,tokenIn:a,tokenOut:l,amountIn:d.best.amountOut},c);if(!f.best)return{chainId:t,token:a,verdict:m.FAIL,evidence:b.LIVE,leg:"sell",bought:d.best.amountOut.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let h=f.best.amountOut,p=Number(h*10000n/BigInt(i)),v=m.PASS,g="round trip completes with expected fee/impact loss";return p<5e3?(v=m.FAIL,g=`round trip returns only ${(p/100).toFixed(2)}% -- punitive tax or no real liquidity`):p<9e3&&(v=m.CAUTION,g=`round trip returns ${(p/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:a,base:l,verdict:v,reason:g,amountIn:String(i),bought:d.best.amountOut.toString(),returned:h.toString(),retentionBps:p,buyFee:d.best.fee,sellFee:f.best.fee,evidence:b.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:a,tokenOut:i,amountIn:s,recipient:c,slippageBps:u=50,fee:l},d={}){let f=H(d.scanner,"router");if(!f)throw new Error(`chain ${t} 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(!se.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let h=await this.quote({tokenIn:a,tokenOut:i,amountIn:s},d);if(h.evidence!==b.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let p=l??h.fee,v=Me(h.amountOut,u);if(v<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let g=`0x${ie.exactInputSingle}`+q(a)+q(i)+I(p)+q(c)+I(s)+I(v)+I(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:f,data:g,value:"0x0"},guard:{quotedOut:h.amountOut,minOut:v.toString(),slippageBps:u,maxSlippageBps:M,fee:p},requires:[{step:"approve",token:a,spender:f,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 L={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function ue(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function de(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length>=128){let r=Number(BigInt(`0x${t.slice(64,128)}`));if(r>0&&r<=256&&t.length>=128+r*2){let o=t.slice(128,128+r*2),a=Buffer.from(o,"hex").toString("utf8").replace(/\0+$/,"");if(a)return a}}return Buffer.from(t.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function je(e){let{chainId:t}=e;async function n(r,o,a){return E(t,"eth_call",[{to:r,data:o},"latest"],a)}return{async blockNumber(r={}){let o=await Z(t,r);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:b.LIVE}},async nativeBalance(r,o={}){let a=await ee(t,r,o);return{chainId:t,address:r,wei:a?.wei??a?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:b.LIVE}},async tokenBalance({token:r,owner:o},a={}){let i=await te({chainId:t,token:r,owner:o},a);return{chainId:t,token:r,owner:o,raw:i?.balance??i,evidence:b.LIVE}},async resolveToken(r,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(r||""))return{chainId:t,token:r,evidence:b.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[a,i,s,c]=await Promise.all([n(r,L.decimals,o).catch(()=>null),n(r,L.symbol,o).catch(()=>null),n(r,L.name,o).catch(()=>null),n(r,L.totalSupply,o).catch(()=>null)]),u=ue(a?.result??a),l=u!==null||i?.result||s?.result;return{chainId:t,address:r,decimals:u===null?null:Number(u),symbol:de(i?.result??i),name:de(s?.result??s),totalSupply:(ue(c?.result??c)??null)?.toString()??null,evidence:l?b.LIVE:b.UNKNOWN,warning:l?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(r,o={}){let a=e.dexscreenerSlug;if(!a)return{chainId:t,token:r,pools:[],evidence:b.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await ne(r,o).catch(()=>null),c=(i?.pairs||i?.data?.pairs||[]).filter(u=>String(u.chainId).toLowerCase()===String(a).toLowerCase()).map(u=>({pair:u.pairAddress,dex:u.dexId,base:u.baseToken?.address,quote:u.quoteToken?.address,liquidityUsd:u.liquidity?.usd??null,priceUsd:u.priceUsd??null,volume24hUsd:u.volume?.h24??null,createdAt:u.pairCreatedAt??null})).sort((u,l)=>(l.liquidityUsd??0)-(u.liquidityUsd??0));return{chainId:t,token:r,pools:c,evidence:c.length?b.LIVE:b.UNKNOWN}},async scanBlocks({fromBlock:r,toBlock:o,address:a,topics:i,chunkSize:s=2e3}={},c={}){if(!Number.isInteger(r)||!Number.isInteger(o))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(o<r)throw new Error("toBlock must be >= fromBlock");let u=[],l=[];for(let d=r;d<=o;d+=s){let f=Math.min(d+s-1,o);l.push([d,f])}for(let[d,f]of l){let h={fromBlock:`0x${d.toString(16)}`,toBlock:`0x${f.toString(16)}`};a&&(h.address=a),i&&(h.topics=i);let p=await E(t,"eth_getLogs",[h],c).catch(v=>({error:String(v?.message||v)}));if(p?.error)return{chainId:t,fromBlock:r,toBlock:o,logs:u,complete:!1,failedAt:[d,f],error:p.error,evidence:b.UNKNOWN};for(let v of p?.result??p??[])u.push(v)}return{chainId:t,fromBlock:r,toBlock:o,logs:u,complete:!0,chunks:l.length,evidence:b.LIVE}},async scoreRisk(r,o={}){let a=[],i=m.PASS,s=l=>{let d={[m.PASS]:0,[m.CAUTION]:1,[m.UNKNOWN]:2,[m.FAIL]:3};d[l]>d[i]&&(i=l)},c=await this.resolveToken(r,o);c.evidence!==b.LIVE?(a.push({check:"erc20-metadata",result:m.UNKNOWN,detail:c.warning}),s(m.UNKNOWN)):a.push({check:"erc20-metadata",result:m.PASS,detail:`${c.symbol} / ${c.decimals}d`});let u=await this.resolvePools(r,o);if(u.evidence===b.UNAVAILABLE)a.push({check:"liquidity",result:m.UNKNOWN,detail:u.reason}),s(m.UNKNOWN);else if(!u.pools.length)a.push({check:"liquidity",result:m.FAIL,detail:"no pool with liquidity found"}),s(m.FAIL);else{let l=u.pools[0],d=l.liquidityUsd??0;d<5e3?(a.push({check:"liquidity",result:m.CAUTION,detail:`top pool only $${d}`}),s(m.CAUTION)):a.push({check:"liquidity",result:m.PASS,detail:`$${d} on ${l.dex}`}),l.createdAt&&Date.now()-l.createdAt<24*3600*1e3&&(a.push({check:"age",result:m.CAUTION,detail:"pool under 24h old"}),s(m.CAUTION))}if(typeof this.sellSimulation=="function"){let l=await this.sellSimulation({token:r,amountIn:(10n**16n).toString()},o).catch(d=>({verdict:m.UNKNOWN,reason:String(d?.message||d)}));a.push({check:"sellability",result:l.verdict,detail:l.retentionBps!=null?`round trip returns ${(l.retentionBps/100).toFixed(2)}% -- ${l.reason}`:l.reason}),s(l.verdict)}else a.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."}),s(m.UNKNOWN);return{chainId:t,token:r,verdict:i,checks:a,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function le(e){let n={...je(e)},r=new Set((e.venues||[]).map(a=>a.kind));e.venueKind==="uniswap-v3"&&r.has("quoter")&&r.has("router")?Object.assign(n,ce({chainId:e.chainId,wrappedNative:e.wrappedNative})):e.venueKind==="uniswap-v2"&&r.has("router")&&Object.assign(n,oe({chainId:e.chainId,wrappedNative:e.wrappedNative}));let o={};for(let[a,i]of Object.entries(n))o[a]=i.bind(n);return{key:e.key,chainId:e.chainId,name:e.name,rpcEnv:e.rpcEnv,nativeCurrency:e.nativeCurrency,explorer:e.explorer,venues:e.venues||[],capabilities:o}}var Ke=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 pe(){return Ke.map(e=>re(le(e)))}pe();var[he,...fe]=process.argv.slice(2),B=fe.includes("--json"),y=fe.filter(e=>e!=="--json");function C(e){e||S("missing <chain>");let t=P(Number(e));if(t)return t;let n=T().find(r=>r.key===String(e).toLowerCase());if(n)return n;S(`unknown chain "${e}". Known: ${T().map(r=>`${r.key}(${r.chainId})`).join(", ")}`)}function S(e){console.error(`error: ${e}`),process.exit(1)}function x(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
6
6
|
`)}function We(e,t){let n=String(t?.message||t);return/rpc|fetch|ECONN|timeout|provider/i.test(n)?`${n}
|
|
7
7
|
|
|
8
8
|
This chain reads its RPC from: ${e.rpcEnv.join(" or ")}
|
|
9
|
-
Set one, e.g.: export ${e.rpcEnv[0]}=https://...`:n}try{switch(he){case"chains":{let e=ae();if(B){
|
|
9
|
+
Set one, e.g.: export ${e.rpcEnv[0]}=https://...`:n}try{switch(he){case"chains":{let e=ae();if(B){x(e);break}console.log(`${e.chainCount} chains registered
|
|
10
10
|
`);let t=Object.entries(e.chains).map(([r,o])=>({chain:`${o.key} (${r})`,caps:o.supported.length,routing:o.failClosed?"fail-closed (no verified venue)":`${o.venueCount} venue(s)`})),n=Math.max(...t.map(r=>r.chain.length));for(let r of t)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 e=
|
|
12
|
+
venue -- see CONTRIBUTING.md for the verification rule.`);break}case"head":{let e=C(y[0]);x(await e.blockNumber());break}case"token":{let e=C(y[0]);y[1]||S("usage: oracle-scan token <chain> <address>"),x(await e.resolveToken(y[1]));break}case"pools":{let e=C(y[0]);y[1]||S("usage: oracle-scan pools <chain> <address>");let t=await e.resolvePools(y[1]);if(B){x(t);break}console.log(`evidence: ${t.evidence}`),t.reason&&console.log(`reason: ${t.reason}`);for(let n of t.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}`)}t.pools.length||console.log(" (no pools with liquidity found)");break}case"risk":{let e=C(y[0]);y[1]||S("usage: oracle-scan risk <chain> <address>");let t=await e.scoreRisk(y[1]);if(B){x(t);break}console.log(`verdict: ${t.verdict}
|
|
13
13
|
`);for(let n of t.checks)console.log(` ${n.result.padEnd(8)} ${n.check.padEnd(16)} ${n.detail??""}`);console.log(`
|
|
14
|
-
${t.note}`);break}case"quote":{let e=
|
|
15
|
-
Add a venue with recorded provenance -- see docs/adding-a-chain.md.`);let t=
|
|
16
|
-
Without it, treat every token on this chain as unproven for exit.`);let t=
|
|
14
|
+
${t.note}`);break}case"quote":{let e=C(y[0]);(!y[1]||!y[2])&&S("usage: oracle-scan quote <chain> <tokenIn> <tokenOut> [amountIn]"),e.supports("quote")||S(`${e.key} has no verified router, so quoting stays fail-closed.
|
|
15
|
+
Add a venue with recorded provenance -- see docs/adding-a-chain.md.`);let t=y[3]||(10n**18n).toString();x(await e.quote({tokenIn:y[1],tokenOut:y[2],amountIn:t}));break}case"sell":{let e=C(y[0]);y[1]||S("usage: oracle-scan sell <chain> <token> [amountIn]"),e.supports("sellSimulation")||S(`${e.key} has no verified router, so sell simulation is unavailable.
|
|
16
|
+
Without it, treat every token on this chain as unproven for exit.`);let t=y[2]||(10n**16n).toString(),n=await e.sellSimulation({token:y[1],amountIn:t});if(B){x(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(he?1:0)}}catch(e){let t=
|
|
18
|
+
`)),process.exit(he?1:0)}}catch(e){let t=y[0]?P(Number(y[0]))||T().find(n=>n.key===y[0]):null;S(t?We(t,e):String(e?.message||e))}
|
package/dist/bin/oracle.mjs
CHANGED
|
@@ -1,21 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{realpathSync as
|
|
2
|
+
import{realpathSync as F}from"node:fs";import{fileURLToPath as he}from"node:url";import _ from"node:fs";import j from"node:path";import{pathToFileURL as le}from"node:url";import g from"node:fs";import q from"node:os";import a from"node:path";import{fileURLToPath as K}from"node:url";var G=a.dirname(K(import.meta.url)),p=a.resolve(G,"../..");function d(){return process.env.ORACLE_FAKE_HOME||q.homedir()}function S(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function k(){return S()?process.env.ORACLE_CONFIG_DIR||a.join(d(),".config","oracle"):a.join(d(),".config","oracle")}function B(){return a.join(k(),"exec.env")}function C(){return a.join(k(),"desk.json")}function L(){return a.join(k(),"env")}function h({force:r=!1}={}){if(h._done&&!r)return h._result||null;h._done=!0;let s={},e=(c,t)=>{if(t==null)return;let o=String(t).trim();o&&(process.env[c]!=null&&String(process.env[c]).trim()!==""||(process.env[c]=o,s[c]=o))};try{let c=L();if(g.existsSync(c))for(let t of g.readFileSync(c,"utf8").split(/\r?\n/)){let o=t.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!o||o[2].startsWith("#"))continue;let i=o[2];(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),e(o[1],i)}}catch{}try{let c=C();if(g.existsSync(c)){let t=JSON.parse(g.readFileSync(c,"utf8"));t&&typeof t=="object"&&(e("ORACLE_DESK_URL",t.deskUrl||t.dataUrl||t.url),e("ORACLE_DATA_URL",t.dataUrl||t.deskUrl||t.url),e("ORACLE_API_URL",t.apiUrl||t.dataUrl||t.deskUrl),e("ORACLE_PUBLIC_URL",t.publicUrl||t.deskUrl||t.dataUrl),e("ORACLE_EXEC_URL",t.execUrl),e("MAD_DESK_URL",t.deskUrl||t.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(e("ORACLE_DESK_URL",n),e("ORACLE_DATA_URL",n),e("ORACLE_API_URL",n),e("ORACLE_PUBLIC_URL",n),e("MAD_DESK_URL",n)),h._result=Object.keys(s).length?s:null,h._result}try{h()}catch{}function J(){return process.env.HERMES_HOME?a.resolve(process.env.HERMES_HOME):a.join(d(),".hermes")}function W(){return a.join(d(),".claude.json")}function z(r=process.cwd()){return a.join(r,".mcp.json")}function V(){return process.platform==="darwin"?a.join(d(),"Library","Application Support","Claude","claude_desktop_config.json"):a.join(d(),".config","Claude","claude_desktop_config.json")}function Y(){return a.join(d(),".codex","config.toml")}function P(){return a.join(k(),"connectors")}function Q(){return a.join(P(),"chatgpt-openapi.json")}function X(){return a.join(k(),"active-chain.json")}function R(r){let s=[a.join(p,"bin",r),a.join(p,"dist","bin",r),a.join(p,"..","bin",r)];return s.find(e=>g.existsSync(e))||s[0]}function Z(r){return g.mkdirSync(r,{recursive:!0}),r}var U={homeDir:d,isPublicDesktop:S,oracleConfigDir:k,oracleExecEnvPath:B,oracleDeskJsonPath:C,oracleEnvFilePath:L,loadDeskRouting:h,hermesRoot:J,activeChainPath:X,claudeCodeUserConfigPath:W,claudeCodeProjectMcpPath:z,claudeDesktopConfigPath:V,codexConfigPath:Y,chatgptConnectorDir:P,chatgptOpenApiPath:Q,packageBin:R,ensureDir:Z,PACKAGE_ROOT:p};import f from"node:fs";import u from"node:path";import{spawnSync as ee}from"node:child_process";import{createRequire as re}from"node:module";import{fileURLToPath as te}from"node:url";var ne=u.dirname(te(import.meta.url)),oe=u.resolve(ne,"../.."),se=Object.freeze(["oracle-vault","oracle-credential","oracle-signer","oracle-runner","oracle-agentic-init","oracle-agentic-doctor","oracle-control-mcp","oracle-operator-caps"]),b=Object.freeze(["vault","credential","signer","runner","sign"]),T=`oracle: signing is unavailable in the public package.
|
|
3
3
|
|
|
4
4
|
The public 'oracle' package is prepare-only and never handles keys.
|
|
5
5
|
Owner-operated signing is private infrastructure and has no public npm install.
|
|
6
6
|
Review and sign prepared artifacts in your own wallet instead.
|
|
7
7
|
|
|
8
8
|
Nothing about your read/research/prepare setup is affected.
|
|
9
|
-
`,
|
|
10
|
-
`)||
|
|
11
|
-
`)}function
|
|
12
|
-
`),3;let
|
|
13
|
-
`),1;let m=typeof l.status=="number"?l.status:1;return m!==0&&
|
|
14
|
-
`),
|
|
9
|
+
`,ce="hint: run 'oracle sign init' to provision keys, or 'oracle sign doctor --json' for detail.";function D(r){let s={};for(let e of se){let n=[u.join(r,e),u.join(r,`${e}.mjs`),u.join(r,`${e}.js`)];for(let c of n)if(f.existsSync(c)&&f.statSync(c).isFile()){s[e]=c;break}}return s}function ie(r){let s=u.dirname(r);for(;s!==u.dirname(s);){let e=u.join(s,"package.json");if(f.existsSync(e))try{let n=JSON.parse(f.readFileSync(e,"utf8"));if(n.name==="@oracle-agent/operator")return{root:s,pkg:n}}catch{}s=u.dirname(s)}return null}function ae(r){for(let s of r)try{let e=re(u.join(s,"package.json")),n;try{let l=e.resolve("@oracle-agent/operator/package.json");n={root:u.dirname(l),pkg:JSON.parse(f.readFileSync(l,"utf8"))}}catch{let l=e.resolve("@oracle-agent/operator");n=ie(l)}if(!n)continue;let{root:c,pkg:t}=n,o=t.bin||{},i={};for(let[l,m]of Object.entries(o))i[l]=u.resolve(c,m);let E=D(u.join(c,"bin"));for(let[l,m]of Object.entries(E))i[l]||(i[l]=m);return{ok:!0,binDir:u.join(c,"bin"),version:t.version||"unknown",bins:i,source:`require:${s}`}}catch{}return null}function y(){if(process.env.ORACLE_PUBLIC_DESKTOP==="1")return{ok:!1,source:"public-desktop"};let r=process.env.ORACLE_OPERATOR_BIN_DIR;if(r){let e=u.resolve(r);if(!f.existsSync(e))return{ok:!1};let n=D(e);if(!Object.keys(n).length)return{ok:!1};let c="unknown",t=u.resolve(e,"../package.json");if(f.existsSync(t))try{c=JSON.parse(f.readFileSync(t,"utf8")).version||c}catch{}return{ok:!0,binDir:e,version:c,bins:n,source:"env:ORACLE_OPERATOR_BIN_DIR"}}return ae([process.cwd(),oe])||{ok:!1}}function x(r=process.stderr){r.write(T),T.endsWith(`
|
|
10
|
+
`)||r.write(`
|
|
11
|
+
`)}function I(r,s=[],e={}){let n=y();if(!n.ok)return x(e.stderr||process.stderr),3;let c=n.bins[r];if(!c)return(e.stderr||process.stderr).write(`oracle: operator bin '${r}' not found in resolved operator (${n.source})
|
|
12
|
+
`),3;let t=e.stdio||"inherit",o=/\.(mjs|cjs|js)$/.test(c),i=o?process.execPath:c,E=o?[c,...s]:[...s],l=ee(i,E,{stdio:t,env:e.env||process.env,cwd:e.cwd||process.cwd(),encoding:t==="pipe"?"utf8":void 0});if(l.error)return(e.stderr||process.stderr).write(`oracle: failed to spawn ${r}: ${l.error.message}
|
|
13
|
+
`),1;let m=typeof l.status=="number"?l.status:1;return m!==0&&e.appendHintOnError&&(e.stderr||process.stderr).write(ce+`
|
|
14
|
+
`),t==="pipe"?{code:m,stdout:l.stdout||"",stderr:l.stderr||""}:m}var ue="oracle \u2014 self-custody multichain agent control plane",pe=`READ / RESEARCH (no keys, this package)
|
|
15
15
|
oracle open the native Oracle chat (TTY)
|
|
16
16
|
oracle bootstrap optional: install an isolated Hermes compatibility runtime
|
|
17
17
|
oracle init install agent lanes + read plane (dry-run by default)
|
|
18
18
|
oracle doctor check read plane; checks signer too when installed
|
|
19
|
+
oracle eval desk run desk harness eval (critical tests + parse smoke)
|
|
19
20
|
oracle chat premium boxed oracle chat (multi-model)
|
|
20
21
|
oracle model choose standalone/Hermes provider and any compatible model
|
|
21
22
|
oracle auth Claude/Codex/Grok OAuth or securely stored provider API keys
|
|
@@ -48,16 +49,16 @@ SIGNING (dispatches to @oracle-agent/operator on THIS machine; never in this pac
|
|
|
48
49
|
|
|
49
50
|
oracle <noun> --help for details. Keys never leave your machine; this package
|
|
50
51
|
cannot sign \u2014 signing commands run the locally installed operator package.
|
|
51
|
-
`;function
|
|
52
|
+
`;function H(){try{return JSON.parse(_.readFileSync(j.join(p,"package.json"),"utf8")).version||"0.0.0"}catch{return"0.0.0"}}function de(){let r=j.join(p,"src","cli","commands");return _.existsSync(r)?r:j.join(p,"dist","cli","commands")}async function v(){let r=de(),s=new Map;if(!_.existsSync(r))return s;let e=_.readdirSync(r).filter(n=>n.endsWith(".mjs")).sort();for(let n of e){let c=j.join(r,n);try{let o=(await import(le(c).href+`?t=${Date.now()}`)).default;if(!o||typeof o!="object"||typeof o.run!="function")continue;let i=o.name||n.replace(/\.mjs$/,"");s.set(i,{...o,name:i,__file:c})}catch(t){process.env.ORACLE_CLI_DEBUG&&console.error(`oracle: failed loading command ${n}: ${t.message}`)}}return s}function w(r,s){let e=[];e.push(`${ue} (v${r})`),e.push(""),e.push(pe.trimEnd());let n=[];for(let c of s.values()){if(["help","version"].includes(c.name))continue;!new Set(["init","doctor","chat","model","chain","setup","data","data-mcp","scan","route","prepare","swap","farm","follow","equities","strategy","public","mcp","plugins","harness","upgrade","bootstrap","eval","sign","vault","signer","runner","credential"]).has(c.name)&&c.summary&&n.push(` oracle ${c.name.padEnd(20)} ${c.summary}`)}return n.length&&(e.push(""),e.push("ADDITIONAL"),e.push(...n)),e.join(`
|
|
52
53
|
`)+`
|
|
53
|
-
`}function
|
|
54
|
+
`}function $(r,s){let e=[...s.keys()].sort(),n=e.length?e.join(", "):"(none loaded yet)";return`oracle: unknown command '${r}'. Known: ${n}
|
|
54
55
|
Try: oracle --help
|
|
55
|
-
`}function
|
|
56
|
-
`),
|
|
57
|
-
`),0):(process.stderr.write(
|
|
58
|
-
`),
|
|
59
|
-
`),0;if(
|
|
60
|
-
`),1}try{let
|
|
61
|
-
`),1}}return
|
|
62
|
-
`),1):(x(process.stderr),3):(process.stderr.write(
|
|
63
|
-
`),0}function
|
|
56
|
+
`}function O(r){return{argv:r,root:p,bin:R,paths:U,dispatchOperator:I,resolveOperator:y}}async function M(r=[]){let s=H();if(r.includes("--version")||r.includes("-V"))return N();if(r[0]==="--help"||r[0]==="-h"){let o=await v();return process.stdout.write(w(s,o)),0}if(r.length===0){let o=await v();if(fe(r)){let i=o.get("chat");if(i)return i.run(O([]))}return process.stdout.write(w(s,o)),0}if(me(r[0])){let i=(await v()).get("chat");if(i)return i.run(O(r))}let e=r[0],n=r.slice(1);if(e==="version")return N();if(e==="help"){let o=await v();if(n[0]){let i=o.get(n[0]);return i?(process.stdout.write((i.usage||`oracle ${i.name}`)+`
|
|
57
|
+
`),i.summary&&process.stdout.write(i.summary+`
|
|
58
|
+
`),0):(process.stderr.write($(n[0],o)),1)}return process.stdout.write(w(s,o)),0}let c=await v(),t=c.get(e);if(t){if(n[0]==="--help"||n[0]==="-h")return process.stdout.write((t.usage||`oracle ${t.name}`)+`
|
|
59
|
+
`),t.summary&&process.stdout.write(t.summary+`
|
|
60
|
+
`),0;if(b.includes(e))try{let o=await t.run(O(n));return typeof o=="number"?o:0}catch(o){return process.stderr.write(`oracle ${e}: ${o?.message||o}
|
|
61
|
+
`),1}try{let o=await t.run(O(n));return typeof o=="number"?o:0}catch(o){return process.stderr.write(`oracle ${e}: ${o?.message||o}
|
|
62
|
+
`),1}}return b.includes(e)?y().ok?(process.stderr.write(`oracle: sign-plane command '${e}' is not available in this build (operator is installed).
|
|
63
|
+
`),1):(x(process.stderr),3):(process.stderr.write($(e,c)),1)}async function N(){let s=`oracle ${H()}`,e=y();return e.ok&&(s+=` operator ${e.version}`),process.stdout.write(s+`
|
|
64
|
+
`),0}function fe(r=[],s={stdin:process.stdin,stdout:process.stdout}){return r.length!==0?!1:process.env.ORACLE_FORCE_CHAT==="1"?!0:s.stdin?.isTTY===!0&&s.stdout?.isTTY===!0}function me(r){return["-m","--model","--provider","-q","--query","-Q","--quiet","-c","--continue","-r","--resume","-s","--skills","-t","--toolsets","--reasoning","--tui","--cli","--yolo","--checkpoints","--source","--max-turns"].includes(String(r||""))}var Ne=Object.freeze({data:"./desk-server.mjs",public:"./oracle-public-server.mjs","data-mcp":"./oracle-data-mcp.mjs",init:"./oracle-init.mjs",upgrade:"./oracle-upgrade.mjs",scan:"./oracle-scan.mjs",route:"./oracle-route.mjs",equities:"./oracle-equities.mjs"});function ge(){if(!process.argv[1])return!1;try{return F(he(import.meta.url))===F(process.argv[1])}catch{return!1}}async function ke(r=process.argv.slice(2)){return M(r)}if(ge()){let r=await ke();process.exit(typeof r=="number"?r:0)}export{Ne as COMMANDS,ke as main};
|
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import $ from"node:fs";import
|
|
2
|
-
`,{mode:384}),$.renameSync(n,r),process.platform!=="win32"&&$.chmodSync(r,384),t}import{createHash as
|
|
3
|
-
`,{mode:384}),g.renameSync(r,e),process.platform!=="win32"&&g.chmodSync(e,384)}function me(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 K(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(),n=Number(e.expiresAt||e.expires_at||0);if(!t)throw new Error("OAuth credential is missing access token");return{accessToken:t,refreshToken:r,expiresAt:Number.isFinite(n)?n: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 we(e={}){let t=e.file||A.join(b(),"oauth.json"),r=e.metadataFile||A.join(A.dirname(t),"oauth-meta.json"),n=e.spawnFn||fe,o=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&me(n),i=o?"linux-secret-service":"private-file",p=`${t}.lock`;async function l(f){q(A.dirname(p));let u;for(let c=0;c<400;c+=1)try{u=g.openSync(p,"wx",384);break}catch(a){if(a?.code!=="EEXIST")throw a;try{Date.now()-g.statSync(p).mtimeMs>3e5&&g.unlinkSync(p)}catch{}await new Promise(d=>setTimeout(d,25))}if(u===void 0)throw new Error("timed out waiting for OAuth credential lock");try{return await f()}finally{try{g.closeSync(u)}catch{}try{g.unlinkSync(p)}catch{}}}function s(f,u="oauth"){return["application","oracle","kind",u,"provider",f]}function h(f){let u=S(f);if(o){let d=n("secret-tool",["lookup",...s(u)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(d.error||d.status!==0||!String(d.stdout||"").trim())return null;try{return C(JSON.parse(String(d.stdout).trim()))}catch{return null}}let a=w(t,{providers:{}}).providers?.[u];if(!a)return null;try{return C(a)}catch{return null}}function y(f,u){let c=S(f),a=C(u);if(o){let m=n("secret-tool",["store",`--label=Oracle ${c} OAuth`,...s(c)],{input:JSON.stringify(a),encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(m.error||m.status!==0)throw new Error("OS credential store rejected OAuth credential");let x=w(r,{providers:{}});return x.providers||={},x.providers[c]={expiresAt:a.expiresAt,source:a.source},k(r,x),a}let d=w(t,{providers:{}});return d.providers||={},d.providers[c]=a,k(t,d),a}function I(f){let u=S(f);if(o){let d=n("secret-tool",["clear",...s(u)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=w(r,{providers:{}});return m.providers&&delete m.providers[u],k(r,m),!d.error&&d.status===0}let c=w(t,{providers:{}}),a=!!c.providers?.[u];return c.providers&&delete c.providers[u],k(t,c),a}function M(f){let u=K(f);if(o){let c=n("secret-tool",["lookup",...s(u,"api-key")],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return c.error||c.status!==0?"":String(c.stdout||"").trim()}return String(w(t,{apiKeys:{}}).apiKeys?.[u]||"").trim()}function Z(f,u){let c=K(f),a=String(u||"").trim();if(!a)throw new Error("API key is empty");if(o){let m=n("secret-tool",["store",`--label=Oracle ${c} API key`,...s(c,"api-key")],{input:a,encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(m.error||m.status!==0)throw new Error("OS credential store rejected API key");let x=w(r,{providers:{},apiKeys:{}});return x.apiKeys||={},x.apiKeys[c]={configured:!0},k(r,x),!0}let d=w(t,{providers:{},apiKeys:{}});return d.apiKeys||={},d.apiKeys[c]=a,k(t,d),!0}function Y(f){let u=K(f);if(o){let d=n("secret-tool",["clear",...s(u,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=w(r,{providers:{},apiKeys:{}});return m.apiKeys&&delete m.apiKeys[u],k(r,m),!d.error&&d.status===0}let c=w(t,{providers:{},apiKeys:{}}),a=!!c.apiKeys?.[u];return c.apiKeys&&delete c.apiKeys[u],k(t,c),a}function Q(){let f={},u={};if(o){let c=w(r,{providers:{},apiKeys:{}});for(let[a,d]of Object.entries(c.providers||{}))f[a]={loggedIn:!!h(a),expiresAt:Number(d.expiresAt||0),source:String(d.source||"oracle"),storage:i};for(let a of Object.keys(c.apiKeys||{}))u[a]={configured:!!M(a),storage:i}}else{let c=w(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:i};for(let[a,d]of Object.entries(c.apiKeys||{}))u[a]={configured:!!d,storage:i}}return{storage:i,providers:f,apiKeys:u}}return Object.freeze({file:t,storage:i,get:h,set:y,remove:I,getApiKey:M,setApiKey:Z,removeApiKey:Y,status:Q,withLock:l})}var H;function V(){return H||=we(),H}function R(e){return Buffer.from(e).toString("base64url")}function ge(){let e=R(U(32));return{verifier:e,challenge:R(ue("sha256").update(e).digest()),state:R(U(24))}}function ye(e,t){let r=Buffer.from(String(e||"")),n=Buffer.from(String(t||""));return r.length===n.length&&de(r,n)}function ve(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 le(r[0],r[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function F(e){return new URLSearchParams(e).toString()}async function _(e,t){if(!e?.ok){let n="";try{n=String((await e.json())?.error||"")}catch{}throw new Error(`${t} failed (HTTP ${e?.status||"unknown"}${n?`, ${n}`:""})`)}let r=await e.json();if(!r||typeof r!="object")throw new Error(`${t} returned invalid JSON`);return r}async function ke(e){if(e)return String(await e()).trim();let t=pe.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function z(e,t={}){let r=String(e.access_token||"").trim(),n=String(e.refresh_token||t.refreshToken||"").trim();if(!r)throw new Error("OAuth token response is missing access token");let o=Number(e.expires_in||3600);return C({accessToken:r,refreshToken:n,expiresAt:he(t)+Math.max(1,o)*1e3,tokenType:e.token_type||"Bearer",idToken:e.id_token,source:"oracle",...t.discovery?{discovery:t.discovery}:{},...e.scope?{scope:e.scope}:{}})}async function xe(e){let t=O["anthropic-oauth"],r=e.pkce||ge(),n=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}),o=`${t.authorizeUrl}?${n}`;e.output(`Open: ${o}`),e.openFn(o);let i=await ke(e.inputFn),[p,l]=i.split("#",2);if(!p||!ye(l,r.state))throw new Error("Claude OAuth state mismatch");let s=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:p,state:l,redirect_uri:t.redirectUri,code_verifier:r.verifier})});return z(await _(s,"Claude OAuth token exchange"),e)}async function Se(e){let t=O["openai-codex"],r=await _(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 n=`${t.issuer}/codex/device`;e.output(`Open: ${n}`),e.output(`Code: ${r.user_code}`),e.openFn(n);let o=Math.max(3,Number(r.interval||5)),i;for(let l=0;l<Math.ceil(900/o);l+=1){await e.sleepFn(o*1e3);let s=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(s.ok){i=await _(s,"Codex device authorization");break}if(![403,404].includes(s.status))throw new Error(`Codex device authorization failed (HTTP ${s.status})`)}if(!i)throw new Error("Codex device authorization timed out");let p=await e.fetchFn(t.tokenUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:F({grant_type:"authorization_code",code:i.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:i.code_verifier})});return z(await _(p,"Codex OAuth token exchange"),e)}function j(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 _e(e){let t=O["xai-oauth"],r=await _(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");j(r.authorization_endpoint);let n=j(r.token_endpoint),o=await _(await e.fetchFn(t.deviceUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:F({client_id:t.clientId,scope:t.scope})}),"xAI device authorization");if(!o.device_code||!o.user_code||!o.verification_uri)throw new Error("xAI device authorization returned incomplete data");let i=j(o.verification_uri_complete||o.verification_uri);e.output(`Open: ${i}`),e.output(`Code: ${o.user_code}`),e.openFn(i);let p=Math.max(1,Number(o.interval||5)),l=Math.ceil(Math.max(1,Number(o.expires_in||600))/p);for(let s=0;s<l;s+=1){let h=await e.fetchFn(n,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:F({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:o.device_code})});if(h.ok){let I=await _(h,"xAI OAuth token exchange");return z(I,{...e,discovery:{authorization_endpoint:j(r.authorization_endpoint),token_endpoint:n}})}let y="";try{y=String((await h.json())?.error||"")}catch{}if(y==="slow_down")await e.sleepFn((p+1)*1e3);else if(y==="authorization_pending")await e.sleepFn(p*1e3);else throw new Error(`xAI OAuth token exchange failed (HTTP ${h.status}${y?`, ${y}`:""})`)}throw new Error("xAI device authorization timed out")}async function W(e,t={}){let r=S(e),n={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(o=>new Promise(i=>setTimeout(i,o))),openFn:t.openFn||ve,output:t.output||(o=>process.stdout.write(`${o}
|
|
4
|
-
`)),now:t.now,pkce:t.pkce};return r==="anthropic-oauth"?
|
|
5
|
-
`)},i=
|
|
6
|
-
`){o(),t(n.trim());return}if(
|
|
1
|
+
import $ from"node:fs";import L from"node:path";import U from"node:fs";import se from"node:os";import O from"node:path";import{fileURLToPath as ce}from"node:url";var ae=O.dirname(ce(import.meta.url)),ze=O.resolve(ae,"../..");function J(){return process.env.ORACLE_FAKE_HOME||se.homedir()}function ue(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function b(){return ue()?process.env.ORACLE_CONFIG_DIR||O.join(J(),".config","oracle"):O.join(J(),".config","oracle")}function de(){return O.join(b(),"desk.json")}function pe(){return O.join(b(),"env")}function E({force:e=!1}={}){if(E._done&&!e)return E._result||null;E._done=!0;let t={},r=(o,i)=>{if(i==null)return;let s=String(i).trim();s&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=s,t[o]=s))};try{let o=pe();if(U.existsSync(o))for(let i of U.readFileSync(o,"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 o=de();if(U.existsSync(o)){let i=JSON.parse(U.readFileSync(o,"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 n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),E._result=Object.keys(t).length?t:null,E._result}try{E()}catch{}function j(e){return U.mkdirSync(e,{recursive:!0}),e}var le=new Set(["auto","standalone","hermes","remote","arch"]),fe=new Set(["openrouter","openai","xai","deepseek","gemini","custom","anthropic-oauth","openai-codex","xai-oauth"]);function he(){return L.join(b(),"model.json")}function k(e){return String(e||"").trim()||void 0}function me(e={}){let t=k(e.backend)?.toLowerCase()||"auto",r=k(e.provider)?.toLowerCase(),n=k(e.model),o=k(e.baseUrl)?.replace(/\/+$/,""),i=k(e.apiKeyEnv),s=Number.parseInt(String(e.contextLength||""),10),p=k(e.reasoningEffort),u=k(e.computeHost||e.remoteHost),g=k(e.computeUser||e.remoteUser),h=k(e.computePath||e.remotePath);if(!le.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(r&&!fe.has(r))throw new Error(`unsupported provider: ${r}`);if(o&&r!=="custom")throw new Error("baseUrl is only supported for the custom provider");if(i&&!/^[A-Z][A-Z0-9_]*$/.test(i))throw new Error("api key env must be an uppercase environment variable name");if(r==="custom"&&!o)throw new Error("custom provider requires baseUrl");if(t==="standalone"&&!n)throw new Error("standalone backend requires a model");if(t==="remote"&&!u)throw new Error("remote backend requires computeHost");return{backend:t,...r?{provider:r}:{},...n?{model:n}:{},...o?{baseUrl:o}:{},...i?{apiKeyEnv:i}:{},...Number.isFinite(s)&&s>0?{contextLength:s}:{},...p?{reasoningEffort:p}:{},...u?{computeHost:u}:{},...g?{computeUser:g}:{},...h?{computePath:h}:{}}}function W(e){let t=me(e),r=he();j(L.dirname(r)),process.platform!=="win32"&&$.chmodSync(L.dirname(r),448);let n=`${r}.${process.pid}.tmp`;return $.writeFileSync(n,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`,{mode:384}),$.renameSync(n,r),process.platform!=="win32"&&$.chmodSync(r,384),t}import{createHash as we,randomBytes as F,timingSafeEqual as ge}from"node:crypto";import y from"node:fs";import x from"node:path";import ye from"node:readline/promises";import{spawn as ve,spawnSync as ke}from"node:child_process";var C=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.5",protocol:"responses"}}),xe=12e4;function _e(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function A(e){let t=String(e||"").trim().toLowerCase();for(let[r,n]of Object.entries(C))if(n.aliases.includes(t))return r;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function V(e){let t=A(e);return{id:t,...C[t]}}function w(e,t={}){if(!y.existsSync(e))return t;try{let r=JSON.parse(y.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: ${x.basename(e)}`)}}function X(e){j(e),process.platform!=="win32"&&y.chmodSync(e,448)}function _(e,t){X(x.dirname(e));let r=`${e}.${process.pid}.${F(4).toString("hex")}.tmp`;y.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
3
|
+
`,{mode:384}),y.renameSync(r,e),process.platform!=="win32"&&y.chmodSync(e,384)}function Ae(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 T(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 R(e={}){let t=String(e.accessToken||e.access_token||"").trim(),r=String(e.refreshToken||e.refresh_token||"").trim(),n=Number(e.expiresAt||e.expires_at||0);if(!t)throw new Error("OAuth credential is missing access token");return{accessToken:t,refreshToken:r,expiresAt:Number.isFinite(n)?n: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 Se(e={}){let t=e.file||x.join(b(),"oauth.json"),r=e.metadataFile||x.join(x.dirname(t),"oauth-meta.json"),n=e.linksFile||x.join(x.dirname(t),"oauth-links.json"),o=()=>typeof e.now=="function"?Number(e.now()):Date.now(),i=e.spawnFn||ke,s=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&Ae(i),p=s?"linux-secret-service":"private-file",u=`${t}.lock`;async function g(f){X(x.dirname(u));let l;for(let c=0;c<400;c+=1)try{l=y.openSync(u,"wx",384);break}catch(a){if(a?.code!=="EEXIST")throw a;try{Date.now()-y.statSync(u).mtimeMs>3e5&&y.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{y.closeSync(l)}catch{}try{y.unlinkSync(u)}catch{}}}function h(f,l="oauth"){return["application","oracle","kind",l,"provider",f]}function P(f){if(!y.existsSync(n))return null;let c=w(n,{providers:{}}).providers?.[f];if(!Array.isArray(c))return null;let a=[];for(let d of c)if(x.isAbsolute(String(d||"")))try{let m=w(d,{}),v=f==="anthropic-oauth"?m.claudeAiOauth:null;if(!v)continue;let ie=R(v);a.push({...ie,refreshToken:"",source:"external-access-only"})}catch{}return a.length?a.find(d=>!d.expiresAt||d.expiresAt>o()+xe)||a[0]:null}function B(f){let l=A(f);if(s){let d=i("secret-tool",["lookup",...h(l)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(!d.error&&d.status===0&&String(d.stdout||"").trim())try{return R(JSON.parse(String(d.stdout).trim()))}catch{}return P(l)}let a=w(t,{providers:{}}).providers?.[l];if(a)try{return R(a)}catch{}return P(l)}function ee(f,l){let c=A(f),a=R(l);if(s){let m=i("secret-tool",["store",`--label=Oracle ${c} OAuth`,...h(c)],{input:JSON.stringify(a),encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(m.error||m.status!==0)throw new Error("OS credential store rejected OAuth credential");let v=w(r,{providers:{}});return v.providers||={},v.providers[c]={expiresAt:a.expiresAt,source:a.source},_(r,v),a}let d=w(t,{providers:{}});return d.providers||={},d.providers[c]=a,_(t,d),a}function te(f){let l=A(f);if(s){let d=i("secret-tool",["clear",...h(l)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=w(r,{providers:{}});return m.providers&&delete m.providers[l],_(r,m),!d.error&&d.status===0}let c=w(t,{providers:{}}),a=!!c.providers?.[l];return c.providers&&delete c.providers[l],_(t,c),a}function H(f){let l=T(f);if(s){let c=i("secret-tool",["lookup",...h(l,"api-key")],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return c.error||c.status!==0?"":String(c.stdout||"").trim()}return String(w(t,{apiKeys:{}}).apiKeys?.[l]||"").trim()}function re(f,l){let c=T(f),a=String(l||"").trim();if(!a)throw new Error("API key is empty");if(s){let m=i("secret-tool",["store",`--label=Oracle ${c} API key`,...h(c,"api-key")],{input:a,encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(m.error||m.status!==0)throw new Error("OS credential store rejected API key");let v=w(r,{providers:{},apiKeys:{}});return v.apiKeys||={},v.apiKeys[c]={configured:!0},_(r,v),!0}let d=w(t,{providers:{},apiKeys:{}});return d.apiKeys||={},d.apiKeys[c]=a,_(t,d),!0}function oe(f){let l=T(f);if(s){let d=i("secret-tool",["clear",...h(l,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=w(r,{providers:{},apiKeys:{}});return m.apiKeys&&delete m.apiKeys[l],_(r,m),!d.error&&d.status===0}let c=w(t,{providers:{},apiKeys:{}}),a=!!c.apiKeys?.[l];return c.apiKeys&&delete c.apiKeys[l],_(t,c),a}function ne(){let f={},l={};if(s){let c=w(r,{providers:{},apiKeys:{}});for(let[a,d]of Object.entries(c.providers||{}))f[a]={loggedIn:!!B(a),expiresAt:Number(d.expiresAt||0),source:String(d.source||"oracle"),storage:p};for(let a of Object.keys(c.apiKeys||{}))l[a]={configured:!!H(a),storage:p}}else{let c=w(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(C)){if(f[c])continue;let a=P(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:B,set:ee,remove:te,getApiKey:H,setApiKey:re,removeApiKey:oe,status:ne,withLock:g})}var q;function G(){return q||=Se(),q}function K(e){return Buffer.from(e).toString("base64url")}function Ee(){let e=K(F(32));return{verifier:e,challenge:K(we("sha256").update(e).digest()),state:K(F(24))}}function Oe(e,t){let r=Buffer.from(String(e||"")),n=Buffer.from(String(t||""));return r.length===n.length&&ge(r,n)}function be(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 ve(r[0],r[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function D(e){return new URLSearchParams(e).toString()}async function S(e,t){if(!e?.ok){let n="";try{n=String((await e.json())?.error||"")}catch{}throw new Error(`${t} failed (HTTP ${e?.status||"unknown"}${n?`, ${n}`:""})`)}let r=await e.json();if(!r||typeof r!="object")throw new Error(`${t} returned invalid JSON`);return r}async function Ce(e){if(e)return String(await e()).trim();let t=ye.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function z(e,t={}){let r=String(e.access_token||"").trim(),n=String(e.refresh_token||t.refreshToken||"").trim();if(!r)throw new Error("OAuth token response is missing access token");let o=Number(e.expires_in||3600);return R({accessToken:r,refreshToken:n,expiresAt:_e(t)+Math.max(1,o)*1e3,tokenType:e.token_type||"Bearer",idToken:e.id_token,source:"oracle",...t.discovery?{discovery:t.discovery}:{},...e.scope?{scope:e.scope}:{}})}async function Pe(e){let t=C["anthropic-oauth"],r=e.pkce||Ee(),n=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}),o=`${t.authorizeUrl}?${n}`;e.output(`Open: ${o}`),e.openFn(o);let i=await Ce(e.inputFn),[s,p]=i.split("#",2);if(!s||!Oe(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 z(await S(u,"Claude OAuth token exchange"),e)}async function Ue(e){let t=C["openai-codex"],r=await S(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 n=`${t.issuer}/codex/device`;e.output(`Open: ${n}`),e.output(`Code: ${r.user_code}`),e.openFn(n);let o=Math.max(3,Number(r.interval||5)),i;for(let p=0;p<Math.ceil(900/o);p+=1){await e.sleepFn(o*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 S(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:D({grant_type:"authorization_code",code:i.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:i.code_verifier})});return z(await S(s,"Codex OAuth token exchange"),e)}function I(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 Re(e){let t=C["xai-oauth"],r=await S(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");I(r.authorization_endpoint);let n=I(r.token_endpoint),o=await S(await e.fetchFn(t.deviceUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:D({client_id:t.clientId,scope:t.scope})}),"xAI device authorization");if(!o.device_code||!o.user_code||!o.verification_uri)throw new Error("xAI device authorization returned incomplete data");let i=I(o.verification_uri_complete||o.verification_uri);e.output(`Open: ${i}`),e.output(`Code: ${o.user_code}`),e.openFn(i);let s=Math.max(1,Number(o.interval||5)),p=Math.ceil(Math.max(1,Number(o.expires_in||600))/s);for(let u=0;u<p;u+=1){let g=await e.fetchFn(n,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:D({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:o.device_code})});if(g.ok){let P=await S(g,"xAI OAuth token exchange");return z(P,{...e,discovery:{authorization_endpoint:I(r.authorization_endpoint),token_endpoint:n}})}let h="";try{h=String((await g.json())?.error||"")}catch{}if(h==="slow_down")await e.sleepFn((s+1)*1e3);else if(h==="authorization_pending")await e.sleepFn(s*1e3);else throw new Error(`xAI OAuth token exchange failed (HTTP ${g.status}${h?`, ${h}`:""})`)}throw new Error("xAI device authorization timed out")}async function Z(e,t={}){let r=A(e),n={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(o=>new Promise(i=>setTimeout(i,o))),openFn:t.openFn||be,output:t.output||(o=>process.stdout.write(`${o}
|
|
4
|
+
`)),now:t.now,pkce:t.pkce};return r==="anthropic-oauth"?Pe(n):r==="openai-codex"?Ue(n):Re(n)}var Y=Object.freeze({openrouter:{model:"openrouter/auto"},openai:{model:"gpt-4.1-mini"},xai:{model:"grok-4.5"},deepseek:{model:"deepseek-chat"},gemini:{model:"gemini-2.5-flash"},custom:{model:""}});function M(e,t){let r=e.indexOf(t);return r>=0&&e[r+1]?e[r+1]:""}async function je(){let e="";for await(let t of process.stdin)e+=t;return e.trim()}function $e(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 n="",o=()=>{process.stdin.off("data",i),process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write(`
|
|
5
|
+
`)},i=s=>{let p=String(s);for(let u of p){if(u==="\r"||u===`
|
|
6
|
+
`){o(),t(n.trim());return}if(u===""){o(),r(new Error("cancelled"));return}u==="\x7F"||u==="\b"?n=n.slice(0,-1):n+=u}};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",i)})}function N(e,t,{baseUrl:r=""}={}){if(!t)throw new Error(`${e} provider requires --model`);let n={backend:"standalone",provider:e,model:t};if(e==="custom"){if(!r)throw new Error("custom provider requires --base-url");n.baseUrl=r}return n}function Q(e,t,r={}){return W(N(e,t,r))}function Ie(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[n,o]of t){let i=o.expiresAt?new Date(o.expiresAt).toISOString():"unknown";process.stdout.write(`${n}: ${o.loggedIn?"logged in":"missing"}, expires ${i}
|
|
9
9
|
`)}for(let[n,o]of r)process.stdout.write(`${n}: API key ${o.configured?"configured":"missing"}
|
|
10
|
-
`)}function
|
|
11
|
-
`)}var
|
|
12
|
-
`):
|
|
13
|
-
`),0}if(r==="api-key"){let o=String(t.find(
|
|
14
|
-
`),0}if(r==="logout"){let o=String(t.find(
|
|
10
|
+
`)}function Le(){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]",` 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
|
+
`)}var tt={name:"auth",summary:"login with Claude, Codex, or Grok OAuth; store provider API keys",group:"read",usage:Le(),async run(e){let t=[...e.argv],r=t.shift()||"status",n=G();try{if(r==="status"){let o=n.status();return t.includes("--json")?process.stdout.write(`${JSON.stringify(o,null,2)}
|
|
12
|
+
`):Ie(o),0}if(r==="login"){let o=t.find(u=>!u.startsWith("-"));if(!o)throw new Error("usage: oracle auth login claude|codex|grok");let i=V(o),s=M(t,"--model")||i.model;N(i.id,s);let p=await Z(i.id,{openFn:t.includes("--no-browser")?()=>!1:void 0});return await n.withLock(async()=>{let u=n.get(i.id);n.set(i.id,p);try{Q(i.id,s)}catch(g){throw u?n.set(i.id,u):n.remove(i.id),g}}),process.stdout.write(`${i.id}: logged in, stored in ${n.storage}
|
|
13
|
+
`),0}if(r==="api-key"){let o=String(t.find(u=>!u.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth api-key PROVIDER [--stdin]");if(!Object.hasOwn(Y,o))throw new Error(`unsupported API-key provider: ${o}`);let i=M(t,"--model")||Y[o].model,s=M(t,"--base-url");N(o,i,{baseUrl:s});let p=t.includes("--stdin")?await je():await $e();return await n.withLock(async()=>{let u=n.getApiKey(o);n.setApiKey(o,p);try{Q(o,i,{baseUrl:s})}catch(g){throw u?n.setApiKey(o,u):n.removeApiKey(o),g}}),process.stdout.write(`${o}: API key configured in ${n.storage}
|
|
14
|
+
`),0}if(r==="logout"){let o=String(t.find(p=>!p.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth logout PROVIDER");let i=!1;try{i=n.remove(A(o))}catch{}let s=n.removeApiKey(o);if(!i&&!s)throw new Error(`${o}: no local credential found`);return process.stdout.write(`${o}: local credential removed
|
|
15
15
|
`),0}throw new Error(`unknown auth action: ${r}`)}catch(o){return process.stderr.write(`oracle auth: ${o.message}
|
|
16
|
-
`),1}}};export{
|
|
16
|
+
`),1}}};export{tt as default};
|