@oracle-agent/oracle 0.35.25 → 0.35.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/bin/desk-server.mjs +35 -35
- package/dist/bin/oracle-data-mcp.mjs +20 -20
- package/dist/bin/oracle-launch-radar-shadow.mjs +21 -0
- package/dist/bin/oracle-route.mjs +20 -20
- package/dist/bin/oracle-scan.mjs +1 -1
- package/dist/cli/commands/chat.mjs +185 -184
- package/dist/cli/commands/doctor.mjs +1 -1
- package/dist/cli/commands/eval.mjs +1 -1
- package/dist/cli/commands/model.mjs +188 -187
- package/dist/cli/commands/snipe.mjs +1 -1
- package/dist/cli/commands/swap.mjs +32 -32
- package/dist/data/desk-data.mjs +33 -33
- package/dist/data/providers/lp-destination-discovery.mjs +4 -4
- package/dist/index.mjs +49 -49
- package/dist/launch-radar/index.mjs +7 -0
- package/dist/router/index.mjs +3 -3
- package/dist/router/prepare-bridge.mjs +2 -2
- package/dist/scanner/index.mjs +1 -1
- package/dist/teams/index.mjs +1 -0
- package/package.json +4 -1
- package/public/eval-report.json +6 -6
- package/public/oracle-splash/index.html +2 -2
- package/server.json +2 -2
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var re=Object.freeze({PASS:"PASS",WARN:"WARN",BLOCK:"BLOCK",UNKNOWN:"UNKNOWN"}),Br=new Set(["LIVE","CACHED","STALE","UNKNOWN","UNAVAILABLE"]),ft=/^0x[0-9a-fA-F]{40}$/,qr=/^0x[0-9a-fA-F]{64}$/;function ee(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))ee(t);Object.freeze(e)}return e}function D(e,t=null){return e&&typeof e=="object"?structuredClone(e):t}function ht(e){return typeof e!="string"||!Number.isFinite(Date.parse(e))?null:new Date(e).toISOString()===e?e:null}function pt(e){return!!(e&&Br.has(e.evidence)&&ht(e.observedAt))}function mt(e){return!e||e.status!=="KNOWN"||e.amount===null||e.amount===void 0||e.amount===""?{status:"UNKNOWN",amount:null,unit:e?.unit??null}:{status:"KNOWN",amount:String(e.amount),unit:e.unit??null}}function he(e){return[...new Set(e.filter(Boolean))]}function Ur(e={}){let t=[],r=[],n=[];(e.venue?.supported!==!0||e.venue?.verified!==!0)&&t.push("unsupported venue"),e.signal?.unsolicitedAirdrop===!0&&t.push("unsolicited airdrop is not a held or eligible candidate"),e.risk?.verdict==="FAIL"&&t.push("risk verdict is FAIL"),e.sellability?.verdict==="FAIL"&&t.push("sellability verdict is FAIL"),e.route?.status==="BLOCK"&&t.push("route is blocked");for(let[s,i]of[["token",e.token],["venue",e.venue],["signal",e.signal],["risk",e.risk],["sellability",e.sellability],["route",e.route]])!pt(i)||i.evidence==="UNKNOWN"||i.evidence==="UNAVAILABLE"?r.push(`${s} evidence is missing or unavailable`):(i.evidence==="CACHED"||i.evidence==="STALE")&&n.push(`${s} evidence is ${i.evidence}`);(!e.pool||!pt(e.pool))&&r.push("pool evidence is missing or unavailable"),(!e.risk||!["PASS","CAUTION","FAIL"].includes(e.risk.verdict))&&r.push("risk verdict is UNKNOWN"),(!e.sellability||!["PASS","CAUTION","FAIL"].includes(e.sellability.verdict))&&r.push("sellability verdict is UNKNOWN"),(!e.route||!["PASS","WARN","BLOCK"].includes(e.route.status))&&r.push("route status is UNKNOWN"),mt(e.route?.cost).status==="UNKNOWN"&&r.push("route cost is UNKNOWN"),e.risk?.verdict==="CAUTION"&&n.push("risk verdict is CAUTION"),e.sellability?.verdict==="CAUTION"&&n.push("sellability verdict is CAUTION"),e.route?.status==="WARN"&&n.push("route status is WARN");let o=he(t);return o.length?ee({status:re.BLOCK,whyBlocked:o}):r.length?ee({status:re.UNKNOWN,whyBlocked:he(r)}):n.length?ee({status:re.WARN,whyBlocked:[],warnings:he(n)}):ee({status:re.PASS,whyBlocked:[]})}function $r(e={}){let t=D(e,{}),r=Object.fromEntries(Object.entries(t).map(([o,s])=>[o,ht(s)])),n=(o,s)=>r[o]&&r[s]?Math.max(0,Date.parse(r[s])-Date.parse(r[o])):null;return t.stagesMs={discoveryToRisk:n("discoveredAt","riskCompletedAt"),riskToSellability:n("riskCompletedAt","sellabilityCompletedAt"),sellabilityToRoute:n("sellabilityCompletedAt","routeCompletedAt"),routeToNormalized:n("routeCompletedAt","normalizedAt"),total:n("discoveredAt","normalizedAt")},t}function bt(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("candidate must be an object");let t=D(e.chain,{}),r=D(e.token,{}),n=D(e.pool),o=D(e.venue,{}),s=D(e.signal,{}),i=D(e.route,{});i.cost=mt(i.cost);let a=Ur({...e,chain:t,token:r,pool:n,venue:o,signal:s,route:i}),c=s.unsolicitedAirdrop===!0,d=ft.test(r.address||"")?r.address.toLowerCase():"unknown-token",l=ft.test(n?.address||"")?n.address.toLowerCase():qr.test(n?.poolId||"")?n.poolId.toLowerCase():"unknown-pool",u=`${Number.isInteger(t.id)?t.id:"unknown-chain"}:${d}:${l}:${o.key||"unknown-venue"}`;return ee({id:u,status:a.status,chain:t,token:r,pool:n,venue:o,signal:s,risk:D(e.risk,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),sellability:D(e.sellability,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),route:i,prepared:D(e.prepared,{status:"NOT_PREPARED",unsigned:!0}),whyBlocked:he([...e.whyBlocked||[],...a.whyBlocked]),latency:$r(e.latency),held:c?!1:e.held===!0,eligible:c?!1:a.status===re.PASS&&e.eligible!==!1})}function yt(e=[]){if(!Array.isArray(e))throw new TypeError("candidates must be an array");return Object.freeze(e.map(bt).sort((t,r)=>t.id.localeCompare(r.id)))}import{AbiCoder as Pr,keccak256 as Dr}from"ethers";var wt=/^0x[0-9a-fA-F]{40}$/,F=/^0x[0-9a-fA-F]{64}$/,Fr=Pr.defaultAbiCoder();function H(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))H(t);Object.freeze(e)}return e}function gt(e){return String(e?.message||e||"unknown scan failure").slice(0,300)}function z(e){if(Number.isInteger(e))return e;if(typeof e=="string"&&/^(?:0x[0-9a-f]+|[0-9]+)$/i.test(e)){let t=Number.parseInt(e,e.startsWith("0x")?16:10);return Number.isSafeInteger(t)?t:null}return null}function jr(e){if(!e||typeof e!="object")return"factory descriptor is invalid";if(!wt.test(e.factoryAddress||""))return`${e.id||"venue"}: verified factory address is required`;if(e.provenance?.verified!==!0)return`${e.id||"venue"}: factory provenance is unverified`;if(e.venue?.supported!==!0)return`${e.id||"venue"}: unsupported venue`;if(e.venue?.verified!==!0)return`${e.id||"venue"}: unverified venue`;if(!Number.isInteger(e.chainId)||e.chainId<=0)return`${e.id||"venue"}: invalid chainId`;if(!Array.isArray(e.events)||e.events.length===0)return`${e.id||"venue"}: no configured events`;for(let t of e.events){if(!F.test(t?.topic0||""))return`${e.id||"venue"}: invalid event signature`;if(t?.decoder==="uniswap-v4-initialize"){if(!Array.isArray(e.quoteAssets)||e.quoteAssets.length===0||e.quoteAssets.some(r=>!wt.test(r||"")))return`${e.id||"venue"}: at least one exact quote asset is required for V4 attribution`;continue}if(t?.decoder!=null)return`${e.id||"venue"}: unsupported event decoder`;for(let r of["token","pool"]){let n=t?.layout?.[r],o=n&&Number.isInteger(n.topic)&&n.topic>0,s=n&&Number.isInteger(n.dataWord)&&n.dataWord>=0;if(o===s)return`${e.id||"venue"}: invalid ${r} event layout`}}return null}function ne(e,t){let r;if(Number.isInteger(t.topic))r=e.topics?.[t.topic];else{let n=typeof e.data=="string"&&/^0x[0-9a-f]*$/i.test(e.data)?e.data.slice(2):"";r=n.length%64===0?`0x${n.slice(t.dataWord*64,t.dataWord*64+64)}`:null}return!F.test(r||"")||!/^0{24}[0-9a-f]{40}$/i.test(r.slice(2))?null:`0x${r.slice(-40)}`.toLowerCase()}function Et(e,t){let r=typeof e?.data=="string"&&/^0x[0-9a-f]*$/i.test(e.data)?e.data.slice(2):"";if(r.length%64!==0)return null;let n=r.slice(t*64,t*64+64);return n.length===64?`0x${n}`:null}function At(e,t,r){let n=Et(e,t);if(!F.test(n||""))return null;let o=BigInt(n);return o<1n<<BigInt(r)?o:null}function vt(e,t,r){let n=Et(e,t);if(!F.test(n||""))return null;let o=BigInt(r),s=(1n<<o)-1n,i=BigInt(n)&s,a=i&1n<<o-1n?i-(1n<<o):i;return Number(a)}function Mr(e,t,r){if(String(e?.address||"").toLowerCase()!==t.factoryAddress.toLowerCase()||!Array.isArray(e.topics)||e.topics.length!==4||String(e.topics[0]||"").toLowerCase()!==r.topic0.toLowerCase()||!F.test(e.topics[1]||"")||typeof e.data!="string"||e.data.length!==322)return null;let n=ne(e,{topic:2}),o=ne(e,{topic:3}),s=At(e,0,24),i=vt(e,1,24),a=ne(e,{dataWord:2}),c=At(e,3,160),d=vt(e,4,24),l=z(e.blockNumber),u=z(e.logIndex);if(!n||!o||s===null||i===null||!a||c===null||d===null||l===null||u===null||!F.test(e.transactionHash||""))return null;let f=new Set(t.quoteAssets.map(N=>N.toLowerCase())),p=f.has(n),h=f.has(o);if(p===h)return null;let m=p?o:n,b=p?n:o;if(Dr(Fr.encode(["address","address","uint24","int24","address"],[n,o,Number(s),i,a])).toLowerCase()!==e.topics[1].toLowerCase())return null;let I=e.transactionHash.toLowerCase();return{id:`${t.chainId}:${I}:${u}`,chainId:t.chainId,factoryId:t.id||null,factoryAddress:t.factoryAddress.toLowerCase(),tokenAddress:m,quoteAsset:b,poolAddress:null,poolId:e.topics[1].toLowerCase(),poolKey:{currency0:n,currency1:o,fee:Number(s),tickSpacing:i,hooks:a},sqrtPriceX96:c.toString(),tick:d,venue:structuredClone(t.venue),kind:r.kind||"pool-initialized",blockNumber:l,blockHash:F.test(e.blockHash||"")?e.blockHash.toLowerCase():null,transactionHash:I,logIndex:u,evidence:"LIVE"}}function Vr(e,t,r){if(String(e?.address||"").toLowerCase()!==t.factoryAddress.toLowerCase()||!Array.isArray(e.topics)||String(e.topics[0]||"").toLowerCase()!==r.topic0.toLowerCase())return null;let n=Object.values(r.layout).filter(f=>Number.isInteger(f.topic)).map(f=>f.topic),o=Object.values(r.layout).filter(f=>Number.isInteger(f.dataWord)).map(f=>f.dataWord),s=Math.max(0,...n)+1,i=Math.max(-1,...o)+1;if(e.topics.length!==s||!/^0x[0-9a-f]*$/i.test(e.data||"")||e.data.length!==2+i*64)return null;let a=ne(e,r.layout.token),c=ne(e,r.layout.pool),d=z(e.blockNumber),l=z(e.logIndex);if(!a||!c||d===null||l===null||!F.test(e.transactionHash||""))return null;let u=e.transactionHash.toLowerCase();return{id:`${t.chainId}:${u}:${l}`,chainId:t.chainId,factoryId:t.id||null,factoryAddress:t.factoryAddress.toLowerCase(),tokenAddress:a,poolAddress:c,venue:structuredClone(t.venue),kind:r.kind||"launch",blockNumber:d,blockHash:F.test(e.blockHash||"")?e.blockHash.toLowerCase():null,transactionHash:u,logIndex:l,evidence:"LIVE"}}function Hr(e,t,r){return r.decoder==="uniswap-v4-initialize"?Mr(e,t,r):Vr(e,t,r)}async function St(e={}){let{scanner:t,factories:r=[],reorgHint:n}=e;if(!t||typeof t.scanBlocks!="function")throw new TypeError("discovery requires an injected scanner.scanBlocks function");if(!Array.isArray(r))throw new TypeError("factories must be an array");let o=z(e.fromBlock??e.cursor?.nextBlock),s=z(e.toBlock);if(o===null||s===null||o<0||s<o)throw new TypeError("a valid integer block range is required");let i=H({nextBlock:z(e.cursor?.nextBlock)??o});if(n)return H({status:"UNKNOWN",discoveries:[],unavailable:[],cursor:i,whyBlocked:["reorg hint requires canonical range reconciliation"]});let a=[],c=[];for(let u of r){let f=jr(u);f?a.push({id:u?.id||null,status:"UNAVAILABLE",reason:f}):c.push(u)}if(c.sort((u,f)=>`${u.chainId}:${u.factoryAddress.toLowerCase()}:${u.id||""}`.localeCompare(`${f.chainId}:${f.factoryAddress.toLowerCase()}:${f.id||""}`)),a.sort((u,f)=>String(u.id).localeCompare(String(f.id))),c.length===0)return H({status:"UNAVAILABLE",discoveries:[],unavailable:a,cursor:i,whyBlocked:a.map(u=>u.reason)});let d=[];for(let u of c){let f=[...u.events].sort((m,b)=>m.topic0.localeCompare(b.topic0)),p=[...new Set(f.map(m=>m.topic0.toLowerCase()))].sort(),h;try{h=await t.scanBlocks({fromBlock:o,toBlock:s,address:u.factoryAddress,topics:[p]})}catch(m){return H({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`scan failed: ${gt(m)}`]})}if(!h||h.complete!==!0||h.evidence&&h.evidence!=="LIVE"){let m=Array.isArray(h?.failedAt)?` at ${h.failedAt.join("-")}`:"";return H({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`incomplete block range${m}${h?.error?`: ${gt(h.error)}`:""}`]})}for(let m of Array.isArray(h.logs)?h.logs:[]){let b=f.find(I=>I.topic0.toLowerCase()===String(m?.topics?.[0]||"").toLowerCase()),x=b&&Hr(m,u,b);x&&d.push(x)}}let l=new Map;for(let u of d.sort((f,p)=>f.id.localeCompare(p.id)))l.has(u.id)||l.set(u.id,u);return H({status:"LIVE",discoveries:[...l.values()],unavailable:a,cursor:{nextBlock:s+1},whyBlocked:a.map(u=>u.reason)})}import{createHash as zr}from"node:crypto";var It="sha256:"+"0".repeat(64);function ke(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))ke(t);Object.freeze(e)}return e}function xe(e){return Array.isArray(e)?`[${e.map(xe).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${xe(e[t])}`).join(",")}}`:JSON.stringify(e)}function xt(e){return`sha256:${zr("sha256").update(xe(e)).digest("hex")}`}function kt(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("evidence event must be an object");if(typeof e.id!="string"||e.id.length===0)throw new TypeError("evidence event id must be non-empty");if(typeof e.type!="string"||e.type.length===0)throw new TypeError("evidence event type must be non-empty");if(typeof e.at!="string"||!Number.isFinite(Date.parse(e.at))||new Date(e.at).toISOString()!==e.at)throw new TypeError("evidence event at must be an exact ISO instant");if(!e.data||typeof e.data!="object"||Array.isArray(e.data))throw new TypeError("evidence event data must be an object");return{sequence:t,id:e.id,type:e.type,at:e.at,data:structuredClone(e.data),previousDigest:r}}function Ne(e=[]){if(!Array.isArray(e))throw new TypeError("evidence records must be an array");let t=new Set,r=It,n=e.map((o,s)=>{if(t.has(o?.id))throw new Error(`duplicate evidence event id: ${o.id}`);t.add(o?.id);let i=kt(o,s+1,r),a=xt(i);if(o.sequence!==s+1||o.previousDigest!==r||o.digest!==a)throw new Error(`evidence digest chain mismatch at sequence ${s+1}`);return r=a,{...i,digest:a}});return ke(n)}function Ce(e=[],t){let r=Ne(e);if(r.some(s=>s.id===t?.id))throw new Error(`duplicate evidence event id: ${t.id}`);let n=r.at(-1)?.digest??It,o=kt(t,r.length+1,n);return ke([...r,{...o,digest:xt(o)}])}import kr from"node:fs";import bo from"node:os";import ct from"node:path";import{createHash as Ct}from"node:crypto";import W from"node:net";import Wr from"node:dns";var Kr=new Set(["localhost","metadata.google.internal","metadata.goog"]);function me(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=l=>{if(!l)return[];let u=l.split(":"),f=u.at(-1);if(f?.includes(".")){let p=f.split(".").map(Number);if(p.length!==4||p.some(h=>!Number.isInteger(h)||h<0||h>255))return null;u.splice(u.length-1,1,(p[0]<<8|p[1]).toString(16),(p[2]<<8|p[3]).toString(16))}return u.some(p=>!/^[0-9a-f]{1,4}$/.test(p))?null:u.map(p=>Number.parseInt(p,16))},[n,o]=t.split("::"),s=r(n),i=r(o);if(!s||!i)return null;let a=t.includes("::"),c=8-s.length-i.length;if(!a&&c!==0||a&&c<1)return null;let d=[...s,...Array(Math.max(0,c)).fill(0),...i];return d.length!==8?null:Uint8Array.from(d.flatMap(l=>[l>>8,l&255]))}function Oe(e,t,r){let n=Math.floor(r/8),o=r%8;for(let i=0;i<n;i+=1)if(e[i]!==t[i])return!1;if(!o)return!0;let s=255<<8-o;return(e[n]&s)===(t[n]&s)}function Le(e){if(W.isIPv4(e)){let t=e.split(".").map(Number);return!(t[0]===0||t[0]===10||t[0]===127||t[0]>=224||t[0]===100&&t[1]>=64&&t[1]<=127||t[0]===169&&t[1]===254||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&(t[1]===0||t[1]===2||t[1]===168)||t[0]===192&&t[1]===88&&t[2]===99||t[0]===198&&(t[1]===18||t[1]===19||t[1]===51)||t[0]===203&&t[1]===0&&t[2]===113)}if(W.isIPv6(e)){let t=me(e);if(!t)return!1;let r=me("::ffff:0:0");return Oe(t,r,96)?Le([...t.slice(12)].join(".")):Oe(t,me("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([o,s])=>Oe(t,me(o),s)):!1}return!1}function Gr(e){let t;try{t=new URL(String(e))}catch{return{ok:!1,error:`not a valid URL: ${String(e).slice(0,120)}`}}if(t.protocol!=="http:"&&t.protocol!=="https:")return{ok:!1,error:`refused protocol ${t.protocol} (only http/https)`};let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(Kr.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=W.isIP(r);return n!==0&&!Le(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function Re(e,{lookupFn:t=Wr.promises.lookup}={}){let r=Gr(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:W.isIPv6(r.host)?6:4}]};let n;try{n=await t(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(o=>!Le(o.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function Te({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n;try{let u=await t();r=u.Agent,n=u.fetch}catch(u){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${u?.message||u}`);return null}if(typeof r!="function"||typeof n!="function"){if(e)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=u=>String(u).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),s=new Map,i=u=>(Array.isArray(u)?u:[u]).map(f=>typeof f=="string"?{address:f}:f).filter(f=>f&&f.address).map(f=>({address:f.address,family:f.family||(W.isIPv6(f.address)?6:4)})),a=(u,f,p)=>{s.set(o(u),i(typeof f=="string"?[{address:f,family:p}]:f))},c=u=>{let f=o(u);if(W.isIP(f))return[{address:f,family:W.isIPv6(f)?6:4}];let p=s.get(f);if(!p||!p.length)throw new Error(`refused: unpinned host ${u} during pinned fetch`);return p},d=new r({connect:{lookup(u,f,p){let h;try{h=c(u)}catch(m){return p(m)}return f?.all?p(null,h):p(null,h[0].address,h[0].family)}}}),l=Yr((u,f={})=>n(u,{...f,dispatcher:d}),a);return{dispatcher:d,fetch:l,pin:a,resolve:c,async close(){try{await d.destroy()}catch{}}}}var _e=Symbol.for("oracle.egressGuard.pinCapableFetch");function Yr(e,t){if(typeof e!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof t!="function")throw new Error("markPinCapableFetch: pin must be a function");return e[_e]=Object.freeze({pin:t}),e}function Be(e){return typeof e=="function"&&typeof e[_e]?.pin=="function"}function Nt(e,t,r){if(!Be(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[_e].pin(t,r)}var Qr=new Set([408,425,429,500,502,503,504]),Ot=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Jr=2,Lt=4e3,qt=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],Xr=new Set([301,302,303,307,308]),Rt=3,Zr=64*1024;function en(e){let t=String(e||"").toLowerCase();return qt.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function tn(e){let t={};for(let[r,n]of Object.entries(e||{}))en(r)||(t[r]=n);return t}function rn(e,t){if(!e)throw new Error(`HTTP redirect from ${t} missing Location`);let r=new URL(String(e),String(t));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${t} used unsupported protocol ${r.protocol}`);return r.toString()}function nn(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}var qe=new Map,on=/(?:^|_)(send|submit|broadcast|sign|requestAirdrop)(?=[A-Z_]|$)/i,sn=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function Tt(e){let t=String(e?.method||"");return t?!on.test(t):!1}function an(e,t){if(e==="GET"&&t==null)return!0;if(e!=="POST"||t==null)return!1;let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch{return!1}return Array.isArray(r)?r.length>0&&r.every(Tt):!r||typeof r!="object"?!1:r.jsonrpc&&r.method?Tt(r):typeof r.type=="string"&&sn.has(r.type)&&r.action==null&&r.signature==null&&r.nonce==null}function cn(e,t,r,n={},o=null){let s={};for(let[f,p]of Object.entries(r||{}))s[f.toLowerCase()]=p;let i=Object.keys(s).filter(f=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(f)),c=[...new Set([...qt,...i])].sort().map(f=>`${f}=${s[f]??""}`).join(`
|
|
3
|
+
`),d=Ct("sha256").update(c).digest("hex").slice(0,32),l=`${n.untrustedUrl?"untrusted":"trusted"}:${n.maxResponseBytes??"unbounded"}`,u=o==null?"-":Ct("sha256").update(String(o)).digest("hex").slice(0,32);return`${e} ${t} ${l} ${d} ${u}`}function un(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Lt):Math.min(250*2**e,Lt)+Math.floor(Math.random()*100)}var dn=e=>new Promise(t=>setTimeout(t,e));function oe(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function Ue(e,t,r){return oe(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function se(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function ln(e){return e?e.byteLength??e.length??0:0}async function _t(e,t,{url:r,truncate:n=!1,onOversize:o}={}){if(t==null)return await e.text();let s=Number(e.headers?.get?.("content-length"));if(Number.isFinite(s)&&s>t&&(se(e),!n))throw Ue(r,`content-length ${s}`,t);let i=e.body?.getReader?.();if(!i){let u=await e.text(),f=Buffer.byteLength(u,"utf8");if(f>t){if(!n)throw Ue(r,`body ${f} bytes`,t);return Buffer.from(u,"utf8").subarray(0,t).toString("utf8")}return u}let a=[],c=0,d=!1;try{for(;;){let{value:u,done:f}=await i.read();if(f)break;if(u&&(a.push(Buffer.from(u)),c+=ln(u),c>t)){d=!0;break}}}finally{if(d)try{await i.cancel()}catch{}try{i.releaseLock?.()}catch{}}if(d&&(typeof o=="function"&&o(),!n))throw Ue(r,`streamed ${c} bytes`,t);let l=Buffer.concat(a);return(d?l.subarray(0,t):l).toString("utf8")}function Bt(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function fn(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:s,lookupFn:i,realFetch:a,untrustedUrl:c=!1,maxResponseBytes:d=null,importUndici:l,validateResponse:u,signal:f}){let p=new AbortController,h=setTimeout(()=>p.abort(),s),m=f?typeof AbortSignal.any=="function"?AbortSignal.any([f,p.signal]):f:p.signal,b=null,x=t,I=i?{lookupFn:i}:{};if(c&&!a&&!Be(x))throw oe(`HTTP refused ${e}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let N=async(v,{status:w=null}={})=>{let A=await Re(v,I);if(!A.ok)throw oe(w==null?`HTTP refused ${v}: ${A.error}`:`HTTP redirect to ${v} ${A.error}`,w==null?{}:{status:w});let E=new URL(v).hostname;if(a){if(b&&(await b.close(),b=null),!b)try{b=await Te({requireUndici:!0,...l?{importUndici:l}:{}})}catch(k){throw oe(w==null?`HTTP refused ${v}: ${k?.message||k}`:`HTTP redirect to ${v} refused: ${k?.message||k}`,w==null?{}:{status:w})}b.pin(E,A.addresses),x=b.fetch}else Nt(x,E,A.addresses);return A};try{let v=String(e),w={...n||{}};c&&await N(v);for(let A=0;A<=Rt;A+=1){let E=await x(v,{method:r,headers:w,body:o,signal:m,redirect:"manual"});if(Xr.has(E.status)){if(r!=="GET"&&r!=="HEAD"){let y=await _t(E,d??Zr,{url:v,truncate:!0}),O=new Error(`HTTP ${E.status} ${r} ${v} redirected non-idempotent request`);throw O.status=E.status,O.body=Bt(y)??y.slice(0,300),O}if(A===Rt)throw se(E),new Error(`HTTP redirect loop for ${e}`);let C=E.headers?.get?.("location"),_;try{_=rn(C,v)}catch(y){throw se(E),y}let M=!nn(_,v);if(se(E),M&&(w=tn(w)),c)await N(_,{status:E.status});else if(M){let y=await Re(_,I);if(!y.ok){let O=new Error(`HTTP redirect from ${v} ${y.error}`);throw O.status=E.status,O.retryable=!1,O}a&&y.addresses?.length&&(b||(b=await Te(l?{importUndici:l}:{})),b&&(b.pin(new URL(_).hostname,y.addresses),x=b.fetch))}v=_;continue}if(typeof u=="function")try{await u(E,{url:v})}catch(C){throw se(E),oe(C?.message||String(C))}let k=await _t(E,d,{url:v,onOversize:()=>p.abort()}),R=Bt(k);if(!E.ok){let C=new Error(`HTTP ${E.status} ${r} ${v}`);throw C.status=E.status,C.retryAfter=E.headers?.get?.("retry-after")??null,C.body=R??k.slice(0,300),C}return R??k}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(h),b&&await b.close()}}async function be(e,t={}){let r=t.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=t.timeoutMs??12e3,o=(t.method||"GET").toUpperCase(),s={Accept:"application/json",...t.headers||{}},i=t.body;i!=null&&typeof i!="string"&&(s["Content-Type"]=s["Content-Type"]||"application/json",i=JSON.stringify(i));let a=Number.isInteger(t.retries)?Math.max(t.retries,0):Jr,c=t.lookupFn,d=!t.fetchImpl,l=t.untrustedUrl===!0,u=t.importUndici,f=t.validateResponse,p=t.signal,h=Number(t.maxResponseBytes),m=Number.isFinite(h)&&h>0?Math.floor(h):null,b=async()=>{let w;for(let A=0;A<=a;A++){p?.throwIfAborted?.();try{return await fn(e,{fetchImpl:r,method:o,headers:s,body:i,timeoutMs:n,lookupFn:c,realFetch:d,untrustedUrl:l,maxResponseBytes:m,importUndici:u,validateResponse:f,signal:p})}catch(E){w=E;let k=E?.status,R=E?.name==="AbortError"||E?.name==="TimeoutError"||p?.aborted,C=new Set([408,425,429]),_=E?.retryable===!1?!1:k!=null?C.has(k)||Qr.has(k)&&Ot.has(o):!R&&Ot.has(o);if(A===a||!_)throw E;let M=un(A,E?.retryAfter);p?await new Promise((y,O)=>{let V=setTimeout(y,M);p.addEventListener("abort",()=>{clearTimeout(V),O(p.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await dn(M)}}throw w};if(!(t.dedupe!==!1&&!p&&an(o,i)))return b();let I=cn(o,e,s,{untrustedUrl:l,maxResponseBytes:m},i),N=qe.get(I);if(N)return N;let v=b().finally(()=>qe.delete(I));return qe.set(I,v),v}async function Ut(e,t,r){let n=Array.from(e),o=Math.max(1,Math.min(Number(t)||1,n.length||1)),s=new Array(n.length),i=0;return await Promise.all(Array.from({length:o},async()=>{for(;i<n.length;){let a=i++;s[a]=await r(n[a],a)}})),s}var $t={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}},pn=new Map(Object.values($t).map(e=>[e.chainId,e]));function Pt(e){return pn.get(Number(e))||null}function Dt(e,t=process.env){let r=Pt(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}import{Interface as hn,getAddress as mn}from"ethers";var Ft=new hn(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function jt(e,t){try{return mn(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}var bn={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 yn(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=Dt(e,r);return n||bn[Number(e)]||null}var wn=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function gn(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!wn.test(r))throw new Error(`evm-rpc: ${t} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}var ie=new Map,Mt=new Map;function An(e){let t=new Error(e?.message||JSON.stringify(e));return t.code=e?.code,t}function vn(e){if(e?.error)throw An(e.error);return e?.result}function En(e,t,r){return`${e}
|
|
4
|
+
${t}
|
|
5
|
+
${JSON.stringify(r??[])}`}async function Sn(e,t,r){return be(e,{method:"POST",body:t,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function B(e,t,r=[],n={}){let o=String(t||""),s=gn(o),i=yn(e,n);if(!i)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);if(s==="eth_chainid"&&n.cacheChainId!==!1){let l=Mt.get(i);if(l!=null)return l}let c=n.dedupe!==!1&&!n.signal?En(i,o,r):null;if(c&&ie.has(c))return ie.get(c);let d=(async()=>{let l=await Sn(i,{jsonrpc:"2.0",id:1,method:t,params:r},n),u=vn(l);return s==="eth_chainid"&&typeof u=="string"&&Mt.set(i,u),u})();return c&&(ie.set(c,d),d.finally(()=>{ie.get(c)===d&&ie.delete(c)}).catch(()=>{})),d}async function Vt(e,t={}){let r=await B(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function Ht(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await B(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function zt(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=jt(e.token||e.tokenAddress,"token"),o=jt(e.account||e.owner||e.address,"account"),s=Ft.encodeFunctionData("balanceOf",[o]),i=await B(r,"eth_call",[{to:n,data:s},e.blockTag||"latest"],t),a=Ft.decodeFunctionResult("balanceOf",i),c=BigInt(a[0]);return{chainId:r,token:n,account:o,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:e.blockTag||"latest"}}var In=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"]);function Wt(e,t){let r=String(e||"").toLowerCase(),n=String(t?.quote||t?.quoteToken?.address||"").toLowerCase(),o=String(t?.base||t?.baseToken?.address||"").toLowerCase();return n===r?{address:t.base||t.baseToken?.address,symbol:t.baseToken?.symbol}:o===r?{address:t.quote||t.quoteToken?.address,symbol:t.quoteToken?.symbol}:{address:t.quote||t.quoteToken?.address,symbol:t.quoteToken?.symbol}}function $e(e,t=[],{stables:r=[],wrappedNative:n=null}={}){let o=String(e||"").toLowerCase(),s=new Set((r||[]).map(c=>String(c).toLowerCase())),i=String(n||"").toLowerCase(),a=(t||[]).map((c,d)=>{let l=Wt(o,c),u=String(l.address||"").toLowerCase(),f=String(l.symbol||"").toLowerCase(),p=Number(c.liquidityUsd??c.liquidity?.usd),h=Number.isFinite(p)?p:0,m=String(c.dex||c.dexId||"").toLowerCase(),b=0;return s.has(u)||In.has(f)?b=300:i&&u===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+h,index:d,otherAddr:u,liquidityUsd:h}});return a.sort((c,d)=>d.score-c.score||c.index-d.index),a.map(c=>c.pool)}function Kt(e,t=[]){let r=Array.isArray(t)?t:[];return r.length&&Wt(e,r[0]).address||null}var xn="https://api.dexscreener.com",es=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function kn(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||xn).replace(/\/$/,"")}async function Gt(e,t={}){if(!e)throw new Error("tokenAddress required");return be(`${kn(t)}/latest/dex/tokens/${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}var ye=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),S=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),g=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),Nn=/^0x[0-9a-fA-F]{40}$/;function Cn(e={}){let t=[],r=[];if(!e||typeof e!="object")return{ok:!1,errors:["definition must be an object"],warnings:r};if((!Number.isInteger(e.chainId)||e.chainId<=0)&&t.push("chainId must be a positive integer"),(typeof e.key!="string"||!/^[a-z][a-z0-9-]*$/.test(e.key||""))&&t.push('key must be a lowercase slug (e.g. "base")'),(typeof e.name!="string"||!e.name.trim())&&t.push("name is required"),!Array.isArray(e.rpcEnv)||e.rpcEnv.length===0)t.push("rpcEnv must list at least one environment variable name");else for(let o of e.rpcEnv)(typeof o!="string"||!/^[A-Z][A-Z0-9_]*$/.test(o))&&t.push(`rpcEnv entry "${o}" should be an UPPER_SNAKE env var name`);if(e.nativeCurrency){let o=e.nativeCurrency;(typeof o.symbol!="string"||!o.symbol)&&t.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(o.decimals)||t.push("nativeCurrency.decimals must be an integer")}for(let[o,s]of(e.venues||[]).entries()){let i=`venues[${o}]`;if(!s||typeof s!="object"){t.push(`${i} must be an object`);continue}Nn.test(s.address||"")||t.push(`${i}.address is not a valid 20-byte address`),/^0x0{40}$/.test(s.address||"")&&t.push(`${i}.address is the zero address -- placeholder left in place?`),s.kind||t.push(`${i}.kind is required (router|quoter|factory|...)`),s.verified?(s.verified.method||t.push(`${i}.verified.method is required`),s.verified.source||t.push(`${i}.verified.source is required`),s.verified.date||r.push(`${i}.verified.date missing -- add one so staleness is visible`)):t.push(`${i} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let n=e.capabilities||{};for(let o of Object.keys(n))ye.includes(o)?typeof n[o]!="function"&&t.push(`capability "${o}" must be a function`):t.push(`unknown capability "${o}"`);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:t.length===0,errors:t,warnings:r}}function On(e){let{ok:t,errors:r,warnings:n}=Cn(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
|
|
6
|
+
- ${r.join(`
|
|
7
|
+
- `)}`);let o=e.capabilities||{},s=ye.filter(a=>typeof o[a]=="function"),i={key:e.key,chainId:e.chainId,name:e.name,rpcEnv:[...e.rpcEnv],nativeCurrency:e.nativeCurrency?{...e.nativeCurrency}:null,wrappedNative:e.wrappedNative||null,explorer:e.explorer||null,venues:(e.venues||[]).map(a=>({...a})),warnings:n,capabilities(){return{chainId:e.chainId,key:e.key,supported:[...s],unsupported:ye.filter(a=>!s.includes(a))}},supports(a){return s.includes(a)}};for(let a of ye)s.includes(a)?i[a]=async(...c)=>o[a](...c,{scanner:i}):i[a]=async()=>{throw new Error(`${e.key} (chain ${e.chainId}) does not implement "${a}". Supported: ${s.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 Yt=new Map;function Qt(e){let t=On(e);return Yt.set(t.chainId,t),t}function Jt(e){return Yt.get(Number(e))||null}var De={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},$=e=>BigInt(e).toString(16).padStart(64,"0"),ae=e=>e.slice(2).toLowerCase().padStart(64,"0");function Ln(e,t){return`0x${De.getAmountsOut}`+$(e)+$(64)+$(t.length)+t.map(ae).join("")}function Rn(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length<128)return null;let r=Number(BigInt(`0x${t.slice(64,128)}`));if(!Number.isFinite(r)||r<1||r>16)return null;let n=[];for(let o=0;o<r;o++){let s=128+o*64;if(t.length<s+64)return null;n.push(BigInt(`0x${t.slice(s,s+64)}`))}return n}function Pe(e,t="router"){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}var Fe=100;function Tn(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Fe)throw new Error(`slippageBps ${r} exceeds the ${Fe} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(r))/10000n}function Xt(e){let{chainId:t,wrappedNative:r}=e;async function n(o,s,i,a){let c=await B(t,"eth_call",[{to:o,data:Ln(s,i)},"latest"],a);return Rn(c?.result??c)}return{async quote({tokenIn:o,tokenOut:s,amountIn:i,path:a},c={}){let d=Pe(c.scanner);if(!d)return{chainId:t,evidence:S.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let l=a||[o,s];if(l.some(f=>!/^0x[0-9a-fA-F]{40}$/.test(f||"")))throw new Error("quote requires valid 20-byte addresses");let u=await n(d,i,l,c);return u?{chainId:t,router:d,path:l,amountIn:String(i),amountOut:u[u.length-1].toString(),hops:l.length-1,evidence:S.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:d,path:l,evidence:S.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:o,amountIn:s,base:i},a={}){let c=Pe(a.scanner),d=i||r;if(d&&String(o).toLowerCase()===String(d).toLowerCase())return{chainId:t,token:o,verdict:g.UNKNOWN,evidence:S.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!c||!d)return{chainId:t,token:o,verdict:g.UNKNOWN,evidence:S.UNAVAILABLE,reason:c?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let l=await n(c,s,[d,o],a);if(!l)return{chainId:t,token:o,verdict:g.FAIL,evidence:S.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let u=l[l.length-1];if(u===0n)return{chainId:t,token:o,verdict:g.FAIL,evidence:S.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let f=await n(c,u,[o,d],a);if(!f)return{chainId:t,token:o,verdict:g.FAIL,evidence:S.LIVE,leg:"sell",bought:u.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let p=f[f.length-1],h=Number(p*10000n/BigInt(s)),m=g.PASS,b="round trip completes with expected fee/impact loss";return h<5e3?(m=g.FAIL,b=`round trip returns only ${(h/100).toFixed(2)}% -- punitive tax or no real liquidity`):h<9e3&&(m=g.CAUTION,b=`round trip returns ${(h/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:o,base:d,router:c,verdict:m,reason:b,amountIn:String(s),bought:u.toString(),returned:p.toString(),retentionBps:h,evidence:S.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:s,amountIn:i,recipient:a,slippageBps:c=50,deadlineSeconds:d=900,path:l},u={}){let f=u.scanner,p=Pe(f);if(!p)throw new Error(`chain ${t} has no verified router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!/^0x[0-9a-fA-F]{40}$/.test(a||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let h=l||[o,s],m=await this.quote({tokenIn:o,tokenOut:s,amountIn:i,path:h},u);if(m.evidence!==S.LIVE)throw new Error(`cannot prepare without a live quote (${m.evidence}: ${m.reason??"no reason given"})`);let b=Tn(m.amountOut,c);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let x=BigInt(Math.floor(Date.now()/1e3)+Number(d)),I=r&&h[0].toLowerCase()===r.toLowerCase()&&u.useNative,N=I?`0x${De.swapExactETHForTokens}`+$(b)+$(128)+ae(a)+$(x)+$(h.length)+h.map(ae).join(""):`0x${De.swapExactTokensForTokens}`+$(i)+$(b)+$(160)+ae(a)+$(x)+$(h.length)+h.map(ae).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:p,data:N,value:I?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:m.amountOut,minOut:b.toString(),slippageBps:c,maxSlippageBps:Fe,deadline:x.toString()},requires:I?[]:[{step:"approve",token:h[0],spender:p,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 _n=[100,500,3e3,1e4],Zt={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},K=e=>BigInt(e).toString(16).padStart(64,"0"),ce=e=>e.slice(2).toLowerCase().padStart(64,"0"),er=/^0x[0-9a-fA-F]{40}$/,Me=100;function Bn(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Me)throw new Error(`slippageBps ${r} exceeds the ${Me} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(r))/10000n}function je(e,t){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function tr(e){let{chainId:t,wrappedNative:r}=e;async function n({quoter:s,tokenIn:i,tokenOut:a,amountIn:c,fee:d},l){let u=`0x${Zt.quoteExactInputSingle}`+ce(i)+ce(a)+K(c)+K(d)+K(0),f=await B(t,"eth_call",[{to:s,data:u},"latest"],l).catch(()=>null),p=f?.result??f;if(!p||p==="0x"||p.length<66)return null;let h=BigInt(`0x${p.slice(2,66)}`);return h>0n?h:null}async function o({quoter:s,tokenIn:i,tokenOut:a,amountIn:c},d){let l=await Promise.all(_n.map(async f=>{let p=await n({quoter:s,tokenIn:i,tokenOut:a,amountIn:c,fee:f},d);return{fee:f,amountOut:p?p.toString():null,out:p}})),u=null;for(let f of l)f.out&&(!u||f.out>u.amountOut)&&(u={fee:f.fee,amountOut:f.out});return{best:u,tried:l.map(({fee:f,amountOut:p})=>({fee:f,amountOut:p}))}}return{async quote({tokenIn:s,tokenOut:i,amountIn:a},c={}){let d=je(c.scanner,"quoter");if(!d)return{chainId:t,evidence:S.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let f of[s,i])if(!er.test(f||""))throw new Error("quote requires valid 20-byte addresses");let{best:l,tried:u}=await o({quoter:d,tokenIn:s,tokenOut:i,amountIn:a},c);return l?{chainId:t,venue:"uniswap-v3",quoter:d,tokenIn:s,tokenOut:i,amountIn:String(a),amountOut:l.amountOut.toString(),fee:l.fee,useNative:!!r&&String(s).toLowerCase()===String(r).toLowerCase(),triedFeeTiers:u,evidence:S.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:d,tokenIn:s,tokenOut:i,triedFeeTiers:u,evidence:S.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:s,amountIn:i,base:a},c={}){let d=je(c.scanner,"quoter"),l=(e.stableQuoteAssets||[]).map(w=>String(w).toLowerCase()),u=null;!a&&typeof e.resolveQuoteAsset=="function"&&(u=await e.resolveQuoteAsset(s,c).catch(()=>null));let f=String(s).toLowerCase(),p=String(r||"").toLowerCase();if(p&&f===p)return{chainId:t,token:s,verdict:g.UNKNOWN,evidence:S.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};let h=a||u||(l[0]&&f!==l[0]?l[0]:null)||r;if(h&&f===String(h).toLowerCase())return{chainId:t,token:s,verdict:g.UNKNOWN,evidence:S.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!d||!h)return{chainId:t,token:s,verdict:g.UNKNOWN,evidence:S.UNAVAILABLE,reason:d?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let m=await o({quoter:d,tokenIn:h,tokenOut:s,amountIn:i},c);if(!m.best){let w=l.find(A=>A&&A!==String(h).toLowerCase()&&A!==String(s).toLowerCase());if(w){let A=await o({quoter:d,tokenIn:w,tokenOut:s,amountIn:i},c);if(A.best){let E=await o({quoter:d,tokenIn:s,tokenOut:w,amountIn:A.best.amountOut},c);if(E.best){let k=E.best.amountOut,R=Number(k*10000n/BigInt(i)),C=g.PASS,_="round trip vs dollar book completes with expected fee/impact loss";return R<5e3?(C=g.FAIL,_=`round trip vs dollar book returns only ${(R/100).toFixed(2)}% -- punitive tax or no real liquidity`):R<9e3&&(C=g.CAUTION,_=`round trip vs dollar book returns ${(R/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:s,base:w,quoteAsset:w,verdict:C,reason:_,amountIn:String(i),bought:A.best.amountOut.toString(),returned:k.toString(),retentionBps:R,buyFee:A.best.fee,sellFee:E.best.fee,evidence:S.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:t,token:s,verdict:g.FAIL,evidence:S.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 o({quoter:d,tokenIn:s,tokenOut:h,amountIn:m.best.amountOut},c);if(!b.best){let w=l.find(A=>A&&A!==String(h).toLowerCase()&&A!==String(s).toLowerCase());if(w){let A=await o({quoter:d,tokenIn:w,tokenOut:s,amountIn:i},c),E=A.best?await o({quoter:d,tokenIn:s,tokenOut:w,amountIn:A.best.amountOut},c):{best:null};if(A.best&&E.best){let k=E.best.amountOut,R=Number(k*10000n/BigInt(i)),C=g.PASS,_="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return R<5e3?(C=g.FAIL,_=`dollar-book round trip returns only ${(R/100).toFixed(2)}%`):R<9e3&&(C=g.CAUTION,_=`dollar-book round trip returns ${(R/100).toFixed(2)}%`),{chainId:t,venue:"uniswap-v3",token:s,base:w,quoteAsset:w,verdict:C,reason:_,amountIn:String(i),bought:A.best.amountOut.toString(),returned:k.toString(),retentionBps:R,buyFee:A.best.fee,sellFee:E.best.fee,evidence:S.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:t,token:s,verdict:g.FAIL,evidence:S.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 x=b.best.amountOut,I=Number(x*10000n/BigInt(i)),N=g.PASS,v="round trip completes with expected fee/impact loss";return I<5e3?(N=g.FAIL,v=`round trip returns only ${(I/100).toFixed(2)}% -- punitive tax or no real liquidity`):I<9e3&&(N=g.CAUTION,v=`round trip returns ${(I/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:s,base:h,verdict:N,reason:v,amountIn:String(i),bought:m.best.amountOut.toString(),returned:x.toString(),retentionBps:I,buyFee:m.best.fee,sellFee:b.best.fee,evidence:S.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:s,tokenOut:i,amountIn:a,recipient:c,slippageBps:d=50,fee:l},u={}){let f=je(u.scanner,"router");if(!f)throw new Error(`chain ${t} has no verified V3 router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!er.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let p=await this.quote({tokenIn:s,tokenOut:i,amountIn:a},u);if(p.evidence!==S.LIVE)throw new Error(`cannot prepare without a live quote (${p.evidence}: ${p.reason??"no reason given"})`);let h=l??p.fee,m=Bn(p.amountOut,d);if(m<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=!!(u.useNative||p.useNative)&&r&&String(s).toLowerCase()===String(r).toLowerCase(),x=`0x${Zt.exactInputSingle}`+ce(s)+ce(i)+K(h)+ce(c)+K(a)+K(m)+K(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:f,data:x,value:b?String(a):"0x0"},guard:{quotedOut:p.amountOut,minOut:m.toString(),slippageBps:d,maxSlippageBps:Me,fee:h},requires:b?[]:[{step:"approve",token:s,spender:f,amount:String(a)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var we={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function rr(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function nr(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length>=128){let n=Number(BigInt(`0x${t.slice(64,128)}`));if(n>0&&n<=256&&t.length>=128+n*2){let o=t.slice(128,128+n*2),s=Buffer.from(o,"hex").toString("utf8").replace(/\0+$/,"");if(s)return s}}return Buffer.from(t.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function qn(e){let{chainId:t}=e;async function r(n,o,s){return B(t,"eth_call",[{to:n,data:o},"latest"],s)}return{async blockNumber(n={}){let o=await Vt(t,n);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:S.LIVE}},async nativeBalance(n,o={}){let s=await Ht(t,n,o);return{chainId:t,address:n,wei:s?.wei??s?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:S.LIVE}},async tokenBalance({token:n,owner:o},s={}){let i=await zt({chainId:t,token:n,owner:o},s);return{chainId:t,token:n,owner:o,raw:i?.balance??i,evidence:S.LIVE}},async resolveToken(n,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:t,token:n,evidence:S.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[s,i,a,c]=await Promise.all([r(n,we.decimals,o).catch(()=>null),r(n,we.symbol,o).catch(()=>null),r(n,we.name,o).catch(()=>null),r(n,we.totalSupply,o).catch(()=>null)]),d=rr(s?.result??s),l=d!==null||i?.result||a?.result,u={chainId:t,address:n,decimals:d===null?null:Number(d),symbol:nr(i?.result??i),name:nr(a?.result??a),totalSupply:(rr(c?.result??c)??null)?.toString()??null,evidence:l?S.LIVE:S.UNKNOWN};return l||(u.warning="no ERC-20 metadata returned -- may not be a token contract"),u},async resolvePools(n,o={}){let s=e.dexscreenerSlug;if(!s)return{chainId:t,token:n,pools:[],evidence:S.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await Gt(n,o).catch(()=>null),c=(i?.pairs||i?.data?.pairs||[]).filter(l=>String(l.chainId).toLowerCase()===String(s).toLowerCase()).map(l=>({pair:l.pairAddress,dex:l.dexId,base:l.baseToken?.address,quote:l.quoteToken?.address,liquidityUsd:l.liquidity?.usd??null,priceUsd:l.priceUsd??null,volume24hUsd:l.volume?.h24??null,createdAt:l.pairCreatedAt??null})).sort((l,u)=>(u.liquidityUsd??0)-(l.liquidityUsd??0)),d=$e(n,c,{stables:e.stableQuoteAssets||[],wrappedNative:e.wrappedNative});return{chainId:t,token:n,pools:d,topPool:d[0]||null,quoteAsset:Kt(n,d),evidence:d.length?S.LIVE:S.UNKNOWN}},async scanBlocks({fromBlock:n,toBlock:o,address:s,topics:i,chunkSize:a=2e3}={},c={}){if(!Number.isInteger(n)||!Number.isInteger(o))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(o<n)throw new Error("toBlock must be >= fromBlock");let d=[],l=[];for(let f=n;f<=o;f+=a){let p=Math.min(f+a-1,o);l.push([f,p])}let u=await Ut(l,4,async([f,p])=>{let h={fromBlock:`0x${f.toString(16)}`,toBlock:`0x${p.toString(16)}`};s&&(h.address=s),i&&(h.topics=i);let m=await B(t,"eth_getLogs",[h],c).catch(b=>({error:String(b?.message||b)}));return{start:f,end:p,res:m}});for(let{start:f,end:p,res:h}of u){if(h?.error)return{chainId:t,fromBlock:n,toBlock:o,logs:d,complete:!1,failedAt:[f,p],error:h.error,evidence:S.UNKNOWN};for(let m of h?.result??h??[])d.push(m)}return{chainId:t,fromBlock:n,toBlock:o,logs:d,complete:!0,chunks:l.length,evidence:S.LIVE}},async scoreRisk(n,o={}){let s=[],i=g.PASS,a=l=>{let u={[g.PASS]:0,[g.CAUTION]:1,[g.UNKNOWN]:2,[g.FAIL]:3};u[l]>u[i]&&(i=l)},[c,d]=await Promise.all([this.resolveToken(n,o),this.resolvePools(n,o)]);if(c.evidence!==S.LIVE?(s.push({check:"erc20-metadata",result:g.UNKNOWN,detail:c.warning}),a(g.UNKNOWN)):s.push({check:"erc20-metadata",result:g.PASS,detail:`${c.symbol} / ${c.decimals}d`}),d.evidence===S.UNAVAILABLE)s.push({check:"liquidity",result:g.UNKNOWN,detail:d.reason}),a(g.UNKNOWN);else if(!d.pools.length)s.push({check:"liquidity",result:g.FAIL,detail:"no pool with liquidity found"}),a(g.FAIL);else{let l=d.pools[0],u=l.liquidityUsd??0;u<5e3?(s.push({check:"liquidity",result:g.CAUTION,detail:`top pool only $${u}`}),a(g.CAUTION)):s.push({check:"liquidity",result:g.PASS,detail:`$${u} on ${l.dex}`}),l.createdAt&&Date.now()-l.createdAt<24*3600*1e3&&(s.push({check:"age",result:g.CAUTION,detail:"pool under 24h old"}),a(g.CAUTION))}if(typeof this.sellSimulation=="function"){let l=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},o).catch(u=>({verdict:g.UNKNOWN,reason:String(u?.message||u)}));s.push({check:"sellability",result:l.verdict,detail:l.retentionBps!=null?`round trip returns ${(l.retentionBps/100).toFixed(2)}% -- ${l.reason}`:l.reason}),a(l.verdict)}else s.push({check:"sellability",result:g.UNKNOWN,detail:"no verified router on this chain, so a round-trip sell simulation cannot run. Treat as unproven -- a buy path is not an exit path."}),a(g.UNKNOWN);return{chainId:t,token:n,verdict:i,checks:s,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function or(e){let r={...qn(e)},n=new Set((e.venues||[]).map(s=>s.kind));e.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,tr({chainId:e.chainId,wrappedNative:e.wrappedNative,stableQuoteAssets:e.stableQuoteAssets||[],resolveQuoteAsset:async(s,i)=>(await r.resolvePools(s,i)).quoteAsset||null})):e.venueKind==="uniswap-v2"&&n.has("router")&&Object.assign(r,Xt({chainId:e.chainId,wrappedNative:e.wrappedNative}));let o={};for(let[s,i]of Object.entries(r))o[s]=i.bind(r);return{key:e.key,chainId:e.chainId,name:e.name,rpcEnv:e.rpcEnv,nativeCurrency:e.nativeCurrency,explorer:e.explorer,venues:e.venues||[],capabilities:o}}var Un=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 sr(){return Un.map(e=>Qt(or(e)))}import{AbiCoder as $n,Interface as dr,getAddress as Y,isAddress as lr,keccak256 as Pn}from"ethers";var Ve="0x0000000000000000000000000000000000000000",Dn="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Fn=$n.defaultAbiCoder(),ir=new dr(["function quoteExactInputSingle((address tokenIn,address tokenOut,uint256 amountIn,uint24 fee,uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut,uint160 sqrtPriceX96After,uint32 initializedTicksCrossed,uint256 gasEstimate)"]),ar=new dr(["function quoteExactInputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountOut,uint256 gasEstimate)"]),P=Object.freeze({1:Object.freeze({quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"}),10:Object.freeze({quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrappedNative:"0x4200000000000000000000000000000000000006"}),56:Object.freeze({quoter:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"}),137:Object.freeze({quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270"}),8453:Object.freeze({quoter:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",wrappedNative:"0x4200000000000000000000000000000000000006"}),42161:Object.freeze({quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"}),43114:Object.freeze({quoter:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7"}),4663:Object.freeze({quoter:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73"}),988:Object.freeze({quoter:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5"}),999:Object.freeze({quoter:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",wrappedNative:"0x5555555555555555555555555555555555555555"}),2741:Object.freeze({quoter:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809"})}),de=Object.freeze({1:Object.freeze({quoter:"0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203",wrappedNative:P[1].wrappedNative}),10:Object.freeze({quoter:"0x1f3131a13296fb91c90870043742c3cdbff1a8d7",wrappedNative:P[10].wrappedNative}),56:Object.freeze({quoter:"0x9f75dd27d6664c475b90e105573e550ff69437b0",wrappedNative:P[56].wrappedNative}),137:Object.freeze({quoter:"0xb3d5c3dfc3a7aebff71895a7191796bffc2c81b9",wrappedNative:P[137].wrappedNative}),8453:Object.freeze({quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",wrappedNative:P[8453].wrappedNative}),42161:Object.freeze({quoter:"0x3972c00f7ed4885e145823eb7c655375d275a1c5",wrappedNative:P[42161].wrappedNative}),43114:Object.freeze({quoter:"0xbe40675bb704506a3c2ccfb762dcfd1e979845c2",wrappedNative:P[43114].wrappedNative}),4663:Object.freeze({quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",wrappedNative:P[4663].wrappedNative})}),jn=Object.freeze([100,500,3e3,1e4]);function G(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError(`${r} must be an object`);let n=Object.keys(e).filter(o=>!t.has(o));if(n.length)throw new Error(`${r} unsupported field: ${n.join(", ")}`)}function fr(e,t){let r=String(e??"");if(!/^[1-9][0-9]*$/.test(r))throw new Error(`${t} must be a positive raw-unit integer string`);return BigInt(r)}function pr(e){let t=Number(e??12e3);if(!Number.isInteger(t)||t<250||t>6e4)throw new Error("timeoutMs must be an integer from 250 through 60000");return Object.freeze({timeoutMs:t})}function He(e){let t=String(e??"").trim().toLowerCase();return t===""||t==="eth"||t===Ve||t===Dn}function ue(e,t){if(!lr(String(e??"")))throw new Error(`${t} must be an EVM address`);return Y(String(e))}function cr(e,t,r){return He(e)?Y(t.wrappedNative):ue(e,r)}function ur(e,t){return He(e)?Y(Ve):ue(e,t)}function hr(e,t){let r=Number(e);if(!Number.isInteger(r)||r<0||r>16777215)throw new Error(`${t} must be uint24`);return r}function Mn(e,t){let r=Number(e);if(!Number.isInteger(r)||r<-8388608||r>8388607)throw new Error(`${t} must be int24`);return r}function Vn({tokenIn:e,tokenOut:t,poolKey:r,poolId:n}){G(r,new Set(["currency0","currency1","fee","tickSpacing","hooks"]),"V4 PoolKey");let o=ue(r.currency0,"V4 currency0"),s=ue(r.currency1,"V4 currency1");if(BigInt(o)>=BigInt(s))throw new Error("V4 PoolKey currencies must use canonical ordering");let i=Object.freeze({currency0:o,currency1:s,fee:hr(r.fee,"V4 fee"),tickSpacing:Mn(r.tickSpacing,"V4 tickSpacing"),hooks:ue(r.hooks??Ve,"V4 hooks")}),a=ur(e,"tokenIn"),c=ur(t,"tokenOut");if(a.toLowerCase()===c.toLowerCase())throw new Error("tokenIn and tokenOut must differ");let d=new Set([i.currency0.toLowerCase(),i.currency1.toLowerCase()]);if(!d.has(a.toLowerCase())||!d.has(c.toLowerCase()))throw new Error("V4 PoolKey currencies do not match tokenIn/tokenOut");if(!/^0x[0-9a-f]{64}$/i.test(String(n??"")))throw new Error("exact V4 poolId must be bytes32");let l=Pn(Fn.encode(["address","address","uint24","int24","address"],[i.currency0,i.currency1,i.fee,i.tickSpacing,i.hooks]));if(l.toLowerCase()!==String(n).toLowerCase())throw new Error(`exact V4 poolId mismatch: expected ${l}`);return Object.freeze({poolKey:i,poolId:l,tokenIn:a,tokenOut:c,zeroForOne:a.toLowerCase()===i.currency0.toLowerCase()})}function ze(e,t){if(He(t))return!0;if(!lr(String(t??"")))return!1;let r=P[Number(e)]?.wrappedNative||de[Number(e)]?.wrappedNative;return!!(r&&Y(String(t)).toLowerCase()===Y(r).toLowerCase())}async function mr(e={},t={},r={}){G(e,new Set(["chainId","tokenIn","tokenOut","amountIn","fee"]),"V3 read"),G(t,new Set(["timeoutMs"]),"V3 read options"),G(r,new Set(["rpc"]),"V3 read dependencies");let n=Number(e.chainId),o=P[n];if(!o)throw new Error(`V3 read unavailable on chain ${e.chainId}`);let s=cr(e.tokenIn,o,"tokenIn"),i=cr(e.tokenOut,o,"tokenOut");if(s.toLowerCase()===i.toLowerCase())throw new Error("tokenIn and tokenOut must differ");let a=fr(e.amountIn,"amountIn"),c=e.fee==null?jn:[hr(e.fee,"V3 fee")],d=r.rpc||B,l=pr(t.timeoutMs),u=await Promise.all(c.map(async p=>{let h=ir.encodeFunctionData("quoteExactInputSingle",[{tokenIn:s,tokenOut:i,amountIn:a,fee:p,sqrtPriceLimitX96:0n}]);try{let m=await d(n,"eth_call",[{to:o.quoter,data:h},"latest"],l);if(!m||m==="0x")throw new Error("empty result");let b=ir.decodeFunctionResult("quoteExactInputSingle",m);return Object.freeze({ok:!0,fee:p,amountOut:b[0].toString(),gasEstimate:b[3].toString()})}catch(m){return Object.freeze({ok:!1,fee:p,error:String(m?.message||m).slice(0,160)})}})),f=u.filter(p=>p.ok).sort((p,h)=>BigInt(h.amountOut)>BigInt(p.amountOut)?1:-1)[0];if(!f)throw new Error(`V3 read failed chain=${n}: ${u.map(p=>`${p.fee}:${p.error}`).join("; ")}`);return Object.freeze({venue:"uniswap-v3",chainId:n,quoter:Y(o.quoter),tokenIn:s,tokenOut:i,amountIn:a.toString(),amountOut:f.amountOut,gasEstimate:f.gasEstimate,fee:f.fee,triedFees:Object.freeze(u),executionReady:!1})}async function br(e={},t={},r={}){G(e,new Set(["chainId","tokenIn","tokenOut","amountIn","poolKey","poolId"]),"V4 read"),G(t,new Set(["timeoutMs"]),"V4 read options"),G(r,new Set(["rpc"]),"V4 read dependencies");let n=Number(e.chainId),o=de[n];if(!o)throw new Error(`V4 read unavailable on chain ${e.chainId}`);let s=fr(e.amountIn,"amountIn");if(s>0xffffffffffffffffffffffffffffffffn)throw new Error("amountIn exceeds uint128");let i=Vn(e),a=ar.encodeFunctionData("quoteExactInputSingle",[{poolKey:i.poolKey,zeroForOne:i.zeroForOne,exactAmount:s,hookData:"0x"}]),d=await(r.rpc||B)(n,"eth_call",[{to:o.quoter,data:a},"latest"],pr(t.timeoutMs));if(!d||d==="0x")throw new Error("V4 read returned an empty result");let l=ar.decodeFunctionResult("quoteExactInputSingle",d);return Object.freeze({venue:"uniswap-v4",chainId:n,quoter:Y(o.quoter),tokenIn:i.tokenIn,tokenOut:i.tokenOut,amountIn:s.toString(),amountOut:l[0].toString(),gasEstimate:l[1].toString(),fee:i.poolKey.fee,tickSpacing:i.poolKey.tickSpacing,hooks:i.poolKey.hooks,poolKey:i.poolKey,poolId:i.poolId,zeroForOne:i.zeroForOne,executionReady:!1})}var Hn=new Set(["chainId","tokenIn","tokenOut","amountIn","v4PoolKey","v4PoolId"]),zn=new Set(["maxImpactPct","timeoutMs"]),Wn=new Set(["quoteV3","quoteV4","gasPrice"]);function We(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError(`${r} must be an object`);let n=Object.keys(e).filter(o=>!t.has(o));if(n.length)throw new Error(`quote-only ${r} unsupported field: ${n.join(", ")}`)}function Ge(e,t){let r=String(e??"");if(!/^[1-9][0-9]*$/.test(r))throw new Error(`${t} must be a positive raw-unit integer string`);return BigInt(r)}function yr(e,t,r,n,o){let s=Number(e??t);if(!Number.isFinite(s)||s<r||s>n)throw new Error(`${o} must be a finite number from ${r} through ${n}`);return s}function j(e){try{if(typeof e=="string"&&/^0x[0-9a-f]+$/i.test(e))return BigInt(e);let t=String(e??"");return/^[0-9]+$/.test(t)?BigInt(t):null}catch{return null}}function Kn(e){if(e<=1n)return null;let t=e/1000n;return t>0n&&t<e?t:1n}function Gn({amountIn:e,amountOut:t,probeIn:r,probeOut:n}){let o=j(e),s=j(t),i=j(r),a=j(n);if(!o||!s||!i||!a||a<=0n)return null;let c=a*o;if(c<=0n)return null;let d=s*i*1000000000n/c;return d>=1000000000n?0:Number(1000000000n-d)/1e7}function Ke(e,t,r){let n;return Promise.race([Promise.resolve().then(e),new Promise((o,s)=>{n=setTimeout(()=>s(new Error(`${r}: timeout`)),t)})]).finally(()=>clearTimeout(n))}function Yn({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,amountOut:o,gasEstimate:s,gasPrice:i}){let a=j(s),c=j(i),d=j(n),l=j(o);if(!a||!c||!d||!l||a<=0n||c<=0n)return null;let u=a*c;return ze(e,r)?u:ze(e,t)?u*l/d:null}async function Qn(e,t){let r=await B(e,"eth_gasPrice",[],{timeoutMs:t});return j(r)}function Jn(e,t){return Object.freeze({source:e,quality:"FAILED",amountOut:null,error:String(t?.message||t).slice(0,240)})}async function wr({source:e,amountIn:t,timeoutMs:r,fullRead:n,probeRead:o}){try{let s=await Ke(n,r,e),i=Ge(s?.amountOut,`${e} amountOut`),a=Kn(t);if(a==null)return{source:e,full:s,impactPct:null};try{let c=await Ke(()=>o(a.toString(),s),r,`${e} impact probe`),d=Gn({amountIn:t,amountOut:i,probeIn:a,probeOut:c?.amountOut});return{source:e,full:s,impactPct:d}}catch{return{source:e,full:s,impactPct:null}}}catch(s){return{source:e,error:s}}}function Xn({inspected:e,params:t,gasPrice:r}){let n=e.full,o=Ge(n.amountOut,`${e.source} amountOut`),s=Yn({chainId:t.chainId,tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,amountOut:o,gasEstimate:n.gasEstimate,gasPrice:r}),i=e.source==="uniswap-v4"?{onchain:!0,venue:"uniswap-v4",poolId:n.poolId,poolKey:n.poolKey,hooks:n.hooks,fee:n.fee,tickSpacing:n.tickSpacing,gasUnits:n.gasEstimate??null,quoter:n.quoter??null,executionReady:!1}:{onchain:!0,venue:"uniswap-v3",fee:n.fee,gasUnits:n.gasEstimate??null,quoter:n.quoter??null,executionReady:!1};return{source:e.source,quality:s==null?"NO_GAS":"ESTIMATED_GAS",amountOut:o.toString(),grossOut:o.toString(),netOut:null,costInDest:s?.toString()??null,costAccounted:s!=null,gasEstimated:s!=null,gasUsd:null,feeUsd:null,liquidityUsd:null,executionReady:!1,impactPct:e.impactPct,meta:i}}function Zn({routes:e,rankedOn:t,improvementBps:r}){return e.length?e.length===1?"Only one verified read-only venue answered; this is unbenchmarked, not a proven best route.":r==null?`Best of ${e.length} verified routes, ranked on ${t}; the margin is not comparable.`:r<.01?`Best of ${e.length} verified routes, ranked on ${t}; effectively tied inside quote noise.`:`Best of ${e.length} verified routes, ranked on ${t}; ${r.toFixed(2)} bps above the runner-up.`:"No verified read-only venue returned a usable route."}async function Ye(e={},t={},r={}){We(e,Hn,"route params"),We(t,zn,"route options"),We(r,Wn,"route dependencies");let n=Number(e.chainId);if(!Number.isSafeInteger(n)||n<=0)throw new Error("chainId must be a positive safe integer");if(typeof e.tokenIn!="string"||typeof e.tokenOut!="string")throw new Error("tokenIn and tokenOut are required");let o=Ge(e.amountIn,"amountIn"),s=yr(t.timeoutMs,12e3,250,6e4,"timeoutMs"),i=yr(t.maxImpactPct,25,0,100,"maxImpactPct"),a=r.quoteV3||mr,c=r.quoteV4||br,d=r.gasPrice||Qn,l=[];P[n]&&l.push(wr({source:"uniswap-v3",amountIn:o,timeoutMs:s,fullRead:()=>a({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:o.toString()},{timeoutMs:s}),probeRead:(y,O)=>a({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:y,fee:O.fee},{timeoutMs:s})}));let u=e.v4PoolKey!=null,f=e.v4PoolId!=null;if(u!==f)throw new Error("quote-only V4 requires both exact v4PoolKey and v4PoolId");if(u&&de[n]&&l.push(wr({source:"uniswap-v4",amountIn:o,timeoutMs:s,fullRead:()=>c({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:o.toString(),poolKey:e.v4PoolKey,poolId:e.v4PoolId},{timeoutMs:s}),probeRead:y=>c({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:y,poolKey:e.v4PoolKey,poolId:e.v4PoolId},{timeoutMs:s})})),!l.length)throw new Error(`no verified read-only quote source on chain ${n}`);let p=Ke(()=>d(n,s),s,"gas price read").catch(()=>null),h=await Promise.all(l),m=await p,b=h.filter(y=>y.error).map(y=>Jn(y.source,y.error)),x=h.filter(y=>y.full),I=x.filter(y=>y.impactPct!=null&&y.impactPct>i).map(y=>({source:y.source,impactPct:Number(y.impactPct.toFixed(2)),reason:`price impact ${y.impactPct.toFixed(2)}% exceeds ${i}% ceiling`})),N=new Set(I.map(y=>y.source)),v=x.filter(y=>!N.has(y.source)),w=v.map(y=>Xn({inspected:y,params:{...e,chainId:n},gasPrice:m})),A=w.length>0&&w.every(y=>y.costAccounted),E=A?"net":"gross";for(let y of w){let O=BigInt(y.grossOut),V=A?BigInt(y.costInDest):0n;y.netOut=(O>V?O-V:0n).toString()}w.sort((y,O)=>{let V=BigInt(A?y.netOut:y.grossOut),lt=BigInt(A?O.netOut:O.grossOut);return V===lt?y.source.localeCompare(O.source):lt>V?1:-1});let k=[];A?k.push("Gas is estimated from quoter gas units and the current read-only gas price; actual gas may differ."):k.push("Gas was not accounted for; routes are ranked on gross output.");let R=v.filter(y=>y.impactPct==null).map(y=>y.source);R.length&&k.push(`Price impact is UNKNOWN for: ${R.join(", ")}.`),I.length&&k.push(`Dropped on price impact: ${I.map(y=>y.source).join(", ")}.`),!u&&de[n]&&k.push("V4 was not queried because no exact verified PoolKey identity was discovered.");let C=null,_=null;if(w.length>1){let y=BigInt(A?w[0].netOut:w[0].grossOut),O=BigInt(A?w[1].netOut:w[1].grossOut);O>0n&&(C=Number((y-O)*10000000n/O)/1e3,_=`${w[0].source} vs ${w[1].source}`)}let M=Object.fromEntries(v.filter(y=>y.impactPct!=null).map(y=>[y.source,Number(y.impactPct.toFixed(4))]));return Object.freeze({kind:"swap",chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:o.toString(),best:w[0]||null,routes:Object.freeze(w.map(y=>Object.freeze(y))),failed:Object.freeze(b),rankedOn:E,sourcesTried:l.length,sourcesAnswered:x.length,improvementBps:C,spreadBasis:_,priceImpact:Object.freeze(M),impactRejected:Object.freeze(I),impactUnmeasured:Object.freeze(R),warnings:Object.freeze(k),note:Zn({routes:w,rankedOn:E,improvementBps:C})})}import{createHash as ao}from"node:crypto";import{createHash as eo}from"node:crypto";var L=Object.freeze({SHADOW:"shadow",ARMED:"armed",AUTONOMOUS:"autonomous"}),to=3,ro=new Set(Object.values(L));function Xe(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Xe(t);Object.freeze(e)}return e}function Je(e){return Array.isArray(e)?`[${e.map(Je).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${Je(e[t])}`).join(",")}}`:JSON.stringify(e)}function no(e){return`sha256:${eo("sha256").update(Je(e)).digest("hex")}`}function Qe(e,t,r){if(!Array.isArray(e)||e.length===0)throw new TypeError(`${t} must be a non-empty exact allowlist`);let n=e.map(o=>r(o,t));if(new Set(n).size!==n.length)throw new TypeError(`${t} contains a duplicate entry`);return n.sort((o,s)=>typeof o=="number"?o-s:o.localeCompare(s))}function oo(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new TypeError(`${t} entries must be positive safe integers`);return e}function gr(e,t){if(typeof e!="string"||e.trim()!==e||e.length===0)throw new TypeError(`${t} entries must be non-empty exact strings`);return e}function te(e,t,{positive:r=!1}={}){let n=typeof e=="number"?String(e):e;if(typeof n!="string"||!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(n))throw new TypeError(`${t} must be a finite non-negative decimal`);if(r&&/^0(?:\.0+)?$/.test(n))throw new TypeError(`${t} must be greater than zero`);return n}function ge(e,t,{min:r=0,max:n=Number.MAX_SAFE_INTEGER}={}){if(!Number.isSafeInteger(e)||e<r||e>n)throw new TypeError(`${t} must be an integer from ${r} through ${n}`);return e}function ve(e,t){let r=te(e,t),[n,o=""]=r.split(".");return{digits:BigInt(n+o),scale:o.length}}function Ae(e,t,r="value"){let n=ve(e,r),o=ve(t,"strategy cap"),s=Math.max(n.scale,o.scale),i=n.digits*10n**BigInt(s-n.scale),a=o.digits*10n**BigInt(s-o.scale);return i<a?-1:i>a?1:0}function Ar(e){let t=structuredClone(e);return delete t.digest,t}function so(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");return no(Ar(e))}function Ze(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");let t=e.mode??L.SHADOW;if(!ro.has(t))throw new TypeError("mode must be shadow, armed, or autonomous");let r={version:1,mode:t,chains:Qe(e.chains,"chains",oo),venues:Qe(e.venues,"venues",gr),quoteAssets:Qe(e.quoteAssets,"quoteAssets",gr),maxSpendPerTrade:te(e.maxSpendPerTrade,"maxSpendPerTrade",{positive:!0}),maxSpendPerDay:te(e.maxSpendPerDay,"maxSpendPerDay",{positive:!0}),minLiquidityUsd:te(e.minLiquidityUsd,"minLiquidityUsd",{positive:!0}),maxSlippageBps:ge(e.maxSlippageBps,"maxSlippageBps",{max:1e4}),maxGas:te(e.maxGas,"maxGas",{positive:!0}),maxPriorityFee:te(e.maxPriorityFee,"maxPriorityFee"),maxBuysPerHour:ge(e.maxBuysPerHour,"maxBuysPerHour",{min:1}),retryCeiling:ge(e.retryCeiling,"retryCeiling",{max:to}),ttlMs:ge(e.ttlMs,"ttlMs",{min:1}),requireSellSimulation:e.requireSellSimulation,killSwitch:e.killSwitch};if(r.requireSellSimulation!==!0)throw new TypeError("requireSellSimulation must be true");if(typeof r.killSwitch!="boolean")throw new TypeError("killSwitch must be boolean");if(Ae(r.maxSpendPerTrade,r.maxSpendPerDay)>0)throw new TypeError("maxSpendPerTrade cannot exceed maxSpendPerDay");return r.digest=so(r),Xe(r)}var io=Object.freeze([["localSignerReady","local signer is not ready"],["dedicatedWallet","dedicated non-main wallet evidence is missing"],["exactStrategyBinding","exact strategy digest/grant binding is missing"],["trustedOneUseTrigger","fresh trusted one-use trigger attestation is missing"],["durableReceipts","durable receipts evidence is missing"],["balanceReconciliation","balance reconciliation evidence is missing"]]);function T(e,t,r){t&&e.push(r)}function et(e,t={},r={}){let n=Ze(Ar(e)),o=[];T(o,n.killSwitch,"kill switch is engaged"),T(o,!n.chains.includes(t.chain),"chain is not on the exact allowlist"),T(o,!n.venues.includes(t.venue),"venue is not on the exact allowlist"),T(o,!n.quoteAssets.includes(t.quoteAsset),"quote asset is not on the exact allowlist");let s=(a,c,d)=>{try{T(o,Ae(a,c,d)>0,`${d} exceeds cap`)}catch{o.push(`${d} evidence is missing or unknown`)}};s(t.spend,n.maxSpendPerTrade,"per-trade spend");try{let a=ve(t.spentToday,"daily spend"),c=ve(t.spend,"per-trade spend"),d=Math.max(a.scale,c.scale),l=a.digits*10n**BigInt(d-a.scale)+c.digits*10n**BigInt(d-c.scale),u=d===0?String(l):`${String(l).padStart(d+1,"0").slice(0,-d)}.${String(l).padStart(d+1,"0").slice(-d)}`;T(o,Ae(u,n.maxSpendPerDay,"daily spend")>0,"daily spend cap would be exceeded")}catch{o.push("daily spend evidence is missing or unknown")}try{T(o,Ae(t.liquidityUsd,n.minLiquidityUsd,"liquidity")<0,"minimum real liquidity is not met")}catch{o.push("liquidity evidence is missing or unknown")}s(t.slippageBps,String(n.maxSlippageBps),"slippage"),s(t.gas,n.maxGas,"gas"),s(t.priorityFee,n.maxPriorityFee,"priority fee"),T(o,!Number.isSafeInteger(t.buysLastHour),"buys per hour evidence is missing or unknown"),T(o,Number.isSafeInteger(t.buysLastHour)&&t.buysLastHour>=n.maxBuysPerHour,"buys per hour cap is reached"),T(o,!Number.isSafeInteger(t.retries)||t.retries<0,"retry evidence is missing or unknown"),T(o,Number.isSafeInteger(t.retries)&&t.retries>n.retryCeiling,"retry ceiling is exceeded"),T(o,!Number.isFinite(t.ageMs)||t.ageMs<0,"TTL evidence is missing or unknown"),T(o,Number.isFinite(t.ageMs)&&t.ageMs>=n.ttlMs,"TTL has expired"),T(o,t.sellSimulation?.verdict!=="PASS"||t.sellSimulation?.evidence!=="LIVE","mandatory sell simulation has no LIVE PASS evidence"),T(o,typeof t.fireId!="string"||t.fireId.length===0,"fire id evidence is missing or unknown"),T(o,!Array.isArray(t.firedIds),"duplicate-fire history is missing or unknown"),T(o,Array.isArray(t.firedIds)&&t.firedIds.includes(t.fireId),"duplicate fire is blocked");let i=[...o];T(i,r?.ORACLE_AUTONOMOUS_TRADING!=="1","ORACLE_AUTONOMOUS_TRADING=1 is required literally");for(let[a,c]of io)T(i,t.autonomousGates?.[a]!==!0,c);return T(i,n.mode!==L.AUTONOMOUS,"strategy mode is not autonomous"),Xe({strategyDigest:n.digest,mode:n.mode,policyEligible:o.length===0,blockers:o,autonomousEligible:i.length===0,autonomousBlockers:i,reportOnly:!0})}function Ee(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tt(e){return Array.isArray(e)?`[${e.map(tt).join(",")}]`:Ee(e)?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${tt(e[t])}`).join(",")}}`:JSON.stringify(e)}function co(e){return`cycle:${ao("sha256").update(tt(e)).digest("hex")}`}function le(e,t){if(typeof e!="function")throw new TypeError(`launch-radar runner: injected ${t} function is required`)}function vr(e){return e instanceof Error?e.message:String(e)}function Er(e={}){let{store:t,strategy:r,discover:n,evaluate:o}=e;if(!t||typeof t.read!="function"||typeof t.commitCycle!="function")throw new TypeError("launch-radar runner: durable store is required");if(!Ee(r))throw new TypeError("launch-radar runner: strategy is required");le(n,"discovery"),le(o,"evaluate");let s=e.now??(()=>new Date().toISOString()),i=e.sleep??(()=>Promise.resolve()),a=e.jitter??(()=>0);le(s,"clock"),le(i,"sleep"),le(a,"jitter");let c=Math.min(3,Math.max(0,Number.isSafeInteger(e.retries)?e.retries:r.retryCeiling)),d=Math.max(0,Number.isFinite(e.baseBackoffMs)?e.baseBackoffMs:100),l=Math.max(d,Number.isFinite(e.maxBackoffMs)?e.maxBackoffMs:2e3);async function u(h){let m;for(let b=0;b<=c;b+=1)try{return await h(b)}catch(x){if(m=x,b===c)break;let I=Number(a()),N=Number.isFinite(I)?Math.max(0,I):0,v=Math.min(l,d*2**b+N);await i(v)}throw m}function f(){let h=t.read().strategyStatus;return{mode:L.SHADOW,status:h.ambiguous?"blocked":"inert",ambiguous:h.ambiguous,autostart:!1}}async function p(){let h=t.read();if(h.strategyStatus.ambiguous)return{mode:L.SHADOW,status:"blocked",blockers:["ambiguous state requires reconciliation"],results:[]};if(r.mode!==L.SHADOW||h.strategyStatus.mode!==L.SHADOW){let v=r.mode!==L.SHADOW?r.mode:h.strategyStatus.mode;return{mode:L.SHADOW,status:"blocked",blockers:[`configured mode ${v} is forbidden by shadow-only runner`],results:[]}}if(r.killSwitch)return{mode:L.SHADOW,status:"blocked",blockers:["kill switch is engaged"],results:[]};let m;try{m=await u(v=>n({cursor:structuredClone(h.cursor),attempt:v,mode:L.SHADOW}))}catch(v){return{mode:L.SHADOW,status:"failed",blockers:[vr(v)],results:[]}}if(!Ee(m)||!Array.isArray(m.candidates)||!(m.cursor===null||Ee(m.cursor)))return{mode:L.SHADOW,status:"failed",blockers:["discovery returned an invalid deterministic result"],results:[]};let b=[];for(let v of m.candidates)try{let w=await u(A=>o(structuredClone(v),{attempt:A,mode:L.SHADOW}));b.push({id:v?.id??null,policy:et(r,w,{})})}catch(w){b.push({id:v?.id??null,policy:{mode:L.SHADOW,policyEligible:!1,reportOnly:!0,blockers:[`evaluation failed: ${vr(w)}`]}})}let x={cursor:m.cursor,candidates:m.candidates,results:b},I={id:co(x),type:"shadow-cycle",at:s(),data:x},N=t.commitCycle({candidates:m.candidates,cursor:m.cursor,strategyStatus:{mode:L.SHADOW,status:"inert",ambiguous:!1},event:I});return{mode:L.SHADOW,status:N.duplicate?"duplicate":"completed",results:b,evidenceId:N.evidence.id}}return Object.freeze({status:f,runCycle:p})}function Sr(e){return[...new Set(e.filter(Boolean).map(String))]}function J(e){return Array.isArray(e)?e.map(J):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,J(r)])):e}function Q(e,t,r="UNKNOWN"){return!e||typeof e!="object"?{evidence:r,observedAt:t}:J({...structuredClone(e),evidence:e.evidence||r,observedAt:e.observedAt||t})}function uo(e,t){let r=String(t||"").toLowerCase();return!!(r&&[e?.address,e?.pair,e?.poolId].some(n=>String(n||"").toLowerCase()===r))}function lo(e,t){let r=e.poolId||e.poolAddress||null,n=[t.topPool,...t.pools?.pools||[]].filter(Boolean),o=r?n.find(i=>uo(i,r)):t.topPool,s={address:e.poolAddress??null,poolId:e.poolId,poolKey:e.poolKey,quoteAsset:e.quoteAsset};return J({...o||{},...s})}function fo(e,t,r,n){let o=e.observedAt||n,s=lo(e,t),i=Q(t.scannerRisk||t.risk,o),a=Q(t.sellability,o,"UNAVAILABLE"),c=Q(t.quote,o,"UNAVAILABLE"),d=c.evidence==="LIVE"?"PASS":"UNKNOWN";return J({chain:{id:e.chainId,...t.chain||{}},token:Q({address:e.tokenAddress,...t.token||{}},o,"LIVE"),pool:Q(s,o,"LIVE"),venue:Q({...e.venue,supported:e.venue?.supported===!0,verified:e.venue?.verified===!0},o,"LIVE"),signal:Q({kind:e.kind,source:"verified-factory",unsolicitedAirdrop:!1},o,"LIVE"),risk:i,sellability:a,route:J({status:d,amountOut:c.amountOut??null,cost:c.fee==null?{status:"UNKNOWN",amount:null,unit:null}:{status:"KNOWN",amount:String(c.fee),unit:c.feeUnit||"wei"},routeEvidence:c.routeEvidence,evidence:c.evidence,observedAt:c.observedAt}),prepared:{status:"NOT_PREPARED",unsigned:!0},whyBlocked:Sr([...r||[],...t.blockedReasons||[],t.error]),latency:{discoveredAt:o,riskCompletedAt:i.observedAt,sellabilityCompletedAt:a.observedAt,routeCompletedAt:c.observedAt,normalizedAt:n}})}async function rt(e={}){let t=e.discover||e.discoveryFn,r=e.evaluator||e.evaluate;if(typeof t!="function")throw new TypeError("service requires an injected discovery function");if(typeof r!="function")throw new TypeError("service requires an injected evaluator function");let n=await t(e.discovery||e.discoveryOptions||{}),o=Array.isArray(n?.discoveries)?n.discoveries:[],s=e.observedAt||o[0]?.observedAt||new Date(0).toISOString(),i=[];for(let a of o){if(a?.signal?.unsolicitedAirdrop===!0||a?.unsolicitedAirdrop===!0||a?.kind==="wallet-transfer")continue;let c;try{c=await r({chainId:a.chainId,tokenAddress:a.tokenAddress,discovery:J(structuredClone(a)),prepare:e.prepare===!0})}catch(d){c={error:`evaluation unavailable: ${String(d?.message||d).slice(0,300)}`}}i.push(fo(a,c||{},n?.status==="LIVE"?[]:n?.whyBlocked,s))}return Object.freeze({status:n?.status||"UNKNOWN",cursor:n?.cursor||null,unavailable:Object.freeze([...n?.unavailable||[]]),whyBlocked:Object.freeze(Sr(n?.whyBlocked||[])),candidates:yt(i)})}import U from"node:fs";import Se from"node:path";var it=1,po=0;function Z(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function q(e){return structuredClone(e)}function ot(e,t="state"){if(!(e===null||typeof e=="string"||typeof e=="boolean")&&!(typeof e=="number"&&Number.isFinite(e))){if(Array.isArray(e))return e.forEach((r,n)=>ot(r,`${t}[${n}]`));if(Z(e)){for(let[r,n]of Object.entries(e)){if(n===void 0)throw new Error(`launch-radar store: non-JSON value at ${t}.${r}`);ot(n,`${t}.${r}`)}return}throw new Error(`launch-radar store: non-JSON value at ${t}`)}}function X(e){return Array.isArray(e)?`[${e.map(X).join(",")}]`:Z(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${X(e[t])}`).join(",")}}`:JSON.stringify(e)}function ho(){return{version:it,candidates:[],cursor:null,strategyStatus:{mode:"shadow",status:"inert",ambiguous:!1},evidence:[]}}function mo(e){if(!Z(e)||!["shadow","armed","autonomous"].includes(e.mode)||typeof e.status!="string"||typeof e.ambiguous!="boolean")throw new Error("launch-radar store: corrupt strategy status shape")}function fe(e){if(!Z(e)||e.version!==it)throw new Error("launch-radar store: corrupt or unsupported version");if(!Array.isArray(e.candidates)||!(e.cursor===null||Z(e.cursor))||!Array.isArray(e.evidence))throw new Error("launch-radar store: corrupt state shape");mo(e.strategyStatus),ot(e);try{Ne(e.evidence)}catch(t){throw new Error(`launch-radar store: corrupt evidence: ${t.message}`)}return q(e)}function Ie(e,t=!1){let r;try{r=U.lstatSync(e)}catch(n){if(t&&n?.code==="ENOENT")return!1;throw n}if(r.isSymbolicLink())throw new Error("launch-radar store: path must not be a symlink");if(!r.isFile())throw new Error("launch-radar store: path must be a regular file");if((r.mode&511)!==384)throw new Error("launch-radar store: existing file permissions must be 0600");return!0}function st(e){Ie(e);let t;try{t=JSON.parse(U.readFileSync(e,"utf8"))}catch{throw new Error("launch-radar store: corrupt JSON")}return fe(t)}function nt(e,t){let r=fe(t),n=Se.dirname(e);U.mkdirSync(n,{recursive:!0,mode:448});let o=U.lstatSync(n);if(o.isSymbolicLink()||!o.isDirectory())throw new Error("launch-radar store: parent must be a regular directory, not a symlink");Ie(e,!0)&&Ie(e);let s=Se.join(n,`.launch-radar.${process.pid}.${po+=1}.tmp`),i;try{i=U.openSync(s,"wx",384),U.writeFileSync(i,`${X(r)}
|
|
8
|
+
`,"utf8"),U.fsyncSync(i),U.closeSync(i),i=void 0,U.renameSync(s,e),U.chmodSync(e,384);let a=U.openSync(n,"r");try{U.fsyncSync(a)}finally{U.closeSync(a)}}catch(a){i!==void 0&&U.closeSync(i);try{U.unlinkSync(s)}catch{}throw a}}function Ir(e={}){let t=e.path;if(typeof t!="string"||!Se.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");Ie(t,!0)?st(t):nt(t,ho());let r=()=>st(t),n=(o,{reconciliation:s=!1}={})=>{if(r().strategyStatus.ambiguous&&!s)throw new Error("launch-radar store: ambiguous state is terminal until reconciliation");return nt(t,o),q(o)};return Object.freeze({path:t,read:r,replaceState(o={}){if(!Z(o))throw new TypeError("launch-radar store: state patch must be an object");let i={...r()};for(let a of["candidates","cursor","strategyStatus"])Object.hasOwn(o,a)&&(i[a]=q(o[a]));return n(fe(i))},appendEvidence(o){let s=r();if(s.strategyStatus.ambiguous)throw new Error("launch-radar store: ambiguous state is terminal until reconciliation");let i=s.evidence.find(d=>d.id===o?.id);if(i){if(i.type===o?.type&&X(i.data)===X(o?.data))return q(i);throw new Error(`launch-radar store: duplicate evidence conflict: ${o?.id}`)}let a=Ce(s.evidence,o),c=a.at(-1);return n({...s,evidence:q(a)}),q(c)},commitCycle({candidates:o,cursor:s,strategyStatus:i,event:a}={}){let c=r();if(c.strategyStatus.ambiguous)throw new Error("launch-radar store: ambiguous state is terminal until reconciliation");let d=c.evidence.find(f=>f.id===a?.id);if(d){if(d.type===a?.type&&X(d.data)===X(a?.data))return{duplicate:!0,evidence:q(d),state:c};throw new Error(`launch-radar store: duplicate evidence conflict: ${a?.id}`)}let l=Ce(c.evidence,a),u=fe({...c,candidates:q(o),cursor:q(s),strategyStatus:q(i),evidence:q(l)});return n(u),{duplicate:!1,evidence:q(l.at(-1)),state:q(u)}},markAmbiguous(o){if(typeof o!="string"||o.length===0)throw new TypeError("launch-radar store: ambiguity reason is required");let s=r(),i={...s.strategyStatus,status:"blocked",ambiguous:!0,reason:o};return nt(t,{...s,strategyStatus:i}),q(i)},reconcile(o={}){if(!Z(o))throw new TypeError("launch-radar store: reconciliation state must be an object");let s=r(),i=fe({...s,...q(o),version:it,evidence:s.evidence});if(i.strategyStatus.ambiguous)throw new Error("launch-radar store: reconciliation must clear ambiguous state");return n(i,{reconciliation:!0})}})}function xr(e={}){let t=e.path;if(typeof t!="string"||!Se.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");return st(t)}function yo(e){return e.ORACLE_CONFIG_DIR||ct.join(bo.homedir(),".config","oracle")}function Nr(e,t){if(!e||!ct.isAbsolute(e))throw new Error(`${t} path must be absolute`);let r=kr.lstatSync(e);if(r.isSymbolicLink()||!r.isFile())throw new Error(`${t} must be a regular non-symlink file`);if(r.size>1024*1024)throw new Error(`${t} exceeds 1 MiB`);return JSON.parse(kr.readFileSync(e,"utf8"))}function wo(e){return e==null?null:String(e)}function pe(e){if(e!==void 0)return typeof e=="bigint"?e.toString():Array.isArray(e)?e.map(pe).filter(t=>t!==void 0):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,pe(r)])):e}function Rr(e,t){let r=String(e??"");if(!/^[1-9][0-9]*$/.test(r))throw new Error(`${t} must be a positive raw-unit integer string`);return r}function at(e,t,r,n){let o=Number(e);if(!Number.isInteger(o)||o<t||o>r)throw new Error(`${n} must be an integer from ${t} to ${r}`);return o}function go(e,t,r,n){let o=Number(e);if(!Number.isFinite(o)||o<t||o>r)throw new Error(`${n} must be a finite number from ${t} to ${r}`);return o}function Ao(e){let t=e?.routeProbe;if(!t||typeof t!="object")throw new Error("verified route probe is not configured for this factory");return Object.freeze({amountIn:Rr(t.amountIn,"routeProbe.amountIn"),quoteAssetDecimals:at(t.quoteAssetDecimals,0,255,"routeProbe.quoteAssetDecimals"),slippageBps:at(t.slippageBps??100,0,1e4,"routeProbe.slippageBps"),maxImpactPct:go(t.maxImpactPct??25,0,100,"routeProbe.maxImpactPct"),timeoutMs:at(t.timeoutMs??12e3,250,6e4,"routeProbe.timeoutMs")})}function Cr(e){return[e?.source,e?.amountOut,e?.netOut,e?.meta?.poolId].map(t=>String(t??"").toLowerCase()).join(":")}function Or(e,t,r){let n=String(t?.poolId||"").toLowerCase();if(!n)return;let o=[e?.best,...Array.isArray(e?.routes)?e.routes:[]].filter(Boolean);for(let s of o){if(String(s?.meta?.venue||s?.source||"").toLowerCase()!=="uniswap-v4")continue;if(String(s?.meta?.poolId||"").toLowerCase()!==n)throw new Error(`V4 ${r} poolId mismatch: quote evidence did not match verified discovery`)}}function Lr(e){if(!e?.best||!Rr(e.best.amountOut,"best route amountOut"))throw new Error("best route returned no positive output");let t=Array.isArray(e.routes)?e.routes:[],r=Cr(e.best),n=t.findIndex(a=>Cr(a)===r),o=t.filter((a,c)=>c!==n),s=String(e.rankedOn||"gross").toLowerCase(),i=[...Array.isArray(e.warnings)?e.warnings:[]];return s!=="net"&&!i.some(a=>/gas.*not (?:included|accounted)|gross/i.test(String(a)))&&i.push("Ranked on gross output. Gas was not accounted for."),pe({rankedOn:s,winner:e.best,runnersUp:o,routes:t,failed:Array.isArray(e.failed)?e.failed:[],sourcesTried:e.sourcesTried??null,sourcesAnswered:e.sourcesAnswered??null,improvementBps:e.improvementBps??null,spreadBasis:e.spreadBasis??null,priceImpact:e.priceImpact,impactRejected:e.impactRejected,impactUnmeasured:e.impactUnmeasured,warnings:i,note:e.note})}function vo(e,t){return{quote:{evidence:"UNAVAILABLE",reason:e,observedAt:t},sellability:{verdict:"UNKNOWN",evidence:"UNAVAILABLE",reason:e,observedAt:t}}}async function Eo({scanner:e,discovery:t,descriptor:r,routeFn:n=Ye,observedAt:o=new Date().toISOString()}={}){if(!e||typeof e!="object")throw new TypeError("installed evaluation requires a scanner");if(!t||typeof t!="object")throw new TypeError("installed evaluation requires a discovery");if(typeof n!="function")throw new TypeError("installed evaluation requires a route function");let s={blockedReasons:[],executionReady:!1,signingReady:!1,broadcastReady:!1},i=t.tokenAddress;try{s.token=e.resolveToken?await e.resolveToken(i):null}catch(a){s.blockedReasons.push(`token resolution unavailable: ${String(a?.message||a).slice(0,160)}`)}try{s.pools=e.resolvePools?await e.resolvePools(i):null}catch(a){s.blockedReasons.push(`pool resolution unavailable: ${String(a?.message||a).slice(0,160)}`)}try{s.risk=e.scoreRisk?await e.scoreRisk(i):null}catch(a){s.blockedReasons.push(`risk evidence unavailable: ${String(a?.message||a).slice(0,160)}`)}try{let a=Ao(r);if(!t.quoteAsset)throw new Error("verified discovery did not identify a quote asset");if(!i)throw new Error("verified discovery did not identify a token");let c=t.poolKey?{v4PoolKey:pe(t.poolKey),v4PoolId:t.poolId}:{},d={chainId:t.chainId,...c},l={maxImpactPct:a.maxImpactPct,timeoutMs:a.timeoutMs},u=await n({...d,tokenIn:t.quoteAsset,tokenOut:i,amountIn:a.amountIn},l);Or(u,t,"buy");let f=Lr(u);s.quote={evidence:"LIVE",observedAt:o,amountIn:a.amountIn,amountOut:String(u.best.amountOut),fee:null,routeEvidence:f};try{let p=await n({...d,tokenIn:i,tokenOut:t.quoteAsset,amountIn:String(u.best.amountOut)},l);Or(p,t,"reverse");let h=Lr(p);s.sellability={verdict:"CAUTION",evidence:"LIVE",method:"reverse-route-quote",simulationReady:!1,reason:"Reverse route quote only; this is not a sell simulation.",observedAt:o,amountIn:String(u.best.amountOut),amountOut:String(p.best.amountOut),routeEvidence:h}}catch(p){let h=`reverse route unavailable: ${String(p?.message||p).slice(0,240)}`;s.blockedReasons.push(h),s.sellability={verdict:"UNKNOWN",evidence:"UNAVAILABLE",reason:h,observedAt:o}}}catch(a){let c=`route evidence unavailable: ${String(a?.message||a).slice(0,240)}`;s.blockedReasons.push(c),Object.assign(s,vo(c,o))}return pe(s)}function So(e){return{chain:e.chain?.id??e.chainId,venue:e.venue?.id||e.venue?.name||e.venue?.venue||"unknown",quoteAsset:"unknown",spend:null,spentToday:"0",liquidityUsd:wo(e.pool?.liquidityUsd),slippageBps:null,gas:null,priorityFee:null,buysLastHour:0,retries:0,ageMs:0,sellSimulation:e.sellability,fireId:e.id,firedIds:[],autonomousGates:{}}}function Tr(e={}){let t=e.env||process.env;if(t.ORACLE_LAUNCH_RADAR_SHADOW!=="1")throw new Error("ORACLE_LAUNCH_RADAR_SHADOW=1 is required for an explicit shadow cycle");let r=Nr(t.ORACLE_LAUNCH_RADAR_STRATEGY_FILE,"strategy file"),n=Nr(t.ORACLE_LAUNCH_RADAR_FACTORIES_FILE,"factories file"),o=Array.isArray(n)?n:n.factories;if(!Array.isArray(o)||o.length===0)throw new Error("factories file must contain a non-empty factories array");let s=[...new Set(o.map(f=>f?.chainId))];if(s.length!==1||!Number.isInteger(s[0]))throw new Error("one installed shadow runner handles exactly one chainId");let i=Ze(r);if(i.mode!==L.SHADOW)throw new Error("installed Launch Radar runner is shadow-only");sr();let a=Jt(s[0]);if(!a)throw new Error(`no scanner registered for chain ${s[0]}`);let c=t.ORACLE_LAUNCH_RADAR_STORE_PATH||ct.join(yo(t),"launch-radar",`state-${s[0]}.json`),d=Ir({path:c});return Er({store:d,strategy:i,discover:async({cursor:f})=>{let p=await a.blockNumber(),h=Number(p?.blockNumber??p);if(!Number.isSafeInteger(h))throw new Error("scanner did not return a safe integer head block");let m=Number.isSafeInteger(f?.nextBlock)?f.nextBlock:Math.max(0,h-10),b=await rt({discover:()=>St({scanner:a,factories:o,fromBlock:m,toBlock:h,cursor:f}),evaluator:async({discovery:x})=>{let I=o.find(N=>N?.id===x?.factoryId||String(N?.factoryAddress||"").toLowerCase()===String(x?.factoryAddress||"").toLowerCase());return Eo({scanner:a,discovery:x,descriptor:I,routeFn:e.routeFn||Ye,observedAt:new Date().toISOString()})},observedAt:new Date().toISOString()});return{candidates:b.candidates,cursor:b.cursor}},evaluate:async f=>So(f)})}var Io=Object.freeze({OK:"ok",DEGRADED:"degraded",UNKNOWN:"unknown"}),Ys=Object.freeze({fresh:0,stale:1,down:2});import xo from"node:os";import _r from"node:path";var ko="oracle.launch-radar.data-plane.v1";function No(e){return String(e?.message||e||"unknown error").slice(0,300)}function Co(e={}){return e.configDir||process.env.ORACLE_CONFIG_DIR||_r.join(xo.homedir(),".config","oracle")}function Oo(e={}){return e.storePath||process.env.LAUNCH_RADAR_STORE_PATH||_r.join(Co(e),"launch-radar","state.json")}function Lo(e={}){let t=Oo(e);try{return{ok:!0,path:t,state:xr({path:t})}}catch(r){return{ok:!1,path:t,error:No(r)}}}function Ro(){return process.env.ORACLE_AUTONOMOUS_TRADING==="1"}function ut(e={},t={}){let r=Lo(t),n={schema:ko,storePath:r.path,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,autonomousTradingEnvSet:Ro()};if(!r.ok)return Object.freeze({...n,evidence:"UNAVAILABLE",reason:r.error,mode:L.SHADOW,status:"unavailable",ambiguous:null,candidateCount:null,cursor:null,evidenceCount:null,lastEvidenceAt:null});let{state:o}=r,s=o.evidence.at(-1)||null;return Object.freeze({...n,evidence:"LIVE",reason:o.strategyStatus.reason??null,mode:o.strategyStatus.mode,status:o.strategyStatus.status,ambiguous:o.strategyStatus.ambiguous,candidateCount:o.candidates.length,cursor:o.cursor,evidenceCount:o.evidence.length,lastEvidenceAt:s?s.at:null})}var dt=new Set(process.argv.slice(2));(dt.has("--help")||dt.has("-h"))&&(console.log(`oracle-launch-radar-shadow
|
|
9
|
+
|
|
10
|
+
Default: print read-only status and exit. Missing state remains UNAVAILABLE and creates nothing.
|
|
11
|
+
|
|
12
|
+
--once run one explicit shadow-only cycle
|
|
13
|
+
|
|
14
|
+
--once requires:
|
|
15
|
+
ORACLE_LAUNCH_RADAR_SHADOW=1
|
|
16
|
+
ORACLE_LAUNCH_RADAR_STRATEGY_FILE=/absolute/private-strategy.json
|
|
17
|
+
ORACLE_LAUNCH_RADAR_FACTORIES_FILE=/absolute/verified-factories.json
|
|
18
|
+
|
|
19
|
+
There is no daemon/autostart, arm, sign, or broadcast mode.`),process.exit(0));try{let e=dt.has("--once")?await Tr({env:process.env}).runCycle():ut({},{});process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
20
|
+
`),e?.status==="failed"&&(process.exitCode=1)}catch(e){process.stderr.write(`launch radar shadow refused: ${e?.message||e}
|
|
21
|
+
`),process.exitCode=1}
|