@oracle-agent/oracle 0.35.27 → 0.35.29

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.
@@ -1,11 +1,11 @@
1
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}
2
+ var so=Object.defineProperty;var z=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var We=(e,t)=>{for(var r in t)so(e,r,{get:t[r],enumerable:!0})};import ee from"node:net";import Ao from"node:dns";function _e(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=l=>{if(!l)return[];let d=l.split(":"),p=d.at(-1);if(p?.includes(".")){let f=p.split(".").map(Number);if(f.length!==4||f.some(m=>!Number.isInteger(m)||m<0||m>255))return null;d.splice(d.length-1,1,(f[0]<<8|f[1]).toString(16),(f[2]<<8|f[3]).toString(16))}return d.some(f=>!/^[0-9a-f]{1,4}$/.test(f))?null:d.map(f=>Number.parseInt(f,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 u=[...s,...Array(Math.max(0,c)).fill(0),...i];return u.length!==8?null:Uint8Array.from(u.flatMap(l=>[l>>8,l&255]))}function Xe(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 Ze(e){if(ee.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(ee.isIPv6(e)){let t=_e(e);if(!t)return!1;let r=_e("::ffff:0:0");return Xe(t,r,96)?Ze([...t.slice(12)].join(".")):Xe(t,_e("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([o,s])=>Xe(t,_e(o),s)):!1}return!1}function Eo(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(So.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=ee.isIP(r);return n!==0&&!Ze(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function et(e,{lookupFn:t=Ao.promises.lookup}={}){let r=Eo(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:ee.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=>!Ze(o.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function tt({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n;try{let d=await t();r=d.Agent,n=d.fetch}catch(d){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${d?.message||d}`);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=d=>String(d).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),s=new Map,i=d=>(Array.isArray(d)?d:[d]).map(p=>typeof p=="string"?{address:p}:p).filter(p=>p&&p.address).map(p=>({address:p.address,family:p.family||(ee.isIPv6(p.address)?6:4)})),a=(d,p,f)=>{s.set(o(d),i(typeof p=="string"?[{address:p,family:f}]:p))},c=d=>{let p=o(d);if(ee.isIP(p))return[{address:p,family:ee.isIPv6(p)?6:4}];let f=s.get(p);if(!f||!f.length)throw new Error(`refused: unpinned host ${d} during pinned fetch`);return f},u=new r({connect:{lookup(d,p,f){let m;try{m=c(d)}catch(h){return f(h)}return p?.all?f(null,m):f(null,m[0].address,m[0].family)}}}),l=vo((d,p={})=>n(d,{...p,dispatcher:u}),a);return{dispatcher:u,fetch:l,pin:a,resolve:c,async close(){try{await u.destroy()}catch{}}}}function vo(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[rt]=Object.freeze({pin:t}),e}function nt(e){return typeof e=="function"&&typeof e[rt]?.pin=="function"}function hr(e,t,r){if(!nt(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[rt].pin(t,r)}var So,rt,br=z(()=>{So=new Set(["localhost","metadata.google.internal","metadata.goog"]);rt=Symbol.for("oracle.egressGuard.pinCapableFetch")});import{createHash as yr}from"node:crypto";function Oo(e){let t=String(e||"").toLowerCase();return Ir.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function Co(e){let t={};for(let[r,n]of Object.entries(e||{}))Oo(r)||(t[r]=n);return t}function Lo(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 Ro(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function Sr(e){let t=String(e?.method||"");return t?!_o.test(t):!1}function Po(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(Sr):!r||typeof r!="object"?!1:r.jsonrpc&&r.method?Sr(r):typeof r.type=="string"&&To.has(r.type)&&r.action==null&&r.signature==null&&r.nonce==null}function Bo(e,t,r,n={},o=null){let s={};for(let[p,f]of Object.entries(r||{}))s[p.toLowerCase()]=f;let i=Object.keys(s).filter(p=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(p)),c=[...new Set([...Ir,...i])].sort().map(p=>`${p}=${s[p]??""}`).join(`
3
+ `),u=yr("sha256").update(c).digest("hex").slice(0,32),l=`${n.untrustedUrl?"untrusted":"trusted"}:${n.maxResponseBytes??"unbounded"}`,d=o==null?"-":yr("sha256").update(String(o)).digest("hex").slice(0,32);return`${e} ${t} ${l} ${u} ${d}`}function qo(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,wr):Math.min(250*2**e,wr)+Math.floor(Math.random()*100)}function ge(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function st(e,t,r){return ge(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function we(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function jo(e){return e?e.byteLength??e.length??0:0}async function Er(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&&(we(e),!n))throw st(r,`content-length ${s}`,t);let i=e.body?.getReader?.();if(!i){let d=await e.text(),p=Buffer.byteLength(d,"utf8");if(p>t){if(!n)throw st(r,`body ${p} bytes`,t);return Buffer.from(d,"utf8").subarray(0,t).toString("utf8")}return d}let a=[],c=0,u=!1;try{for(;;){let{value:d,done:p}=await i.read();if(p)break;if(d&&(a.push(Buffer.from(d)),c+=jo(d),c>t)){u=!0;break}}}finally{if(u)try{await i.cancel()}catch{}try{i.releaseLock?.()}catch{}}if(u&&(typeof o=="function"&&o(),!n))throw st(r,`streamed ${c} bytes`,t);let l=Buffer.concat(a);return(u?l.subarray(0,t):l).toString("utf8")}function vr(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function Do(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:s,lookupFn:i,realFetch:a,untrustedUrl:c=!1,maxResponseBytes:u=null,importUndici:l,validateResponse:d,signal:p}){let f=new AbortController,m=setTimeout(()=>f.abort(),s),h=p?typeof AbortSignal.any=="function"?AbortSignal.any([p,f.signal]):p:f.signal,b=null,v=t,I=i?{lookupFn:i}:{};if(c&&!a&&!nt(v))throw ge(`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 C=async(x,{status:g=null}={})=>{let w=await et(x,I);if(!w.ok)throw ge(g==null?`HTTP refused ${x}: ${w.error}`:`HTTP redirect to ${x} ${w.error}`,g==null?{}:{status:g});let A=new URL(x).hostname;if(a){if(b&&(await b.close(),b=null),!b)try{b=await tt({requireUndici:!0,...l?{importUndici:l}:{}})}catch(N){throw ge(g==null?`HTTP refused ${x}: ${N?.message||N}`:`HTTP redirect to ${x} refused: ${N?.message||N}`,g==null?{}:{status:g})}b.pin(A,w.addresses),v=b.fetch}else hr(v,A,w.addresses);return w};try{let x=String(e),g={...n||{}};c&&await C(x);for(let w=0;w<=Ar;w+=1){let A=await v(x,{method:r,headers:g,body:o,signal:h,redirect:"manual"});if(No.has(A.status)){if(r!=="GET"&&r!=="HEAD"){let y=await Er(A,u??ko,{url:x,truncate:!0}),R=new Error(`HTTP ${A.status} ${r} ${x} redirected non-idempotent request`);throw R.status=A.status,R.body=vr(y)??y.slice(0,300),R}if(w===Ar)throw we(A),new Error(`HTTP redirect loop for ${e}`);let O=A.headers?.get?.("location"),L;try{L=Lo(O,x)}catch(y){throw we(A),y}let Q=!Ro(L,x);if(we(A),Q&&(g=Co(g)),c)await C(L,{status:A.status});else if(Q){let y=await et(L,I);if(!y.ok){let R=new Error(`HTTP redirect from ${x} ${y.error}`);throw R.status=A.status,R.retryable=!1,R}a&&y.addresses?.length&&(b||(b=await tt(l?{importUndici:l}:{})),b&&(b.pin(new URL(L).hostname,y.addresses),v=b.fetch))}x=L;continue}if(typeof d=="function")try{await d(A,{url:x})}catch(O){throw we(A),ge(O?.message||String(O))}let N=await Er(A,u,{url:x,onOversize:()=>f.abort()}),k=vr(N);if(!A.ok){let O=new Error(`HTTP ${A.status} ${r} ${x}`);throw O.status=A.status,O.retryAfter=A.headers?.get?.("retry-after")??null,O.body=k??N.slice(0,300),O}return k??N}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(m),b&&await b.close()}}async function K(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):xo,c=t.lookupFn,u=!t.fetchImpl,l=t.untrustedUrl===!0,d=t.importUndici,p=t.validateResponse,f=t.signal,m=Number(t.maxResponseBytes),h=Number.isFinite(m)&&m>0?Math.floor(m):null,b=async()=>{let g;for(let w=0;w<=a;w++){f?.throwIfAborted?.();try{return await Do(e,{fetchImpl:r,method:o,headers:s,body:i,timeoutMs:n,lookupFn:c,realFetch:u,untrustedUrl:l,maxResponseBytes:h,importUndici:d,validateResponse:p,signal:f})}catch(A){g=A;let N=A?.status,k=A?.name==="AbortError"||A?.name==="TimeoutError"||f?.aborted,O=new Set([408,425,429]),L=A?.retryable===!1?!1:N!=null?O.has(N)||Io.has(N)&&gr.has(o):!k&&gr.has(o);if(w===a||!L)throw A;let Q=qo(w,A?.retryAfter);f?await new Promise((y,R)=>{let J=setTimeout(y,Q);f.addEventListener("abort",()=>{clearTimeout(J),R(f.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await Uo(Q)}}throw g};if(!(t.dedupe!==!1&&!f&&Po(o,i)))return b();let I=Bo(o,e,s,{untrustedUrl:l,maxResponseBytes:h},i),C=ot.get(I);if(C)return C;let x=b().finally(()=>ot.delete(I));return ot.set(I,x),x}async function xr(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 Io,gr,xo,wr,Ir,No,Ar,ko,ot,_o,To,Uo,ue=z(()=>{br();Io=new Set([408,425,429,500,502,503,504]),gr=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),xo=2,wr=4e3,Ir=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],No=new Set([301,302,303,307,308]),Ar=3,ko=64*1024;ot=new Map,_o=/(?:^|_)(send|submit|broadcast|sign|requestAirdrop)(?=[A-Z_]|$)/i,To=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);Uo=e=>new Promise(t=>setTimeout(t,e))});function Os(e={}){return String(e.rpcUrl||process.env.SOLANA_RPC_URL||ks).trim()}function le(e,t="address"){let r=String(e||"").trim();if(!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(r))throw new Error(`solana-rpc: ${t} must be a base58 public key`);return r}async function un(e,t=[],r={}){let n=String(e||"");if(n==="sendTransaction"||n==="sendRawTransaction"||n==="requestAirdrop"||n==="requestAirDrop"||/airdrop/i.test(n)||/^send/i.test(n))throw new Error(`solana-rpc: ${n} refused \u2014 @oracle-agent/oracle is prepare-only (no broadcast/airdrop)`);let o=await K(Os(r),{method:"POST",body:{jsonrpc:"2.0",id:r.id||1,method:e,params:t},fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3});if(o?.error)throw new Error(`solana-rpc ${e}: ${o.error.message||JSON.stringify(o.error)}`);return o?.result}var ks,wt=z(()=>{ue();ks="https://api.mainnet-beta.solana.com"});import{createHash as Cs,createHmac as Ls,timingSafeEqual as dc}from"node:crypto";function At(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(At).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${At(e[r])}`).join(",")}}`}function ln(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function dn(e=process.env){return ln(process.env)||ln(e)}function Ps(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function Bs(e){let t=Ps(e);return Cs("sha256").update(At(t)).digest("hex")}function qs(e,t=dn()){return t?Ls("sha256",t).update(String(e)).digest("hex"):""}function pn(e,{provider:t,kind:r,env:n=process.env,nowMs:o=Date.now(),expiresAtMs:s}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let i=Object.prototype.hasOwnProperty.call(e,"oraclePrepared");if(i&&typeof e.oraclePrepared!="boolean")throw new Error("stampPrepared: oraclePrepared must be boolean");let a={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1,oraclePrepared:i?e.oraclePrepared:!0};if(!a.provider)throw new Error("stampPrepared: provider required");if(!a.kind)throw new Error("stampPrepared: kind required");let c=Number(o),u=s==null?c+_s:Number(s),l=u-c;if(!Number.isSafeInteger(c)||!Number.isSafeInteger(u)||l<=0||l>Ts)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let p={...a,preparedAt:c,expiresAt:u,prepareVersion:Rs},f=Bs(p),m=dn(n),h=m?qs(f,m):void 0,b={...p,prepareHash:f};return h&&(b.prepareMac=h),b}var Rs,_s,Ts,fn=z(()=>{Rs=2,_s=300*1e3,Ts=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});function St(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function $s(e){return Us.some(t=>e.startsWith(t))||js.has(e)}function Fs(e){let t=String(e);if(!/^[\x20-\x7e]+$/.test(t))return!0;let r=St(t);return $s(r)?!1:Ds.has(r)?!0:r.includes("signed")||r.includes("signature")||r.endsWith("sig")||r.endsWith("sigs")}function Ms(e){let t=Number(e?.v),r=String(e?.r||""),n=String(e?.s||"");return[0,1,27,28].includes(t)&&/^0x[0-9a-f]{2,64}$/i.test(r)&&/^0x[0-9a-f]{2,64}$/i.test(n)}function Et(e,t=0,r=new Set,n={nodes:0}){if(e==null||typeof e!="object")return[];if(t>16)return["<max-depth>"];if(r.has(e))return[];if(n.nodes+=1,n.nodes>2048)return["<max-nodes>"];if(r.add(e),Array.isArray(e))return e.flatMap(c=>Et(c,t+1,r,n));let o=[];for(let[c,u]of Object.entries(e)){if(Fs(c)){o.push(c);continue}o.push(...Et(u,t+1,r,n))}let i=Object.keys(e).map(St).some(c=>c.endsWith("psbt")||c.endsWith("psbtbase64")),a=Object.entries(e).some(([c,u])=>/complete|finalized|isfinal/.test(St(c))&&u===!0);return i&&a&&o.push("psbt(complete)"),Ms(e)&&o.push("v/r/s"),o}function mn(e,t){let r=Et(t);if(r.length)throw new Error(`${e}: refused a pre-signed transaction payload from the API (fields: ${[...new Set(r)].join(", ")}) \u2014 @oracle-agent/oracle is prepare-only and will not bind signed material into a prepared envelope`)}var Us,js,Ds,hn=z(()=>{Us=["unsigned","notsigned","tosign","signable"],js=new Set(["requiresusersignature","requiressignature","needssignature","signaturerequired","signaturesrequired","signingready","signaturecount","signaturethreshold","requiredsignatures","signatureneeded","hassignature","allowsignatures","requestsignature","multisig","cosig","msig"]),Ds=new Set(["sig","sigs","scriptsig","witness","psbt","finalizedpsbt","completepsbt","finalpsbt","psbtfinalized","serializedtransaction"])});var xt={};We(xt,{JUPITER_MAX_SLIPPAGE_BPS:()=>gn,JUPITER_SWAP_API:()=>xe,SOL_MINT:()=>Ue,USDC_MINT:()=>vt,jupiterHealth:()=>Gs,jupiterPrepareSwap:()=>Qs,jupiterQuote:()=>It,jupiterSignerEnvelope:()=>En,jupiterVenues:()=>Ws,solanaGuard:()=>qe});function wn(e={}){return String(e.baseUrl||process.env.JUPITER_SWAP_API_URL||xe).replace(/\/$/,"")}function Ne(e,t="amount"){try{let r=BigInt(String(e));if(r<=0n)throw new Error("nonpositive");return r.toString()}catch{throw new Error(`jupiter: ${t} must be a positive integer string`)}}function An(e){let t=e==null?50:Number(e);if(!Number.isInteger(t)||t<0)throw new Error("jupiter: slippageBps must be a non-negative integer");if(t>gn)throw new Error("jupiter: slippage exceeds hard 100 bps cap");return t}function Be(e,t){return e==null?t:!!e}function Vs(e){let t=String(e||"").trim();if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t)||t.length%4!==0)throw new Error("jupiter: swapTransaction must be base64");return t}function zs(e,t=0){let r=0,n=0,o=t;for(;o<e.length&&o-t<3;){let s=e[o++];if(r|=(s&127)<<n,(s&128)===0)return{value:r,offset:o};n+=7}return null}function Sn(e){let t=Buffer.from(e,"base64"),r=zs(t,0);if(!r||r.value!==1)throw new Error("jupiter: unsigned swapTransaction must declare exactly one signature slot");let n=r.offset+r.value*64;if(n>=t.length)throw new Error("jupiter: Solana transaction missing message bytes");if(t.subarray(r.offset,n).some(s=>s!==0))throw new Error("jupiter: swapTransaction already contains signature material");return t.subarray(n).toString("base64")}function qe(e={},{quotedAtMs:t=Date.now(),ttlMs:r=bn}={}){let n=le(e.inputMint,"inputMint"),o=le(e.outputMint,"outputMint"),s=Ne(e.inAmount,"inAmount"),i=Ne(e.outAmount,"outAmount"),a=Ne(e.otherAmountThreshold??e.outAmount,"otherAmountThreshold"),c=An(e.slippageBps??50),u=(BigInt(i)-BigInt(i)*BigInt(c)/10000n).toString();if(a!==u)throw new Error("jupiter: otherAmountThreshold does not match serialized min-out");return{mode:"solana-jupiter-quote",provider:"jupiter",venue:"jupiter-swap-v1",inputMint:n,outputMint:o,inAmount:s,outAmount:i,otherAmountThreshold:a,slippageBps:c,contextSlot:e.contextSlot??null,quotedAtMs:t,expiresAtMs:t+Math.min(Math.max(Number(r)||bn,1e3),3e4)}}function En({userPublicKey:e,guard:t,swapTransaction:r,args:n={},response:o={}}){if(t.inputMint!==Ue)throw new Error("jupiter: local signer supports native SOL input only");if(BigInt(o?.prioritizationFeeLamports??0)!==0n)throw new Error("jupiter: local signer requires zero priority fee until exact fee accounting is supplied");let s=Sn(r),i=Ne(n.exactFeeLamports??o.exactFeeLamports??"5000","exactFeeLamports");return{version:1,surface:"sol",action:"swap",owner:e,destination:t.outputMint,tradeId:n.tradeId||`jupiter-${t.inputMint.slice(0,6)}-${t.outputMint.slice(0,6)}-${t.inAmount}`,slippageBps:t.slippageBps,expiresAtMs:t.expiresAtMs,fee:{oracleFeeBps:5},artifact:{cluster:n.cluster||"mainnet",provider:"jupiter",inputMint:t.inputMint,outputMint:t.outputMint,inAmount:t.inAmount,outAmount:t.outAmount,otherAmountThreshold:t.otherAmountThreshold,slippageBps:t.slippageBps,jupiterProgram:n.jupiterProgram||o.jupiterProgram||"JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4",messageBase64:s,exactFeeLamports:i}}}function yn(e){if(typeof e!="string"||!e.length)return!1;let t=0n;for(let o of e){let s=Ks.indexOf(o);if(s<0)return!1;t=t*58n+BigInt(s)}let r=t.toString(16);r.length%2&&(r="0"+r);let n=r.length/2;for(let o of e)if(o==="1")n++;else break;return n===32}async function Ws(e={},t={}){let r=e.rpc||t.solanaRpc||process.env.SOLANA_RPC||"https://api.mainnet-beta.solana.com",n=t.fetchImpl||fetch,o=await n(`${xe}/program-id-to-label`,{signal:AbortSignal.timeout(Number(t.timeoutMs)||15e3)});if(!o.ok)throw new Error(`jupiter venue map failed: HTTP ${o.status}`);let s=await o.json(),i=Object.entries(s),a=i.filter(([p])=>yn(p)),c=[],u=i.filter(([p])=>!yn(p)).map(([p,f])=>({programId:p,label:f,reason:"malformed program id"}));if(e.verify===!1)return{source:`${xe}/program-id-to-label`,verified:a.map(([p,f])=>({programId:p,label:f})),unresolved:u,verifiedOnChain:!1,totals:{fromRouterMap:i.length,verified:a.length}};let l=async p=>{let m=await(await n(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(p),signal:AbortSignal.timeout(Number(t.timeoutMs)||2e4)})).json();if(m.error)throw new Error(m.error.message);return m.result};for(let p=0;p<a.length;p+=90){let f=a.slice(p,p+90),m=null;for(let h=0;h<3&&!m;h++)try{m=await l({jsonrpc:"2.0",id:1,method:"getMultipleAccounts",params:[f.map(([b])=>b),{encoding:"base64",dataSlice:{offset:0,length:0}}]})}catch{await new Promise(b=>setTimeout(b,2e3*(h+1)))}if(!m){for(let[h,b]of f)u.push({programId:h,label:b,reason:"rpc batch failed after 3 attempts"});continue}m.value.forEach((h,b)=>{let[v,I]=f[b];h&&h.executable===!0&&Hs.has(h.owner)?c.push({programId:v,label:I,owner:h.owner}):u.push({programId:v,label:I,reason:h?h.executable!==!0?"not executable":`unknown owner ${h.owner}`:"account not found"})}),p+90<a.length&&await new Promise(h=>setTimeout(h,700))}let d=new Set(c.map(p=>p.label.replace(/\s+(CLMM|CP|V\d+|Launchlab|DLMM|Pools?)$/i,"").trim()));return{source:`${xe}/program-id-to-label`,verifiedOnChain:!0,verifiedAt:new Date().toISOString(),totals:{fromRouterMap:i.length,verified:c.length,unresolved:u.length,distinctLabels:new Set(c.map(p=>p.label)).size,distinctBrands:d.size},verified:c.sort((p,f)=>p.label.localeCompare(f.label)),unresolved:u}}async function Gs(e={}){try{return{ok:!0,provider:"jupiter",outAmount:(await It({inputMint:Ue,outputMint:vt,amount:"1000000",slippageBps:50},e)).quote.outAmount,exec:!1}}catch(t){return{ok:!1,provider:"jupiter",error:String(t?.message||t),exec:!1}}}async function It(e={},t={}){let r=le(e.inputMint||e.fromMint||Ue,"inputMint"),n=le(e.outputMint||e.toMint||vt,"outputMint"),o=Ne(e.amount||e.inAmount,"amount"),s=An(e.slippageBps??e.maxSlippageBps??50),i=new URL(`${wn(t)}/quote`);i.searchParams.set("inputMint",r),i.searchParams.set("outputMint",n),i.searchParams.set("amount",o),i.searchParams.set("slippageBps",String(s)),i.searchParams.set("swapMode",e.swapMode||"ExactIn"),e.onlyDirectRoutes!=null&&i.searchParams.set("onlyDirectRoutes",String(!!e.onlyDirectRoutes)),e.platformFeeBps!=null&&i.searchParams.set("platformFeeBps",String(e.platformFeeBps));let a=await K(i.toString(),{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),c=qe({...a,slippageBps:s},t);return{provider:"jupiter",chain:"solana-mainnet-beta",quoteReady:!0,executionReady:!1,inputMint:r,outputMint:n,amount:o,quote:a,solanaGuard:c}}function Ys(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function Qs(e={},t={}){let r=le(e.userPublicKey||e.owner||e.wallet,"userPublicKey"),n=e.quoteResponse?{quote:e.quoteResponse,solanaGuard:qe(e.quoteResponse,t)}:await It(e,t),o=n.quote,s=n.solanaGuard||qe(o,t);if(Be(e.dynamicSlippage,!1)===!0)throw new Error("jupiter: dynamicSlippage would override the enforced slippage ceiling \u2014 pass an explicit slippageBps instead");let i=await K(`${wn(t)}/swap`,{method:"POST",body:Ys({quoteResponse:o,userPublicKey:r,wrapAndUnwrapSol:Be(e.wrapAndUnwrapSol,!0),dynamicComputeUnitLimit:Be(e.dynamicComputeUnitLimit,!0),dynamicSlippage:!1,asLegacyTransaction:Be(e.asLegacyTransaction,!0),prioritizationFeeLamports:e.prioritizationFeeLamports??0}),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),a=Vs(i?.swapTransaction);Sn(a),mn("jupiter",i);let c=i?.quoteResponse??i?.quote??null,u=["inAmount","outAmount","otherAmountThreshold","inputMint","outputMint"],l=!1;if(c&&typeof c=="object"){for(let f of u){let m=o?.[f],h=c?.[f];if(m==null||h==null)throw new Error(`jupiter: echoed quote is incomplete \u2014 missing ${f}`);if(String(m)!==String(h))throw new Error(`jupiter: swap response ${f} (${h}) does not match the quoted ${f} (${m}) \u2014 refusing to prepare`)}l=!0}let d=null,p=null;try{d=En({userPublicKey:r,guard:s,swapTransaction:a,args:e,response:i})}catch(f){p=String(f?.message||f).slice(0,200)}return pn({provider:"jupiter",chain:"solana-mainnet-beta",prepareReady:!0,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,verifiedAgainstQuote:l,userPublicKey:r,quote:o,solanaGuard:s,swapTransaction:a,localSignerEnvelope:d,localSignerBlockedReason:p,swapTransactionEncoding:"base64",lastValidBlockHeight:i?.lastValidBlockHeight??null,prioritizationFeeLamports:i?.prioritizationFeeLamports??null,computeUnitLimit:i?.computeUnitLimit??null,raw:i},{provider:"jupiter",kind:"jupiter-swap"})}var xe,Ue,vt,gn,bn,Hs,Ks,Nt=z(()=>{ue();wt();fn();hn();xe="https://lite-api.jup.ag/swap/v1",Ue="So11111111111111111111111111111111111111112",vt="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",gn=100,bn=2e4;Hs=new Set(["BPFLoaderUpgradeab1e11111111111111111111111","BPFLoader2111111111111111111111111111111111","BPFLoader1111111111111111111111111111111111"]),Ks="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});var xn={};We(xn,{SELL_SIM:()=>T,assertSellable:()=>ti,simulateSell:()=>In});function Zs(e,t){return t===0n?null:Number((t-e)*10000n/t)}function ei(e,t){if(e==null||e==="")throw new Error(`sell-sim: ${t} required`);if(typeof e=="bigint")return e;let r=String(e).trim();if(!/^\d+$/.test(r))throw new Error(`sell-sim: ${t} must be an integer base-unit amount`);return BigInt(r)}async function In(e={},t={}){let{token:r,base:n,chainId:o=null}=e;if(!r)throw new Error("sell-sim: token required");if(!n)throw new Error("sell-sim: base asset required");if(typeof t.quote!="function")throw new Error("sell-sim: opts.quote function required");let s=ei(e.amountIn,"amountIn"),i;try{i=await t.quote({chainId:o,inputMint:n,outputMint:r,amount:s.toString(),side:"buy"})}catch(f){return V(T.UNKNOWN,`buy leg could not be quoted: ${kt(f)}`,{chainId:o,token:r,base:n})}let a=vn(i?.outAmount);if(a==null||a===0n)return V(T.UNKNOWN,"buy leg returned no output \u2014 no route or no liquidity",{chainId:o,token:r,base:n});let c;try{c=await t.quote({chainId:o,inputMint:r,outputMint:n,amount:a.toString(),side:"sell"})}catch(f){return V(T.HONEYPOT,`buy routes but the SELL leg fails to quote (${kt(f)}) \u2014 you would not be able to exit`,{chainId:o,token:r,base:n,tokensOut:a.toString()})}let u=vn(c?.outAmount);if(u==null||u===0n)return V(T.HONEYPOT,"sell leg returns zero \u2014 the position cannot be exited for value",{chainId:o,token:r,base:n,tokensOut:a.toString()});let l=Zs(u,s),d={chainId:o,token:r,base:n,amountIn:s.toString(),tokensOut:a.toString(),roundTripOut:u.toString(),roundTripLossBps:l,evidence:"quote-only"},p=t.executionProven===!0?!0:null;if(typeof t.executionCheck=="function")try{let f=await t.executionCheck({chainId:o,token:r,base:n,tokensOut:a.toString(),amountIn:s.toString()});if(f?.executable===!1)return V(T.HONEYPOT,`the sell reverts or returns false at execution (${f?.reason||"transfer-level block"}) even though it quotes cleanly \u2014 a honeypot a pool-math quote cannot see`,{...d,evidence:"execution",executable:!1});p=f?.executable===!0?!0:p}catch(f){d.executionCheckError=kt(f)}return p===!0&&(d.evidence="execution"),l==null?V(T.UNKNOWN,"could not compute round-trip loss",d):l>=Js?V(T.HONEYPOT,`round trip loses ${(l/100).toFixed(1)}% \u2014 a sell tax or rigged curve, not normal slippage`,d):l>=Xs?V(T.CAUTION,`round trip loses ${(l/100).toFixed(1)}% \u2014 high tax or thin liquidity`,d):p===!0?V(T.SAFE,`round trip loses ${(l/100).toFixed(1)}% and the sell executes \u2014 exit path verified`,d):V(T.CAUTION,`round trip quotes clean (${(l/100).toFixed(1)}% loss) but is unverified at execution \u2014 a pool-math quote cannot see a transfer-hook blacklist or transfer-only sell tax; run an execution-level sell simulation to clear SAFE`,d)}function V(e,t,r){return{status:e,safe:e===T.SAFE,tradable:e===T.SAFE||e===T.CAUTION,reason:t,...r}}function vn(e){if(e==null)return null;try{let t=String(e).trim();return/^\d+$/.test(t)?BigInt(t):null}catch{return null}}function kt(e){return String(e?.message||e).slice(0,120)}async function ti(e={},t={}){let r=await In(e,t);if(!(r.status===T.SAFE||r.status===T.CAUTION&&t.allowCaution!==!1||r.status===T.UNKNOWN&&t.allowUnknown===!0)){let o=new Error(`sell-sim ${r.status}: ${r.reason}`);throw o.sellSim=r,o}return r}var T,Js,Xs,Nn=z(()=>{T=Object.freeze({SAFE:"SAFE",CAUTION:"CAUTION",HONEYPOT:"HONEYPOT",UNKNOWN:"UNKNOWN"}),Js=5e3,Xs=1500});import je from"node:fs";import si from"node:os";import pe from"node:path";import{fileURLToPath as ii}from"node:url";function Rn(){return process.env.ORACLE_FAKE_HOME||si.homedir()}function ci(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function De(){return ci()?process.env.ORACLE_CONFIG_DIR||pe.join(Rn(),".config","oracle"):pe.join(Rn(),".config","oracle")}function ui(){return pe.join(De(),"desk.json")}function li(){return pe.join(De(),"env")}function de({force:e=!1}={}){if(de._done&&!e)return de._result||null;de._done=!0;let t={},r=(o,s)=>{if(s==null)return;let i=String(s).trim();i&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=i,t[o]=i))};try{let o=li();if(je.existsSync(o))for(let s of je.readFileSync(o,"utf8").split(/\r?\n/)){let i=s.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!i||i[2].startsWith("#"))continue;let a=i[2];(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),r(i[1],a)}}catch{}try{let o=ui();if(je.existsSync(o)){let s=JSON.parse(je.readFileSync(o,"utf8"));s&&typeof s=="object"&&(r("ORACLE_DESK_URL",s.deskUrl||s.dataUrl||s.url),r("ORACLE_DATA_URL",s.dataUrl||s.deskUrl||s.url),r("ORACLE_API_URL",s.apiUrl||s.dataUrl||s.deskUrl),r("ORACLE_PUBLIC_URL",s.publicUrl||s.deskUrl||s.dataUrl),r("ORACLE_EXEC_URL",s.execUrl),r("MAD_DESK_URL",s.deskUrl||s.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),de._result=Object.keys(t).length?t:null,de._result}var ai,vc,_n=z(()=>{ai=pe.dirname(ii(import.meta.url)),vc=pe.resolve(ai,"../..");try{de()}catch{}});var Bn={};We(Bn,{armPreparedAction:()=>gi,callSigner:()=>Tn,queueOwnerAction:()=>Pn});import{existsSync as di,readFileSync as pi}from"node:fs";import{request as fi}from"node:http";import mi from"node:path";function bi(e=process.env){let t=String(e.ORACLE_SIGNER_URL||hi).replace(/\/$/,""),r;try{r=new URL(t)}catch{return null}return r.hostname!=="127.0.0.1"&&r.hostname!=="localhost"&&r.hostname!=="::1"?null:r.origin}function yi(e=process.env){if(e.ORACLE_SIGNER_TOKEN)return String(e.ORACLE_SIGNER_TOKEN);let t=mi.join(De(),"signer","signer-token");return di(t)?pi(t,"utf8").trim():null}function Tn(e,{method:t="GET",body:r=null,env:n=process.env,timeoutMs:o=4e3}={}){let s=bi(n),i=yi(n);return!s||!i?Promise.resolve({ok:!1,error:"local signer is not running"}):new Promise(a=>{let c=new URL(e,s),u=r?Buffer.from(JSON.stringify(r)):null,l=fi({hostname:c.hostname,port:c.port||80,path:c.pathname,method:t,timeout:o,headers:{authorization:`Bearer ${i}`,origin:s,...u?{"content-type":"application/json","content-length":u.length}:{}}},d=>{let p=[];d.on("data",f=>p.push(f)),d.on("end",()=>{let f=Buffer.concat(p).toString("utf8"),m={};try{m=f?JSON.parse(f):{}}catch{m={error:"signer refused"}}a({httpStatus:d.statusCode,...m})})});l.on("timeout",()=>{l.destroy(),a({ok:!1,error:"local signer timed out"})}),l.on("error",()=>a({ok:!1,error:"local signer is not running"})),u&&l.write(u),l.end()})}async function Pn(e,t=process.env){if(!e||e.version!==1||!e.surface)throw new Error("queueOwnerAction: version-1 surface envelope required");return Tn("/pending",{method:"POST",body:{artifact:e},env:t,timeoutMs:8e3})}async function gi(e,t=process.env){let r=e?.localSignerEnvelope||e?.envelope;if(!r||r.version!==1||!r.surface)throw new Error("armPreparedAction: prepared.localSignerEnvelope v1 required");return Pn(r,t)}var hi,qn=z(()=>{_n();hi="http://127.0.0.1:9462"});var be=Object.freeze({PASS:"PASS",WARN:"WARN",BLOCK:"BLOCK",UNKNOWN:"UNKNOWN"}),io=new Set(["LIVE","CACHED","STALE","UNKNOWN","UNAVAILABLE"]),Jt=/^0x[0-9a-fA-F]{40}$/,ao=/^0x[0-9a-fA-F]{64}$/;function ce(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))ce(t);Object.freeze(e)}return e}function M(e,t=null){return e&&typeof e=="object"?structuredClone(e):t}function Zt(e){return typeof e!="string"||!Number.isFinite(Date.parse(e))?null:new Date(e).toISOString()===e?e:null}function Xt(e){return!!(e&&io.has(e.evidence)&&Zt(e.observedAt))}function er(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 Le(e){return[...new Set(e.filter(Boolean))]}function co(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]])!Xt(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||!Xt(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"),er(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=Le(t);return o.length?ce({status:be.BLOCK,whyBlocked:o}):r.length?ce({status:be.UNKNOWN,whyBlocked:Le(r)}):n.length?ce({status:be.WARN,whyBlocked:[],warnings:Le(n)}):ce({status:be.PASS,whyBlocked:[]})}function uo(e={}){let t=M(e,{}),r=Object.fromEntries(Object.entries(t).map(([o,s])=>[o,Zt(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 tr(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("candidate must be an object");let t=M(e.chain,{}),r=M(e.token,{}),n=M(e.pool),o=M(e.venue,{}),s=M(e.signal,{}),i=M(e.route,{});i.cost=er(i.cost);let a=co({...e,chain:t,token:r,pool:n,venue:o,signal:s,route:i}),c=s.unsolicitedAirdrop===!0,u=Jt.test(r.address||"")?r.address.toLowerCase():"unknown-token",l=Jt.test(n?.address||"")?n.address.toLowerCase():ao.test(n?.poolId||"")?n.poolId.toLowerCase():"unknown-pool",d=`${Number.isInteger(t.id)?t.id:"unknown-chain"}:${u}:${l}:${o.key||"unknown-venue"}`;return ce({id:d,status:a.status,chain:t,token:r,pool:n,venue:o,signal:s,risk:M(e.risk,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),sellability:M(e.sellability,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),sellSimulation:M(e.sellSimulation,{verdict:"UNKNOWN",evidence:"UNAVAILABLE",observedAt:null}),quoteAsset:e.quoteAsset??n?.quoteAsset??null,roundTripLossBps:e.roundTripLossBps??null,quoteAmountIn:e.quoteAmountIn??null,quoteSlippageBps:e.quoteSlippageBps??null,quoteAssetDecimals:e.quoteAssetDecimals??null,route:i,prepared:M(e.prepared,{status:"NOT_PREPARED",unsigned:!0}),whyBlocked:Le([...e.whyBlocked||[],...a.whyBlocked]),latency:uo(e.latency),held:c?!1:e.held===!0,eligible:c?!1:a.status===be.PASS&&e.eligible!==!1})}function rr(e=[]){if(!Array.isArray(e))throw new TypeError("candidates must be an array");return Object.freeze(e.map(tr).sort((t,r)=>t.id.localeCompare(r.id)))}import{AbiCoder as lo,keccak256 as po}from"ethers";var nr=/^0x[0-9a-fA-F]{40}$/,H=/^0x[0-9a-fA-F]{64}$/,fo=lo.defaultAbiCoder();function X(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))X(t);Object.freeze(e)}return e}function or(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 mo(e){if(!e||typeof e!="object")return"factory descriptor is invalid";if(!nr.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(!H.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=>!nr.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 ye(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!H.test(r||"")||!/^0{24}[0-9a-f]{40}$/i.test(r.slice(2))?null:`0x${r.slice(-40)}`.toLowerCase()}function ar(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 sr(e,t,r){let n=ar(e,t);if(!H.test(n||""))return null;let o=BigInt(n);return o<1n<<BigInt(r)?o:null}function ir(e,t,r){let n=ar(e,t);if(!H.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 ho(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()||!H.test(e.topics[1]||"")||typeof e.data!="string"||e.data.length!==322)return null;let n=ye(e,{topic:2}),o=ye(e,{topic:3}),s=sr(e,0,24),i=ir(e,1,24),a=ye(e,{dataWord:2}),c=sr(e,3,160),u=ir(e,4,24),l=Z(e.blockNumber),d=Z(e.logIndex);if(!n||!o||s===null||i===null||!a||c===null||u===null||l===null||d===null||!H.test(e.transactionHash||""))return null;let p=new Set(t.quoteAssets.map(C=>C.toLowerCase())),f=p.has(n),m=p.has(o);if(f===m)return null;let h=f?o:n,b=f?n:o;if(po(fo.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}:${d}`,chainId:t.chainId,factoryId:t.id||null,factoryAddress:t.factoryAddress.toLowerCase(),tokenAddress:h,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:u,venue:structuredClone(t.venue),kind:r.kind||"pool-initialized",blockNumber:l,blockHash:H.test(e.blockHash||"")?e.blockHash.toLowerCase():null,transactionHash:I,logIndex:d,evidence:"LIVE"}}function bo(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,a=typeof e.data=="string"&&/^0x[0-9a-f]*$/i.test(e.data)?e.data:null;if(e.topics.length<s||a==null||i>0&&a.length<2+i*64)return null;let c=ye(e,r.layout.token),u=ye(e,r.layout.pool),l=Z(e.blockNumber),d=Z(e.logIndex);if(!c||!u||l===null||d===null||!H.test(e.transactionHash||""))return null;let p=e.transactionHash.toLowerCase();return{id:`${t.chainId}:${p}:${d}`,chainId:t.chainId,factoryId:t.id||null,factoryAddress:t.factoryAddress.toLowerCase(),tokenAddress:c,poolAddress:u,venue:structuredClone(t.venue),kind:r.kind||"launch",blockNumber:l,blockHash:H.test(e.blockHash||"")?e.blockHash.toLowerCase():null,transactionHash:p,logIndex:d,evidence:"LIVE"}}function yo(e,t,r){return r.decoder==="uniswap-v4-initialize"?ho(e,t,r):bo(e,t,r)}async function cr(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=X({nextBlock:Z(e.cursor?.nextBlock)??o});if(n)return X({status:"UNKNOWN",discoveries:[],unavailable:[],cursor:i,whyBlocked:["reorg hint requires canonical range reconciliation"]});let a=[],c=[];for(let d of r){let p=mo(d);p?a.push({id:d?.id||null,status:"UNAVAILABLE",reason:p}):c.push(d)}if(c.sort((d,p)=>`${d.chainId}:${d.factoryAddress.toLowerCase()}:${d.id||""}`.localeCompare(`${p.chainId}:${p.factoryAddress.toLowerCase()}:${p.id||""}`)),a.sort((d,p)=>String(d.id).localeCompare(String(p.id))),c.length===0)return X({status:"UNAVAILABLE",discoveries:[],unavailable:a,cursor:i,whyBlocked:a.map(d=>d.reason)});let u=[];for(let d of c){let p=[...d.events].sort((h,b)=>h.topic0.localeCompare(b.topic0)),f=[...new Set(p.map(h=>h.topic0.toLowerCase()))].sort(),m;try{m=await t.scanBlocks({fromBlock:o,toBlock:s,address:d.factoryAddress,topics:[f]})}catch(h){return X({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`scan failed: ${or(h)}`]})}if(!m||m.complete!==!0||m.evidence&&m.evidence!=="LIVE"){let h=Array.isArray(m?.failedAt)?` at ${m.failedAt.join("-")}`:"";return X({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`incomplete block range${h}${m?.error?`: ${or(m.error)}`:""}`]})}for(let h of Array.isArray(m.logs)?m.logs:[]){let b=p.find(I=>I.topic0.toLowerCase()===String(h?.topics?.[0]||"").toLowerCase()),v=b&&yo(h,d,b);v&&u.push(v)}}let l=new Map;for(let d of u.sort((p,f)=>p.id.localeCompare(f.id)))l.has(d.id)||l.set(d.id,d);return X({status:"LIVE",discoveries:[...l.values()],unavailable:a,cursor:{nextBlock:s+1},whyBlocked:a.map(d=>d.reason)})}import{createHash as go}from"node:crypto";var ur="sha256:"+"0".repeat(64);function Ye(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Ye(t);Object.freeze(e)}return e}function Ge(e){return Array.isArray(e)?`[${e.map(Ge).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Ge(e[t])}`).join(",")}}`:JSON.stringify(e)}function lr(e){return`sha256:${go("sha256").update(Ge(e)).digest("hex")}`}function dr(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 Qe(e=[]){if(!Array.isArray(e))throw new TypeError("evidence records must be an array");let t=new Set,r=ur,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=dr(o,s+1,r),a=lr(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 Ye(n)}function Je(e=[],t){let r=Qe(e);if(r.some(s=>s.id===t?.id))throw new Error(`duplicate evidence event id: ${t.id}`);let n=r.at(-1)?.digest??ur,o=dr(t,r.length+1,n);return Ye([...r,{...o,digest:lr(o)}])}var pr=Object.freeze({ALERT_ONLY:"alert_only",EXECUTE:"execute"});function fr(e){return e?.mode==="shadow"?pr.ALERT_ONLY:pr.EXECUTE}function Re(e,t){return!!(e?.mode&&e.mode!=="shadow"&&t?.policyEligible===!0)}function mr(e,t,r){return Re(e,t)&&r?.prepared===!0}var wo="0x783cca1c0412dd0d695e784568c96da2e9c22ff989357a2e8b1d9b2b4e6b7118",ba=Object.freeze([Object.freeze({topic0:wo,kind:"pool-created",layout:Object.freeze({token:Object.freeze({topic:2}),fee:Object.freeze({topic:3}),tickSpacing:Object.freeze({dataWord:0}),pool:Object.freeze({dataWord:1})})})]),ya=Object.freeze({amountIn:"1000000000000000",quoteAssetDecimals:18,slippageBps:100,maxImpactPct:25,timeoutMs:4e3}),ga=Object.freeze({amountIn:"1000000",quoteAssetDecimals:9,slippageBps:100,maxImpactPct:25,timeoutMs:12e3}),wa=Object.freeze([Object.freeze({chainId:1,key:"ethereum",factoryAddress:"0x1f98431c8ad98523631ae4a59f267346ea31f984",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"}),Object.freeze({chainId:10,key:"optimism",factoryAddress:"0x1f98431c8ad98523631ae4a59f267346ea31f984",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"}),Object.freeze({chainId:56,key:"bsc",factoryAddress:"0xdb1d10011ad0ff90774d0c6bb92e5c5c8b4461f7",router:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2"}),Object.freeze({chainId:137,key:"polygon",factoryAddress:"0x1f98431c8ad98523631ae4a59f267346ea31f984",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"}),Object.freeze({chainId:8453,key:"base",factoryAddress:"0x33128a8fc17869897dce68ed026d694621f6fdfd",router:"0x2626664c2603336E57B271c5C0b26F421741e481"}),Object.freeze({chainId:42161,key:"arbitrum",factoryAddress:"0x1f98431c8ad98523631ae4a59f267346ea31f984",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"}),Object.freeze({chainId:43114,key:"avalanche",factoryAddress:"0x740b1c1de25031c31ff4fc9a62f554a55cdc1bad",router:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE"}),Object.freeze({chainId:999,key:"hyperevm",factoryAddress:"0xb1c0fa0b789320044a6f623cfe5ebda9562602e3",router:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D"}),Object.freeze({chainId:988,key:"stable",factoryAddress:"0x88f0a512ef09175d456bc9547f914f48c013e4aa",router:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",provenance:"chains.config router.factory() on 2026-08-05"}),Object.freeze({chainId:2741,key:"abstract",factoryAddress:"0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1",router:"0x7712FA47387542819d4E35A23f8116C90C18767C",provenance:"chains.config pool.factory() on 2026-08-05"}),Object.freeze({chainId:4663,key:"robinhood",factoryAddress:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",router:"0xcaf681a66d020601342297493863e78c959e5cb2"})]);import Ke from"node:fs";import Ki from"node:os";import Y from"node:path";ue();var Nr={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}},$o=new Map(Object.values(Nr).map(e=>[e.chainId,e]));function kr(e){return $o.get(Number(e))||null}function Or(e,t=process.env){let r=kr(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 Fo,getAddress as Mo}from"ethers";var Cr=new Fo(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Lr(e,t){try{return Mo(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}var Vo={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 zo(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=Or(e,r);return n||Vo[Number(e)]||null}var Ho=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Ko(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!Ho.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 Ae=new Map,Rr=new Map;function Wo(e){let t=new Error(e?.message||JSON.stringify(e));return t.code=e?.code,t}function Go(e){if(e?.error)throw Wo(e.error);return e?.result}function Yo(e,t,r){return`${e}
4
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>"}:
5
+ ${JSON.stringify(r??[])}`}async function Qo(e,t,r){return K(e,{method:"POST",body:t,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function P(e,t,r=[],n={}){let o=String(t||""),s=Ko(o),i=zo(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=Rr.get(i);if(l!=null)return l}let c=n.dedupe!==!1&&!n.signal?Yo(i,o,r):null;if(c&&Ae.has(c))return Ae.get(c);let u=(async()=>{let l=await Qo(i,{jsonrpc:"2.0",id:1,method:t,params:r},n),d=Go(l);return s==="eth_chainid"&&typeof d=="string"&&Rr.set(i,d),d})();return c&&(Ae.set(c,u),u.finally(()=>{Ae.get(c)===u&&Ae.delete(c)}).catch(()=>{})),u}async function _r(e,t={}){let r=await P(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function Tr(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await P(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function Pr(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=Lr(e.token||e.tokenAddress,"token"),o=Lr(e.account||e.owner||e.address,"account"),s=Cr.encodeFunctionData("balanceOf",[o]),i=await P(r,"eth_call",[{to:n,data:s},e.blockTag||"latest"],t),a=Cr.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"}}ue();var Jo=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"]);function Br(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 it(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,u)=>{let l=Br(o,c),d=String(l.address||"").toLowerCase(),p=String(l.symbol||"").toLowerCase(),f=Number(c.liquidityUsd??c.liquidity?.usd),m=Number.isFinite(f)?f:0,h=String(c.dex||c.dexId||"").toLowerCase(),b=0;return s.has(d)||Jo.has(p)?b=300:i&&d===i&&(b=100),h.includes("v4")?b+=20:h.includes("v3")?b+=10:(h.includes("v2")||h.includes("raydium")||h.includes("orca")||h.includes("meteora"))&&(b+=8),{pool:c,score:b*1e12+m,index:u,otherAddr:d,liquidityUsd:m}});return a.sort((c,u)=>u.score-c.score||c.index-u.index),a.map(c=>c.pool)}function qr(e,t=[]){let r=Array.isArray(t)?t:[];return r.length&&Br(e,r[0]).address||null}var Xo="https://api.dexscreener.com",qa=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function Zo(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||Xo).replace(/\/$/,"")}async function Ur(e,t={}){if(!e)throw new Error("tokenAddress required");return K(`${Zo(t)}/latest/dex/tokens/${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}ue();var Te=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),E=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),S=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),es=/^0x[0-9a-fA-F]{40}$/;function ts(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}es.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))Te.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 rs(e){let{ok:t,errors:r,warnings:n}=ts(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
6
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
7
+ - `)}`);let o=e.capabilities||{},s=Te.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:Te.filter(a=>!s.includes(a))}},supports(a){return s.includes(a)}};for(let a of Te)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 jr=new Map;function Dr(e){let t=rs(e);return jr.set(t.chainId,t),t}function $r(e){return jr.get(Number(e))||null}var ct={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},$=e=>BigInt(e).toString(16).padStart(64,"0"),Se=e=>e.slice(2).toLowerCase().padStart(64,"0");function ns(e,t){return`0x${ct.getAmountsOut}`+$(e)+$(64)+$(t.length)+t.map(Se).join("")}function os(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 at(e,t="router"){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}var ut=100;function ss(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>ut)throw new Error(`slippageBps ${r} exceeds the ${ut} 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 Fr(e){let{chainId:t,wrappedNative:r}=e;async function n(o,s,i,a){let c=await P(t,"eth_call",[{to:o,data:ns(s,i)},"latest"],a);return os(c?.result??c)}return{async quote({tokenIn:o,tokenOut:s,amountIn:i,path:a},c={}){let u=at(c.scanner);if(!u)return{chainId:t,evidence:E.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(p=>!/^0x[0-9a-fA-F]{40}$/.test(p||"")))throw new Error("quote requires valid 20-byte addresses");let d=await n(u,i,l,c);return d?{chainId:t,router:u,path:l,amountIn:String(i),amountOut:d[d.length-1].toString(),hops:l.length-1,evidence:E.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:u,path:l,evidence:E.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=at(a.scanner),u=i||r;if(u&&String(o).toLowerCase()===String(u).toLowerCase())return{chainId:t,token:o,verdict:S.UNKNOWN,evidence:E.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!c||!u)return{chainId:t,token:o,verdict:S.UNKNOWN,evidence:E.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,[u,o],a);if(!l)return{chainId:t,token:o,verdict:S.FAIL,evidence:E.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let d=l[l.length-1];if(d===0n)return{chainId:t,token:o,verdict:S.FAIL,evidence:E.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let p=await n(c,d,[o,u],a);if(!p)return{chainId:t,token:o,verdict:S.FAIL,evidence:E.LIVE,leg:"sell",bought:d.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let f=p[p.length-1],m=Number(f*10000n/BigInt(s)),h=S.PASS,b="round trip completes with expected fee/impact loss";return m<5e3?(h=S.FAIL,b=`round trip returns only ${(m/100).toFixed(2)}% -- punitive tax or no real liquidity`):m<9e3&&(h=S.CAUTION,b=`round trip returns ${(m/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:o,base:u,router:c,verdict:h,reason:b,amountIn:String(s),bought:d.toString(),returned:f.toString(),retentionBps:m,evidence:E.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:u=900,path:l},d={}){let p=d.scanner,f=at(p);if(!f)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 m=l||[o,s],h=await this.quote({tokenIn:o,tokenOut:s,amountIn:i,path:m},d);if(h.evidence!==E.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let b=ss(h.amountOut,c);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let v=BigInt(Math.floor(Date.now()/1e3)+Number(u)),I=r&&m[0].toLowerCase()===r.toLowerCase()&&d.useNative,C=I?`0x${ct.swapExactETHForTokens}`+$(b)+$(128)+Se(a)+$(v)+$(m.length)+m.map(Se).join(""):`0x${ct.swapExactTokensForTokens}`+$(i)+$(b)+$(160)+Se(a)+$(v)+$(m.length)+m.map(Se).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:f,data:C,value:I?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:h.amountOut,minOut:b.toString(),slippageBps:c,maxSlippageBps:ut,deadline:v.toString()},requires:I?[]:[{step:"approve",token:m[0],spender:f,amount:String(i)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var is=[100,500,3e3,1e4],Mr={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},te=e=>BigInt(e).toString(16).padStart(64,"0"),Ee=e=>e.slice(2).toLowerCase().padStart(64,"0"),Vr=/^0x[0-9a-fA-F]{40}$/,dt=100;function as(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>dt)throw new Error(`slippageBps ${r} exceeds the ${dt} 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 lt(e,t){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function zr(e){let{chainId:t,wrappedNative:r}=e;async function n({quoter:s,tokenIn:i,tokenOut:a,amountIn:c,fee:u},l){let d=`0x${Mr.quoteExactInputSingle}`+Ee(i)+Ee(a)+te(c)+te(u)+te(0),p=await P(t,"eth_call",[{to:s,data:d},"latest"],l).catch(()=>null),f=p?.result??p;if(!f||f==="0x"||f.length<66)return null;let m=BigInt(`0x${f.slice(2,66)}`);return m>0n?m:null}async function o({quoter:s,tokenIn:i,tokenOut:a,amountIn:c},u){let l=await Promise.all(is.map(async p=>{let f=await n({quoter:s,tokenIn:i,tokenOut:a,amountIn:c,fee:p},u);return{fee:p,amountOut:f?f.toString():null,out:f}})),d=null;for(let p of l)p.out&&(!d||p.out>d.amountOut)&&(d={fee:p.fee,amountOut:p.out});return{best:d,tried:l.map(({fee:p,amountOut:f})=>({fee:p,amountOut:f}))}}return{async quote({tokenIn:s,tokenOut:i,amountIn:a},c={}){let u=lt(c.scanner,"quoter");if(!u)return{chainId:t,evidence:E.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let p of[s,i])if(!Vr.test(p||""))throw new Error("quote requires valid 20-byte addresses");let{best:l,tried:d}=await o({quoter:u,tokenIn:s,tokenOut:i,amountIn:a},c);return l?{chainId:t,venue:"uniswap-v3",quoter:u,tokenIn:s,tokenOut:i,amountIn:String(a),amountOut:l.amountOut.toString(),fee:l.fee,useNative:!!r&&String(s).toLowerCase()===String(r).toLowerCase(),triedFeeTiers:d,evidence:E.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:u,tokenIn:s,tokenOut:i,triedFeeTiers:d,evidence:E.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 u=lt(c.scanner,"quoter"),l=(e.stableQuoteAssets||[]).map(g=>String(g).toLowerCase()),d=null;!a&&typeof e.resolveQuoteAsset=="function"&&(d=await e.resolveQuoteAsset(s,c).catch(()=>null));let p=String(s).toLowerCase(),f=String(r||"").toLowerCase();if(f&&p===f)return{chainId:t,token:s,verdict:S.UNKNOWN,evidence:E.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 m=a||d||(l[0]&&p!==l[0]?l[0]:null)||r;if(m&&p===String(m).toLowerCase())return{chainId:t,token:s,verdict:S.UNKNOWN,evidence:E.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!u||!m)return{chainId:t,token:s,verdict:S.UNKNOWN,evidence:E.UNAVAILABLE,reason:u?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let h=await o({quoter:u,tokenIn:m,tokenOut:s,amountIn:i},c);if(!h.best){let g=l.find(w=>w&&w!==String(m).toLowerCase()&&w!==String(s).toLowerCase());if(g){let w=await o({quoter:u,tokenIn:g,tokenOut:s,amountIn:i},c);if(w.best){let A=await o({quoter:u,tokenIn:s,tokenOut:g,amountIn:w.best.amountOut},c);if(A.best){let N=A.best.amountOut,k=Number(N*10000n/BigInt(i)),O=S.PASS,L="round trip vs dollar book completes with expected fee/impact loss";return k<5e3?(O=S.FAIL,L=`round trip vs dollar book returns only ${(k/100).toFixed(2)}% -- punitive tax or no real liquidity`):k<9e3&&(O=S.CAUTION,L=`round trip vs dollar book returns ${(k/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:s,base:g,quoteAsset:g,verdict:O,reason:L,amountIn:String(i),bought:w.best.amountOut.toString(),returned:N.toString(),retentionBps:k,buyFee:w.best.fee,sellFee:A.best.fee,evidence:E.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:t,token:s,verdict:S.FAIL,evidence:E.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:u,tokenIn:s,tokenOut:m,amountIn:h.best.amountOut},c);if(!b.best){let g=l.find(w=>w&&w!==String(m).toLowerCase()&&w!==String(s).toLowerCase());if(g){let w=await o({quoter:u,tokenIn:g,tokenOut:s,amountIn:i},c),A=w.best?await o({quoter:u,tokenIn:s,tokenOut:g,amountIn:w.best.amountOut},c):{best:null};if(w.best&&A.best){let N=A.best.amountOut,k=Number(N*10000n/BigInt(i)),O=S.PASS,L="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return k<5e3?(O=S.FAIL,L=`dollar-book round trip returns only ${(k/100).toFixed(2)}%`):k<9e3&&(O=S.CAUTION,L=`dollar-book round trip returns ${(k/100).toFixed(2)}%`),{chainId:t,venue:"uniswap-v3",token:s,base:g,quoteAsset:g,verdict:O,reason:L,amountIn:String(i),bought:w.best.amountOut.toString(),returned:N.toString(),retentionBps:k,buyFee:w.best.fee,sellFee:A.best.fee,evidence:E.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:t,token:s,verdict:S.FAIL,evidence:E.LIVE,leg:"sell",bought:h.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let v=b.best.amountOut,I=Number(v*10000n/BigInt(i)),C=S.PASS,x="round trip completes with expected fee/impact loss";return I<5e3?(C=S.FAIL,x=`round trip returns only ${(I/100).toFixed(2)}% -- punitive tax or no real liquidity`):I<9e3&&(C=S.CAUTION,x=`round trip returns ${(I/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:s,base:m,verdict:C,reason:x,amountIn:String(i),bought:h.best.amountOut.toString(),returned:v.toString(),retentionBps:I,buyFee:h.best.fee,sellFee:b.best.fee,evidence:E.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:u=50,fee:l},d={}){let p=lt(d.scanner,"router");if(!p)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(!Vr.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=await this.quote({tokenIn:s,tokenOut:i,amountIn:a},d);if(f.evidence!==E.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let m=l??f.fee,h=as(f.amountOut,u);if(h<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=!!(d.useNative||f.useNative)&&r&&String(s).toLowerCase()===String(r).toLowerCase(),v=`0x${Mr.exactInputSingle}`+Ee(s)+Ee(i)+te(m)+Ee(c)+te(a)+te(h)+te(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:p,data:v,value:b?String(a):"0x0"},guard:{quotedOut:f.amountOut,minOut:h.toString(),slippageBps:u,maxSlippageBps:dt,fee:m},requires:b?[]:[{step:"approve",token:s,spender:p,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 Pe={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function Hr(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function Kr(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 cs(e){let{chainId:t}=e;async function r(n,o,s){return P(t,"eth_call",[{to:n,data:o},"latest"],s)}return{async blockNumber(n={}){let o=await _r(t,n);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:E.LIVE}},async nativeBalance(n,o={}){let s=await Tr(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:E.LIVE}},async tokenBalance({token:n,owner:o},s={}){let i=await Pr({chainId:t,token:n,owner:o},s);return{chainId:t,token:n,owner:o,raw:i?.balance??i,evidence:E.LIVE}},async resolveToken(n,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:t,token:n,evidence:E.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,Pe.decimals,o).catch(()=>null),r(n,Pe.symbol,o).catch(()=>null),r(n,Pe.name,o).catch(()=>null),r(n,Pe.totalSupply,o).catch(()=>null)]),u=Hr(s?.result??s),l=u!==null||i?.result||a?.result,d={chainId:t,address:n,decimals:u===null?null:Number(u),symbol:Kr(i?.result??i),name:Kr(a?.result??a),totalSupply:(Hr(c?.result??c)??null)?.toString()??null,evidence:l?E.LIVE:E.UNKNOWN};return l||(d.warning="no ERC-20 metadata returned -- may not be a token contract"),d},async resolvePools(n,o={}){let s=e.dexscreenerSlug;if(!s)return{chainId:t,token:n,pools:[],evidence:E.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await Ur(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,d)=>(d.liquidityUsd??0)-(l.liquidityUsd??0)),u=it(n,c,{stables:e.stableQuoteAssets||[],wrappedNative:e.wrappedNative});return{chainId:t,token:n,pools:u,topPool:u[0]||null,quoteAsset:qr(n,u),evidence:u.length?E.LIVE:E.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 u=[],l=[];for(let p=n;p<=o;p+=a){let f=Math.min(p+a-1,o);l.push([p,f])}let d=await xr(l,4,async([p,f])=>{let m={fromBlock:`0x${p.toString(16)}`,toBlock:`0x${f.toString(16)}`};s&&(m.address=s),i&&(m.topics=i);let h=await P(t,"eth_getLogs",[m],c).catch(b=>({error:String(b?.message||b)}));return{start:p,end:f,res:h}});for(let{start:p,end:f,res:m}of d){if(m?.error)return{chainId:t,fromBlock:n,toBlock:o,logs:u,complete:!1,failedAt:[p,f],error:m.error,evidence:E.UNKNOWN};for(let h of m?.result??m??[])u.push(h)}return{chainId:t,fromBlock:n,toBlock:o,logs:u,complete:!0,chunks:l.length,evidence:E.LIVE}},async scoreRisk(n,o={}){let s=[],i=S.PASS,a=l=>{let d={[S.PASS]:0,[S.CAUTION]:1,[S.UNKNOWN]:2,[S.FAIL]:3};d[l]>d[i]&&(i=l)},[c,u]=await Promise.all([this.resolveToken(n,o),this.resolvePools(n,o)]);if(c.evidence!==E.LIVE?(s.push({check:"erc20-metadata",result:S.UNKNOWN,detail:c.warning}),a(S.UNKNOWN)):s.push({check:"erc20-metadata",result:S.PASS,detail:`${c.symbol} / ${c.decimals}d`}),u.evidence===E.UNAVAILABLE)s.push({check:"liquidity",result:S.UNKNOWN,detail:u.reason}),a(S.UNKNOWN);else if(!u.pools.length)s.push({check:"liquidity",result:S.FAIL,detail:"no pool with liquidity found"}),a(S.FAIL);else{let l=u.pools[0],d=l.liquidityUsd??0;d<5e3?(s.push({check:"liquidity",result:S.CAUTION,detail:`top pool only $${d}`}),a(S.CAUTION)):s.push({check:"liquidity",result:S.PASS,detail:`$${d} on ${l.dex}`}),l.createdAt&&Date.now()-l.createdAt<24*3600*1e3&&(s.push({check:"age",result:S.CAUTION,detail:"pool under 24h old"}),a(S.CAUTION))}if(typeof this.sellSimulation=="function"){let l=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},o).catch(d=>({verdict:S.UNKNOWN,reason:String(d?.message||d)}));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:S.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(S.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 Wr(e){let r={...cs(e)},n=new Set((e.venues||[]).map(s=>s.kind));e.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,zr({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,Fr({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 us=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 Gr(){return us.map(e=>Dr(Wr(e)))}import{AbiCoder as ls,Interface as Zr,getAddress as ne,isAddress as en,keccak256 as ds}from"ethers";var pt="0x0000000000000000000000000000000000000000",ps="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",fs=ls.defaultAbiCoder(),Yr=new Zr(["function quoteExactInputSingle((address tokenIn,address tokenOut,uint256 amountIn,uint24 fee,uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut,uint160 sqrtPriceX96After,uint32 initializedTicksCrossed,uint256 gasEstimate)"]),Qr=new Zr(["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)"]),F=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"})}),Ie=Object.freeze({1:Object.freeze({quoter:"0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203",wrappedNative:F[1].wrappedNative}),10:Object.freeze({quoter:"0x1f3131a13296fb91c90870043742c3cdbff1a8d7",wrappedNative:F[10].wrappedNative}),56:Object.freeze({quoter:"0x9f75dd27d6664c475b90e105573e550ff69437b0",wrappedNative:F[56].wrappedNative}),137:Object.freeze({quoter:"0xb3d5c3dfc3a7aebff71895a7191796bffc2c81b9",wrappedNative:F[137].wrappedNative}),8453:Object.freeze({quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",wrappedNative:F[8453].wrappedNative}),42161:Object.freeze({quoter:"0x3972c00f7ed4885e145823eb7c655375d275a1c5",wrappedNative:F[42161].wrappedNative}),43114:Object.freeze({quoter:"0xbe40675bb704506a3c2ccfb762dcfd1e979845c2",wrappedNative:F[43114].wrappedNative}),4663:Object.freeze({quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",wrappedNative:F[4663].wrappedNative})}),ms=Object.freeze([100,500,3e3,1e4]);function re(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 tn(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 rn(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 ft(e){let t=String(e??"").trim().toLowerCase();return t===""||t==="eth"||t===pt||t===ps}function ve(e,t){if(!en(String(e??"")))throw new Error(`${t} must be an EVM address`);return ne(String(e))}function Jr(e,t,r){return ft(e)?ne(t.wrappedNative):ve(e,r)}function Xr(e,t){return ft(e)?ne(pt):ve(e,t)}function nn(e,t){let r=Number(e);if(!Number.isInteger(r)||r<0||r>16777215)throw new Error(`${t} must be uint24`);return r}function hs(e,t){let r=Number(e);if(!Number.isInteger(r)||r<-8388608||r>8388607)throw new Error(`${t} must be int24`);return r}function bs({tokenIn:e,tokenOut:t,poolKey:r,poolId:n}){re(r,new Set(["currency0","currency1","fee","tickSpacing","hooks"]),"V4 PoolKey");let o=ve(r.currency0,"V4 currency0"),s=ve(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:nn(r.fee,"V4 fee"),tickSpacing:hs(r.tickSpacing,"V4 tickSpacing"),hooks:ve(r.hooks??pt,"V4 hooks")}),a=Xr(e,"tokenIn"),c=Xr(t,"tokenOut");if(a.toLowerCase()===c.toLowerCase())throw new Error("tokenIn and tokenOut must differ");let u=new Set([i.currency0.toLowerCase(),i.currency1.toLowerCase()]);if(!u.has(a.toLowerCase())||!u.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=ds(fs.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 mt(e,t){if(ft(t))return!0;if(!en(String(t??"")))return!1;let r=F[Number(e)]?.wrappedNative||Ie[Number(e)]?.wrappedNative;return!!(r&&ne(String(t)).toLowerCase()===ne(r).toLowerCase())}async function on(e={},t={},r={}){re(e,new Set(["chainId","tokenIn","tokenOut","amountIn","fee"]),"V3 read"),re(t,new Set(["timeoutMs"]),"V3 read options"),re(r,new Set(["rpc"]),"V3 read dependencies");let n=Number(e.chainId),o=F[n];if(!o)throw new Error(`V3 read unavailable on chain ${e.chainId}`);let s=Jr(e.tokenIn,o,"tokenIn"),i=Jr(e.tokenOut,o,"tokenOut");if(s.toLowerCase()===i.toLowerCase())throw new Error("tokenIn and tokenOut must differ");let a=tn(e.amountIn,"amountIn"),c=e.fee==null?ms:[nn(e.fee,"V3 fee")],u=r.rpc||P,l=rn(t.timeoutMs),d=await Promise.all(c.map(async f=>{let m=Yr.encodeFunctionData("quoteExactInputSingle",[{tokenIn:s,tokenOut:i,amountIn:a,fee:f,sqrtPriceLimitX96:0n}]);try{let h=await u(n,"eth_call",[{to:o.quoter,data:m},"latest"],l);if(!h||h==="0x")throw new Error("empty result");let b=Yr.decodeFunctionResult("quoteExactInputSingle",h);return Object.freeze({ok:!0,fee:f,amountOut:b[0].toString(),gasEstimate:b[3].toString()})}catch(h){return Object.freeze({ok:!1,fee:f,error:String(h?.message||h).slice(0,160)})}})),p=d.filter(f=>f.ok).sort((f,m)=>BigInt(m.amountOut)>BigInt(f.amountOut)?1:-1)[0];if(!p)throw new Error(`V3 read failed chain=${n}: ${d.map(f=>`${f.fee}:${f.error}`).join("; ")}`);return Object.freeze({venue:"uniswap-v3",chainId:n,quoter:ne(o.quoter),tokenIn:s,tokenOut:i,amountIn:a.toString(),amountOut:p.amountOut,gasEstimate:p.gasEstimate,fee:p.fee,triedFees:Object.freeze(d),executionReady:!1})}async function sn(e={},t={},r={}){re(e,new Set(["chainId","tokenIn","tokenOut","amountIn","poolKey","poolId"]),"V4 read"),re(t,new Set(["timeoutMs"]),"V4 read options"),re(r,new Set(["rpc"]),"V4 read dependencies");let n=Number(e.chainId),o=Ie[n];if(!o)throw new Error(`V4 read unavailable on chain ${e.chainId}`);let s=tn(e.amountIn,"amountIn");if(s>0xffffffffffffffffffffffffffffffffn)throw new Error("amountIn exceeds uint128");let i=bs(e),a=Qr.encodeFunctionData("quoteExactInputSingle",[{poolKey:i.poolKey,zeroForOne:i.zeroForOne,exactAmount:s,hookData:"0x"}]),u=await(r.rpc||P)(n,"eth_call",[{to:o.quoter,data:a},"latest"],rn(t.timeoutMs));if(!u||u==="0x")throw new Error("V4 read returned an empty result");let l=Qr.decodeFunctionResult("quoteExactInputSingle",u);return Object.freeze({venue:"uniswap-v4",chainId:n,quoter:ne(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 ys=new Set(["chainId","tokenIn","tokenOut","amountIn","v4PoolKey","v4PoolId"]),gs=new Set(["maxImpactPct","timeoutMs"]),ws=new Set(["quoteV3","quoteV4","gasPrice"]);function ht(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 yt(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 an(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 W(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 As(e){if(e<=1n)return null;let t=e/1000n;return t>0n&&t<e?t:1n}function Ss({amountIn:e,amountOut:t,probeIn:r,probeOut:n}){let o=W(e),s=W(t),i=W(r),a=W(n);if(!o||!s||!i||!a||a<=0n)return null;let c=a*o;if(c<=0n)return null;let u=s*i*1000000000n/c;return u>=1000000000n?0:Number(1000000000n-u)/1e7}function bt(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 Es({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,amountOut:o,gasEstimate:s,gasPrice:i}){let a=W(s),c=W(i),u=W(n),l=W(o);if(!a||!c||!u||!l||a<=0n||c<=0n)return null;let d=a*c;return mt(e,r)?d:mt(e,t)?d*l/u:null}async function vs(e,t){let r=await P(e,"eth_gasPrice",[],{timeoutMs:t});return W(r)}function Is(e,t){return Object.freeze({source:e,quality:"FAILED",amountOut:null,error:String(t?.message||t).slice(0,240)})}async function cn({source:e,amountIn:t,timeoutMs:r,fullRead:n,probeRead:o}){try{let s=await bt(n,r,e),i=yt(s?.amountOut,`${e} amountOut`),a=As(t);if(a==null)return{source:e,full:s,impactPct:null};try{let c=await bt(()=>o(a.toString(),s),r,`${e} impact probe`),u=Ss({amountIn:t,amountOut:i,probeIn:a,probeOut:c?.amountOut});return{source:e,full:s,impactPct:u}}catch{return{source:e,full:s,impactPct:null}}}catch(s){return{source:e,error:s}}}function xs({inspected:e,params:t,gasPrice:r}){let n=e.full,o=yt(n.amountOut,`${e.source} amountOut`),s=Es({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 Ns({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 gt(e={},t={},r={}){ht(e,ys,"route params"),ht(t,gs,"route options"),ht(r,ws,"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=yt(e.amountIn,"amountIn"),s=an(t.timeoutMs,12e3,250,6e4,"timeoutMs"),i=an(t.maxImpactPct,25,0,100,"maxImpactPct"),a=r.quoteV3||on,c=r.quoteV4||sn,u=r.gasPrice||vs,l=[];F[n]&&l.push(cn({source:"uniswap-v3",amountIn:o,timeoutMs:s,fullRead:()=>a({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:o.toString()},{timeoutMs:s}),probeRead:(y,R)=>a({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:y,fee:R.fee},{timeoutMs:s})}));let d=e.v4PoolKey!=null,p=e.v4PoolId!=null;if(d!==p)throw new Error("quote-only V4 requires both exact v4PoolKey and v4PoolId");if(d&&Ie[n]&&l.push(cn({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 f=bt(()=>u(n,s),s,"gas price read").catch(()=>null),m=await Promise.all(l),h=await f,b=m.filter(y=>y.error).map(y=>Is(y.source,y.error)),v=m.filter(y=>y.full),I=v.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`})),C=new Set(I.map(y=>y.source)),x=v.filter(y=>!C.has(y.source)),g=x.map(y=>xs({inspected:y,params:{...e,chainId:n},gasPrice:h})),w=g.length>0&&g.every(y=>y.costAccounted),A=w?"net":"gross";for(let y of g){let R=BigInt(y.grossOut),J=w?BigInt(y.costInDest):0n;y.netOut=(R>J?R-J:0n).toString()}g.sort((y,R)=>{let J=BigInt(w?y.netOut:y.grossOut),Qt=BigInt(w?R.netOut:R.grossOut);return J===Qt?y.source.localeCompare(R.source):Qt>J?1:-1});let N=[];w?N.push("Gas is estimated from quoter gas units and the current read-only gas price; actual gas may differ."):N.push("Gas was not accounted for; routes are ranked on gross output.");let k=x.filter(y=>y.impactPct==null).map(y=>y.source);k.length&&N.push(`Price impact is UNKNOWN for: ${k.join(", ")}.`),I.length&&N.push(`Dropped on price impact: ${I.map(y=>y.source).join(", ")}.`),!d&&Ie[n]&&N.push("V4 was not queried because no exact verified PoolKey identity was discovered.");let O=null,L=null;if(g.length>1){let y=BigInt(w?g[0].netOut:g[0].grossOut),R=BigInt(w?g[1].netOut:g[1].grossOut);R>0n&&(O=Number((y-R)*10000000n/R)/1e3,L=`${g[0].source} vs ${g[1].source}`)}let Q=Object.fromEntries(x.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:g[0]||null,routes:Object.freeze(g.map(y=>Object.freeze(y))),failed:Object.freeze(b),rankedOn:A,sourcesTried:l.length,sourcesAnswered:v.length,improvementBps:O,spreadBasis:L,priceImpact:Object.freeze(Q),impactRejected:Object.freeze(I),impactUnmeasured:Object.freeze(k),warnings:Object.freeze(N),note:Ns({routes:g,rankedOn:A,improvementBps:O})})}var oe="So11111111111111111111111111111111111111112";var ri=new Set(["chainId","tokenIn","tokenOut","amountIn"]),ni=new Set(["maxImpactPct","timeoutMs","quoteFn"]);function kn(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 On(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 Cn(e,t){let r=String(e||"").trim();if(!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(r))throw new Error(`${t} must be a Solana pubkey`);return r}async function oi(e,t={}){let{jupiterQuote:r}=await Promise.resolve().then(()=>(Nt(),xt)),n=await r({inputMint:e.inputMint,outputMint:e.outputMint,amount:e.amount,slippageBps:e.slippageBps??50},{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs,baseUrl:t.baseUrl}),o=n?.quote?.outAmount;if(!o)throw new Error("jupiter quote returned no outAmount");return{source:"jupiter",outAmount:String(o),inAmount:String(n.quote.inAmount||e.amount),routePlan:n.quote.routePlan||null,contextSlot:n.quote.contextSlot??null}}async function Ot(e={},t={}){if(kn(e,ri,"params"),kn(t,ni,"options"),e.chainId!=null&&Number(e.chainId)!==101)throw new Error("solana quote adapter only handles chainId 101");let r=Cn(e.tokenIn,"tokenIn"),n=Cn(e.tokenOut,"tokenOut"),o=On(e.amountIn,"amountIn");if(r===n)throw new Error("solana quote tokenIn and tokenOut must differ");let s=t.quoteFn||oi;if(typeof s!="function")throw new TypeError("solana quote adapter requires a quote function");let i=Number(t.timeoutMs??12e3),a=await s({inputMint:r,outputMint:n,amount:o,slippageBps:100},{timeoutMs:i}),c=On(a?.outAmount,"outAmount"),u=String(a?.source||"jupiter"),l=Object.freeze({source:u,amountOut:c,netOut:c,grossOut:c,costAccounted:!1,meta:Object.freeze({venue:u,executionReady:!1,contextSlot:a?.contextSlot??null})});return Object.freeze({kind:"swap",chainId:101,tokenIn:r,tokenOut:n,amountIn:o,best:l,routes:Object.freeze([l]),failed:Object.freeze([]),rankedOn:"gross",sourcesTried:1,sourcesAnswered:1,improvementBps:null,spreadBasis:null,warnings:Object.freeze(["Ranked on gross output. Solana compute/priority fees were not accounted for."]),executionReady:!1,signingReady:!1,broadcastReady:!1})}function Ln({routeFn:e=Ot}={}){return Object.freeze({async sellSimulation({token:t,amountIn:r,base:n}={}){let{simulateSell:o,SELL_SIM:s}=await Promise.resolve().then(()=>(Nn(),xn)),i=await o({token:t,base:n||oe,amountIn:r,chainId:101},{quote:async u=>({outAmount:(await e({chainId:101,tokenIn:u.inputMint,tokenOut:u.outputMint,amountIn:String(u.amount)})).best.amountOut})}),a={[s.SAFE]:"PASS",[s.CAUTION]:"CAUTION",[s.HONEYPOT]:"FAIL",[s.UNKNOWN]:"UNKNOWN"}[i.status]||"UNKNOWN",c=i.status===s.CAUTION||i.status===s.SAFE||i.status===s.HONEYPOT;return{verdict:a,evidence:c?"LIVE":"UNKNOWN",method:"jupiter-quote-round-trip",simulationReady:!1,reason:i.reason,retentionBps:i.roundTripLossBps==null?null:1e4-i.roundTripLossBps,roundTripLossBps:i.roundTripLossBps??null}}})}function wi(e){return e?.token?.address||e?.tokenAddress||null}function Ai(e){return e?.quoteAsset||e?.pool?.quoteAsset||null}function Si(e,t){return e?.quoteAmountIn||e?.quote?.amountIn||null}async function Lt({candidate:e,strategy:t,scanner:r}={}){if(t?.mode==="shadow")return{prepared:!1,reason:"shadow mode does not prepare"};if(!t?.recipient)return{prepared:!1,blockedReasons:["recipient is required"]};let n=wi(e),o=Ai(e),s=Si(e);if(!n||!o||!s)return{prepared:!1,blockedReasons:["prepare requires token, quote asset, and amountIn"]};if((e?.chain?.id??e?.chainId)===101||e?.chain==="solana"){let{jupiterPrepareSwap:c}=await Promise.resolve().then(()=>(Nt(),xt)),u=await c({userPublicKey:t.recipient,inputMint:o==="unknown"?oe:o,outputMint:n,amount:s,slippageBps:Math.min(100,t.maxSlippageBps??50)});return{prepared:!!(u?.localSignerEnvelope||u?.swapTransaction),envelope:u?.localSignerEnvelope||null,localSignerEnvelope:u?.localSignerEnvelope||null,swapTransaction:u?.swapTransaction||null,executionReady:!1,signingReady:!!(u?.localSignerEnvelope||u?.swapTransaction),broadcastReady:!1}}if(typeof r?.prepareUnsignedTx!="function")return{prepared:!1,blockedReasons:["scanner has no prepareUnsignedTx"]};let a=await r.prepareUnsignedTx({tokenIn:o,tokenOut:n,amountIn:s,recipient:t.recipient,slippageBps:t.maxSlippageBps??50});return{prepared:!!a,unsignedTx:a,executionReady:!1,signingReady:!!a,broadcastReady:!1}}async function Rt({prepared:e}={},t=process.env){if(e?.prepared!==!0)return{ok:!1,error:"nothing prepared"};let{armPreparedAction:r}=await Promise.resolve().then(()=>(qn(),Bn)),n=e.localSignerEnvelope||e.envelope;return n?r({localSignerEnvelope:n},t):{ok:!1,error:"prepared envelope missing"}}import{createHash as Ci}from"node:crypto";import{createHash as Ei}from"node:crypto";var U=Object.freeze({SHADOW:"shadow",ARMED:"armed",AUTONOMOUS:"autonomous"}),vi=3,Ii=new Set(Object.values(U));function Bt(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Bt(t);Object.freeze(e)}return e}function Pt(e){return Array.isArray(e)?`[${e.map(Pt).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${Pt(e[t])}`).join(",")}}`:JSON.stringify(e)}function xi(e){return`sha256:${Ei("sha256").update(Pt(e)).digest("hex")}`}function _t(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 Ni(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new TypeError(`${t} entries must be positive safe integers`);return e}function Tt(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 fe(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 ke(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 Fe(e,t){let r=fe(e,t),[n,o=""]=r.split(".");return{digits:BigInt(n+o),scale:o.length}}function $e(e,t,r="value"){let n=Fe(e,r),o=Fe(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 Un(e){let t=structuredClone(e);return delete t.digest,t}function ki(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");return xi(Un(e))}function qt(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");let t=e.mode??U.SHADOW;if(!Ii.has(t))throw new TypeError("mode must be shadow, armed, or autonomous");let r={version:1,mode:t,chains:_t(e.chains,"chains",Ni),venues:_t(e.venues,"venues",Tt),quoteAssets:_t(e.quoteAssets,"quoteAssets",Tt),maxSpendPerTrade:fe(e.maxSpendPerTrade,"maxSpendPerTrade",{positive:!0}),maxSpendPerDay:fe(e.maxSpendPerDay,"maxSpendPerDay",{positive:!0}),minLiquidityUsd:fe(e.minLiquidityUsd,"minLiquidityUsd",{positive:!0}),maxSlippageBps:ke(e.maxSlippageBps,"maxSlippageBps",{max:1e4}),maxGas:fe(e.maxGas,"maxGas",{positive:!0}),maxPriorityFee:fe(e.maxPriorityFee,"maxPriorityFee"),maxBuysPerHour:ke(e.maxBuysPerHour,"maxBuysPerHour",{min:1}),retryCeiling:ke(e.retryCeiling,"retryCeiling",{max:vi}),ttlMs:ke(e.ttlMs,"ttlMs",{min:1}),requireSellSimulation:e.requireSellSimulation,requireRiskPass:e.requireRiskPass??!0,maxRoundTripLossBps:ke(e.maxRoundTripLossBps??1500,"maxRoundTripLossBps",{max:1e4}),killSwitch:e.killSwitch,recipient:e.recipient==null||e.recipient===""?null:Tt(e.recipient,"recipient")};if(r.requireSellSimulation!==!0)throw new TypeError("requireSellSimulation must be true");if(r.requireRiskPass!==!0)throw new TypeError("requireRiskPass must be true");if(typeof r.killSwitch!="boolean")throw new TypeError("killSwitch must be boolean");if(r.mode!==U.SHADOW&&!r.recipient)throw new TypeError("recipient is required when mode is armed or autonomous");if($e(r.maxSpendPerTrade,r.maxSpendPerDay)>0)throw new TypeError("maxSpendPerTrade cannot exceed maxSpendPerDay");return r.digest=ki(r),Bt(r)}var Oi=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 _(e,t,r){t&&e.push(r)}function Ut(e,t={},r={}){let n=qt(Un(e)),o=[];_(o,n.killSwitch,"kill switch is engaged"),_(o,!n.chains.includes(t.chain),"chain is not on the exact allowlist"),_(o,!n.venues.includes(t.venue),"venue is not on the exact allowlist"),_(o,!n.quoteAssets.includes(t.quoteAsset),"quote asset is not on the exact allowlist");let s=(a,c,u)=>{try{_(o,$e(a,c,u)>0,`${u} exceeds cap`)}catch{o.push(`${u} evidence is missing or unknown`)}};s(t.spend,n.maxSpendPerTrade,"per-trade spend");try{let a=Fe(t.spentToday,"daily spend"),c=Fe(t.spend,"per-trade spend"),u=Math.max(a.scale,c.scale),l=a.digits*10n**BigInt(u-a.scale)+c.digits*10n**BigInt(u-c.scale),d=u===0?String(l):`${String(l).padStart(u+1,"0").slice(0,-u)}.${String(l).padStart(u+1,"0").slice(-u)}`;_(o,$e(d,n.maxSpendPerDay,"daily spend")>0,"daily spend cap would be exceeded")}catch{o.push("daily spend evidence is missing or unknown")}try{_(o,$e(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"),_(o,!Number.isSafeInteger(t.buysLastHour),"buys per hour evidence is missing or unknown"),_(o,Number.isSafeInteger(t.buysLastHour)&&t.buysLastHour>=n.maxBuysPerHour,"buys per hour cap is reached"),_(o,!Number.isSafeInteger(t.retries)||t.retries<0,"retry evidence is missing or unknown"),_(o,Number.isSafeInteger(t.retries)&&t.retries>n.retryCeiling,"retry ceiling is exceeded"),_(o,!Number.isFinite(t.ageMs)||t.ageMs<0,"TTL evidence is missing or unknown"),_(o,Number.isFinite(t.ageMs)&&t.ageMs>=n.ttlMs,"TTL has expired"),_(o,t.sellSimulation?.verdict!=="PASS"||t.sellSimulation?.evidence!=="LIVE","mandatory sell simulation has no LIVE PASS evidence"),_(o,typeof t.fireId!="string"||t.fireId.length===0,"fire id evidence is missing or unknown"),_(o,!Array.isArray(t.firedIds),"duplicate-fire history is missing or unknown"),_(o,Array.isArray(t.firedIds)&&t.firedIds.includes(t.fireId),"duplicate fire is blocked");let i=[...o];_(i,r?.ORACLE_AUTONOMOUS_TRADING!=="1","ORACLE_AUTONOMOUS_TRADING=1 is required literally");for(let[a,c]of Oi)_(i,t.autonomousGates?.[a]!==!0,c);return _(i,n.mode!==U.AUTONOMOUS,"strategy mode is not autonomous"),Bt({strategyDigest:n.digest,mode:n.mode,policyEligible:o.length===0,blockers:o,autonomousEligible:i.length===0,autonomousBlockers:i,reportOnly:!0})}function Fn(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Fn(t);Object.freeze(e)}return e}var jn=Object.freeze({ALERT_ONLY:"alert_only",EXECUTE:"execute"}),Dn=Object.freeze({liveQuote:20,sellSimulation:30,contractRisk:20,liquidity:15,roundTripLoss:15});function D(e,t){return{id:e,verdict:"PASS",detail:t}}function j(e,t){return{id:e,verdict:"BLOCK",detail:t}}function $n(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function Mn({strategy:e,observation:t={},evaluation:r={}}={}){if(!e||typeof e!="object")throw new TypeError("snipe features require a strategy");let n=[],o=[],s=(h,b)=>{n.push(h),h.verdict==="BLOCK"&&o.push(b)};s(e.killSwitch===!0?j("killSwitch","engaged"):D("killSwitch","off"),"kill switch is engaged"),s(e.chains.includes(t.chain)?D("chain",String(t.chain)):j("chain",String(t.chain??"missing")),"chain is not on the exact allowlist"),s(e.venues.includes(t.venue)?D("venue",String(t.venue)):j("venue",String(t.venue??"missing")),"venue is not on the exact allowlist"),s(e.quoteAssets.includes(t.quoteAsset)?D("quoteAsset",String(t.quoteAsset)):j("quoteAsset",String(t.quoteAsset??"missing")),"quote asset is not on the exact allowlist");let i=r.quote?.evidence||t.quoteEvidence;s(i==="LIVE"?D("liveQuote","LIVE"):j("liveQuote",String(i||"missing")),"live quote is missing");let a=t.sellSimulation||r.sellSimulation;s(a?.verdict==="PASS"&&a?.evidence==="LIVE"?D("sellSimulation","LIVE PASS"):j("sellSimulation",`${a?.verdict||"missing"}/${a?.evidence||"missing"}`),"mandatory sell simulation has no LIVE PASS evidence");let c=t.riskVerdict||r.risk?.verdict;s(e.requireRiskPass===!0&&c==="PASS"?D("contractRisk","PASS"):j("contractRisk",String(c||"missing")),"contract risk is not PASS");let u=t.liquidityUsd;try{let h=Number(u),b=Number(e.minLiquidityUsd);s(Number.isFinite(h)&&Number.isFinite(b)&&h>=b?D("liquidity",String(u)):j("liquidity",String(u??"missing")),"minimum real liquidity is not met")}catch{s(j("liquidity","unknown"),"liquidity evidence is missing or unknown")}let l=$n(t.slippageBps);s(l!=null&&l<=e.maxSlippageBps?D("slippage",String(l)):j("slippage",String(t.slippageBps??"missing")),"slippage exceeds cap or is unknown");let d=$n(t.roundTripLossBps);s(d!=null&&d<=e.maxRoundTripLossBps?D("roundTripLoss",String(d)):j("roundTripLoss",String(t.roundTripLossBps??"missing")),"round-trip loss exceeds cap or is unknown"),s(Number.isSafeInteger(t.retries)&&t.retries<=e.retryCeiling?D("retryCeiling",String(t.retries)):j("retryCeiling",String(t.retries??"missing")),"retry ceiling is exceeded or unknown"),s(Number.isFinite(t.ageMs)&&t.ageMs>=0&&t.ageMs<e.ttlMs?D("ttl",String(t.ageMs)):j("ttl",String(t.ageMs??"missing")),"TTL has expired or is unknown"),s(typeof t.fireId=="string"&&t.fireId.length>0&&Array.isArray(t.firedIds)&&!t.firedIds.includes(t.fireId)?D("duplicateFire",t.fireId):j("duplicateFire","missing or duplicate"),"duplicate fire is blocked or fire id is unknown");let p=0;for(let h of n)h.verdict==="PASS"&&Dn[h.id]&&(p+=Dn[h.id]);let f=o.length===0,m=e.mode==="shadow"?jn.ALERT_ONLY:jn.EXECUTE;return Fn({snipeReady:f,wouldSnipe:f,armed:!1,actionMode:m,score:p,features:n,blockers:o,reportOnly:e.mode==="shadow"})}function Me(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function jt(e){return Array.isArray(e)?`[${e.map(jt).join(",")}]`:Me(e)?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${jt(e[t])}`).join(",")}}`:JSON.stringify(e)}function Li(e){return`cycle:${Ci("sha256").update(jt(e)).digest("hex")}`}function Oe(e,t){if(typeof e!="function")throw new TypeError(`launch-radar runner: injected ${t} function is required`)}function Vn(e){return e instanceof Error?e.message:String(e)}function Dt(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(!Me(r))throw new TypeError("launch-radar runner: strategy is required");Oe(n,"discovery"),Oe(o,"evaluate");let s=e.now??(()=>new Date().toISOString()),i=e.sleep??(()=>Promise.resolve()),a=e.jitter??(()=>0);Oe(s,"clock"),Oe(i,"sleep"),Oe(a,"jitter");let c=Math.min(3,Math.max(0,Number.isSafeInteger(e.retries)?e.retries:r.retryCeiling)),u=Math.max(0,Number.isFinite(e.baseBackoffMs)?e.baseBackoffMs:100),l=Math.max(u,Number.isFinite(e.maxBackoffMs)?e.maxBackoffMs:2e3);async function d(m){let h;for(let b=0;b<=c;b+=1)try{return await m(b)}catch(v){if(h=v,b===c)break;let I=Number(a()),C=Number.isFinite(I)?Math.max(0,I):0,x=Math.min(l,u*2**b+C);await i(x)}throw h}function p(){let m=t.read().strategyStatus;return{mode:r.mode,status:m.ambiguous?"blocked":"inert",ambiguous:m.ambiguous,autostart:!1}}async function f(){let m=t.read(),h=fr(r);if(m.strategyStatus.ambiguous)return{mode:r.mode,status:"blocked",blockers:["ambiguous state requires reconciliation"],results:[],actionMode:h};if(Array.isArray(m.evidence)&&m.evidence.length>0&&m.strategyStatus.mode!==r.mode)return{mode:r.mode,status:"blocked",blockers:["persisted mode does not match configured strategy"],results:[],actionMode:h};if(r.killSwitch)return{mode:r.mode,status:"blocked",blockers:["kill switch is engaged"],results:[],actionMode:h};let b;try{b=await d(g=>n({cursor:structuredClone(m.cursor),attempt:g,mode:r.mode}))}catch(g){return{mode:r.mode,status:"failed",blockers:[Vn(g)],results:[],actionMode:h}}if(!Me(b)||!Array.isArray(b.candidates)||!(b.cursor===null||Me(b.cursor)))return{mode:r.mode,status:"failed",blockers:["discovery returned an invalid deterministic result"],results:[],actionMode:h};let v=[];for(let g of b.candidates)try{let w=await d(L=>o(structuredClone(g),{attempt:L,mode:r.mode})),A=Ut(r,w,{}),N=Mn({strategy:r,observation:w,evaluation:g}),k={prepared:!1},O=!1;Re(r,A)&&typeof e.prepareFn=="function"?k=await e.prepareFn({candidate:g,observation:w,strategy:r,policy:A})||{prepared:!1}:Re(r,A)&&(k={prepared:!1,blockedReasons:["prepareFn is required when strategy mode is not shadow"]}),mr(r,A,k)&&typeof e.queueFn=="function"&&(O=(await e.queueFn({prepared:k,candidate:g,observation:w,strategy:r,policy:A}))?.ok===!0),v.push({id:g?.id??null,policy:A,snipe:N,prepared:k.prepared===!0,queued:O,actionMode:h})}catch(w){v.push({id:g?.id??null,policy:{mode:r.mode,policyEligible:!1,reportOnly:r.mode===U.SHADOW,blockers:[`evaluation failed: ${Vn(w)}`]},actionMode:h,prepared:!1,queued:!1})}let I={cursor:b.cursor,candidates:b.candidates,results:v},C={id:Li(I),type:r.mode===U.SHADOW?"shadow-cycle":"execute-cycle",at:s(),data:I},x=t.commitCycle({candidates:b.candidates,cursor:b.cursor,strategyStatus:{mode:r.mode,status:"inert",ambiguous:!1},event:C});return{mode:r.mode,status:x.duplicate?"duplicate":"completed",results:v,evidenceId:x.evidence.id,actionMode:h}}return Object.freeze({status:p,runCycle:f})}function zn(e){return[...new Set(e.filter(Boolean).map(String))]}function se(e){return Array.isArray(e)?e.map(se):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,se(r)])):e}function G(e,t,r="UNKNOWN"){return!e||typeof e!="object"?{evidence:r,observedAt:t}:se({...structuredClone(e),evidence:e.evidence||r,observedAt:e.observedAt||t})}function Ri(e,t){let r=String(t||"").toLowerCase();return!!(r&&[e?.address,e?.pair,e?.poolId].some(n=>String(n||"").toLowerCase()===r))}function _i(e,t){let r=e.poolId||e.poolAddress||null,n=[t.topPool,...t.pools?.pools||[]].filter(Boolean),o=r?n.find(i=>Ri(i,r)):t.topPool,s={address:e.poolAddress??null,poolId:e.poolId,poolKey:e.poolKey,quoteAsset:e.quoteAsset};return se({...o||{},...s})}function Ti(e,t,r,n){let o=e.observedAt||n,s=_i(e,t),i=G(t.scannerRisk||t.risk,o),a=G(t.sellability,o,"UNAVAILABLE"),c=G(t.quote,o,"UNAVAILABLE"),u=c.evidence==="LIVE"?"PASS":"UNKNOWN";return se({chain:{id:e.chainId,...t.chain||{}},token:G({address:e.tokenAddress,...t.token||{}},o,"LIVE"),pool:G(s,o,"LIVE"),venue:G({...e.venue,supported:e.venue?.supported===!0,verified:e.venue?.verified===!0},o,"LIVE"),signal:G({kind:e.kind,source:"verified-factory",unsolicitedAirdrop:!1},o,"LIVE"),risk:i,sellability:a,sellSimulation:G(t.sellSimulation,o,"UNAVAILABLE"),quoteAsset:e.quoteAsset||s.quoteAsset||null,roundTripLossBps:t.roundTripLossBps??null,quoteAmountIn:c.amountIn??null,quoteSlippageBps:t.quoteSlippageBps??null,quoteAssetDecimals:t.quoteAssetDecimals??null,route:se({status:u,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:zn([...r||[],...t.blockedReasons||[],t.error]),latency:{discoveredAt:o,riskCompletedAt:i.observedAt,sellabilityCompletedAt:a.observedAt,routeCompletedAt:c.observedAt,normalizedAt:n}})}async function Ve(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:se(structuredClone(a)),prepare:e.prepare===!0})}catch(u){c={error:`evaluation unavailable: ${String(u?.message||u).slice(0,300)}`}}i.push(Ti(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(zn(n?.whyBlocked||[])),candidates:rr(i)})}var Pi=101,Hn=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/,Bi="181ec828051c0777",qi="6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P";function me(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))me(t);Object.freeze(e)}return e}function Ui(e){if(!e||typeof e!="object")return"factory descriptor is invalid";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(e.chain!=="solana")return`${e.id||"venue"}: solana discovery requires chain=solana`;if(e.programId!==qi)return`${e.id||"venue"}: program id is not the official Pump.fun program`;let t=Array.isArray(e.events)?e.events:[];return t.length!==1||t[0]?.decoder!=="pump-create"?`${e.id||"venue"}: only the pump-create decoder is supported`:null}function ji(e,t){let r=typeof e?.signature=="string"?e.signature:null,n=Number.isInteger(e?.slot)?e.slot:null;if(!r||n==null)return null;let o=Array.isArray(e?.instructions)?e.instructions:[];for(let s=0;s<o.length;s+=1){let i=o[s];if(String(i?.programId||"")!==t.programId||!String(i?.dataHex||"").toLowerCase().replace(/^0x/,"").startsWith(Bi))continue;let c=Array.isArray(i.accounts)?i.accounts:[],u=c[0],l=c[2];return!Hn.test(u||"")||!Hn.test(l||"")?null:{id:`solana:${r}:${s}`,chain:"solana",chainId:Pi,factoryId:t.id||null,factoryAddress:t.programId,tokenAddress:u,quoteAsset:oe,poolAddress:l,venue:structuredClone(t.venue),kind:"token-launched",slot:n,signature:r,instructionIndex:s,evidence:"LIVE"}}return null}async function Kn(e={}){let{scanner:t,factories:r=[]}=e;if(!t||typeof t.getSignatures!="function"||typeof t.getTransaction!="function")throw new TypeError("solana discovery requires injected getSignatures and getTransaction");if(!Array.isArray(r))throw new TypeError("factories must be an array");let n=[],o=[];for(let u of r){let l=Ui(u);l?n.push({id:u?.id||null,status:"UNAVAILABLE",reason:l}):o.push(u)}let s=me({until:e.cursor?.until||null});if(o.length===0)return me({status:"UNAVAILABLE",discoveries:[],unavailable:n,cursor:s,whyBlocked:n.map(u=>u.reason)});let i=[],a=s.until;for(let u of o){let l;try{l=await t.getSignatures({programId:u.programId,until:a,limit:e.limit||20})}catch(p){return me({status:"UNKNOWN",discoveries:[],unavailable:n,cursor:s,whyBlocked:[`scan failed: ${String(p?.message||p).slice(0,300)}`]})}if(!l||l.complete!==!0||l.evidence&&l.evidence!=="LIVE")return me({status:"UNKNOWN",discoveries:[],unavailable:n,cursor:s,whyBlocked:["incomplete signature range"]});let d=Array.isArray(l.signatures)?l.signatures:[];d.length&&(a=d[0]);for(let p of d){let f;try{f=await t.getTransaction(p)}catch{continue}let m=ji({...f,signature:f?.signature||p},u);m&&i.push(m)}}let c=new Map;for(let u of i.sort((l,d)=>l.id.localeCompare(d.id)))c.has(u.id)||c.set(u.id,u);return me({status:"LIVE",discoveries:[...c.values()],unavailable:n,cursor:{until:a},whyBlocked:n.map(u=>u.reason)})}wt();var Di="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function $i(e){let t=String(e||"");if(!t)return Buffer.alloc(0);let r=[0];for(let o of t){let s=Di.indexOf(o);if(s<0)throw new Error("solana-scanner: instruction data is not base58");let i=s;for(let a=0;a<r.length;a+=1)i+=r[a]*58,r[a]=i&255,i>>=8;for(;i>0;)r.push(i&255),i>>=8}let n=0;for(let o of t){if(o!=="1")break;n+=1}return Buffer.from([...Array(n).fill(0),...r.reverse()])}function Fi(e){return typeof e=="string"?e:e?.pubkey||null}function Mi(e){let t=e?.transaction?.message||{},r=Array.isArray(t.accountKeys)?t.accountKeys.map(Fi):[],n=Array.isArray(t.instructions)?t.instructions:Array.isArray(t.compiledInstructions)?t.compiledInstructions:[],o=Array.isArray(e?.meta?.innerInstructions)?e.meta.innerInstructions.flatMap(i=>i?.instructions||[]):[],s=[];for(let i of[...n,...o]){let a=typeof i?.programId=="string"?i.programId:r[i?.programIdIndex],c=Array.isArray(i?.accounts)?i.accounts.map(l=>typeof l=="string"?l:r[l]):[],u="";typeof i?.data=="string"&&/^[0-9a-f]+$/i.test(i.data)?u=i.data.toLowerCase():typeof i?.data=="string"&&(u=$i(i.data).toString("hex")),a&&s.push({programId:a,accounts:c,dataHex:u})}return s}function Wn(e={}){let t=e.solanaRpc||un;return{async getSignatures({programId:r,until:n,limit:o=20}={}){let s={limit:Math.min(100,Math.max(1,Number(o)||20))};n&&(s.until=n);let i=await t("getSignaturesForAddress",[r,s],e);return{complete:!0,evidence:"LIVE",signatures:Array.isArray(i)?i.map(c=>c?.signature).filter(Boolean):[]}},async getTransaction(r){let n=await t("getTransaction",[r,{encoding:"json",maxSupportedTransactionVersion:0,commitment:"confirmed"}],e);return n?{signature:r,slot:Number.isInteger(n.slot)?n.slot:null,instructions:Mi(n)}:{signature:r,slot:null,instructions:[]}}}}import q from"node:fs";import ze from"node:path";var Vt=1,Vi=0;function ae(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function B(e){return structuredClone(e)}function Ft(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)=>Ft(r,`${t}[${n}]`));if(ae(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}`);Ft(n,`${t}.${r}`)}return}throw new Error(`launch-radar store: non-JSON value at ${t}`)}}function ie(e){return Array.isArray(e)?`[${e.map(ie).join(",")}]`:ae(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${ie(e[t])}`).join(",")}}`:JSON.stringify(e)}function zi(){return{version:Vt,candidates:[],cursor:null,strategyStatus:{mode:"shadow",status:"inert",ambiguous:!1},evidence:[]}}function Hi(e){if(!ae(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 Ce(e){if(!ae(e)||e.version!==Vt)throw new Error("launch-radar store: corrupt or unsupported version");if(!Array.isArray(e.candidates)||!(e.cursor===null||ae(e.cursor))||!Array.isArray(e.evidence))throw new Error("launch-radar store: corrupt state shape");Hi(e.strategyStatus),Ft(e);try{Qe(e.evidence)}catch(t){throw new Error(`launch-radar store: corrupt evidence: ${t.message}`)}return B(e)}function He(e,t=!1){let r;try{r=q.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 Mt(e){He(e);let t;try{t=JSON.parse(q.readFileSync(e,"utf8"))}catch{throw new Error("launch-radar store: corrupt JSON")}return Ce(t)}function $t(e,t){let r=Ce(t),n=ze.dirname(e);q.mkdirSync(n,{recursive:!0,mode:448});let o=q.lstatSync(n);if(o.isSymbolicLink()||!o.isDirectory())throw new Error("launch-radar store: parent must be a regular directory, not a symlink");He(e,!0)&&He(e);let s=ze.join(n,`.launch-radar.${process.pid}.${Vi+=1}.tmp`),i;try{i=q.openSync(s,"wx",384),q.writeFileSync(i,`${ie(r)}
8
+ `,"utf8"),q.fsyncSync(i),q.closeSync(i),i=void 0,q.renameSync(s,e),q.chmodSync(e,384);let a=q.openSync(n,"r");try{q.fsyncSync(a)}finally{q.closeSync(a)}}catch(a){i!==void 0&&q.closeSync(i);try{q.unlinkSync(s)}catch{}throw a}}function zt(e={}){let t=e.path;if(typeof t!="string"||!ze.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");He(t,!0)?Mt(t):$t(t,zi());let r=()=>Mt(t),n=(o,{reconciliation:s=!1}={})=>{if(r().strategyStatus.ambiguous&&!s)throw new Error("launch-radar store: ambiguous state is terminal until reconciliation");return $t(t,o),B(o)};return Object.freeze({path:t,read:r,replaceState(o={}){if(!ae(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]=B(o[a]));return n(Ce(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(u=>u.id===o?.id);if(i){if(i.type===o?.type&&ie(i.data)===ie(o?.data))return B(i);throw new Error(`launch-radar store: duplicate evidence conflict: ${o?.id}`)}let a=Je(s.evidence,o),c=a.at(-1);return n({...s,evidence:B(a)}),B(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 u=c.evidence.find(p=>p.id===a?.id);if(u){if(u.type===a?.type&&ie(u.data)===ie(a?.data))return{duplicate:!0,evidence:B(u),state:c};throw new Error(`launch-radar store: duplicate evidence conflict: ${a?.id}`)}let l=Je(c.evidence,a),d=Ce({...c,candidates:B(o),cursor:B(s),strategyStatus:B(i),evidence:B(l)});return n(d),{duplicate:!1,evidence:B(l.at(-1)),state:B(d)}},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 $t(t,{...s,strategyStatus:i}),B(i)},reconcile(o={}){if(!ae(o))throw new TypeError("launch-radar store: reconciliation state must be an object");let s=r(),i=Ce({...s,...B(o),version:Vt,evidence:s.evidence});if(i.strategyStatus.ambiguous)throw new Error("launch-radar store: reconciliation must clear ambiguous state");return n(i,{reconciliation:!0})}})}function Gn(e={}){let t=e.path;if(typeof t!="string"||!ze.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");return Mt(t)}function Kt(e){return e.ORACLE_CONFIG_DIR||Y.join(Ki.homedir(),".config","oracle")}function Yn(e,t){if(!e||!Y.isAbsolute(e))throw new Error(`${t} path must be absolute`);let r=Ke.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(Ke.readFileSync(e,"utf8"))}function Wi(e){return e==null?null:String(e)}function he(e){if(e!==void 0)return typeof e=="bigint"?e.toString():Array.isArray(e)?e.map(he).filter(t=>t!==void 0):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,he(r)])):e}function eo(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 Ht(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 Gi(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 Yi(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:eo(t.amountIn,"routeProbe.amountIn"),quoteAssetDecimals:Ht(t.quoteAssetDecimals,0,255,"routeProbe.quoteAssetDecimals"),slippageBps:Ht(t.slippageBps??100,0,1e4,"routeProbe.slippageBps"),maxImpactPct:Gi(t.maxImpactPct??25,0,100,"routeProbe.maxImpactPct"),timeoutMs:Ht(t.timeoutMs??12e3,250,6e4,"routeProbe.timeoutMs")})}function Qn(e){return[e?.source,e?.amountOut,e?.netOut,e?.meta?.poolId].map(t=>String(t??"").toLowerCase()).join(":")}function Jn(e,t){let r=String(e??"");if(!/^[0-9]+$/.test(r))return null;let n=Number(t);if(!Number.isInteger(n)||n<0)return null;if(n===0)return r.replace(/^0+(?=\d)/,"")||"0";let o=r.padStart(n+1,"0"),s=o.slice(0,-n).replace(/^0+(?=\d)/,"")||"0",i=o.slice(-n).replace(/0+$/,"");return i?`${s}.${i}`:s}function Qi(e,t){try{let r=BigInt(String(e)),n=BigInt(String(t));return r<=0n?null:n>=r?0:Number((r-n)*10000n/r)}catch{return null}}function Xn(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 Zn(e){if(!e?.best||!eo(e.best.amountOut,"best route amountOut"))throw new Error("best route returned no positive output");let t=Array.isArray(e.routes)?e.routes:[],r=Qn(e.best),n=t.findIndex(a=>Qn(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."),he({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 Ji(e,t){return{quote:{evidence:"UNAVAILABLE",reason:e,observedAt:t},sellability:{verdict:"UNKNOWN",evidence:"UNAVAILABLE",reason:e,observedAt:t}}}async function to({scanner:e,discovery:t,descriptor:r,routeFn:n=gt,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=Yi(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:he(t.poolKey),v4PoolId:t.poolId}:{},u={chainId:t.chainId,...c},l={maxImpactPct:a.maxImpactPct,timeoutMs:a.timeoutMs},d=await n({...u,tokenIn:t.quoteAsset,tokenOut:i,amountIn:a.amountIn},l);Xn(d,t,"buy");let p=Zn(d);s.quote={evidence:"LIVE",observedAt:o,amountIn:a.amountIn,amountOut:String(d.best.amountOut),fee:null,routeEvidence:p},s.quoteAssetDecimals=a.quoteAssetDecimals,s.quoteSlippageBps=a.slippageBps;try{let f=await n({...u,tokenIn:i,tokenOut:t.quoteAsset,amountIn:String(d.best.amountOut)},l);Xn(f,t,"reverse");let m=Zn(f);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(d.best.amountOut),amountOut:String(f.best.amountOut),routeEvidence:m},s.roundTripLossBps=Qi(a.amountIn,f.best.amountOut),s.quoteSlippageBps=a.slippageBps}catch(f){let m=`reverse route unavailable: ${String(f?.message||f).slice(0,240)}`;s.blockedReasons.push(m),s.sellability={verdict:"UNKNOWN",evidence:"UNAVAILABLE",reason:m,observedAt:o}}if(typeof e.sellSimulation=="function")try{let f=await e.sellSimulation({token:i,amountIn:a.amountIn,base:t.quoteAsset});s.sellSimulation=he({verdict:f?.verdict||"UNKNOWN",evidence:f?.evidence||"UNKNOWN",reason:f?.reason||null,retentionBps:f?.retentionBps??null,observedAt:o})}catch(f){let m=`sell simulation unavailable: ${String(f?.message||f).slice(0,240)}`;s.blockedReasons.push(m),s.sellSimulation={verdict:"UNKNOWN",evidence:"UNAVAILABLE",reason:m,observedAt:o}}else s.sellSimulation={verdict:"UNKNOWN",evidence:"UNAVAILABLE",reason:"scanner has no sellSimulation capability",observedAt:o}}catch(a){let c=`route evidence unavailable: ${String(a?.message||a).slice(0,240)}`;s.blockedReasons.push(c),Object.assign(s,Ji(c,o))}return he(s)}function ro(e){let t=e.quoteAsset||e.pool?.quoteAsset||e.token?.quoteAsset||"unknown",r=Jn(e.quoteAmountIn,e.quoteAssetDecimals??18)||Jn(e.quote?.amountIn,e.quoteAssetDecimals??18),n=e.quoteSlippageBps,o=e.pool?.liquidityUsd,s=e.sellSimulation,i=s&&(s.verdict||s.evidence)?{verdict:s.verdict,evidence:s.evidence,reason:s.reason,retentionBps:s.retentionBps}:{verdict:"UNKNOWN",evidence:"UNKNOWN"};return{chain:e.chain?.id??e.chainId,venue:e.venue?.id||e.venue?.name||e.venue?.venue||"unknown",quoteAsset:t,spend:r,spentToday:"0",liquidityUsd:Wi(o),slippageBps:n??null,gas:null,priorityFee:null,buysLastHour:0,retries:0,ageMs:0,roundTripLossBps:e.roundTripLossBps??null,riskVerdict:e.risk?.verdict||null,quoteEvidence:e.quote?.evidence||e.route?.evidence||null,sellSimulation:i,fireId:e.id,firedIds:[],autonomousGates:{}}}function Wt(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=Yn(t.ORACLE_LAUNCH_RADAR_STRATEGY_FILE,"strategy file"),n=Yn(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=qt(r);if(![U.SHADOW,U.ARMED,U.AUTONOMOUS].includes(s.mode))throw new Error("installed Launch Radar runner requires shadow, armed, or autonomous mode");if(o.every(p=>p?.chain==="solana"))return Xi({env:t,factories:o,strategy:s,options:e});let i=[...new Set(o.map(p=>p?.chainId))];if(i.length!==1||!Number.isInteger(i[0]))throw new Error("one installed shadow runner handles exactly one chainId");Gr();let a=$r(i[0]);if(!a)throw new Error(`no scanner registered for chain ${i[0]}`);let c=t.ORACLE_LAUNCH_RADAR_STORE_PATH||Y.join(Kt(t),"launch-radar",`state-${i[0]}.json`),u=zt({path:c});return Dt({store:u,strategy:s,discover:async({cursor:p})=>{let f=await a.blockNumber(),m=Number(f?.blockNumber??f);if(!Number.isSafeInteger(m))throw new Error("scanner did not return a safe integer head block");let h=Number.isSafeInteger(p?.nextBlock)?p.nextBlock:Math.max(0,m-10),b=await Ve({discover:()=>cr({scanner:a,factories:o,fromBlock:h,toBlock:m,cursor:p}),evaluator:async({discovery:v})=>{let I=o.find(C=>C?.id===v?.factoryId||String(C?.factoryAddress||"").toLowerCase()===String(v?.factoryAddress||"").toLowerCase());return to({scanner:a,discovery:v,descriptor:I,routeFn:e.routeFn||gt,observedAt:new Date().toISOString()})},observedAt:new Date().toISOString()});return{candidates:b.candidates,cursor:b.cursor}},evaluate:async p=>ro(p),prepareFn:e.prepareFn||(p=>Lt({...p,scanner:a})),queueFn:e.queueFn||(p=>Rt(p,t))})}function Xi({env:e,factories:t,strategy:r,options:n}){let o=n.solanaScanner||Wn(),s=n.solanaRouteFn||Ot,i=n.solanaQuoteScanner||Ln({routeFn:s}),a=e.ORACLE_LAUNCH_RADAR_STORE_PATH||Y.join(Kt(e),"launch-radar","state-solana.json"),c=zt({path:a});return Dt({store:c,strategy:r,discover:async({cursor:l})=>{let d=await Ve({discover:()=>Kn({scanner:o,factories:t,cursor:l,limit:20}),evaluator:async({discovery:p})=>{let f=t.find(m=>m?.id===p?.factoryId||String(m?.programId||"")===String(p?.factoryAddress||""));return to({scanner:i,discovery:{...p,quoteAsset:p.quoteAsset||oe},descriptor:f,routeFn:s,observedAt:new Date().toISOString()})},observedAt:new Date().toISOString()});return{candidates:d.candidates,cursor:d.cursor}},evaluate:async l=>ro(l),prepareFn:n.prepareFn||(l=>Lt({...l,scanner:i})),queueFn:n.queueFn||(l=>Rt(l,e))})}async function no(e={}){let t=e.env||process.env,r=t.ORACLE_LAUNCH_RADAR_FACTORIES_DIR;if(!r||!Y.isAbsolute(r))throw new Error("ORACLE_LAUNCH_RADAR_FACTORIES_DIR must be an absolute directory");let n=Ke.lstatSync(r);if(n.isSymbolicLink()||!n.isDirectory())throw new Error("factories dir must be a regular directory");let o=Ke.readdirSync(r).filter(i=>i.endsWith(".json")).sort();if(o.length===0)throw new Error("factories dir contains no json manifests");let s=[];for(let i of o){let a=i.endsWith(".json")?i.slice(0,-5):i,c={...t,ORACLE_LAUNCH_RADAR_FACTORIES_FILE:Y.join(r,i),ORACLE_LAUNCH_RADAR_STORE_PATH:Y.join(t.ORACLE_LAUNCH_RADAR_STORE_DIR||Y.join(Kt(t),"launch-radar"),`state-${a}.json`)},u=await Wt({...e,env:c}).runCycle();s.push({file:i,mode:u.mode,status:u.status,blockers:u.blockers||[],count:(u.results||[]).length})}return{mode:U.SHADOW,status:"fleet",results:s}}var Zi=Object.freeze({OK:"ok",DEGRADED:"degraded",UNKNOWN:"unknown"}),du=Object.freeze({fresh:0,stale:1,down:2});var fu=Object.freeze([Object.freeze({id:"uniswap-v3",kind:"factory",chains:Object.freeze(["evm"]),status:"VERIFIED",evidence:"Uniswap V3 PoolCreated against factories returned by verified SwapRouter02.factory() eth_call."}),Object.freeze({id:"uniswap-v4",kind:"pool-manager",chains:Object.freeze(["evm"]),status:"VERIFIED",evidence:"Uniswap V4 Initialize logs against a verified PoolManager, exact PoolKey preserved."}),Object.freeze({id:"pons-v2",kind:"factory",chains:Object.freeze(["evm"]),chainIds:Object.freeze([4663]),status:"VERIFIED",factoryAddress:"0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e",evidence:"Blockscout-verified PonsV2LaunchFactory. Live TokenLaunched topic0 matched on RH."}),Object.freeze({id:"pump-fun",kind:"program",chains:Object.freeze(["solana"]),status:"VERIFIED",programId:"6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P",evidence:"Official pump-fun/pump-public-docs: create discriminator 181ec828051c0777."}),Object.freeze({id:"fomo",kind:"frontend",chains:Object.freeze(["solana","evm"]),status:"COVERED",via:Object.freeze(["pons-v2","pump-fun"]),evidence:"fomopad.family says Built on Pons / Robinhood Chain. fomopad.site says it is a pump.fun launchpad. No separate factory."}),Object.freeze({id:"based-bot",kind:"frontend",chains:Object.freeze(["evm"]),status:"UNAVAILABLE",evidence:"basedbot.app is a trading terminal, not a verified launch factory."}),Object.freeze({id:"opensea",kind:"nft-marketplace",chains:Object.freeze(["evm"]),status:"UNAVAILABLE",evidence:"OpenSea/Seaport is an NFT marketplace, not a fungible-token launch factory."}),Object.freeze({id:"four-meme",kind:"factory",chains:Object.freeze(["evm"]),status:"UNAVAILABLE",evidence:"No independently verified TokenManager/factory address on file this release."}),Object.freeze({id:"clanker",kind:"factory",chains:Object.freeze(["evm"]),status:"UNAVAILABLE",evidence:"No independently verified Clanker factory address on file this release."})]);import ea from"node:os";import oo from"node:path";var ta="oracle.launch-radar.data-plane.v1";function ra(e){return String(e?.message||e||"unknown error").slice(0,300)}function na(e={}){return e.configDir||process.env.ORACLE_CONFIG_DIR||oo.join(ea.homedir(),".config","oracle")}function oa(e={}){return e.storePath||process.env.LAUNCH_RADAR_STORE_PATH||oo.join(na(e),"launch-radar","state.json")}function sa(e={}){let t=oa(e);try{return{ok:!0,path:t,state:Gn({path:t})}}catch(r){return{ok:!1,path:t,error:ra(r)}}}function ia(){return process.env.ORACLE_AUTONOMOUS_TRADING==="1"}function Gt(e={},t={}){let r=sa(t),n={schema:ta,storePath:r.path,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,autonomousTradingEnvSet:ia()};if(!r.ok)return Object.freeze({...n,evidence:"UNAVAILABLE",reason:r.error,mode:U.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 Yt=new Set(process.argv.slice(2));(Yt.has("--help")||Yt.has("-h"))&&(console.log(`oracle-launch-radar-shadow
9
9
 
10
10
  Default: print read-only status and exit. Missing state remains UNAVAILABLE and creates nothing.
11
11
 
@@ -15,7 +15,8 @@ Default: print read-only status and exit. Missing state remains UNAVAILABLE and
15
15
  ORACLE_LAUNCH_RADAR_SHADOW=1
16
16
  ORACLE_LAUNCH_RADAR_STRATEGY_FILE=/absolute/private-strategy.json
17
17
  ORACLE_LAUNCH_RADAR_FACTORIES_FILE=/absolute/verified-factories.json
18
+ or ORACLE_LAUNCH_RADAR_FACTORIES_DIR=/absolute/dir-of-factory-jsons
18
19
 
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
+ There is no daemon/autostart, arm, sign, or broadcast mode.`),process.exit(0));try{let e=Yt.has("--once")?process.env.ORACLE_LAUNCH_RADAR_FACTORIES_DIR?await no({env:process.env}):await Wt({env:process.env}).runCycle():Gt({},{});process.stdout.write(`${JSON.stringify(e,null,2)}
20
21
  `),e?.status==="failed"&&(process.exitCode=1)}catch(e){process.stderr.write(`launch radar shadow refused: ${e?.message||e}
21
22
  `),process.exitCode=1}