@oracle-agent/oracle 0.35.49 → 0.35.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +3 -2
  2. package/artifacts/specialist-packs/oracle-full-crypto.json +11 -0
  3. package/dist/agent-sessions.mjs +19 -19
  4. package/dist/artifacts/token-dashboard.mjs +1 -1
  5. package/dist/assets/profiles/near-agent/SOUL.md +46 -0
  6. package/dist/assets/profiles/near-agent/profile.json +30 -0
  7. package/dist/assets/profiles/oracle/SOUL.md +1 -0
  8. package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
  9. package/dist/assets/skills/oracle-near/SKILL.md +66 -0
  10. package/dist/automation-plan.mjs +1 -1
  11. package/dist/bin/desk-server.mjs +33 -33
  12. package/dist/bin/oracle-data-mcp.mjs +16 -16
  13. package/dist/bin/oracle-gateway.mjs +3 -3
  14. package/dist/bin/oracle-launch-radar-shadow.mjs +3 -3
  15. package/dist/bin/oracle-mev-arb-shadow.mjs +4 -4
  16. package/dist/bin/oracle-mev-shadow.mjs +4 -4
  17. package/dist/bin/oracle-public-server.mjs +5 -5
  18. package/dist/bin/oracle-route.mjs +27 -27
  19. package/dist/bin/oracle-scan.mjs +3 -3
  20. package/dist/bin/oracle-telegram-mcp.mjs +1 -1
  21. package/dist/chains.mjs +1 -1
  22. package/dist/cli/commands/account.mjs +22 -22
  23. package/dist/cli/commands/agent-session.mjs +23 -23
  24. package/dist/cli/commands/auth.mjs +16 -15
  25. package/dist/cli/commands/chain.mjs +5 -5
  26. package/dist/cli/commands/chat.mjs +310 -228
  27. package/dist/cli/commands/data.mjs +37 -37
  28. package/dist/cli/commands/doctor.mjs +5 -5
  29. package/dist/cli/commands/eval.mjs +249 -167
  30. package/dist/cli/commands/farm.mjs +1 -1
  31. package/dist/cli/commands/follow.mjs +4 -4
  32. package/dist/cli/commands/harness.mjs +5 -5
  33. package/dist/cli/commands/mint.mjs +11 -11
  34. package/dist/cli/commands/model.mjs +313 -231
  35. package/dist/cli/commands/project.mjs +8 -7
  36. package/dist/cli/commands/quickstart.mjs +2 -2
  37. package/dist/cli/commands/receipt.mjs +2 -2
  38. package/dist/cli/commands/resolve.mjs +4 -4
  39. package/dist/cli/commands/session-vault.mjs +4 -4
  40. package/dist/cli/commands/setup.mjs +53 -52
  41. package/dist/cli/commands/snipe.mjs +13 -13
  42. package/dist/cli/commands/strategy.mjs +5 -5
  43. package/dist/cli/commands/swap.mjs +11 -11
  44. package/dist/cli/commands/telegram.mjs +7 -7
  45. package/dist/cli/commands/venues.mjs +1 -1
  46. package/dist/cli/project-access.mjs +4 -3
  47. package/dist/data/desk-data.mjs +31 -31
  48. package/dist/data/holder-table.mjs +2 -2
  49. package/dist/data/market-tape.mjs +1 -1
  50. package/dist/data/names.mjs +3 -3
  51. package/dist/data/providers/farming.mjs +2 -2
  52. package/dist/data/providers/lp-destination-discovery.mjs +4 -4
  53. package/dist/index.mjs +49 -49
  54. package/dist/launch-radar/index.mjs +5 -5
  55. package/dist/lp/index.mjs +4 -4
  56. package/dist/nft/universal-mint-router.mjs +4 -4
  57. package/dist/notifications/index.mjs +1 -1
  58. package/dist/router/index.mjs +3 -3
  59. package/dist/router/prepare-bridge.mjs +2 -2
  60. package/dist/router/prepare-route.mjs +3 -3
  61. package/dist/scanner/index.mjs +3 -3
  62. package/dist/strategy/index.mjs +4 -4
  63. package/dist/task.mjs +1 -1
  64. package/dist/teams/index.mjs +6 -6
  65. package/dist/telegram/chart-card.mjs +5 -5
  66. package/dist/telegram/market-commands.mjs +1 -1
  67. package/dist/tui/standalone-client.mjs +179 -97
  68. package/package.json +2 -2
  69. package/public/oracle-splash/assets/desktop-app.jpg +0 -0
  70. package/public/oracle-splash/docs/browser-and-web/index.html +2 -2
  71. package/public/oracle-splash/docs/connectors/index.html +2 -2
  72. package/public/oracle-splash/docs/getting-started/index.html +2 -2
  73. package/public/oracle-splash/docs/index.html +3 -3
  74. package/public/oracle-splash/docs/reference/index.html +2 -2
  75. package/public/oracle-splash/docs/security/index.html +2 -2
  76. package/public/oracle-splash/docs/using-oracle/index.html +2 -2
  77. package/public/oracle-splash/download/index.html +219 -5
  78. package/public/oracle-splash/downloads/index.html +1 -1
  79. package/public/oracle-splash/eval/index.html +19 -19
  80. package/public/oracle-splash/eval/releases/oracle-0.35.49.json +852 -0
  81. package/public/oracle-splash/index.html +262 -37
  82. package/public/oracle-splash/pricing/index.html +215 -1
  83. package/public/oracle-splash/security/index.html +215 -1
  84. package/public/oracle-splash/what-it-does/index.html +215 -1
  85. package/public/oracle-splash/where-it-works/index.html +215 -1
  86. package/server.json +2 -2
@@ -1,6 +1,6 @@
1
1
  var J=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),g=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),w=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),dt=/^0x[0-9a-fA-F]{40}$/;function pt(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}dt.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))J.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 ft(t){let{ok:e,errors:r,warnings:n}=pt(t);if(!e)throw new Error(`invalid scanner for ${t?.key??"<unknown>"}:
2
2
  - ${r.join(`
3
- - `)}`);let s=t.capabilities||{},o=J.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:J.filter(u=>!o.includes(u))}},supports(u){return o.includes(u)}};for(let u of J)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 G=new Map;function de(t){let e=ft(t);return G.set(e.chainId,e),e}function yr(t){return G.get(Number(t))||null}function wr(){return[...G.values()]}function gr(){G.clear()}function vr(){let t={};for(let e of G.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:G.size,capabilities:[...J],chains:t}}import{createHash as At}from"node:crypto";import{types as j}from"node:util";import{AsyncLocalStorage as ht}from"node:async_hooks";var mt=new ht,bt=["http","retry","shared"],yt=512;function oe(t){let e=mt.getStore();if(!e||e.closed||!bt.includes(t))return null;if(e.spans.length>=yt)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 V from"node:net";import wt from"node:dns";var gt=new Set(["localhost","metadata.google.internal","metadata.goog"]);function se(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 pe(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 fe(t){if(V.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(V.isIPv6(t)){let e=se(t);if(!e)return!1;let r=se("::ffff:0:0");return pe(e,r,96)?fe([...e.slice(12)].join(".")):pe(e,se("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([s,o])=>pe(e,se(s),o)):!1}return!1}function vt(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(gt.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=V.isIP(r);return n!==0&&!fe(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:e,host:r,isLiteralIp:n!==0}}async function he(t,{lookupFn:e=wt.promises.lookup}={}){let r=vt(t);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:V.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=>!fe(s.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}function Et(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 me({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||(V.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(V.isIP(d))return[{address:d,family:V.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=Et(),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=St((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 be=Symbol.for("oracle.egressGuard.pinCapableFetch");function St(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[be]=Object.freeze({pin:e}),t}function ye(t){return typeof t=="function"&&typeof t[be]?.pin=="function"}function Le(t,e,r){if(!ye(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[be].pin(e,r)}var xt=new Set([408,425,429,500,502,503,504]),Ue=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Ct=2,qe=4e3,Tt=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,It=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Ot=AbortSignal.prototype.throwIfAborted,Nt=EventTarget.prototype.addEventListener,Be=EventTarget.prototype.removeEventListener,Fe=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,Z=t=>t?Tt.call(t):!1,kt=t=>t?It.call(t):void 0,Pt=new Set([301,302,303,307,308]),ie=3,Pr=64*1024,D=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});function I(t){return H(`HTTP JSON body refused: ${t}`)}function Rt(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 j[e]=="function"&&j[e](t))}function _t(t){let e=[],r=0,n=0,s=0,o=0,i=new WeakSet,u=a=>{if(r+=Buffer.byteLength(a,"utf8"),r>D.bytes)throw I("serialized byte limit exceeded");e.push(a)},c=a=>{if(Buffer.byteLength(a,"utf8")>D.bytes)throw I("serialized byte limit exceeded");return JSON.stringify(a)},l=(a,p)=>{if(n+=1,n>D.nodes)throw I("node limit exceeded");if(p>D.depth)throw I("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 I("non-finite number");u(Object.is(a,-0)?"0":String(a));return}if(typeof a!="object")throw I("unsupported non-JSON value");if(j.isProxy(a))throw I("proxy value");if(Rt(a))throw I("unsupported exotic object");if(i.has(a))throw I("cyclic value");i.add(a);try{if(Object.getOwnPropertySymbols(a).length>0)throw I("symbol-keyed fields are unsupported");if(Array.isArray(a)){let d=Object.getPrototypeOf(a),m=0;for(;d!==null;){if(j.isProxy(d))throw I("proxy array prototype");if(m+=1,m>D.depth)throw I("array prototype depth limit exceeded");d=Object.getPrototypeOf(d)}if(a.length>D.arrayLength)throw I("array length limit exceeded");for(let E=0;E<a.length;E+=1){let k=Object.getOwnPropertyDescriptor(a,String(E));if(!k||!Object.hasOwn(k,"value")||k.enumerable!==!0)throw I("array entries must be dense enumerable own data")}let b=0;for(let E in a){if(o+=1,o>D.fields)throw I("enumeration limit exceeded");if(Object.hasOwn(a,E)&&(b+=1,b>a.length))throw I("named array fields are unsupported")}if(b!==a.length)throw I("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 I("non-plain object");let f=[];for(let d in a){if(o+=1,o>D.fields)throw I("enumeration limit exceeded");if(!Object.hasOwn(a,d))continue;if(s+=1,s>D.fields)throw I("field limit exceeded");let m=Object.getOwnPropertyDescriptor(a,d);if(!m||!Object.hasOwn(m,"value")||m.enumerable!==!0)throw I("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 Lt(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(j.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 Ut(){return Object.assign(Object.create(null),{Accept:"application/json"})}function qt(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 Bt(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var we=new Map,$e=new WeakMap,De=1;function ae(t){if((typeof t!="object"||t===null)&&typeof t!="function")return`${typeof t}:${String(t)}`;let e=$e.get(t);return e||(e=De,De+=1,$e.set(t,e)),`reference:${e}`}var Ft=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),$t=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function je(t){if(!t||typeof t!="object"||Array.isArray(t)||!Object.hasOwn(t,"jsonrpc")||!Object.hasOwn(t,"method")||t.jsonrpc!=="2.0")return!1;let e=typeof t.method=="string"?t.method:"";return e?Ft.has(e)||/^get[A-Z0-9_]/u.test(e)||/^is[A-Z0-9_]/u.test(e)||/^eth_get[A-Z0-9_]/u.test(e):!1}function He(t,e){if(t==="GET"&&e==null)return!0;if(t!=="POST"||e==null)return!1;let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{return!1}if(Array.isArray(r))return r.length>0&&r.every(je);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return je(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&$t.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function Dt(t,e,r,n={},s=null){let o=At("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(`
4
- `)};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 jt(t,e){let r=Number(e);return Number.isFinite(r)&&r>0?Math.min(r*1e3,qe):Math.min(250*2**t,qe)+Math.floor(Math.random()*100)}var Ht=t=>new Promise(e=>setTimeout(e,t));function H(t,e={}){let r=new Error(t);return r.retryable=!1,Object.assign(r,e),r}function ge(t,e,r){return H(`HTTP response from ${t} exceeded maxResponseBytes ${r} (${e})`,{oversize:!0})}function z(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function Mt(t){return t?t.byteLength??t.length??0:0}async function Vt(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&&(z(t),!n))throw ge(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 ge(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+=Mt(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 ge(r,`streamed ${c} bytes`,e);let a=Buffer.concat(u);return(l?a.subarray(0,e):a).toString("utf8")}function zt(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Wt(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=ie}){let b=null,E=e,k=i?{lookupFn:i}:{};if(c&&!u&&!ye(E))throw H(`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 P=new AbortController,L=setTimeout(()=>P.abort(),o),O=f?Fe?Fe([f,P.signal]):f:P.signal,C=async(v,{status:T=null}={})=>{let S=await he(v,k);if(!S.ok)throw H(T==null?`HTTP refused ${v}: ${S.error}`:`HTTP redirect to ${v} ${S.error}`,T==null?{}:{status:T});let R=new URL(v).hostname;if(u){if(b&&(await b.close(),b=null),!b)try{b=await me({requireUndici:!0,...p?{importUndici:p}:{}})}catch(y){throw H(T==null?`HTTP refused ${v}: ${y?.message||y}`:`HTTP redirect to ${v} refused: ${y?.message||y}`,T==null?{}:{status:T})}b.pin(R,S.addresses),E=b.fetch}else Le(E,R,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 R=Object.assign(Object.create(null),{method:r,headers:T,body:s,signal:O,redirect:"manual",dispatcher:void 0}),y=await E(v,R);if((d==="error"||m===0)&&y.status>=300&&y.status<400)throw z(y),H(`HTTP ${y.status} ${r} redirect refused`,{status:y.status,redirectRefused:!0});if(Pt.has(y.status)){let U=a===!0&&r==="POST"&&[307,308].includes(y.status)&&He(r,s);if(r!=="GET"&&r!=="HEAD"&&!U){z(y);let N=new Error(`HTTP ${y.status} ${r} ${v} redirected non-idempotent request`);throw N.status=y.status,N}if(S===m)throw z(y),H(`HTTP ${y.status} ${r} redirect budget exhausted`,{status:y.status,redirectRefused:!0});let Ne=y.headers?.get?.("location"),B;try{B=qt(Ne,v)}catch(N){throw z(y),N}let M=!Bt(B,v);if(z(y),M&&r==="POST"){let N=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw N.status=y.status,N}if(M&&a){let N=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw N.status=y.status,N.retryable=!1,N}if(M&&(T=Ut(T)),c)await C(B,{status:y.status});else if(M){let N=await he(B,k);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 me(p?{importUndici:p}:{})),b&&(b.pin(new URL(B).hostname,N.addresses),E=b.fetch))}v=B;continue}if(typeof h=="function")try{await h(y,{url:v})}catch(U){throw z(y),H(U?.message||String(U))}let _=await Vt(y,l,{url:v,onOversize:()=>P.abort()}),Q=zt(_);if(!y.ok){let U=new Error(`HTTP ${y.status} ${r} ${v}`);throw U.status=y.status,U.retryAfter=y.headers?.get?.("retry-after")??null,U.body=Q??_.slice(0,300),U}return Q??_}throw new Error(`HTTP redirect loop for ${t}`)}catch(v){if(P.signal.aborted&&!Z(f)){let T=v&&(typeof v=="object"||typeof v=="function")&&!j.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(L),b&&await b.close()}}async function ce(t,e={}){if(e!=null&&typeof e!="object"&&typeof e!="function")throw new TypeError("HTTP options must be an object");if(e!=null&&j.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>ie))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${ie}`);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??ie;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(j.isProxy(h)||!(h instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{Z(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"),k=Lt(E),P=Object.assign(Object.create(null),k);Object.keys(P).some(x=>x.toLowerCase()==="accept")||(P.Accept="application/json");let L=n("body");L!=null&&typeof L!="string"&&(Object.keys(P).find(A=>A.toLowerCase()==="content-type")||(P["Content-Type"]="application/json"),L=_t(L));let O=i??Ct,C=n("lookupFn"),v=!f,T=n("untrustedUrl")===!0,S=n("sameOriginRedirectsOnly")===!0,R=n("importUndici"),y=n("validateResponse"),_=h,Q=p??null,U=async()=>{let x;for(let A=0;A<=O;A++){_&&Ot.call(_);let ke=oe("http");try{let $=await Wt(t,{fetchImpl:d,method:b,headers:P,body:L,timeoutMs:m,lookupFn:C,realFetch:v,untrustedUrl:T,maxResponseBytes:Q,sameOriginRedirectsOnly:S,importUndici:R,validateResponse:y,signal:_,redirectPolicy:l,maxRedirects:a});return ke?.("succeeded"),$}catch($){x=$;let K=le=>{if(!$||typeof $!="object"&&typeof $!="function"||j.isProxy($))return;let Y=Object.getOwnPropertyDescriptor($,le);return Y&&Object.hasOwn(Y,"value")?Y.value:void 0},ne=K("status");ke?.("failed",ne);let it=K("oracleTimeout")===!0||K("name")==="AbortError"||K("name")==="TimeoutError"||Z(_),ct=new Set([408,425,429]),ut=K("retryable")===!1?!1:ne!=null?ct.has(ne)||xt.has(ne)&&Ue.has(b):!it&&Ue.has(b);if(A===O||!ut)throw $;let Pe=jt(A,K("retryAfter")),lt=oe("retry"),Re=!1;try{_?await new Promise((le,Y)=>{let _e,X=()=>{clearTimeout(_e),Be.call(_,"abort",X),Y(kt(_)||new DOMException("Aborted","AbortError"))};if(Z(_)){X();return}_e=setTimeout(()=>{Be.call(_,"abort",X),le()},Pe),Nt.call(_,"abort",X,{once:!0}),Z(_)&&X()}):await Ht(Pe),Re=!0}finally{lt?.(Re?"succeeded":"failed")}}}throw x};if(!(n("dedupe")!==!1&&!_&&He(b,L)))return U();let B=Dt(b,t,P,{untrustedUrl:T,maxResponseBytes:Q,sameOriginRedirectsOnly:S,redirectPolicy:l,maxRedirects:a,timeoutMs:m,retries:O,fetchImpl:ae(d),realFetch:v,lookupFn:ae(C),importUndici:ae(R),validateResponse:ae(y)},L),M=we.get(B);if(M){let x=oe("shared");try{let A=await M;return x?.("succeeded"),A}catch(A){throw x?.("failed"),A}}let N=U().finally(()=>we.delete(B));return we.set(B,N),N}async function Me(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 ve={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}};var Kt=new Map(Object.values(ve).map(t=>[t.chainId,t]));function Ve(t){return Kt.get(Number(t))||null}function ze(t,e=process.env){let r=Ve(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 Gt,getAddress as Qt}from"ethers";var We=new Gt(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Ke(t,e){try{return Qt(t).toLowerCase()}catch{throw new Error(`${e} must be a valid EVM address`)}}var Yt={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 Xt(t,{rpcUrl:e,env:r=process.env}={}){if(e)return e;let n=ze(t,r);return n||Yt[Number(t)]||null}var Jt=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Zt(t){let e=String(t||""),r=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!Jt.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 ee=new Map,Ge=new Map;function er(t){let e=new Error(t?.message||JSON.stringify(t));return e.code=t?.code,e}function tr(t){if(t?.error)throw er(t.error);return t?.result}function rr(t,e,r){return`${t}
3
+ - `)}`);let s=t.capabilities||{},o=J.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:J.filter(u=>!o.includes(u))}},supports(u){return o.includes(u)}};for(let u of J)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 G=new Map;function de(t){let e=ft(t);return G.set(e.chainId,e),e}function yr(t){return G.get(Number(t))||null}function wr(){return[...G.values()]}function gr(){G.clear()}function vr(){let t={};for(let e of G.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:G.size,capabilities:[...J],chains:t}}import{createHash as At}from"node:crypto";import{types as j}from"node:util";import{AsyncLocalStorage as ht}from"node:async_hooks";var mt=new ht,bt=["http","retry","shared"],yt=512;function oe(t){let e=mt.getStore();if(!e||e.closed||!bt.includes(t))return null;if(e.spans.length>=yt)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 V from"node:net";import wt from"node:dns";var gt=new Set(["localhost","metadata.google.internal","metadata.goog"]);function se(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 pe(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 fe(t){if(V.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(V.isIPv6(t)){let e=se(t);if(!e)return!1;let r=se("::ffff:0:0");return pe(e,r,96)?fe([...e.slice(12)].join(".")):pe(e,se("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([s,o])=>pe(e,se(s),o)):!1}return!1}function vt(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(gt.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=V.isIP(r);return n!==0&&!fe(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:e,host:r,isLiteralIp:n!==0}}async function he(t,{lookupFn:e=wt.promises.lookup}={}){let r=vt(t);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:V.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=>!fe(s.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}function Et(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 me({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||(V.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(V.isIP(d))return[{address:d,family:V.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=Et(),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=St((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 be=Symbol.for("oracle.egressGuard.pinCapableFetch");function St(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[be]=Object.freeze({pin:e}),t}function ye(t){return typeof t=="function"&&typeof t[be]?.pin=="function"}function Le(t,e,r){if(!ye(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[be].pin(e,r)}var xt=new Set([408,425,429,500,502,503,504]),Ue=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Ct=2,qe=4e3,Tt=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,It=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Ot=AbortSignal.prototype.throwIfAborted,Nt=EventTarget.prototype.addEventListener,Be=EventTarget.prototype.removeEventListener,$e=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,Z=t=>t?Tt.call(t):!1,kt=t=>t?It.call(t):void 0,Pt=new Set([301,302,303,307,308]),ie=3,Pr=64*1024,D=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});function I(t){return H(`HTTP JSON body refused: ${t}`)}function Rt(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 j[e]=="function"&&j[e](t))}function _t(t){let e=[],r=0,n=0,s=0,o=0,i=new WeakSet,u=a=>{if(r+=Buffer.byteLength(a,"utf8"),r>D.bytes)throw I("serialized byte limit exceeded");e.push(a)},c=a=>{if(Buffer.byteLength(a,"utf8")>D.bytes)throw I("serialized byte limit exceeded");return JSON.stringify(a)},l=(a,p)=>{if(n+=1,n>D.nodes)throw I("node limit exceeded");if(p>D.depth)throw I("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 I("non-finite number");u(Object.is(a,-0)?"0":String(a));return}if(typeof a!="object")throw I("unsupported non-JSON value");if(j.isProxy(a))throw I("proxy value");if(Rt(a))throw I("unsupported exotic object");if(i.has(a))throw I("cyclic value");i.add(a);try{if(Object.getOwnPropertySymbols(a).length>0)throw I("symbol-keyed fields are unsupported");if(Array.isArray(a)){let d=Object.getPrototypeOf(a),m=0;for(;d!==null;){if(j.isProxy(d))throw I("proxy array prototype");if(m+=1,m>D.depth)throw I("array prototype depth limit exceeded");d=Object.getPrototypeOf(d)}if(a.length>D.arrayLength)throw I("array length limit exceeded");for(let E=0;E<a.length;E+=1){let k=Object.getOwnPropertyDescriptor(a,String(E));if(!k||!Object.hasOwn(k,"value")||k.enumerable!==!0)throw I("array entries must be dense enumerable own data")}let b=0;for(let E in a){if(o+=1,o>D.fields)throw I("enumeration limit exceeded");if(Object.hasOwn(a,E)&&(b+=1,b>a.length))throw I("named array fields are unsupported")}if(b!==a.length)throw I("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 I("non-plain object");let f=[];for(let d in a){if(o+=1,o>D.fields)throw I("enumeration limit exceeded");if(!Object.hasOwn(a,d))continue;if(s+=1,s>D.fields)throw I("field limit exceeded");let m=Object.getOwnPropertyDescriptor(a,d);if(!m||!Object.hasOwn(m,"value")||m.enumerable!==!0)throw I("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 Lt(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(j.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 Ut(){return Object.assign(Object.create(null),{Accept:"application/json"})}function qt(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 Bt(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var we=new Map,Fe=new WeakMap,De=1;function ae(t){if((typeof t!="object"||t===null)&&typeof t!="function")return`${typeof t}:${String(t)}`;let e=Fe.get(t);return e||(e=De,De+=1,Fe.set(t,e)),`reference:${e}`}var $t=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),Ft=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function je(t){if(!t||typeof t!="object"||Array.isArray(t)||!Object.hasOwn(t,"jsonrpc")||!Object.hasOwn(t,"method")||t.jsonrpc!=="2.0")return!1;let e=typeof t.method=="string"?t.method:"";return e?$t.has(e)||/^get[A-Z0-9_]/u.test(e)||/^is[A-Z0-9_]/u.test(e)||/^eth_get[A-Z0-9_]/u.test(e):!1}function He(t,e){if(t==="GET"&&e==null)return!0;if(t!=="POST"||e==null)return!1;let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{return!1}if(Array.isArray(r))return r.length>0&&r.every(je);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return je(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&Ft.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function Dt(t,e,r,n={},s=null){let o=At("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(`
4
+ `)};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 jt(t,e){let r=Number(e);return Number.isFinite(r)&&r>0?Math.min(r*1e3,qe):Math.min(250*2**t,qe)+Math.floor(Math.random()*100)}var Ht=t=>new Promise(e=>setTimeout(e,t));function H(t,e={}){let r=new Error(t);return r.retryable=!1,Object.assign(r,e),r}function ge(t,e,r){return H(`HTTP response from ${t} exceeded maxResponseBytes ${r} (${e})`,{oversize:!0})}function z(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function Mt(t){return t?t.byteLength??t.length??0:0}async function Vt(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&&(z(t),!n))throw ge(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 ge(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+=Mt(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 ge(r,`streamed ${c} bytes`,e);let a=Buffer.concat(u);return(l?a.subarray(0,e):a).toString("utf8")}function zt(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Wt(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=ie}){let b=null,E=e,k=i?{lookupFn:i}:{};if(c&&!u&&!ye(E))throw H(`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 P=new AbortController,L=setTimeout(()=>P.abort(),o),O=f?$e?$e([f,P.signal]):f:P.signal,C=async(v,{status:T=null}={})=>{let S=await he(v,k);if(!S.ok)throw H(T==null?`HTTP refused ${v}: ${S.error}`:`HTTP redirect to ${v} ${S.error}`,T==null?{}:{status:T});let R=new URL(v).hostname;if(u){if(b&&(await b.close(),b=null),!b)try{b=await me({requireUndici:!0,...p?{importUndici:p}:{}})}catch(y){throw H(T==null?`HTTP refused ${v}: ${y?.message||y}`:`HTTP redirect to ${v} refused: ${y?.message||y}`,T==null?{}:{status:T})}b.pin(R,S.addresses),E=b.fetch}else Le(E,R,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 R=Object.assign(Object.create(null),{method:r,headers:T,body:s,signal:O,redirect:"manual",dispatcher:void 0}),y=await E(v,R);if((d==="error"||m===0)&&y.status>=300&&y.status<400)throw z(y),H(`HTTP ${y.status} ${r} redirect refused`,{status:y.status,redirectRefused:!0});if(Pt.has(y.status)){let U=a===!0&&r==="POST"&&[307,308].includes(y.status)&&He(r,s);if(r!=="GET"&&r!=="HEAD"&&!U){z(y);let N=new Error(`HTTP ${y.status} ${r} ${v} redirected non-idempotent request`);throw N.status=y.status,N}if(S===m)throw z(y),H(`HTTP ${y.status} ${r} redirect budget exhausted`,{status:y.status,redirectRefused:!0});let Ne=y.headers?.get?.("location"),B;try{B=qt(Ne,v)}catch(N){throw z(y),N}let M=!Bt(B,v);if(z(y),M&&r==="POST"){let N=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw N.status=y.status,N}if(M&&a){let N=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw N.status=y.status,N.retryable=!1,N}if(M&&(T=Ut(T)),c)await C(B,{status:y.status});else if(M){let N=await he(B,k);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 me(p?{importUndici:p}:{})),b&&(b.pin(new URL(B).hostname,N.addresses),E=b.fetch))}v=B;continue}if(typeof h=="function")try{await h(y,{url:v})}catch(U){throw z(y),H(U?.message||String(U))}let _=await Vt(y,l,{url:v,onOversize:()=>P.abort()}),Q=zt(_);if(!y.ok){let U=new Error(`HTTP ${y.status} ${r} ${v}`);throw U.status=y.status,U.retryAfter=y.headers?.get?.("retry-after")??null,U.body=Q??_.slice(0,300),U}return Q??_}throw new Error(`HTTP redirect loop for ${t}`)}catch(v){if(P.signal.aborted&&!Z(f)){let T=v&&(typeof v=="object"||typeof v=="function")&&!j.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(L),b&&await b.close()}}async function ce(t,e={}){if(e!=null&&typeof e!="object"&&typeof e!="function")throw new TypeError("HTTP options must be an object");if(e!=null&&j.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>ie))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${ie}`);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??ie;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(j.isProxy(h)||!(h instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{Z(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"),k=Lt(E),P=Object.assign(Object.create(null),k);Object.keys(P).some(x=>x.toLowerCase()==="accept")||(P.Accept="application/json");let L=n("body");L!=null&&typeof L!="string"&&(Object.keys(P).find(A=>A.toLowerCase()==="content-type")||(P["Content-Type"]="application/json"),L=_t(L));let O=i??Ct,C=n("lookupFn"),v=!f,T=n("untrustedUrl")===!0,S=n("sameOriginRedirectsOnly")===!0,R=n("importUndici"),y=n("validateResponse"),_=h,Q=p??null,U=async()=>{let x;for(let A=0;A<=O;A++){_&&Ot.call(_);let ke=oe("http");try{let F=await Wt(t,{fetchImpl:d,method:b,headers:P,body:L,timeoutMs:m,lookupFn:C,realFetch:v,untrustedUrl:T,maxResponseBytes:Q,sameOriginRedirectsOnly:S,importUndici:R,validateResponse:y,signal:_,redirectPolicy:l,maxRedirects:a});return ke?.("succeeded"),F}catch(F){x=F;let K=le=>{if(!F||typeof F!="object"&&typeof F!="function"||j.isProxy(F))return;let Y=Object.getOwnPropertyDescriptor(F,le);return Y&&Object.hasOwn(Y,"value")?Y.value:void 0},ne=K("status");ke?.("failed",ne);let it=K("oracleTimeout")===!0||K("name")==="AbortError"||K("name")==="TimeoutError"||Z(_),ct=new Set([408,425,429]),ut=K("retryable")===!1?!1:ne!=null?ct.has(ne)||xt.has(ne)&&Ue.has(b):!it&&Ue.has(b);if(A===O||!ut)throw F;let Pe=jt(A,K("retryAfter")),lt=oe("retry"),Re=!1;try{_?await new Promise((le,Y)=>{let _e,X=()=>{clearTimeout(_e),Be.call(_,"abort",X),Y(kt(_)||new DOMException("Aborted","AbortError"))};if(Z(_)){X();return}_e=setTimeout(()=>{Be.call(_,"abort",X),le()},Pe),Nt.call(_,"abort",X,{once:!0}),Z(_)&&X()}):await Ht(Pe),Re=!0}finally{lt?.(Re?"succeeded":"failed")}}}throw x};if(!(n("dedupe")!==!1&&!_&&He(b,L)))return U();let B=Dt(b,t,P,{untrustedUrl:T,maxResponseBytes:Q,sameOriginRedirectsOnly:S,redirectPolicy:l,maxRedirects:a,timeoutMs:m,retries:O,fetchImpl:ae(d),realFetch:v,lookupFn:ae(C),importUndici:ae(R),validateResponse:ae(y)},L),M=we.get(B);if(M){let x=oe("shared");try{let A=await M;return x?.("succeeded"),A}catch(A){throw x?.("failed"),A}}let N=U().finally(()=>we.delete(B));return we.set(B,N),N}async function Me(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 ve={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0},elysium:{chainId:1339,name:"Elysium",rpcEnv:["ELYSIUM_RPC_URL"],evm:!0,readOnly:!0}};var Kt=new Map(Object.values(ve).map(t=>[t.chainId,t]));function Ve(t){return Kt.get(Number(t))||null}function ze(t,e=process.env){let r=Ve(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 Gt,getAddress as Qt}from"ethers";var We=new Gt(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Ke(t,e){try{return Qt(t).toLowerCase()}catch{throw new Error(`${e} must be a valid EVM address`)}}var Yt={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",1339:"https://rpc.elysiumchain.tech"};function Xt(t,{rpcUrl:e,env:r=process.env}={}){if(e)return e;let n=ze(t,r);return n||Yt[Number(t)]||null}var Jt=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Zt(t){let e=String(t||""),r=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!Jt.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 ee=new Map,Ge=new Map;function er(t){let e=new Error(t?.message||JSON.stringify(t));return e.code=t?.code,e}function tr(t){if(t?.error)throw er(t.error);return t?.result}function rr(t,e,r){return`${t}
5
5
  ${e}
6
- ${JSON.stringify(r??[])}`}async function nr(t,e,r){return ce(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=Zt(s),i=Xt(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=Ge.get(i);if(a!=null)return a}let c=n.dedupe!==!1&&!n.signal?rr(i,s,r):null;if(c&&ee.has(c))return ee.get(c);let l=(async()=>{let a=await nr(i,{jsonrpc:"2.0",id:1,method:e,params:r},n),p=tr(a);return o==="eth_chainid"&&typeof p=="string"&&Ge.set(i,p),p})();return c&&(ee.set(c,l),l.finally(()=>{ee.get(c)===l&&ee.delete(c)}).catch(()=>{})),l}async function Qe(t,e={}){let r=await F(t,"eth_blockNumber",[],e);return parseInt(r,16)}async function Ye(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 Xe(t={},e={}){let r=Number(t.chainId??e.chainId??1),n=Ke(t.token||t.tokenAddress,"token"),s=Ke(t.account||t.owner||t.address,"account"),o=We.encodeFunctionData("balanceOf",[s]),i=await F(r,"eth_call",[{to:n,data:o},t.blockTag||"latest"],e),u=We.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 or=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"]);function Je(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 Ee(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=Je(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)||or.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 Ze(t,e=[]){let r=Array.isArray(e)?e:[];return r.length&&Je(t,r[0]).address||null}var sr="https://api.dexscreener.com",Vr=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function ar(t={}){return(t.baseUrl||process.env.DEXSCREENER_API_URL||sr).replace(/\/$/,"")}function ir(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 cr(t,e){return ce(`${ar(e)}${t}`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}async function et(t,e={}){return cr(`/latest/dex/tokens/${ir(t,"tokenAddress")}`,e)}var Ae={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},q=t=>BigInt(t).toString(16).padStart(64,"0"),te=t=>t.slice(2).toLowerCase().padStart(64,"0");function ur(t,e){return`0x${Ae.getAmountsOut}`+q(t)+q(64)+q(e.length)+e.map(te).join("")}function lr(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 Se(t,e="router"){return(t?.venues||[]).find(n=>n.kind===e)?.address??null}var xe=100;function dr(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>xe)throw new Error(`slippageBps ${r} exceeds the ${xe} 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 tt(t){let{chainId:e,wrappedNative:r}=t;async function n(s,o,i,u){let c=await F(e,"eth_call",[{to:s,data:ur(o,i)},"latest"],u);return lr(c?.result??c)}return{async quote({tokenIn:s,tokenOut:o,amountIn:i,path:u},c={}){let l=Se(c.scanner);if(!l)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=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:g.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:e,router:l,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},u={}){let c=Se(u.scanner),l=i||r;if(l&&String(s).toLowerCase()===String(l).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||!l)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,[l,s],u);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 p=a[a.length-1];if(p===0n)return{chainId:e,token:s,verdict:w.FAIL,evidence:g.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:w.FAIL,evidence:g.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=w.PASS,b="round trip completes with expected fee/impact loss";return d<5e3?(m=w.FAIL,b=`round trip returns only ${(d/100).toFixed(2)}% -- punitive tax or no real liquidity`):d<9e3&&(m=w.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: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:u,slippageBps:c=50,deadlineSeconds:l=900,path:a},p={}){let h=p.scanner,f=Se(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!==g.LIVE)throw new Error(`cannot prepare without a live quote (${m.evidence}: ${m.reason??"no reason given"})`);let b=dr(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)),k=r&&d[0].toLowerCase()===r.toLowerCase()&&p.useNative,P=k?`0x${Ae.swapExactETHForTokens}`+q(b)+q(128)+te(u)+q(E)+q(d.length)+d.map(te).join(""):`0x${Ae.swapExactTokensForTokens}`+q(i)+q(b)+q(160)+te(u)+q(E)+q(d.length)+d.map(te).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:e,tx:{to:f,data:P,value:k?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:m.amountOut,minOut:b.toString(),slippageBps:c,maxSlippageBps:xe,deadline:E.toString()},requires:k?[]:[{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 pr=[100,500,3e3,1e4],rt={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},W=t=>BigInt(t).toString(16).padStart(64,"0"),re=t=>t.slice(2).toLowerCase().padStart(64,"0"),nt=/^0x[0-9a-fA-F]{40}$/,Te=100;function fr(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Te)throw new Error(`slippageBps ${r} exceeds the ${Te} 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 Ce(t,e){return(t?.venues||[]).find(r=>r.kind===e)?.address??null}function ot(t){let{chainId:e,wrappedNative:r}=t;async function n({quoter:o,tokenIn:i,tokenOut:u,amountIn:c,fee:l},a){let p=`0x${rt.quoteExactInputSingle}`+re(i)+re(u)+W(c)+W(l)+W(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(pr.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=Ce(c.scanner,"quoter");if(!l)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 h of[o,i])if(!nt.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:g.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: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:u},c={}){let l=Ce(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: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 d=u||p||(a[0]&&h!==a[0]?a[0]:null)||r;if(d&&h===String(d).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(!l||!d)return{chainId:e,token:o,verdict:w.UNKNOWN,evidence:g.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)),R=w.PASS,y="round trip vs dollar book completes with expected fee/impact loss";return S<5e3?(R=w.FAIL,y=`round trip vs dollar book returns only ${(S/100).toFixed(2)}% -- punitive tax or no real liquidity`):S<9e3&&(R=w.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:R,reason:y,amountIn:String(i),bought:C.best.amountOut.toString(),returned:T.toString(),retentionBps:S,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 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)),R=w.PASS,y="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return S<5e3?(R=w.FAIL,y=`dollar-book round trip returns only ${(S/100).toFixed(2)}%`):S<9e3&&(R=w.CAUTION,y=`dollar-book round trip returns ${(S/100).toFixed(2)}%`),{chainId:e,venue:"uniswap-v3",token:o,base:O,quoteAsset:O,verdict:R,reason:y,amountIn:String(i),bought:C.best.amountOut.toString(),returned:T.toString(),retentionBps:S,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: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,k=Number(E*10000n/BigInt(i)),P=w.PASS,L="round trip completes with expected fee/impact loss";return k<5e3?(P=w.FAIL,L=`round trip returns only ${(k/100).toFixed(2)}% -- punitive tax or no real liquidity`):k<9e3&&(P=w.CAUTION,L=`round trip returns ${(k/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:d,verdict:P,reason:L,amountIn:String(i),bought:m.best.amountOut.toString(),returned:E.toString(),retentionBps:k,buyFee:m.best.fee,sellFee:b.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:u,recipient:c,slippageBps:l=50,fee:a},p={}){let h=Ce(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(!nt.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!==g.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let d=a??f.fee,m=fr(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${rt.exactInputSingle}`+re(o)+re(i)+W(d)+re(c)+W(u)+W(m)+W(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:Te,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 ue={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function st(t){if(!t||t==="0x")return null;try{return BigInt(t)}catch{return null}}function at(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 hr(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 Qe(e,n);return{chainId:e,blockNumber:s?.blockNumber??s,evidence:g.LIVE}},async nativeBalance(n,s={}){let o=await Ye(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 Xe({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,u,c]=await Promise.all([r(n,ue.decimals,s).catch(()=>null),r(n,ue.symbol,s).catch(()=>null),r(n,ue.name,s).catch(()=>null),r(n,ue.totalSupply,s).catch(()=>null)]),l=st(o?.result??o),a=l!==null||i?.result||u?.result,p={chainId:e,address:n,decimals:l===null?null:Number(l),symbol:at(i?.result??i),name:at(u?.result??u),totalSupply:(st(c?.result??c)??null)?.toString()??null,evidence:a?g.LIVE:g.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:g.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await et(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=Ee(n,c,{stables:t.stableQuoteAssets||[],wrappedNative:t.wrappedNative});return{chainId:e,token:n,pools:l,topPool:l[0]||null,quoteAsset:Ze(n,l),evidence:l.length?g.LIVE:g.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 Me(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:g.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:g.LIVE}},async scoreRisk(n,s={}){let o=[],i=w.PASS,u=a=>{let p={[w.PASS]:0,[w.CAUTION]:1,[w.UNKNOWN]:2,[w.FAIL]:3};p[a]>p[i]&&(i=a)},[c,l]=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}),u(w.UNKNOWN)):o.push({check:"erc20-metadata",result:w.PASS,detail:`${c.symbol} / ${c.decimals}d`}),l.evidence===g.UNAVAILABLE)o.push({check:"liquidity",result:w.UNKNOWN,detail:l.reason}),u(w.UNKNOWN);else if(!l.pools.length)o.push({check:"liquidity",result:w.FAIL,detail:"no pool with liquidity found"}),u(w.FAIL);else{let a=l.pools[0],p=a.liquidityUsd??0;p<5e3?(o.push({check:"liquidity",result:w.CAUTION,detail:`top pool only $${p}`}),u(w.CAUTION)):o.push({check:"liquidity",result:w.PASS,detail:`$${p} on ${a.dex}`}),a.createdAt&&Date.now()-a.createdAt<24*3600*1e3&&(o.push({check:"age",result:w.CAUTION,detail:"pool under 24h old"}),u(w.CAUTION))}if(typeof this.sellSimulation=="function"){let a=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},s).catch(p=>({verdict:w.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: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."}),u(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 Ie(t){let r={...hr(t)},n=new Set((t.venues||[]).map(o=>o.kind));t.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,ot({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,tt({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 Oe=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 mr(){return Oe.map(t=>de(Ie(t)))}function br(t){return de(Ie(t))}export{Oe as CHAIN_CONFIGS,g as EVIDENCE,w as RISK,J as SCANNER_CAPABILITIES,gr as __clearScanners,ft as createScanner,yr as getScanner,wr as listScanners,mr as registerBuiltinScanners,br as registerCustomChain,de as registerScanner,vr as scannerCoverage,pt as validateScanner};
6
+ ${JSON.stringify(r??[])}`}async function nr(t,e,r){return ce(t,{method:"POST",body:e,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function $(t,e,r=[],n={}){let s=String(e||""),o=Zt(s),i=Xt(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=Ge.get(i);if(a!=null)return a}let c=n.dedupe!==!1&&!n.signal?rr(i,s,r):null;if(c&&ee.has(c))return ee.get(c);let l=(async()=>{let a=await nr(i,{jsonrpc:"2.0",id:1,method:e,params:r},n),p=tr(a);return o==="eth_chainid"&&typeof p=="string"&&Ge.set(i,p),p})();return c&&(ee.set(c,l),l.finally(()=>{ee.get(c)===l&&ee.delete(c)}).catch(()=>{})),l}async function Qe(t,e={}){let r=await $(t,"eth_blockNumber",[],e);return parseInt(r,16)}async function Ye(t,e,r={}){if(!e)throw new Error("rpcGetBalance requires address");let n=await $(t,"eth_getBalance",[e,"latest"],r);return{chainId:Number(t),address:e,balanceWei:BigInt(n).toString(),balanceHex:n}}async function Xe(t={},e={}){let r=Number(t.chainId??e.chainId??1),n=Ke(t.token||t.tokenAddress,"token"),s=Ke(t.account||t.owner||t.address,"account"),o=We.encodeFunctionData("balanceOf",[s]),i=await $(r,"eth_call",[{to:n,data:o},t.blockTag||"latest"],e),u=We.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 or=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"]);function Je(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 Ee(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=Je(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)||or.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 Ze(t,e=[]){let r=Array.isArray(e)?e:[];return r.length&&Je(t,r[0]).address||null}var sr="https://api.dexscreener.com",Vr=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function ar(t={}){return(t.baseUrl||process.env.DEXSCREENER_API_URL||sr).replace(/\/$/,"")}function ir(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 cr(t,e){return ce(`${ar(e)}${t}`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}async function et(t,e={}){return cr(`/latest/dex/tokens/${ir(t,"tokenAddress")}`,e)}var Ae={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},q=t=>BigInt(t).toString(16).padStart(64,"0"),te=t=>t.slice(2).toLowerCase().padStart(64,"0");function ur(t,e){return`0x${Ae.getAmountsOut}`+q(t)+q(64)+q(e.length)+e.map(te).join("")}function lr(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 Se(t,e="router"){return(t?.venues||[]).find(n=>n.kind===e)?.address??null}var xe=100;function dr(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>xe)throw new Error(`slippageBps ${r} exceeds the ${xe} 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 tt(t){let{chainId:e,wrappedNative:r}=t;async function n(s,o,i,u){let c=await $(e,"eth_call",[{to:s,data:ur(o,i)},"latest"],u);return lr(c?.result??c)}return{async quote({tokenIn:s,tokenOut:o,amountIn:i,path:u},c={}){let l=Se(c.scanner);if(!l)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=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:g.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:e,router:l,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},u={}){let c=Se(u.scanner),l=i||r;if(l&&String(s).toLowerCase()===String(l).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||!l)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,[l,s],u);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 p=a[a.length-1];if(p===0n)return{chainId:e,token:s,verdict:w.FAIL,evidence:g.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:w.FAIL,evidence:g.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=w.PASS,b="round trip completes with expected fee/impact loss";return d<5e3?(m=w.FAIL,b=`round trip returns only ${(d/100).toFixed(2)}% -- punitive tax or no real liquidity`):d<9e3&&(m=w.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: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:u,slippageBps:c=50,deadlineSeconds:l=900,path:a},p={}){let h=p.scanner,f=Se(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!==g.LIVE)throw new Error(`cannot prepare without a live quote (${m.evidence}: ${m.reason??"no reason given"})`);let b=dr(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)),k=r&&d[0].toLowerCase()===r.toLowerCase()&&p.useNative,P=k?`0x${Ae.swapExactETHForTokens}`+q(b)+q(128)+te(u)+q(E)+q(d.length)+d.map(te).join(""):`0x${Ae.swapExactTokensForTokens}`+q(i)+q(b)+q(160)+te(u)+q(E)+q(d.length)+d.map(te).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:e,tx:{to:f,data:P,value:k?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:m.amountOut,minOut:b.toString(),slippageBps:c,maxSlippageBps:xe,deadline:E.toString()},requires:k?[]:[{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 pr=[100,500,3e3,1e4],rt={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},W=t=>BigInt(t).toString(16).padStart(64,"0"),re=t=>t.slice(2).toLowerCase().padStart(64,"0"),nt=/^0x[0-9a-fA-F]{40}$/,Te=100;function fr(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Te)throw new Error(`slippageBps ${r} exceeds the ${Te} 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 Ce(t,e){return(t?.venues||[]).find(r=>r.kind===e)?.address??null}function ot(t){let{chainId:e,wrappedNative:r}=t;async function n({quoter:o,tokenIn:i,tokenOut:u,amountIn:c,fee:l},a){let p=`0x${rt.quoteExactInputSingle}`+re(i)+re(u)+W(c)+W(l)+W(0),h=await $(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(pr.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=Ce(c.scanner,"quoter");if(!l)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 h of[o,i])if(!nt.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:g.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: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:u},c={}){let l=Ce(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: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 d=u||p||(a[0]&&h!==a[0]?a[0]:null)||r;if(d&&h===String(d).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(!l||!d)return{chainId:e,token:o,verdict:w.UNKNOWN,evidence:g.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)),R=w.PASS,y="round trip vs dollar book completes with expected fee/impact loss";return S<5e3?(R=w.FAIL,y=`round trip vs dollar book returns only ${(S/100).toFixed(2)}% -- punitive tax or no real liquidity`):S<9e3&&(R=w.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:R,reason:y,amountIn:String(i),bought:C.best.amountOut.toString(),returned:T.toString(),retentionBps:S,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 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)),R=w.PASS,y="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return S<5e3?(R=w.FAIL,y=`dollar-book round trip returns only ${(S/100).toFixed(2)}%`):S<9e3&&(R=w.CAUTION,y=`dollar-book round trip returns ${(S/100).toFixed(2)}%`),{chainId:e,venue:"uniswap-v3",token:o,base:O,quoteAsset:O,verdict:R,reason:y,amountIn:String(i),bought:C.best.amountOut.toString(),returned:T.toString(),retentionBps:S,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: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,k=Number(E*10000n/BigInt(i)),P=w.PASS,L="round trip completes with expected fee/impact loss";return k<5e3?(P=w.FAIL,L=`round trip returns only ${(k/100).toFixed(2)}% -- punitive tax or no real liquidity`):k<9e3&&(P=w.CAUTION,L=`round trip returns ${(k/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:d,verdict:P,reason:L,amountIn:String(i),bought:m.best.amountOut.toString(),returned:E.toString(),retentionBps:k,buyFee:m.best.fee,sellFee:b.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:u,recipient:c,slippageBps:l=50,fee:a},p={}){let h=Ce(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(!nt.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!==g.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let d=a??f.fee,m=fr(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${rt.exactInputSingle}`+re(o)+re(i)+W(d)+re(c)+W(u)+W(m)+W(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:Te,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 ue={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function st(t){if(!t||t==="0x")return null;try{return BigInt(t)}catch{return null}}function at(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 hr(t){let{chainId:e}=t;async function r(n,s,o){return $(e,"eth_call",[{to:n,data:s},"latest"],o)}return{async blockNumber(n={}){let s=await Qe(e,n);return{chainId:e,blockNumber:s?.blockNumber??s,evidence:g.LIVE}},async nativeBalance(n,s={}){let o=await Ye(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 Xe({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,u,c]=await Promise.all([r(n,ue.decimals,s).catch(()=>null),r(n,ue.symbol,s).catch(()=>null),r(n,ue.name,s).catch(()=>null),r(n,ue.totalSupply,s).catch(()=>null)]),l=st(o?.result??o),a=l!==null||i?.result||u?.result,p={chainId:e,address:n,decimals:l===null?null:Number(l),symbol:at(i?.result??i),name:at(u?.result??u),totalSupply:(st(c?.result??c)??null)?.toString()??null,evidence:a?g.LIVE:g.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:g.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await et(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=Ee(n,c,{stables:t.stableQuoteAssets||[],wrappedNative:t.wrappedNative});return{chainId:e,token:n,pools:l,topPool:l[0]||null,quoteAsset:Ze(n,l),evidence:l.length?g.LIVE:g.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 Me(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 $(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:g.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:g.LIVE}},async scoreRisk(n,s={}){let o=[],i=w.PASS,u=a=>{let p={[w.PASS]:0,[w.CAUTION]:1,[w.UNKNOWN]:2,[w.FAIL]:3};p[a]>p[i]&&(i=a)},[c,l]=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}),u(w.UNKNOWN)):o.push({check:"erc20-metadata",result:w.PASS,detail:`${c.symbol} / ${c.decimals}d`}),l.evidence===g.UNAVAILABLE)o.push({check:"liquidity",result:w.UNKNOWN,detail:l.reason}),u(w.UNKNOWN);else if(!l.pools.length)o.push({check:"liquidity",result:w.FAIL,detail:"no pool with liquidity found"}),u(w.FAIL);else{let a=l.pools[0],p=a.liquidityUsd??0;p<5e3?(o.push({check:"liquidity",result:w.CAUTION,detail:`top pool only $${p}`}),u(w.CAUTION)):o.push({check:"liquidity",result:w.PASS,detail:`$${p} on ${a.dex}`}),a.createdAt&&Date.now()-a.createdAt<24*3600*1e3&&(o.push({check:"age",result:w.CAUTION,detail:"pool under 24h old"}),u(w.CAUTION))}if(typeof this.sellSimulation=="function"){let a=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},s).catch(p=>({verdict:w.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: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."}),u(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 Ie(t){let r={...hr(t)},n=new Set((t.venues||[]).map(o=>o.kind));t.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,ot({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,tt({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 Oe=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 mr(){return Oe.map(t=>de(Ie(t)))}function br(t){return de(Ie(t))}export{Oe as CHAIN_CONFIGS,g as EVIDENCE,w as RISK,J as SCANNER_CAPABILITIES,gr as __clearScanners,ft as createScanner,yr as getScanner,wr as listScanners,mr as registerBuiltinScanners,br as registerCustomChain,de as registerScanner,vr as scannerCoverage,pt as validateScanner};