@oracle-agent/oracle 0.12.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/README.md +31 -4
  2. package/SETUP.md +5 -2
  3. package/artifacts/specialist-packs/oracle-full-crypto.json +3 -0
  4. package/dist/address-book.mjs +2 -2
  5. package/dist/assets/profiles/_template/SOUL.md +54 -0
  6. package/dist/assets/profiles/_template/profile.json +22 -0
  7. package/dist/assets/profiles/bitcoin-agent/SOUL.md +31 -0
  8. package/dist/assets/profiles/bitcoin-agent/profile.json +32 -0
  9. package/dist/assets/profiles/hyperliquid-agent/SOUL.md +34 -0
  10. package/dist/assets/profiles/hyperliquid-agent/profile.json +38 -0
  11. package/dist/assets/profiles/oracle/SOUL.md +134 -0
  12. package/dist/assets/profiles/oracle/profile.json +40 -0
  13. package/dist/assets/profiles/polymarket-agent/SOUL.md +35 -0
  14. package/dist/assets/profiles/polymarket-agent/profile.json +34 -0
  15. package/dist/assets/profiles/profile.schema.json +90 -0
  16. package/dist/assets/profiles/protocol-builder/SOUL.md +57 -0
  17. package/dist/assets/profiles/protocol-builder/profile.json +39 -0
  18. package/dist/assets/profiles/robinhood-agent/SOUL.md +53 -0
  19. package/dist/assets/profiles/robinhood-agent/profile.json +41 -0
  20. package/dist/assets/profiles/solana-agent/SOUL.md +37 -0
  21. package/dist/assets/profiles/solana-agent/profile.json +38 -0
  22. package/dist/assets/profiles/stable-agent/SOUL.md +43 -0
  23. package/dist/assets/profiles/stable-agent/profile.json +38 -0
  24. package/dist/assets/skills/balance/SKILL.md +176 -0
  25. package/dist/assets/skills/bitcoin-l1.md +33 -0
  26. package/dist/assets/skills/chain-defi-ecosystem-profiling.md +27 -0
  27. package/dist/assets/skills/evm-contract-research.md +27 -0
  28. package/dist/assets/skills/hyperliquid.md +26 -0
  29. package/dist/assets/skills/multichain-exec-desk.md +33 -0
  30. package/dist/assets/skills/oracle-action-semantics/SKILL.md +40 -0
  31. package/dist/assets/skills/oracle-best-execution/SKILL.md +127 -0
  32. package/dist/assets/skills/oracle-best-execution.md +27 -0
  33. package/dist/assets/skills/oracle-bitcoin/SKILL.md +53 -0
  34. package/dist/assets/skills/oracle-chain-graphs-telegram-cards/SKILL.md +59 -0
  35. package/dist/assets/skills/oracle-chat/SKILL.md +61 -0
  36. package/dist/assets/skills/oracle-chat/chain.SKILL.md +31 -0
  37. package/dist/assets/skills/oracle-chat/setup.SKILL.md +37 -0
  38. package/dist/assets/skills/oracle-circuit-breaker/SKILL.md +51 -0
  39. package/dist/assets/skills/oracle-contract-research/SKILL.md +55 -0
  40. package/dist/assets/skills/oracle-desk/SKILL.md +58 -0
  41. package/dist/assets/skills/oracle-desk.md +27 -0
  42. package/dist/assets/skills/oracle-dex-launch/SKILL.md +38 -0
  43. package/dist/assets/skills/oracle-equities/SKILL.md +62 -0
  44. package/dist/assets/skills/oracle-grants/SKILL.md +69 -0
  45. package/dist/assets/skills/oracle-hypercore-staking/SKILL.md +57 -0
  46. package/dist/assets/skills/oracle-hyperliquid/SKILL.md +56 -0
  47. package/dist/assets/skills/oracle-meme-token-sniper/SKILL.md +73 -0
  48. package/dist/assets/skills/oracle-multichain-nft-launch/SKILL.md +338 -0
  49. package/dist/assets/skills/oracle-multichain-token-launch/SKILL.md +300 -0
  50. package/dist/assets/skills/oracle-nft-gacha-launch/SKILL.md +48 -0
  51. package/dist/assets/skills/oracle-nft-mint-gas-war/SKILL.md +63 -0
  52. package/dist/assets/skills/oracle-polymarket/SKILL.md +60 -0
  53. package/dist/assets/skills/oracle-protocol-builder/SKILL.md +59 -0
  54. package/dist/assets/skills/oracle-protocol-security/SKILL.md +60 -0
  55. package/dist/assets/skills/oracle-public-product/SKILL.md +44 -0
  56. package/dist/assets/skills/oracle-receipts/SKILL.md +52 -0
  57. package/dist/assets/skills/oracle-receipts.md +29 -0
  58. package/dist/assets/skills/oracle-rfq-tokenized-assets/SKILL.md +69 -0
  59. package/dist/assets/skills/oracle-smart-wallet-scanner/SKILL.md +49 -0
  60. package/dist/assets/skills/oracle-solana/SKILL.md +65 -0
  61. package/dist/assets/skills/oracle-solana-nft/SKILL.md +54 -0
  62. package/dist/assets/skills/oracle-token-research/SKILL.md +67 -0
  63. package/dist/assets/skills/solana.md +22 -0
  64. package/dist/bin/desk-server.mjs +56 -11
  65. package/dist/bin/oracle-data-mcp.mjs +6 -6
  66. package/dist/bin/oracle-equities.mjs +20 -0
  67. package/dist/bin/oracle-init.mjs +19 -19
  68. package/dist/bin/oracle-public-server.mjs +4 -4
  69. package/dist/bin/oracle-route.mjs +13 -13
  70. package/dist/bin/oracle-scan.mjs +10 -10
  71. package/dist/bin/oracle.mjs +35 -27
  72. package/dist/cli/commands/auth.mjs +11 -11
  73. package/dist/cli/commands/bootstrap.mjs +6 -6
  74. package/dist/cli/commands/chain.mjs +12 -12
  75. package/dist/cli/commands/chat.mjs +39 -29
  76. package/dist/cli/commands/data-mcp.mjs +2 -2
  77. package/dist/cli/commands/data.mjs +5 -5
  78. package/dist/cli/commands/doctor.mjs +3 -3
  79. package/dist/cli/commands/equities.mjs +15 -0
  80. package/dist/cli/commands/farm.mjs +59 -0
  81. package/dist/cli/commands/follow.mjs +28 -0
  82. package/dist/cli/commands/gate.mjs +4 -4
  83. package/dist/cli/commands/harness.mjs +15 -0
  84. package/dist/cli/commands/init.mjs +3 -3
  85. package/dist/cli/commands/mcp.mjs +50 -23
  86. package/dist/cli/commands/model.mjs +44 -34
  87. package/dist/cli/commands/plugins.mjs +38 -0
  88. package/dist/cli/commands/prepare.mjs +2 -2
  89. package/dist/cli/commands/public.mjs +3 -3
  90. package/dist/cli/commands/resolve.mjs +23 -0
  91. package/dist/cli/commands/route.mjs +2 -2
  92. package/dist/cli/commands/scan.mjs +2 -2
  93. package/dist/cli/commands/setup.mjs +12 -12
  94. package/dist/cli/commands/sign.mjs +19 -2
  95. package/dist/cli/commands/swap.mjs +36 -0
  96. package/dist/cli/commands/upgrade.mjs +2 -2
  97. package/dist/cli/commands/version.mjs +2 -2
  98. package/dist/data/desk-data.mjs +53 -10
  99. package/dist/data/names.mjs +2 -0
  100. package/dist/data/providers/farming.mjs +2 -0
  101. package/dist/equities/index.mjs +1 -0
  102. package/dist/index.mjs +58 -15
  103. package/dist/public-api/agent-grants.mjs +3 -0
  104. package/dist/router/index.mjs +2 -2
  105. package/dist/scanner/index.mjs +3 -3
  106. package/package.json +8 -3
  107. package/public/oracle-splash/_variants/ice.html +2073 -0
  108. package/public/oracle-splash/_variants/ivory.html +2075 -0
  109. package/public/oracle-splash/assets/agents/claude.png +0 -0
  110. package/public/oracle-splash/assets/agents/codex.png +0 -0
  111. package/public/oracle-splash/assets/desktop-app.jpg +0 -0
  112. package/public/oracle-splash/assets/hero/cli-session-poster.jpg +0 -0
  113. package/public/oracle-splash/assets/hero/cli-session.mp4 +0 -0
  114. package/public/oracle-splash/assets/hero/cli-session.webm +0 -0
  115. package/public/oracle-splash/assets/hero/orb-poster.jpg +0 -0
  116. package/public/oracle-splash/assets/hero/orb.webm +0 -0
  117. package/public/oracle-splash/assets/hero/risk-session-poster.jpg +0 -0
  118. package/public/oracle-splash/assets/hero/risk-session.mp4 +0 -0
  119. package/public/oracle-splash/assets/hero/risk-session.webm +0 -0
  120. package/public/oracle-splash/assets/hero/route-session-poster.jpg +0 -0
  121. package/public/oracle-splash/assets/hero/route-session.mp4 +0 -0
  122. package/public/oracle-splash/assets/hero/route-session.webm +0 -0
  123. package/public/oracle-splash/downloads/index.html +241 -0
  124. package/public/oracle-splash/index.html +1211 -242
@@ -1,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import{createHash as fe}from"node:crypto";var ve=new Set([408,425,429,500,502,503,504]),j=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),be=2,K=4e3,z=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],ge=new Set([301,302,303,307,308]),W=3;function ye(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||{}))ye(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,l]of Object.entries(n||{}))r[c.toLowerCase()]=l;let a=Object.keys(r).filter(c=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(c)),i=[...new Set([...z,...a])].sort().map(c=>`${c}=${r[c]??""}`).join(`
3
- `),s=fe("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:a,timeoutMs:o}){let i=new AbortController,s=setTimeout(()=>i.abort(),o);try{let c=String(e),l={...r||{}};for(let d=0;d<=W;d+=1){let u=await t(c,{method:n,headers:l,body:a,signal:i.signal,redirect:"manual"}),m=await u.text(),h=null;if(m)try{h=JSON.parse(m)}catch{h=null}if(ge.has(u.status)){if(n!=="GET"&&n!=="HEAD"){let b=new Error(`HTTP ${u.status} ${n} ${c} redirected non-idempotent request`);throw b.status=u.status,b.body=h??m.slice(0,300),b}if(d===W)throw new Error(`HTTP redirect loop for ${e}`);let p=Ee(u.headers?.get?.("location"),c);Se(p,c)||(l=we(l)),c=p;continue}if(!u.ok){let p=new Error(`HTTP ${u.status} ${n} ${c}`);throw p.status=u.status,p.retryAfter=u.headers?.get?.("retry-after")??null,p.body=h??m.slice(0,300),p}return h??m}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(s)}}async function q(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,a=(t.method||"GET").toUpperCase(),o={Accept:"application/json",...t.headers||{}},i=t.body;i!=null&&typeof i!="string"&&(o["Content-Type"]=o["Content-Type"]||"application/json",i=JSON.stringify(i));let s=Number.isInteger(t.retries)?Math.max(t.retries,0):be,c=async()=>{let h;for(let p=0;p<=s;p++)try{return await Ae(e,{fetchImpl:n,method:a,headers:o,body:i,timeoutMs:r})}catch(b){h=b;let y=b?.status,A=b?.name==="AbortError",N=new Set([408,425,429]),B=y!=null?N.has(y)||ve.has(y)&&j.has(a):!A&&j.has(a);if(p===s||!B)throw b;await Ce(xe(p,b?.retryAfter))}throw h};if(!(t.dedupe!==!1&&a==="GET"&&i==null))return c();let d=Ie(a,e,o),u=O.get(d);if(u)return u;let m=c().finally(()=>O.delete(d));return O.set(d,m),m}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 a=(t[r]||"").trim();if(a)return a}return null}import{Interface as ke,getAddress as _e}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 _e(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}var Re={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 Ue(e,{rpcUrl:t,env:n=process.env}={}){if(t)return t;let r=Q(e,n);return r||Re[Number(e)]||null}var qe=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Le(e){let t=String(e||""),n=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!qe.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 a=String(t||"");Le(a);let o=Ue(e,r);if(!o)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let s=await q(o,{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"),a=J(e.account||e.owner||e.address,"account"),o=X.encodeFunctionData("balanceOf",[a]),i=await E(n,"eth_call",[{to:r,data:o},e.blockTag||"latest"],t),s=X.decodeFunctionResult("balanceOf",i),c=BigInt(s[0]);return{chainId:n,token:r,account:a,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:e.blockTag||"latest"}}var Te="https://api.dexscreener.com";function $e(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||Te).replace(/\/$/,"")}async function ne(e,t={}){if(!e)throw new Error("tokenAddress required");return q(`${$e(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"]),v=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),f=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),Be=/^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 a of e.rpcEnv)(typeof a!="string"||!/^[A-Z][A-Z0-9_]*$/.test(a))&&t.push(`rpcEnv entry "${a}" should be an UPPER_SNAKE env var name`);if(e.nativeCurrency){let a=e.nativeCurrency;(typeof a.symbol!="string"||!a.symbol)&&t.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(a.decimals)||t.push("nativeCurrency.decimals must be an integer")}for(let[a,o]of(e.venues||[]).entries()){let i=`venues[${a}]`;if(!o||typeof o!="object"){t.push(`${i} must be an object`);continue}Be.test(o.address||"")||t.push(`${i}.address is not a valid 20-byte address`),/^0x0{40}$/.test(o.address||"")&&t.push(`${i}.address is the zero address -- placeholder left in place?`),o.kind||t.push(`${i}.kind is required (router|quoter|factory|...)`),o.verified?(o.verified.method||t.push(`${i}.verified.method is required`),o.verified.source||t.push(`${i}.verified.source is required`),o.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 a of Object.keys(r))k.includes(a)?typeof r[a]!="function"&&t.push(`capability "${a}" must be a function`):t.push(`unknown capability "${a}"`);return Object.keys(r).length===0&&n.push("scanner implements no capabilities -- it can only be registered, not used"),r.prepareUnsignedTx&&!r.quote&&n.push("prepareUnsignedTx without quote: no priced expectation to validate the built tx against"),r.prepareUnsignedTx&&!r.sellSimulation&&n.push("prepareUnsignedTx without sellSimulation: cannot prove an asset is exitable before buying"),{ok: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>"}:
2
+ import{createHash as me}from"node:crypto";var ve=new Set([408,425,429,500,502,503,504]),j=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),be=2,K=4e3,z=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],ge=new Set([301,302,303,307,308]),W=3;function ye(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||{}))ye(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 Ce(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 xe=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(ge.has(d.status)){if(n!=="GET"&&n!=="HEAD"){let b=new Error(`HTTP ${d.status} ${n} ${c} redirected non-idempotent request`);throw b.status=d.status,b.body=h??f.slice(0,300),b}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 T(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):be,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(b){h=b;let y=b?.status,A=b?.name==="AbortError",N=new Set([408,425,429]),$=y!=null?N.has(y)||ve.has(y)&&j.has(o):!A&&j.has(o);if(p===s||!$)throw b;await xe(Ce(p,b?.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 Re(e,{rpcUrl:t,env:n=process.env}={}){if(t)return t;let r=Q(e,n);return r||_e[Number(e)]||null}var Te=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function qe(e){let t=String(e||""),n=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!Te.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||"");qe(o);let a=Re(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 T(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";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 T(`${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"]),v=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 a=e.capabilities||{},o=k.filter(s=>typeof a[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:[...o],unsupported:k.filter(s=>!o.includes(s))}},supports(s){return o.includes(s)}};for(let s of k)o.includes(s)?i[s]=async(...c)=>a[s](...c,{scanner:i}):i[s]=async()=>{throw new Error(`${e.key} (chain ${e.chainId}) does not implement "${s}". Supported: ${o.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(i)}var _=new Map;function re(e){let t=Pe(e);return _.set(t.chainId,t),t}function P(e){return _.get(Number(e))||null}function L(){return[..._.values()]}function oe(){let e={};for(let t of _.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:_.size,capabilities:[...k],chains:e}}var V={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},w=e=>BigInt(e).toString(16).padStart(64,"0"),R=e=>e.slice(2).toLowerCase().padStart(64,"0");function Fe(e,t){return`0x${V.getAmountsOut}`+w(e)+w(64)+w(t.length)+t.map(R).join("")}function Ve(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 a=0;a<n;a++){let o=128+a*64;if(t.length<o+64)return null;r.push(BigInt(`0x${t.slice(o,o+64)}`))}return r}function F(e,t="router"){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}var D=100;function De(e,t){let n=Number(t);if(!Number.isFinite(n)||n<0)throw new Error("slippageBps must be a non-negative number");if(n>D)throw new Error(`slippageBps ${n} exceeds the ${D} 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 ae(e){let{chainId:t,wrappedNative:n}=e;async function r(a,o,i,s){let c=await E(t,"eth_call",[{to:a,data:Fe(o,i)},"latest"],s);return Ve(c?.result??c)}return{async quote({tokenIn:a,tokenOut:o,amountIn:i,path:s},c={}){let l=F(c.scanner);if(!l)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 d=s||[a,o];if(d.some(m=>!/^0x[0-9a-fA-F]{40}$/.test(m||"")))throw new Error("quote requires valid 20-byte addresses");let u=await r(l,i,d,c);return u?{chainId:t,router:l,path:d,amountIn:String(i),amountOut:u[u.length-1].toString(),hops:d.length-1,evidence:v.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:l,path:d,evidence:v.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:a,amountIn:o,base:i},s={}){let c=F(s.scanner),l=i||n;if(!c||!l)return{chainId:t,token:a,verdict:f.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 d=await r(c,o,[l,a],s);if(!d)return{chainId:t,token:a,verdict:f.FAIL,evidence:v.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let u=d[d.length-1];if(u===0n)return{chainId:t,token:a,verdict:f.FAIL,evidence:v.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let m=await r(c,u,[a,l],s);if(!m)return{chainId:t,token:a,verdict:f.FAIL,evidence:v.LIVE,leg:"sell",bought:u.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let h=m[m.length-1],p=Number(h*10000n/BigInt(o)),b=f.PASS,y="round trip completes with expected fee/impact loss";return p<5e3?(b=f.FAIL,y=`round trip returns only ${(p/100).toFixed(2)}% -- punitive tax or no real liquidity`):p<9e3&&(b=f.CAUTION,y=`round trip returns ${(p/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:a,base:l,router:c,verdict:b,reason:y,amountIn:String(o),bought:u.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:a,tokenOut:o,amountIn:i,recipient:s,slippageBps:c=50,deadlineSeconds:l=900,path:d},u={}){let m=u.scanner,h=F(m);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=d||[a,o],b=await this.quote({tokenIn:a,tokenOut:o,amountIn:i,path:p},u);if(b.evidence!==v.LIVE)throw new Error(`cannot prepare without a live quote (${b.evidence}: ${b.reason??"no reason given"})`);let y=De(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(l)),N=n&&p[0].toLowerCase()===n.toLowerCase()&&u.useNative,B=N?`0x${V.swapExactETHForTokens}`+w(y)+w(128)+R(s)+w(A)+w(p.length)+p.map(R).join(""):`0x${V.swapExactTokensForTokens}`+w(i)+w(y)+w(160)+R(s)+w(A)+w(p.length)+p.map(R).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:h,data:B,value:N?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:b.amountOut,minOut:y.toString(),slippageBps:c,maxSlippageBps:D,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"),U=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:o,tokenIn:i,tokenOut:s,amountIn:c,fee:l},d){let u=`0x${ie.quoteExactInputSingle}`+U(i)+U(s)+I(c)+I(l)+I(0),m=await E(t,"eth_call",[{to:o,data:u},"latest"],d).catch(()=>null),h=m?.result??m;if(!h||h==="0x"||h.length<66)return null;let p=BigInt(`0x${h.slice(2,66)}`);return p>0n?p:null}async function a({quoter:o,tokenIn:i,tokenOut:s,amountIn:c},l){let d=[],u=null;for(let m of He){let h=await r({quoter:o,tokenIn:i,tokenOut:s,amountIn:c,fee:m},l);d.push({fee:m,amountOut:h?h.toString():null}),h&&(!u||h>u.amountOut)&&(u={fee:m,amountOut:h})}return{best:u,tried:d}}return{async quote({tokenIn:o,tokenOut:i,amountIn:s},c={}){let l=H(c.scanner,"quoter");if(!l)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 m of[o,i])if(!se.test(m||""))throw new Error("quote requires valid 20-byte addresses");let{best:d,tried:u}=await a({quoter:l,tokenIn:o,tokenOut:i,amountIn:s},c);return d?{chainId:t,venue:"uniswap-v3",quoter:l,tokenIn:o,tokenOut:i,amountIn:String(s),amountOut:d.amountOut.toString(),fee:d.fee,triedFeeTiers:u,evidence:v.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:l,tokenIn:o,tokenOut:i,triedFeeTiers:u,evidence:v.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:o,amountIn:i,base:s},c={}){let l=H(c.scanner,"quoter"),d=s||n;if(!l||!d)return{chainId:t,token:o,verdict:f.UNKNOWN,evidence:v.UNAVAILABLE,reason:l?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let u=await a({quoter:l,tokenIn:d,tokenOut:o,amountIn:i},c);if(!u.best)return{chainId:t,token:o,verdict:f.FAIL,evidence:v.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier"};let m=await a({quoter:l,tokenIn:o,tokenOut:d,amountIn:u.best.amountOut},c);if(!m.best)return{chainId:t,token:o,verdict:f.FAIL,evidence:v.LIVE,leg:"sell",bought:u.best.amountOut.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let h=m.best.amountOut,p=Number(h*10000n/BigInt(i)),b=f.PASS,y="round trip completes with expected fee/impact loss";return p<5e3?(b=f.FAIL,y=`round trip returns only ${(p/100).toFixed(2)}% -- punitive tax or no real liquidity`):p<9e3&&(b=f.CAUTION,y=`round trip returns ${(p/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:o,base:d,verdict:b,reason:y,amountIn:String(i),bought:u.best.amountOut.toString(),returned:h.toString(),retentionBps:p,buyFee:u.best.fee,sellFee:m.best.fee,evidence:v.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:i,amountIn:s,recipient:c,slippageBps:l=50,fee:d},u={}){let m=H(u.scanner,"router");if(!m)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:o,tokenOut:i,amountIn:s},u);if(h.evidence!==v.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let p=d??h.fee,b=Me(h.amountOut,l);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let y=`0x${ie.exactInputSingle}`+U(o)+U(i)+I(p)+U(c)+I(s)+I(b)+I(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:m,data:y,value:"0x0"},guard:{quotedOut:h.amountOut,minOut:b.toString(),slippageBps:l,maxSlippageBps:M,fee:p},requires:[{step:"approve",token:o,spender:m,amount:String(s)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var T={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 le(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 a=t.slice(128,128+r*2),o=Buffer.from(a,"hex").toString("utf8").replace(/\0+$/,"");if(o)return o}}return Buffer.from(t.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function je(e){let{chainId:t}=e;async function n(r,a,o){return E(t,"eth_call",[{to:r,data:a},"latest"],o)}return{async blockNumber(r={}){let a=await Z(t,r);return{chainId:t,blockNumber:a?.blockNumber??a,evidence:v.LIVE}},async nativeBalance(r,a={}){let o=await ee(t,r,a);return{chainId:t,address:r,wei:o?.wei??o?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:v.LIVE}},async tokenBalance({token:r,owner:a},o={}){let i=await te({chainId:t,token:r,owner:a},o);return{chainId:t,token:r,owner:a,raw:i?.balance??i,evidence:v.LIVE}},async resolveToken(r,a={}){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[o,i,s,c]=await Promise.all([n(r,T.decimals,a).catch(()=>null),n(r,T.symbol,a).catch(()=>null),n(r,T.name,a).catch(()=>null),n(r,T.totalSupply,a).catch(()=>null)]),l=ue(o?.result??o),d=l!==null||i?.result||s?.result;return{chainId:t,address:r,decimals:l===null?null:Number(l),symbol:le(i?.result??i),name:le(s?.result??s),totalSupply:(ue(c?.result??c)??null)?.toString()??null,evidence:d?v.LIVE:v.UNKNOWN,warning:d?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(r,a={}){let o=e.dexscreenerSlug;if(!o)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,a).catch(()=>null),c=(i?.pairs||i?.data?.pairs||[]).filter(l=>String(l.chainId).toLowerCase()===String(o).toLowerCase()).map(l=>({pair:l.pairAddress,dex:l.dexId,base:l.baseToken?.address,quote:l.quoteToken?.address,liquidityUsd:l.liquidity?.usd??null,priceUsd:l.priceUsd??null,volume24hUsd:l.volume?.h24??null,createdAt:l.pairCreatedAt??null})).sort((l,d)=>(d.liquidityUsd??0)-(l.liquidityUsd??0));return{chainId:t,token:r,pools:c,evidence:c.length?v.LIVE:v.UNKNOWN}},async scanBlocks({fromBlock:r,toBlock:a,address:o,topics:i,chunkSize:s=2e3}={},c={}){if(!Number.isInteger(r)||!Number.isInteger(a))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(a<r)throw new Error("toBlock must be >= fromBlock");let l=[],d=[];for(let u=r;u<=a;u+=s){let m=Math.min(u+s-1,a);d.push([u,m])}for(let[u,m]of d){let h={fromBlock:`0x${u.toString(16)}`,toBlock:`0x${m.toString(16)}`};o&&(h.address=o),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:a,logs:l,complete:!1,failedAt:[u,m],error:p.error,evidence:v.UNKNOWN};for(let b of p?.result??p??[])l.push(b)}return{chainId:t,fromBlock:r,toBlock:a,logs:l,complete:!0,chunks:d.length,evidence:v.LIVE}},async scoreRisk(r,a={}){let o=[],i=f.PASS,s=d=>{let u={[f.PASS]:0,[f.CAUTION]:1,[f.UNKNOWN]:2,[f.FAIL]:3};u[d]>u[i]&&(i=d)},c=await this.resolveToken(r,a);c.evidence!==v.LIVE?(o.push({check:"erc20-metadata",result:f.UNKNOWN,detail:c.warning}),s(f.UNKNOWN)):o.push({check:"erc20-metadata",result:f.PASS,detail:`${c.symbol} / ${c.decimals}d`});let l=await this.resolvePools(r,a);if(l.evidence===v.UNAVAILABLE)o.push({check:"liquidity",result:f.UNKNOWN,detail:l.reason}),s(f.UNKNOWN);else if(!l.pools.length)o.push({check:"liquidity",result:f.FAIL,detail:"no pool with liquidity found"}),s(f.FAIL);else{let d=l.pools[0],u=d.liquidityUsd??0;u<5e3?(o.push({check:"liquidity",result:f.CAUTION,detail:`top pool only $${u}`}),s(f.CAUTION)):o.push({check:"liquidity",result:f.PASS,detail:`$${u} on ${d.dex}`}),d.createdAt&&Date.now()-d.createdAt<24*3600*1e3&&(o.push({check:"age",result:f.CAUTION,detail:"pool under 24h old"}),s(f.CAUTION))}if(typeof this.sellSimulation=="function"){let d=await this.sellSimulation({token:r,amountIn:(10n**16n).toString()},a).catch(u=>({verdict:f.UNKNOWN,reason:String(u?.message||u)}));o.push({check:"sellability",result:d.verdict,detail:d.retentionBps!=null?`round trip returns ${(d.retentionBps/100).toFixed(2)}% -- ${d.reason}`:d.reason}),s(d.verdict)}else o.push({check:"sellability",result:f.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(f.UNKNOWN);return{chainId:t,token:r,verdict:i,checks:o,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function de(e){let n={...je(e)},r=new Set((e.venues||[]).map(o=>o.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,ae({chainId:e.chainId,wrappedNative:e.wrappedNative}));let a={};for(let[o,i]of Object.entries(n))a[o]=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:a}}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},venues:[]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venues:[]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venues:[]},{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(de(e)))}pe();var[he,...me]=process.argv.slice(2),$=me.includes("--json"),g=me.filter(e=>e!=="--json");function C(e){e||S("missing <chain>");let t=P(Number(e));if(t)return t;let n=L().find(r=>r.key===String(e).toLowerCase());if(n)return n;S(`unknown chain "${e}". Known: ${L().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)}
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)}
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=oe();if($){x(e);break}console.log(`${e.chainCount} chains registered
10
- `);let t=Object.entries(e.chains).map(([r,a])=>({chain:`${a.key} (${r})`,caps:a.supported.length,routing:a.failClosed?"fail-closed (no verified venue)":`${a.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(`
9
+ Set one, e.g.: export ${e.rpcEnv[0]}=https://...`:n}try{switch(he){case"chains":{let e=ae();if(B){C(e);break}console.log(`${e.chainCount} chains registered
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=C(g[0]);x(await e.blockNumber());break}case"token":{let e=C(g[0]);g[1]||S("usage: oracle-scan token <chain> <address>"),x(await e.resolveToken(g[1]));break}case"pools":{let e=C(g[0]);g[1]||S("usage: oracle-scan pools <chain> <address>");let t=await e.resolvePools(g[1]);if($){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(g[0]);g[1]||S("usage: oracle-scan risk <chain> <address>");let t=await e.scoreRisk(g[1]);if($){x(t);break}console.log(`verdict: ${t.verdict}
12
+ venue -- see CONTRIBUTING.md for the verification rule.`);break}case"head":{let e=x(g[0]);C(await e.blockNumber());break}case"token":{let e=x(g[0]);g[1]||S("usage: oracle-scan token <chain> <address>"),C(await e.resolveToken(g[1]));break}case"pools":{let e=x(g[0]);g[1]||S("usage: oracle-scan pools <chain> <address>");let t=await e.resolvePools(g[1]);if(B){C(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=x(g[0]);g[1]||S("usage: oracle-scan risk <chain> <address>");let t=await e.scoreRisk(g[1]);if(B){C(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=C(g[0]);(!g[1]||!g[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=g[3]||(10n**18n).toString();x(await e.quote({tokenIn:g[1],tokenOut:g[2],amountIn:t}));break}case"sell":{let e=C(g[0]);g[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=g[2]||(10n**16n).toString(),n=await e.sellSimulation({token:g[1],amountIn:t});if($){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(`
14
+ ${t.note}`);break}case"quote":{let e=x(g[0]);(!g[1]||!g[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=g[3]||(10n**18n).toString();C(await e.quote({tokenIn:g[1],tokenOut:g[2],amountIn:t}));break}case"sell":{let e=x(g[0]);g[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=g[2]||(10n**16n).toString(),n=await e.sellSimulation({token:g[1],amountIn:t});if(B){C(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=g[0]?P(Number(g[0]))||L().find(n=>n.key===g[0]):null;S(t?We(t,e):String(e?.message||e))}
18
+ `)),process.exit(he?1:0)}}catch(e){let t=g[0]?P(Number(g[0]))||q().find(n=>n.key===g[0]):null;S(t?We(t,e):String(e?.message||e))}
@@ -1,33 +1,33 @@
1
1
  #!/usr/bin/env node
2
- import{realpathSync as K}from"node:fs";import{fileURLToPath as Ie}from"node:url";import O from"node:fs";import v from"node:path";import{pathToFileURL as Le}from"node:url";import V from"node:fs";import W from"node:os";import u from"node:path";import{fileURLToPath as Q}from"node:url";var X=u.dirname(Q(import.meta.url)),h=u.resolve(X,"../..");function m(){return process.env.ORACLE_FAKE_HOME||W.homedir()}function g(){return u.join(m(),".config","oracle")}function S(){return u.join(g(),"exec.env")}function Z(){return process.env.HERMES_HOME?u.resolve(process.env.HERMES_HOME):u.join(m(),".hermes")}function ee(){return u.join(m(),".claude.json")}function re(e=process.cwd()){return u.join(e,".mcp.json")}function te(){return process.platform==="darwin"?u.join(m(),"Library","Application Support","Claude","claude_desktop_config.json"):u.join(m(),".config","Claude","claude_desktop_config.json")}function ne(){return u.join(m(),".codex","config.toml")}function _(){return u.join(g(),"connectors")}function oe(){return u.join(_(),"chatgpt-openapi.json")}function se(){return u.join(g(),"active-chain.json")}function ae(e){return u.join(h,"bin",e)}function ce(e){return V.mkdirSync(e,{recursive:!0}),e}var N={homeDir:m,oracleConfigDir:g,oracleExecEnvPath:S,hermesRoot:Z,activeChainPath:se,claudeCodeUserConfigPath:ee,claudeCodeProjectMcpPath:re,claudeDesktopConfigPath:te,codexConfigPath:ne,chatgptConnectorDir:_,chatgptOpenApiPath:oe,packageBin:ae,ensureDir:ce,PACKAGE_ROOT:h};import{readFileSync as T,writeFileSync as me,existsSync as D,mkdirSync as he}from"node:fs";import P from"node:path";import{Contract as ie,JsonRpcProvider as le,verifyMessage as Ye}from"ethers";var k="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",ue=999,pe="https://rpc.hyperliquid.xyz/evm",de=["function balanceOf(address owner) view returns (uint256)"],ze=300*1e3,Ke=720*60*1e3,fe=/^0x[a-fA-F0-9]{40}$/;function b(e){return fe.test(String(e||""))}async function L(e,{contract:t=k,rpc:r=pe,chainId:n=ue}={}){let o=new le(r,n,{staticNetwork:!0}),c=new ie(t,de,o);return BigInt(await c.balanceOf(e))}var ge=Object.freeze(new Set(["help","version","gate","init","doctor","bootstrap","upgrade","auth","model"])),we=600*1e3;function $(){return P.join(g(),"gate-cache.json")}function ye(e=Date.now(),t=$()){try{if(!D(t))return null;let r=JSON.parse(T(t,"utf8"));return!r||typeof r!="object"||!Number.isFinite(r.checkedAt)||e-r.checkedAt>we||!b(r.address)?null:r}catch{return null}}function xe(e,t=$()){try{he(P.dirname(t),{recursive:!0}),me(t,JSON.stringify(e),{mode:384})}catch{}}function Oe(e=S()){if(!D(e))return null;try{let t=T(e,"utf8");for(let r of t.split(`
3
- `)){let n=r.match(/^\s*(?:export\s+)?ORACLE_EVM_ADDRESS\s*=\s*(.+?)\s*$/);if(!n)continue;let o=n[1].trim().replace(/^["']|["']$/g,"");if(b(o))return o}}catch{return null}return null}var R=`oracle: this build is for Locals Only holders.
2
+ import{realpathSync as Q}from"node:fs";import{fileURLToPath as Me}from"node:url";import x from"node:fs";import b from"node:path";import{pathToFileURL as Re}from"node:url";import N from"node:fs";import X from"node:os";import u from"node:path";import{fileURLToPath as Z}from"node:url";var ee=u.dirname(Z(import.meta.url)),m=u.resolve(ee,"../..");function h(){return process.env.ORACLE_FAKE_HOME||X.homedir()}function R(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function w(){return R()?process.env.ORACLE_CONFIG_DIR||u.join(h(),".config","oracle"):u.join(h(),".config","oracle")}function S(){return u.join(w(),"exec.env")}function re(){return process.env.HERMES_HOME?u.resolve(process.env.HERMES_HOME):u.join(h(),".hermes")}function te(){return u.join(h(),".claude.json")}function ne(e=process.cwd()){return u.join(e,".mcp.json")}function oe(){return process.platform==="darwin"?u.join(h(),"Library","Application Support","Claude","claude_desktop_config.json"):u.join(h(),".config","Claude","claude_desktop_config.json")}function se(){return u.join(h(),".codex","config.toml")}function T(){return u.join(w(),"connectors")}function ae(){return u.join(T(),"chatgpt-openapi.json")}function ce(){return u.join(w(),"active-chain.json")}function k(e){let t=[u.join(m,"bin",e),u.join(m,"dist","bin",e),u.join(m,"..","bin",e)];return t.find(r=>N.existsSync(r))||t[0]}function ie(e){return N.mkdirSync(e,{recursive:!0}),e}var D={homeDir:h,isPublicDesktop:R,oracleConfigDir:w,oracleExecEnvPath:S,hermesRoot:re,activeChainPath:ce,claudeCodeUserConfigPath:te,claudeCodeProjectMcpPath:ne,claudeDesktopConfigPath:oe,codexConfigPath:se,chatgptConnectorDir:T,chatgptOpenApiPath:ae,packageBin:k,ensureDir:ie,PACKAGE_ROOT:m};import{readFileSync as q,writeFileSync as ke,existsSync as J,mkdirSync as Ae}from"node:fs";import U from"node:path";import{Contract as le,JsonRpcProvider as ue,verifyMessage as Ye}from"ethers";var A="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",pe=999,de="https://rpc.hyperliquid.xyz/evm",fe=["function balanceOf(address owner) view returns (uint256)"],ze=300*1e3,Ve=720*60*1e3,me=/^0x[a-fA-F0-9]{40}$/;function E(e){return me.test(String(e||""))}async function P(e,{contract:t=A,rpc:r=de,chainId:n=pe}={}){let o=new ue(r,n,{staticNetwork:!0}),c=new le(t,fe,o);return BigInt(await c.balanceOf(e))}import d from"node:fs";import i from"node:path";import{spawnSync as $}from"node:child_process";import{createRequire as he}from"node:module";import{fileURLToPath as ge}from"node:url";var we=i.dirname(ge(import.meta.url)),ye=i.resolve(we,"../.."),M=Object.freeze(["oracle-vault","oracle-credential","oracle-signer","oracle-runner","oracle-agentic-init","oracle-agentic-doctor","oracle-control-mcp","oracle-operator-caps"]),C=Object.freeze(["vault","credential","signer","runner","sign"]),I=`oracle: signing is unavailable in the public package.
3
+
4
+ The public 'oracle' package is prepare-only and never handles keys.
5
+ Owner-operated signing is private infrastructure and has no public npm install.
6
+ Review and sign prepared artifacts in your own wallet instead.
7
+
8
+ Nothing about your read/research/prepare setup is affected.
9
+ `,Oe="hint: run 'oracle sign init' to provision keys, or 'oracle sign doctor --json' for detail.";function H(e){let r=(process.env.PATH||"").split(i.delimiter).filter(Boolean),n=process.platform==="win32"?["",".cmd",".exe",".bat"]:[""];for(let o of r)for(let c of n){let a=i.join(o,e+c);try{if(d.existsSync(a)&&d.statSync(a).isFile())return a}catch{}}return null}function B(e){let t={};for(let r of M){let n=[i.join(e,r),i.join(e,`${r}.mjs`),i.join(e,`${r}.js`)];for(let o of n)if(d.existsSync(o)&&d.statSync(o).isFile()){t[r]=o;break}}return t}function ve(e){let t=i.dirname(e);for(;t!==i.dirname(t);){let r=i.join(t,"package.json");if(d.existsSync(r))try{let n=JSON.parse(d.readFileSync(r,"utf8"));if(n.name==="@oracle-agent/operator")return{root:t,pkg:n}}catch{}t=i.dirname(t)}return null}function xe(e){for(let t of e)try{let r=he(i.join(t,"package.json")),n;try{let l=r.resolve("@oracle-agent/operator/package.json");n={root:i.dirname(l),pkg:JSON.parse(d.readFileSync(l,"utf8"))}}catch{let l=r.resolve("@oracle-agent/operator");n=ve(l)}if(!n)continue;let{root:o,pkg:c}=n,a=c.bin||{},s={};for(let[l,f]of Object.entries(a))s[l]=i.resolve(o,f);let p=B(i.join(o,"bin"));for(let[l,f]of Object.entries(p))s[l]||(s[l]=f);return{ok:!0,binDir:i.join(o,"bin"),version:c.version||"unknown",bins:s,source:`require:${t}`}}catch{}return null}function be(){let e=H("oracle-operator-caps");if(!e)return null;let t=$(e,[],{encoding:"utf8",timeout:5e3,env:process.env});if(t.status!==0||!t.stdout)return null;try{let r=JSON.parse(t.stdout);return!r||typeof r!="object"||!r.bins?null:{ok:!0,binDir:i.dirname(Object.values(r.bins)[0]||e),version:r.version||"unknown",bins:r.bins,source:"caps-path",controlMcp:r.controlMcp}}catch{return null}}function Se(){let e={};for(let t of M){let r=H(t);r&&(e[t]=r)}return Object.keys(e).length?{ok:!0,binDir:i.dirname(Object.values(e)[0]),version:"unknown",bins:e,source:"path-probe"}:null}function g(){if(process.env.ORACLE_PUBLIC_DESKTOP==="1")return{ok:!1,source:"public-desktop"};let e=process.env.ORACLE_OPERATOR_BIN_DIR;if(e){let r=i.resolve(e);if(!d.existsSync(r))return{ok:!1};let n=B(r);if(!Object.keys(n).length)return{ok:!1};let o="unknown",c=i.resolve(r,"../package.json");if(d.existsSync(c))try{o=JSON.parse(d.readFileSync(c,"utf8")).version||o}catch{}return{ok:!0,binDir:r,version:o,bins:n,source:"env:ORACLE_OPERATOR_BIN_DIR"}}return xe([process.cwd(),ye])||be()||Se()||{ok:!1}}function j(e=process.stderr){e.write(I),I.endsWith(`
10
+ `)||e.write(`
11
+ `)}function F(e,t=[],r={}){let n=g();if(!n.ok)return j(r.stderr||process.stderr),3;let o=n.bins[e];if(!o)return(r.stderr||process.stderr).write(`oracle: operator bin '${e}' not found in resolved operator (${n.source})
12
+ `),3;let c=r.stdio||"inherit",a=/\.(mjs|cjs|js)$/.test(o),s=a?process.execPath:o,p=a?[o,...t]:[...t],l=$(s,p,{stdio:c,env:r.env||process.env,cwd:r.cwd||process.cwd(),encoding:c==="pipe"?"utf8":void 0});if(l.error)return(r.stderr||process.stderr).write(`oracle: failed to spawn ${e}: ${l.error.message}
13
+ `),1;let f=typeof l.status=="number"?l.status:1;return f!==0&&r.appendHintOnError&&(r.stderr||process.stderr).write(Oe+`
14
+ `),c==="pipe"?{code:f,stdout:l.stdout||"",stderr:l.stderr||""}:f}var Ee=Object.freeze(new Set(["help","version","gate","init","doctor","bootstrap","upgrade","auth","model"])),Ce=600*1e3;function K(){return U.join(w(),"gate-cache.json")}function je(e=Date.now(),t=K()){try{if(!J(t))return null;let r=JSON.parse(q(t,"utf8"));return!r||typeof r!="object"||!Number.isFinite(r.checkedAt)||e-r.checkedAt>Ce||!E(r.address)?null:r}catch{return null}}function _e(e,t=K()){try{Ae(U.dirname(t),{recursive:!0}),ke(t,JSON.stringify(e),{mode:384})}catch{}}function Le(e=S()){if(!J(e))return null;try{let t=q(e,"utf8");for(let r of t.split(`
15
+ `)){let n=r.match(/^\s*(?:export\s+)?ORACLE_EVM_ADDRESS\s*=\s*(.+?)\s*$/);if(!n)continue;let o=n[1].trim().replace(/^["']|["']$/g,"");if(E(o))return o}}catch{return null}return null}var G=`oracle: this build is for Locals Only holders.
4
16
 
5
17
  Oracle checks the agent wallet it created for you, or a wallet you imported.
6
- Hold a Locals Only NFT in that wallet to unlock the CLI.
18
+ Hold a Locals Only NFT in that wallet to use this build.
7
19
 
8
- contract ${k}
20
+ contract ${A}
9
21
  chain HyperEVM (999)
10
22
 
11
23
  Check status: oracle gate status
12
24
  Check a wallet: oracle gate check <address>
13
- `,ve=`oracle: no wallet configured yet.
25
+ `,Ne=`oracle: no wallet configured yet.
14
26
 
15
27
  Run 'oracle init' to create an agent wallet or import your own, then Oracle
16
28
  can verify your Locals Only holding.
17
- `;async function x(e,{now:t=Date.now(),address:r=Oe(),balanceOf:n=L,cache:o=ye(t),persist:c=xe,env:a=process.env}={}){if(ge.has(e))return{allow:!0,reason:"ungated"};if(a.ORACLE_GATE_BYPASS==="1")return{allow:!0,reason:"bypass"};if(!r)return{allow:!1,reason:"no-wallet",message:ve};if(o&&o.address.toLowerCase()===r.toLowerCase())return o.holder?{allow:!0,reason:"cached-holder"}:{allow:!1,reason:"cached-denied",message:R};let s;try{s=await n(r)}catch(l){return{allow:!0,reason:"unverifiable",warning:`oracle: could not verify Locals Only holding (${l.message}); continuing.
18
- `}}let p=BigInt(s)>0n;return c({address:r.toLowerCase(),holder:p,balance:String(s),checkedAt:t}),p?{allow:!0,reason:"holder"}:{allow:!1,reason:"denied",message:R}}import d from"node:fs";import i from"node:path";import{spawnSync as M}from"node:child_process";import{createRequire as Se}from"node:module";import{fileURLToPath as ke}from"node:url";var be=i.dirname(ke(import.meta.url)),Ae=i.resolve(be,"../.."),H=Object.freeze(["oracle-vault","oracle-credential","oracle-signer","oracle-runner","oracle-agentic-init","oracle-agentic-doctor","oracle-control-mcp","oracle-operator-caps"]),F=Object.freeze(["vault","credential","signer","runner","sign"]),I=`oracle: signing is unavailable in the public package.
19
-
20
- The public 'oracle' package is prepare-only and never handles keys.
21
- Owner-operated signing is private infrastructure and has no public npm install.
22
- Review and sign prepared artifacts in your own wallet instead.
23
-
24
- Nothing about your read/research/prepare setup is affected.
25
- `,Ee="hint: run 'oracle sign init' to provision keys, or 'oracle sign doctor --json' for detail.";function B(e){let r=(process.env.PATH||"").split(i.delimiter).filter(Boolean),n=process.platform==="win32"?["",".cmd",".exe",".bat"]:[""];for(let o of r)for(let c of n){let a=i.join(o,e+c);try{if(d.existsSync(a)&&d.statSync(a).isFile())return a}catch{}}return null}function G(e){let t={};for(let r of H){let n=[i.join(e,r),i.join(e,`${r}.mjs`),i.join(e,`${r}.js`)];for(let o of n)if(d.existsSync(o)&&d.statSync(o).isFile()){t[r]=o;break}}return t}function je(e){let t=i.dirname(e);for(;t!==i.dirname(t);){let r=i.join(t,"package.json");if(d.existsSync(r))try{let n=JSON.parse(d.readFileSync(r,"utf8"));if(n.name==="@oracle-agent/operator")return{root:t,pkg:n}}catch{}t=i.dirname(t)}return null}function Ce(e){for(let t of e)try{let r=Se(i.join(t,"package.json")),n;try{let l=r.resolve("@oracle-agent/operator/package.json");n={root:i.dirname(l),pkg:JSON.parse(d.readFileSync(l,"utf8"))}}catch{let l=r.resolve("@oracle-agent/operator");n=je(l)}if(!n)continue;let{root:o,pkg:c}=n,a=c.bin||{},s={};for(let[l,f]of Object.entries(a))s[l]=i.resolve(o,f);let p=G(i.join(o,"bin"));for(let[l,f]of Object.entries(p))s[l]||(s[l]=f);return{ok:!0,binDir:i.join(o,"bin"),version:c.version||"unknown",bins:s,source:`require:${t}`}}catch{}return null}function _e(){let e=B("oracle-operator-caps");if(!e)return null;let t=M(e,[],{encoding:"utf8",timeout:5e3,env:process.env});if(t.status!==0||!t.stdout)return null;try{let r=JSON.parse(t.stdout);return!r||typeof r!="object"||!r.bins?null:{ok:!0,binDir:i.dirname(Object.values(r.bins)[0]||e),version:r.version||"unknown",bins:r.bins,source:"caps-path",controlMcp:r.controlMcp}}catch{return null}}function Ne(){let e={};for(let t of H){let r=B(t);r&&(e[t]=r)}return Object.keys(e).length?{ok:!0,binDir:i.dirname(Object.values(e)[0]),version:"unknown",bins:e,source:"path-probe"}:null}function w(){let e=process.env.ORACLE_OPERATOR_BIN_DIR;if(e){let r=i.resolve(e);if(!d.existsSync(r))return{ok:!1};let n=G(r);if(!Object.keys(n).length)return{ok:!1};let o="unknown",c=i.resolve(r,"../package.json");if(d.existsSync(c))try{o=JSON.parse(d.readFileSync(c,"utf8")).version||o}catch{}return{ok:!0,binDir:r,version:o,bins:n,source:"env:ORACLE_OPERATOR_BIN_DIR"}}return Ce([process.cwd(),Ae])||_e()||Ne()||{ok:!1}}function A(e=process.stderr){e.write(I),I.endsWith(`
26
- `)||e.write(`
27
- `)}function J(e,t=[],r={}){let n=w();if(!n.ok)return A(r.stderr||process.stderr),3;let o=n.bins[e];if(!o)return(r.stderr||process.stderr).write(`oracle: operator bin '${e}' not found in resolved operator (${n.source})
28
- `),3;let c=r.stdio||"inherit",a=/\.(mjs|cjs|js)$/.test(o),s=a?process.execPath:o,p=a?[o,...t]:[...t],l=M(s,p,{stdio:c,env:r.env||process.env,cwd:r.cwd||process.cwd(),encoding:c==="pipe"?"utf8":void 0});if(l.error)return(r.stderr||process.stderr).write(`oracle: failed to spawn ${e}: ${l.error.message}
29
- `),1;let f=typeof l.status=="number"?l.status:1;return f!==0&&r.appendHintOnError&&(r.stderr||process.stderr).write(Ee+`
30
- `),c==="pipe"?{code:f,stdout:l.stdout||"",stderr:l.stderr||""}:f}var Re="oracle \u2014 self-custody multichain agent control plane",Te=`READ / RESEARCH (no keys, this package)
29
+ `;async function O(e,{now:t=Date.now(),address:r=Le(),balanceOf:n=P,cache:o=je(t),persist:c=_e,env:a=process.env,operator:s=g}={}){if(Ee.has(e))return{allow:!0,reason:"ungated"};if(a.ORACLE_GATE_BYPASS==="1")return{allow:!0,reason:"bypass"};try{if(s().ok)return{allow:!0,reason:"operator"}}catch{}if(!r)return{allow:!1,reason:"no-wallet",message:Ne};if(o&&o.address.toLowerCase()===r.toLowerCase())return o.holder?{allow:!0,reason:"cached-holder"}:{allow:!1,reason:"cached-denied",message:G};let p;try{p=await n(r)}catch(f){return{allow:!0,reason:"unverifiable",warning:`oracle: could not verify Locals Only holding (${f.message}); continuing.
30
+ `}}let l=BigInt(p)>0n;return c({address:r.toLowerCase(),holder:l,balance:String(p),checkedAt:t}),l?{allow:!0,reason:"holder"}:{allow:!1,reason:"denied",message:G}}var Te="oracle \u2014 self-custody multichain agent control plane",De=`READ / RESEARCH (no keys, this package)
31
31
  oracle open the native Oracle chat (TTY)
32
32
  oracle bootstrap optional: install an isolated Hermes compatibility runtime
33
33
  oracle init install agent lanes + read plane (dry-run by default)
@@ -41,9 +41,16 @@ import{realpathSync as K}from"node:fs";import{fileURLToPath as Ie}from"node:url"
41
41
  oracle data-mcp start the read-only MCP server
42
42
  oracle scan chains|head|token|pools|risk|quote|sell
43
43
  oracle route swap|bridge|prepare|prepare-bridge
44
+ oracle swap <chain> <sell> <buy> <amt> --taker <addr> unsigned swap + calldata
45
+ oracle farm methods|discover|airdrop
44
46
  oracle prepare build an unsigned swap (alias of route prepare)
47
+ oracle equities venues|quote|prepare
48
+ Crossbook: HIP-3 / Arcus / RH / Solana / TON best-ex
45
49
  oracle public serve secret-free public HTTP surface
46
50
  oracle mcp install <t> wire Oracle into claude-code|claude-desktop|codex|chatgpt
51
+ oracle plugins install|list|remove|scan|setup
52
+ manage Agent Plugins (open-standard portable agent tooling)
53
+ oracle harness detect|list scan PATH for installed agent harnesses (opencode, claude, codex, cursor\u2026)
47
54
  oracle upgrade upgrade installed agent lanes
48
55
 
49
56
  SIGNING (dispatches to @oracle-agent/operator on THIS machine; never in this package)
@@ -54,15 +61,16 @@ SIGNING (dispatches to @oracle-agent/operator on THIS machine; never in this pac
54
61
 
55
62
  oracle <noun> --help for details. Keys never leave your machine; this package
56
63
  cannot sign \u2014 signing commands run the locally installed operator package.
57
- `;function Y(){try{return JSON.parse(O.readFileSync(v.join(h,"package.json"),"utf8")).version||"0.0.0"}catch{return"0.0.0"}}function De(){let e=v.join(h,"src","cli","commands");return O.existsSync(e)?e:v.join(h,"dist","cli","commands")}async function y(){let e=De(),t=new Map;if(!O.existsSync(e))return t;let r=O.readdirSync(e).filter(n=>n.endsWith(".mjs")).sort();for(let n of r){let o=v.join(e,n);try{let a=(await import(Le(o).href+`?t=${Date.now()}`)).default;if(!a||typeof a!="object"||typeof a.run!="function")continue;let s=a.name||n.replace(/\.mjs$/,"");t.set(s,{...a,name:s,__file:o})}catch(c){process.env.ORACLE_CLI_DEBUG&&console.error(`oracle: failed loading command ${n}: ${c.message}`)}}return t}function E(e,t){let r=[];r.push(`${Re} (v${e})`),r.push(""),r.push(Te.trimEnd());let n=[];for(let o of t.values()){if(["help","version"].includes(o.name))continue;!new Set(["init","doctor","chat","model","chain","setup","data","data-mcp","scan","route","prepare","public","mcp","upgrade","bootstrap","sign","vault","signer","runner","credential"]).has(o.name)&&o.summary&&n.push(` oracle ${o.name.padEnd(20)} ${o.summary}`)}return n.length&&(r.push(""),r.push("ADDITIONAL"),r.push(...n)),r.join(`
64
+ `;function V(){try{return JSON.parse(x.readFileSync(b.join(m,"package.json"),"utf8")).version||"0.0.0"}catch{return"0.0.0"}}function Pe(){let e=b.join(m,"src","cli","commands");return x.existsSync(e)?e:b.join(m,"dist","cli","commands")}async function y(){let e=Pe(),t=new Map;if(!x.existsSync(e))return t;let r=x.readdirSync(e).filter(n=>n.endsWith(".mjs")).sort();for(let n of r){let o=b.join(e,n);try{let a=(await import(Re(o).href+`?t=${Date.now()}`)).default;if(!a||typeof a!="object"||typeof a.run!="function")continue;let s=a.name||n.replace(/\.mjs$/,"");t.set(s,{...a,name:s,__file:o})}catch(c){process.env.ORACLE_CLI_DEBUG&&console.error(`oracle: failed loading command ${n}: ${c.message}`)}}return t}function _(e,t){let r=[];r.push(`${Te} (v${e})`),r.push(""),r.push(De.trimEnd());let n=[];for(let o of t.values()){if(["help","version"].includes(o.name))continue;!new Set(["init","doctor","chat","model","chain","setup","data","data-mcp","scan","route","prepare","swap","farm","follow","equities","public","mcp","plugins","harness","upgrade","bootstrap","sign","vault","signer","runner","credential"]).has(o.name)&&o.summary&&n.push(` oracle ${o.name.padEnd(20)} ${o.summary}`)}return n.length&&(r.push(""),r.push("ADDITIONAL"),r.push(...n)),r.join(`
58
65
  `)+`
59
- `}function q(e,t){let r=[...t.keys()].sort(),n=r.length?r.join(", "):"(none loaded yet)";return`oracle: unknown command '${e}'. Known: ${n}
66
+ `}function Y(e,t){let r=[...t.keys()].sort(),n=r.length?r.join(", "):"(none loaded yet)";return`oracle: unknown command '${e}'. Known: ${n}
60
67
  Try: oracle --help
61
- `}function j(e){return{argv:e,root:h,paths:N,dispatchOperator:J,resolveOperator:w}}async function z(e=[]){let t=Y();if(e.includes("--version")||e.includes("-V"))return U();if(e[0]==="--help"||e[0]==="-h"){let a=await y();return process.stdout.write(E(t,a)),0}if(e.length===0){let a=await y();if(Pe(e)){let s=await x("chat");if(!s.allow)return process.stderr.write(s.message),77;s.warning&&process.stderr.write(s.warning);let p=a.get("chat");if(p)return p.run(j([]))}return process.stdout.write(E(t,a)),0}if($e(e[0])){let a=await y(),s=await x("chat");if(!s.allow)return process.stderr.write(s.message),77;s.warning&&process.stderr.write(s.warning);let p=a.get("chat");if(p)return p.run(j(e))}let r=e[0],n=e.slice(1);if(r==="version")return U();if(r==="help"){let a=await y();if(n[0]){let s=a.get(n[0]);return s?(process.stdout.write((s.usage||`oracle ${s.name}`)+`
68
+ `}function v(e){return{argv:e,root:m,bin:k,paths:D,dispatchOperator:F,resolveOperator:g}}async function W(e=[]){let t=V();if(e.includes("--version")||e.includes("-V"))return z();if(e[0]==="--help"||e[0]==="-h"){let a=await y();return process.stdout.write(_(t,a)),0}if(e.length===0){let a=await y();if(Ie(e)){let s=await O("chat");if(!s.allow)return process.stderr.write(s.message),77;s.warning&&process.stderr.write(s.warning);let p=a.get("chat");if(p)return p.run(v([]))}return process.stdout.write(_(t,a)),0}if($e(e[0])){let a=await y(),s=await O("chat");if(!s.allow)return process.stderr.write(s.message),77;s.warning&&process.stderr.write(s.warning);let p=a.get("chat");if(p)return p.run(v(e))}let r=e[0],n=e.slice(1);if(r==="version")return z();if(r==="help"){let a=await y();if(n[0]){let s=a.get(n[0]);return s?(process.stdout.write((s.usage||`oracle ${s.name}`)+`
62
69
  `),s.summary&&process.stdout.write(s.summary+`
63
- `),0):(process.stderr.write(q(n[0],a)),1)}return process.stdout.write(E(t,a)),0}let o=await y(),c=o.get(r);if(c){if(n[0]==="--help"||n[0]==="-h")return process.stdout.write((c.usage||`oracle ${c.name}`)+`
70
+ `),0):(process.stderr.write(Y(n[0],a)),1)}return process.stdout.write(_(t,a)),0}let o=await y(),c=o.get(r);if(c){if(n[0]==="--help"||n[0]==="-h")return process.stdout.write((c.usage||`oracle ${c.name}`)+`
64
71
  `),c.summary&&process.stdout.write(c.summary+`
65
- `),0;let a=await x(r);if(!a.allow)return process.stderr.write(a.message),77;a.warning&&process.stderr.write(a.warning);try{let s=await c.run(j(n));return typeof s=="number"?s:0}catch(s){return process.stderr.write(`oracle ${r}: ${s?.message||s}
66
- `),1}}return F.includes(r)?w().ok?(process.stderr.write(`oracle: sign-plane command '${r}' is not available in this build (operator is installed).
67
- `),1):(A(process.stderr),3):(process.stderr.write(q(r,o)),1)}async function U(){let t=`oracle ${Y()}`,r=w();return r.ok&&(t+=` operator ${r.version}`),process.stdout.write(t+`
68
- `),0}function Pe(e=[],t={stdin:process.stdin,stdout:process.stdout}){return e.length!==0?!1:process.env.ORACLE_FORCE_CHAT==="1"?!0:t.stdin?.isTTY===!0&&t.stdout?.isTTY===!0}function $e(e){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(e||""))}var wr=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"});function Me(){if(!process.argv[1])return!1;try{return K(Ie(import.meta.url))===K(process.argv[1])}catch{return!1}}async function He(e=process.argv.slice(2)){return z(e)}if(Me()){let e=await He();process.exit(typeof e=="number"?e:0)}export{wr as COMMANDS,He as main};
72
+ `),0;if(C.includes(r))try{let s=await c.run(v(n));return typeof s=="number"?s:0}catch(s){return process.stderr.write(`oracle ${r}: ${s?.message||s}
73
+ `),1}let a=await O(r);if(!a.allow)return process.stderr.write(a.message),77;a.warning&&process.stderr.write(a.warning);try{let s=await c.run(v(n));return typeof s=="number"?s:0}catch(s){return process.stderr.write(`oracle ${r}: ${s?.message||s}
74
+ `),1}}return C.includes(r)?g().ok?(process.stderr.write(`oracle: sign-plane command '${r}' is not available in this build (operator is installed).
75
+ `),1):(j(process.stderr),3):(process.stderr.write(Y(r,o)),1)}async function z(){let t=`oracle ${V()}`,r=g();return r.ok&&(t+=` operator ${r.version}`),process.stdout.write(t+`
76
+ `),0}function Ie(e=[],t={stdin:process.stdin,stdout:process.stdout}){return e.length!==0?!1:process.env.ORACLE_FORCE_CHAT==="1"?!0:t.stdin?.isTTY===!0&&t.stdout?.isTTY===!0}function $e(e){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(e||""))}var Or=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 He(){if(!process.argv[1])return!1;try{return Q(Me(import.meta.url))===Q(process.argv[1])}catch{return!1}}async function Be(e=process.argv.slice(2)){return W(e)}if(He()){let e=await Be();process.exit(typeof e=="number"?e:0)}export{Or as COMMANDS,Be as main};
@@ -1,16 +1,16 @@
1
- import $ from"node:fs";import T from"node:path";import Q from"node:fs";import ee from"node:os";import I from"node:path";import{fileURLToPath as te}from"node:url";var re=I.dirname(te(import.meta.url)),Ce=I.resolve(re,"../..");function oe(){return process.env.ORACLE_FAKE_HOME||ee.homedir()}function E(){return I.join(oe(),".config","oracle")}function b(e){return Q.mkdirSync(e,{recursive:!0}),e}var ne=new Set(["auto","standalone","hermes"]),ie=new Set(["openrouter","openai","xai","deepseek","gemini","custom","anthropic-oauth","openai-codex","xai-oauth"]);function se(){return T.join(E(),"model.json")}function A(e){return String(e||"").trim()||void 0}function ce(e={}){let t=A(e.backend)?.toLowerCase()||"auto",r=A(e.provider)?.toLowerCase(),n=A(e.model),o=A(e.baseUrl)?.replace(/\/+$/,""),i=A(e.apiKeyEnv),p=Number.parseInt(String(e.contextLength||""),10),l=A(e.reasoningEffort);if(!ne.has(t))throw new Error(`unsupported backend: ${t}`);if(r&&!ie.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");return{backend:t,...r?{provider:r}:{},...n?{model:n}:{},...o?{baseUrl:o}:{},...i?{apiKeyEnv:i}:{},...Number.isFinite(p)&&p>0?{contextLength:p}:{},...l?{reasoningEffort:l}:{}}}function N(e){let t=ce(e),r=se();b(T.dirname(r)),process.platform!=="win32"&&$.chmodSync(T.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 ae,randomBytes as R,timingSafeEqual as ue}from"node:crypto";import g from"node:fs";import _ from"node:path";import de from"node:readline/promises";import{spawn as pe,spawnSync as le}from"node:child_process";var O=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"}});function fe(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function x(e){let t=String(e||"").trim().toLowerCase();for(let[r,n]of Object.entries(O))if(n.aliases.includes(t))return r;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function J(e){let t=x(e);return{id:t,...O[t]}}function m(e,t={}){if(!g.existsSync(e))return t;try{let r=JSON.parse(g.readFileSync(e,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid object");return r}catch{throw new Error(`credential store is unreadable or corrupt: ${_.basename(e)}`)}}function H(e){b(e),process.platform!=="win32"&&g.chmodSync(e,448)}function y(e,t){H(_.dirname(e));let r=`${e}.${process.pid}.${R(4).toString("hex")}.tmp`;g.writeFileSync(r,`${JSON.stringify(t,null,2)}
3
- `,{mode:384}),g.renameSync(r,e),process.platform!=="win32"&&g.chmodSync(e,384)}function he(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 j(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 me(e={}){let t=e.file||_.join(E(),"oauth.json"),r=e.metadataFile||_.join(_.dirname(t),"oauth-meta.json"),n=e.spawnFn||le,o=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&he(n),i=o?"linux-secret-service":"private-file",p=`${t}.lock`;async function l(f){H(_.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 w(f){let u=x(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 j(JSON.parse(String(d.stdout).trim()))}catch{return null}}let a=m(t,{providers:{}}).providers?.[u];if(!a)return null;try{return j(a)}catch{return null}}function v(f,u){let c=x(f),a=j(u);if(o){let h=n("secret-tool",["store",`--label=Oracle ${c} OAuth`,...s(c)],{input:JSON.stringify(a),encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(h.error||h.status!==0)throw new Error("OS credential store rejected OAuth credential");let k=m(r,{providers:{}});return k.providers||={},k.providers[c]={expiresAt:a.expiresAt,source:a.source},y(r,k),a}let d=m(t,{providers:{}});return d.providers||={},d.providers[c]=a,y(t,d),a}function C(f){let u=x(f);if(o){let d=n("secret-tool",["clear",...s(u)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),h=m(r,{providers:{}});return h.providers&&delete h.providers[u],y(r,h),!d.error&&d.status===0}let c=m(t,{providers:{}}),a=!!c.providers?.[u];return c.providers&&delete c.providers[u],y(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(m(t,{apiKeys:{}}).apiKeys?.[u]||"").trim()}function G(f,u){let c=K(f),a=String(u||"").trim();if(!a)throw new Error("API key is empty");if(o){let h=n("secret-tool",["store",`--label=Oracle ${c} API key`,...s(c,"api-key")],{input:a,encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(h.error||h.status!==0)throw new Error("OS credential store rejected API key");let k=m(r,{providers:{},apiKeys:{}});return k.apiKeys||={},k.apiKeys[c]={configured:!0},y(r,k),!0}let d=m(t,{providers:{},apiKeys:{}});return d.apiKeys||={},d.apiKeys[c]=a,y(t,d),!0}function Z(f){let u=K(f);if(o){let d=n("secret-tool",["clear",...s(u,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),h=m(r,{providers:{},apiKeys:{}});return h.apiKeys&&delete h.apiKeys[u],y(r,h),!d.error&&d.status===0}let c=m(t,{providers:{},apiKeys:{}}),a=!!c.apiKeys?.[u];return c.apiKeys&&delete c.apiKeys[u],y(t,c),a}function Y(){let f={},u={};if(o){let c=m(r,{providers:{},apiKeys:{}});for(let[a,d]of Object.entries(c.providers||{}))f[a]={loggedIn:!!w(a),expiresAt:Number(d.expiresAt||0),source:String(d.source||"oracle"),storage:i};for(let a of Object.keys(c.apiKeys||{}))u[a]={configured:!!M(a),storage:i}}else{let c=m(t,{providers:{},apiKeys:{}});for(let[a,d]of Object.entries(c.providers||{}))f[a]={loggedIn:!!d?.accessToken,expiresAt:Number(d?.expiresAt||0),source:String(d?.source||"oracle"),storage: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:w,set:v,remove:C,getApiKey:M,setApiKey:G,removeApiKey:Z,status:Y,withLock:l})}var B;function q(){return B||=me(),B}function F(e){return Buffer.from(e).toString("base64url")}function we(){let e=F(R(32));return{verifier:e,challenge:F(ae("sha256").update(e).digest()),state:F(R(24))}}function ge(e,t){let r=Buffer.from(String(e||"")),n=Buffer.from(String(t||""));return r.length===n.length&&ue(r,n)}function ye(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 pe(r[0],r[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function z(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 ve(e){if(e)return String(await e()).trim();let t=de.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function U(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 j({accessToken:r,refreshToken:n,expiresAt:fe(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 ke(e){let t=O["anthropic-oauth"],r=e.pkce||we(),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 ve(e.inputFn),[p,l]=i.split("#",2);if(!p||!ge(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 U(await S(s,"Claude OAuth token exchange"),e)}async function xe(e){let t=O["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 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(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:z({grant_type:"authorization_code",code:i.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:i.code_verifier})});return U(await S(p,"Codex OAuth token exchange"),e)}function P(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 Se(e){let t=O["xai-oauth"],r=await S(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");P(r.authorization_endpoint);let n=P(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:z({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=P(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 w=await e.fetchFn(n,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:z({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:o.device_code})});if(w.ok){let C=await S(w,"xAI OAuth token exchange");return U(C,{...e,discovery:{authorization_endpoint:P(r.authorization_endpoint),token_endpoint:n}})}let v="";try{v=String((await w.json())?.error||"")}catch{}if(v==="slow_down")await e.sleepFn((p+1)*1e3);else if(v==="authorization_pending")await e.sleepFn(p*1e3);else throw new Error(`xAI OAuth token exchange failed (HTTP ${w.status}${v?`, ${v}`:""})`)}throw new Error("xAI device authorization timed out")}async function V(e,t={}){let r=x(e),n={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(o=>new Promise(i=>setTimeout(i,o))),openFn:t.openFn||ye,output:t.output||(o=>process.stdout.write(`${o}
4
- `)),now:t.now,pkce:t.pkce};return r==="anthropic-oauth"?ke(n):r==="openai-codex"?xe(n):Se(n)}var W=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 D(e,t){let r=e.indexOf(t);return r>=0&&e[r+1]?e[r+1]:""}async function Ae(){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(`
1
+ import $ from"node:fs";import T from"node:path";import ee from"node:fs";import te from"node:os";import E from"node:path";import{fileURLToPath as re}from"node:url";var oe=E.dirname(re(import.meta.url)),Ie=E.resolve(oe,"../..");function N(){return process.env.ORACLE_FAKE_HOME||te.homedir()}function ne(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function b(){return ne()?process.env.ORACLE_CONFIG_DIR||E.join(N(),".config","oracle"):E.join(N(),".config","oracle")}function P(e){return ee.mkdirSync(e,{recursive:!0}),e}var ie=new Set(["auto","standalone","hermes","remote","arch"]),se=new Set(["openrouter","openai","xai","deepseek","gemini","custom","anthropic-oauth","openai-codex","xai-oauth"]);function ce(){return T.join(b(),"model.json")}function v(e){return String(e||"").trim()||void 0}function ae(e={}){let t=v(e.backend)?.toLowerCase()||"auto",r=v(e.provider)?.toLowerCase(),n=v(e.model),o=v(e.baseUrl)?.replace(/\/+$/,""),i=v(e.apiKeyEnv),p=Number.parseInt(String(e.contextLength||""),10),l=v(e.reasoningEffort),s=v(e.computeHost||e.remoteHost),h=v(e.computeUser||e.remoteUser),y=v(e.computePath||e.remotePath);if(!ie.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&&!se.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"&&!s)throw new Error("remote backend requires computeHost");return{backend:t,...r?{provider:r}:{},...n?{model:n}:{},...o?{baseUrl:o}:{},...i?{apiKeyEnv:i}:{},...Number.isFinite(p)&&p>0?{contextLength:p}:{},...l?{reasoningEffort:l}:{},...s?{computeHost:s}:{},...h?{computeUser:h}:{},...y?{computePath:y}:{}}}function B(e){let t=ae(e),r=ce();P(T.dirname(r)),process.platform!=="win32"&&$.chmodSync(T.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 ue,randomBytes as U,timingSafeEqual as de}from"node:crypto";import g from"node:fs";import A from"node:path";import pe from"node:readline/promises";import{spawn as le,spawnSync as fe}from"node:child_process";var O=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"}});function he(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function S(e){let t=String(e||"").trim().toLowerCase();for(let[r,n]of Object.entries(O))if(n.aliases.includes(t))return r;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function J(e){let t=S(e);return{id:t,...O[t]}}function w(e,t={}){if(!g.existsSync(e))return t;try{let r=JSON.parse(g.readFileSync(e,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid object");return r}catch{throw new Error(`credential store is unreadable or corrupt: ${A.basename(e)}`)}}function q(e){P(e),process.platform!=="win32"&&g.chmodSync(e,448)}function k(e,t){q(A.dirname(e));let r=`${e}.${process.pid}.${U(4).toString("hex")}.tmp`;g.writeFileSync(r,`${JSON.stringify(t,null,2)}
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"?xe(n):r==="openai-codex"?Se(n):_e(n)}var G=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 D(e,t){let r=e.indexOf(t);return r>=0&&e[r+1]?e[r+1]:""}async function Ae(){let e="";for await(let t of process.stdin)e+=t;return e.trim()}function Oe(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
5
  `)},i=p=>{let l=String(p);for(let s of l){if(s==="\r"||s===`
6
- `){o(),t(n.trim());return}if(s===""){o(),r(new Error("cancelled"));return}s==="\x7F"||s==="\b"?n=n.slice(0,-1):n+=s}};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",i)})}function L(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 X(e,t,r={}){return N(L(e,t,r))}function Oe(e){process.stdout.write(`storage: ${e.storage}
6
+ `){o(),t(n.trim());return}if(s===""){o(),r(new Error("cancelled"));return}s==="\x7F"||s==="\b"?n=n.slice(0,-1):n+=s}};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",i)})}function L(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 X(e,t,r={}){return B(L(e,t,r))}function Ee(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 Ee(){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 qe={name:"auth",summary:"login with Claude, Codex, or Grok OAuth; store provider API keys",group:"read",usage:Ee(),async run(e){let t=[...e.argv],r=t.shift()||"status",n=q();try{if(r==="status"){let o=n.status();return t.includes("--json")?process.stdout.write(`${JSON.stringify(o,null,2)}
12
- `):Oe(o),0}if(r==="login"){let o=t.find(s=>!s.startsWith("-"));if(!o)throw new Error("usage: oracle auth login claude|codex|grok");let i=J(o),p=D(t,"--model")||i.model;L(i.id,p);let l=await V(i.id,{openFn:t.includes("--no-browser")?()=>!1:void 0});return await n.withLock(async()=>{let s=n.get(i.id);n.set(i.id,l);try{X(i.id,p)}catch(w){throw s?n.set(i.id,s):n.remove(i.id),w}}),process.stdout.write(`${i.id}: logged in, stored in ${n.storage}
13
- `),0}if(r==="api-key"){let o=String(t.find(s=>!s.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth api-key PROVIDER [--stdin]");if(!Object.hasOwn(W,o))throw new Error(`unsupported API-key provider: ${o}`);let i=D(t,"--model")||W[o].model,p=D(t,"--base-url");L(o,i,{baseUrl:p});let l=t.includes("--stdin")?await Ae():await _e();return await n.withLock(async()=>{let s=n.getApiKey(o);n.setApiKey(o,l);try{X(o,i,{baseUrl:p})}catch(w){throw s?n.setApiKey(o,s):n.removeApiKey(o),w}}),process.stdout.write(`${o}: API key configured in ${n.storage}
14
- `),0}if(r==="logout"){let o=String(t.find(l=>!l.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth logout PROVIDER");let i=!1;try{i=n.remove(x(o))}catch{}let p=n.removeApiKey(o);if(!i&&!p)throw new Error(`${o}: no local credential found`);return process.stdout.write(`${o}: local credential removed
10
+ `)}function be(){return["oracle auth, configure OAuth or API-key authentication",""," oracle auth login claude|codex|grok [--model MODEL] [--no-browser]"," oracle auth api-key PROVIDER [--model MODEL] [--base-url URL]",` 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 Ve={name:"auth",summary:"login with Claude, Codex, or Grok OAuth; store provider API keys",group:"read",usage:be(),async run(e){let t=[...e.argv],r=t.shift()||"status",n=V();try{if(r==="status"){let o=n.status();return t.includes("--json")?process.stdout.write(`${JSON.stringify(o,null,2)}
12
+ `):Ee(o),0}if(r==="login"){let o=t.find(s=>!s.startsWith("-"));if(!o)throw new Error("usage: oracle auth login claude|codex|grok");let i=J(o),p=D(t,"--model")||i.model;L(i.id,p);let l=await W(i.id,{openFn:t.includes("--no-browser")?()=>!1:void 0});return await n.withLock(async()=>{let s=n.get(i.id);n.set(i.id,l);try{X(i.id,p)}catch(h){throw s?n.set(i.id,s):n.remove(i.id),h}}),process.stdout.write(`${i.id}: logged in, stored in ${n.storage}
13
+ `),0}if(r==="api-key"){let o=String(t.find(s=>!s.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth api-key PROVIDER [--stdin]");if(!Object.hasOwn(G,o))throw new Error(`unsupported API-key provider: ${o}`);let i=D(t,"--model")||G[o].model,p=D(t,"--base-url");L(o,i,{baseUrl:p});let l=t.includes("--stdin")?await Ae():await Oe();return await n.withLock(async()=>{let s=n.getApiKey(o);n.setApiKey(o,l);try{X(o,i,{baseUrl:p})}catch(h){throw s?n.setApiKey(o,s):n.removeApiKey(o),h}}),process.stdout.write(`${o}: API key configured in ${n.storage}
14
+ `),0}if(r==="logout"){let o=String(t.find(l=>!l.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth logout PROVIDER");let i=!1;try{i=n.remove(S(o))}catch{}let p=n.removeApiKey(o);if(!i&&!p)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{qe as default};
16
+ `),1}}};export{Ve as default};