@oracle-agent/oracle 0.35.43 → 0.35.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-sessions.mjs +19 -19
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/bin/desk-server.mjs +28 -28
- package/dist/bin/oracle-data-mcp.mjs +19 -19
- package/dist/bin/oracle-gateway.mjs +42 -42
- package/dist/bin/oracle-investigate.mjs +5 -5
- package/dist/bin/oracle-launch-radar-shadow.mjs +6 -6
- package/dist/bin/oracle-mev-arb-shadow.mjs +6 -6
- package/dist/bin/oracle-mev-shadow.mjs +6 -6
- package/dist/bin/oracle-public-server.mjs +5 -5
- package/dist/bin/oracle-route.mjs +18 -18
- package/dist/bin/oracle-scan.mjs +11 -11
- package/dist/bin/oracle.mjs +12 -12
- package/dist/cli/commands/agent-session.mjs +21 -21
- package/dist/cli/commands/airdrop.mjs +10 -10
- package/dist/cli/commands/chat.mjs +218 -217
- package/dist/cli/commands/data.mjs +244 -8
- package/dist/cli/commands/doctor.mjs +5 -5
- package/dist/cli/commands/eval.mjs +157 -153
- package/dist/cli/commands/extension-policy.mjs +1 -1
- package/dist/cli/commands/farm.mjs +17 -17
- package/dist/cli/commands/fees.mjs +3 -3
- package/dist/cli/commands/follow.mjs +17 -17
- package/dist/cli/commands/mcp.mjs +6 -6
- package/dist/cli/commands/mint.mjs +10 -10
- package/dist/cli/commands/model.mjs +222 -221
- package/dist/cli/commands/quickstart.mjs +7 -7
- package/dist/cli/commands/receipt.mjs +8 -8
- package/dist/cli/commands/resolve.mjs +10 -10
- package/dist/cli/commands/sign.mjs +11 -11
- package/dist/cli/commands/signer.mjs +20 -20
- package/dist/cli/commands/snipe.mjs +11 -11
- package/dist/cli/commands/strategy.mjs +5 -5
- package/dist/cli/commands/swap.mjs +11 -11
- package/dist/cli/commands/venues.mjs +2 -2
- package/dist/data/desk-data.mjs +26 -26
- package/dist/data/names.mjs +3 -3
- package/dist/data/providers/farming.mjs +2 -2
- package/dist/data/providers/lp-destination-discovery.mjs +4 -4
- package/dist/index.mjs +44 -44
- package/dist/investigator/index.mjs +2 -2
- package/dist/launch-radar/index.mjs +5 -5
- package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
- package/dist/local-signer/index.mjs +3 -3
- package/dist/local-signer/runtime.mjs +16 -16
- package/dist/nft/universal-mint-router.mjs +4 -4
- package/dist/notifications/index.mjs +7 -7
- package/dist/router/index.mjs +3 -3
- package/dist/router/prepare-bridge.mjs +2 -2
- package/dist/router/prepare-route.mjs +3 -3
- package/dist/scanner/index.mjs +4 -4
- package/dist/strategy/index.mjs +3 -3
- package/dist/tui/standalone-client.mjs +90 -88
- package/package.json +1 -1
- package/public/eval-report.json +347 -13
- package/public/oracle-splash/docs/browser-and-web/index.html +2 -2
- package/public/oracle-splash/docs/connectors/index.html +2 -2
- package/public/oracle-splash/docs/getting-started/index.html +2 -2
- package/public/oracle-splash/docs/index.html +3 -3
- package/public/oracle-splash/docs/reference/index.html +2 -2
- package/public/oracle-splash/docs/security/index.html +2 -2
- package/public/oracle-splash/docs/using-oracle/index.html +2 -2
- package/server.json +2 -2
package/dist/bin/oracle-scan.mjs
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createHash as Et}from"node:crypto";import{types as H}from"node:util";import W from"node:net";import yt from"node:dns";var wt=new Set(["localhost","metadata.google.internal","metadata.goog"]);function ae(t){let e=String(t).toLowerCase().split("%")[0];if((e.match(/::/g)||[]).length>1)return null;let r=i=>{if(!i)return[];let u=i.split(":"),p=u.at(-1);if(p?.includes(".")){let f=p.split(".").map(Number);if(f.length!==4||f.some(h=>!Number.isInteger(h)||h<0||h>255))return null;u.splice(u.length-1,1,(f[0]<<8|f[1]).toString(16),(f[2]<<8|f[3]).toString(16))}return u.some(f=>!/^[0-9a-f]{1,4}$/.test(f))?null:u.map(f=>Number.parseInt(f,16))},[n,s]=e.split("::"),o=r(n),a=r(s);if(!o||!a)return null;let l=e.includes("::"),c=8-o.length-a.length;if(!l&&c!==0||l&&c<1)return null;let d=[...o,...Array(Math.max(0,c)).fill(0),...a];return d.length!==8?null:Uint8Array.from(d.flatMap(i=>[i>>8,i&255]))}function be(t,e,r){let n=Math.floor(r/8),s=r%8;for(let a=0;a<n;a+=1)if(t[a]!==e[a])return!1;if(!s)return!0;let o=255<<8-s;return(t[n]&o)===(e[n]&o)}function ye(t){if(W.isIPv4(t)){let e=t.split(".").map(Number);return!(e[0]===0||e[0]===10||e[0]===127||e[0]>=224||e[0]===100&&e[1]>=64&&e[1]<=127||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&(e[1]===0||e[1]===2||e[1]===168)||e[0]===192&&e[1]===88&&e[2]===99||e[0]===198&&(e[1]===18||e[1]===19||e[1]===51)||e[0]===203&&e[1]===0&&e[2]===113)}if(W.isIPv6(t)){let e=ae(t);if(!e)return!1;let r=ae("::ffff:0:0");return be(e,r,96)?ye([...e.slice(12)].join(".")):be(e,ae("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([s,o])=>be(e,ae(s),o)):!1}return!1}function gt(t){let e;try{e=new URL(String(t))}catch{return{ok:!1,error:`not a valid URL: ${String(t).slice(0,120)}`}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{ok:!1,error:`refused protocol ${e.protocol} (only http/https)`};let r=e.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(wt.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=W.isIP(r);return n!==0&&!ye(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:e,host:r,isLiteralIp:n!==0}}async function we(t,{lookupFn:e=yt.promises.lookup}={}){let r=gt(t);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:W.isIPv6(r.host)?6:4}]};let n;try{n=await e(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(s=>!ye(s.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function ge({requireUndici:t=!1,importUndici:e=()=>import("undici")}={}){let r,n;try{let u=await e();r=u.Agent,n=u.fetch}catch(u){if(t)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${u?.message||u}`);return null}if(typeof r!="function"||typeof n!="function"){if(t)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let s=u=>String(u).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),o=new Map,a=u=>(Array.isArray(u)?u:[u]).map(p=>typeof p=="string"?{address:p}:p).filter(p=>p&&p.address).map(p=>({address:p.address,family:p.family||(W.isIPv6(p.address)?6:4)})),l=(u,p,f)=>{o.set(s(u),a(typeof p=="string"?[{address:p,family:f}]:p))},c=u=>{let p=s(u);if(W.isIP(p))return[{address:p,family:W.isIPv6(p)?6:4}];let f=o.get(p);if(!f||!f.length)throw new Error(`refused: unpinned host ${u} during pinned fetch`);return f},d=new r({connect:{lookup(u,p,f){let h;try{h=c(u)}catch(y){return f(y)}return p?.all?f(null,h):f(null,h[0].address,h[0].family)}}}),i=vt((u,p={})=>n(u,{...p,dispatcher:d}),l);return{dispatcher:d,fetch:i,pin:l,resolve:c,async close(){try{await d.destroy()}catch{}}}}var ve=Symbol.for("oracle.egressGuard.pinCapableFetch");function vt(t,e){if(typeof t!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof e!="function")throw new Error("markPinCapableFetch: pin must be a function");return t[ve]=Object.freeze({pin:e}),t}function Ee(t){return typeof t=="function"&&typeof t[ve]?.pin=="function"}function _e(t,e,r){if(!Ee(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[ve].pin(e,r)}var St=new Set([408,425,429,500,502,503,504]),Ue=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),At=2,qe=4e3,xt=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Ct=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Tt=AbortSignal.prototype.throwIfAborted,It=EventTarget.prototype.addEventListener,Be=EventTarget.prototype.removeEventListener,$e=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,te=t=>t?xt.call(t):!1,kt=t=>t?Ct.call(t):void 0,Nt=new Set([301,302,303,307,308]),ue=3,xr=64*1024,j=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});function k(t){return V(`HTTP JSON body refused: ${t}`)}function Ot(t){return["isArgumentsObject","isArrayBuffer","isAnyArrayBuffer","isArrayBufferView","isBoxedPrimitive","isDataView","isDate","isExternal","isGeneratorObject","isKeyObject","isCryptoKey","isMap","isMapIterator","isModuleNamespaceObject","isNativeError","isPromise","isRegExp","isSet","isSetIterator","isTypedArray","isWeakMap","isWeakSet"].some(e=>typeof H[e]=="function"&&H[e](t))}function Pt(t){let e=[],r=0,n=0,s=0,o=0,a=new WeakSet,l=i=>{if(r+=Buffer.byteLength(i,"utf8"),r>j.bytes)throw k("serialized byte limit exceeded");e.push(i)},c=i=>{if(Buffer.byteLength(i,"utf8")>j.bytes)throw k("serialized byte limit exceeded");return JSON.stringify(i)},d=(i,u)=>{if(n+=1,n>j.nodes)throw k("node limit exceeded");if(u>j.depth)throw k("depth limit exceeded");if(i===null){l("null");return}if(typeof i=="string"){l(c(i));return}if(typeof i=="boolean"){l(i?"true":"false");return}if(typeof i=="number"){if(!Number.isFinite(i))throw k("non-finite number");l(Object.is(i,-0)?"0":String(i));return}if(typeof i!="object")throw k("unsupported non-JSON value");if(H.isProxy(i))throw k("proxy value");if(Ot(i))throw k("unsupported exotic object");if(a.has(i))throw k("cyclic value");a.add(i);try{if(Object.getOwnPropertySymbols(i).length>0)throw k("symbol-keyed fields are unsupported");if(Array.isArray(i)){let h=Object.getPrototypeOf(i),y=0;for(;h!==null;){if(H.isProxy(h))throw k("proxy array prototype");if(y+=1,y>j.depth)throw k("array prototype depth limit exceeded");h=Object.getPrototypeOf(h)}if(i.length>j.arrayLength)throw k("array length limit exceeded");for(let S=0;S<i.length;S+=1){let P=Object.getOwnPropertyDescriptor(i,String(S));if(!P||!Object.hasOwn(P,"value")||P.enumerable!==!0)throw k("array entries must be dense enumerable own data")}let m=0;for(let S in i){if(o+=1,o>j.fields)throw k("enumeration limit exceeded");if(Object.hasOwn(i,S)&&(m+=1,m>i.length))throw k("named array fields are unsupported")}if(m!==i.length)throw k("array entries must be dense enumerable own data");l("[");for(let S=0;S<i.length;S+=1)S&&l(","),d(Object.getOwnPropertyDescriptor(i,String(S)).value,u+1);l("]");return}let p=Object.getPrototypeOf(i);if(p!==Object.prototype&&p!==null)throw k("non-plain object");let f=[];for(let h in i){if(o+=1,o>j.fields)throw k("enumeration limit exceeded");if(!Object.hasOwn(i,h))continue;if(s+=1,s>j.fields)throw k("field limit exceeded");let y=Object.getOwnPropertyDescriptor(i,h);if(!y||!Object.hasOwn(y,"value")||y.enumerable!==!0)throw k("object fields must be enumerable own data");f.push([h,y.value])}l("{");for(let h=0;h<f.length;h+=1)h&&l(","),l(c(f[h][0])),l(":"),d(f[h][1],u+1);l("}")}finally{a.delete(i)}};return d(t,0),e.join("")}function Rt(t){let e=Object.create(null);if(t==null)return e;if(typeof t!="object"&&typeof t!="function")throw new TypeError("HTTP headers must be an object");if(H.isProxy(t))throw new TypeError("HTTP headers must not be a proxy");if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("HTTP headers must not contain symbol fields");let r=new Set;for(let n of Object.keys(t)){if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(n))throw new TypeError("HTTP header names must be valid tokens");let s=n.toLowerCase();if(r.has(s))throw new TypeError("HTTP headers contain a duplicate canonical name");r.add(s);let o=Object.getOwnPropertyDescriptor(t,n);if(!o||!Object.hasOwn(o,"value"))throw new TypeError("HTTP headers must contain own data properties");let a=o.value;if(a==null||["object","function","symbol"].includes(typeof a))throw new TypeError("HTTP header values must be scalar");e[n]=String(a)}return e}function Lt(){return Object.assign(Object.create(null),{Accept:"application/json"})}function _t(t,e){if(!t)throw new Error(`HTTP redirect from ${e} missing Location`);let r=new URL(String(t),String(e));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${e} used unsupported protocol ${r.protocol}`);return r.toString()}function Ut(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var Se=new Map,Fe=new WeakMap,De=1;function ce(t){if((typeof t!="object"||t===null)&&typeof t!="function")return`${typeof t}:${String(t)}`;let e=Fe.get(t);return e||(e=De,De+=1,Fe.set(t,e)),`reference:${e}`}var qt=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),Bt=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function je(t){if(!t||typeof t!="object"||Array.isArray(t)||!Object.hasOwn(t,"jsonrpc")||!Object.hasOwn(t,"method")||t.jsonrpc!=="2.0")return!1;let e=typeof t.method=="string"?t.method:"";return e?qt.has(e)||/^get[A-Z0-9_]/u.test(e)||/^is[A-Z0-9_]/u.test(e)||/^eth_get[A-Z0-9_]/u.test(e):!1}function He(t,e){if(t==="GET"&&e==null)return!0;if(t!=="POST"||e==null)return!1;let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{return!1}if(Array.isArray(r))return r.length>0&&r.every(je);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return je(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&Bt.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function $t(t,e,r,n={},s=null){let o=Et("sha256"),a=(c,d)=>{let i=String(d);o.update(String(Buffer.byteLength(c,"utf8"))).update(":").update(c),o.update("=").update(String(Buffer.byteLength(i,"utf8"))).update(":").update(i).update(`
|
|
3
|
-
`)};a("method",t),a("url",e),Object.keys(r||{}).map((c,d)=>({name:c.toLowerCase(),order:d,value:String(r[c])})).sort((c,d)=>c.name.localeCompare(d.name)||c.order-d.order).forEach((c,d)=>{a(`header-name-${d}`,c.name),a(`header-value-${d}`,c.value)}),a("body",s??"-");for(let c of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])a(`context-${c}`,n[c]??"-");return o.digest("hex")}function Ft(t,e){let r=Number(e);return Number.isFinite(r)&&r>0?Math.min(r*1e3,qe):Math.min(250*2**t,qe)+Math.floor(Math.random()*100)}var Dt=t=>new Promise(e=>setTimeout(e,t));function V(t,e={}){let r=new Error(t);return r.retryable=!1,Object.assign(r,e),r}function Ae(t,e,r){return V(`HTTP response from ${t} exceeded maxResponseBytes ${r} (${e})`,{oversize:!0})}function K(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function jt(t){return t?t.byteLength??t.length??0:0}async function Ht(t,e,{url:r,truncate:n=!1,onOversize:s}={}){if(e==null)return await t.text();let o=Number(t.headers?.get?.("content-length"));if(Number.isFinite(o)&&o>e&&(K(t),!n))throw Ae(r,`content-length ${o}`,e);let a=t.body?.getReader?.();if(!a){let u=await t.text(),p=Buffer.byteLength(u,"utf8");if(p>e){if(!n)throw Ae(r,`body ${p} bytes`,e);return Buffer.from(u,"utf8").subarray(0,e).toString("utf8")}return u}let l=[],c=0,d=!1;try{for(;;){let{value:u,done:p}=await a.read();if(p)break;if(u&&(l.push(Buffer.from(u)),c+=jt(u),c>e)){d=!0;break}}}finally{if(d)try{await a.cancel()}catch{}try{a.releaseLock?.()}catch{}}if(d&&(typeof s=="function"&&s(),!n))throw Ae(r,`streamed ${c} bytes`,e);let i=Buffer.concat(l);return(d?i.subarray(0,e):i).toString("utf8")}function Vt(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Mt(t,{fetchImpl:e,method:r,headers:n,body:s,timeoutMs:o,lookupFn:a,realFetch:l,untrustedUrl:c=!1,maxResponseBytes:d=null,sameOriginRedirectsOnly:i=!1,importUndici:u,validateResponse:p,signal:f,redirectPolicy:h="follow",maxRedirects:y=ue}){let m=null,S=e,P=a?{lookupFn:a}:{};if(c&&!l&&!Ee(S))throw V(`HTTP refused ${t}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let R=new AbortController,U=setTimeout(()=>R.abort(),o),N=f?$e?$e([f,R.signal]):f:R.signal,A=async(v,{status:x=null}={})=>{let E=await we(v,P);if(!E.ok)throw V(x==null?`HTTP refused ${v}: ${E.error}`:`HTTP redirect to ${v} ${E.error}`,x==null?{}:{status:x});let L=new URL(v).hostname;if(l){if(m&&(await m.close(),m=null),!m)try{m=await ge({requireUndici:!0,...u?{importUndici:u}:{}})}catch(b){throw V(x==null?`HTTP refused ${v}: ${b?.message||b}`:`HTTP redirect to ${v} refused: ${b?.message||b}`,x==null?{}:{status:x})}m.pin(L,E.addresses),S=m.fetch}else _e(S,L,E.addresses);return E};try{let v=String(t),x=Object.assign(Object.create(null),n||{});c&&await A(v);for(let E=0;E<=y;E+=1){let L=Object.assign(Object.create(null),{method:r,headers:x,body:s,signal:N,redirect:"manual",dispatcher:void 0}),b=await S(v,L);if((h==="error"||y===0)&&b.status>=300&&b.status<400)throw K(b),V(`HTTP ${b.status} ${r} redirect refused`,{status:b.status,redirectRefused:!0});if(Nt.has(b.status)){let q=i===!0&&r==="POST"&&[307,308].includes(b.status)&&He(r,s);if(r!=="GET"&&r!=="HEAD"&&!q){K(b);let O=new Error(`HTTP ${b.status} ${r} ${v} redirected non-idempotent request`);throw O.status=b.status,O}if(E===y)throw K(b),V(`HTTP ${b.status} ${r} redirect budget exhausted`,{status:b.status,redirectRefused:!0});let Pe=b.headers?.get?.("location"),$;try{$=_t(Pe,v)}catch(O){throw K(b),O}let M=!Ut($,v);if(K(b),M&&r==="POST"){let O=new Error(`HTTP ${b.status} ${r} cross-origin redirect refused`);throw O.status=b.status,O}if(M&&i){let O=new Error(`HTTP ${b.status} ${r} cross-origin redirect refused`);throw O.status=b.status,O.retryable=!1,O}if(M&&(x=Lt(x)),c)await A($,{status:b.status});else if(M){let O=await we($,P);if(!O.ok){let I=new Error(`HTTP redirect from ${v} ${O.error}`);throw I.status=b.status,I.retryable=!1,I}l&&O.addresses?.length&&(m||(m=await ge(u?{importUndici:u}:{})),m&&(m.pin(new URL($).hostname,O.addresses),S=m.fetch))}v=$;continue}if(typeof p=="function")try{await p(b,{url:v})}catch(q){throw K(b),V(q?.message||String(q))}let _=await Ht(b,d,{url:v,onOversize:()=>R.abort()}),X=Vt(_);if(!b.ok){let q=new Error(`HTTP ${b.status} ${r} ${v}`);throw q.status=b.status,q.retryAfter=b.headers?.get?.("retry-after")??null,q.body=X??_.slice(0,300),q}return X??_}throw new Error(`HTTP redirect loop for ${t}`)}catch(v){if(R.signal.aborted&&!te(f)){let x=v&&(typeof v=="object"||typeof v=="function")&&!H.isProxy(v)?v:null,E=x?Object.getOwnPropertyDescriptor(x,"oversize"):null;if(!(E&&Object.hasOwn(E,"value")&&E.value===!0))try{if(!x)throw new TypeError("unsafe rejection");Object.defineProperties(x,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let b=new Error("HTTP request timed out");throw Object.defineProperties(b,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),b}}throw v}finally{clearTimeout(U),m&&await m.close()}}async function le(t,e={}){if(e!=null&&typeof e!="object"&&typeof e!="function")throw new TypeError("HTTP options must be an object");if(e!=null&&H.isProxy(e))throw new TypeError("HTTP options must not be a proxy");let r=new Set(["body","dedupe","fetchImpl","headers","importUndici","lookupFn","maxRedirects","maxResponseBytes","method","redirectPolicy","retries","sameOriginRedirectsOnly","signal","timeoutMs","untrustedUrl","validateResponse"]);if(e!=null){if(Object.getOwnPropertySymbols(e).length>0)throw new TypeError("HTTP options contain unknown fields");for(let I of Object.getOwnPropertyNames(e)){let C=Object.getOwnPropertyDescriptor(e,I);if(!(I==="toJSON"&&C&&Object.hasOwn(C,"value")&&C.value===void 0)){if(!r.has(I))throw new TypeError("HTTP options contain unknown fields");if(!C||!C.enumerable||!Object.hasOwn(C,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=I=>{if(e==null||!Object.hasOwn(e,I))return;let C=Object.getOwnPropertyDescriptor(e,I);if(!C||!Object.hasOwn(C,"value"))throw new TypeError("HTTP options must contain own data properties");return C.value};if(typeof t!="string"||t.length===0||t.length>8192)throw new TypeError("HTTP URL must be a bounded string");let s=n("method");if(s!==void 0&&(typeof s!="string"||!/^[A-Za-z]+$/u.test(s)))throw new TypeError("HTTP method must be a string token");let o=n("timeoutMs");if(o!==void 0&&(!Number.isInteger(o)||o<1||o>12e4))throw new TypeError("HTTP timeoutMs must be a bounded integer");let a=n("retries");if(a!==void 0&&(!Number.isInteger(a)||a<0||a>10))throw new TypeError("HTTP retries must be a bounded integer");let l=n("redirectPolicy");if(l!==void 0&&l!=="follow"&&l!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let c=n("maxRedirects");if(c!==void 0&&(!Number.isInteger(c)||c<0||c>ue))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${ue}`);if(l==="error"&&c!==void 0&&c!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let d=l??"follow",i=d==="error"?0:c??ue;for(let I of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let C=n(I);if(C!==void 0&&typeof C!="boolean")throw new TypeError(`HTTP ${I} must be boolean`)}let u=n("maxResponseBytes");if(u!==void 0&&(!Number.isInteger(u)||u<1||u>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let p=n("signal");if(p!==void 0){if(H.isProxy(p)||!(p instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{te(p)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let I of["importUndici","lookupFn","validateResponse"]){let C=n(I);if(C!==void 0&&typeof C!="function")throw new TypeError(`HTTP ${I} must be a function`)}let f=n("fetchImpl"),h=f||globalThis.fetch;if(typeof h!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let y=o??12e3,m=(s||"GET").toUpperCase(),S=n("headers"),P=Rt(S),R=Object.assign(Object.create(null),P);Object.keys(R).some(I=>I.toLowerCase()==="accept")||(R.Accept="application/json");let U=n("body");U!=null&&typeof U!="string"&&(Object.keys(R).find(C=>C.toLowerCase()==="content-type")||(R["Content-Type"]="application/json"),U=Pt(U));let N=a??At,A=n("lookupFn"),v=!f,x=n("untrustedUrl")===!0,E=n("sameOriginRedirectsOnly")===!0,L=n("importUndici"),b=n("validateResponse"),_=p,X=u??null,q=async()=>{let I;for(let C=0;C<=N;C++){_&&Tt.call(_);try{return await Mt(t,{fetchImpl:h,method:m,headers:R,body:U,timeoutMs:y,lookupFn:A,realFetch:v,untrustedUrl:x,maxResponseBytes:X,sameOriginRedirectsOnly:E,importUndici:L,validateResponse:b,signal:_,redirectPolicy:d,maxRedirects:i})}catch(z){I=z;let Y=me=>{if(!z||typeof z!="object"&&typeof z!="function"||H.isProxy(z))return;let Z=Object.getOwnPropertyDescriptor(z,me);return Z&&Object.hasOwn(Z,"value")?Z.value:void 0},he=Y("status"),ht=Y("oracleTimeout")===!0||Y("name")==="AbortError"||Y("name")==="TimeoutError"||te(_),mt=new Set([408,425,429]),bt=Y("retryable")===!1?!1:he!=null?mt.has(he)||St.has(he)&&Ue.has(m):!ht&&Ue.has(m);if(C===N||!bt)throw z;let Re=Ft(C,Y("retryAfter"));_?await new Promise((me,Z)=>{let Le,ee=()=>{clearTimeout(Le),Be.call(_,"abort",ee),Z(kt(_)||new DOMException("Aborted","AbortError"))};if(te(_)){ee();return}Le=setTimeout(()=>{Be.call(_,"abort",ee),me()},Re),It.call(_,"abort",ee,{once:!0}),te(_)&&ee()}):await Dt(Re)}}throw I};if(!(n("dedupe")!==!1&&!_&&He(m,U)))return q();let $=$t(m,t,R,{untrustedUrl:x,maxResponseBytes:X,sameOriginRedirectsOnly:E,redirectPolicy:d,maxRedirects:i,timeoutMs:y,retries:N,fetchImpl:ce(h),realFetch:v,lookupFn:ce(A),importUndici:ce(L),validateResponse:ce(b)},U),M=Se.get($);if(M)return M;let O=q().finally(()=>Se.delete($));return Se.set($,O),O}async function Ve(t,e,r){let n=Array.from(t),s=Math.max(1,Math.min(Number(e)||1,n.length||1)),o=new Array(n.length),a=0;return await Promise.all(Array.from({length:s},async()=>{for(;a<n.length;){let l=a++;o[l]=await r(n[l],l)}})),o}var Me={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}},zt=new Map(Object.values(Me).map(t=>[t.chainId,t]));function ze(t){return zt.get(Number(t))||null}function We(t,e=process.env){let r=ze(t);if(!r)return null;for(let n of r.rpcEnv){let s=(e[n]||"").trim();if(s)return s}return null}import{Interface as Wt,getAddress as Kt}from"ethers";var Ke=new Wt(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Ge(t,e){try{return Kt(t).toLowerCase()}catch{throw new Error(`${e} must be a valid EVM address`)}}var Gt={1:"https://ethereum.publicnode.com",137:"https://polygon-bor-rpc.publicnode.com",42161:"https://arbitrum-one-rpc.publicnode.com",8453:"https://base-rpc.publicnode.com",10:"https://optimism-rpc.publicnode.com",988:"https://rpc.stable.xyz",56:"https://bsc-rpc.publicnode.com",43114:"https://avalanche-c-chain-rpc.publicnode.com",999:"https://rpc.hyperliquid.xyz/evm",2741:"https://api.mainnet.abs.xyz",4663:"https://rpc.mainnet.chain.robinhood.com"};function Qt(t,{rpcUrl:e,env:r=process.env}={}){if(e)return e;let n=We(t,r);return n||Gt[Number(t)]||null}var Yt=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Jt(t){let e=String(t||""),r=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!Yt.test(r))throw new Error(`evm-rpc: ${e} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}var re=new Map,Qe=new Map;function Xt(t){let e=new Error(t?.message||JSON.stringify(t));return e.code=t?.code,e}function Zt(t){if(t?.error)throw Xt(t.error);return t?.result}function er(t,e,r){return`${t}
|
|
2
|
+
import{createHash as Nt}from"node:crypto";import{types as M}from"node:util";import{AsyncLocalStorage as Et}from"node:async_hooks";var St=new Et,At=["http","retry","shared"],xt=512;function ce(t){let e=St.getStore();if(!e||e.closed||!At.includes(t))return null;if(e.spans.length>=xt)return e.droppedSpans++,null;let r={stage:t,startMs:e.now()-e.start,durationMs:null,outcome:"pending",status:null};return e.spans.push(r),(n,s=null)=>{e.closed||r.durationMs!==null||(r.durationMs=Math.max(0,e.now()-e.start-r.startMs),r.outcome=n==="succeeded"?"succeeded":"failed",r.status=Number.isInteger(s)&&s>=100&&s<=599?s:null)}}import W from"node:net";import Ct from"node:dns";var Tt=new Set(["localhost","metadata.google.internal","metadata.goog"]);function ue(t){let e=String(t).toLowerCase().split("%")[0];if((e.match(/::/g)||[]).length>1)return null;let r=a=>{if(!a)return[];let u=a.split(":"),p=u.at(-1);if(p?.includes(".")){let f=p.split(".").map(Number);if(f.length!==4||f.some(h=>!Number.isInteger(h)||h<0||h>255))return null;u.splice(u.length-1,1,(f[0]<<8|f[1]).toString(16),(f[2]<<8|f[3]).toString(16))}return u.some(f=>!/^[0-9a-f]{1,4}$/.test(f))?null:u.map(f=>Number.parseInt(f,16))},[n,s]=e.split("::"),o=r(n),i=r(s);if(!o||!i)return null;let l=e.includes("::"),c=8-o.length-i.length;if(!l&&c!==0||l&&c<1)return null;let d=[...o,...Array(Math.max(0,c)).fill(0),...i];return d.length!==8?null:Uint8Array.from(d.flatMap(a=>[a>>8,a&255]))}function ye(t,e,r){let n=Math.floor(r/8),s=r%8;for(let i=0;i<n;i+=1)if(t[i]!==e[i])return!1;if(!s)return!0;let o=255<<8-s;return(t[n]&o)===(e[n]&o)}function we(t){if(W.isIPv4(t)){let e=t.split(".").map(Number);return!(e[0]===0||e[0]===10||e[0]===127||e[0]>=224||e[0]===100&&e[1]>=64&&e[1]<=127||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&(e[1]===0||e[1]===2||e[1]===168)||e[0]===192&&e[1]===88&&e[2]===99||e[0]===198&&(e[1]===18||e[1]===19||e[1]===51)||e[0]===203&&e[1]===0&&e[2]===113)}if(W.isIPv6(t)){let e=ue(t);if(!e)return!1;let r=ue("::ffff:0:0");return ye(e,r,96)?we([...e.slice(12)].join(".")):ye(e,ue("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([s,o])=>ye(e,ue(s),o)):!1}return!1}function It(t){let e;try{e=new URL(String(t))}catch{return{ok:!1,error:`not a valid URL: ${String(t).slice(0,120)}`}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{ok:!1,error:`refused protocol ${e.protocol} (only http/https)`};let r=e.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(Tt.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=W.isIP(r);return n!==0&&!we(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:e,host:r,isLiteralIp:n!==0}}async function ge(t,{lookupFn:e=Ct.promises.lookup}={}){let r=It(t);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:W.isIPv6(r.host)?6:4}]};let n;try{n=await e(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(s=>!we(s.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function ve({requireUndici:t=!1,importUndici:e=()=>import("undici")}={}){let r,n;try{let u=await e();r=u.Agent,n=u.fetch}catch(u){if(t)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${u?.message||u}`);return null}if(typeof r!="function"||typeof n!="function"){if(t)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let s=u=>String(u).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),o=new Map,i=u=>(Array.isArray(u)?u:[u]).map(p=>typeof p=="string"?{address:p}:p).filter(p=>p&&p.address).map(p=>({address:p.address,family:p.family||(W.isIPv6(p.address)?6:4)})),l=(u,p,f)=>{o.set(s(u),i(typeof p=="string"?[{address:p,family:f}]:p))},c=u=>{let p=s(u);if(W.isIP(p))return[{address:p,family:W.isIPv6(p)?6:4}];let f=o.get(p);if(!f||!f.length)throw new Error(`refused: unpinned host ${u} during pinned fetch`);return f},d=new r({connect:{lookup(u,p,f){let h;try{h=c(u)}catch(y){return f(y)}return p?.all?f(null,h):f(null,h[0].address,h[0].family)}}}),a=kt((u,p={})=>n(u,{...p,dispatcher:d}),l);return{dispatcher:d,fetch:a,pin:l,resolve:c,async close(){try{await d.destroy()}catch{}}}}var Ee=Symbol.for("oracle.egressGuard.pinCapableFetch");function kt(t,e){if(typeof t!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof e!="function")throw new Error("markPinCapableFetch: pin must be a function");return t[Ee]=Object.freeze({pin:e}),t}function Se(t){return typeof t=="function"&&typeof t[Ee]?.pin=="function"}function Be(t,e,r){if(!Se(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[Ee].pin(e,r)}var Ot=new Set([408,425,429,500,502,503,504]),$e=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Pt=2,Fe=4e3,Rt=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Lt=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,_t=AbortSignal.prototype.throwIfAborted,Ut=EventTarget.prototype.addEventListener,De=EventTarget.prototype.removeEventListener,je=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,te=t=>t?Rt.call(t):!1,qt=t=>t?Lt.call(t):void 0,Bt=new Set([301,302,303,307,308]),de=3,Ur=64*1024,H=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});function k(t){return V(`HTTP JSON body refused: ${t}`)}function $t(t){return["isArgumentsObject","isArrayBuffer","isAnyArrayBuffer","isArrayBufferView","isBoxedPrimitive","isDataView","isDate","isExternal","isGeneratorObject","isKeyObject","isCryptoKey","isMap","isMapIterator","isModuleNamespaceObject","isNativeError","isPromise","isRegExp","isSet","isSetIterator","isTypedArray","isWeakMap","isWeakSet"].some(e=>typeof M[e]=="function"&&M[e](t))}function Ft(t){let e=[],r=0,n=0,s=0,o=0,i=new WeakSet,l=a=>{if(r+=Buffer.byteLength(a,"utf8"),r>H.bytes)throw k("serialized byte limit exceeded");e.push(a)},c=a=>{if(Buffer.byteLength(a,"utf8")>H.bytes)throw k("serialized byte limit exceeded");return JSON.stringify(a)},d=(a,u)=>{if(n+=1,n>H.nodes)throw k("node limit exceeded");if(u>H.depth)throw k("depth limit exceeded");if(a===null){l("null");return}if(typeof a=="string"){l(c(a));return}if(typeof a=="boolean"){l(a?"true":"false");return}if(typeof a=="number"){if(!Number.isFinite(a))throw k("non-finite number");l(Object.is(a,-0)?"0":String(a));return}if(typeof a!="object")throw k("unsupported non-JSON value");if(M.isProxy(a))throw k("proxy value");if($t(a))throw k("unsupported exotic object");if(i.has(a))throw k("cyclic value");i.add(a);try{if(Object.getOwnPropertySymbols(a).length>0)throw k("symbol-keyed fields are unsupported");if(Array.isArray(a)){let h=Object.getPrototypeOf(a),y=0;for(;h!==null;){if(M.isProxy(h))throw k("proxy array prototype");if(y+=1,y>H.depth)throw k("array prototype depth limit exceeded");h=Object.getPrototypeOf(h)}if(a.length>H.arrayLength)throw k("array length limit exceeded");for(let S=0;S<a.length;S+=1){let P=Object.getOwnPropertyDescriptor(a,String(S));if(!P||!Object.hasOwn(P,"value")||P.enumerable!==!0)throw k("array entries must be dense enumerable own data")}let m=0;for(let S in a){if(o+=1,o>H.fields)throw k("enumeration limit exceeded");if(Object.hasOwn(a,S)&&(m+=1,m>a.length))throw k("named array fields are unsupported")}if(m!==a.length)throw k("array entries must be dense enumerable own data");l("[");for(let S=0;S<a.length;S+=1)S&&l(","),d(Object.getOwnPropertyDescriptor(a,String(S)).value,u+1);l("]");return}let p=Object.getPrototypeOf(a);if(p!==Object.prototype&&p!==null)throw k("non-plain object");let f=[];for(let h in a){if(o+=1,o>H.fields)throw k("enumeration limit exceeded");if(!Object.hasOwn(a,h))continue;if(s+=1,s>H.fields)throw k("field limit exceeded");let y=Object.getOwnPropertyDescriptor(a,h);if(!y||!Object.hasOwn(y,"value")||y.enumerable!==!0)throw k("object fields must be enumerable own data");f.push([h,y.value])}l("{");for(let h=0;h<f.length;h+=1)h&&l(","),l(c(f[h][0])),l(":"),d(f[h][1],u+1);l("}")}finally{i.delete(a)}};return d(t,0),e.join("")}function Dt(t){let e=Object.create(null);if(t==null)return e;if(typeof t!="object"&&typeof t!="function")throw new TypeError("HTTP headers must be an object");if(M.isProxy(t))throw new TypeError("HTTP headers must not be a proxy");if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("HTTP headers must not contain symbol fields");let r=new Set;for(let n of Object.keys(t)){if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(n))throw new TypeError("HTTP header names must be valid tokens");let s=n.toLowerCase();if(r.has(s))throw new TypeError("HTTP headers contain a duplicate canonical name");r.add(s);let o=Object.getOwnPropertyDescriptor(t,n);if(!o||!Object.hasOwn(o,"value"))throw new TypeError("HTTP headers must contain own data properties");let i=o.value;if(i==null||["object","function","symbol"].includes(typeof i))throw new TypeError("HTTP header values must be scalar");e[n]=String(i)}return e}function jt(){return Object.assign(Object.create(null),{Accept:"application/json"})}function Ht(t,e){if(!t)throw new Error(`HTTP redirect from ${e} missing Location`);let r=new URL(String(t),String(e));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${e} used unsupported protocol ${r.protocol}`);return r.toString()}function Mt(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var Ae=new Map,He=new WeakMap,Me=1;function le(t){if((typeof t!="object"||t===null)&&typeof t!="function")return`${typeof t}:${String(t)}`;let e=He.get(t);return e||(e=Me,Me+=1,He.set(t,e)),`reference:${e}`}var Vt=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),zt=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function Ve(t){if(!t||typeof t!="object"||Array.isArray(t)||!Object.hasOwn(t,"jsonrpc")||!Object.hasOwn(t,"method")||t.jsonrpc!=="2.0")return!1;let e=typeof t.method=="string"?t.method:"";return e?Vt.has(e)||/^get[A-Z0-9_]/u.test(e)||/^is[A-Z0-9_]/u.test(e)||/^eth_get[A-Z0-9_]/u.test(e):!1}function ze(t,e){if(t==="GET"&&e==null)return!0;if(t!=="POST"||e==null)return!1;let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{return!1}if(Array.isArray(r))return r.length>0&&r.every(Ve);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return Ve(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&zt.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function Wt(t,e,r,n={},s=null){let o=Nt("sha256"),i=(c,d)=>{let a=String(d);o.update(String(Buffer.byteLength(c,"utf8"))).update(":").update(c),o.update("=").update(String(Buffer.byteLength(a,"utf8"))).update(":").update(a).update(`
|
|
3
|
+
`)};i("method",t),i("url",e),Object.keys(r||{}).map((c,d)=>({name:c.toLowerCase(),order:d,value:String(r[c])})).sort((c,d)=>c.name.localeCompare(d.name)||c.order-d.order).forEach((c,d)=>{i(`header-name-${d}`,c.name),i(`header-value-${d}`,c.value)}),i("body",s??"-");for(let c of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])i(`context-${c}`,n[c]??"-");return o.digest("hex")}function Kt(t,e){let r=Number(e);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Fe):Math.min(250*2**t,Fe)+Math.floor(Math.random()*100)}var Gt=t=>new Promise(e=>setTimeout(e,t));function V(t,e={}){let r=new Error(t);return r.retryable=!1,Object.assign(r,e),r}function xe(t,e,r){return V(`HTTP response from ${t} exceeded maxResponseBytes ${r} (${e})`,{oversize:!0})}function K(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function Qt(t){return t?t.byteLength??t.length??0:0}async function Yt(t,e,{url:r,truncate:n=!1,onOversize:s}={}){if(e==null)return await t.text();let o=Number(t.headers?.get?.("content-length"));if(Number.isFinite(o)&&o>e&&(K(t),!n))throw xe(r,`content-length ${o}`,e);let i=t.body?.getReader?.();if(!i){let u=await t.text(),p=Buffer.byteLength(u,"utf8");if(p>e){if(!n)throw xe(r,`body ${p} bytes`,e);return Buffer.from(u,"utf8").subarray(0,e).toString("utf8")}return u}let l=[],c=0,d=!1;try{for(;;){let{value:u,done:p}=await i.read();if(p)break;if(u&&(l.push(Buffer.from(u)),c+=Qt(u),c>e)){d=!0;break}}}finally{if(d)try{await i.cancel()}catch{}try{i.releaseLock?.()}catch{}}if(d&&(typeof s=="function"&&s(),!n))throw xe(r,`streamed ${c} bytes`,e);let a=Buffer.concat(l);return(d?a.subarray(0,e):a).toString("utf8")}function Jt(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Xt(t,{fetchImpl:e,method:r,headers:n,body:s,timeoutMs:o,lookupFn:i,realFetch:l,untrustedUrl:c=!1,maxResponseBytes:d=null,sameOriginRedirectsOnly:a=!1,importUndici:u,validateResponse:p,signal:f,redirectPolicy:h="follow",maxRedirects:y=de}){let m=null,S=e,P=i?{lookupFn:i}:{};if(c&&!l&&!Se(S))throw V(`HTTP refused ${t}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let R=new AbortController,U=setTimeout(()=>R.abort(),o),N=f?je?je([f,R.signal]):f:R.signal,C=async(v,{status:T=null}={})=>{let E=await ge(v,P);if(!E.ok)throw V(T==null?`HTTP refused ${v}: ${E.error}`:`HTTP redirect to ${v} ${E.error}`,T==null?{}:{status:T});let L=new URL(v).hostname;if(l){if(m&&(await m.close(),m=null),!m)try{m=await ve({requireUndici:!0,...u?{importUndici:u}:{}})}catch(b){throw V(T==null?`HTTP refused ${v}: ${b?.message||b}`:`HTTP redirect to ${v} refused: ${b?.message||b}`,T==null?{}:{status:T})}m.pin(L,E.addresses),S=m.fetch}else Be(S,L,E.addresses);return E};try{let v=String(t),T=Object.assign(Object.create(null),n||{});c&&await C(v);for(let E=0;E<=y;E+=1){let L=Object.assign(Object.create(null),{method:r,headers:T,body:s,signal:N,redirect:"manual",dispatcher:void 0}),b=await S(v,L);if((h==="error"||y===0)&&b.status>=300&&b.status<400)throw K(b),V(`HTTP ${b.status} ${r} redirect refused`,{status:b.status,redirectRefused:!0});if(Bt.has(b.status)){let q=a===!0&&r==="POST"&&[307,308].includes(b.status)&&ze(r,s);if(r!=="GET"&&r!=="HEAD"&&!q){K(b);let O=new Error(`HTTP ${b.status} ${r} ${v} redirected non-idempotent request`);throw O.status=b.status,O}if(E===y)throw K(b),V(`HTTP ${b.status} ${r} redirect budget exhausted`,{status:b.status,redirectRefused:!0});let Re=b.headers?.get?.("location"),$;try{$=Ht(Re,v)}catch(O){throw K(b),O}let z=!Mt($,v);if(K(b),z&&r==="POST"){let O=new Error(`HTTP ${b.status} ${r} cross-origin redirect refused`);throw O.status=b.status,O}if(z&&a){let O=new Error(`HTTP ${b.status} ${r} cross-origin redirect refused`);throw O.status=b.status,O.retryable=!1,O}if(z&&(T=jt(T)),c)await C($,{status:b.status});else if(z){let O=await ge($,P);if(!O.ok){let x=new Error(`HTTP redirect from ${v} ${O.error}`);throw x.status=b.status,x.retryable=!1,x}l&&O.addresses?.length&&(m||(m=await ve(u?{importUndici:u}:{})),m&&(m.pin(new URL($).hostname,O.addresses),S=m.fetch))}v=$;continue}if(typeof p=="function")try{await p(b,{url:v})}catch(q){throw K(b),V(q?.message||String(q))}let _=await Yt(b,d,{url:v,onOversize:()=>R.abort()}),X=Jt(_);if(!b.ok){let q=new Error(`HTTP ${b.status} ${r} ${v}`);throw q.status=b.status,q.retryAfter=b.headers?.get?.("retry-after")??null,q.body=X??_.slice(0,300),q}return X??_}throw new Error(`HTTP redirect loop for ${t}`)}catch(v){if(R.signal.aborted&&!te(f)){let T=v&&(typeof v=="object"||typeof v=="function")&&!M.isProxy(v)?v:null,E=T?Object.getOwnPropertyDescriptor(T,"oversize"):null;if(!(E&&Object.hasOwn(E,"value")&&E.value===!0))try{if(!T)throw new TypeError("unsafe rejection");Object.defineProperties(T,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let b=new Error("HTTP request timed out");throw Object.defineProperties(b,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),b}}throw v}finally{clearTimeout(U),m&&await m.close()}}async function pe(t,e={}){if(e!=null&&typeof e!="object"&&typeof e!="function")throw new TypeError("HTTP options must be an object");if(e!=null&&M.isProxy(e))throw new TypeError("HTTP options must not be a proxy");let r=new Set(["body","dedupe","fetchImpl","headers","importUndici","lookupFn","maxRedirects","maxResponseBytes","method","redirectPolicy","retries","sameOriginRedirectsOnly","signal","timeoutMs","untrustedUrl","validateResponse"]);if(e!=null){if(Object.getOwnPropertySymbols(e).length>0)throw new TypeError("HTTP options contain unknown fields");for(let x of Object.getOwnPropertyNames(e)){let A=Object.getOwnPropertyDescriptor(e,x);if(!(x==="toJSON"&&A&&Object.hasOwn(A,"value")&&A.value===void 0)){if(!r.has(x))throw new TypeError("HTTP options contain unknown fields");if(!A||!A.enumerable||!Object.hasOwn(A,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=x=>{if(e==null||!Object.hasOwn(e,x))return;let A=Object.getOwnPropertyDescriptor(e,x);if(!A||!Object.hasOwn(A,"value"))throw new TypeError("HTTP options must contain own data properties");return A.value};if(typeof t!="string"||t.length===0||t.length>8192)throw new TypeError("HTTP URL must be a bounded string");let s=n("method");if(s!==void 0&&(typeof s!="string"||!/^[A-Za-z]+$/u.test(s)))throw new TypeError("HTTP method must be a string token");let o=n("timeoutMs");if(o!==void 0&&(!Number.isInteger(o)||o<1||o>12e4))throw new TypeError("HTTP timeoutMs must be a bounded integer");let i=n("retries");if(i!==void 0&&(!Number.isInteger(i)||i<0||i>10))throw new TypeError("HTTP retries must be a bounded integer");let l=n("redirectPolicy");if(l!==void 0&&l!=="follow"&&l!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let c=n("maxRedirects");if(c!==void 0&&(!Number.isInteger(c)||c<0||c>de))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${de}`);if(l==="error"&&c!==void 0&&c!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let d=l??"follow",a=d==="error"?0:c??de;for(let x of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let A=n(x);if(A!==void 0&&typeof A!="boolean")throw new TypeError(`HTTP ${x} must be boolean`)}let u=n("maxResponseBytes");if(u!==void 0&&(!Number.isInteger(u)||u<1||u>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let p=n("signal");if(p!==void 0){if(M.isProxy(p)||!(p instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{te(p)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let x of["importUndici","lookupFn","validateResponse"]){let A=n(x);if(A!==void 0&&typeof A!="function")throw new TypeError(`HTTP ${x} must be a function`)}let f=n("fetchImpl"),h=f||globalThis.fetch;if(typeof h!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let y=o??12e3,m=(s||"GET").toUpperCase(),S=n("headers"),P=Dt(S),R=Object.assign(Object.create(null),P);Object.keys(R).some(x=>x.toLowerCase()==="accept")||(R.Accept="application/json");let U=n("body");U!=null&&typeof U!="string"&&(Object.keys(R).find(A=>A.toLowerCase()==="content-type")||(R["Content-Type"]="application/json"),U=Ft(U));let N=i??Pt,C=n("lookupFn"),v=!f,T=n("untrustedUrl")===!0,E=n("sameOriginRedirectsOnly")===!0,L=n("importUndici"),b=n("validateResponse"),_=p,X=u??null,q=async()=>{let x;for(let A=0;A<=N;A++){_&&_t.call(_);let Le=ce("http");try{let j=await Xt(t,{fetchImpl:h,method:m,headers:R,body:U,timeoutMs:y,lookupFn:C,realFetch:v,untrustedUrl:T,maxResponseBytes:X,sameOriginRedirectsOnly:E,importUndici:L,validateResponse:b,signal:_,redirectPolicy:d,maxRedirects:a});return Le?.("succeeded"),j}catch(j){x=j;let Y=be=>{if(!j||typeof j!="object"&&typeof j!="function"||M.isProxy(j))return;let Z=Object.getOwnPropertyDescriptor(j,be);return Z&&Object.hasOwn(Z,"value")?Z.value:void 0},ie=Y("status");Le?.("failed",ie);let yt=Y("oracleTimeout")===!0||Y("name")==="AbortError"||Y("name")==="TimeoutError"||te(_),wt=new Set([408,425,429]),gt=Y("retryable")===!1?!1:ie!=null?wt.has(ie)||Ot.has(ie)&&$e.has(m):!yt&&$e.has(m);if(A===N||!gt)throw j;let _e=Kt(A,Y("retryAfter")),vt=ce("retry"),Ue=!1;try{_?await new Promise((be,Z)=>{let qe,ee=()=>{clearTimeout(qe),De.call(_,"abort",ee),Z(qt(_)||new DOMException("Aborted","AbortError"))};if(te(_)){ee();return}qe=setTimeout(()=>{De.call(_,"abort",ee),be()},_e),Ut.call(_,"abort",ee,{once:!0}),te(_)&&ee()}):await Gt(_e),Ue=!0}finally{vt?.(Ue?"succeeded":"failed")}}}throw x};if(!(n("dedupe")!==!1&&!_&&ze(m,U)))return q();let $=Wt(m,t,R,{untrustedUrl:T,maxResponseBytes:X,sameOriginRedirectsOnly:E,redirectPolicy:d,maxRedirects:a,timeoutMs:y,retries:N,fetchImpl:le(h),realFetch:v,lookupFn:le(C),importUndici:le(L),validateResponse:le(b)},U),z=Ae.get($);if(z){let x=ce("shared");try{let A=await z;return x?.("succeeded"),A}catch(A){throw x?.("failed"),A}}let O=q().finally(()=>Ae.delete($));return Ae.set($,O),O}async function We(t,e,r){let n=Array.from(t),s=Math.max(1,Math.min(Number(e)||1,n.length||1)),o=new Array(n.length),i=0;return await Promise.all(Array.from({length:s},async()=>{for(;i<n.length;){let l=i++;o[l]=await r(n[l],l)}})),o}var Ke={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}},Zt=new Map(Object.values(Ke).map(t=>[t.chainId,t]));function Ge(t){return Zt.get(Number(t))||null}function Qe(t,e=process.env){let r=Ge(t);if(!r)return null;for(let n of r.rpcEnv){let s=(e[n]||"").trim();if(s)return s}return null}import{Interface as er,getAddress as tr}from"ethers";var Ye=new er(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Je(t,e){try{return tr(t).toLowerCase()}catch{throw new Error(`${e} must be a valid EVM address`)}}var rr={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 nr(t,{rpcUrl:e,env:r=process.env}={}){if(e)return e;let n=Qe(t,r);return n||rr[Number(t)]||null}var or=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function sr(t){let e=String(t||""),r=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!or.test(r))throw new Error(`evm-rpc: ${e} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}var re=new Map,Xe=new Map;function ar(t){let e=new Error(t?.message||JSON.stringify(t));return e.code=t?.code,e}function ir(t){if(t?.error)throw ar(t.error);return t?.result}function cr(t,e,r){return`${t}
|
|
4
4
|
${e}
|
|
5
|
-
${JSON.stringify(r??[])}`}async function
|
|
5
|
+
${JSON.stringify(r??[])}`}async function ur(t,e,r){return pe(t,{method:"POST",body:e,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function F(t,e,r=[],n={}){let s=String(e||""),o=sr(s),i=nr(t,n);if(!i)throw new Error(`No RPC URL for chainId ${t} (set env from chain registry rpcEnv or pass rpcUrl)`);if(o==="eth_chainid"&&n.cacheChainId!==!1){let a=Xe.get(i);if(a!=null)return a}let c=n.dedupe!==!1&&!n.signal?cr(i,s,r):null;if(c&&re.has(c))return re.get(c);let d=(async()=>{let a=await ur(i,{jsonrpc:"2.0",id:1,method:e,params:r},n),u=ir(a);return o==="eth_chainid"&&typeof u=="string"&&Xe.set(i,u),u})();return c&&(re.set(c,d),d.finally(()=>{re.get(c)===d&&re.delete(c)}).catch(()=>{})),d}async function Ze(t,e={}){let r=await F(t,"eth_blockNumber",[],e);return parseInt(r,16)}async function et(t,e,r={}){if(!e)throw new Error("rpcGetBalance requires address");let n=await F(t,"eth_getBalance",[e,"latest"],r);return{chainId:Number(t),address:e,balanceWei:BigInt(n).toString(),balanceHex:n}}async function tt(t={},e={}){let r=Number(t.chainId??e.chainId??1),n=Je(t.token||t.tokenAddress,"token"),s=Je(t.account||t.owner||t.address,"account"),o=Ye.encodeFunctionData("balanceOf",[s]),i=await F(r,"eth_call",[{to:n,data:o},t.blockTag||"latest"],e),l=Ye.decodeFunctionResult("balanceOf",i),c=BigInt(l[0]);return{chainId:r,token:n,account:s,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:t.blockTag||"latest"}}var lr=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"]);function rt(t,e){let r=String(t||"").toLowerCase(),n=String(e?.quote||e?.quoteToken?.address||"").toLowerCase(),s=String(e?.base||e?.baseToken?.address||"").toLowerCase();return n===r?{address:e.base||e.baseToken?.address,symbol:e.baseToken?.symbol}:s===r?{address:e.quote||e.quoteToken?.address,symbol:e.quoteToken?.symbol}:{address:e.quote||e.quoteToken?.address,symbol:e.quoteToken?.symbol}}function Ce(t,e=[],{stables:r=[],wrappedNative:n=null}={}){let s=String(t||"").toLowerCase(),o=new Set((r||[]).map(c=>String(c).toLowerCase())),i=String(n||"").toLowerCase(),l=(e||[]).map((c,d)=>{let a=rt(s,c),u=String(a.address||"").toLowerCase(),p=String(a.symbol||"").toLowerCase(),f=Number(c.liquidityUsd??c.liquidity?.usd),h=Number.isFinite(f)?f:0,y=String(c.dex||c.dexId||"").toLowerCase(),m=0;return o.has(u)||lr.has(p)?m=300:i&&u===i&&(m=100),y.includes("v4")?m+=20:y.includes("v3")?m+=10:(y.includes("v2")||y.includes("raydium")||y.includes("orca")||y.includes("meteora"))&&(m+=8),{pool:c,score:m*1e12+h,index:d,otherAddr:u,liquidityUsd:h}});return l.sort((c,d)=>d.score-c.score||c.index-d.index),l.map(c=>c.pool)}function nt(t,e=[]){let r=Array.isArray(e)?e:[];return r.length&&rt(t,r[0]).address||null}var dr="https://api.dexscreener.com",Wr=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function pr(t={}){return(t.baseUrl||process.env.DEXSCREENER_API_URL||dr).replace(/\/$/,"")}function fr(t,e){if(typeof t!="string"&&typeof t!="number")throw new Error(`${e} required`);let r=String(t).trim();if(!r||r.length>128||!/^[A-Za-z0-9][A-Za-z0-9._:+~-]*$/u.test(r))throw new Error(`${e} must be a valid path component of at most 128 characters`);return encodeURIComponent(r)}function hr(t,e){return pe(`${pr(e)}${t}`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}async function ot(t,e={}){return hr(`/latest/dex/tokens/${fr(t,"tokenAddress")}`,e)}var ne=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),g=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),w=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),mr=/^0x[0-9a-fA-F]{40}$/;function br(t={}){let e=[],r=[];if(!t||typeof t!="object")return{ok:!1,errors:["definition must be an object"],warnings:r};if((!Number.isInteger(t.chainId)||t.chainId<=0)&&e.push("chainId must be a positive integer"),(typeof t.key!="string"||!/^[a-z][a-z0-9-]*$/.test(t.key||""))&&e.push('key must be a lowercase slug (e.g. "base")'),(typeof t.name!="string"||!t.name.trim())&&e.push("name is required"),!Array.isArray(t.rpcEnv)||t.rpcEnv.length===0)e.push("rpcEnv must list at least one environment variable name");else for(let s of t.rpcEnv)(typeof s!="string"||!/^[A-Z][A-Z0-9_]*$/.test(s))&&e.push(`rpcEnv entry "${s}" should be an UPPER_SNAKE env var name`);if(t.nativeCurrency){let s=t.nativeCurrency;(typeof s.symbol!="string"||!s.symbol)&&e.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(s.decimals)||e.push("nativeCurrency.decimals must be an integer")}for(let[s,o]of(t.venues||[]).entries()){let i=`venues[${s}]`;if(!o||typeof o!="object"){e.push(`${i} must be an object`);continue}mr.test(o.address||"")||e.push(`${i}.address is not a valid 20-byte address`),/^0x0{40}$/.test(o.address||"")&&e.push(`${i}.address is the zero address -- placeholder left in place?`),o.kind||e.push(`${i}.kind is required (router|quoter|factory|...)`),o.verified?(o.verified.method||e.push(`${i}.verified.method is required`),o.verified.source||e.push(`${i}.verified.source is required`),o.verified.date||r.push(`${i}.verified.date missing -- add one so staleness is visible`)):e.push(`${i} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let n=t.capabilities||{};for(let s of Object.keys(n))ne.includes(s)?typeof n[s]!="function"&&e.push(`capability "${s}" must be a function`):e.push(`unknown capability "${s}"`);return Object.keys(n).length===0&&r.push("scanner implements no capabilities -- it can only be registered, not used"),n.prepareUnsignedTx&&!n.quote&&r.push("prepareUnsignedTx without quote: no priced expectation to validate the built tx against"),n.prepareUnsignedTx&&!n.sellSimulation&&r.push("prepareUnsignedTx without sellSimulation: cannot prove an asset is exitable before buying"),{ok:e.length===0,errors:e,warnings:r}}function yr(t){let{ok:e,errors:r,warnings:n}=br(t);if(!e)throw new Error(`invalid scanner for ${t?.key??"<unknown>"}:
|
|
6
6
|
- ${r.join(`
|
|
7
|
-
- `)}`);let s=t.capabilities||{},o=ne.filter(l=>typeof s[l]=="function"),a={key:t.key,chainId:t.chainId,name:t.name,rpcEnv:[...t.rpcEnv],nativeCurrency:t.nativeCurrency?{...t.nativeCurrency}:null,wrappedNative:t.wrappedNative||null,explorer:t.explorer||null,venues:(t.venues||[]).map(l=>({...l})),warnings:n,capabilities(){return{chainId:t.chainId,key:t.key,supported:[...o],unsupported:ne.filter(l=>!o.includes(l))}},supports(l){return o.includes(l)}};for(let l of ne)o.includes(l)?a[l]=async(...c)=>s[l](...c,{scanner:a}):a[l]=async()=>{throw new Error(`${t.key} (chain ${t.chainId}) does not implement "${l}". Supported: ${o.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(a)}var oe=new Map;function rt(t){let e=ur(t);return oe.set(e.chainId,e),e}function Ce(t){return oe.get(Number(t))||null}function de(){return[...oe.values()]}function nt(){let t={};for(let e of oe.values())t[e.chainId]={key:e.key,name:e.name,...e.capabilities(),venueCount:e.venues.length,failClosed:e.venues.length===0};return{generatedAt:new Date().toISOString(),chainCount:oe.size,capabilities:[...ne],chains:t}}var Ie={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},B=t=>BigInt(t).toString(16).padStart(64,"0"),se=t=>t.slice(2).toLowerCase().padStart(64,"0");function lr(t,e){return`0x${Ie.getAmountsOut}`+B(t)+B(64)+B(e.length)+e.map(se).join("")}function dr(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length<128)return null;let r=Number(BigInt(`0x${e.slice(64,128)}`));if(!Number.isFinite(r)||r<1||r>16)return null;let n=[];for(let s=0;s<r;s++){let o=128+s*64;if(e.length<o+64)return null;n.push(BigInt(`0x${e.slice(o,o+64)}`))}return n}function Te(t,e="router"){return(t?.venues||[]).find(n=>n.kind===e)?.address??null}var ke=100;function pr(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>ke)throw new Error(`slippageBps ${r} exceeds the ${ke} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(r))/10000n}function ot(t){let{chainId:e,wrappedNative:r}=t;async function n(s,o,a,l){let c=await F(e,"eth_call",[{to:s,data:lr(o,a)},"latest"],l);return dr(c?.result??c)}return{async quote({tokenIn:s,tokenOut:o,amountIn:a,path:l},c={}){let d=Te(c.scanner);if(!d)return{chainId:e,evidence:g.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let i=l||[s,o];if(i.some(p=>!/^0x[0-9a-fA-F]{40}$/.test(p||"")))throw new Error("quote requires valid 20-byte addresses");let u=await n(d,a,i,c);return u?{chainId:e,router:d,path:i,amountIn:String(a),amountOut:u[u.length-1].toString(),hops:i.length-1,evidence:g.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:e,router:d,path:i,evidence:g.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:s,amountIn:o,base:a},l={}){let c=Te(l.scanner),d=a||r;if(d&&String(s).toLowerCase()===String(d).toLowerCase())return{chainId:e,token:s,verdict:w.UNKNOWN,evidence:g.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||!d)return{chainId:e,token:s,verdict:w.UNKNOWN,evidence:g.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 i=await n(c,o,[d,s],l);if(!i)return{chainId:e,token:s,verdict:w.FAIL,evidence:g.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let u=i[i.length-1];if(u===0n)return{chainId:e,token:s,verdict:w.FAIL,evidence:g.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let p=await n(c,u,[s,d],l);if(!p)return{chainId:e,token:s,verdict:w.FAIL,evidence:g.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 f=p[p.length-1],h=Number(f*10000n/BigInt(o)),y=w.PASS,m="round trip completes with expected fee/impact loss";return h<5e3?(y=w.FAIL,m=`round trip returns only ${(h/100).toFixed(2)}% -- punitive tax or no real liquidity`):h<9e3&&(y=w.CAUTION,m=`round trip returns ${(h/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,token:s,base:d,router:c,verdict:y,reason:m,amountIn:String(o),bought:u.toString(),returned:f.toString(),retentionBps:h,evidence:g.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:s,tokenOut:o,amountIn:a,recipient:l,slippageBps:c=50,deadlineSeconds:d=900,path:i},u={}){let p=u.scanner,f=Te(p);if(!f)throw new Error(`chain ${e} has no verified router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!/^0x[0-9a-fA-F]{40}$/.test(l||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let h=i||[s,o],y=await this.quote({tokenIn:s,tokenOut:o,amountIn:a,path:h},u);if(y.evidence!==g.LIVE)throw new Error(`cannot prepare without a live quote (${y.evidence}: ${y.reason??"no reason given"})`);let m=pr(y.amountOut,c);if(m<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let S=BigInt(Math.floor(Date.now()/1e3)+Number(d)),P=r&&h[0].toLowerCase()===r.toLowerCase()&&u.useNative,R=P?`0x${Ie.swapExactETHForTokens}`+B(m)+B(128)+se(l)+B(S)+B(h.length)+h.map(se).join(""):`0x${Ie.swapExactTokensForTokens}`+B(a)+B(m)+B(160)+se(l)+B(S)+B(h.length)+h.map(se).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:e,tx:{to:f,data:R,value:P?`0x${BigInt(a).toString(16)}`:"0x0"},guard:{quotedOut:y.amountOut,minOut:m.toString(),slippageBps:c,maxSlippageBps:ke,deadline:S.toString()},requires:P?[]:[{step:"approve",token:h[0],spender:f,amount:String(a)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var fr=[100,500,3e3,1e4],st={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},G=t=>BigInt(t).toString(16).padStart(64,"0"),ie=t=>t.slice(2).toLowerCase().padStart(64,"0"),it=/^0x[0-9a-fA-F]{40}$/,Oe=100;function hr(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Oe)throw new Error(`slippageBps ${r} exceeds the ${Oe} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(r))/10000n}function Ne(t,e){return(t?.venues||[]).find(r=>r.kind===e)?.address??null}function at(t){let{chainId:e,wrappedNative:r}=t;async function n({quoter:o,tokenIn:a,tokenOut:l,amountIn:c,fee:d},i){let u=`0x${st.quoteExactInputSingle}`+ie(a)+ie(l)+G(c)+G(d)+G(0),p=await F(e,"eth_call",[{to:o,data:u},"latest"],i).catch(()=>null),f=p?.result??p;if(!f||f==="0x"||f.length<66)return null;let h=BigInt(`0x${f.slice(2,66)}`);return h>0n?h:null}async function s({quoter:o,tokenIn:a,tokenOut:l,amountIn:c},d){let i=await Promise.all(fr.map(async p=>{let f=await n({quoter:o,tokenIn:a,tokenOut:l,amountIn:c,fee:p},d);return{fee:p,amountOut:f?f.toString():null,out:f}})),u=null;for(let p of i)p.out&&(!u||p.out>u.amountOut)&&(u={fee:p.fee,amountOut:p.out});return{best:u,tried:i.map(({fee:p,amountOut:f})=>({fee:p,amountOut:f}))}}return{async quote({tokenIn:o,tokenOut:a,amountIn:l},c={}){let d=Ne(c.scanner,"quoter");if(!d)return{chainId:e,evidence:g.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let p of[o,a])if(!it.test(p||""))throw new Error("quote requires valid 20-byte addresses");let{best:i,tried:u}=await s({quoter:d,tokenIn:o,tokenOut:a,amountIn:l},c);return i?{chainId:e,venue:"uniswap-v3",quoter:d,tokenIn:o,tokenOut:a,amountIn:String(l),amountOut:i.amountOut.toString(),fee:i.fee,useNative:!!r&&String(o).toLowerCase()===String(r).toLowerCase(),triedFeeTiers:u,evidence:g.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:e,quoter:d,tokenIn:o,tokenOut:a,triedFeeTiers:u,evidence:g.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:o,amountIn:a,base:l},c={}){let d=Ne(c.scanner,"quoter"),i=(t.stableQuoteAssets||[]).map(N=>String(N).toLowerCase()),u=null;!l&&typeof t.resolveQuoteAsset=="function"&&(u=await t.resolveQuoteAsset(o,c).catch(()=>null));let p=String(o).toLowerCase(),f=String(r||"").toLowerCase();if(f&&p===f)return{chainId:e,token:o,verdict:w.UNKNOWN,evidence:g.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};let h=l||u||(i[0]&&p!==i[0]?i[0]:null)||r;if(h&&p===String(h).toLowerCase())return{chainId:e,token:o,verdict:w.UNKNOWN,evidence:g.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!d||!h)return{chainId:e,token:o,verdict:w.UNKNOWN,evidence:g.UNAVAILABLE,reason:d?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let y=await s({quoter:d,tokenIn:h,tokenOut:o,amountIn:a},c);if(!y.best){let N=i.find(A=>A&&A!==String(h).toLowerCase()&&A!==String(o).toLowerCase());if(N){let A=await s({quoter:d,tokenIn:N,tokenOut:o,amountIn:a},c);if(A.best){let v=await s({quoter:d,tokenIn:o,tokenOut:N,amountIn:A.best.amountOut},c);if(v.best){let x=v.best.amountOut,E=Number(x*10000n/BigInt(a)),L=w.PASS,b="round trip vs dollar book completes with expected fee/impact loss";return E<5e3?(L=w.FAIL,b=`round trip vs dollar book returns only ${(E/100).toFixed(2)}% -- punitive tax or no real liquidity`):E<9e3&&(L=w.CAUTION,b=`round trip vs dollar book returns ${(E/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:N,quoteAsset:N,verdict:L,reason:b,amountIn:String(a),bought:A.best.amountOut.toString(),returned:x.toString(),retentionBps:E,buyFee:A.best.fee,sellFee:v.best.fee,evidence:g.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:e,token:o,verdict:w.FAIL,evidence:g.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let m=await s({quoter:d,tokenIn:o,tokenOut:h,amountIn:y.best.amountOut},c);if(!m.best){let N=i.find(A=>A&&A!==String(h).toLowerCase()&&A!==String(o).toLowerCase());if(N){let A=await s({quoter:d,tokenIn:N,tokenOut:o,amountIn:a},c),v=A.best?await s({quoter:d,tokenIn:o,tokenOut:N,amountIn:A.best.amountOut},c):{best:null};if(A.best&&v.best){let x=v.best.amountOut,E=Number(x*10000n/BigInt(a)),L=w.PASS,b="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return E<5e3?(L=w.FAIL,b=`dollar-book round trip returns only ${(E/100).toFixed(2)}%`):E<9e3&&(L=w.CAUTION,b=`dollar-book round trip returns ${(E/100).toFixed(2)}%`),{chainId:e,venue:"uniswap-v3",token:o,base:N,quoteAsset:N,verdict:L,reason:b,amountIn:String(a),bought:A.best.amountOut.toString(),returned:x.toString(),retentionBps:E,buyFee:A.best.fee,sellFee:v.best.fee,evidence:g.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:e,token:o,verdict:w.FAIL,evidence:g.LIVE,leg:"sell",bought:y.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let S=m.best.amountOut,P=Number(S*10000n/BigInt(a)),R=w.PASS,U="round trip completes with expected fee/impact loss";return P<5e3?(R=w.FAIL,U=`round trip returns only ${(P/100).toFixed(2)}% -- punitive tax or no real liquidity`):P<9e3&&(R=w.CAUTION,U=`round trip returns ${(P/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:h,verdict:R,reason:U,amountIn:String(a),bought:y.best.amountOut.toString(),returned:S.toString(),retentionBps:P,buyFee:y.best.fee,sellFee:m.best.fee,evidence:g.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:a,amountIn:l,recipient:c,slippageBps:d=50,fee:i},u={}){let p=Ne(u.scanner,"router");if(!p)throw new Error(`chain ${e} has no verified V3 router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!it.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=await this.quote({tokenIn:o,tokenOut:a,amountIn:l},u);if(f.evidence!==g.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let h=i??f.fee,y=hr(f.amountOut,d);if(y<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let m=!!(u.useNative||f.useNative)&&r&&String(o).toLowerCase()===String(r).toLowerCase(),S=`0x${st.exactInputSingle}`+ie(o)+ie(a)+G(h)+ie(c)+G(l)+G(y)+G(0);return{unsigned:!0,signedBy:"user-wallet",chainId:e,venue:"uniswap-v3",tx:{to:p,data:S,value:m?String(l):"0x0"},guard:{quotedOut:f.amountOut,minOut:y.toString(),slippageBps:d,maxSlippageBps:Oe,fee:h},requires:m?[]:[{step:"approve",token:o,spender:p,amount:String(l)}],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 pe={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function ct(t){if(!t||t==="0x")return null;try{return BigInt(t)}catch{return null}}function ut(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length>=128){let n=Number(BigInt(`0x${e.slice(64,128)}`));if(n>0&&n<=256&&e.length>=128+n*2){let s=e.slice(128,128+n*2),o=Buffer.from(s,"hex").toString("utf8").replace(/\0+$/,"");if(o)return o}}return Buffer.from(e.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function mr(t){let{chainId:e}=t;async function r(n,s,o){return F(e,"eth_call",[{to:n,data:s},"latest"],o)}return{async blockNumber(n={}){let s=await Ye(e,n);return{chainId:e,blockNumber:s?.blockNumber??s,evidence:g.LIVE}},async nativeBalance(n,s={}){let o=await Je(e,n,s);return{chainId:e,address:n,wei:o?.wei??o?.balance??null,symbol:t.nativeCurrency?.symbol??null,decimals:t.nativeCurrency?.decimals??18,evidence:g.LIVE}},async tokenBalance({token:n,owner:s},o={}){let a=await Xe({chainId:e,token:n,owner:s},o);return{chainId:e,token:n,owner:s,raw:a?.balance??a,evidence:g.LIVE}},async resolveToken(n,s={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:e,token:n,evidence:g.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[o,a,l,c]=await Promise.all([r(n,pe.decimals,s).catch(()=>null),r(n,pe.symbol,s).catch(()=>null),r(n,pe.name,s).catch(()=>null),r(n,pe.totalSupply,s).catch(()=>null)]),d=ct(o?.result??o),i=d!==null||a?.result||l?.result,u={chainId:e,address:n,decimals:d===null?null:Number(d),symbol:ut(a?.result??a),name:ut(l?.result??l),totalSupply:(ct(c?.result??c)??null)?.toString()??null,evidence:i?g.LIVE:g.UNKNOWN};return i||(u.warning="no ERC-20 metadata returned -- may not be a token contract"),u},async resolvePools(n,s={}){let o=t.dexscreenerSlug;if(!o)return{chainId:e,token:n,pools:[],evidence:g.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let a=await tt(n,s).catch(()=>null),c=(a?.pairs||a?.data?.pairs||[]).filter(i=>String(i.chainId).toLowerCase()===String(o).toLowerCase()).map(i=>({pair:i.pairAddress,dex:i.dexId,base:i.baseToken?.address,quote:i.quoteToken?.address,liquidityUsd:i.liquidity?.usd??null,priceUsd:i.priceUsd??null,volume24hUsd:i.volume?.h24??null,createdAt:i.pairCreatedAt??null})).sort((i,u)=>(u.liquidityUsd??0)-(i.liquidityUsd??0)),d=xe(n,c,{stables:t.stableQuoteAssets||[],wrappedNative:t.wrappedNative});return{chainId:e,token:n,pools:d,topPool:d[0]||null,quoteAsset:et(n,d),evidence:d.length?g.LIVE:g.UNKNOWN}},async scanBlocks({fromBlock:n,toBlock:s,address:o,topics:a,chunkSize:l=2e3}={},c={}){if(!Number.isInteger(n)||!Number.isInteger(s))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(s<n)throw new Error("toBlock must be >= fromBlock");let d=[],i=[];for(let p=n;p<=s;p+=l){let f=Math.min(p+l-1,s);i.push([p,f])}let u=await Ve(i,4,async([p,f])=>{let h={fromBlock:`0x${p.toString(16)}`,toBlock:`0x${f.toString(16)}`};o&&(h.address=o),a&&(h.topics=a);let y=await F(e,"eth_getLogs",[h],c).catch(m=>({error:String(m?.message||m)}));return{start:p,end:f,res:y}});for(let{start:p,end:f,res:h}of u){if(h?.error)return{chainId:e,fromBlock:n,toBlock:s,logs:d,complete:!1,failedAt:[p,f],error:h.error,evidence:g.UNKNOWN};for(let y of h?.result??h??[])d.push(y)}return{chainId:e,fromBlock:n,toBlock:s,logs:d,complete:!0,chunks:i.length,evidence:g.LIVE}},async scoreRisk(n,s={}){let o=[],a=w.PASS,l=i=>{let u={[w.PASS]:0,[w.CAUTION]:1,[w.UNKNOWN]:2,[w.FAIL]:3};u[i]>u[a]&&(a=i)},[c,d]=await Promise.all([this.resolveToken(n,s),this.resolvePools(n,s)]);if(c.evidence!==g.LIVE?(o.push({check:"erc20-metadata",result:w.UNKNOWN,detail:c.warning}),l(w.UNKNOWN)):o.push({check:"erc20-metadata",result:w.PASS,detail:`${c.symbol} / ${c.decimals}d`}),d.evidence===g.UNAVAILABLE)o.push({check:"liquidity",result:w.UNKNOWN,detail:d.reason}),l(w.UNKNOWN);else if(!d.pools.length)o.push({check:"liquidity",result:w.FAIL,detail:"no pool with liquidity found"}),l(w.FAIL);else{let i=d.pools[0],u=i.liquidityUsd??0;u<5e3?(o.push({check:"liquidity",result:w.CAUTION,detail:`top pool only $${u}`}),l(w.CAUTION)):o.push({check:"liquidity",result:w.PASS,detail:`$${u} on ${i.dex}`}),i.createdAt&&Date.now()-i.createdAt<24*3600*1e3&&(o.push({check:"age",result:w.CAUTION,detail:"pool under 24h old"}),l(w.CAUTION))}if(typeof this.sellSimulation=="function"){let i=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},s).catch(u=>({verdict:w.UNKNOWN,reason:String(u?.message||u)}));o.push({check:"sellability",result:i.verdict,detail:i.retentionBps!=null?`round trip returns ${(i.retentionBps/100).toFixed(2)}% -- ${i.reason}`:i.reason}),l(i.verdict)}else o.push({check:"sellability",result:w.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."}),l(w.UNKNOWN);return{chainId:e,token:n,verdict:a,checks:o,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function lt(t){let r={...mr(t)},n=new Set((t.venues||[]).map(o=>o.kind));t.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,at({chainId:t.chainId,wrappedNative:t.wrappedNative,stableQuoteAssets:t.stableQuoteAssets||[],resolveQuoteAsset:async(o,a)=>(await r.resolvePools(o,a)).quoteAsset||null})):t.venueKind==="uniswap-v2"&&n.has("router")&&Object.assign(r,ot({chainId:t.chainId,wrappedNative:t.wrappedNative}));let s={};for(let[o,a]of Object.entries(r))s[o]=a.bind(r);return{key:t.key,chainId:t.chainId,name:t.name,rpcEnv:t.rpcEnv,nativeCurrency:t.nativeCurrency,explorer:t.explorer,venues:t.venues||[],capabilities:s}}var br=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",stableQuoteAssets:["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48","0xdAC17F958D2ee523a2206206994597C13D831ec7"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85","0x94b008aA00579c1307B0EF2c499aD98a8ce58e58"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",stableQuoteAssets:["0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d","0x55d398326f99059fF775485246999027B3197955"],venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",stableQuoteAssets:["0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359","0xc2132D05D31c914a87C6611C10748AEb04B58e8F"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",stableQuoteAssets:["0x5fc5360d0400a0fd4f2af552add042d716f1d168"],venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",stableQuoteAssets:["0xaf88d065e77c8cC2239327C5EDb3A432268e5831","0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",stableQuoteAssets:["0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"],venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);function dt(){return br.map(t=>rt(lt(t)))}dt();var[pt,...ft]=process.argv.slice(2),fe=ft.includes("--json"),T=ft.filter(t=>t!=="--json");function J(t){t||D("missing <chain>");let e=Ce(Number(t));if(e)return e;let r=de().find(n=>n.key===String(t).toLowerCase());if(r)return r;D(`unknown chain "${t}". Known: ${de().map(n=>`${n.key}(${n.chainId})`).join(", ")}`)}function D(t){console.error(`error: ${t}`),process.exit(1)}function Q(t){process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
8
|
-
`)}function
|
|
7
|
+
- `)}`);let s=t.capabilities||{},o=ne.filter(l=>typeof s[l]=="function"),i={key:t.key,chainId:t.chainId,name:t.name,rpcEnv:[...t.rpcEnv],nativeCurrency:t.nativeCurrency?{...t.nativeCurrency}:null,wrappedNative:t.wrappedNative||null,explorer:t.explorer||null,venues:(t.venues||[]).map(l=>({...l})),warnings:n,capabilities(){return{chainId:t.chainId,key:t.key,supported:[...o],unsupported:ne.filter(l=>!o.includes(l))}},supports(l){return o.includes(l)}};for(let l of ne)o.includes(l)?i[l]=async(...c)=>s[l](...c,{scanner:i}):i[l]=async()=>{throw new Error(`${t.key} (chain ${t.chainId}) does not implement "${l}". 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 oe=new Map;function st(t){let e=yr(t);return oe.set(e.chainId,e),e}function Te(t){return oe.get(Number(t))||null}function fe(){return[...oe.values()]}function at(){let t={};for(let e of oe.values())t[e.chainId]={key:e.key,name:e.name,...e.capabilities(),venueCount:e.venues.length,failClosed:e.venues.length===0};return{generatedAt:new Date().toISOString(),chainCount:oe.size,capabilities:[...ne],chains:t}}var ke={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},B=t=>BigInt(t).toString(16).padStart(64,"0"),se=t=>t.slice(2).toLowerCase().padStart(64,"0");function wr(t,e){return`0x${ke.getAmountsOut}`+B(t)+B(64)+B(e.length)+e.map(se).join("")}function gr(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length<128)return null;let r=Number(BigInt(`0x${e.slice(64,128)}`));if(!Number.isFinite(r)||r<1||r>16)return null;let n=[];for(let s=0;s<r;s++){let o=128+s*64;if(e.length<o+64)return null;n.push(BigInt(`0x${e.slice(o,o+64)}`))}return n}function Ie(t,e="router"){return(t?.venues||[]).find(n=>n.kind===e)?.address??null}var Ne=100;function vr(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Ne)throw new Error(`slippageBps ${r} exceeds the ${Ne} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(r))/10000n}function it(t){let{chainId:e,wrappedNative:r}=t;async function n(s,o,i,l){let c=await F(e,"eth_call",[{to:s,data:wr(o,i)},"latest"],l);return gr(c?.result??c)}return{async quote({tokenIn:s,tokenOut:o,amountIn:i,path:l},c={}){let d=Ie(c.scanner);if(!d)return{chainId:e,evidence:g.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let a=l||[s,o];if(a.some(p=>!/^0x[0-9a-fA-F]{40}$/.test(p||"")))throw new Error("quote requires valid 20-byte addresses");let u=await n(d,i,a,c);return u?{chainId:e,router:d,path:a,amountIn:String(i),amountOut:u[u.length-1].toString(),hops:a.length-1,evidence:g.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:e,router:d,path:a,evidence:g.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:s,amountIn:o,base:i},l={}){let c=Ie(l.scanner),d=i||r;if(d&&String(s).toLowerCase()===String(d).toLowerCase())return{chainId:e,token:s,verdict:w.UNKNOWN,evidence:g.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||!d)return{chainId:e,token:s,verdict:w.UNKNOWN,evidence:g.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 a=await n(c,o,[d,s],l);if(!a)return{chainId:e,token:s,verdict:w.FAIL,evidence:g.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let u=a[a.length-1];if(u===0n)return{chainId:e,token:s,verdict:w.FAIL,evidence:g.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let p=await n(c,u,[s,d],l);if(!p)return{chainId:e,token:s,verdict:w.FAIL,evidence:g.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 f=p[p.length-1],h=Number(f*10000n/BigInt(o)),y=w.PASS,m="round trip completes with expected fee/impact loss";return h<5e3?(y=w.FAIL,m=`round trip returns only ${(h/100).toFixed(2)}% -- punitive tax or no real liquidity`):h<9e3&&(y=w.CAUTION,m=`round trip returns ${(h/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,token:s,base:d,router:c,verdict:y,reason:m,amountIn:String(o),bought:u.toString(),returned:f.toString(),retentionBps:h,evidence:g.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:s,tokenOut:o,amountIn:i,recipient:l,slippageBps:c=50,deadlineSeconds:d=900,path:a},u={}){let p=u.scanner,f=Ie(p);if(!f)throw new Error(`chain ${e} has no verified router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!/^0x[0-9a-fA-F]{40}$/.test(l||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let h=a||[s,o],y=await this.quote({tokenIn:s,tokenOut:o,amountIn:i,path:h},u);if(y.evidence!==g.LIVE)throw new Error(`cannot prepare without a live quote (${y.evidence}: ${y.reason??"no reason given"})`);let m=vr(y.amountOut,c);if(m<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let S=BigInt(Math.floor(Date.now()/1e3)+Number(d)),P=r&&h[0].toLowerCase()===r.toLowerCase()&&u.useNative,R=P?`0x${ke.swapExactETHForTokens}`+B(m)+B(128)+se(l)+B(S)+B(h.length)+h.map(se).join(""):`0x${ke.swapExactTokensForTokens}`+B(i)+B(m)+B(160)+se(l)+B(S)+B(h.length)+h.map(se).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:e,tx:{to:f,data:R,value:P?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:y.amountOut,minOut:m.toString(),slippageBps:c,maxSlippageBps:Ne,deadline:S.toString()},requires:P?[]:[{step:"approve",token:h[0],spender:f,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 Er=[100,500,3e3,1e4],ct={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},G=t=>BigInt(t).toString(16).padStart(64,"0"),ae=t=>t.slice(2).toLowerCase().padStart(64,"0"),ut=/^0x[0-9a-fA-F]{40}$/,Pe=100;function Sr(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Pe)throw new Error(`slippageBps ${r} exceeds the ${Pe} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(r))/10000n}function Oe(t,e){return(t?.venues||[]).find(r=>r.kind===e)?.address??null}function lt(t){let{chainId:e,wrappedNative:r}=t;async function n({quoter:o,tokenIn:i,tokenOut:l,amountIn:c,fee:d},a){let u=`0x${ct.quoteExactInputSingle}`+ae(i)+ae(l)+G(c)+G(d)+G(0),p=await F(e,"eth_call",[{to:o,data:u},"latest"],a).catch(()=>null),f=p?.result??p;if(!f||f==="0x"||f.length<66)return null;let h=BigInt(`0x${f.slice(2,66)}`);return h>0n?h:null}async function s({quoter:o,tokenIn:i,tokenOut:l,amountIn:c},d){let a=await Promise.all(Er.map(async p=>{let f=await n({quoter:o,tokenIn:i,tokenOut:l,amountIn:c,fee:p},d);return{fee:p,amountOut:f?f.toString():null,out:f}})),u=null;for(let p of a)p.out&&(!u||p.out>u.amountOut)&&(u={fee:p.fee,amountOut:p.out});return{best:u,tried:a.map(({fee:p,amountOut:f})=>({fee:p,amountOut:f}))}}return{async quote({tokenIn:o,tokenOut:i,amountIn:l},c={}){let d=Oe(c.scanner,"quoter");if(!d)return{chainId:e,evidence:g.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let p of[o,i])if(!ut.test(p||""))throw new Error("quote requires valid 20-byte addresses");let{best:a,tried:u}=await s({quoter:d,tokenIn:o,tokenOut:i,amountIn:l},c);return a?{chainId:e,venue:"uniswap-v3",quoter:d,tokenIn:o,tokenOut:i,amountIn:String(l),amountOut:a.amountOut.toString(),fee:a.fee,useNative:!!r&&String(o).toLowerCase()===String(r).toLowerCase(),triedFeeTiers:u,evidence:g.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:e,quoter:d,tokenIn:o,tokenOut:i,triedFeeTiers:u,evidence:g.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:o,amountIn:i,base:l},c={}){let d=Oe(c.scanner,"quoter"),a=(t.stableQuoteAssets||[]).map(N=>String(N).toLowerCase()),u=null;!l&&typeof t.resolveQuoteAsset=="function"&&(u=await t.resolveQuoteAsset(o,c).catch(()=>null));let p=String(o).toLowerCase(),f=String(r||"").toLowerCase();if(f&&p===f)return{chainId:e,token:o,verdict:w.UNKNOWN,evidence:g.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};let h=l||u||(a[0]&&p!==a[0]?a[0]:null)||r;if(h&&p===String(h).toLowerCase())return{chainId:e,token:o,verdict:w.UNKNOWN,evidence:g.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!d||!h)return{chainId:e,token:o,verdict:w.UNKNOWN,evidence:g.UNAVAILABLE,reason:d?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let y=await s({quoter:d,tokenIn:h,tokenOut:o,amountIn:i},c);if(!y.best){let N=a.find(C=>C&&C!==String(h).toLowerCase()&&C!==String(o).toLowerCase());if(N){let C=await s({quoter:d,tokenIn:N,tokenOut:o,amountIn:i},c);if(C.best){let v=await s({quoter:d,tokenIn:o,tokenOut:N,amountIn:C.best.amountOut},c);if(v.best){let T=v.best.amountOut,E=Number(T*10000n/BigInt(i)),L=w.PASS,b="round trip vs dollar book completes with expected fee/impact loss";return E<5e3?(L=w.FAIL,b=`round trip vs dollar book returns only ${(E/100).toFixed(2)}% -- punitive tax or no real liquidity`):E<9e3&&(L=w.CAUTION,b=`round trip vs dollar book returns ${(E/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:N,quoteAsset:N,verdict:L,reason:b,amountIn:String(i),bought:C.best.amountOut.toString(),returned:T.toString(),retentionBps:E,buyFee:C.best.fee,sellFee:v.best.fee,evidence:g.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:e,token:o,verdict:w.FAIL,evidence:g.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let m=await s({quoter:d,tokenIn:o,tokenOut:h,amountIn:y.best.amountOut},c);if(!m.best){let N=a.find(C=>C&&C!==String(h).toLowerCase()&&C!==String(o).toLowerCase());if(N){let C=await s({quoter:d,tokenIn:N,tokenOut:o,amountIn:i},c),v=C.best?await s({quoter:d,tokenIn:o,tokenOut:N,amountIn:C.best.amountOut},c):{best:null};if(C.best&&v.best){let T=v.best.amountOut,E=Number(T*10000n/BigInt(i)),L=w.PASS,b="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return E<5e3?(L=w.FAIL,b=`dollar-book round trip returns only ${(E/100).toFixed(2)}%`):E<9e3&&(L=w.CAUTION,b=`dollar-book round trip returns ${(E/100).toFixed(2)}%`),{chainId:e,venue:"uniswap-v3",token:o,base:N,quoteAsset:N,verdict:L,reason:b,amountIn:String(i),bought:C.best.amountOut.toString(),returned:T.toString(),retentionBps:E,buyFee:C.best.fee,sellFee:v.best.fee,evidence:g.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:e,token:o,verdict:w.FAIL,evidence:g.LIVE,leg:"sell",bought:y.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let S=m.best.amountOut,P=Number(S*10000n/BigInt(i)),R=w.PASS,U="round trip completes with expected fee/impact loss";return P<5e3?(R=w.FAIL,U=`round trip returns only ${(P/100).toFixed(2)}% -- punitive tax or no real liquidity`):P<9e3&&(R=w.CAUTION,U=`round trip returns ${(P/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:h,verdict:R,reason:U,amountIn:String(i),bought:y.best.amountOut.toString(),returned:S.toString(),retentionBps:P,buyFee:y.best.fee,sellFee:m.best.fee,evidence:g.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:i,amountIn:l,recipient:c,slippageBps:d=50,fee:a},u={}){let p=Oe(u.scanner,"router");if(!p)throw new Error(`chain ${e} has no verified V3 router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!ut.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=await this.quote({tokenIn:o,tokenOut:i,amountIn:l},u);if(f.evidence!==g.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let h=a??f.fee,y=Sr(f.amountOut,d);if(y<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let m=!!(u.useNative||f.useNative)&&r&&String(o).toLowerCase()===String(r).toLowerCase(),S=`0x${ct.exactInputSingle}`+ae(o)+ae(i)+G(h)+ae(c)+G(l)+G(y)+G(0);return{unsigned:!0,signedBy:"user-wallet",chainId:e,venue:"uniswap-v3",tx:{to:p,data:S,value:m?String(l):"0x0"},guard:{quotedOut:f.amountOut,minOut:y.toString(),slippageBps:d,maxSlippageBps:Pe,fee:h},requires:m?[]:[{step:"approve",token:o,spender:p,amount:String(l)}],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={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function dt(t){if(!t||t==="0x")return null;try{return BigInt(t)}catch{return null}}function pt(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length>=128){let n=Number(BigInt(`0x${e.slice(64,128)}`));if(n>0&&n<=256&&e.length>=128+n*2){let s=e.slice(128,128+n*2),o=Buffer.from(s,"hex").toString("utf8").replace(/\0+$/,"");if(o)return o}}return Buffer.from(e.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function Ar(t){let{chainId:e}=t;async function r(n,s,o){return F(e,"eth_call",[{to:n,data:s},"latest"],o)}return{async blockNumber(n={}){let s=await Ze(e,n);return{chainId:e,blockNumber:s?.blockNumber??s,evidence:g.LIVE}},async nativeBalance(n,s={}){let o=await et(e,n,s);return{chainId:e,address:n,wei:o?.wei??o?.balance??null,symbol:t.nativeCurrency?.symbol??null,decimals:t.nativeCurrency?.decimals??18,evidence:g.LIVE}},async tokenBalance({token:n,owner:s},o={}){let i=await tt({chainId:e,token:n,owner:s},o);return{chainId:e,token:n,owner:s,raw:i?.balance??i,evidence:g.LIVE}},async resolveToken(n,s={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:e,token:n,evidence:g.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[o,i,l,c]=await Promise.all([r(n,he.decimals,s).catch(()=>null),r(n,he.symbol,s).catch(()=>null),r(n,he.name,s).catch(()=>null),r(n,he.totalSupply,s).catch(()=>null)]),d=dt(o?.result??o),a=d!==null||i?.result||l?.result,u={chainId:e,address:n,decimals:d===null?null:Number(d),symbol:pt(i?.result??i),name:pt(l?.result??l),totalSupply:(dt(c?.result??c)??null)?.toString()??null,evidence:a?g.LIVE:g.UNKNOWN};return a||(u.warning="no ERC-20 metadata returned -- may not be a token contract"),u},async resolvePools(n,s={}){let o=t.dexscreenerSlug;if(!o)return{chainId:e,token:n,pools:[],evidence:g.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await ot(n,s).catch(()=>null),c=(i?.pairs||i?.data?.pairs||[]).filter(a=>String(a.chainId).toLowerCase()===String(o).toLowerCase()).map(a=>({pair:a.pairAddress,dex:a.dexId,base:a.baseToken?.address,quote:a.quoteToken?.address,liquidityUsd:a.liquidity?.usd??null,priceUsd:a.priceUsd??null,volume24hUsd:a.volume?.h24??null,createdAt:a.pairCreatedAt??null})).sort((a,u)=>(u.liquidityUsd??0)-(a.liquidityUsd??0)),d=Ce(n,c,{stables:t.stableQuoteAssets||[],wrappedNative:t.wrappedNative});return{chainId:e,token:n,pools:d,topPool:d[0]||null,quoteAsset:nt(n,d),evidence:d.length?g.LIVE:g.UNKNOWN}},async scanBlocks({fromBlock:n,toBlock:s,address:o,topics:i,chunkSize:l=2e3}={},c={}){if(!Number.isInteger(n)||!Number.isInteger(s))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(s<n)throw new Error("toBlock must be >= fromBlock");let d=[],a=[];for(let p=n;p<=s;p+=l){let f=Math.min(p+l-1,s);a.push([p,f])}let u=await We(a,4,async([p,f])=>{let h={fromBlock:`0x${p.toString(16)}`,toBlock:`0x${f.toString(16)}`};o&&(h.address=o),i&&(h.topics=i);let y=await F(e,"eth_getLogs",[h],c).catch(m=>({error:String(m?.message||m)}));return{start:p,end:f,res:y}});for(let{start:p,end:f,res:h}of u){if(h?.error)return{chainId:e,fromBlock:n,toBlock:s,logs:d,complete:!1,failedAt:[p,f],error:h.error,evidence:g.UNKNOWN};for(let y of h?.result??h??[])d.push(y)}return{chainId:e,fromBlock:n,toBlock:s,logs:d,complete:!0,chunks:a.length,evidence:g.LIVE}},async scoreRisk(n,s={}){let o=[],i=w.PASS,l=a=>{let u={[w.PASS]:0,[w.CAUTION]:1,[w.UNKNOWN]:2,[w.FAIL]:3};u[a]>u[i]&&(i=a)},[c,d]=await Promise.all([this.resolveToken(n,s),this.resolvePools(n,s)]);if(c.evidence!==g.LIVE?(o.push({check:"erc20-metadata",result:w.UNKNOWN,detail:c.warning}),l(w.UNKNOWN)):o.push({check:"erc20-metadata",result:w.PASS,detail:`${c.symbol} / ${c.decimals}d`}),d.evidence===g.UNAVAILABLE)o.push({check:"liquidity",result:w.UNKNOWN,detail:d.reason}),l(w.UNKNOWN);else if(!d.pools.length)o.push({check:"liquidity",result:w.FAIL,detail:"no pool with liquidity found"}),l(w.FAIL);else{let a=d.pools[0],u=a.liquidityUsd??0;u<5e3?(o.push({check:"liquidity",result:w.CAUTION,detail:`top pool only $${u}`}),l(w.CAUTION)):o.push({check:"liquidity",result:w.PASS,detail:`$${u} on ${a.dex}`}),a.createdAt&&Date.now()-a.createdAt<24*3600*1e3&&(o.push({check:"age",result:w.CAUTION,detail:"pool under 24h old"}),l(w.CAUTION))}if(typeof this.sellSimulation=="function"){let a=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},s).catch(u=>({verdict:w.UNKNOWN,reason:String(u?.message||u)}));o.push({check:"sellability",result:a.verdict,detail:a.retentionBps!=null?`round trip returns ${(a.retentionBps/100).toFixed(2)}% -- ${a.reason}`:a.reason}),l(a.verdict)}else o.push({check:"sellability",result:w.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."}),l(w.UNKNOWN);return{chainId:e,token:n,verdict:i,checks:o,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function ft(t){let r={...Ar(t)},n=new Set((t.venues||[]).map(o=>o.kind));t.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,lt({chainId:t.chainId,wrappedNative:t.wrappedNative,stableQuoteAssets:t.stableQuoteAssets||[],resolveQuoteAsset:async(o,i)=>(await r.resolvePools(o,i)).quoteAsset||null})):t.venueKind==="uniswap-v2"&&n.has("router")&&Object.assign(r,it({chainId:t.chainId,wrappedNative:t.wrappedNative}));let s={};for(let[o,i]of Object.entries(r))s[o]=i.bind(r);return{key:t.key,chainId:t.chainId,name:t.name,rpcEnv:t.rpcEnv,nativeCurrency:t.nativeCurrency,explorer:t.explorer,venues:t.venues||[],capabilities:s}}var xr=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",stableQuoteAssets:["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48","0xdAC17F958D2ee523a2206206994597C13D831ec7"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85","0x94b008aA00579c1307B0EF2c499aD98a8ce58e58"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",stableQuoteAssets:["0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d","0x55d398326f99059fF775485246999027B3197955"],venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",stableQuoteAssets:["0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359","0xc2132D05D31c914a87C6611C10748AEb04B58e8F"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",stableQuoteAssets:["0x5fc5360d0400a0fd4f2af552add042d716f1d168"],venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",stableQuoteAssets:["0xaf88d065e77c8cC2239327C5EDb3A432268e5831","0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",stableQuoteAssets:["0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"],venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);function ht(){return xr.map(t=>st(ft(t)))}ht();var[mt,...bt]=process.argv.slice(2),me=bt.includes("--json"),I=bt.filter(t=>t!=="--json");function J(t){t||D("missing <chain>");let e=Te(Number(t));if(e)return e;let r=fe().find(n=>n.key===String(t).toLowerCase());if(r)return r;D(`unknown chain "${t}". Known: ${fe().map(n=>`${n.key}(${n.chainId})`).join(", ")}`)}function D(t){console.error(`error: ${t}`),process.exit(1)}function Q(t){process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
8
|
+
`)}function Cr(t,e){let r=String(e?.message||e);return/rpc|fetch|ECONN|timeout|provider/i.test(r)?`${r}
|
|
9
9
|
|
|
10
10
|
This chain reads its RPC from: ${t.rpcEnv.join(" or ")}
|
|
11
|
-
Set one, e.g.: export ${t.rpcEnv[0]}=https://...`:r}try{switch(
|
|
11
|
+
Set one, e.g.: export ${t.rpcEnv[0]}=https://...`:r}try{switch(mt){case"chains":{let t=at();if(me){Q(t);break}console.log(`${t.chainCount} chains registered
|
|
12
12
|
`);let e=Object.entries(t.chains).map(([n,s])=>({chain:`${s.key} (${n})`,caps:s.supported.length,routing:s.failClosed?"fail-closed (no verified venue)":`${s.venueCount} venue(s)`})),r=Math.max(...e.map(n=>n.chain.length));for(let n of e)console.log(` ${n.chain.padEnd(r)} ${String(n.caps).padStart(2)} caps ${n.routing}`);console.log(`
|
|
13
13
|
Every chain is read/research capable. Routing value requires a verified
|
|
14
|
-
venue -- see CONTRIBUTING.md for the verification rule.`);break}case"head":{let t=J(
|
|
14
|
+
venue -- see CONTRIBUTING.md for the verification rule.`);break}case"head":{let t=J(I[0]);Q(await t.blockNumber());break}case"token":{let t=J(I[0]);I[1]||D("usage: oracle-scan token <chain> <address>"),Q(await t.resolveToken(I[1]));break}case"pools":{let t=J(I[0]);I[1]||D("usage: oracle-scan pools <chain> <address>");let e=await t.resolvePools(I[1]);if(me){Q(e);break}console.log(`evidence: ${e.evidence}`),e.reason&&console.log(`reason: ${e.reason}`);for(let r of e.pools.slice(0,10)){let n=r.liquidityUsd==null?"?":`$${Math.round(r.liquidityUsd).toLocaleString()}`;console.log(` ${r.dex.padEnd(12)} ${n.padStart(14)} ${r.pair}`)}e.pools.length||console.log(" (no pools with liquidity found)");break}case"risk":{let t=J(I[0]);I[1]||D("usage: oracle-scan risk <chain> <address>");let e=await t.scoreRisk(I[1]);if(me){Q(e);break}console.log(`verdict: ${e.verdict}
|
|
15
15
|
`);for(let r of e.checks)console.log(` ${r.result.padEnd(8)} ${r.check.padEnd(16)} ${r.detail??""}`);console.log(`
|
|
16
|
-
${e.note}`);break}case"quote":{let t=J(
|
|
17
|
-
Add a venue with recorded provenance -- see docs/adding-a-chain.md.`);let e=
|
|
18
|
-
Without it, treat every token on this chain as unproven for exit.`);let e=
|
|
16
|
+
${e.note}`);break}case"quote":{let t=J(I[0]);(!I[1]||!I[2])&&D("usage: oracle-scan quote <chain> <tokenIn> <tokenOut> [amountIn]"),t.supports("quote")||D(`${t.key} has no verified router, so quoting stays fail-closed.
|
|
17
|
+
Add a venue with recorded provenance -- see docs/adding-a-chain.md.`);let e=I[3]||(10n**18n).toString();Q(await t.quote({tokenIn:I[1],tokenOut:I[2],amountIn:e}));break}case"sell":{let t=J(I[0]);I[1]||D("usage: oracle-scan sell <chain> <token> [amountIn]"),t.supports("sellSimulation")||D(`${t.key} has no verified router, so sell simulation is unavailable.
|
|
18
|
+
Without it, treat every token on this chain as unproven for exit.`);let e=I[2]||(10n**16n).toString(),r=await t.sellSimulation({token:I[1],amountIn:e});if(me){Q(r);break}console.log(`verdict: ${r.verdict}`),console.log(`reason: ${r.reason??""}`),r.retentionBps!=null&&console.log(`retention: ${(r.retentionBps/100).toFixed(2)}%`),r.leg&&console.log(`failed at: ${r.leg} leg`),r.note&&console.log(`
|
|
19
19
|
${r.note}`);break}default:console.log(["oracle-scan -- chain scanner CLI",""," oracle-scan chains coverage matrix"," oracle-scan head <chain> current block"," oracle-scan token <chain> <address> ERC-20 identity"," oracle-scan pools <chain> <address> pools by liquidity"," oracle-scan risk <chain> <address> structural risk checks"," oracle-scan quote <chain> <tIn> <tOut> [amt] live exact-input quote"," oracle-scan sell <chain> <token> [amt] round-trip: can you exit?",""," <chain> is an id (8453) or key (base). --json for machine output."," quote/sell need a chain with a verified router (see: oracle-scan chains)."].join(`
|
|
20
|
-
`)),process.exit(
|
|
20
|
+
`)),process.exit(mt?1:0)}}catch(t){let e=I[0]?Te(Number(I[0]))||fe().find(r=>r.key===I[0]):null;D(e?Cr(e,t):String(t?.message||t))}
|
package/dist/bin/oracle.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{realpathSync as
|
|
2
|
+
import{realpathSync as W}from"node:fs";import{fileURLToPath as xe}from"node:url";import y from"node:fs";import g from"node:path";import{pathToFileURL as H}from"node:url";import m from"node:fs";import J from"node:os";import c from"node:path";import{fileURLToPath as z}from"node:url";var Y=c.dirname(z(import.meta.url)),f=c.resolve(Y,"../..");function u(){return process.env.ORACLE_FAKE_HOME||J.homedir()}function v(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function h(){return v()?process.env.ORACLE_CONFIG_DIR||c.join(u(),".config","oracle"):c.join(u(),".config","oracle")}function X(){return c.join(h(),"exec.env")}function S(){return c.join(h(),"desk.json")}function O(){return c.join(h(),"env")}function p({force:e=!1}={}){if(p._done&&!e)return p._result||null;p._done=!0;let r={},o=(n,t)=>{if(t==null)return;let a=String(t).trim();a&&(process.env[n]!=null&&String(process.env[n]).trim()!==""||(process.env[n]=a,r[n]=a))};try{let n=O();if(m.existsSync(n))for(let t of m.readFileSync(n,"utf8").split(/\r?\n/)){let a=t.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!a||a[2].startsWith("#"))continue;let i=a[2];(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),o(a[1],i)}}catch{}try{let n=S();if(m.existsSync(n)){let t=JSON.parse(m.readFileSync(n,"utf8"));t&&typeof t=="object"&&(o("ORACLE_DESK_URL",t.deskUrl||t.dataUrl||t.url),o("ORACLE_DATA_URL",t.dataUrl||t.deskUrl||t.url),o("ORACLE_API_URL",t.apiUrl||t.dataUrl||t.deskUrl),o("ORACLE_PUBLIC_URL",t.publicUrl||t.deskUrl||t.dataUrl),o("ORACLE_EXEC_URL",t.execUrl),o("MAD_DESK_URL",t.deskUrl||t.dataUrl))}}catch{}let s=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return s&&(o("ORACLE_DESK_URL",s),o("ORACLE_DATA_URL",s),o("ORACLE_API_URL",s),o("ORACLE_PUBLIC_URL",s),o("MAD_DESK_URL",s)),p._result=Object.keys(r).length?r:null,p._result}try{p()}catch{}function Z(){return process.env.HERMES_HOME?c.resolve(process.env.HERMES_HOME):c.join(u(),".hermes")}function Q(){return c.join(u(),".claude.json")}function ee(e=process.cwd()){return c.join(e,".mcp.json")}function te(){return process.platform==="darwin"?c.join(u(),"Library","Application Support","Claude","claude_desktop_config.json"):c.join(u(),".config","Claude","claude_desktop_config.json")}function re(){return c.join(u(),".codex","config.toml")}function k(){return c.join(h(),"connectors")}function oe(){return c.join(k(),"chatgpt-openapi.json")}function ne(){return c.join(h(),"active-chain.json")}function A(e,r=f){let o=[c.join(r,"bin",e),c.join(r,"dist","bin",e),c.join(r,"..","bin",e)];return o.find(s=>m.existsSync(s))||o[0]}function se(e){return m.mkdirSync(e,{recursive:!0}),e}var L={homeDir:u,isPublicDesktop:v,oracleConfigDir:h,oracleExecEnvPath:X,oracleDeskJsonPath:S,oracleEnvFilePath:O,loadDeskRouting:p,hermesRoot:Z,activeChainPath:ne,claudeCodeUserConfigPath:Q,claudeCodeProjectMcpPath:ee,claudeDesktopConfigPath:te,codexConfigPath:re,chatgptConnectorDir:k,chatgptOpenApiPath:oe,packageBin:A,ensureDir:se,PACKAGE_ROOT:f};import{execFile as ae}from"node:child_process";import{existsSync as je,mkdirSync as De,readFileSync as ie,realpathSync as Ue,writeFileSync as He}from"node:fs";import b from"node:path";import{promisify as ce}from"node:util";var $e=ce(ae);var Me=1440*60*1e3;function T(e,r){let o=t=>String(t).replace(/^v/,"").split("-")[0].split(".").map(a=>Number.parseInt(a,10)||0),s=o(e),n=o(r);for(let t=0;t<Math.max(s.length,n.length);t+=1){let a=s[t]??0,i=n[t]??0;if(a>i)return 1;if(a<i)return-1}return 0}function le(e){let r=e?.stateDir||b.join(process.env.HOME||".",".oracle");return b.join(r,"update-check.json")}function j(e){try{return JSON.parse(ie(le(e),"utf8"))}catch{return null}}var ue="\u25C7 ORACLE // self-custody multichain agent control plane",de=`START
|
|
3
3
|
oracle open the native Oracle chat (TTY)
|
|
4
4
|
oracle chat open chat explicitly
|
|
5
5
|
oracle setup connect a model and optional messaging
|
|
@@ -63,16 +63,16 @@ BOUNDARY
|
|
|
63
63
|
MEV observe is read-only. Flash-loan execute needs ORACLE_MEV_EXECUTE_ENABLED=1
|
|
64
64
|
and literal --execute. There is no autonomous MEV loop.
|
|
65
65
|
Use oracle <command> --help for command details.
|
|
66
|
-
`;function
|
|
67
|
-
Update available: ${e} \u2192 ${
|
|
68
|
-
`}function
|
|
66
|
+
`;function P(){try{return JSON.parse(y.readFileSync(g.join(f,"package.json"),"utf8")).version||"0.0.0"}catch{return"0.0.0"}}function I(){let e=g.join(f,"src","cli","commands");return y.existsSync(e)?e:g.join(f,"dist","cli","commands")}var $=Object.freeze({clients:"harness"});function M(){let e=I();return y.existsSync(e)?new Map(y.readdirSync(e).filter(r=>r.endsWith(".mjs")).map(r=>[r.replace(/\.mjs$/,""),g.join(e,r)])):new Map}function pe(){return[...new Set([...M().keys(),...Object.keys($)])].sort()}async function w(e){let r=$[e]||e,o=M().get(r);if(!o)return null;try{let n=(await import(H(o).href)).default;if(!n||typeof n!="object"||typeof n.run!="function")return null;let t=n.name||r,a={...n,name:t,__file:o};return e!==r?{...a,name:e,aliasFor:t}:a}catch(s){return process.env.ORACLE_CLI_DEBUG&&console.error(`oracle: failed loading command ${r}: ${s.message}`),null}}async function _(){let e=I(),r=new Map;if(!y.existsSync(e))return r;let o=y.readdirSync(e).filter(s=>s.endsWith(".mjs")).sort();for(let s of o){let n=g.join(e,s);try{let a=(await import(H(n).href+`?t=${Date.now()}`)).default;if(!a||typeof a!="object"||typeof a.run!="function")continue;let i=a.name||s.replace(/\.mjs$/,""),l={...a,name:i,__file:n};r.set(i,l);for(let d of Array.isArray(a.aliases)?a.aliases:[])r.set(d,{...l,name:d,aliasFor:i})}catch(t){process.env.ORACLE_CLI_DEBUG&&console.error(`oracle: failed loading command ${s}: ${t.message}`)}}return r}function fe(e,r=j()){return!r?.latest||!e||T(r.latest,e)<=0?"":`
|
|
67
|
+
Update available: ${e} \u2192 ${r.latest}. Run 'oracle update'.
|
|
68
|
+
`}function x(e,r){let o=[];o.push(`${ue} (v${e})`),o.push(""),o.push(de.trimEnd());let s=[];for(let n of r.values()){if(["help","version"].includes(n.name))continue;!new Set(["init","doctor","chat","model","auth","chain","setup","data","data-mcp","scan","route","prepare","swap","farm","airdrop","follow","equities","strategy","shadow","mint","mev","snipe","public","mcp","plugins","harness","clients","upgrade","bootstrap","eval","fees","sign","signer","project","context","lifecycle","x402"]).has(n.name)&&n.summary&&s.push(` oracle ${n.name.padEnd(20)} ${n.summary}`)}return s.length&&(o.push(""),o.push("ADDITIONAL"),o.push(...s)),o.join(`
|
|
69
69
|
`)+`
|
|
70
|
-
`+
|
|
70
|
+
`+fe(e)}function D(e,r){let o=r?[...r.keys()].sort():pe(),s=o.length?o.join(", "):"(none loaded yet)";return`oracle: unknown command '${e}'. Known: ${s}
|
|
71
71
|
Try: oracle --help
|
|
72
|
-
`}function
|
|
73
|
-
`),
|
|
74
|
-
`),0):(process.stderr.write(
|
|
75
|
-
`),
|
|
76
|
-
`),0;try{let
|
|
77
|
-
`),1}}return process.stderr.write(
|
|
78
|
-
`),0}function
|
|
72
|
+
`}function R(e){return{argv:e,root:f,bin:A,paths:L}}async function F(e=[]){let r=P();if(e.includes("--version")||e.includes("-V"))return U();if(e[0]==="--help"||e[0]==="-h"){let t=await _();return process.stdout.write(x(r,t)),0}if(e.length===0){if(me(e)){let a=await w("chat");if(a)return a.run(R([]))}let t=await _();return process.stdout.write(x(r,t)),0}if(he(e[0])){let t=await w("chat");if(t)return t.run(R(e))}let o=e[0],s=e.slice(1);if(o==="version")return U();if(o==="help"){if(s[0]){let a=await w(s[0]);return a?(process.stdout.write((a.usage||`oracle ${a.name}`)+`
|
|
73
|
+
`),a.summary&&process.stdout.write(a.summary+`
|
|
74
|
+
`),0):(process.stderr.write(D(s[0])),1)}let t=await _();return process.stdout.write(x(r,t)),0}let n=await w(o);if(n){if(s[0]==="--help"||s[0]==="-h")return process.stdout.write((n.usage||`oracle ${n.name}`)+`
|
|
75
|
+
`),n.summary&&process.stdout.write(n.summary+`
|
|
76
|
+
`),0;try{let t=await n.run(R(s));return typeof t=="number"?t:0}catch(t){return process.stderr.write(`oracle ${o}: ${t?.message||t}
|
|
77
|
+
`),1}}return process.stderr.write(D(o)),1}async function U(){let e=P();return process.stdout.write(`oracle ${e}
|
|
78
|
+
`),0}function me(e=[],r={stdin:process.stdin,stdout:process.stdout}){return e.length!==0?!1:process.env.ORACLE_FORCE_CHAT==="1"?!0:r.stdin?.isTTY===!0&&r.stdout?.isTTY===!0}function he(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||""))}import q from"node:https";import{X509Certificate as B}from"node:crypto";import{checkServerIdentity as ye}from"node:tls";import{Readable as N}from"node:stream";function K(e){let r=new URL(e);if(r.protocol!=="https:"||r.hostname!=="127.0.0.1"||!r.port||r.username||r.password)throw new Error("Hosted transport requires authenticated loopback HTTPS");return r}function ge(e){let r=new B(e).raw;return new q.Agent({keepAlive:!1,maxCachedSessions:0,ca:e,rejectUnauthorized:!0,minVersion:"TLSv1.3",checkServerIdentity(o,s){let n=ye(o,s);if(n)return n;if(!s.raw?.equals(r))return new Error("Hosted child identity mismatch")}})}function Ee(e,r,o,s){let n=K(e),t=ge(r),a=q.request(n,{agent:t,method:o.method,headers:o.headers,signal:o.signal,servername:""},s);return a.once("close",()=>t.destroy()),a}function V(e){return new B(e),async(r,o={})=>{let s=new Request(r,o);return K(s.url),new Promise((n,t)=>{let a=Object.fromEntries(s.headers);a["accept-encoding"]="identity";let i=Ee(s.url,e,{method:s.method,headers:a,signal:s.signal},l=>{if(l.statusCode>=300&&l.statusCode<400&&l.headers.location){l.destroy(),t(new Error("Hosted redirects are refused"));return}let d=new Headers;for(let E=0;E<l.rawHeaders.length;E+=2)d.append(l.rawHeaders[E],l.rawHeaders[E+1]);let C=s.method==="HEAD"||[204,205,304].includes(l.statusCode);C&&l.resume(),n(new Response(C?null:N.toWeb(l),{status:l.statusCode,headers:d}))});if(i.once("error",t),s.body){let l=N.fromWeb(s.body);l.once("error",d=>i.destroy(d)),i.once("close",()=>l.destroy()),l.pipe(i)}else i.end()})}}var we="x-oracle-sidecar-token",Ae=e=>typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e);function _e(e,r=process.env){if(r.ORACLE_HOSTED_SIDECAR!=="1")return e;if(!Ae(r.ORACLE_HOSTED_SIDECAR_TOKEN))throw new Error("Hosted service authentication is missing");let o=new Map([[r.ORACLE_DATA_URL,r.ORACLE_HOSTED_DATA_CERT],[r.ORACLE_PUBLIC_URL,r.ORACLE_HOSTED_PUBLIC_CERT]].map(([s,n])=>{let t=new URL(s);if(t.origin!==s||t.protocol!=="https:"||t.hostname!=="127.0.0.1"||!t.port||t.username||t.password)throw new Error("Hosted services must use exact loopback origins");return[t.origin,V(n)]}));return function(n,t={}){let a=new URL(n instanceof Request?n.url:n);if(!o.has(a.origin))return e(n,t);if(a.username||a.password)throw new Error("Hosted service URL contains credentials");let i=new Headers(t.headers??(n instanceof Request?n.headers:void 0));return i.set(we,r.ORACLE_HOSTED_SIDECAR_TOKEN),o.get(a.origin)(n,{...t,headers:i,redirect:"error"})}}function G(e=process.env){if(e.ORACLE_HOSTED_SIDECAR!=="1")return;let r=Symbol.for("oracle.hosted.sidecar-fetch");globalThis[r]||(globalThis.fetch=_e(globalThis.fetch.bind(globalThis),e),globalThis[r]=!0)}var nt=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 Re(){if(!process.argv[1])return!1;try{return W(xe(import.meta.url))===W(process.argv[1])}catch{return!1}}async function Ce(e=process.argv.slice(2)){return G(),F(e)}if(Re()){let e=await Ce();process.exit(typeof e=="number"?e:0)}export{nt as COMMANDS,Ce as main};
|