@oracle-agent/oracle 0.35.44 → 0.35.45
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 +24 -24
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/bin/desk-server.mjs +26 -26
- package/dist/bin/oracle-data-mcp.mjs +14 -14
- package/dist/bin/oracle-gateway.mjs +47 -47
- package/dist/bin/oracle-investigate.mjs +4 -4
- package/dist/bin/oracle-launch-radar-shadow.mjs +5 -5
- package/dist/bin/oracle-mev-arb-shadow.mjs +5 -5
- package/dist/bin/oracle-mev-shadow.mjs +5 -5
- package/dist/bin/oracle-public-server.mjs +5 -5
- package/dist/bin/oracle-route.mjs +23 -23
- package/dist/bin/oracle-scan.mjs +6 -6
- package/dist/bin/oracle.mjs +1 -0
- package/dist/cli/commands/account.mjs +39 -0
- package/dist/cli/commands/agent-session.mjs +23 -23
- package/dist/cli/commands/airdrop.mjs +7 -7
- package/dist/cli/commands/chat.mjs +198 -198
- package/dist/cli/commands/data.mjs +29 -29
- package/dist/cli/commands/doctor.mjs +7 -7
- package/dist/cli/commands/eval.mjs +123 -123
- package/dist/cli/commands/farm.mjs +16 -16
- package/dist/cli/commands/follow.mjs +36 -36
- package/dist/cli/commands/mint.mjs +10 -10
- package/dist/cli/commands/model.mjs +205 -205
- package/dist/cli/commands/quickstart.mjs +6 -6
- package/dist/cli/commands/receipt.mjs +11 -11
- package/dist/cli/commands/resolve.mjs +9 -9
- package/dist/cli/commands/session-vault.mjs +5 -5
- package/dist/cli/commands/sign.mjs +12 -12
- package/dist/cli/commands/signer.mjs +25 -25
- package/dist/cli/commands/snipe.mjs +7 -7
- package/dist/cli/commands/strategy.mjs +5 -5
- package/dist/cli/commands/swap.mjs +14 -14
- package/dist/cli/commands/venues.mjs +2 -2
- package/dist/data/desk-data.mjs +24 -24
- 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 +7 -3
- package/dist/local-signer/runtime.mjs +22 -22
- 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 +85 -85
- package/package.json +1 -1
- 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/public/oracle-splash/download/index.html +3 -3
- package/public/oracle-splash/downloads/index.html +1 -1
- package/public/oracle-splash/index.html +6 -6
- package/server.json +2 -2
package/dist/bin/oracle-scan.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
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}
|
|
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 p=a.split(":"),h=p.at(-1);if(h?.includes(".")){let f=h.split(".").map(Number);if(f.length!==4||f.some(d=>!Number.isInteger(d)||d<0||d>255))return null;p.splice(p.length-1,1,(f[0]<<8|f[1]).toString(16),(f[2]<<8|f[3]).toString(16))}return p.some(f=>!/^[0-9a-f]{1,4}$/.test(f))?null:p.map(f=>Number.parseInt(f,16))},[n,s]=e.split("::"),o=r(n),i=r(s);if(!o||!i)return null;let u=e.includes("::"),c=8-o.length-i.length;if(!u&&c!==0||u&&c<1)return null;let l=[...o,...Array(Math.max(0,c)).fill(0),...i];return l.length!==8?null:Uint8Array.from(l.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 ge(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)?ge([...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&&!ge(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:e,host:r,isLiteralIp:n!==0}}async function we(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;if(process.env.ORACLE_HOSTED_EGRESS_PROXY)return{ok:!0,url:r.url,addresses:[]};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=>!ge(s.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}function kt(t=process.env){let e=t.ORACLE_HOSTED_EGRESS_PROXY||"";if(!e)return null;let r;try{r=new URL(e)}catch{throw new Error("egress-guard: ORACLE_HOSTED_EGRESS_PROXY is not a URL")}if(r.protocol!=="http:"||!["127.0.0.1","::1","localhost","[::1]"].includes(r.hostname)||!r.port||r.username||r.password)throw new Error("egress-guard: egress proxy must be an exact loopback http origin");let n=t.ORACLE_HOSTED_EGRESS_TOKEN||"";if(!/^[A-Za-z0-9_-]{43}$/.test(n))throw new Error("egress-guard: egress proxy token is missing");return{uri:r.origin,token:n}}async function ve({requireUndici:t=!1,importUndici:e=()=>import("undici")}={}){let r,n,s;try{s=await e(),r=s.Agent,n=s.fetch}catch(f){if(t)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${f?.message||f}`);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 o=f=>String(f).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),i=new Map,u=f=>(Array.isArray(f)?f:[f]).map(d=>typeof d=="string"?{address:d}:d).filter(d=>d&&d.address).map(d=>({address:d.address,family:d.family||(W.isIPv6(d.address)?6:4)})),c=(f,d,m)=>{i.set(o(f),u(typeof d=="string"?[{address:d,family:m}]:d))},l=f=>{let d=o(f);if(W.isIP(d))return[{address:d,family:W.isIPv6(d)?6:4}];let m=i.get(d);if(!m||!m.length)throw new Error(`refused: unpinned host ${f} during pinned fetch`);return m},a=kt(),p=a&&typeof s.ProxyAgent=="function"?new s.ProxyAgent({uri:a.uri,token:`Bearer ${a.token}`,connectTimeout:1e4}):new r({connect:{lookup(f,d,m){let b;try{b=l(f)}catch(E){return m(E)}return d?.all?m(null,b):m(null,b[0].address,b[0].family)}}}),h=Ot((f,d={})=>n(f,{...d,dispatcher:p}),c);return{dispatcher:p,fetch:h,pin:c,resolve:l,async close(){try{await p.destroy()}catch{}}}}var Ee=Symbol.for("oracle.egressGuard.pinCapableFetch");function Ot(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 Pt=new Set([408,425,429,500,502,503,504]),$e=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Rt=2,Fe=4e3,_t=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Lt=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Ut=AbortSignal.prototype.throwIfAborted,qt=EventTarget.prototype.addEventListener,De=EventTarget.prototype.removeEventListener,je=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,te=t=>t?_t.call(t):!1,Bt=t=>t?Lt.call(t):void 0,$t=new Set([301,302,303,307,308]),de=3,qr=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 Ft(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 Dt(t){let e=[],r=0,n=0,s=0,o=0,i=new WeakSet,u=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)},l=(a,p)=>{if(n+=1,n>H.nodes)throw k("node limit exceeded");if(p>H.depth)throw k("depth limit exceeded");if(a===null){u("null");return}if(typeof a=="string"){u(c(a));return}if(typeof a=="boolean"){u(a?"true":"false");return}if(typeof a=="number"){if(!Number.isFinite(a))throw k("non-finite number");u(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(Ft(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 d=Object.getPrototypeOf(a),m=0;for(;d!==null;){if(M.isProxy(d))throw k("proxy array prototype");if(m+=1,m>H.depth)throw k("array prototype depth limit exceeded");d=Object.getPrototypeOf(d)}if(a.length>H.arrayLength)throw k("array length limit exceeded");for(let E=0;E<a.length;E+=1){let P=Object.getOwnPropertyDescriptor(a,String(E));if(!P||!Object.hasOwn(P,"value")||P.enumerable!==!0)throw k("array entries must be dense enumerable own data")}let b=0;for(let E in a){if(o+=1,o>H.fields)throw k("enumeration limit exceeded");if(Object.hasOwn(a,E)&&(b+=1,b>a.length))throw k("named array fields are unsupported")}if(b!==a.length)throw k("array entries must be dense enumerable own data");u("[");for(let E=0;E<a.length;E+=1)E&&u(","),l(Object.getOwnPropertyDescriptor(a,String(E)).value,p+1);u("]");return}let h=Object.getPrototypeOf(a);if(h!==Object.prototype&&h!==null)throw k("non-plain object");let f=[];for(let d in a){if(o+=1,o>H.fields)throw k("enumeration limit exceeded");if(!Object.hasOwn(a,d))continue;if(s+=1,s>H.fields)throw k("field limit exceeded");let m=Object.getOwnPropertyDescriptor(a,d);if(!m||!Object.hasOwn(m,"value")||m.enumerable!==!0)throw k("object fields must be enumerable own data");f.push([d,m.value])}u("{");for(let d=0;d<f.length;d+=1)d&&u(","),u(c(f[d][0])),u(":"),l(f[d][1],p+1);u("}")}finally{i.delete(a)}};return l(t,0),e.join("")}function jt(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 Ht(){return Object.assign(Object.create(null),{Accept:"application/json"})}function Mt(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 Vt(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 zt=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),Wt=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?zt.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"&&Wt.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function Kt(t,e,r,n={},s=null){let o=Nt("sha256"),i=(c,l)=>{let a=String(l);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,l)=>({name:c.toLowerCase(),order:l,value:String(r[c])})).sort((c,l)=>c.name.localeCompare(l.name)||c.order-l.order).forEach((c,l)=>{i(`header-name-${l}`,c.name),i(`header-value-${l}`,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 Gt(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 Qt=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 Yt(t){return t?t.byteLength??t.length??0:0}async function Jt(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 p=await t.text(),h=Buffer.byteLength(p,"utf8");if(h>e){if(!n)throw xe(r,`body ${h} bytes`,e);return Buffer.from(p,"utf8").subarray(0,e).toString("utf8")}return p}let u=[],c=0,l=!1;try{for(;;){let{value:p,done:h}=await i.read();if(h)break;if(p&&(u.push(Buffer.from(p)),c+=Yt(p),c>e)){l=!0;break}}}finally{if(l)try{await i.cancel()}catch{}try{i.releaseLock?.()}catch{}}if(l&&(typeof s=="function"&&s(),!n))throw xe(r,`streamed ${c} bytes`,e);let a=Buffer.concat(u);return(l?a.subarray(0,e):a).toString("utf8")}function Xt(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Zt(t,{fetchImpl:e,method:r,headers:n,body:s,timeoutMs:o,lookupFn:i,realFetch:u,untrustedUrl:c=!1,maxResponseBytes:l=null,sameOriginRedirectsOnly:a=!1,importUndici:p,validateResponse:h,signal:f,redirectPolicy:d="follow",maxRedirects:m=de}){let b=null,E=e,P=i?{lookupFn:i}:{};if(c&&!u&&!Se(E))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),O=f?je?je([f,R.signal]):f:R.signal,C=async(v,{status:T=null}={})=>{let S=await we(v,P);if(!S.ok)throw V(T==null?`HTTP refused ${v}: ${S.error}`:`HTTP redirect to ${v} ${S.error}`,T==null?{}:{status:T});let _=new URL(v).hostname;if(u){if(b&&(await b.close(),b=null),!b)try{b=await ve({requireUndici:!0,...p?{importUndici:p}:{}})}catch(y){throw V(T==null?`HTTP refused ${v}: ${y?.message||y}`:`HTTP redirect to ${v} refused: ${y?.message||y}`,T==null?{}:{status:T})}b.pin(_,S.addresses),E=b.fetch}else Be(E,_,S.addresses);return S};try{let v=String(t),T=Object.assign(Object.create(null),n||{});c&&await C(v);for(let S=0;S<=m;S+=1){let _=Object.assign(Object.create(null),{method:r,headers:T,body:s,signal:O,redirect:"manual",dispatcher:void 0}),y=await E(v,_);if((d==="error"||m===0)&&y.status>=300&&y.status<400)throw K(y),V(`HTTP ${y.status} ${r} redirect refused`,{status:y.status,redirectRefused:!0});if($t.has(y.status)){let q=a===!0&&r==="POST"&&[307,308].includes(y.status)&&ze(r,s);if(r!=="GET"&&r!=="HEAD"&&!q){K(y);let N=new Error(`HTTP ${y.status} ${r} ${v} redirected non-idempotent request`);throw N.status=y.status,N}if(S===m)throw K(y),V(`HTTP ${y.status} ${r} redirect budget exhausted`,{status:y.status,redirectRefused:!0});let Re=y.headers?.get?.("location"),$;try{$=Mt(Re,v)}catch(N){throw K(y),N}let z=!Vt($,v);if(K(y),z&&r==="POST"){let N=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw N.status=y.status,N}if(z&&a){let N=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw N.status=y.status,N.retryable=!1,N}if(z&&(T=Ht(T)),c)await C($,{status:y.status});else if(z){let N=await we($,P);if(!N.ok){let x=new Error(`HTTP redirect from ${v} ${N.error}`);throw x.status=y.status,x.retryable=!1,x}u&&N.addresses?.length&&(b||(b=await ve(p?{importUndici:p}:{})),b&&(b.pin(new URL($).hostname,N.addresses),E=b.fetch))}v=$;continue}if(typeof h=="function")try{await h(y,{url:v})}catch(q){throw K(y),V(q?.message||String(q))}let L=await Jt(y,l,{url:v,onOversize:()=>R.abort()}),X=Xt(L);if(!y.ok){let q=new Error(`HTTP ${y.status} ${r} ${v}`);throw q.status=y.status,q.retryAfter=y.headers?.get?.("retry-after")??null,q.body=X??L.slice(0,300),q}return X??L}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,S=T?Object.getOwnPropertyDescriptor(T,"oversize"):null;if(!(S&&Object.hasOwn(S,"value")&&S.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 y=new Error("HTTP request timed out");throw Object.defineProperties(y,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),y}}throw v}finally{clearTimeout(U),b&&await b.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 u=n("redirectPolicy");if(u!==void 0&&u!=="follow"&&u!=="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(u==="error"&&c!==void 0&&c!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let l=u??"follow",a=l==="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 p=n("maxResponseBytes");if(p!==void 0&&(!Number.isInteger(p)||p<1||p>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let h=n("signal");if(h!==void 0){if(M.isProxy(h)||!(h instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{te(h)}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"),d=f||globalThis.fetch;if(typeof d!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let m=o??12e3,b=(s||"GET").toUpperCase(),E=n("headers"),P=jt(E),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=Dt(U));let O=i??Rt,C=n("lookupFn"),v=!f,T=n("untrustedUrl")===!0,S=n("sameOriginRedirectsOnly")===!0,_=n("importUndici"),y=n("validateResponse"),L=h,X=p??null,q=async()=>{let x;for(let A=0;A<=O;A++){L&&Ut.call(L);let _e=ce("http");try{let j=await Zt(t,{fetchImpl:d,method:b,headers:R,body:U,timeoutMs:m,lookupFn:C,realFetch:v,untrustedUrl:T,maxResponseBytes:X,sameOriginRedirectsOnly:S,importUndici:_,validateResponse:y,signal:L,redirectPolicy:l,maxRedirects:a});return _e?.("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");_e?.("failed",ie);let yt=Y("oracleTimeout")===!0||Y("name")==="AbortError"||Y("name")==="TimeoutError"||te(L),gt=new Set([408,425,429]),wt=Y("retryable")===!1?!1:ie!=null?gt.has(ie)||Pt.has(ie)&&$e.has(b):!yt&&$e.has(b);if(A===O||!wt)throw j;let Le=Gt(A,Y("retryAfter")),vt=ce("retry"),Ue=!1;try{L?await new Promise((be,Z)=>{let qe,ee=()=>{clearTimeout(qe),De.call(L,"abort",ee),Z(Bt(L)||new DOMException("Aborted","AbortError"))};if(te(L)){ee();return}qe=setTimeout(()=>{De.call(L,"abort",ee),be()},Le),qt.call(L,"abort",ee,{once:!0}),te(L)&&ee()}):await Qt(Le),Ue=!0}finally{vt?.(Ue?"succeeded":"failed")}}}throw x};if(!(n("dedupe")!==!1&&!L&&ze(b,U)))return q();let $=Kt(b,t,R,{untrustedUrl:T,maxResponseBytes:X,sameOriginRedirectsOnly:S,redirectPolicy:l,maxRedirects:a,timeoutMs:m,retries:O,fetchImpl:le(d),realFetch:v,lookupFn:le(C),importUndici:le(_),validateResponse:le(y)},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 N=q().finally(()=>Ae.delete($));return Ae.set($,N),N}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 u=i++;o[u]=await r(n[u],u)}})),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}},er=new Map(Object.values(Ke).map(t=>[t.chainId,t]));function Ge(t){return er.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 tr,getAddress as rr}from"ethers";var Ye=new tr(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Je(t,e){try{return rr(t).toLowerCase()}catch{throw new Error(`${e} must be a valid EVM address`)}}var nr={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 or(t,{rpcUrl:e,env:r=process.env}={}){if(e)return e;let n=Qe(t,r);return n||nr[Number(t)]||null}var sr=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function ar(t){let e=String(t||""),r=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!sr.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 ir(t){let e=new Error(t?.message||JSON.stringify(t));return e.code=t?.code,e}function cr(t){if(t?.error)throw ir(t.error);return t?.result}function ur(t,e,r){return`${t}
|
|
4
4
|
${e}
|
|
5
|
-
${JSON.stringify(r??[])}`}async function
|
|
5
|
+
${JSON.stringify(r??[])}`}async function lr(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=ar(s),i=or(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?ur(i,s,r):null;if(c&&re.has(c))return re.get(c);let l=(async()=>{let a=await lr(i,{jsonrpc:"2.0",id:1,method:e,params:r},n),p=cr(a);return o==="eth_chainid"&&typeof p=="string"&&Xe.set(i,p),p})();return c&&(re.set(c,l),l.finally(()=>{re.get(c)===l&&re.delete(c)}).catch(()=>{})),l}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),u=Ye.decodeFunctionResult("balanceOf",i),c=BigInt(u[0]);return{chainId:r,token:n,account:s,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:t.blockTag||"latest"}}var dr=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(),u=(e||[]).map((c,l)=>{let a=rt(s,c),p=String(a.address||"").toLowerCase(),h=String(a.symbol||"").toLowerCase(),f=Number(c.liquidityUsd??c.liquidity?.usd),d=Number.isFinite(f)?f:0,m=String(c.dex||c.dexId||"").toLowerCase(),b=0;return o.has(p)||dr.has(h)?b=300:i&&p===i&&(b=100),m.includes("v4")?b+=20:m.includes("v3")?b+=10:(m.includes("v2")||m.includes("raydium")||m.includes("orca")||m.includes("meteora"))&&(b+=8),{pool:c,score:b*1e12+d,index:l,otherAddr:p,liquidityUsd:d}});return u.sort((c,l)=>l.score-c.score||c.index-l.index),u.map(c=>c.pool)}function nt(t,e=[]){let r=Array.isArray(e)?e:[];return r.length&&rt(t,r[0]).address||null}var pr="https://api.dexscreener.com",Kr=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function fr(t={}){return(t.baseUrl||process.env.DEXSCREENER_API_URL||pr).replace(/\/$/,"")}function hr(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 mr(t,e){return pe(`${fr(e)}${t}`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}async function ot(t,e={}){return mr(`/latest/dex/tokens/${hr(t,"tokenAddress")}`,e)}var ne=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),w=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),g=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),br=/^0x[0-9a-fA-F]{40}$/;function yr(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}br.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 gr(t){let{ok:e,errors:r,warnings:n}=yr(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"),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
|
|
7
|
+
- `)}`);let s=t.capabilities||{},o=ne.filter(u=>typeof s[u]=="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(u=>({...u})),warnings:n,capabilities(){return{chainId:t.chainId,key:t.key,supported:[...o],unsupported:ne.filter(u=>!o.includes(u))}},supports(u){return o.includes(u)}};for(let u of ne)o.includes(u)?i[u]=async(...c)=>s[u](...c,{scanner:i}):i[u]=async()=>{throw new Error(`${t.key} (chain ${t.chainId}) does not implement "${u}". Supported: ${o.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(i)}var oe=new Map;function st(t){let e=gr(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 vr(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 Oe=100;function Er(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 it(t){let{chainId:e,wrappedNative:r}=t;async function n(s,o,i,u){let c=await F(e,"eth_call",[{to:s,data:wr(o,i)},"latest"],u);return vr(c?.result??c)}return{async quote({tokenIn:s,tokenOut:o,amountIn:i,path:u},c={}){let l=Ie(c.scanner);if(!l)return{chainId:e,evidence:w.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let a=u||[s,o];if(a.some(h=>!/^0x[0-9a-fA-F]{40}$/.test(h||"")))throw new Error("quote requires valid 20-byte addresses");let p=await n(l,i,a,c);return p?{chainId:e,router:l,path:a,amountIn:String(i),amountOut:p[p.length-1].toString(),hops:a.length-1,evidence:w.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:e,router:l,path:a,evidence:w.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:s,amountIn:o,base:i},u={}){let c=Ie(u.scanner),l=i||r;if(l&&String(s).toLowerCase()===String(l).toLowerCase())return{chainId:e,token:s,verdict:g.UNKNOWN,evidence:w.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||!l)return{chainId:e,token:s,verdict:g.UNKNOWN,evidence:w.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,[l,s],u);if(!a)return{chainId:e,token:s,verdict:g.FAIL,evidence:w.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let p=a[a.length-1];if(p===0n)return{chainId:e,token:s,verdict:g.FAIL,evidence:w.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let h=await n(c,p,[s,l],u);if(!h)return{chainId:e,token:s,verdict:g.FAIL,evidence:w.LIVE,leg:"sell",bought:p.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let f=h[h.length-1],d=Number(f*10000n/BigInt(o)),m=g.PASS,b="round trip completes with expected fee/impact loss";return d<5e3?(m=g.FAIL,b=`round trip returns only ${(d/100).toFixed(2)}% -- punitive tax or no real liquidity`):d<9e3&&(m=g.CAUTION,b=`round trip returns ${(d/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,token:s,base:l,router:c,verdict:m,reason:b,amountIn:String(o),bought:p.toString(),returned:f.toString(),retentionBps:d,evidence:w.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:u,slippageBps:c=50,deadlineSeconds:l=900,path:a},p={}){let h=p.scanner,f=Ie(h);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(u||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let d=a||[s,o],m=await this.quote({tokenIn:s,tokenOut:o,amountIn:i,path:d},p);if(m.evidence!==w.LIVE)throw new Error(`cannot prepare without a live quote (${m.evidence}: ${m.reason??"no reason given"})`);let b=Er(m.amountOut,c);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let E=BigInt(Math.floor(Date.now()/1e3)+Number(l)),P=r&&d[0].toLowerCase()===r.toLowerCase()&&p.useNative,R=P?`0x${ke.swapExactETHForTokens}`+B(b)+B(128)+se(u)+B(E)+B(d.length)+d.map(se).join(""):`0x${ke.swapExactTokensForTokens}`+B(i)+B(b)+B(160)+se(u)+B(E)+B(d.length)+d.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:m.amountOut,minOut:b.toString(),slippageBps:c,maxSlippageBps:Oe,deadline:E.toString()},requires:P?[]:[{step:"approve",token:d[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 Sr=[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 Ar(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 Ne(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:u,amountIn:c,fee:l},a){let p=`0x${ct.quoteExactInputSingle}`+ae(i)+ae(u)+G(c)+G(l)+G(0),h=await F(e,"eth_call",[{to:o,data:p},"latest"],a).catch(()=>null),f=h?.result??h;if(!f||f==="0x"||f.length<66)return null;let d=BigInt(`0x${f.slice(2,66)}`);return d>0n?d:null}async function s({quoter:o,tokenIn:i,tokenOut:u,amountIn:c},l){let a=await Promise.all(Sr.map(async h=>{let f=await n({quoter:o,tokenIn:i,tokenOut:u,amountIn:c,fee:h},l);return{fee:h,amountOut:f?f.toString():null,out:f}})),p=null;for(let h of a)h.out&&(!p||h.out>p.amountOut)&&(p={fee:h.fee,amountOut:h.out});return{best:p,tried:a.map(({fee:h,amountOut:f})=>({fee:h,amountOut:f}))}}return{async quote({tokenIn:o,tokenOut:i,amountIn:u},c={}){let l=Ne(c.scanner,"quoter");if(!l)return{chainId:e,evidence:w.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let h of[o,i])if(!ut.test(h||""))throw new Error("quote requires valid 20-byte addresses");let{best:a,tried:p}=await s({quoter:l,tokenIn:o,tokenOut:i,amountIn:u},c);return a?{chainId:e,venue:"uniswap-v3",quoter:l,tokenIn:o,tokenOut:i,amountIn:String(u),amountOut:a.amountOut.toString(),fee:a.fee,useNative:!!r&&String(o).toLowerCase()===String(r).toLowerCase(),triedFeeTiers:p,evidence:w.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:e,quoter:l,tokenIn:o,tokenOut:i,triedFeeTiers:p,evidence:w.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:o,amountIn:i,base:u},c={}){let l=Ne(c.scanner,"quoter"),a=(t.stableQuoteAssets||[]).map(O=>String(O).toLowerCase()),p=null;!u&&typeof t.resolveQuoteAsset=="function"&&(p=await t.resolveQuoteAsset(o,c).catch(()=>null));let h=String(o).toLowerCase(),f=String(r||"").toLowerCase();if(f&&h===f)return{chainId:e,token:o,verdict:g.UNKNOWN,evidence:w.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 d=u||p||(a[0]&&h!==a[0]?a[0]:null)||r;if(d&&h===String(d).toLowerCase())return{chainId:e,token:o,verdict:g.UNKNOWN,evidence:w.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!l||!d)return{chainId:e,token:o,verdict:g.UNKNOWN,evidence:w.UNAVAILABLE,reason:l?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let m=await s({quoter:l,tokenIn:d,tokenOut:o,amountIn:i},c);if(!m.best){let O=a.find(C=>C&&C!==String(d).toLowerCase()&&C!==String(o).toLowerCase());if(O){let C=await s({quoter:l,tokenIn:O,tokenOut:o,amountIn:i},c);if(C.best){let v=await s({quoter:l,tokenIn:o,tokenOut:O,amountIn:C.best.amountOut},c);if(v.best){let T=v.best.amountOut,S=Number(T*10000n/BigInt(i)),_=g.PASS,y="round trip vs dollar book completes with expected fee/impact loss";return S<5e3?(_=g.FAIL,y=`round trip vs dollar book returns only ${(S/100).toFixed(2)}% -- punitive tax or no real liquidity`):S<9e3&&(_=g.CAUTION,y=`round trip vs dollar book returns ${(S/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:O,quoteAsset:O,verdict:_,reason:y,amountIn:String(i),bought:C.best.amountOut.toString(),returned:T.toString(),retentionBps:S,buyFee:C.best.fee,sellFee:v.best.fee,evidence:w.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:e,token:o,verdict:g.FAIL,evidence:w.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let b=await s({quoter:l,tokenIn:o,tokenOut:d,amountIn:m.best.amountOut},c);if(!b.best){let O=a.find(C=>C&&C!==String(d).toLowerCase()&&C!==String(o).toLowerCase());if(O){let C=await s({quoter:l,tokenIn:O,tokenOut:o,amountIn:i},c),v=C.best?await s({quoter:l,tokenIn:o,tokenOut:O,amountIn:C.best.amountOut},c):{best:null};if(C.best&&v.best){let T=v.best.amountOut,S=Number(T*10000n/BigInt(i)),_=g.PASS,y="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return S<5e3?(_=g.FAIL,y=`dollar-book round trip returns only ${(S/100).toFixed(2)}%`):S<9e3&&(_=g.CAUTION,y=`dollar-book round trip returns ${(S/100).toFixed(2)}%`),{chainId:e,venue:"uniswap-v3",token:o,base:O,quoteAsset:O,verdict:_,reason:y,amountIn:String(i),bought:C.best.amountOut.toString(),returned:T.toString(),retentionBps:S,buyFee:C.best.fee,sellFee:v.best.fee,evidence:w.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:e,token:o,verdict:g.FAIL,evidence:w.LIVE,leg:"sell",bought:m.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let E=b.best.amountOut,P=Number(E*10000n/BigInt(i)),R=g.PASS,U="round trip completes with expected fee/impact loss";return P<5e3?(R=g.FAIL,U=`round trip returns only ${(P/100).toFixed(2)}% -- punitive tax or no real liquidity`):P<9e3&&(R=g.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:d,verdict:R,reason:U,amountIn:String(i),bought:m.best.amountOut.toString(),returned:E.toString(),retentionBps:P,buyFee:m.best.fee,sellFee:b.best.fee,evidence:w.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:i,amountIn:u,recipient:c,slippageBps:l=50,fee:a},p={}){let h=Ne(p.scanner,"router");if(!h)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:u},p);if(f.evidence!==w.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let d=a??f.fee,m=Ar(f.amountOut,l);if(m<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=!!(p.useNative||f.useNative)&&r&&String(o).toLowerCase()===String(r).toLowerCase(),E=`0x${ct.exactInputSingle}`+ae(o)+ae(i)+G(d)+ae(c)+G(u)+G(m)+G(0);return{unsigned:!0,signedBy:"user-wallet",chainId:e,venue:"uniswap-v3",tx:{to:h,data:E,value:b?String(u):"0x0"},guard:{quotedOut:f.amountOut,minOut:m.toString(),slippageBps:l,maxSlippageBps:Pe,fee:d},requires:b?[]:[{step:"approve",token:o,spender:h,amount:String(u)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var 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 xr(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:w.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:w.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:w.LIVE}},async resolveToken(n,s={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:e,token:n,evidence:w.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[o,i,u,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)]),l=dt(o?.result??o),a=l!==null||i?.result||u?.result,p={chainId:e,address:n,decimals:l===null?null:Number(l),symbol:pt(i?.result??i),name:pt(u?.result??u),totalSupply:(dt(c?.result??c)??null)?.toString()??null,evidence:a?w.LIVE:w.UNKNOWN};return a||(p.warning="no ERC-20 metadata returned -- may not be a token contract"),p},async resolvePools(n,s={}){let o=t.dexscreenerSlug;if(!o)return{chainId:e,token:n,pools:[],evidence:w.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,p)=>(p.liquidityUsd??0)-(a.liquidityUsd??0)),l=Ce(n,c,{stables:t.stableQuoteAssets||[],wrappedNative:t.wrappedNative});return{chainId:e,token:n,pools:l,topPool:l[0]||null,quoteAsset:nt(n,l),evidence:l.length?w.LIVE:w.UNKNOWN}},async scanBlocks({fromBlock:n,toBlock:s,address:o,topics:i,chunkSize:u=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 l=[],a=[];for(let h=n;h<=s;h+=u){let f=Math.min(h+u-1,s);a.push([h,f])}let p=await We(a,4,async([h,f])=>{let d={fromBlock:`0x${h.toString(16)}`,toBlock:`0x${f.toString(16)}`};o&&(d.address=o),i&&(d.topics=i);let m=await F(e,"eth_getLogs",[d],c).catch(b=>({error:String(b?.message||b)}));return{start:h,end:f,res:m}});for(let{start:h,end:f,res:d}of p){if(d?.error)return{chainId:e,fromBlock:n,toBlock:s,logs:l,complete:!1,failedAt:[h,f],error:d.error,evidence:w.UNKNOWN};for(let m of d?.result??d??[])l.push(m)}return{chainId:e,fromBlock:n,toBlock:s,logs:l,complete:!0,chunks:a.length,evidence:w.LIVE}},async scoreRisk(n,s={}){let o=[],i=g.PASS,u=a=>{let p={[g.PASS]:0,[g.CAUTION]:1,[g.UNKNOWN]:2,[g.FAIL]:3};p[a]>p[i]&&(i=a)},[c,l]=await Promise.all([this.resolveToken(n,s),this.resolvePools(n,s)]);if(c.evidence!==w.LIVE?(o.push({check:"erc20-metadata",result:g.UNKNOWN,detail:c.warning}),u(g.UNKNOWN)):o.push({check:"erc20-metadata",result:g.PASS,detail:`${c.symbol} / ${c.decimals}d`}),l.evidence===w.UNAVAILABLE)o.push({check:"liquidity",result:g.UNKNOWN,detail:l.reason}),u(g.UNKNOWN);else if(!l.pools.length)o.push({check:"liquidity",result:g.FAIL,detail:"no pool with liquidity found"}),u(g.FAIL);else{let a=l.pools[0],p=a.liquidityUsd??0;p<5e3?(o.push({check:"liquidity",result:g.CAUTION,detail:`top pool only $${p}`}),u(g.CAUTION)):o.push({check:"liquidity",result:g.PASS,detail:`$${p} on ${a.dex}`}),a.createdAt&&Date.now()-a.createdAt<24*3600*1e3&&(o.push({check:"age",result:g.CAUTION,detail:"pool under 24h old"}),u(g.CAUTION))}if(typeof this.sellSimulation=="function"){let a=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},s).catch(p=>({verdict:g.UNKNOWN,reason:String(p?.message||p)}));o.push({check:"sellability",result:a.verdict,detail:a.retentionBps!=null?`round trip returns ${(a.retentionBps/100).toFixed(2)}% -- ${a.reason}`:a.reason}),u(a.verdict)}else o.push({check:"sellability",result:g.UNKNOWN,detail:"no verified router on this chain, so a round-trip sell simulation cannot run. Treat as unproven -- a buy path is not an exit path."}),u(g.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={...xr(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 Cr=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 Cr.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 Tr(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
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
|
|
@@ -17,4 +17,4 @@ ${e.note}`);break}case"quote":{let t=J(I[0]);(!I[1]||!I[2])&&D("usage: oracle-sc
|
|
|
17
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
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(mt?1:0)}}catch(t){let e=I[0]?Te(Number(I[0]))||fe().find(r=>r.key===I[0]):null;D(e?
|
|
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?Tr(e,t):String(t?.message||t))}
|
package/dist/bin/oracle.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import{realpathSync as W}from"node:fs";import{fileURLToPath as xe}from"node:url"
|
|
|
7
7
|
oracle auth manage Claude, Codex, Grok, or API-key auth
|
|
8
8
|
oracle chain list/select working chains (hyperliquid, base, ...)
|
|
9
9
|
oracle project allow|deny|list folders chat may read/write
|
|
10
|
+
oracle account bind|pull hosted memory, skills, threads (no keys)
|
|
10
11
|
|
|
11
12
|
READ / RESEARCH
|
|
12
13
|
oracle doctor check the read plane
|