@oracle-agent/oracle 0.35.40 → 0.35.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-sessions.mjs +17 -17
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/bin/desk-server.mjs +28 -28
- package/dist/bin/oracle-data-mcp.mjs +19 -19
- package/dist/bin/oracle-gateway.mjs +44 -44
- package/dist/bin/oracle-investigate.mjs +5 -5
- package/dist/bin/oracle-launch-radar-shadow.mjs +6 -6
- package/dist/bin/oracle-mev-arb-shadow.mjs +6 -6
- package/dist/bin/oracle-mev-shadow.mjs +6 -6
- package/dist/bin/oracle-public-server.mjs +5 -5
- package/dist/bin/oracle-route.mjs +31 -31
- package/dist/bin/oracle-scan.mjs +11 -11
- package/dist/bin/oracle.mjs +1 -1
- package/dist/cli/commands/agent-session.mjs +20 -20
- package/dist/cli/commands/airdrop.mjs +8 -8
- package/dist/cli/commands/auth.mjs +5 -5
- package/dist/cli/commands/chat.mjs +218 -217
- package/dist/cli/commands/doctor.mjs +9 -9
- package/dist/cli/commands/eval.mjs +204 -217
- package/dist/cli/commands/extension-policy.mjs +3 -3
- package/dist/cli/commands/farm.mjs +17 -17
- package/dist/cli/commands/follow.mjs +17 -17
- package/dist/cli/commands/harness.mjs +7 -7
- package/dist/cli/commands/mint.mjs +10 -10
- package/dist/cli/commands/model.mjs +222 -221
- package/dist/cli/commands/portfolio-risk.mjs +1 -1
- package/dist/cli/commands/project.mjs +7 -7
- package/dist/cli/commands/quickstart.mjs +6 -6
- package/dist/cli/commands/receipt.mjs +12 -12
- package/dist/cli/commands/resolve.mjs +7 -7
- package/dist/cli/commands/setup.mjs +13 -13
- package/dist/cli/commands/sign.mjs +4 -4
- package/dist/cli/commands/signer.mjs +14 -14
- package/dist/cli/commands/snipe.mjs +9 -9
- package/dist/cli/commands/strategy.mjs +4 -4
- package/dist/cli/commands/swap.mjs +14 -14
- package/dist/cli/commands/venues.mjs +2 -2
- package/dist/cli/project-access.mjs +3 -0
- package/dist/data/desk-data.mjs +26 -26
- package/dist/data/names.mjs +3 -3
- package/dist/data/providers/farming.mjs +2 -2
- package/dist/data/providers/lp-destination-discovery.mjs +4 -4
- package/dist/index.mjs +44 -44
- package/dist/investigator/index.mjs +2 -2
- package/dist/launch-radar/index.mjs +5 -5
- package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
- package/dist/local-signer/index.mjs +2 -2
- package/dist/local-signer/runtime.mjs +8 -8
- package/dist/nft/universal-mint-router.mjs +4 -4
- package/dist/notifications/index.mjs +8 -8
- package/dist/portfolio-risk.mjs +1 -1
- package/dist/router/index.mjs +3 -3
- package/dist/router/prepare-bridge.mjs +2 -2
- package/dist/router/prepare-route.mjs +3 -3
- package/dist/scanner/index.mjs +4 -4
- package/dist/strategy/index.mjs +3 -3
- package/dist/tui/standalone-client.mjs +86 -85
- package/package.json +5 -4
- package/public/eval-report.json +1 -1
- package/public/oracle-splash/_variants/ice.html +2 -4
- package/public/oracle-splash/_variants/ivory.html +2 -4
- package/public/oracle-splash/assets/fonts/LICENSE-Cormorant-Garamond.txt +93 -0
- package/public/oracle-splash/assets/fonts/LICENSE-IBM-Plex-Mono.txt +93 -0
- package/public/oracle-splash/assets/fonts/LICENSE-Outfit.txt +93 -0
- package/public/oracle-splash/assets/fonts/LICENSE-UnifrakturCook.txt +94 -0
- package/public/oracle-splash/assets/fonts/font-provenance.json +426 -0
- package/public/oracle-splash/assets/fonts/oracle-font-00.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-01.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-02.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-03.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-04.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-05.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-06.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-07.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-08.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-09.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-10.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-11.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-12.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-13.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-14.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-15.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-16.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-17.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-18.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-19.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-20.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-21.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-22.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-23.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-24.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-25.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-26.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-27.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-fonts.css +504 -0
- package/public/oracle-splash/assets/transport-probe-sw.js +2 -0
- package/public/oracle-splash/docs/browser-and-web/index.html +6 -6
- package/public/oracle-splash/docs/connectors/index.html +5 -5
- package/public/oracle-splash/docs/docs.css +4 -4
- package/public/oracle-splash/docs/docs.js +119 -7
- package/public/oracle-splash/docs/getting-started/index.html +5 -5
- package/public/oracle-splash/docs/index.html +6 -6
- package/public/oracle-splash/docs/reference/index.html +5 -5
- package/public/oracle-splash/docs/security/index.html +5 -5
- package/public/oracle-splash/docs/using-oracle/index.html +5 -5
- package/public/oracle-splash/download/index.html +8 -10
- package/public/oracle-splash/downloads/index.html +3 -5
- package/public/oracle-splash/eval/archive/oracle-0.35.40.json +101 -0
- package/public/oracle-splash/eval/archive/oracle-0.35.41-blocked-attempt.json +672 -0
- package/public/oracle-splash/eval/index.html +104 -0
- package/public/oracle-splash/eval/releases/oracle-0.35.41.json +788 -0
- package/public/oracle-splash/index.html +16 -18
- package/public/oracle-splash/mesh-graph.svg +1 -1
- package/public/oracle-splash/pricing/index.html +6 -8
- package/public/oracle-splash/security/index.html +3 -5
- package/public/oracle-splash/what-it-does/index.html +4 -6
- package/public/oracle-splash/where-it-works/index.html +3 -5
- package/server.json +2 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)};i("method",e),i("url",t),Object.keys(r||{}).map((c,u)=>({name:c.toLowerCase(),order:u,value:String(r[c])})).sort((c,u)=>c.name.localeCompare(u.name)||c.order-u.order).forEach((c,u)=>{i(`header-name-${u}`,c.name),i(`header-value-${u}`,c.value)}),i("body",o??"-");for(let c of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])i(`context-${c}`,n[c]??"-");return s.digest("hex")}function vs(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Dr):Math.min(250*2**e,Dr)+Math.floor(Math.random()*100)}function oe(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function Pt(e,t,r){return oe(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function pe(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function Is(e){return e?e.byteLength??e.length??0:0}async function xs(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&&(pe(e),!n))throw Pt(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 Pt(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+=Is(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 Pt(r,`streamed ${c} bytes`,t);let l=Buffer.concat(a);return(u?l.subarray(0,t):l).toString("utf8")}function Ns(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function ks(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:s,lookupFn:i,realFetch:a,untrustedUrl:c=!1,maxResponseBytes:u=null,sameOriginRedirectsOnly:l=!1,importUndici:d,validateResponse:p,signal:f,redirectPolicy:m="follow",maxRedirects:h=et}){let b=new AbortController,g=setTimeout(()=>b.abort(),s),S=f?Fr?Fr([f,b.signal]):f:b.signal,N=null,T=t,E=i?{lookupFn:i}:{};if(c&&!a&&!Lt(T))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 O=async(v,{status:x=null}={})=>{let y=await kt(v,E);if(!y.ok)throw oe(x==null?`HTTP refused ${v}: ${y.error}`:`HTTP redirect to ${v} ${y.error}`,x==null?{}:{status:x});let C=new URL(v).hostname;if(a){if(N&&(await N.close(),N=null),!N)try{N=await Ct({requireUndici:!0,...d?{importUndici:d}:{}})}catch(w){throw oe(x==null?`HTTP refused ${v}: ${w?.message||w}`:`HTTP redirect to ${v} refused: ${w?.message||w}`,x==null?{}:{status:x})}N.pin(C,y.addresses),T=N.fetch}else qr(T,C,y.addresses);return y};try{let v=String(e),x=Object.assign(Object.create(null),n||{});c&&await O(v);for(let y=0;y<=h;y+=1){let C=Object.assign(Object.create(null),{method:r,headers:x,body:o,signal:S,redirect:"manual",dispatcher:void 0}),w=await T(v,C);if((m==="error"||h===0)&&w.status>=300&&w.status<400)throw pe(w),oe(`HTTP ${w.status} ${r} redirect refused`,{status:w.status,redirectRefused:!0});if(fs.has(w.status)){let L=l===!0&&r==="POST"&&[307,308].includes(w.status)&&zr(r,o);if(r!=="GET"&&r!=="HEAD"&&!L){pe(w);let B=new Error(`HTTP ${w.status} ${r} ${v} redirected non-idempotent request`);throw B.status=w.status,B}if(y===h)throw pe(w),oe(`HTTP ${w.status} ${r} redirect budget exhausted`,{status:w.status,redirectRefused:!0});let ne=w.headers?.get?.("location"),V;try{V=ws(ne,v)}catch(B){throw pe(w),B}let ae=!gs(V,v);if(pe(w),ae&&r==="POST"){let B=new Error(`HTTP ${w.status} ${r} cross-origin redirect refused`);throw B.status=w.status,B}if(ae&&l){let B=new Error(`HTTP ${w.status} ${r} cross-origin redirect refused`);throw B.status=w.status,B.retryable=!1,B}if(ae&&(x=ys(x)),c)await O(V,{status:w.status});else if(ae){let B=await kt(V,E);if(!B.ok){let P=new Error(`HTTP redirect from ${v} ${B.error}`);throw P.status=w.status,P.retryable=!1,P}a&&B.addresses?.length&&(N||(N=await Ct(d?{importUndici:d}:{})),N&&(N.pin(new URL(V).hostname,B.addresses),T=N.fetch))}v=V;continue}if(typeof p=="function")try{await p(w,{url:v})}catch(L){throw pe(w),oe(L?.message||String(L))}let M=await xs(w,u,{url:v,onOversize:()=>b.abort()}),A=Ns(M);if(!w.ok){let L=new Error(`HTTP ${w.status} ${r} ${v}`);throw L.status=w.status,L.retryAfter=w.headers?.get?.("retry-after")??null,L.body=A??M.slice(0,300),L}return A??M}throw new Error(`HTTP redirect loop for ${e}`)}catch(v){if(b.signal.aborted&&!_t(f)){let x=v&&(typeof v=="object"||typeof v=="function")&&!ee.isProxy(v)?v:null,y=x?Object.getOwnPropertyDescriptor(x,"oversize"):null;if(!(y&&Object.hasOwn(y,"value")&&y.value===!0))try{if(!x)throw new TypeError("unsafe rejection");Object.defineProperties(x,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let w=new Error("HTTP request timed out");throw Object.defineProperties(w,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),w}}throw v}finally{clearTimeout(g),N&&await N.close()}}async function te(e,t={}){if(t!=null&&typeof t!="object"&&typeof t!="function")throw new TypeError("HTTP options must be an object");if(t!=null&&ee.isProxy(t))throw new TypeError("HTTP options must not be a proxy");let r=new Set(["body","dedupe","fetchImpl","headers","importUndici","lookupFn","maxRedirects","maxResponseBytes","method","redirectPolicy","retries","sameOriginRedirectsOnly","signal","timeoutMs","untrustedUrl","validateResponse"]);if(t!=null){if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("HTTP options contain unknown fields");for(let P of Object.getOwnPropertyNames(t)){let R=Object.getOwnPropertyDescriptor(t,P);if(!(P==="toJSON"&&R&&Object.hasOwn(R,"value")&&R.value===void 0)){if(!r.has(P))throw new TypeError("HTTP options contain unknown fields");if(!R||!R.enumerable||!Object.hasOwn(R,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=P=>{if(t==null||!Object.hasOwn(t,P))return;let R=Object.getOwnPropertyDescriptor(t,P);if(!R||!Object.hasOwn(R,"value"))throw new TypeError("HTTP options must contain own data properties");return R.value};if(typeof e!="string"||e.length===0||e.length>8192)throw new TypeError("HTTP URL must be a bounded string");let o=n("method");if(o!==void 0&&(typeof o!="string"||!/^[A-Za-z]+$/u.test(o)))throw new TypeError("HTTP method must be a string token");let s=n("timeoutMs");if(s!==void 0&&(!Number.isInteger(s)||s<1||s>12e4))throw new TypeError("HTTP timeoutMs must be a bounded integer");let i=n("retries");if(i!==void 0&&(!Number.isInteger(i)||i<0||i>10))throw new TypeError("HTTP retries must be a bounded integer");let a=n("redirectPolicy");if(a!==void 0&&a!=="follow"&&a!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let c=n("maxRedirects");if(c!==void 0&&(!Number.isInteger(c)||c<0||c>et))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${et}`);if(a==="error"&&c!==void 0&&c!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let u=a??"follow",l=u==="error"?0:c??et;for(let P of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let R=n(P);if(R!==void 0&&typeof R!="boolean")throw new TypeError(`HTTP ${P} must be boolean`)}let d=n("maxResponseBytes");if(d!==void 0&&(!Number.isInteger(d)||d<1||d>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let p=n("signal");if(p!==void 0){if(ee.isProxy(p)||!(p instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{_t(p)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let P of["importUndici","lookupFn","validateResponse"]){let R=n(P);if(R!==void 0&&typeof R!="function")throw new TypeError(`HTTP ${P} must be a function`)}let f=n("fetchImpl"),m=f||globalThis.fetch;if(typeof m!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let h=s??12e3,b=(o||"GET").toUpperCase(),g=n("headers"),S=bs(g),N=Object.assign(Object.create(null),S);Object.keys(N).some(P=>P.toLowerCase()==="accept")||(N.Accept="application/json");let T=n("body");T!=null&&typeof T!="string"&&(Object.keys(N).find(R=>R.toLowerCase()==="content-type")||(N["Content-Type"]="application/json"),T=hs(T));let E=i??as,O=n("lookupFn"),v=!f,x=n("untrustedUrl")===!0,y=n("sameOriginRedirectsOnly")===!0,C=n("importUndici"),w=n("validateResponse"),M=p,A=d??null,L=async()=>{let P;for(let R=0;R<=E;R++){M&&ls.call(M);try{return await ks(e,{fetchImpl:m,method:b,headers:N,body:T,timeoutMs:h,lookupFn:O,realFetch:v,untrustedUrl:x,maxResponseBytes:A,sameOriginRedirectsOnly:y,importUndici:C,validateResponse:w,signal:M,redirectPolicy:u,maxRedirects:l})}catch(ce){P=ce;let Ae=At=>{if(!ce||typeof ce!="object"&&typeof ce!="function"||ee.isProxy(ce))return;let Le=Object.getOwnPropertyDescriptor(ce,At);return Le&&Object.hasOwn(Le,"value")?Le.value:void 0},gt=Ae("status"),_o=Ae("oracleTimeout")===!0||Ae("name")==="AbortError"||Ae("name")==="TimeoutError"||_t(M),jo=new Set([408,425,429]),Bo=Ae("retryable")===!1?!1:gt!=null?jo.has(gt)||is.has(gt)&&$r.has(b):!_o&&$r.has(b);if(R===E||!Bo)throw ce;let Ar=vs(R,Ae("retryAfter"));M?await new Promise((At,Le)=>{let qo=setTimeout(At,Ar);ds.call(M,"abort",()=>{clearTimeout(qo),Le(ps(M)||new DOMException("Aborted","AbortError"))},{once:!0})}):await Os(Ar)}}throw P};if(!(n("dedupe")!==!1&&!M&&zr(b,T)))return L();let V=Es(b,e,N,{untrustedUrl:x,maxResponseBytes:A,sameOriginRedirectsOnly:y,redirectPolicy:u,maxRedirects:l,timeoutMs:h,retries:E,fetchImpl:Ze(m),realFetch:v,lookupFn:Ze(O),importUndici:Ze(C),validateResponse:Ze(w)},T),ae=Rt.get(V);if(ae)return ae;let B=L().finally(()=>Rt.delete(V));return Rt.set(V,B),B}async function Kr(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 is,$r,as,Dr,cs,us,ls,ds,Fr,_t,ps,fs,et,Pc,Z,Rt,Mr,Hr,As,Ss,Os,Ee=J(()=>{Ur();is=new Set([408,425,429,500,502,503,504]),$r=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),as=2,Dr=4e3,cs=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,us=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,ls=AbortSignal.prototype.throwIfAborted,ds=EventTarget.prototype.addEventListener,Fr=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,_t=e=>e?cs.call(e):!1,ps=e=>e?us.call(e):void 0,fs=new Set([301,302,303,307,308]),et=3,Pc=64*1024,Z=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});Rt=new Map,Mr=new WeakMap,Hr=1;As=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),Ss=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);Os=e=>new Promise(t=>setTimeout(t,e))});import{types as Gt}from"node:util";function Jt(e){if(!e||typeof e!="object"||Gt.isProxy(e)||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ot(e,t){if(e==null||(typeof e=="object"||typeof e=="function")&&Gt.isProxy(e)||!Object.hasOwn(Object(e),t))return;let r=Object.getOwnPropertyDescriptor(Object(e),t);return r&&Object.hasOwn(r,"value")?r.value:void 0}function nt(e,t="provider response",r=0){if(r>64)throw new Error(`${t} exceeds the JSON nesting bound`);if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e;if(Array.isArray(e)){if(Gt.isProxy(e)||e.length>1e5)throw new Error(`${t} contains an invalid array`);let o=new Array(e.length);for(let s=0;s<e.length;s+=1){let i=Object.getOwnPropertyDescriptor(e,String(s));if(!i||!Object.hasOwn(i,"value"))throw new Error(`${t} arrays must contain dense own data`);o[s]=nt(i.value,t,r+1)}return o}if(!Jt(e))throw new Error(`${t} contains a non-JSON value`);let n=Object.create(null);for(let o of Object.keys(e)){let s=Object.getOwnPropertyDescriptor(e,o);if(!s||!Object.hasOwn(s,"value"))throw new Error(`${t} objects must contain own data`);n[o]=nt(s.value,t,r+1)}return n}var Tn=J(()=>{});function gi(e={}){return String(e.rpcUrl||process.env.SOLANA_RPC_URL||wi).trim()}function ve(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 Ln(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=nt(await te(gi(r),{method:"POST",body:{jsonrpc:"2.0",id:r.id||1,method:e,params:t},fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,maxResponseBytes:r.maxResponseBytes,sameOriginRedirectsOnly:r.sameOriginRedirectsOnly}),"solana-rpc response");if(!Jt(o))throw new Error(`solana-rpc ${e}: invalid response envelope`);let s=ot(o,"error");if(s)throw new Error(`solana-rpc ${e}: ${ot(s,"message")||JSON.stringify(s)}`);if(!Object.hasOwn(o,"result"))throw new Error(`solana-rpc ${e}: missing result`);return ot(o,"result")}var wi,Yt=J(()=>{Ee();Tn();wi="https://api.mainnet-beta.solana.com"});import{createHash as Ai,createHmac as Si,timingSafeEqual as Eu}from"node:crypto";function Qt(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Qt).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Qt(e[r])}`).join(",")}}`}function Rn(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Pn(e=process.env){return Rn(process.env)||Rn(e)}function Ii(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function xi(e){let t=Ii(e);return Ai("sha256").update(Qt(t)).digest("hex")}function Ni(e,t=Pn()){return t?Si("sha256",t).update(String(e)).digest("hex"):""}function _n(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+vi:Number(s),l=u-c;if(!Number.isSafeInteger(c)||!Number.isSafeInteger(u)||l<=0||l>Oi)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let p={...a,preparedAt:c,expiresAt:u,prepareVersion:Ei},f=xi(p),m=Pn(n),h=m?Ni(f,m):void 0,b={...p,prepareHash:f};return h&&(b.prepareMac=h),b}var Ei,vi,Oi,jn=J(()=>{Ei=2,vi=300*1e3,Oi=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});function Xt(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function Li(e){return ki.some(t=>e.startsWith(t))||Ci.has(e)}function Ri(e){let t=String(e);if(!/^[\x20-\x7e]+$/.test(t))return!0;let r=Xt(t);return Li(r)?!1:Ti.has(r)?!0:r.includes("signed")||r.includes("signature")||r.endsWith("sig")||r.endsWith("sigs")}function Pi(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 Zt(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=>Zt(c,t+1,r,n));let o=[];for(let[c,u]of Object.entries(e)){if(Ri(c)){o.push(c);continue}o.push(...Zt(u,t+1,r,n))}let i=Object.keys(e).map(Xt).some(c=>c.endsWith("psbt")||c.endsWith("psbtbase64")),a=Object.entries(e).some(([c,u])=>/complete|finalized|isfinal/.test(Xt(c))&&u===!0);return i&&a&&o.push("psbt(complete)"),Pi(e)&&o.push("v/r/s"),o}function Bn(e,t){let r=Zt(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 ki,Ci,Ti,qn=J(()=>{ki=["unsigned","notsigned","tosign","signable"],Ci=new Set(["requiresusersignature","requiressignature","needssignature","signaturerequired","signaturesrequired","signingready","signaturecount","signaturethreshold","requiredsignatures","signatureneeded","hassignature","allowsignatures","requestsignature","multisig","cosig","msig"]),Ti=new Set(["sig","sigs","scriptsig","witness","psbt","finalizedpsbt","completepsbt","finalpsbt","psbtfinalized","serializedtransaction"])});var rr={};St(rr,{JUPITER_MAX_SLIPPAGE_BPS:()=>Dn,JUPITER_SWAP_API:()=>$e,SOL_MINT:()=>at,USDC_MINT:()=>er,jupiterHealth:()=>$i,jupiterPrepareSwap:()=>Fi,jupiterQuote:()=>tr,jupiterSignerEnvelope:()=>Vn,jupiterVenues:()=>Ui,solanaGuard:()=>it});function Fn(e={}){return String(e.baseUrl||process.env.JUPITER_SWAP_API_URL||$e).replace(/\/$/,"")}function De(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 Mn(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>Dn)throw new Error("jupiter: slippage exceeds hard 100 bps cap");return t}function st(e,t){return e==null?t:!!e}function _i(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 ji(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 Hn(e){let t=Buffer.from(e,"base64"),r=ji(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 it(e={},{quotedAtMs:t=Date.now(),ttlMs:r=Un}={}){let n=ve(e.inputMint,"inputMint"),o=ve(e.outputMint,"outputMint"),s=De(e.inAmount,"inAmount"),i=De(e.outAmount,"outAmount"),a=De(e.otherAmountThreshold??e.outAmount,"otherAmountThreshold"),c=Mn(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)||Un,1e3),3e4)}}function Vn({userPublicKey:e,guard:t,swapTransaction:r,args:n={},response:o={}}){if(t.inputMint!==at)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=Hn(r),i=De(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 $n(e){if(typeof e!="string"||!e.length)return!1;let t=0n;for(let o of e){let s=qi.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 Ui(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(`${$e}/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])=>$n(p)),c=[],u=i.filter(([p])=>!$n(p)).map(([p,f])=>({programId:p,label:f,reason:"malformed program id"}));if(e.verify===!1)return{source:`${$e}/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[g,S]=f[b];h&&h.executable===!0&&Bi.has(h.owner)?c.push({programId:g,label:S,owner:h.owner}):u.push({programId:g,label:S,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:`${$e}/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 $i(e={}){try{return{ok:!0,provider:"jupiter",outAmount:(await tr({inputMint:at,outputMint:er,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 tr(e={},t={}){let r=ve(e.inputMint||e.fromMint||at,"inputMint"),n=ve(e.outputMint||e.toMint||er,"outputMint"),o=De(e.amount||e.inAmount,"amount"),s=Mn(e.slippageBps??e.maxSlippageBps??50),i=new URL(`${Fn(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 te(i.toString(),{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),c=it({...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 Di(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function Fi(e={},t={}){let r=ve(e.userPublicKey||e.owner||e.wallet,"userPublicKey"),n=e.quoteResponse?{quote:e.quoteResponse,solanaGuard:it(e.quoteResponse,t)}:await tr(e,t),o=n.quote,s=n.solanaGuard||it(o,t);if(st(e.dynamicSlippage,!1)===!0)throw new Error("jupiter: dynamicSlippage would override the enforced slippage ceiling \u2014 pass an explicit slippageBps instead");let i=await te(`${Fn(t)}/swap`,{method:"POST",body:Di({quoteResponse:o,userPublicKey:r,wrapAndUnwrapSol:st(e.wrapAndUnwrapSol,!0),dynamicComputeUnitLimit:st(e.dynamicComputeUnitLimit,!0),dynamicSlippage:!1,asLegacyTransaction:st(e.asLegacyTransaction,!0),prioritizationFeeLamports:e.prioritizationFeeLamports??0}),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),a=_i(i?.swapTransaction);Hn(a),Bn("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=Vn({userPublicKey:r,guard:s,swapTransaction:a,args:e,response:i})}catch(f){p=String(f?.message||f).slice(0,200)}return _n({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 $e,at,er,Dn,Un,Bi,qi,nr=J(()=>{Ee();Yt();jn();qn();$e="https://lite-api.jup.ag/swap/v1",at="So11111111111111111111111111111111111111112",er="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",Dn=100,Un=2e4;Bi=new Set(["BPFLoaderUpgradeab1e11111111111111111111111","BPFLoader2111111111111111111111111111111111","BPFLoader1111111111111111111111111111111111"]),qi="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});var Wn={};St(Wn,{SELL_SIM:()=>q,assertSellable:()=>Ki,simulateSell:()=>Kn});function Vi(e,t){return t===0n?null:Number((t-e)*10000n/t)}function zi(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 Kn(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=zi(e.amountIn,"amountIn"),i;try{i=await t.quote({chainId:o,inputMint:n,outputMint:r,amount:s.toString(),side:"buy"})}catch(f){return Y(q.UNKNOWN,`buy leg could not be quoted: ${or(f)}`,{chainId:o,token:r,base:n})}let a=zn(i?.outAmount);if(a==null||a===0n)return Y(q.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 Y(q.HONEYPOT,`buy routes but the SELL leg fails to quote (${or(f)}) \u2014 you would not be able to exit`,{chainId:o,token:r,base:n,tokensOut:a.toString()})}let u=zn(c?.outAmount);if(u==null||u===0n)return Y(q.HONEYPOT,"sell leg returns zero \u2014 the position cannot be exited for value",{chainId:o,token:r,base:n,tokensOut:a.toString()});let l=Vi(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 Y(q.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=or(f)}return p===!0&&(d.evidence="execution"),l==null?Y(q.UNKNOWN,"could not compute round-trip loss",d):l>=Mi?Y(q.HONEYPOT,`round trip loses ${(l/100).toFixed(1)}% \u2014 a sell tax or rigged curve, not normal slippage`,d):l>=Hi?Y(q.CAUTION,`round trip loses ${(l/100).toFixed(1)}% \u2014 high tax or thin liquidity`,d):p===!0?Y(q.SAFE,`round trip loses ${(l/100).toFixed(1)}% and the sell executes \u2014 exit path verified`,d):Y(q.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 Y(e,t,r){return{status:e,safe:e===q.SAFE,tradable:e===q.SAFE||e===q.CAUTION,reason:t,...r}}function zn(e){if(e==null)return null;try{let t=String(e).trim();return/^\d+$/.test(t)?BigInt(t):null}catch{return null}}function or(e){return String(e?.message||e).slice(0,120)}async function Ki(e={},t={}){let r=await Kn(e,t);if(!(r.status===q.SAFE||r.status===q.CAUTION&&t.allowCaution!==!1||r.status===q.UNKNOWN&&t.allowUnknown===!0)){let o=new Error(`sell-sim ${r.status}: ${r.reason}`);throw o.sellSim=r,o}return r}var q,Mi,Hi,Gn=J(()=>{q=Object.freeze({SAFE:"SAFE",CAUTION:"CAUTION",HONEYPOT:"HONEYPOT",UNKNOWN:"UNKNOWN"}),Mi=5e3,Hi=1500});import ut from"node:fs";import Yi from"node:os";import Ie from"node:path";import{fileURLToPath as Qi}from"node:url";function Zn(){return process.env.ORACLE_FAKE_HOME||Yi.homedir()}function Zi(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function lt(){return Zi()?process.env.ORACLE_CONFIG_DIR||Ie.join(Zn(),".config","oracle"):Ie.join(Zn(),".config","oracle")}function ea(){return Ie.join(lt(),"desk.json")}function ta(){return Ie.join(lt(),"env")}function Oe({force:e=!1}={}){if(Oe._done&&!e)return Oe._result||null;Oe._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=ta();if(ut.existsSync(o))for(let s of ut.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=ea();if(ut.existsSync(o)){let s=JSON.parse(ut.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)),Oe._result=Object.keys(t).length?t:null,Oe._result}var Xi,ju,eo=J(()=>{Xi=Ie.dirname(Qi(import.meta.url)),ju=Ie.resolve(Xi,"../..");try{Oe()}catch{}});var no={};St(no,{armPreparedAction:()=>ua,callSigner:()=>to,queueOwnerAction:()=>ro});import{existsSync as ra,readFileSync as na}from"node:fs";import{request as oa}from"node:http";import sa from"node:path";function aa(e=process.env){let t=String(e.ORACLE_SIGNER_URL||ia).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 ca(e=process.env){if(e.ORACLE_SIGNER_TOKEN)return String(e.ORACLE_SIGNER_TOKEN);let t=sa.join(lt(),"signer","signer-token");return ra(t)?na(t,"utf8").trim():null}function to(e,{method:t="GET",body:r=null,env:n=process.env,timeoutMs:o=4e3}={}){let s=aa(n),i=ca(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=oa({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 ro(e,t=process.env){if(!e||e.version!==1||!e.surface)throw new Error("queueOwnerAction: version-1 surface envelope required");return to("/pending",{method:"POST",body:{artifact:e},env:t,timeoutMs:8e3})}async function ua(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 ro(r,t)}var ia,oo=J(()=>{eo();ia="http://127.0.0.1:9462"});var Re=Object.freeze({PASS:"PASS",WARN:"WARN",BLOCK:"BLOCK",UNKNOWN:"UNKNOWN"}),$o=new Set(["LIVE","CACHED","STALE","UNKNOWN","UNAVAILABLE"]),Sr=/^0x[0-9a-fA-F]{40}$/,Do=/^0x[0-9a-fA-F]{64}$/;function Se(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Se(t);Object.freeze(e)}return e}function G(e,t=null){return e&&typeof e=="object"?structuredClone(e):t}function vr(e){return typeof e!="string"||!Number.isFinite(Date.parse(e))?null:new Date(e).toISOString()===e?e:null}function Er(e){return!!(e&&$o.has(e.evidence)&&vr(e.observedAt))}function Or(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 Ge(e){return[...new Set(e.filter(Boolean))]}function Fo(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]])!Er(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||!Er(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"),Or(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=Ge(t);return o.length?Se({status:Re.BLOCK,whyBlocked:o}):r.length?Se({status:Re.UNKNOWN,whyBlocked:Ge(r)}):n.length?Se({status:Re.WARN,whyBlocked:[],warnings:Ge(n)}):Se({status:Re.PASS,whyBlocked:[]})}function Mo(e={}){let t=G(e,{}),r=Object.fromEntries(Object.entries(t).map(([o,s])=>[o,vr(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 Ir(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("candidate must be an object");let t=G(e.chain,{}),r=G(e.token,{}),n=G(e.pool),o=G(e.venue,{}),s=G(e.signal,{}),i=G(e.route,{});i.cost=Or(i.cost);let a=Fo({...e,chain:t,token:r,pool:n,venue:o,signal:s,route:i}),c=s.unsolicitedAirdrop===!0,u=Sr.test(r.address||"")?r.address.toLowerCase():"unknown-token",l=Sr.test(n?.address||"")?n.address.toLowerCase():Do.test(n?.poolId||"")?n.poolId.toLowerCase():"unknown-pool",d=`${Number.isInteger(t.id)?t.id:"unknown-chain"}:${u}:${l}:${o.key||"unknown-venue"}`;return Se({id:d,status:a.status,chain:t,token:r,pool:n,venue:o,signal:s,risk:G(e.risk,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),sellability:G(e.sellability,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),sellSimulation:G(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:G(e.prepared,{status:"NOT_PREPARED",unsigned:!0}),whyBlocked:Ge([...e.whyBlocked||[],...a.whyBlocked]),latency:Mo(e.latency),held:c?!1:e.held===!0,eligible:c?!1:a.status===Re.PASS&&e.eligible!==!1})}function xr(e=[]){if(!Array.isArray(e))throw new TypeError("candidates must be an array");return Object.freeze(e.map(Ir).sort((t,r)=>t.id.localeCompare(r.id)))}import{AbiCoder as Ho,keccak256 as Vo}from"ethers";var Nr=/^0x[0-9a-fA-F]{40}$/,X=/^0x[0-9a-fA-F]{64}$/,zo=Ho.defaultAbiCoder();function ue(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))ue(t);Object.freeze(e)}return e}function kr(e){return String(e?.message||e||"unknown scan failure").slice(0,300)}function le(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 Ko(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(!X.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 Pe(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!X.test(r||"")||!/^0{24}[0-9a-f]{40}$/i.test(r.slice(2))?null:`0x${r.slice(-40)}`.toLowerCase()}function Lr(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 Cr(e,t,r){let n=Lr(e,t);if(!X.test(n||""))return null;let o=BigInt(n);return o<1n<<BigInt(r)?o:null}function Tr(e,t,r){let n=Lr(e,t);if(!X.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 Wo(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()||!X.test(e.topics[1]||"")||typeof e.data!="string"||e.data.length!==322)return null;let n=Pe(e,{topic:2}),o=Pe(e,{topic:3}),s=Cr(e,0,24),i=Tr(e,1,24),a=Pe(e,{dataWord:2}),c=Cr(e,3,160),u=Tr(e,4,24),l=le(e.blockNumber),d=le(e.logIndex);if(!n||!o||s===null||i===null||!a||c===null||u===null||l===null||d===null||!X.test(e.transactionHash||""))return null;let p=new Set(t.quoteAssets.map(N=>N.toLowerCase())),f=p.has(n),m=p.has(o);if(f===m)return null;let h=f?o:n,b=f?n:o;if(Vo(zo.encode(["address","address","uint24","int24","address"],[n,o,Number(s),i,a])).toLowerCase()!==e.topics[1].toLowerCase())return null;let S=e.transactionHash.toLowerCase();return{id:`${t.chainId}:${S}:${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:X.test(e.blockHash||"")?e.blockHash.toLowerCase():null,transactionHash:S,logIndex:d,evidence:"LIVE"}}function Go(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=Pe(e,r.layout.token),u=Pe(e,r.layout.pool),l=le(e.blockNumber),d=le(e.logIndex);if(!c||!u||l===null||d===null||!X.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:X.test(e.blockHash||"")?e.blockHash.toLowerCase():null,transactionHash:p,logIndex:d,evidence:"LIVE"}}function Jo(e,t,r){return r.decoder==="uniswap-v4-initialize"?Wo(e,t,r):Go(e,t,r)}async function Et(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=le(e.fromBlock??e.cursor?.nextBlock),s=le(e.toBlock);if(o===null||s===null||o<0||s<o)throw new TypeError("a valid integer block range is required");let i=ue({nextBlock:le(e.cursor?.nextBlock)??o});if(n)return ue({status:"UNKNOWN",discoveries:[],unavailable:[],cursor:i,whyBlocked:["reorg hint requires canonical range reconciliation"]});let a=[],c=[];for(let d of r){let p=Ko(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 ue({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 ue({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`scan failed: ${kr(h)}`]})}if(!m||m.complete!==!0||m.evidence&&m.evidence!=="LIVE"){let h=Array.isArray(m?.failedAt)?` at ${m.failedAt.join("-")}`:"";return ue({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`incomplete block range${h}${m?.error?`: ${kr(m.error)}`:""}`]})}for(let h of Array.isArray(m.logs)?m.logs:[]){let b=p.find(S=>S.topic0.toLowerCase()===String(h?.topics?.[0]||"").toLowerCase()),g=b&&Jo(h,d,b);g&&u.push(g)}}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 ue({status:"LIVE",discoveries:[...l.values()],unavailable:a,cursor:{nextBlock:s+1},whyBlocked:a.map(d=>d.reason)})}var hc=Et;import{createHash as Yo}from"node:crypto";var Ot="sha256:"+"0".repeat(64);function It(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))It(t);Object.freeze(e)}return e}function vt(e){return Array.isArray(e)?`[${e.map(vt).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${vt(e[t])}`).join(",")}}`:JSON.stringify(e)}function Rr(e){return`sha256:${Yo("sha256").update(vt(e)).digest("hex")}`}function Pr(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 Je(e=[]){if(!Array.isArray(e))throw new TypeError("evidence records must be an array");let t=new Set,r=Ot,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=Pr(o,s+1,r),a=Rr(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 It(n)}function Ye(e=[],t){let r=Je(e);if(r.some(s=>s.id===t?.id))throw new Error(`duplicate evidence event id: ${t.id}`);let n=r.at(-1)?.digest??Ot,o=Pr(t,r.length+1,n);return It([...r,{...o,digest:Rr(o)}])}var wc=Ye,gc=Je,Ac=Ot;var _r=Object.freeze({ALERT_ONLY:"alert_only",EXECUTE:"execute"});function jr(e){return e?.mode==="shadow"?_r.ALERT_ONLY:_r.EXECUTE}function Qe(e,t){return!!(e?.mode&&e.mode!=="shadow"&&t?.policyEligible===!0)}function Br(e,t,r){return Qe(e,t)&&r?.prepared===!0}var Qo="0x783cca1c0412dd0d695e784568c96da2e9c22ff989357a2e8b1d9b2b4e6b7118",Xo=Object.freeze([Object.freeze({topic0:Qo,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})})})]),Zo=Object.freeze({amountIn:"1000000000000000",quoteAssetDecimals:18,slippageBps:100,maxImpactPct:25,timeoutMs:4e3}),es=Object.freeze({amountIn:"1000000",quoteAssetDecimals:9,slippageBps:100,maxImpactPct:25,timeoutMs:12e3}),vc=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"})]);function Oc(e){return Object.freeze({id:`${e.key}-uniswap-v3-verified`,chainId:e.chainId,factoryAddress:e.factoryAddress,venue:Object.freeze({id:"uniswap-v3",key:"uniswap-v3",name:"Uniswap V3",supported:!0,verified:!0}),provenance:Object.freeze({verified:!0,source:e.provenance||`verified SwapRouter02.factory() eth_call on ${e.key} returned this address on 2026-08-28`,verifiedAt:"2026-08-28",router:e.router}),events:Xo,routeProbe:Zo})}function Ic(){return Object.freeze({id:"solana-pump-fun-verified",chain:"solana",programId:"6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P",venue:Object.freeze({id:"pump-fun",key:"pump-fun",name:"Pump.fun",supported:!0,verified:!0}),provenance:Object.freeze({verified:!0,source:"Official pump-fun/pump-public-docs create discriminator 181ec828051c0777",verifiedAt:"2026-08-28"}),events:Object.freeze([Object.freeze({decoder:"pump-create"})]),routeProbe:es})}import wt from"node:fs";import ja from"node:os";import ie from"node:path";Ee();var Wr={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}},Cs=new Map(Object.values(Wr).map(e=>[e.chainId,e]));function Gr(e){return Cs.get(Number(e))||null}function Jr(e,t=process.env){let r=Gr(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 Ts,getAddress as Ls}from"ethers";var Yr=new Ts(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Qr(e,t){try{return Ls(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}var Rs={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 Ps(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=Jr(e,r);return n||Rs[Number(e)]||null}var _s=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function js(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!_s.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 _e=new Map,Xr=new Map;function Bs(e){let t=new Error(e?.message||JSON.stringify(e));return t.code=e?.code,t}function qs(e){if(e?.error)throw Bs(e.error);return e?.result}function Us(e,t,r){return`${e}
|
|
1
|
+
var Do=Object.defineProperty;var J=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var vt=(e,t)=>{for(var r in t)Do(e,r,{get:t[r],enumerable:!0})};import de from"node:net";import ns from"node:dns";function et(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 kt(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 Ct(e){if(de.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(de.isIPv6(e)){let t=et(e);if(!t)return!1;let r=et("::ffff:0:0");return kt(t,r,96)?Ct([...t.slice(12)].join(".")):kt(t,et("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([o,s])=>kt(t,et(o),s)):!1}return!1}function ss(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(os.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=de.isIP(r);return n!==0&&!Ct(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function Tt(e,{lookupFn:t=ns.promises.lookup}={}){let r=ss(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:de.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=>!Ct(o.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function Lt({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||(de.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(de.isIP(p))return[{address:p,family:de.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=is((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 is(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 Pt(e){return typeof e=="function"&&typeof e[Rt]?.pin=="function"}function $r(e,t,r){if(!Pt(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[Rt].pin(t,r)}var os,Rt,Dr=J(()=>{os=new Set(["localhost","metadata.google.internal","metadata.goog"]);Rt=Symbol.for("oracle.egressGuard.pinCapableFetch")});import{createHash as as}from"node:crypto";import{types as ee}from"node:util";function _(e){return oe(`HTTP JSON body refused: ${e}`)}function bs(e){return["isArgumentsObject","isArrayBuffer","isAnyArrayBuffer","isArrayBufferView","isBoxedPrimitive","isDataView","isDate","isExternal","isGeneratorObject","isKeyObject","isCryptoKey","isMap","isMapIterator","isModuleNamespaceObject","isNativeError","isPromise","isRegExp","isSet","isSetIterator","isTypedArray","isWeakMap","isWeakSet"].some(t=>typeof ee[t]=="function"&&ee[t](e))}function ys(e){let t=[],r=0,n=0,o=0,s=0,i=new WeakSet,a=l=>{if(r+=Buffer.byteLength(l,"utf8"),r>Z.bytes)throw _("serialized byte limit exceeded");t.push(l)},c=l=>{if(Buffer.byteLength(l,"utf8")>Z.bytes)throw _("serialized byte limit exceeded");return JSON.stringify(l)},u=(l,d)=>{if(n+=1,n>Z.nodes)throw _("node limit exceeded");if(d>Z.depth)throw _("depth limit exceeded");if(l===null){a("null");return}if(typeof l=="string"){a(c(l));return}if(typeof l=="boolean"){a(l?"true":"false");return}if(typeof l=="number"){if(!Number.isFinite(l))throw _("non-finite number");a(Object.is(l,-0)?"0":String(l));return}if(typeof l!="object")throw _("unsupported non-JSON value");if(ee.isProxy(l))throw _("proxy value");if(bs(l))throw _("unsupported exotic object");if(i.has(l))throw _("cyclic value");i.add(l);try{if(Object.getOwnPropertySymbols(l).length>0)throw _("symbol-keyed fields are unsupported");if(Array.isArray(l)){let m=Object.getPrototypeOf(l),h=0;for(;m!==null;){if(ee.isProxy(m))throw _("proxy array prototype");if(h+=1,h>Z.depth)throw _("array prototype depth limit exceeded");m=Object.getPrototypeOf(m)}if(l.length>Z.arrayLength)throw _("array length limit exceeded");for(let w=0;w<l.length;w+=1){let A=Object.getOwnPropertyDescriptor(l,String(w));if(!A||!Object.hasOwn(A,"value")||A.enumerable!==!0)throw _("array entries must be dense enumerable own data")}let b=0;for(let w in l){if(s+=1,s>Z.fields)throw _("enumeration limit exceeded");if(Object.hasOwn(l,w)&&(b+=1,b>l.length))throw _("named array fields are unsupported")}if(b!==l.length)throw _("array entries must be dense enumerable own data");a("[");for(let w=0;w<l.length;w+=1)w&&a(","),u(Object.getOwnPropertyDescriptor(l,String(w)).value,d+1);a("]");return}let p=Object.getPrototypeOf(l);if(p!==Object.prototype&&p!==null)throw _("non-plain object");let f=[];for(let m in l){if(s+=1,s>Z.fields)throw _("enumeration limit exceeded");if(!Object.hasOwn(l,m))continue;if(o+=1,o>Z.fields)throw _("field limit exceeded");let h=Object.getOwnPropertyDescriptor(l,m);if(!h||!Object.hasOwn(h,"value")||h.enumerable!==!0)throw _("object fields must be enumerable own data");f.push([m,h.value])}a("{");for(let m=0;m<f.length;m+=1)m&&a(","),a(c(f[m][0])),a(":"),u(f[m][1],d+1);a("}")}finally{i.delete(l)}};return u(e,0),t.join("")}function ws(e){let t=Object.create(null);if(e==null)return t;if(typeof e!="object"&&typeof e!="function")throw new TypeError("HTTP headers must be an object");if(ee.isProxy(e))throw new TypeError("HTTP headers must not be a proxy");if(Object.getOwnPropertySymbols(e).length>0)throw new TypeError("HTTP headers must not contain symbol fields");let r=new Set;for(let n of Object.keys(e)){if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(n))throw new TypeError("HTTP header names must be valid tokens");let o=n.toLowerCase();if(r.has(o))throw new TypeError("HTTP headers contain a duplicate canonical name");r.add(o);let s=Object.getOwnPropertyDescriptor(e,n);if(!s||!Object.hasOwn(s,"value"))throw new TypeError("HTTP headers must contain own data properties");let i=s.value;if(i==null||["object","function","symbol"].includes(typeof i))throw new TypeError("HTTP header values must be scalar");t[n]=String(i)}return t}function gs(){return Object.assign(Object.create(null),{Accept:"application/json"})}function As(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 Ss(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function tt(e){if((typeof e!="object"||e===null)&&typeof e!="function")return`${typeof e}:${String(e)}`;let t=zr.get(e);return t||(t=Kr,Kr+=1,zr.set(e,t)),`reference:${t}`}function Wr(e){if(!e||typeof e!="object"||Array.isArray(e)||!Object.hasOwn(e,"jsonrpc")||!Object.hasOwn(e,"method")||e.jsonrpc!=="2.0")return!1;let t=typeof e.method=="string"?e.method:"";return t?Es.has(t)||/^get[A-Z0-9_]/u.test(t)||/^is[A-Z0-9_]/u.test(t)||/^eth_get[A-Z0-9_]/u.test(t):!1}function Gr(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}if(Array.isArray(r))return r.length>0&&r.every(Wr);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return Wr(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&vs.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function Os(e,t,r,n={},o=null){let s=as("sha256"),i=(c,u)=>{let l=String(u);s.update(String(Buffer.byteLength(c,"utf8"))).update(":").update(c),s.update("=").update(String(Buffer.byteLength(l,"utf8"))).update(":").update(l).update(`
|
|
2
|
+
`)};i("method",e),i("url",t),Object.keys(r||{}).map((c,u)=>({name:c.toLowerCase(),order:u,value:String(r[c])})).sort((c,u)=>c.name.localeCompare(u.name)||c.order-u.order).forEach((c,u)=>{i(`header-name-${u}`,c.name),i(`header-value-${u}`,c.value)}),i("body",o??"-");for(let c of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])i(`context-${c}`,n[c]??"-");return s.digest("hex")}function Is(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Mr):Math.min(250*2**e,Mr)+Math.floor(Math.random()*100)}function oe(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function jt(e,t,r){return oe(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function pe(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function Ns(e){return e?e.byteLength??e.length??0:0}async function ks(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&&(pe(e),!n))throw jt(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 jt(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+=Ns(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 jt(r,`streamed ${c} bytes`,t);let l=Buffer.concat(a);return(u?l.subarray(0,t):l).toString("utf8")}function Cs(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function Ts(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:s,lookupFn:i,realFetch:a,untrustedUrl:c=!1,maxResponseBytes:u=null,sameOriginRedirectsOnly:l=!1,importUndici:d,validateResponse:p,signal:f,redirectPolicy:m="follow",maxRedirects:h=rt}){let b=null,w=t,A=i?{lookupFn:i}:{};if(c&&!a&&!Pt(w))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 C=new AbortController,T=setTimeout(()=>C.abort(),s),E=f?Vr?Vr([f,C.signal]):f:C.signal,O=async(v,{status:x=null}={})=>{let y=await Tt(v,A);if(!y.ok)throw oe(x==null?`HTTP refused ${v}: ${y.error}`:`HTTP redirect to ${v} ${y.error}`,x==null?{}:{status:x});let k=new URL(v).hostname;if(a){if(b&&(await b.close(),b=null),!b)try{b=await Lt({requireUndici:!0,...d?{importUndici:d}:{}})}catch(g){throw oe(x==null?`HTTP refused ${v}: ${g?.message||g}`:`HTTP redirect to ${v} refused: ${g?.message||g}`,x==null?{}:{status:x})}b.pin(k,y.addresses),w=b.fetch}else $r(w,k,y.addresses);return y};try{let v=String(e),x=Object.assign(Object.create(null),n||{});c&&await O(v);for(let y=0;y<=h;y+=1){let k=Object.assign(Object.create(null),{method:r,headers:x,body:o,signal:E,redirect:"manual",dispatcher:void 0}),g=await w(v,k);if((m==="error"||h===0)&&g.status>=300&&g.status<400)throw pe(g),oe(`HTTP ${g.status} ${r} redirect refused`,{status:g.status,redirectRefused:!0});if(hs.has(g.status)){let L=l===!0&&r==="POST"&&[307,308].includes(g.status)&&Gr(r,o);if(r!=="GET"&&r!=="HEAD"&&!L){pe(g);let B=new Error(`HTTP ${g.status} ${r} ${v} redirected non-idempotent request`);throw B.status=g.status,B}if(y===h)throw pe(g),oe(`HTTP ${g.status} ${r} redirect budget exhausted`,{status:g.status,redirectRefused:!0});let ne=g.headers?.get?.("location"),V;try{V=As(ne,v)}catch(B){throw pe(g),B}let ae=!Ss(V,v);if(pe(g),ae&&r==="POST"){let B=new Error(`HTTP ${g.status} ${r} cross-origin redirect refused`);throw B.status=g.status,B}if(ae&&l){let B=new Error(`HTTP ${g.status} ${r} cross-origin redirect refused`);throw B.status=g.status,B.retryable=!1,B}if(ae&&(x=gs(x)),c)await O(V,{status:g.status});else if(ae){let B=await Tt(V,A);if(!B.ok){let P=new Error(`HTTP redirect from ${v} ${B.error}`);throw P.status=g.status,P.retryable=!1,P}a&&B.addresses?.length&&(b||(b=await Lt(d?{importUndici:d}:{})),b&&(b.pin(new URL(V).hostname,B.addresses),w=b.fetch))}v=V;continue}if(typeof p=="function")try{await p(g,{url:v})}catch(L){throw pe(g),oe(L?.message||String(L))}let q=await ks(g,u,{url:v,onOversize:()=>C.abort()}),S=Cs(q);if(!g.ok){let L=new Error(`HTTP ${g.status} ${r} ${v}`);throw L.status=g.status,L.retryAfter=g.headers?.get?.("retry-after")??null,L.body=S??q.slice(0,300),L}return S??q}throw new Error(`HTTP redirect loop for ${e}`)}catch(v){if(C.signal.aborted&&!je(f)){let x=v&&(typeof v=="object"||typeof v=="function")&&!ee.isProxy(v)?v:null,y=x?Object.getOwnPropertyDescriptor(x,"oversize"):null;if(!(y&&Object.hasOwn(y,"value")&&y.value===!0))try{if(!x)throw new TypeError("unsafe rejection");Object.defineProperties(x,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let g=new Error("HTTP request timed out");throw Object.defineProperties(g,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),g}}throw v}finally{clearTimeout(T),b&&await b.close()}}async function te(e,t={}){if(t!=null&&typeof t!="object"&&typeof t!="function")throw new TypeError("HTTP options must be an object");if(t!=null&&ee.isProxy(t))throw new TypeError("HTTP options must not be a proxy");let r=new Set(["body","dedupe","fetchImpl","headers","importUndici","lookupFn","maxRedirects","maxResponseBytes","method","redirectPolicy","retries","sameOriginRedirectsOnly","signal","timeoutMs","untrustedUrl","validateResponse"]);if(t!=null){if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("HTTP options contain unknown fields");for(let P of Object.getOwnPropertyNames(t)){let R=Object.getOwnPropertyDescriptor(t,P);if(!(P==="toJSON"&&R&&Object.hasOwn(R,"value")&&R.value===void 0)){if(!r.has(P))throw new TypeError("HTTP options contain unknown fields");if(!R||!R.enumerable||!Object.hasOwn(R,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=P=>{if(t==null||!Object.hasOwn(t,P))return;let R=Object.getOwnPropertyDescriptor(t,P);if(!R||!Object.hasOwn(R,"value"))throw new TypeError("HTTP options must contain own data properties");return R.value};if(typeof e!="string"||e.length===0||e.length>8192)throw new TypeError("HTTP URL must be a bounded string");let o=n("method");if(o!==void 0&&(typeof o!="string"||!/^[A-Za-z]+$/u.test(o)))throw new TypeError("HTTP method must be a string token");let s=n("timeoutMs");if(s!==void 0&&(!Number.isInteger(s)||s<1||s>12e4))throw new TypeError("HTTP timeoutMs must be a bounded integer");let i=n("retries");if(i!==void 0&&(!Number.isInteger(i)||i<0||i>10))throw new TypeError("HTTP retries must be a bounded integer");let a=n("redirectPolicy");if(a!==void 0&&a!=="follow"&&a!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let c=n("maxRedirects");if(c!==void 0&&(!Number.isInteger(c)||c<0||c>rt))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${rt}`);if(a==="error"&&c!==void 0&&c!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let u=a??"follow",l=u==="error"?0:c??rt;for(let P of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let R=n(P);if(R!==void 0&&typeof R!="boolean")throw new TypeError(`HTTP ${P} must be boolean`)}let d=n("maxResponseBytes");if(d!==void 0&&(!Number.isInteger(d)||d<1||d>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let p=n("signal");if(p!==void 0){if(ee.isProxy(p)||!(p instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{je(p)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let P of["importUndici","lookupFn","validateResponse"]){let R=n(P);if(R!==void 0&&typeof R!="function")throw new TypeError(`HTTP ${P} must be a function`)}let f=n("fetchImpl"),m=f||globalThis.fetch;if(typeof m!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let h=s??12e3,b=(o||"GET").toUpperCase(),w=n("headers"),A=ws(w),C=Object.assign(Object.create(null),A);Object.keys(C).some(P=>P.toLowerCase()==="accept")||(C.Accept="application/json");let T=n("body");T!=null&&typeof T!="string"&&(Object.keys(C).find(R=>R.toLowerCase()==="content-type")||(C["Content-Type"]="application/json"),T=ys(T));let E=i??us,O=n("lookupFn"),v=!f,x=n("untrustedUrl")===!0,y=n("sameOriginRedirectsOnly")===!0,k=n("importUndici"),g=n("validateResponse"),q=p,S=d??null,L=async()=>{let P;for(let R=0;R<=E;R++){q&&ps.call(q);try{return await Ts(e,{fetchImpl:m,method:b,headers:C,body:T,timeoutMs:h,lookupFn:O,realFetch:v,untrustedUrl:x,maxResponseBytes:S,sameOriginRedirectsOnly:y,importUndici:k,validateResponse:g,signal:q,redirectPolicy:u,maxRedirects:l})}catch(ce){P=ce;let Ae=Et=>{if(!ce||typeof ce!="object"&&typeof ce!="function"||ee.isProxy(ce))return;let Le=Object.getOwnPropertyDescriptor(ce,Et);return Le&&Object.hasOwn(Le,"value")?Le.value:void 0},St=Ae("status"),qo=Ae("oracleTimeout")===!0||Ae("name")==="AbortError"||Ae("name")==="TimeoutError"||je(q),Uo=new Set([408,425,429]),$o=Ae("retryable")===!1?!1:St!=null?Uo.has(St)||cs.has(St)&&Fr.has(b):!qo&&Fr.has(b);if(R===E||!$o)throw ce;let Sr=Is(R,Ae("retryAfter"));q?await new Promise((Et,Le)=>{let Er,Re=()=>{clearTimeout(Er),Hr.call(q,"abort",Re),Le(ms(q)||new DOMException("Aborted","AbortError"))};if(je(q)){Re();return}Er=setTimeout(()=>{Hr.call(q,"abort",Re),Et()},Sr),fs.call(q,"abort",Re,{once:!0}),je(q)&&Re()}):await xs(Sr)}}throw P};if(!(n("dedupe")!==!1&&!q&&Gr(b,T)))return L();let V=Os(b,e,C,{untrustedUrl:x,maxResponseBytes:S,sameOriginRedirectsOnly:y,redirectPolicy:u,maxRedirects:l,timeoutMs:h,retries:E,fetchImpl:tt(m),realFetch:v,lookupFn:tt(O),importUndici:tt(k),validateResponse:tt(g)},T),ae=_t.get(V);if(ae)return ae;let B=L().finally(()=>_t.delete(V));return _t.set(V,B),B}async function Jr(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 cs,Fr,us,Mr,ls,ds,ps,fs,Hr,Vr,je,ms,hs,rt,jc,Z,_t,zr,Kr,Es,vs,xs,Ee=J(()=>{Dr();cs=new Set([408,425,429,500,502,503,504]),Fr=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),us=2,Mr=4e3,ls=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,ds=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,ps=AbortSignal.prototype.throwIfAborted,fs=EventTarget.prototype.addEventListener,Hr=EventTarget.prototype.removeEventListener,Vr=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,je=e=>e?ls.call(e):!1,ms=e=>e?ds.call(e):void 0,hs=new Set([301,302,303,307,308]),rt=3,jc=64*1024,Z=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});_t=new Map,zr=new WeakMap,Kr=1;Es=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),vs=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);xs=e=>new Promise(t=>setTimeout(t,e))});import{types as Jt}from"node:util";function Yt(e){if(!e||typeof e!="object"||Jt.isProxy(e)||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function it(e,t){if(e==null||(typeof e=="object"||typeof e=="function")&&Jt.isProxy(e)||!Object.hasOwn(Object(e),t))return;let r=Object.getOwnPropertyDescriptor(Object(e),t);return r&&Object.hasOwn(r,"value")?r.value:void 0}function st(e,t="provider response",r=0){if(r>64)throw new Error(`${t} exceeds the JSON nesting bound`);if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e;if(Array.isArray(e)){if(Jt.isProxy(e)||e.length>1e5)throw new Error(`${t} contains an invalid array`);let o=new Array(e.length);for(let s=0;s<e.length;s+=1){let i=Object.getOwnPropertyDescriptor(e,String(s));if(!i||!Object.hasOwn(i,"value"))throw new Error(`${t} arrays must contain dense own data`);o[s]=st(i.value,t,r+1)}return o}if(!Yt(e))throw new Error(`${t} contains a non-JSON value`);let n=Object.create(null);for(let o of Object.keys(e)){let s=Object.getOwnPropertyDescriptor(e,o);if(!s||!Object.hasOwn(s,"value"))throw new Error(`${t} objects must contain own data`);n[o]=st(s.value,t,r+1)}return n}var Pn=J(()=>{});function Si(e={}){return String(e.rpcUrl||process.env.SOLANA_RPC_URL||Ai).trim()}function ve(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 _n(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=st(await te(Si(r),{method:"POST",body:{jsonrpc:"2.0",id:r.id||1,method:e,params:t},fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,maxResponseBytes:r.maxResponseBytes,sameOriginRedirectsOnly:r.sameOriginRedirectsOnly}),"solana-rpc response");if(!Yt(o))throw new Error(`solana-rpc ${e}: invalid response envelope`);let s=it(o,"error");if(s)throw new Error(`solana-rpc ${e}: ${it(s,"message")||JSON.stringify(s)}`);if(!Object.hasOwn(o,"result"))throw new Error(`solana-rpc ${e}: missing result`);return it(o,"result")}var Ai,Qt=J(()=>{Ee();Pn();Ai="https://api.mainnet-beta.solana.com"});import{createHash as Ei,createHmac as vi,timingSafeEqual as Ou}from"node:crypto";function Xt(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Xt).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Xt(e[r])}`).join(",")}}`}function jn(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Bn(e=process.env){return jn(process.env)||jn(e)}function Ni(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function ki(e){let t=Ni(e);return Ei("sha256").update(Xt(t)).digest("hex")}function Ci(e,t=Bn()){return t?vi("sha256",t).update(String(e)).digest("hex"):""}function qn(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+Ii:Number(s),l=u-c;if(!Number.isSafeInteger(c)||!Number.isSafeInteger(u)||l<=0||l>xi)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let p={...a,preparedAt:c,expiresAt:u,prepareVersion:Oi},f=ki(p),m=Bn(n),h=m?Ci(f,m):void 0,b={...p,prepareHash:f};return h&&(b.prepareMac=h),b}var Oi,Ii,xi,Un=J(()=>{Oi=2,Ii=300*1e3,xi=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});function Zt(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function Pi(e){return Ti.some(t=>e.startsWith(t))||Li.has(e)}function _i(e){let t=String(e);if(!/^[\x20-\x7e]+$/.test(t))return!0;let r=Zt(t);return Pi(r)?!1:Ri.has(r)?!0:r.includes("signed")||r.includes("signature")||r.endsWith("sig")||r.endsWith("sigs")}function ji(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 er(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=>er(c,t+1,r,n));let o=[];for(let[c,u]of Object.entries(e)){if(_i(c)){o.push(c);continue}o.push(...er(u,t+1,r,n))}let i=Object.keys(e).map(Zt).some(c=>c.endsWith("psbt")||c.endsWith("psbtbase64")),a=Object.entries(e).some(([c,u])=>/complete|finalized|isfinal/.test(Zt(c))&&u===!0);return i&&a&&o.push("psbt(complete)"),ji(e)&&o.push("v/r/s"),o}function $n(e,t){let r=er(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 Ti,Li,Ri,Dn=J(()=>{Ti=["unsigned","notsigned","tosign","signable"],Li=new Set(["requiresusersignature","requiressignature","needssignature","signaturerequired","signaturesrequired","signingready","signaturecount","signaturethreshold","requiredsignatures","signatureneeded","hassignature","allowsignatures","requestsignature","multisig","cosig","msig"]),Ri=new Set(["sig","sigs","scriptsig","witness","psbt","finalizedpsbt","completepsbt","finalpsbt","psbtfinalized","serializedtransaction"])});var nr={};vt(nr,{JUPITER_MAX_SLIPPAGE_BPS:()=>Hn,JUPITER_SWAP_API:()=>Fe,SOL_MINT:()=>ut,USDC_MINT:()=>tr,jupiterHealth:()=>Fi,jupiterPrepareSwap:()=>Hi,jupiterQuote:()=>rr,jupiterSignerEnvelope:()=>Wn,jupiterVenues:()=>Di,solanaGuard:()=>ct});function Vn(e={}){return String(e.baseUrl||process.env.JUPITER_SWAP_API_URL||Fe).replace(/\/$/,"")}function Me(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 zn(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>Hn)throw new Error("jupiter: slippage exceeds hard 100 bps cap");return t}function at(e,t){return e==null?t:!!e}function Bi(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 qi(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 Kn(e){let t=Buffer.from(e,"base64"),r=qi(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 ct(e={},{quotedAtMs:t=Date.now(),ttlMs:r=Fn}={}){let n=ve(e.inputMint,"inputMint"),o=ve(e.outputMint,"outputMint"),s=Me(e.inAmount,"inAmount"),i=Me(e.outAmount,"outAmount"),a=Me(e.otherAmountThreshold??e.outAmount,"otherAmountThreshold"),c=zn(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)||Fn,1e3),3e4)}}function Wn({userPublicKey:e,guard:t,swapTransaction:r,args:n={},response:o={}}){if(t.inputMint!==ut)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=Kn(r),i=Me(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 Mn(e){if(typeof e!="string"||!e.length)return!1;let t=0n;for(let o of e){let s=$i.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 Di(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(`${Fe}/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])=>Mn(p)),c=[],u=i.filter(([p])=>!Mn(p)).map(([p,f])=>({programId:p,label:f,reason:"malformed program id"}));if(e.verify===!1)return{source:`${Fe}/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[w,A]=f[b];h&&h.executable===!0&&Ui.has(h.owner)?c.push({programId:w,label:A,owner:h.owner}):u.push({programId:w,label:A,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:`${Fe}/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 Fi(e={}){try{return{ok:!0,provider:"jupiter",outAmount:(await rr({inputMint:ut,outputMint:tr,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 rr(e={},t={}){let r=ve(e.inputMint||e.fromMint||ut,"inputMint"),n=ve(e.outputMint||e.toMint||tr,"outputMint"),o=Me(e.amount||e.inAmount,"amount"),s=zn(e.slippageBps??e.maxSlippageBps??50),i=new URL(`${Vn(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 te(i.toString(),{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),c=ct({...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 Mi(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function Hi(e={},t={}){let r=ve(e.userPublicKey||e.owner||e.wallet,"userPublicKey"),n=e.quoteResponse?{quote:e.quoteResponse,solanaGuard:ct(e.quoteResponse,t)}:await rr(e,t),o=n.quote,s=n.solanaGuard||ct(o,t);if(at(e.dynamicSlippage,!1)===!0)throw new Error("jupiter: dynamicSlippage would override the enforced slippage ceiling \u2014 pass an explicit slippageBps instead");let i=await te(`${Vn(t)}/swap`,{method:"POST",body:Mi({quoteResponse:o,userPublicKey:r,wrapAndUnwrapSol:at(e.wrapAndUnwrapSol,!0),dynamicComputeUnitLimit:at(e.dynamicComputeUnitLimit,!0),dynamicSlippage:!1,asLegacyTransaction:at(e.asLegacyTransaction,!0),prioritizationFeeLamports:e.prioritizationFeeLamports??0}),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),a=Bi(i?.swapTransaction);Kn(a),$n("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=Wn({userPublicKey:r,guard:s,swapTransaction:a,args:e,response:i})}catch(f){p=String(f?.message||f).slice(0,200)}return qn({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 Fe,ut,tr,Hn,Fn,Ui,$i,or=J(()=>{Ee();Qt();Un();Dn();Fe="https://lite-api.jup.ag/swap/v1",ut="So11111111111111111111111111111111111111112",tr="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",Hn=100,Fn=2e4;Ui=new Set(["BPFLoaderUpgradeab1e11111111111111111111111","BPFLoader2111111111111111111111111111111111","BPFLoader1111111111111111111111111111111111"]),$i="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});var Yn={};vt(Yn,{SELL_SIM:()=>U,assertSellable:()=>Gi,simulateSell:()=>Jn});function Ki(e,t){return t===0n?null:Number((t-e)*10000n/t)}function Wi(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 Jn(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=Wi(e.amountIn,"amountIn"),i;try{i=await t.quote({chainId:o,inputMint:n,outputMint:r,amount:s.toString(),side:"buy"})}catch(f){return Y(U.UNKNOWN,`buy leg could not be quoted: ${sr(f)}`,{chainId:o,token:r,base:n})}let a=Gn(i?.outAmount);if(a==null||a===0n)return Y(U.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 Y(U.HONEYPOT,`buy routes but the SELL leg fails to quote (${sr(f)}) \u2014 you would not be able to exit`,{chainId:o,token:r,base:n,tokensOut:a.toString()})}let u=Gn(c?.outAmount);if(u==null||u===0n)return Y(U.HONEYPOT,"sell leg returns zero \u2014 the position cannot be exited for value",{chainId:o,token:r,base:n,tokensOut:a.toString()});let l=Ki(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 Y(U.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=sr(f)}return p===!0&&(d.evidence="execution"),l==null?Y(U.UNKNOWN,"could not compute round-trip loss",d):l>=Vi?Y(U.HONEYPOT,`round trip loses ${(l/100).toFixed(1)}% \u2014 a sell tax or rigged curve, not normal slippage`,d):l>=zi?Y(U.CAUTION,`round trip loses ${(l/100).toFixed(1)}% \u2014 high tax or thin liquidity`,d):p===!0?Y(U.SAFE,`round trip loses ${(l/100).toFixed(1)}% and the sell executes \u2014 exit path verified`,d):Y(U.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 Y(e,t,r){return{status:e,safe:e===U.SAFE,tradable:e===U.SAFE||e===U.CAUTION,reason:t,...r}}function Gn(e){if(e==null)return null;try{let t=String(e).trim();return/^\d+$/.test(t)?BigInt(t):null}catch{return null}}function sr(e){return String(e?.message||e).slice(0,120)}async function Gi(e={},t={}){let r=await Jn(e,t);if(!(r.status===U.SAFE||r.status===U.CAUTION&&t.allowCaution!==!1||r.status===U.UNKNOWN&&t.allowUnknown===!0)){let o=new Error(`sell-sim ${r.status}: ${r.reason}`);throw o.sellSim=r,o}return r}var U,Vi,zi,Qn=J(()=>{U=Object.freeze({SAFE:"SAFE",CAUTION:"CAUTION",HONEYPOT:"HONEYPOT",UNKNOWN:"UNKNOWN"}),Vi=5e3,zi=1500});import dt from"node:fs";import Xi from"node:os";import Ie from"node:path";import{fileURLToPath as Zi}from"node:url";function ro(){return process.env.ORACLE_FAKE_HOME||Xi.homedir()}function ta(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function pt(){return ta()?process.env.ORACLE_CONFIG_DIR||Ie.join(ro(),".config","oracle"):Ie.join(ro(),".config","oracle")}function ra(){return Ie.join(pt(),"desk.json")}function na(){return Ie.join(pt(),"env")}function Oe({force:e=!1}={}){if(Oe._done&&!e)return Oe._result||null;Oe._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=na();if(dt.existsSync(o))for(let s of dt.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=ra();if(dt.existsSync(o)){let s=JSON.parse(dt.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)),Oe._result=Object.keys(t).length?t:null,Oe._result}var ea,qu,no=J(()=>{ea=Ie.dirname(Zi(import.meta.url)),qu=Ie.resolve(ea,"../..");try{Oe()}catch{}});var io={};vt(io,{armPreparedAction:()=>da,callSigner:()=>oo,queueOwnerAction:()=>so});import{existsSync as oa,readFileSync as sa}from"node:fs";import{request as ia}from"node:http";import aa from"node:path";function ua(e=process.env){let t=String(e.ORACLE_SIGNER_URL||ca).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 la(e=process.env){if(e.ORACLE_SIGNER_TOKEN)return String(e.ORACLE_SIGNER_TOKEN);let t=aa.join(pt(),"signer","signer-token");return oa(t)?sa(t,"utf8").trim():null}function oo(e,{method:t="GET",body:r=null,env:n=process.env,timeoutMs:o=4e3}={}){let s=ua(n),i=la(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=ia({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 so(e,t=process.env){if(!e||e.version!==1||!e.surface)throw new Error("queueOwnerAction: version-1 surface envelope required");return oo("/pending",{method:"POST",body:{artifact:e},env:t,timeoutMs:8e3})}async function da(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 so(r,t)}var ca,ao=J(()=>{no();ca="http://127.0.0.1:9462"});var Pe=Object.freeze({PASS:"PASS",WARN:"WARN",BLOCK:"BLOCK",UNKNOWN:"UNKNOWN"}),Fo=new Set(["LIVE","CACHED","STALE","UNKNOWN","UNAVAILABLE"]),vr=/^0x[0-9a-fA-F]{40}$/,Mo=/^0x[0-9a-fA-F]{64}$/;function Se(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Se(t);Object.freeze(e)}return e}function G(e,t=null){return e&&typeof e=="object"?structuredClone(e):t}function Ir(e){return typeof e!="string"||!Number.isFinite(Date.parse(e))?null:new Date(e).toISOString()===e?e:null}function Or(e){return!!(e&&Fo.has(e.evidence)&&Ir(e.observedAt))}function xr(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 Ye(e){return[...new Set(e.filter(Boolean))]}function Ho(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]])!Or(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||!Or(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"),xr(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=Ye(t);return o.length?Se({status:Pe.BLOCK,whyBlocked:o}):r.length?Se({status:Pe.UNKNOWN,whyBlocked:Ye(r)}):n.length?Se({status:Pe.WARN,whyBlocked:[],warnings:Ye(n)}):Se({status:Pe.PASS,whyBlocked:[]})}function Vo(e={}){let t=G(e,{}),r=Object.fromEntries(Object.entries(t).map(([o,s])=>[o,Ir(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 Nr(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("candidate must be an object");let t=G(e.chain,{}),r=G(e.token,{}),n=G(e.pool),o=G(e.venue,{}),s=G(e.signal,{}),i=G(e.route,{});i.cost=xr(i.cost);let a=Ho({...e,chain:t,token:r,pool:n,venue:o,signal:s,route:i}),c=s.unsolicitedAirdrop===!0,u=vr.test(r.address||"")?r.address.toLowerCase():"unknown-token",l=vr.test(n?.address||"")?n.address.toLowerCase():Mo.test(n?.poolId||"")?n.poolId.toLowerCase():"unknown-pool",d=`${Number.isInteger(t.id)?t.id:"unknown-chain"}:${u}:${l}:${o.key||"unknown-venue"}`;return Se({id:d,status:a.status,chain:t,token:r,pool:n,venue:o,signal:s,risk:G(e.risk,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),sellability:G(e.sellability,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),sellSimulation:G(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:G(e.prepared,{status:"NOT_PREPARED",unsigned:!0}),whyBlocked:Ye([...e.whyBlocked||[],...a.whyBlocked]),latency:Vo(e.latency),held:c?!1:e.held===!0,eligible:c?!1:a.status===Pe.PASS&&e.eligible!==!1})}function kr(e=[]){if(!Array.isArray(e))throw new TypeError("candidates must be an array");return Object.freeze(e.map(Nr).sort((t,r)=>t.id.localeCompare(r.id)))}import{AbiCoder as zo,keccak256 as Ko}from"ethers";var Cr=/^0x[0-9a-fA-F]{40}$/,X=/^0x[0-9a-fA-F]{64}$/,Wo=zo.defaultAbiCoder();function ue(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))ue(t);Object.freeze(e)}return e}function Tr(e){return String(e?.message||e||"unknown scan failure").slice(0,300)}function le(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 Go(e){if(!e||typeof e!="object")return"factory descriptor is invalid";if(!Cr.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(!X.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=>!Cr.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 _e(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!X.test(r||"")||!/^0{24}[0-9a-f]{40}$/i.test(r.slice(2))?null:`0x${r.slice(-40)}`.toLowerCase()}function Pr(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 Lr(e,t,r){let n=Pr(e,t);if(!X.test(n||""))return null;let o=BigInt(n);return o<1n<<BigInt(r)?o:null}function Rr(e,t,r){let n=Pr(e,t);if(!X.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 Jo(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()||!X.test(e.topics[1]||"")||typeof e.data!="string"||e.data.length!==322)return null;let n=_e(e,{topic:2}),o=_e(e,{topic:3}),s=Lr(e,0,24),i=Rr(e,1,24),a=_e(e,{dataWord:2}),c=Lr(e,3,160),u=Rr(e,4,24),l=le(e.blockNumber),d=le(e.logIndex);if(!n||!o||s===null||i===null||!a||c===null||u===null||l===null||d===null||!X.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(Ko(Wo.encode(["address","address","uint24","int24","address"],[n,o,Number(s),i,a])).toLowerCase()!==e.topics[1].toLowerCase())return null;let A=e.transactionHash.toLowerCase();return{id:`${t.chainId}:${A}:${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:X.test(e.blockHash||"")?e.blockHash.toLowerCase():null,transactionHash:A,logIndex:d,evidence:"LIVE"}}function Yo(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=_e(e,r.layout.token),u=_e(e,r.layout.pool),l=le(e.blockNumber),d=le(e.logIndex);if(!c||!u||l===null||d===null||!X.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:X.test(e.blockHash||"")?e.blockHash.toLowerCase():null,transactionHash:p,logIndex:d,evidence:"LIVE"}}function Qo(e,t,r){return r.decoder==="uniswap-v4-initialize"?Jo(e,t,r):Yo(e,t,r)}async function Ot(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=le(e.fromBlock??e.cursor?.nextBlock),s=le(e.toBlock);if(o===null||s===null||o<0||s<o)throw new TypeError("a valid integer block range is required");let i=ue({nextBlock:le(e.cursor?.nextBlock)??o});if(n)return ue({status:"UNKNOWN",discoveries:[],unavailable:[],cursor:i,whyBlocked:["reorg hint requires canonical range reconciliation"]});let a=[],c=[];for(let d of r){let p=Go(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 ue({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 ue({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`scan failed: ${Tr(h)}`]})}if(!m||m.complete!==!0||m.evidence&&m.evidence!=="LIVE"){let h=Array.isArray(m?.failedAt)?` at ${m.failedAt.join("-")}`:"";return ue({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`incomplete block range${h}${m?.error?`: ${Tr(m.error)}`:""}`]})}for(let h of Array.isArray(m.logs)?m.logs:[]){let b=p.find(A=>A.topic0.toLowerCase()===String(h?.topics?.[0]||"").toLowerCase()),w=b&&Qo(h,d,b);w&&u.push(w)}}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 ue({status:"LIVE",discoveries:[...l.values()],unavailable:a,cursor:{nextBlock:s+1},whyBlocked:a.map(d=>d.reason)})}var yc=Ot;import{createHash as Xo}from"node:crypto";var xt="sha256:"+"0".repeat(64);function Nt(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Nt(t);Object.freeze(e)}return e}function It(e){return Array.isArray(e)?`[${e.map(It).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${It(e[t])}`).join(",")}}`:JSON.stringify(e)}function _r(e){return`sha256:${Xo("sha256").update(It(e)).digest("hex")}`}function jr(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=xt,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=jr(o,s+1,r),a=_r(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 Nt(n)}function Xe(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??xt,o=jr(t,r.length+1,n);return Nt([...r,{...o,digest:_r(o)}])}var Ac=Xe,Sc=Qe,Ec=xt;var Br=Object.freeze({ALERT_ONLY:"alert_only",EXECUTE:"execute"});function qr(e){return e?.mode==="shadow"?Br.ALERT_ONLY:Br.EXECUTE}function Ze(e,t){return!!(e?.mode&&e.mode!=="shadow"&&t?.policyEligible===!0)}function Ur(e,t,r){return Ze(e,t)&&r?.prepared===!0}var Zo="0x783cca1c0412dd0d695e784568c96da2e9c22ff989357a2e8b1d9b2b4e6b7118",es=Object.freeze([Object.freeze({topic0:Zo,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})})})]),ts=Object.freeze({amountIn:"1000000000000000",quoteAssetDecimals:18,slippageBps:100,maxImpactPct:25,timeoutMs:4e3}),rs=Object.freeze({amountIn:"1000000",quoteAssetDecimals:9,slippageBps:100,maxImpactPct:25,timeoutMs:12e3}),Ic=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"})]);function xc(e){return Object.freeze({id:`${e.key}-uniswap-v3-verified`,chainId:e.chainId,factoryAddress:e.factoryAddress,venue:Object.freeze({id:"uniswap-v3",key:"uniswap-v3",name:"Uniswap V3",supported:!0,verified:!0}),provenance:Object.freeze({verified:!0,source:e.provenance||`verified SwapRouter02.factory() eth_call on ${e.key} returned this address on 2026-08-28`,verifiedAt:"2026-08-28",router:e.router}),events:es,routeProbe:ts})}function Nc(){return Object.freeze({id:"solana-pump-fun-verified",chain:"solana",programId:"6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P",venue:Object.freeze({id:"pump-fun",key:"pump-fun",name:"Pump.fun",supported:!0,verified:!0}),provenance:Object.freeze({verified:!0,source:"Official pump-fun/pump-public-docs create discriminator 181ec828051c0777",verifiedAt:"2026-08-28"}),events:Object.freeze([Object.freeze({decoder:"pump-create"})]),routeProbe:rs})}import At from"node:fs";import qa from"node:os";import ie from"node:path";Ee();var Yr={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}},Ls=new Map(Object.values(Yr).map(e=>[e.chainId,e]));function Qr(e){return Ls.get(Number(e))||null}function Xr(e,t=process.env){let r=Qr(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 Rs,getAddress as Ps}from"ethers";var Zr=new Rs(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function en(e,t){try{return Ps(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}var _s={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 js(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=Xr(e,r);return n||_s[Number(e)]||null}var Bs=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function qs(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!Bs.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 Be=new Map,tn=new Map;function Us(e){let t=new Error(e?.message||JSON.stringify(e));return t.code=e?.code,t}function $s(e){if(e?.error)throw Us(e.error);return e?.result}function Ds(e,t,r){return`${e}
|
|
3
3
|
${t}
|
|
4
|
-
${JSON.stringify(r??[])}`}async function
|
|
4
|
+
${JSON.stringify(r??[])}`}async function Fs(e,t,r){return te(e,{method:"POST",body:t,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function D(e,t,r=[],n={}){let o=String(t||""),s=qs(o),i=js(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=tn.get(i);if(l!=null)return l}let c=n.dedupe!==!1&&!n.signal?Ds(i,o,r):null;if(c&&Be.has(c))return Be.get(c);let u=(async()=>{let l=await Fs(i,{jsonrpc:"2.0",id:1,method:t,params:r},n),d=$s(l);return s==="eth_chainid"&&typeof d=="string"&&tn.set(i,d),d})();return c&&(Be.set(c,u),u.finally(()=>{Be.get(c)===u&&Be.delete(c)}).catch(()=>{})),u}async function rn(e,t={}){let r=await D(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function nn(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await D(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function on(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=en(e.token||e.tokenAddress,"token"),o=en(e.account||e.owner||e.address,"account"),s=Zr.encodeFunctionData("balanceOf",[o]),i=await D(r,"eth_call",[{to:n,data:s},e.blockTag||"latest"],t),a=Zr.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"}}Ee();var Ms=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"]);function sn(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 Bt(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=sn(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)||Ms.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 an(e,t=[]){let r=Array.isArray(t)?t:[];return r.length&&sn(e,r[0]).address||null}var Hs="https://api.dexscreener.com",Kc=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function Vs(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||Hs).replace(/\/$/,"")}function zs(e,t){if(typeof e!="string"&&typeof e!="number")throw new Error(`${t} required`);let r=String(e).trim();if(!r||r.length>128||!/^[A-Za-z0-9][A-Za-z0-9._:+~-]*$/u.test(r))throw new Error(`${t} must be a valid path component of at most 128 characters`);return encodeURIComponent(r)}function Ks(e,t){return te(`${Vs(t)}${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}async function cn(e,t={}){return Ks(`/latest/dex/tokens/${zs(e,"tokenAddress")}`,t)}Ee();var nt=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),N=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),I=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),Ws=/^0x[0-9a-fA-F]{40}$/;function Gs(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}Ws.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))nt.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 Js(e){let{ok:t,errors:r,warnings:n}=Gs(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
|
|
5
5
|
- ${r.join(`
|
|
6
|
-
- `)}`);let o=e.capabilities||{},s=tt.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:tt.filter(a=>!s.includes(a))}},supports(a){return s.includes(a)}};for(let a of tt)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 sn=new Map;function an(e){let t=Ws(e);return sn.set(t.chainId,t),t}function cn(e){return sn.get(Number(e))||null}var qt={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},K=e=>BigInt(e).toString(16).padStart(64,"0"),je=e=>e.slice(2).toLowerCase().padStart(64,"0");function Gs(e,t){return`0x${qt.getAmountsOut}`+K(e)+K(64)+K(t.length)+t.map(je).join("")}function Js(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 Bt(e,t="router"){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}var Ut=100;function Ys(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 un(e){let{chainId:t,wrappedNative:r}=e;async function n(o,s,i,a){let c=await $(t,"eth_call",[{to:o,data:Gs(s,i)},"latest"],a);return Js(c?.result??c)}return{async quote({tokenIn:o,tokenOut:s,amountIn:i,path:a},c={}){let u=Bt(c.scanner);if(!u)return{chainId:t,evidence:k.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:k.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:u,path:l,evidence:k.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=Bt(a.scanner),u=i||r;if(u&&String(o).toLowerCase()===String(u).toLowerCase())return{chainId:t,token:o,verdict:I.UNKNOWN,evidence:k.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:I.UNKNOWN,evidence:k.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:I.FAIL,evidence:k.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:I.FAIL,evidence:k.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:I.FAIL,evidence:k.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=I.PASS,b="round trip completes with expected fee/impact loss";return m<5e3?(h=I.FAIL,b=`round trip returns only ${(m/100).toFixed(2)}% -- punitive tax or no real liquidity`):m<9e3&&(h=I.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:k.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=Bt(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!==k.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let b=Ys(h.amountOut,c);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let g=BigInt(Math.floor(Date.now()/1e3)+Number(u)),S=r&&m[0].toLowerCase()===r.toLowerCase()&&d.useNative,N=S?`0x${qt.swapExactETHForTokens}`+K(b)+K(128)+je(a)+K(g)+K(m.length)+m.map(je).join(""):`0x${qt.swapExactTokensForTokens}`+K(i)+K(b)+K(160)+je(a)+K(g)+K(m.length)+m.map(je).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:f,data:N,value:S?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:h.amountOut,minOut:b.toString(),slippageBps:c,maxSlippageBps:Ut,deadline:g.toString()},requires:S?[]:[{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 Qs=[100,500,3e3,1e4],ln={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},fe=e=>BigInt(e).toString(16).padStart(64,"0"),Be=e=>e.slice(2).toLowerCase().padStart(64,"0"),dn=/^0x[0-9a-fA-F]{40}$/,Dt=100;function Xs(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 $t(e,t){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function pn(e){let{chainId:t,wrappedNative:r}=e;async function n({quoter:s,tokenIn:i,tokenOut:a,amountIn:c,fee:u},l){let d=`0x${ln.quoteExactInputSingle}`+Be(i)+Be(a)+fe(c)+fe(u)+fe(0),p=await $(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(Qs.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=$t(c.scanner,"quoter");if(!u)return{chainId:t,evidence:k.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(!dn.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:k.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:k.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=$t(c.scanner,"quoter"),l=(e.stableQuoteAssets||[]).map(E=>String(E).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:I.UNKNOWN,evidence:k.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:I.UNKNOWN,evidence:k.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:I.UNKNOWN,evidence:k.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 E=l.find(O=>O&&O!==String(m).toLowerCase()&&O!==String(s).toLowerCase());if(E){let O=await o({quoter:u,tokenIn:E,tokenOut:s,amountIn:i},c);if(O.best){let v=await o({quoter:u,tokenIn:s,tokenOut:E,amountIn:O.best.amountOut},c);if(v.best){let x=v.best.amountOut,y=Number(x*10000n/BigInt(i)),C=I.PASS,w="round trip vs dollar book completes with expected fee/impact loss";return y<5e3?(C=I.FAIL,w=`round trip vs dollar book returns only ${(y/100).toFixed(2)}% -- punitive tax or no real liquidity`):y<9e3&&(C=I.CAUTION,w=`round trip vs dollar book returns ${(y/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:s,base:E,quoteAsset:E,verdict:C,reason:w,amountIn:String(i),bought:O.best.amountOut.toString(),returned:x.toString(),retentionBps:y,buyFee:O.best.fee,sellFee:v.best.fee,evidence:k.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:t,token:s,verdict:I.FAIL,evidence:k.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 E=l.find(O=>O&&O!==String(m).toLowerCase()&&O!==String(s).toLowerCase());if(E){let O=await o({quoter:u,tokenIn:E,tokenOut:s,amountIn:i},c),v=O.best?await o({quoter:u,tokenIn:s,tokenOut:E,amountIn:O.best.amountOut},c):{best:null};if(O.best&&v.best){let x=v.best.amountOut,y=Number(x*10000n/BigInt(i)),C=I.PASS,w="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return y<5e3?(C=I.FAIL,w=`dollar-book round trip returns only ${(y/100).toFixed(2)}%`):y<9e3&&(C=I.CAUTION,w=`dollar-book round trip returns ${(y/100).toFixed(2)}%`),{chainId:t,venue:"uniswap-v3",token:s,base:E,quoteAsset:E,verdict:C,reason:w,amountIn:String(i),bought:O.best.amountOut.toString(),returned:x.toString(),retentionBps:y,buyFee:O.best.fee,sellFee:v.best.fee,evidence:k.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:t,token:s,verdict:I.FAIL,evidence:k.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 g=b.best.amountOut,S=Number(g*10000n/BigInt(i)),N=I.PASS,T="round trip completes with expected fee/impact loss";return S<5e3?(N=I.FAIL,T=`round trip returns only ${(S/100).toFixed(2)}% -- punitive tax or no real liquidity`):S<9e3&&(N=I.CAUTION,T=`round trip returns ${(S/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:s,base:m,verdict:N,reason:T,amountIn:String(i),bought:h.best.amountOut.toString(),returned:g.toString(),retentionBps:S,buyFee:h.best.fee,sellFee:b.best.fee,evidence:k.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=$t(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(!dn.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!==k.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let m=l??f.fee,h=Xs(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(),g=`0x${ln.exactInputSingle}`+Be(s)+Be(i)+fe(m)+Be(c)+fe(a)+fe(h)+fe(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:p,data:g,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 rt={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function fn(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function mn(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 Zs(e){let{chainId:t}=e;async function r(n,o,s){return $(t,"eth_call",[{to:n,data:o},"latest"],s)}return{async blockNumber(n={}){let o=await Zr(t,n);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:k.LIVE}},async nativeBalance(n,o={}){let s=await en(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:k.LIVE}},async tokenBalance({token:n,owner:o},s={}){let i=await tn({chainId:t,token:n,owner:o},s);return{chainId:t,token:n,owner:o,raw:i?.balance??i,evidence:k.LIVE}},async resolveToken(n,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:t,token:n,evidence:k.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,rt.decimals,o).catch(()=>null),r(n,rt.symbol,o).catch(()=>null),r(n,rt.name,o).catch(()=>null),r(n,rt.totalSupply,o).catch(()=>null)]),u=fn(s?.result??s),l=u!==null||i?.result||a?.result,d={chainId:t,address:n,decimals:u===null?null:Number(u),symbol:mn(i?.result??i),name:mn(a?.result??a),totalSupply:(fn(c?.result??c)??null)?.toString()??null,evidence:l?k.LIVE:k.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:k.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await on(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=jt(n,c,{stables:e.stableQuoteAssets||[],wrappedNative:e.wrappedNative});return{chainId:t,token:n,pools:u,topPool:u[0]||null,quoteAsset:nn(n,u),evidence:u.length?k.LIVE:k.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 Kr(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 $(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:k.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:k.LIVE}},async scoreRisk(n,o={}){let s=[],i=I.PASS,a=l=>{let d={[I.PASS]:0,[I.CAUTION]:1,[I.UNKNOWN]:2,[I.FAIL]:3};d[l]>d[i]&&(i=l)},[c,u]=await Promise.all([this.resolveToken(n,o),this.resolvePools(n,o)]);if(c.evidence!==k.LIVE?(s.push({check:"erc20-metadata",result:I.UNKNOWN,detail:c.warning}),a(I.UNKNOWN)):s.push({check:"erc20-metadata",result:I.PASS,detail:`${c.symbol} / ${c.decimals}d`}),u.evidence===k.UNAVAILABLE)s.push({check:"liquidity",result:I.UNKNOWN,detail:u.reason}),a(I.UNKNOWN);else if(!u.pools.length)s.push({check:"liquidity",result:I.FAIL,detail:"no pool with liquidity found"}),a(I.FAIL);else{let l=u.pools[0],d=l.liquidityUsd??0;d<5e3?(s.push({check:"liquidity",result:I.CAUTION,detail:`top pool only $${d}`}),a(I.CAUTION)):s.push({check:"liquidity",result:I.PASS,detail:`$${d} on ${l.dex}`}),l.createdAt&&Date.now()-l.createdAt<24*3600*1e3&&(s.push({check:"age",result:I.CAUTION,detail:"pool under 24h old"}),a(I.CAUTION))}if(typeof this.sellSimulation=="function"){let l=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},o).catch(d=>({verdict:I.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:I.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(I.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 hn(e){let r={...Zs(e)},n=new Set((e.venues||[]).map(s=>s.kind));e.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,pn({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,un({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 ei=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 bn(){return ei.map(e=>an(hn(e)))}import{AbiCoder as ti,Interface as Sn,getAddress as he,isAddress as En,keccak256 as ri}from"ethers";var Ft="0x0000000000000000000000000000000000000000",ni="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",oi=ti.defaultAbiCoder(),yn=new Sn(["function quoteExactInputSingle((address tokenIn,address tokenOut,uint256 amountIn,uint24 fee,uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut,uint160 sqrtPriceX96After,uint32 initializedTicksCrossed,uint256 gasEstimate)"]),wn=new Sn(["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)"]),W=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"})}),Ue=Object.freeze({1:Object.freeze({quoter:"0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203",wrappedNative:W[1].wrappedNative}),10:Object.freeze({quoter:"0x1f3131a13296fb91c90870043742c3cdbff1a8d7",wrappedNative:W[10].wrappedNative}),56:Object.freeze({quoter:"0x9f75dd27d6664c475b90e105573e550ff69437b0",wrappedNative:W[56].wrappedNative}),137:Object.freeze({quoter:"0xb3d5c3dfc3a7aebff71895a7191796bffc2c81b9",wrappedNative:W[137].wrappedNative}),8453:Object.freeze({quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",wrappedNative:W[8453].wrappedNative}),42161:Object.freeze({quoter:"0x3972c00f7ed4885e145823eb7c655375d275a1c5",wrappedNative:W[42161].wrappedNative}),43114:Object.freeze({quoter:"0xbe40675bb704506a3c2ccfb762dcfd1e979845c2",wrappedNative:W[43114].wrappedNative}),4663:Object.freeze({quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",wrappedNative:W[4663].wrappedNative})}),si=Object.freeze([100,500,3e3,1e4]);function me(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 vn(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 On(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 Mt(e){let t=String(e??"").trim().toLowerCase();return t===""||t==="eth"||t===Ft||t===ni}function qe(e,t){if(!En(String(e??"")))throw new Error(`${t} must be an EVM address`);return he(String(e))}function gn(e,t,r){return Mt(e)?he(t.wrappedNative):qe(e,r)}function An(e,t){return Mt(e)?he(Ft):qe(e,t)}function In(e,t){let r=Number(e);if(!Number.isInteger(r)||r<0||r>16777215)throw new Error(`${t} must be uint24`);return r}function ii(e,t){let r=Number(e);if(!Number.isInteger(r)||r<-8388608||r>8388607)throw new Error(`${t} must be int24`);return r}function ai({tokenIn:e,tokenOut:t,poolKey:r,poolId:n}){me(r,new Set(["currency0","currency1","fee","tickSpacing","hooks"]),"V4 PoolKey");let o=qe(r.currency0,"V4 currency0"),s=qe(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:In(r.fee,"V4 fee"),tickSpacing:ii(r.tickSpacing,"V4 tickSpacing"),hooks:qe(r.hooks??Ft,"V4 hooks")}),a=An(e,"tokenIn"),c=An(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=ri(oi.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 Ht(e,t){if(Mt(t))return!0;if(!En(String(t??"")))return!1;let r=W[Number(e)]?.wrappedNative||Ue[Number(e)]?.wrappedNative;return!!(r&&he(String(t)).toLowerCase()===he(r).toLowerCase())}async function xn(e={},t={},r={}){me(e,new Set(["chainId","tokenIn","tokenOut","amountIn","fee"]),"V3 read"),me(t,new Set(["timeoutMs"]),"V3 read options"),me(r,new Set(["rpc"]),"V3 read dependencies");let n=Number(e.chainId),o=W[n];if(!o)throw new Error(`V3 read unavailable on chain ${e.chainId}`);let s=gn(e.tokenIn,o,"tokenIn"),i=gn(e.tokenOut,o,"tokenOut");if(s.toLowerCase()===i.toLowerCase())throw new Error("tokenIn and tokenOut must differ");let a=vn(e.amountIn,"amountIn"),c=e.fee==null?si:[In(e.fee,"V3 fee")],u=r.rpc||$,l=On(t.timeoutMs),d=await Promise.all(c.map(async f=>{let m=yn.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=yn.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:he(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 Nn(e={},t={},r={}){me(e,new Set(["chainId","tokenIn","tokenOut","amountIn","poolKey","poolId"]),"V4 read"),me(t,new Set(["timeoutMs"]),"V4 read options"),me(r,new Set(["rpc"]),"V4 read dependencies");let n=Number(e.chainId),o=Ue[n];if(!o)throw new Error(`V4 read unavailable on chain ${e.chainId}`);let s=vn(e.amountIn,"amountIn");if(s>0xffffffffffffffffffffffffffffffffn)throw new Error("amountIn exceeds uint128");let i=ai(e),a=wn.encodeFunctionData("quoteExactInputSingle",[{poolKey:i.poolKey,zeroForOne:i.zeroForOne,exactAmount:s,hookData:"0x"}]),u=await(r.rpc||$)(n,"eth_call",[{to:o.quoter,data:a},"latest"],On(t.timeoutMs));if(!u||u==="0x")throw new Error("V4 read returned an empty result");let l=wn.decodeFunctionResult("quoteExactInputSingle",u);return Object.freeze({venue:"uniswap-v4",chainId:n,quoter:he(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 ci=new Set(["chainId","tokenIn","tokenOut","amountIn","v4PoolKey","v4PoolId"]),ui=new Set(["maxImpactPct","timeoutMs"]),li=new Set(["quoteV3","quoteV4","gasPrice"]);function Vt(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 Kt(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 kn(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 re(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 di(e){if(e<=1n)return null;let t=e/1000n;return t>0n&&t<e?t:1n}function pi({amountIn:e,amountOut:t,probeIn:r,probeOut:n}){let o=re(e),s=re(t),i=re(r),a=re(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 zt(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 fi({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,amountOut:o,gasEstimate:s,gasPrice:i}){let a=re(s),c=re(i),u=re(n),l=re(o);if(!a||!c||!u||!l||a<=0n||c<=0n)return null;let d=a*c;return Ht(e,r)?d:Ht(e,t)?d*l/u:null}async function mi(e,t){let r=await $(e,"eth_gasPrice",[],{timeoutMs:t});return re(r)}function hi(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 zt(n,r,e),i=Kt(s?.amountOut,`${e} amountOut`),a=di(t);if(a==null)return{source:e,full:s,impactPct:null};try{let c=await zt(()=>o(a.toString(),s),r,`${e} impact probe`),u=pi({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 bi({inspected:e,params:t,gasPrice:r}){let n=e.full,o=Kt(n.amountOut,`${e.source} amountOut`),s=fi({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 yi({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 Wt(e={},t={},r={}){Vt(e,ci,"route params"),Vt(t,ui,"route options"),Vt(r,li,"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=Kt(e.amountIn,"amountIn"),s=kn(t.timeoutMs,12e3,250,6e4,"timeoutMs"),i=kn(t.maxImpactPct,25,0,100,"maxImpactPct"),a=r.quoteV3||xn,c=r.quoteV4||Nn,u=r.gasPrice||mi,l=[];W[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:(A,L)=>a({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:A,fee:L.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&&Ue[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:A=>c({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:A,poolKey:e.v4PoolKey,poolId:e.v4PoolId},{timeoutMs:s})})),!l.length)throw new Error(`no verified read-only quote source on chain ${n}`);let f=zt(()=>u(n,s),s,"gas price read").catch(()=>null),m=await Promise.all(l),h=await f,b=m.filter(A=>A.error).map(A=>hi(A.source,A.error)),g=m.filter(A=>A.full),S=g.filter(A=>A.impactPct!=null&&A.impactPct>i).map(A=>({source:A.source,impactPct:Number(A.impactPct.toFixed(2)),reason:`price impact ${A.impactPct.toFixed(2)}% exceeds ${i}% ceiling`})),N=new Set(S.map(A=>A.source)),T=g.filter(A=>!N.has(A.source)),E=T.map(A=>bi({inspected:A,params:{...e,chainId:n},gasPrice:h})),O=E.length>0&&E.every(A=>A.costAccounted),v=O?"net":"gross";for(let A of E){let L=BigInt(A.grossOut),ne=O?BigInt(A.costInDest):0n;A.netOut=(L>ne?L-ne:0n).toString()}E.sort((A,L)=>{let ne=BigInt(O?A.netOut:A.grossOut),V=BigInt(O?L.netOut:L.grossOut);return ne===V?A.source.localeCompare(L.source):V>ne?1:-1});let x=[];O?x.push("Gas is estimated from quoter gas units and the current read-only gas price; actual gas may differ."):x.push("Gas was not accounted for; routes are ranked on gross output.");let y=T.filter(A=>A.impactPct==null).map(A=>A.source);y.length&&x.push(`Price impact is UNKNOWN for: ${y.join(", ")}.`),S.length&&x.push(`Dropped on price impact: ${S.map(A=>A.source).join(", ")}.`),!d&&Ue[n]&&x.push("V4 was not queried because no exact verified PoolKey identity was discovered.");let C=null,w=null;if(E.length>1){let A=BigInt(O?E[0].netOut:E[0].grossOut),L=BigInt(O?E[1].netOut:E[1].grossOut);L>0n&&(C=Number((A-L)*10000000n/L)/1e3,w=`${E[0].source} vs ${E[1].source}`)}let M=Object.fromEntries(T.filter(A=>A.impactPct!=null).map(A=>[A.source,Number(A.impactPct.toFixed(4))]));return Object.freeze({kind:"swap",chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:o.toString(),best:E[0]||null,routes:Object.freeze(E.map(A=>Object.freeze(A))),failed:Object.freeze(b),rankedOn:v,sourcesTried:l.length,sourcesAnswered:g.length,improvementBps:C,spreadBasis:w,priceImpact:Object.freeze(M),impactRejected:Object.freeze(S),impactUnmeasured:Object.freeze(y),warnings:Object.freeze(x),note:yi({routes:E,rankedOn:v,improvementBps:C})})}var be="So11111111111111111111111111111111111111112",ct=101,Cu=100,Wi=new Set(["chainId","tokenIn","tokenOut","amountIn"]),Gi=new Set(["maxImpactPct","timeoutMs","quoteFn"]);function Jn(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 Yn(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 Qn(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 Ji(e,t={}){let{jupiterQuote:r}=await Promise.resolve().then(()=>(nr(),rr)),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 sr(e={},t={}){if(Jn(e,Wi,"params"),Jn(t,Gi,"options"),e.chainId!=null&&Number(e.chainId)!==101)throw new Error("solana quote adapter only handles chainId 101");let r=Qn(e.tokenIn,"tokenIn"),n=Qn(e.tokenOut,"tokenOut"),o=Yn(e.amountIn,"amountIn");if(r===n)throw new Error("solana quote tokenIn and tokenOut must differ");let s=t.quoteFn||Ji;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=Yn(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 Xn({routeFn:e=sr}={}){return Object.freeze({async sellSimulation({token:t,amountIn:r,base:n}={}){let{simulateSell:o,SELL_SIM:s}=await Promise.resolve().then(()=>(Gn(),Wn)),i=await o({token:t,base:n||be,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 la(e){return e?.token?.address||e?.tokenAddress||null}function da(e){return e?.quoteAsset||e?.pool?.quoteAsset||null}function pa(e,t){return e?.quoteAmountIn||e?.quote?.amountIn||null}async function ir({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=la(e),o=da(e),s=pa(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(()=>(nr(),rr)),u=await c({userPublicKey:t.recipient,inputMint:o==="unknown"?be: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 ar({prepared:e}={},t=process.env){if(e?.prepared!==!0)return{ok:!1,error:"nothing prepared"};let{armPreparedAction:r}=await Promise.resolve().then(()=>(oo(),no)),n=e.localSignerEnvelope||e.envelope;return n?r({localSignerEnvelope:n},t):{ok:!1,error:"prepared envelope missing"}}import{createHash as Aa}from"node:crypto";import{createHash as fa}from"node:crypto";var U=Object.freeze({SHADOW:"shadow",ARMED:"armed",AUTONOMOUS:"autonomous"}),ma=3,ha=new Set(Object.values(U));function dr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))dr(t);Object.freeze(e)}return e}function lr(e){return Array.isArray(e)?`[${e.map(lr).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${lr(e[t])}`).join(",")}}`:JSON.stringify(e)}function ba(e){return`sha256:${fa("sha256").update(lr(e)).digest("hex")}`}function cr(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 ya(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new TypeError(`${t} entries must be positive safe integers`);return e}function ur(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 xe(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 Fe(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 pt(e,t){let r=xe(e,t),[n,o=""]=r.split(".");return{digits:BigInt(n+o),scale:o.length}}function dt(e,t,r="value"){let n=pt(e,r),o=pt(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 so(e){let t=structuredClone(e);return delete t.digest,t}function wa(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");return ba(so(e))}function Me(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");let t=e.mode??U.SHADOW;if(!ha.has(t))throw new TypeError("mode must be shadow, armed, or autonomous");let r={version:1,mode:t,chains:cr(e.chains,"chains",ya),venues:cr(e.venues,"venues",ur),quoteAssets:cr(e.quoteAssets,"quoteAssets",ur),maxSpendPerTrade:xe(e.maxSpendPerTrade,"maxSpendPerTrade",{positive:!0}),maxSpendPerDay:xe(e.maxSpendPerDay,"maxSpendPerDay",{positive:!0}),minLiquidityUsd:xe(e.minLiquidityUsd,"minLiquidityUsd",{positive:!0}),maxSlippageBps:Fe(e.maxSlippageBps,"maxSlippageBps",{max:1e4}),maxGas:xe(e.maxGas,"maxGas",{positive:!0}),maxPriorityFee:xe(e.maxPriorityFee,"maxPriorityFee"),maxBuysPerHour:Fe(e.maxBuysPerHour,"maxBuysPerHour",{min:1}),retryCeiling:Fe(e.retryCeiling,"retryCeiling",{max:ma}),ttlMs:Fe(e.ttlMs,"ttlMs",{min:1}),requireSellSimulation:e.requireSellSimulation,requireRiskPass:e.requireRiskPass??!0,maxRoundTripLossBps:Fe(e.maxRoundTripLossBps??1500,"maxRoundTripLossBps",{max:1e4}),killSwitch:e.killSwitch,recipient:e.recipient==null||e.recipient===""?null:ur(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(dt(r.maxSpendPerTrade,r.maxSpendPerDay)>0)throw new TypeError("maxSpendPerTrade cannot exceed maxSpendPerDay");return r.digest=wa(r),dr(r)}var ga=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 j(e,t,r){t&&e.push(r)}function He(e,t={},r={}){let n=Me(so(e)),o=[];j(o,n.killSwitch,"kill switch is engaged"),j(o,!n.chains.includes(t.chain),"chain is not on the exact allowlist"),j(o,!n.venues.includes(t.venue),"venue is not on the exact allowlist"),j(o,!n.quoteAssets.includes(t.quoteAsset),"quote asset is not on the exact allowlist");let s=(a,c,u)=>{try{j(o,dt(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=pt(t.spentToday,"daily spend"),c=pt(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)}`;j(o,dt(d,n.maxSpendPerDay,"daily spend")>0,"daily spend cap would be exceeded")}catch{o.push("daily spend evidence is missing or unknown")}try{j(o,dt(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"),j(o,!Number.isSafeInteger(t.buysLastHour),"buys per hour evidence is missing or unknown"),j(o,Number.isSafeInteger(t.buysLastHour)&&t.buysLastHour>=n.maxBuysPerHour,"buys per hour cap is reached"),j(o,!Number.isSafeInteger(t.retries)||t.retries<0,"retry evidence is missing or unknown"),j(o,Number.isSafeInteger(t.retries)&&t.retries>n.retryCeiling,"retry ceiling is exceeded"),j(o,!Number.isFinite(t.ageMs)||t.ageMs<0,"TTL evidence is missing or unknown"),j(o,Number.isFinite(t.ageMs)&&t.ageMs>=n.ttlMs,"TTL has expired"),j(o,t.sellSimulation?.verdict!=="PASS"||t.sellSimulation?.evidence!=="LIVE","mandatory sell simulation has no LIVE PASS evidence"),j(o,typeof t.fireId!="string"||t.fireId.length===0,"fire id evidence is missing or unknown"),j(o,!Array.isArray(t.firedIds),"duplicate-fire history is missing or unknown"),j(o,Array.isArray(t.firedIds)&&t.firedIds.includes(t.fireId),"duplicate fire is blocked");let i=[...o];j(i,r?.ORACLE_AUTONOMOUS_TRADING!=="1","ORACLE_AUTONOMOUS_TRADING=1 is required literally");for(let[a,c]of ga)j(i,t.autonomousGates?.[a]!==!0,c);return j(i,n.mode!==U.AUTONOMOUS,"strategy mode is not autonomous"),dr({strategyDigest:n.digest,mode:n.mode,policyEligible:o.length===0,blockers:o,autonomousEligible:i.length===0,autonomousBlockers:i,reportOnly:!0})}var Vu=Me,zu=Me,Ku=He;function pr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))pr(t);Object.freeze(e)}return e}var io=Object.freeze({ALERT_ONLY:"alert_only",EXECUTE:"execute"}),ao=Object.freeze({liveQuote:20,sellSimulation:30,contractRisk:20,liquidity:15,roundTripLoss:15});function z(e,t){return{id:e,verdict:"PASS",detail:t}}function H(e,t){return{id:e,verdict:"BLOCK",detail:t}}function co(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function uo({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?H("killSwitch","engaged"):z("killSwitch","off"),"kill switch is engaged"),s(e.chains.includes(t.chain)?z("chain",String(t.chain)):H("chain",String(t.chain??"missing")),"chain is not on the exact allowlist"),s(e.venues.includes(t.venue)?z("venue",String(t.venue)):H("venue",String(t.venue??"missing")),"venue is not on the exact allowlist"),s(e.quoteAssets.includes(t.quoteAsset)?z("quoteAsset",String(t.quoteAsset)):H("quoteAsset",String(t.quoteAsset??"missing")),"quote asset is not on the exact allowlist");let i=r.quote?.evidence||t.quoteEvidence;s(i==="LIVE"?z("liveQuote","LIVE"):H("liveQuote",String(i||"missing")),"live quote is missing");let a=t.sellSimulation||r.sellSimulation;s(a?.verdict==="PASS"&&a?.evidence==="LIVE"?z("sellSimulation","LIVE PASS"):H("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"?z("contractRisk","PASS"):H("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?z("liquidity",String(u)):H("liquidity",String(u??"missing")),"minimum real liquidity is not met")}catch{s(H("liquidity","unknown"),"liquidity evidence is missing or unknown")}let l=co(t.slippageBps);s(l!=null&&l<=e.maxSlippageBps?z("slippage",String(l)):H("slippage",String(t.slippageBps??"missing")),"slippage exceeds cap or is unknown");let d=co(t.roundTripLossBps);s(d!=null&&d<=e.maxRoundTripLossBps?z("roundTripLoss",String(d)):H("roundTripLoss",String(t.roundTripLossBps??"missing")),"round-trip loss exceeds cap or is unknown"),s(Number.isSafeInteger(t.retries)&&t.retries<=e.retryCeiling?z("retryCeiling",String(t.retries)):H("retryCeiling",String(t.retries??"missing")),"retry ceiling is exceeded or unknown"),s(Number.isFinite(t.ageMs)&&t.ageMs>=0&&t.ageMs<e.ttlMs?z("ttl",String(t.ageMs)):H("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)?z("duplicateFire",t.fireId):H("duplicateFire","missing or duplicate"),"duplicate fire is blocked or fire id is unknown");let p=0;for(let h of n)h.verdict==="PASS"&&ao[h.id]&&(p+=ao[h.id]);let f=o.length===0,m=e.mode==="shadow"?io.ALERT_ONLY:io.EXECUTE;return pr({snipeReady:f,wouldSnipe:f,armed:!1,actionMode:m,score:p,features:n,blockers:o,reportOnly:e.mode==="shadow"})}function Gu(e=[]){if(!Array.isArray(e))throw new TypeError("snipe candidates must be an array");return pr([...e].sort((t,r)=>{let n=+!!r?.snipe?.snipeReady-+!!t?.snipe?.snipeReady;return n!==0?n:(r?.snipe?.score||0)-(t?.snipe?.score||0)}))}function ft(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fr(e){return Array.isArray(e)?`[${e.map(fr).join(",")}]`:ft(e)?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${fr(e[t])}`).join(",")}}`:JSON.stringify(e)}function Sa(e){return`cycle:${Aa("sha256").update(fr(e)).digest("hex")}`}function Ve(e,t){if(typeof e!="function")throw new TypeError(`launch-radar runner: injected ${t} function is required`)}function lo(e){return e instanceof Error?e.message:String(e)}function ze(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(!ft(r))throw new TypeError("launch-radar runner: strategy is required");Ve(n,"discovery"),Ve(o,"evaluate");let s=e.now??(()=>new Date().toISOString()),i=e.sleep??(()=>Promise.resolve()),a=e.jitter??(()=>0);Ve(s,"clock"),Ve(i,"sleep"),Ve(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(g){if(h=g,b===c)break;let S=Number(a()),N=Number.isFinite(S)?Math.max(0,S):0,T=Math.min(l,u*2**b+N);await i(T)}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=jr(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(E=>n({cursor:structuredClone(m.cursor),attempt:E,mode:r.mode}))}catch(E){return{mode:r.mode,status:"failed",blockers:[lo(E)],results:[],actionMode:h}}if(!ft(b)||!Array.isArray(b.candidates)||!(b.cursor===null||ft(b.cursor)))return{mode:r.mode,status:"failed",blockers:["discovery returned an invalid deterministic result"],results:[],actionMode:h};let g=[];for(let E of b.candidates)try{let O=await d(w=>o(structuredClone(E),{attempt:w,mode:r.mode})),v=He(r,O,{}),x=uo({strategy:r,observation:O,evaluation:E}),y={prepared:!1},C=!1;Qe(r,v)&&typeof e.prepareFn=="function"?y=await e.prepareFn({candidate:E,observation:O,strategy:r,policy:v})||{prepared:!1}:Qe(r,v)&&(y={prepared:!1,blockedReasons:["prepareFn is required when strategy mode is not shadow"]}),Br(r,v,y)&&typeof e.queueFn=="function"&&(C=(await e.queueFn({prepared:y,candidate:E,observation:O,strategy:r,policy:v}))?.ok===!0),g.push({id:E?.id??null,policy:v,snipe:x,prepared:y.prepared===!0,queued:C,actionMode:h})}catch(O){g.push({id:E?.id??null,policy:{mode:r.mode,policyEligible:!1,reportOnly:r.mode===U.SHADOW,blockers:[`evaluation failed: ${lo(O)}`]},actionMode:h,prepared:!1,queued:!1})}let S={cursor:b.cursor,candidates:b.candidates,results:g},N={id:Sa(S),type:r.mode===U.SHADOW?"shadow-cycle":"execute-cycle",at:s(),data:S},T=t.commitCycle({candidates:b.candidates,cursor:b.cursor,strategyStatus:{mode:r.mode,status:"inert",ambiguous:!1},event:N});return{mode:r.mode,status:T.duplicate?"duplicate":"completed",results:g,evidenceId:T.evidence.id,actionMode:h}}return Object.freeze({status:p,runCycle:f})}var el=ze,tl=async e=>ze(e).runCycle();function po(e){return[...new Set(e.filter(Boolean).map(String))]}function ye(e){return Array.isArray(e)?e.map(ye):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,ye(r)])):e}function se(e,t,r="UNKNOWN"){return!e||typeof e!="object"?{evidence:r,observedAt:t}:ye({...structuredClone(e),evidence:e.evidence||r,observedAt:e.observedAt||t})}function Ea(e,t){let r=String(t||"").toLowerCase();return!!(r&&[e?.address,e?.pair,e?.poolId].some(n=>String(n||"").toLowerCase()===r))}function va(e,t){let r=e.poolId||e.poolAddress||null,n=[t.topPool,...t.pools?.pools||[]].filter(Boolean),o=r?n.find(i=>Ea(i,r)):t.topPool,s={address:e.poolAddress??null,poolId:e.poolId,poolKey:e.poolKey,quoteAsset:e.quoteAsset};return ye({...o||{},...s})}function Oa(e,t,r,n){let o=e.observedAt||n,s=va(e,t),i=se(t.scannerRisk||t.risk,o),a=se(t.sellability,o,"UNAVAILABLE"),c=se(t.quote,o,"UNAVAILABLE"),u=c.evidence==="LIVE"?"PASS":"UNKNOWN";return ye({chain:{id:e.chainId,...t.chain||{}},token:se({address:e.tokenAddress,...t.token||{}},o,"LIVE"),pool:se(s,o,"LIVE"),venue:se({...e.venue,supported:e.venue?.supported===!0,verified:e.venue?.verified===!0},o,"LIVE"),signal:se({kind:e.kind,source:"verified-factory",unsolicitedAirdrop:!1},o,"LIVE"),risk:i,sellability:a,sellSimulation:se(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:ye({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:po([...r||[],...t.blockedReasons||[],t.error]),latency:{discoveredAt:o,riskCompletedAt:i.observedAt,sellabilityCompletedAt:a.observedAt,routeCompletedAt:c.observedAt,normalizedAt:n}})}async function Ne(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:ye(structuredClone(a)),prepare:e.prepare===!0})}catch(u){c={error:`evaluation unavailable: ${String(u?.message||u).slice(0,300)}`}}i.push(Oa(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(po(n?.whyBlocked||[])),candidates:xr(i)})}var ol=Ne;var Ia=101,fo=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/,mo="181ec828051c0777",ho="6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P";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 xa(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!==ho)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 Na(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(mo))continue;let c=Array.isArray(i.accounts)?i.accounts:[],u=c[0],l=c[2];return!fo.test(u||"")||!fo.test(l||"")?null:{id:`solana:${r}:${s}`,chain:"solana",chainId:Ia,factoryId:t.id||null,factoryAddress:t.programId,tokenAddress:u,quoteAsset:be,poolAddress:l,venue:structuredClone(t.venue),kind:"token-launched",slot:n,signature:r,instructionIndex:s,evidence:"LIVE"}}return null}async function bo(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=xa(u);l?n.push({id:u?.id||null,status:"UNAVAILABLE",reason:l}):o.push(u)}let s=ke({until:e.cursor?.until||null});if(o.length===0)return ke({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 ke({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 ke({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=Na({...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 ke({status:"LIVE",discoveries:[...c.values()],unavailable:n,cursor:{until:a},whyBlocked:n.map(u=>u.reason)})}var al=ho,cl=mo;Yt();var ka="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function Ca(e){let t=String(e||"");if(!t)return Buffer.alloc(0);let r=[0];for(let o of t){let s=ka.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 Ta(e){return typeof e=="string"?e:e?.pubkey||null}function La(e){let t=e?.transaction?.message||{},r=Array.isArray(t.accountKeys)?t.accountKeys.map(Ta):[],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=Ca(i.data).toString("hex")),a&&s.push({programId:a,accounts:c,dataHex:u})}return s}function yo(e={}){let t=e.solanaRpc||Ln;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:La(n)}:{signature:r,slot:null,instructions:[]}}}}import F from"node:fs";import mt from"node:path";var bt=1,Ra=0;function ge(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function D(e){return structuredClone(e)}function hr(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)=>hr(r,`${t}[${n}]`));if(ge(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}`);hr(n,`${t}.${r}`)}return}throw new Error(`launch-radar store: non-JSON value at ${t}`)}}function we(e){return Array.isArray(e)?`[${e.map(we).join(",")}]`:ge(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${we(e[t])}`).join(",")}}`:JSON.stringify(e)}function Pa(){return{version:bt,candidates:[],cursor:null,strategyStatus:{mode:"shadow",status:"inert",ambiguous:!1},evidence:[]}}function _a(e){if(!ge(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 Ke(e){if(!ge(e)||e.version!==bt)throw new Error("launch-radar store: corrupt or unsupported version");if(!Array.isArray(e.candidates)||!(e.cursor===null||ge(e.cursor))||!Array.isArray(e.evidence))throw new Error("launch-radar store: corrupt state shape");_a(e.strategyStatus),hr(e);try{Je(e.evidence)}catch(t){throw new Error(`launch-radar store: corrupt evidence: ${t.message}`)}return D(e)}function ht(e,t=!1){let r;try{r=F.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 br(e){ht(e);let t;try{t=JSON.parse(F.readFileSync(e,"utf8"))}catch{throw new Error("launch-radar store: corrupt JSON")}return Ke(t)}function mr(e,t){let r=Ke(t),n=mt.dirname(e);F.mkdirSync(n,{recursive:!0,mode:448});let o=F.lstatSync(n);if(o.isSymbolicLink()||!o.isDirectory())throw new Error("launch-radar store: parent must be a regular directory, not a symlink");ht(e,!0)&&ht(e);let s=mt.join(n,`.launch-radar.${process.pid}.${Ra+=1}.tmp`),i;try{i=F.openSync(s,"wx",384),F.writeFileSync(i,`${we(r)}
|
|
7
|
-
`,"utf8"),F.fsyncSync(i),F.closeSync(i),i=void 0,F.renameSync(s,e),F.chmodSync(e,384);let a=F.openSync(n,"r");try{F.fsyncSync(a)}finally{F.closeSync(a)}}catch(a){i!==void 0&&F.closeSync(i);try{F.unlinkSync(s)}catch{}throw a}}function yt(e={}){let t=e.path;if(typeof t!="string"||!mt.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");ht(t,!0)?br(t):mr(t,Pa());let r=()=>br(t),n=(o,{reconciliation:s=!1}={})=>{if(r().strategyStatus.ambiguous&&!s)throw new Error("launch-radar store: ambiguous state is terminal until reconciliation");return mr(t,o),D(o)};return Object.freeze({path:t,read:r,replaceState(o={}){if(!ge(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]=D(o[a]));return n(Ke(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&&we(i.data)===we(o?.data))return D(i);throw new Error(`launch-radar store: duplicate evidence conflict: ${o?.id}`)}let a=Ye(s.evidence,o),c=a.at(-1);return n({...s,evidence:D(a)}),D(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&&we(u.data)===we(a?.data))return{duplicate:!0,evidence:D(u),state:c};throw new Error(`launch-radar store: duplicate evidence conflict: ${a?.id}`)}let l=Ye(c.evidence,a),d=Ke({...c,candidates:D(o),cursor:D(s),strategyStatus:D(i),evidence:D(l)});return n(d),{duplicate:!1,evidence:D(l.at(-1)),state:D(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 mr(t,{...s,strategyStatus:i}),D(i)},reconcile(o={}){if(!ge(o))throw new TypeError("launch-radar store: reconciliation state must be an object");let s=r(),i=Ke({...s,...D(o),version:bt,evidence:s.evidence});if(i.strategyStatus.ambiguous)throw new Error("launch-radar store: reconciliation must clear ambiguous state");return n(i,{reconciliation:!0})}})}function wo(e={}){let t=e.path;if(typeof t!="string"||!mt.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");return br(t)}var hl=yt,bl=bt;function wr(e){return e.ORACLE_CONFIG_DIR||ie.join(ja.homedir(),".config","oracle")}function go(e,t){if(!e||!ie.isAbsolute(e))throw new Error(`${t} path must be absolute`);let r=wt.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(wt.readFileSync(e,"utf8"))}function Ba(e){return e==null?null:String(e)}function Ce(e){if(e!==void 0)return typeof e=="bigint"?e.toString():Array.isArray(e)?e.map(Ce).filter(t=>t!==void 0):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,Ce(r)])):e}function Oo(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 yr(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 qa(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 Ua(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:Oo(t.amountIn,"routeProbe.amountIn"),quoteAssetDecimals:yr(t.quoteAssetDecimals,0,255,"routeProbe.quoteAssetDecimals"),slippageBps:yr(t.slippageBps??100,0,1e4,"routeProbe.slippageBps"),maxImpactPct:qa(t.maxImpactPct??25,0,100,"routeProbe.maxImpactPct"),timeoutMs:yr(t.timeoutMs??12e3,250,6e4,"routeProbe.timeoutMs")})}function Ao(e){return[e?.source,e?.amountOut,e?.netOut,e?.meta?.poolId].map(t=>String(t??"").toLowerCase()).join(":")}function So(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 $a(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 Eo(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 vo(e){if(!e?.best||!Oo(e.best.amountOut,"best route amountOut"))throw new Error("best route returned no positive output");let t=Array.isArray(e.routes)?e.routes:[],r=Ao(e.best),n=t.findIndex(a=>Ao(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."),Ce({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 Da(e,t){return{quote:{evidence:"UNAVAILABLE",reason:e,observedAt:t},sellability:{verdict:"UNKNOWN",evidence:"UNAVAILABLE",reason:e,observedAt:t}}}async function Io({scanner:e,discovery:t,descriptor:r,routeFn:n=Wt,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=Ua(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:Ce(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);Eo(d,t,"buy");let p=vo(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);Eo(f,t,"reverse");let m=vo(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=$a(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=Ce({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,Da(c,o))}return Ce(s)}function xo(e){let t=e.quoteAsset||e.pool?.quoteAsset||e.token?.quoteAsset||"unknown",r=So(e.quoteAmountIn,e.quoteAssetDecimals??18)||So(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:Ba(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 Fa(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=go(t.ORACLE_LAUNCH_RADAR_STRATEGY_FILE,"strategy file"),n=go(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=Me(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 Ma({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");bn();let a=cn(i[0]);if(!a)throw new Error(`no scanner registered for chain ${i[0]}`);let c=t.ORACLE_LAUNCH_RADAR_STORE_PATH||ie.join(wr(t),"launch-radar",`state-${i[0]}.json`),u=yt({path:c});return ze({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 Ne({discover:()=>Et({scanner:a,factories:o,fromBlock:h,toBlock:m,cursor:p}),evaluator:async({discovery:g})=>{let S=o.find(N=>N?.id===g?.factoryId||String(N?.factoryAddress||"").toLowerCase()===String(g?.factoryAddress||"").toLowerCase());return Io({scanner:a,discovery:g,descriptor:S,routeFn:e.routeFn||Wt,observedAt:new Date().toISOString()})},observedAt:new Date().toISOString()});return{candidates:b.candidates,cursor:b.cursor}},evaluate:async p=>xo(p),prepareFn:e.prepareFn||(p=>ir({...p,scanner:a})),queueFn:e.queueFn||(p=>ar(p,t))})}function Ma({env:e,factories:t,strategy:r,options:n}){let o=n.solanaScanner||yo(),s=n.solanaRouteFn||sr,i=n.solanaQuoteScanner||Xn({routeFn:s}),a=e.ORACLE_LAUNCH_RADAR_STORE_PATH||ie.join(wr(e),"launch-radar","state-solana.json"),c=yt({path:a});return ze({store:c,strategy:r,discover:async({cursor:l})=>{let d=await Ne({discover:()=>bo({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 Io({scanner:i,discovery:{...p,quoteAsset:p.quoteAsset||be},descriptor:f,routeFn:s,observedAt:new Date().toISOString()})},observedAt:new Date().toISOString()});return{candidates:d.candidates,cursor:d.cursor}},evaluate:async l=>xo(l),prepareFn:n.prepareFn||(l=>ir({...l,scanner:i})),queueFn:n.queueFn||(l=>ar(l,e))})}async function Pl(e={}){let t=e.env||process.env,r=t.ORACLE_LAUNCH_RADAR_FACTORIES_DIR;if(!r||!ie.isAbsolute(r))throw new Error("ORACLE_LAUNCH_RADAR_FACTORIES_DIR must be an absolute directory");let n=wt.lstatSync(r);if(n.isSymbolicLink()||!n.isDirectory())throw new Error("factories dir must be a regular directory");let o=wt.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:ie.join(r,i),ORACLE_LAUNCH_RADAR_STORE_PATH:ie.join(t.ORACLE_LAUNCH_RADAR_STORE_DIR||ie.join(wr(t),"launch-radar"),`state-${a}.json`)},u=await Fa({...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 ko=3,jl=2e3,Bl=4,ql=3,Ul=6e4,$l=.5,Te=Object.freeze({OK:"ok",DEGRADED:"degraded",UNKNOWN:"unknown"}),No=Object.freeze({fresh:0,stale:1,down:2});function Ha(e,t,r=.5){return Number.isFinite(t)?e==null||!Number.isFinite(e)?t:r*t+(1-r)*e:e??null}function Va(e,t=Math.random){let r=Math.min(1e3,50*2**Math.max(0,e-1)),n=t()*r*.5;return Math.round(r+n)}function za(e){if(!e||typeof e!="object")return{ok:!1,reason:"malformed probe response: not an object"};let{blockNumber:t,chainId:r,timestampMs:n}=e;return!Number.isInteger(t)||t<0?{ok:!1,reason:"malformed probe response: blockNumber must be a non-negative integer"}:r!=null&&(!Number.isFinite(r)||r<=0)?{ok:!1,reason:"malformed probe response: chainId must be a positive number"}:n!=null&&(!Number.isFinite(n)||n<0)?{ok:!1,reason:"malformed probe response: timestampMs must be a non-negative number"}:{ok:!0}}function Ka(e,t,r){let n=r(t).then(()=>{throw new Error(`rpc-health: probe timeout after ${t}ms`)});return n.catch(()=>{}),Promise.race([e,n])}async function Wa(e,t){let{probe:r,clock:n,sleep:o,rng:s,timeoutMs:i,maxRetries:a,backoff:c,latencyAlpha:u,previousLatencyEwmaMs:l,previousErrorRate:d,previousSamples:p}=t,f=1+a,m=0,h=0,b=l??null,g=null,S=null;for(let O=1;O<=f;O++){m=O;let v=n.now();try{let x=await Ka(r(e,{attempt:O,timeoutMs:i}),i,o),y=n.now()-v,C=za(x);if(!C.ok)h+=1,g=C.reason;else{b=Ha(b,y,u),S={blockNumber:x.blockNumber,chainId:x.chainId??null,timestampMs:x.timestampMs??null,latencyMs:y};break}}catch(x){h+=1,g=x?.message||String(x)}if(O<f){let x=c(O,s);await o(x)}}let N=(p??0)+m,T=d!=null&&p?d*p:0,E=N>0?(T+h)/N:0;return{id:e.id,endpoint:e,ok:S!=null,attempts:m,failures:h,errorRate:E,latencyEwmaMs:S?b:l??null,latencyMs:S?S.latencyMs:null,blockNumber:S?S.blockNumber:null,chainId:S?S.chainId:null,timestampMs:S?S.timestampMs:null,lastError:S?null:g,sampleCount:N}}async function Ga(e,t,r){let n=new Array(e.length),o=0;async function s(){for(;o<e.length;){let a=o++;n[a]=await r(e[a],a)}}let i=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:i},()=>s())),n}function Ja(e,{networkHeadBlock:t,maxHeadLagBlocks:r,maxHeadAgeMs:n,now:o}){if(!e.ok)return"down";let s=t!=null&&e.blockNumber!=null?t-e.blockNumber:null,i=s!=null&&s>r,a=e.timestampMs!=null&&o-e.timestampMs>n;return i||a?"stale":"fresh"}function Ya(e,t){let r=No[e.tier]-No[t.tier];if(r!==0)return r;let n=e.errorRate-t.errorRate;if(n!==0)return n;let o=e.headLagBlocks??1/0,s=t.headLagBlocks??1/0;if(o!==s)return o-s;let i=e.latencyEwmaMs??1/0,a=t.latencyEwmaMs??1/0;return i!==a?i-a:e.id<t.id?-1:e.id>t.id?1:0}async function Co(e,t={}){if(!Array.isArray(e)||e.length===0)throw new Error("rankRpcEndpoints requires a non-empty array of endpoints");let{probe:r,clock:n={now:()=>Date.now()},sleep:o=y=>new Promise(C=>setTimeout(C,y)),rng:s=Math.random,timeoutMs:i=2e3,retries:a=3,concurrency:c=4,backoff:u=Va,maxHeadLagBlocks:l=3,maxHeadAgeMs:d=6e4,latencyAlpha:p=.5,previousStats:f={}}=t;if(typeof r!="function")throw new Error("rankRpcEndpoints requires an injected probe(endpoint, ctx) function");let m=new Set;for(let y of e){if(!y||typeof y.id!="string"||!y.id)throw new Error("each RPC endpoint requires a stable string id");if(m.has(y.id))throw new Error(`duplicate RPC endpoint id: ${y.id}`);m.add(y.id)}let h=Math.min(Math.max(0,a),3),b=await Ga(e,c,y=>Wa(y,{probe:r,clock:n,sleep:o,rng:s,timeoutMs:i,maxRetries:h,backoff:u,latencyAlpha:p,previousLatencyEwmaMs:f[y.id]?.latencyEwmaMs??null,previousErrorRate:f[y.id]?.errorRate??null,previousSamples:f[y.id]?.sampleCount??0})),g=b.reduce((y,C)=>C.ok&&C.blockNumber!=null&&(y==null||C.blockNumber>y)?C.blockNumber:y,null),S=n.now(),T=[...b.map(y=>{let C=Ja(y,{networkHeadBlock:g,maxHeadLagBlocks:l,maxHeadAgeMs:d,now:S}),w=y.ok&&g!=null&&y.blockNumber!=null?g-y.blockNumber:null;return{...y,tier:C,headLagBlocks:w,costUnknown:!y.ok}})].sort(Ya),E=T.every(y=>y.tier==="down"),O=E?null:T[0],v=E?null:T[1]??null;return{status:E?Te.UNKNOWN:T.some(y=>y.tier!=="fresh")?Te.DEGRADED:Te.OK,networkHeadBlock:g,results:T,primary:O,backup:v,allDown:E}}var To=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."})]);function Fl(e){return To.find(t=>t.id===e)||null}function Ml(){return To.filter(e=>e.status==="VERIFIED")}import Qa from"node:os";import Lo from"node:path";var Q="oracle.launch-radar.data-plane.v1",Xa=200,Za=500,ec=100,tc=500;function We(e){return String(e?.message||e||"unknown error").slice(0,300)}function rc(e={}){return e.configDir||process.env.ORACLE_CONFIG_DIR||Lo.join(Qa.homedir(),".config","oracle")}function nc(e={}){return e.storePath||process.env.LAUNCH_RADAR_STORE_PATH||Lo.join(rc(e),"launch-radar","state.json")}function gr(e,t,r){return Number.isSafeInteger(e)&&e>0?Math.min(e,r):t}function Ro(e={}){let t=nc(e);try{return{ok:!0,path:t,state:wo({path:t})}}catch(r){return{ok:!1,path:t,error:We(r)}}}function Po(){return process.env.ORACLE_AUTONOMOUS_TRADING==="1"}function oc(){return Object.freeze({schema:Q,evidence:"LIVE",mode:U.SHADOW,executionReady:!1,signingReady:!1,broadcastReady:!1,funded:!1,autonomousTradingEnvSet:Po()})}function sc(e={},t={}){let r=Ro(t),n={schema:Q,storePath:r.path,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,autonomousTradingEnvSet:Po()};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})}function ic(e={},t={}){let r=Ro(t);if(!r.ok)return Object.freeze({schema:Q,evidence:"UNAVAILABLE",reason:r.error,storePath:r.path,strategyStatus:null,cursor:null,candidates:[],evidenceRecords:[]});let{state:n}=r,o=gr(e.limit,Xa,Za),s=gr(e.evidenceLimit,ec,tc);return Object.freeze({schema:Q,evidence:"LIVE",storePath:r.path,strategyStatus:structuredClone(n.strategyStatus),cursor:structuredClone(n.cursor),candidateCount:n.candidates.length,candidates:structuredClone(n.candidates.slice(0,o)),evidenceCount:n.evidence.length,evidenceRecords:structuredClone(n.evidence.slice(-s))})}async function ac(e={}){let t=Array.isArray(e.discoveries)?e.discoveries:[],r=Array.isArray(e.evaluations)?e.evaluations:[],n=Array.isArray(e.whyBlocked)?e.whyBlocked:[],o=typeof e.status=="string"&&e.status?e.status:t.length?"LIVE":"UNKNOWN",s=async()=>({status:o,cursor:e.cursor??null,discoveries:t,whyBlocked:n,unavailable:[]}),i=async({chainId:a,tokenAddress:c})=>{let u=r.find(l=>l?.chainId===a&&String(l?.tokenAddress||"").toLowerCase()===String(c||"").toLowerCase());return u?u.evaluation&&typeof u.evaluation=="object"?u.evaluation:u:{}};try{let a=await Ne({discover:s,evaluator:i,observedAt:e.observedAt}),c=a.status==="LIVE"?"LIVE":a.status==="UNAVAILABLE"?"UNAVAILABLE":"UNKNOWN";return{schema:Q,evidence:c,...a}}catch(a){return{schema:Q,evidence:"UNAVAILABLE",reason:We(a),status:"UNKNOWN",cursor:null,unavailable:[],whyBlocked:[We(a)],candidates:[]}}}async function cc(e={}){let t=Array.isArray(e.endpoints)?e.endpoints:[],r={schema:Q,evidence:"UNAVAILABLE",status:Te.UNKNOWN,networkHeadBlock:null,results:[],primary:null,backup:null,allDown:!0};if(t.length===0)return{...r,reason:"no endpoints supplied"};let n=e.samples&&typeof e.samples=="object"&&!Array.isArray(e.samples)?e.samples:{},o=async i=>{let a=n[i.id];if(!a||a.ok===!1)throw new Error(a?.error||`no probe sample supplied for endpoint "${i.id}"`);return a},s=gr(e.retries,0,3);try{let i=await Co(t,{probe:o,retries:s,concurrency:e.concurrency,maxHeadLagBlocks:e.maxHeadLagBlocks,maxHeadAgeMs:e.maxHeadAgeMs}),a=i.allDown?"UNAVAILABLE":i.status===Te.OK?"LIVE":"STALE";return{schema:Q,evidence:a,...i}}catch(i){return{...r,reason:We(i)}}}function uc(e={}){try{let t=He(e.strategy,e.observation,{});return{schema:Q,evidence:"LIVE",...t,autonomousEligible:!1,autonomousBlockers:[...new Set([...t.autonomousBlockers||[],"Launch Radar autonomous execution is not released"])],reportOnly:!0}}catch(t){let r=We(t);return{schema:Q,evidence:"UNAVAILABLE",reason:r,mode:U.SHADOW,policyEligible:!1,blockers:[r],autonomousEligible:!1,autonomousBlockers:[r],reportOnly:!0}}}export{_r as ACTION_MODE,Re as CANDIDATE_STATUS,Bl as DEFAULT_CONCURRENCY,$l as DEFAULT_LATENCY_EWMA_ALPHA,Ul as DEFAULT_MAX_HEAD_AGE_MS,ql as DEFAULT_MAX_HEAD_LAG_BLOCKS,Zo as DEFAULT_ROUTE_PROBE,es as DEFAULT_SOLANA_ROUTE_PROBE,jl as DEFAULT_TIMEOUT_MS,Ac as EVIDENCE_GENESIS_DIGEST,bl as LAUNCH_RADAR_STORE_VERSION,To as LAUNCH_RADAR_VENUES,ko as MAX_RETRIES_CEILING,cl as PUMP_CREATE_DISCRIMINATOR,al as PUMP_FUN_PROGRAM_ID,ma as RETRY_CEILING,io as SNIPE_ACTION,Ia as SOLANA_CHAIN_ID,ct as SOLANA_QUOTE_CHAIN_ID,Cu as SOLANA_QUOTE_MAX_SLIPPAGE_BPS,be as SOL_MINT,Te as STATUS,U as STRATEGY_MODE,Xo as UNISWAP_V3_POOL_CREATED_EVENTS,Qo as UNISWAP_V3_POOL_CREATED_TOPIC0,vc as VERIFIED_UNISWAP_V3_FACTORIES,jr as actionModeFor,Ye as appendEvidence,wc as appendEvidenceProjection,sr as bestSolanaShadowSwapRoute,Fo as classifyCandidate,Ha as computeEwma,gc as createEvidenceProjection,Fa as createInstalledShadowRunner,ze as createLaunchRadarRunner,hl as createLaunchRadarStore,el as createShadowRunner,yo as createSolanaLaunchScanner,Xn as createSolanaQuoteScanner,Me as createStrategy,zu as createStrategyPolicy,Va as defaultBackoffMs,hc as discoverFactoryLaunches,Et as discoverLaunches,bo as discoverSolanaLaunches,Io as evaluateInstalledDiscovery,uo as evaluateSnipeFeatures,He as evaluateStrategy,Ku as evaluateStrategyPolicy,ac as launchRadarCandidates,uc as launchRadarEvaluateStrategy,oc as launchRadarHealth,cc as launchRadarRpcHealth,ic as launchRadarSnapshot,sc as launchRadarStatus,Fl as launchRadarVenue,Ir as normalizeCandidate,xr as normalizeCandidates,Vu as normalizeStrategy,yt as openLaunchRadarStore,ol as orchestrateLaunchRadar,Je as projectEvidence,Ic as pumpFunFactoryDescriptor,Co as rankRpcEndpoints,Gu as rankSnipeCandidates,wo as readLaunchRadarStore,Pl as runInstalledShadowFleet,Ne as runLaunchRadar,tl as runLaunchRadarShadowCycle,Qe as shouldPrepare,Br as shouldQueue,wa as strategyDigest,Oc as uniswapV3FactoryDescriptor,Ml as verifiedLaunchRadarVenues};
|
|
6
|
+
- `)}`);let o=e.capabilities||{},s=nt.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:nt.filter(a=>!s.includes(a))}},supports(a){return s.includes(a)}};for(let a of nt)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 un=new Map;function ln(e){let t=Js(e);return un.set(t.chainId,t),t}function dn(e){return un.get(Number(e))||null}var Ut={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},K=e=>BigInt(e).toString(16).padStart(64,"0"),qe=e=>e.slice(2).toLowerCase().padStart(64,"0");function Ys(e,t){return`0x${Ut.getAmountsOut}`+K(e)+K(64)+K(t.length)+t.map(qe).join("")}function Qs(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 qt(e,t="router"){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}var $t=100;function Xs(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>$t)throw new Error(`slippageBps ${r} exceeds the ${$t} 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 pn(e){let{chainId:t,wrappedNative:r}=e;async function n(o,s,i,a){let c=await D(t,"eth_call",[{to:o,data:Ys(s,i)},"latest"],a);return Qs(c?.result??c)}return{async quote({tokenIn:o,tokenOut:s,amountIn:i,path:a},c={}){let u=qt(c.scanner);if(!u)return{chainId:t,evidence:N.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:N.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:u,path:l,evidence:N.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=qt(a.scanner),u=i||r;if(u&&String(o).toLowerCase()===String(u).toLowerCase())return{chainId:t,token:o,verdict:I.UNKNOWN,evidence:N.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:I.UNKNOWN,evidence:N.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:I.FAIL,evidence:N.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:I.FAIL,evidence:N.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:I.FAIL,evidence:N.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=I.PASS,b="round trip completes with expected fee/impact loss";return m<5e3?(h=I.FAIL,b=`round trip returns only ${(m/100).toFixed(2)}% -- punitive tax or no real liquidity`):m<9e3&&(h=I.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:N.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=qt(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!==N.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let b=Xs(h.amountOut,c);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let w=BigInt(Math.floor(Date.now()/1e3)+Number(u)),A=r&&m[0].toLowerCase()===r.toLowerCase()&&d.useNative,C=A?`0x${Ut.swapExactETHForTokens}`+K(b)+K(128)+qe(a)+K(w)+K(m.length)+m.map(qe).join(""):`0x${Ut.swapExactTokensForTokens}`+K(i)+K(b)+K(160)+qe(a)+K(w)+K(m.length)+m.map(qe).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:f,data:C,value:A?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:h.amountOut,minOut:b.toString(),slippageBps:c,maxSlippageBps:$t,deadline:w.toString()},requires:A?[]:[{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 Zs=[100,500,3e3,1e4],fn={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},fe=e=>BigInt(e).toString(16).padStart(64,"0"),Ue=e=>e.slice(2).toLowerCase().padStart(64,"0"),mn=/^0x[0-9a-fA-F]{40}$/,Ft=100;function ei(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Ft)throw new Error(`slippageBps ${r} exceeds the ${Ft} 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 Dt(e,t){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function hn(e){let{chainId:t,wrappedNative:r}=e;async function n({quoter:s,tokenIn:i,tokenOut:a,amountIn:c,fee:u},l){let d=`0x${fn.quoteExactInputSingle}`+Ue(i)+Ue(a)+fe(c)+fe(u)+fe(0),p=await D(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(Zs.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=Dt(c.scanner,"quoter");if(!u)return{chainId:t,evidence:N.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(!mn.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:N.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:N.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=Dt(c.scanner,"quoter"),l=(e.stableQuoteAssets||[]).map(E=>String(E).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:I.UNKNOWN,evidence:N.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:I.UNKNOWN,evidence:N.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:I.UNKNOWN,evidence:N.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 E=l.find(O=>O&&O!==String(m).toLowerCase()&&O!==String(s).toLowerCase());if(E){let O=await o({quoter:u,tokenIn:E,tokenOut:s,amountIn:i},c);if(O.best){let v=await o({quoter:u,tokenIn:s,tokenOut:E,amountIn:O.best.amountOut},c);if(v.best){let x=v.best.amountOut,y=Number(x*10000n/BigInt(i)),k=I.PASS,g="round trip vs dollar book completes with expected fee/impact loss";return y<5e3?(k=I.FAIL,g=`round trip vs dollar book returns only ${(y/100).toFixed(2)}% -- punitive tax or no real liquidity`):y<9e3&&(k=I.CAUTION,g=`round trip vs dollar book returns ${(y/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:s,base:E,quoteAsset:E,verdict:k,reason:g,amountIn:String(i),bought:O.best.amountOut.toString(),returned:x.toString(),retentionBps:y,buyFee:O.best.fee,sellFee:v.best.fee,evidence:N.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:t,token:s,verdict:I.FAIL,evidence:N.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 E=l.find(O=>O&&O!==String(m).toLowerCase()&&O!==String(s).toLowerCase());if(E){let O=await o({quoter:u,tokenIn:E,tokenOut:s,amountIn:i},c),v=O.best?await o({quoter:u,tokenIn:s,tokenOut:E,amountIn:O.best.amountOut},c):{best:null};if(O.best&&v.best){let x=v.best.amountOut,y=Number(x*10000n/BigInt(i)),k=I.PASS,g="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return y<5e3?(k=I.FAIL,g=`dollar-book round trip returns only ${(y/100).toFixed(2)}%`):y<9e3&&(k=I.CAUTION,g=`dollar-book round trip returns ${(y/100).toFixed(2)}%`),{chainId:t,venue:"uniswap-v3",token:s,base:E,quoteAsset:E,verdict:k,reason:g,amountIn:String(i),bought:O.best.amountOut.toString(),returned:x.toString(),retentionBps:y,buyFee:O.best.fee,sellFee:v.best.fee,evidence:N.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:t,token:s,verdict:I.FAIL,evidence:N.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 w=b.best.amountOut,A=Number(w*10000n/BigInt(i)),C=I.PASS,T="round trip completes with expected fee/impact loss";return A<5e3?(C=I.FAIL,T=`round trip returns only ${(A/100).toFixed(2)}% -- punitive tax or no real liquidity`):A<9e3&&(C=I.CAUTION,T=`round trip returns ${(A/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:s,base:m,verdict:C,reason:T,amountIn:String(i),bought:h.best.amountOut.toString(),returned:w.toString(),retentionBps:A,buyFee:h.best.fee,sellFee:b.best.fee,evidence:N.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=Dt(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(!mn.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!==N.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let m=l??f.fee,h=ei(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(),w=`0x${fn.exactInputSingle}`+Ue(s)+Ue(i)+fe(m)+Ue(c)+fe(a)+fe(h)+fe(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:p,data:w,value:b?String(a):"0x0"},guard:{quotedOut:f.amountOut,minOut:h.toString(),slippageBps:u,maxSlippageBps:Ft,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 ot={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function bn(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function yn(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 ti(e){let{chainId:t}=e;async function r(n,o,s){return D(t,"eth_call",[{to:n,data:o},"latest"],s)}return{async blockNumber(n={}){let o=await rn(t,n);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:N.LIVE}},async nativeBalance(n,o={}){let s=await nn(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:N.LIVE}},async tokenBalance({token:n,owner:o},s={}){let i=await on({chainId:t,token:n,owner:o},s);return{chainId:t,token:n,owner:o,raw:i?.balance??i,evidence:N.LIVE}},async resolveToken(n,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:t,token:n,evidence:N.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,ot.decimals,o).catch(()=>null),r(n,ot.symbol,o).catch(()=>null),r(n,ot.name,o).catch(()=>null),r(n,ot.totalSupply,o).catch(()=>null)]),u=bn(s?.result??s),l=u!==null||i?.result||a?.result,d={chainId:t,address:n,decimals:u===null?null:Number(u),symbol:yn(i?.result??i),name:yn(a?.result??a),totalSupply:(bn(c?.result??c)??null)?.toString()??null,evidence:l?N.LIVE:N.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:N.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await cn(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=Bt(n,c,{stables:e.stableQuoteAssets||[],wrappedNative:e.wrappedNative});return{chainId:t,token:n,pools:u,topPool:u[0]||null,quoteAsset:an(n,u),evidence:u.length?N.LIVE:N.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 Jr(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 D(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:N.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:N.LIVE}},async scoreRisk(n,o={}){let s=[],i=I.PASS,a=l=>{let d={[I.PASS]:0,[I.CAUTION]:1,[I.UNKNOWN]:2,[I.FAIL]:3};d[l]>d[i]&&(i=l)},[c,u]=await Promise.all([this.resolveToken(n,o),this.resolvePools(n,o)]);if(c.evidence!==N.LIVE?(s.push({check:"erc20-metadata",result:I.UNKNOWN,detail:c.warning}),a(I.UNKNOWN)):s.push({check:"erc20-metadata",result:I.PASS,detail:`${c.symbol} / ${c.decimals}d`}),u.evidence===N.UNAVAILABLE)s.push({check:"liquidity",result:I.UNKNOWN,detail:u.reason}),a(I.UNKNOWN);else if(!u.pools.length)s.push({check:"liquidity",result:I.FAIL,detail:"no pool with liquidity found"}),a(I.FAIL);else{let l=u.pools[0],d=l.liquidityUsd??0;d<5e3?(s.push({check:"liquidity",result:I.CAUTION,detail:`top pool only $${d}`}),a(I.CAUTION)):s.push({check:"liquidity",result:I.PASS,detail:`$${d} on ${l.dex}`}),l.createdAt&&Date.now()-l.createdAt<24*3600*1e3&&(s.push({check:"age",result:I.CAUTION,detail:"pool under 24h old"}),a(I.CAUTION))}if(typeof this.sellSimulation=="function"){let l=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},o).catch(d=>({verdict:I.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:I.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(I.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 wn(e){let r={...ti(e)},n=new Set((e.venues||[]).map(s=>s.kind));e.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,hn({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,pn({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 ri=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 gn(){return ri.map(e=>ln(wn(e)))}import{AbiCoder as ni,Interface as On,getAddress as he,isAddress as In,keccak256 as oi}from"ethers";var Mt="0x0000000000000000000000000000000000000000",si="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",ii=ni.defaultAbiCoder(),An=new On(["function quoteExactInputSingle((address tokenIn,address tokenOut,uint256 amountIn,uint24 fee,uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut,uint160 sqrtPriceX96After,uint32 initializedTicksCrossed,uint256 gasEstimate)"]),Sn=new On(["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)"]),W=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:W[1].wrappedNative}),10:Object.freeze({quoter:"0x1f3131a13296fb91c90870043742c3cdbff1a8d7",wrappedNative:W[10].wrappedNative}),56:Object.freeze({quoter:"0x9f75dd27d6664c475b90e105573e550ff69437b0",wrappedNative:W[56].wrappedNative}),137:Object.freeze({quoter:"0xb3d5c3dfc3a7aebff71895a7191796bffc2c81b9",wrappedNative:W[137].wrappedNative}),8453:Object.freeze({quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",wrappedNative:W[8453].wrappedNative}),42161:Object.freeze({quoter:"0x3972c00f7ed4885e145823eb7c655375d275a1c5",wrappedNative:W[42161].wrappedNative}),43114:Object.freeze({quoter:"0xbe40675bb704506a3c2ccfb762dcfd1e979845c2",wrappedNative:W[43114].wrappedNative}),4663:Object.freeze({quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",wrappedNative:W[4663].wrappedNative})}),ai=Object.freeze([100,500,3e3,1e4]);function me(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 xn(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 Nn(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 Ht(e){let t=String(e??"").trim().toLowerCase();return t===""||t==="eth"||t===Mt||t===si}function $e(e,t){if(!In(String(e??"")))throw new Error(`${t} must be an EVM address`);return he(String(e))}function En(e,t,r){return Ht(e)?he(t.wrappedNative):$e(e,r)}function vn(e,t){return Ht(e)?he(Mt):$e(e,t)}function kn(e,t){let r=Number(e);if(!Number.isInteger(r)||r<0||r>16777215)throw new Error(`${t} must be uint24`);return r}function ci(e,t){let r=Number(e);if(!Number.isInteger(r)||r<-8388608||r>8388607)throw new Error(`${t} must be int24`);return r}function ui({tokenIn:e,tokenOut:t,poolKey:r,poolId:n}){me(r,new Set(["currency0","currency1","fee","tickSpacing","hooks"]),"V4 PoolKey");let o=$e(r.currency0,"V4 currency0"),s=$e(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:kn(r.fee,"V4 fee"),tickSpacing:ci(r.tickSpacing,"V4 tickSpacing"),hooks:$e(r.hooks??Mt,"V4 hooks")}),a=vn(e,"tokenIn"),c=vn(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=oi(ii.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 Vt(e,t){if(Ht(t))return!0;if(!In(String(t??"")))return!1;let r=W[Number(e)]?.wrappedNative||De[Number(e)]?.wrappedNative;return!!(r&&he(String(t)).toLowerCase()===he(r).toLowerCase())}async function Cn(e={},t={},r={}){me(e,new Set(["chainId","tokenIn","tokenOut","amountIn","fee"]),"V3 read"),me(t,new Set(["timeoutMs"]),"V3 read options"),me(r,new Set(["rpc"]),"V3 read dependencies");let n=Number(e.chainId),o=W[n];if(!o)throw new Error(`V3 read unavailable on chain ${e.chainId}`);let s=En(e.tokenIn,o,"tokenIn"),i=En(e.tokenOut,o,"tokenOut");if(s.toLowerCase()===i.toLowerCase())throw new Error("tokenIn and tokenOut must differ");let a=xn(e.amountIn,"amountIn"),c=e.fee==null?ai:[kn(e.fee,"V3 fee")],u=r.rpc||D,l=Nn(t.timeoutMs),d=await Promise.all(c.map(async f=>{let m=An.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=An.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:he(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 Tn(e={},t={},r={}){me(e,new Set(["chainId","tokenIn","tokenOut","amountIn","poolKey","poolId"]),"V4 read"),me(t,new Set(["timeoutMs"]),"V4 read options"),me(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=xn(e.amountIn,"amountIn");if(s>0xffffffffffffffffffffffffffffffffn)throw new Error("amountIn exceeds uint128");let i=ui(e),a=Sn.encodeFunctionData("quoteExactInputSingle",[{poolKey:i.poolKey,zeroForOne:i.zeroForOne,exactAmount:s,hookData:"0x"}]),u=await(r.rpc||D)(n,"eth_call",[{to:o.quoter,data:a},"latest"],Nn(t.timeoutMs));if(!u||u==="0x")throw new Error("V4 read returned an empty result");let l=Sn.decodeFunctionResult("quoteExactInputSingle",u);return Object.freeze({venue:"uniswap-v4",chainId:n,quoter:he(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 li=new Set(["chainId","tokenIn","tokenOut","amountIn","v4PoolKey","v4PoolId"]),di=new Set(["maxImpactPct","timeoutMs"]),pi=new Set(["quoteV3","quoteV4","gasPrice"]);function zt(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 Wt(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 Ln(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 re(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 fi(e){if(e<=1n)return null;let t=e/1000n;return t>0n&&t<e?t:1n}function mi({amountIn:e,amountOut:t,probeIn:r,probeOut:n}){let o=re(e),s=re(t),i=re(r),a=re(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 Kt(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 hi({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,amountOut:o,gasEstimate:s,gasPrice:i}){let a=re(s),c=re(i),u=re(n),l=re(o);if(!a||!c||!u||!l||a<=0n||c<=0n)return null;let d=a*c;return Vt(e,r)?d:Vt(e,t)?d*l/u:null}async function bi(e,t){let r=await D(e,"eth_gasPrice",[],{timeoutMs:t});return re(r)}function yi(e,t){return Object.freeze({source:e,quality:"FAILED",amountOut:null,error:String(t?.message||t).slice(0,240)})}async function Rn({source:e,amountIn:t,timeoutMs:r,fullRead:n,probeRead:o}){try{let s=await Kt(n,r,e),i=Wt(s?.amountOut,`${e} amountOut`),a=fi(t);if(a==null)return{source:e,full:s,impactPct:null};try{let c=await Kt(()=>o(a.toString(),s),r,`${e} impact probe`),u=mi({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 wi({inspected:e,params:t,gasPrice:r}){let n=e.full,o=Wt(n.amountOut,`${e.source} amountOut`),s=hi({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 gi({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={}){zt(e,li,"route params"),zt(t,di,"route options"),zt(r,pi,"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=Wt(e.amountIn,"amountIn"),s=Ln(t.timeoutMs,12e3,250,6e4,"timeoutMs"),i=Ln(t.maxImpactPct,25,0,100,"maxImpactPct"),a=r.quoteV3||Cn,c=r.quoteV4||Tn,u=r.gasPrice||bi,l=[];W[n]&&l.push(Rn({source:"uniswap-v3",amountIn:o,timeoutMs:s,fullRead:()=>a({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:o.toString()},{timeoutMs:s}),probeRead:(S,L)=>a({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:S,fee:L.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&&De[n]&&l.push(Rn({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:S=>c({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:S,poolKey:e.v4PoolKey,poolId:e.v4PoolId},{timeoutMs:s})})),!l.length)throw new Error(`no verified read-only quote source on chain ${n}`);let f=Kt(()=>u(n,s),s,"gas price read").catch(()=>null),m=await Promise.all(l),h=await f,b=m.filter(S=>S.error).map(S=>yi(S.source,S.error)),w=m.filter(S=>S.full),A=w.filter(S=>S.impactPct!=null&&S.impactPct>i).map(S=>({source:S.source,impactPct:Number(S.impactPct.toFixed(2)),reason:`price impact ${S.impactPct.toFixed(2)}% exceeds ${i}% ceiling`})),C=new Set(A.map(S=>S.source)),T=w.filter(S=>!C.has(S.source)),E=T.map(S=>wi({inspected:S,params:{...e,chainId:n},gasPrice:h})),O=E.length>0&&E.every(S=>S.costAccounted),v=O?"net":"gross";for(let S of E){let L=BigInt(S.grossOut),ne=O?BigInt(S.costInDest):0n;S.netOut=(L>ne?L-ne:0n).toString()}E.sort((S,L)=>{let ne=BigInt(O?S.netOut:S.grossOut),V=BigInt(O?L.netOut:L.grossOut);return ne===V?S.source.localeCompare(L.source):V>ne?1:-1});let x=[];O?x.push("Gas is estimated from quoter gas units and the current read-only gas price; actual gas may differ."):x.push("Gas was not accounted for; routes are ranked on gross output.");let y=T.filter(S=>S.impactPct==null).map(S=>S.source);y.length&&x.push(`Price impact is UNKNOWN for: ${y.join(", ")}.`),A.length&&x.push(`Dropped on price impact: ${A.map(S=>S.source).join(", ")}.`),!d&&De[n]&&x.push("V4 was not queried because no exact verified PoolKey identity was discovered.");let k=null,g=null;if(E.length>1){let S=BigInt(O?E[0].netOut:E[0].grossOut),L=BigInt(O?E[1].netOut:E[1].grossOut);L>0n&&(k=Number((S-L)*10000000n/L)/1e3,g=`${E[0].source} vs ${E[1].source}`)}let q=Object.fromEntries(T.filter(S=>S.impactPct!=null).map(S=>[S.source,Number(S.impactPct.toFixed(4))]));return Object.freeze({kind:"swap",chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:o.toString(),best:E[0]||null,routes:Object.freeze(E.map(S=>Object.freeze(S))),failed:Object.freeze(b),rankedOn:v,sourcesTried:l.length,sourcesAnswered:w.length,improvementBps:k,spreadBasis:g,priceImpact:Object.freeze(q),impactRejected:Object.freeze(A),impactUnmeasured:Object.freeze(y),warnings:Object.freeze(x),note:gi({routes:E,rankedOn:v,improvementBps:k})})}var be="So11111111111111111111111111111111111111112",lt=101,Lu=100,Ji=new Set(["chainId","tokenIn","tokenOut","amountIn"]),Yi=new Set(["maxImpactPct","timeoutMs","quoteFn"]);function Xn(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 Zn(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 eo(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 Qi(e,t={}){let{jupiterQuote:r}=await Promise.resolve().then(()=>(or(),nr)),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 ir(e={},t={}){if(Xn(e,Ji,"params"),Xn(t,Yi,"options"),e.chainId!=null&&Number(e.chainId)!==101)throw new Error("solana quote adapter only handles chainId 101");let r=eo(e.tokenIn,"tokenIn"),n=eo(e.tokenOut,"tokenOut"),o=Zn(e.amountIn,"amountIn");if(r===n)throw new Error("solana quote tokenIn and tokenOut must differ");let s=t.quoteFn||Qi;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=Zn(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 to({routeFn:e=ir}={}){return Object.freeze({async sellSimulation({token:t,amountIn:r,base:n}={}){let{simulateSell:o,SELL_SIM:s}=await Promise.resolve().then(()=>(Qn(),Yn)),i=await o({token:t,base:n||be,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 pa(e){return e?.token?.address||e?.tokenAddress||null}function fa(e){return e?.quoteAsset||e?.pool?.quoteAsset||null}function ma(e,t){return e?.quoteAmountIn||e?.quote?.amountIn||null}async function ar({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=pa(e),o=fa(e),s=ma(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(()=>(or(),nr)),u=await c({userPublicKey:t.recipient,inputMint:o==="unknown"?be: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 cr({prepared:e}={},t=process.env){if(e?.prepared!==!0)return{ok:!1,error:"nothing prepared"};let{armPreparedAction:r}=await Promise.resolve().then(()=>(ao(),io)),n=e.localSignerEnvelope||e.envelope;return n?r({localSignerEnvelope:n},t):{ok:!1,error:"prepared envelope missing"}}import{createHash as Ea}from"node:crypto";import{createHash as ha}from"node:crypto";var $=Object.freeze({SHADOW:"shadow",ARMED:"armed",AUTONOMOUS:"autonomous"}),ba=3,ya=new Set(Object.values($));function pr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))pr(t);Object.freeze(e)}return e}function dr(e){return Array.isArray(e)?`[${e.map(dr).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${dr(e[t])}`).join(",")}}`:JSON.stringify(e)}function wa(e){return`sha256:${ha("sha256").update(dr(e)).digest("hex")}`}function ur(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 ga(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new TypeError(`${t} entries must be positive safe integers`);return e}function lr(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 xe(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 He(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 mt(e,t){let r=xe(e,t),[n,o=""]=r.split(".");return{digits:BigInt(n+o),scale:o.length}}function ft(e,t,r="value"){let n=mt(e,r),o=mt(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 co(e){let t=structuredClone(e);return delete t.digest,t}function Aa(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");return wa(co(e))}function Ve(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");let t=e.mode??$.SHADOW;if(!ya.has(t))throw new TypeError("mode must be shadow, armed, or autonomous");let r={version:1,mode:t,chains:ur(e.chains,"chains",ga),venues:ur(e.venues,"venues",lr),quoteAssets:ur(e.quoteAssets,"quoteAssets",lr),maxSpendPerTrade:xe(e.maxSpendPerTrade,"maxSpendPerTrade",{positive:!0}),maxSpendPerDay:xe(e.maxSpendPerDay,"maxSpendPerDay",{positive:!0}),minLiquidityUsd:xe(e.minLiquidityUsd,"minLiquidityUsd",{positive:!0}),maxSlippageBps:He(e.maxSlippageBps,"maxSlippageBps",{max:1e4}),maxGas:xe(e.maxGas,"maxGas",{positive:!0}),maxPriorityFee:xe(e.maxPriorityFee,"maxPriorityFee"),maxBuysPerHour:He(e.maxBuysPerHour,"maxBuysPerHour",{min:1}),retryCeiling:He(e.retryCeiling,"retryCeiling",{max:ba}),ttlMs:He(e.ttlMs,"ttlMs",{min:1}),requireSellSimulation:e.requireSellSimulation,requireRiskPass:e.requireRiskPass??!0,maxRoundTripLossBps:He(e.maxRoundTripLossBps??1500,"maxRoundTripLossBps",{max:1e4}),killSwitch:e.killSwitch,recipient:e.recipient==null||e.recipient===""?null:lr(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!==$.SHADOW&&!r.recipient)throw new TypeError("recipient is required when mode is armed or autonomous");if(ft(r.maxSpendPerTrade,r.maxSpendPerDay)>0)throw new TypeError("maxSpendPerTrade cannot exceed maxSpendPerDay");return r.digest=Aa(r),pr(r)}var Sa=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 j(e,t,r){t&&e.push(r)}function ze(e,t={},r={}){let n=Ve(co(e)),o=[];j(o,n.killSwitch,"kill switch is engaged"),j(o,!n.chains.includes(t.chain),"chain is not on the exact allowlist"),j(o,!n.venues.includes(t.venue),"venue is not on the exact allowlist"),j(o,!n.quoteAssets.includes(t.quoteAsset),"quote asset is not on the exact allowlist");let s=(a,c,u)=>{try{j(o,ft(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=mt(t.spentToday,"daily spend"),c=mt(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)}`;j(o,ft(d,n.maxSpendPerDay,"daily spend")>0,"daily spend cap would be exceeded")}catch{o.push("daily spend evidence is missing or unknown")}try{j(o,ft(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"),j(o,!Number.isSafeInteger(t.buysLastHour),"buys per hour evidence is missing or unknown"),j(o,Number.isSafeInteger(t.buysLastHour)&&t.buysLastHour>=n.maxBuysPerHour,"buys per hour cap is reached"),j(o,!Number.isSafeInteger(t.retries)||t.retries<0,"retry evidence is missing or unknown"),j(o,Number.isSafeInteger(t.retries)&&t.retries>n.retryCeiling,"retry ceiling is exceeded"),j(o,!Number.isFinite(t.ageMs)||t.ageMs<0,"TTL evidence is missing or unknown"),j(o,Number.isFinite(t.ageMs)&&t.ageMs>=n.ttlMs,"TTL has expired"),j(o,t.sellSimulation?.verdict!=="PASS"||t.sellSimulation?.evidence!=="LIVE","mandatory sell simulation has no LIVE PASS evidence"),j(o,typeof t.fireId!="string"||t.fireId.length===0,"fire id evidence is missing or unknown"),j(o,!Array.isArray(t.firedIds),"duplicate-fire history is missing or unknown"),j(o,Array.isArray(t.firedIds)&&t.firedIds.includes(t.fireId),"duplicate fire is blocked");let i=[...o];j(i,r?.ORACLE_AUTONOMOUS_TRADING!=="1","ORACLE_AUTONOMOUS_TRADING=1 is required literally");for(let[a,c]of Sa)j(i,t.autonomousGates?.[a]!==!0,c);return j(i,n.mode!==$.AUTONOMOUS,"strategy mode is not autonomous"),pr({strategyDigest:n.digest,mode:n.mode,policyEligible:o.length===0,blockers:o,autonomousEligible:i.length===0,autonomousBlockers:i,reportOnly:!0})}var Ku=Ve,Wu=Ve,Gu=ze;function fr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))fr(t);Object.freeze(e)}return e}var uo=Object.freeze({ALERT_ONLY:"alert_only",EXECUTE:"execute"}),lo=Object.freeze({liveQuote:20,sellSimulation:30,contractRisk:20,liquidity:15,roundTripLoss:15});function z(e,t){return{id:e,verdict:"PASS",detail:t}}function H(e,t){return{id:e,verdict:"BLOCK",detail:t}}function po(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function fo({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?H("killSwitch","engaged"):z("killSwitch","off"),"kill switch is engaged"),s(e.chains.includes(t.chain)?z("chain",String(t.chain)):H("chain",String(t.chain??"missing")),"chain is not on the exact allowlist"),s(e.venues.includes(t.venue)?z("venue",String(t.venue)):H("venue",String(t.venue??"missing")),"venue is not on the exact allowlist"),s(e.quoteAssets.includes(t.quoteAsset)?z("quoteAsset",String(t.quoteAsset)):H("quoteAsset",String(t.quoteAsset??"missing")),"quote asset is not on the exact allowlist");let i=r.quote?.evidence||t.quoteEvidence;s(i==="LIVE"?z("liveQuote","LIVE"):H("liveQuote",String(i||"missing")),"live quote is missing");let a=t.sellSimulation||r.sellSimulation;s(a?.verdict==="PASS"&&a?.evidence==="LIVE"?z("sellSimulation","LIVE PASS"):H("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"?z("contractRisk","PASS"):H("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?z("liquidity",String(u)):H("liquidity",String(u??"missing")),"minimum real liquidity is not met")}catch{s(H("liquidity","unknown"),"liquidity evidence is missing or unknown")}let l=po(t.slippageBps);s(l!=null&&l<=e.maxSlippageBps?z("slippage",String(l)):H("slippage",String(t.slippageBps??"missing")),"slippage exceeds cap or is unknown");let d=po(t.roundTripLossBps);s(d!=null&&d<=e.maxRoundTripLossBps?z("roundTripLoss",String(d)):H("roundTripLoss",String(t.roundTripLossBps??"missing")),"round-trip loss exceeds cap or is unknown"),s(Number.isSafeInteger(t.retries)&&t.retries<=e.retryCeiling?z("retryCeiling",String(t.retries)):H("retryCeiling",String(t.retries??"missing")),"retry ceiling is exceeded or unknown"),s(Number.isFinite(t.ageMs)&&t.ageMs>=0&&t.ageMs<e.ttlMs?z("ttl",String(t.ageMs)):H("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)?z("duplicateFire",t.fireId):H("duplicateFire","missing or duplicate"),"duplicate fire is blocked or fire id is unknown");let p=0;for(let h of n)h.verdict==="PASS"&&lo[h.id]&&(p+=lo[h.id]);let f=o.length===0,m=e.mode==="shadow"?uo.ALERT_ONLY:uo.EXECUTE;return fr({snipeReady:f,wouldSnipe:f,armed:!1,actionMode:m,score:p,features:n,blockers:o,reportOnly:e.mode==="shadow"})}function Yu(e=[]){if(!Array.isArray(e))throw new TypeError("snipe candidates must be an array");return fr([...e].sort((t,r)=>{let n=+!!r?.snipe?.snipeReady-+!!t?.snipe?.snipeReady;return n!==0?n:(r?.snipe?.score||0)-(t?.snipe?.score||0)}))}function ht(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function mr(e){return Array.isArray(e)?`[${e.map(mr).join(",")}]`:ht(e)?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${mr(e[t])}`).join(",")}}`:JSON.stringify(e)}function va(e){return`cycle:${Ea("sha256").update(mr(e)).digest("hex")}`}function Ke(e,t){if(typeof e!="function")throw new TypeError(`launch-radar runner: injected ${t} function is required`)}function mo(e){return e instanceof Error?e.message:String(e)}function We(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(!ht(r))throw new TypeError("launch-radar runner: strategy is required");Ke(n,"discovery"),Ke(o,"evaluate");let s=e.now??(()=>new Date().toISOString()),i=e.sleep??(()=>Promise.resolve()),a=e.jitter??(()=>0);Ke(s,"clock"),Ke(i,"sleep"),Ke(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(w){if(h=w,b===c)break;let A=Number(a()),C=Number.isFinite(A)?Math.max(0,A):0,T=Math.min(l,u*2**b+C);await i(T)}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=qr(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(E=>n({cursor:structuredClone(m.cursor),attempt:E,mode:r.mode}))}catch(E){return{mode:r.mode,status:"failed",blockers:[mo(E)],results:[],actionMode:h}}if(!ht(b)||!Array.isArray(b.candidates)||!(b.cursor===null||ht(b.cursor)))return{mode:r.mode,status:"failed",blockers:["discovery returned an invalid deterministic result"],results:[],actionMode:h};let w=[];for(let E of b.candidates)try{let O=await d(g=>o(structuredClone(E),{attempt:g,mode:r.mode})),v=ze(r,O,{}),x=fo({strategy:r,observation:O,evaluation:E}),y={prepared:!1},k=!1;Ze(r,v)&&typeof e.prepareFn=="function"?y=await e.prepareFn({candidate:E,observation:O,strategy:r,policy:v})||{prepared:!1}:Ze(r,v)&&(y={prepared:!1,blockedReasons:["prepareFn is required when strategy mode is not shadow"]}),Ur(r,v,y)&&typeof e.queueFn=="function"&&(k=(await e.queueFn({prepared:y,candidate:E,observation:O,strategy:r,policy:v}))?.ok===!0),w.push({id:E?.id??null,policy:v,snipe:x,prepared:y.prepared===!0,queued:k,actionMode:h})}catch(O){w.push({id:E?.id??null,policy:{mode:r.mode,policyEligible:!1,reportOnly:r.mode===$.SHADOW,blockers:[`evaluation failed: ${mo(O)}`]},actionMode:h,prepared:!1,queued:!1})}let A={cursor:b.cursor,candidates:b.candidates,results:w},C={id:va(A),type:r.mode===$.SHADOW?"shadow-cycle":"execute-cycle",at:s(),data:A},T=t.commitCycle({candidates:b.candidates,cursor:b.cursor,strategyStatus:{mode:r.mode,status:"inert",ambiguous:!1},event:C});return{mode:r.mode,status:T.duplicate?"duplicate":"completed",results:w,evidenceId:T.evidence.id,actionMode:h}}return Object.freeze({status:p,runCycle:f})}var rl=We,nl=async e=>We(e).runCycle();function ho(e){return[...new Set(e.filter(Boolean).map(String))]}function ye(e){return Array.isArray(e)?e.map(ye):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,ye(r)])):e}function se(e,t,r="UNKNOWN"){return!e||typeof e!="object"?{evidence:r,observedAt:t}:ye({...structuredClone(e),evidence:e.evidence||r,observedAt:e.observedAt||t})}function Oa(e,t){let r=String(t||"").toLowerCase();return!!(r&&[e?.address,e?.pair,e?.poolId].some(n=>String(n||"").toLowerCase()===r))}function Ia(e,t){let r=e.poolId||e.poolAddress||null,n=[t.topPool,...t.pools?.pools||[]].filter(Boolean),o=r?n.find(i=>Oa(i,r)):t.topPool,s={address:e.poolAddress??null,poolId:e.poolId,poolKey:e.poolKey,quoteAsset:e.quoteAsset};return ye({...o||{},...s})}function xa(e,t,r,n){let o=e.observedAt||n,s=Ia(e,t),i=se(t.scannerRisk||t.risk,o),a=se(t.sellability,o,"UNAVAILABLE"),c=se(t.quote,o,"UNAVAILABLE"),u=c.evidence==="LIVE"?"PASS":"UNKNOWN";return ye({chain:{id:e.chainId,...t.chain||{}},token:se({address:e.tokenAddress,...t.token||{}},o,"LIVE"),pool:se(s,o,"LIVE"),venue:se({...e.venue,supported:e.venue?.supported===!0,verified:e.venue?.verified===!0},o,"LIVE"),signal:se({kind:e.kind,source:"verified-factory",unsolicitedAirdrop:!1},o,"LIVE"),risk:i,sellability:a,sellSimulation:se(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:ye({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:ho([...r||[],...t.blockedReasons||[],t.error]),latency:{discoveredAt:o,riskCompletedAt:i.observedAt,sellabilityCompletedAt:a.observedAt,routeCompletedAt:c.observedAt,normalizedAt:n}})}async function Ne(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:ye(structuredClone(a)),prepare:e.prepare===!0})}catch(u){c={error:`evaluation unavailable: ${String(u?.message||u).slice(0,300)}`}}i.push(xa(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(ho(n?.whyBlocked||[])),candidates:kr(i)})}var il=Ne;var Na=101,bo=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/,yo="181ec828051c0777",wo="6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P";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 ka(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!==wo)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 Ca(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(yo))continue;let c=Array.isArray(i.accounts)?i.accounts:[],u=c[0],l=c[2];return!bo.test(u||"")||!bo.test(l||"")?null:{id:`solana:${r}:${s}`,chain:"solana",chainId:Na,factoryId:t.id||null,factoryAddress:t.programId,tokenAddress:u,quoteAsset:be,poolAddress:l,venue:structuredClone(t.venue),kind:"token-launched",slot:n,signature:r,instructionIndex:s,evidence:"LIVE"}}return null}async function go(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=ka(u);l?n.push({id:u?.id||null,status:"UNAVAILABLE",reason:l}):o.push(u)}let s=ke({until:e.cursor?.until||null});if(o.length===0)return ke({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 ke({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 ke({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=Ca({...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 ke({status:"LIVE",discoveries:[...c.values()],unavailable:n,cursor:{until:a},whyBlocked:n.map(u=>u.reason)})}var ul=wo,ll=yo;Qt();var Ta="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function La(e){let t=String(e||"");if(!t)return Buffer.alloc(0);let r=[0];for(let o of t){let s=Ta.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 Ra(e){return typeof e=="string"?e:e?.pubkey||null}function Pa(e){let t=e?.transaction?.message||{},r=Array.isArray(t.accountKeys)?t.accountKeys.map(Ra):[],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=La(i.data).toString("hex")),a&&s.push({programId:a,accounts:c,dataHex:u})}return s}function Ao(e={}){let t=e.solanaRpc||_n;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:Pa(n)}:{signature:r,slot:null,instructions:[]}}}}import M from"node:fs";import bt from"node:path";var wt=1,_a=0;function ge(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function F(e){return structuredClone(e)}function br(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)=>br(r,`${t}[${n}]`));if(ge(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}`);br(n,`${t}.${r}`)}return}throw new Error(`launch-radar store: non-JSON value at ${t}`)}}function we(e){return Array.isArray(e)?`[${e.map(we).join(",")}]`:ge(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${we(e[t])}`).join(",")}}`:JSON.stringify(e)}function ja(){return{version:wt,candidates:[],cursor:null,strategyStatus:{mode:"shadow",status:"inert",ambiguous:!1},evidence:[]}}function Ba(e){if(!ge(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 Ge(e){if(!ge(e)||e.version!==wt)throw new Error("launch-radar store: corrupt or unsupported version");if(!Array.isArray(e.candidates)||!(e.cursor===null||ge(e.cursor))||!Array.isArray(e.evidence))throw new Error("launch-radar store: corrupt state shape");Ba(e.strategyStatus),br(e);try{Qe(e.evidence)}catch(t){throw new Error(`launch-radar store: corrupt evidence: ${t.message}`)}return F(e)}function yt(e,t=!1){let r;try{r=M.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 yr(e){yt(e);let t;try{t=JSON.parse(M.readFileSync(e,"utf8"))}catch{throw new Error("launch-radar store: corrupt JSON")}return Ge(t)}function hr(e,t){let r=Ge(t),n=bt.dirname(e);M.mkdirSync(n,{recursive:!0,mode:448});let o=M.lstatSync(n);if(o.isSymbolicLink()||!o.isDirectory())throw new Error("launch-radar store: parent must be a regular directory, not a symlink");yt(e,!0)&&yt(e);let s=bt.join(n,`.launch-radar.${process.pid}.${_a+=1}.tmp`),i;try{i=M.openSync(s,"wx",384),M.writeFileSync(i,`${we(r)}
|
|
7
|
+
`,"utf8"),M.fsyncSync(i),M.closeSync(i),i=void 0,M.renameSync(s,e),M.chmodSync(e,384);let a=M.openSync(n,"r");try{M.fsyncSync(a)}finally{M.closeSync(a)}}catch(a){i!==void 0&&M.closeSync(i);try{M.unlinkSync(s)}catch{}throw a}}function gt(e={}){let t=e.path;if(typeof t!="string"||!bt.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");yt(t,!0)?yr(t):hr(t,ja());let r=()=>yr(t),n=(o,{reconciliation:s=!1}={})=>{if(r().strategyStatus.ambiguous&&!s)throw new Error("launch-radar store: ambiguous state is terminal until reconciliation");return hr(t,o),F(o)};return Object.freeze({path:t,read:r,replaceState(o={}){if(!ge(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]=F(o[a]));return n(Ge(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&&we(i.data)===we(o?.data))return F(i);throw new Error(`launch-radar store: duplicate evidence conflict: ${o?.id}`)}let a=Xe(s.evidence,o),c=a.at(-1);return n({...s,evidence:F(a)}),F(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&&we(u.data)===we(a?.data))return{duplicate:!0,evidence:F(u),state:c};throw new Error(`launch-radar store: duplicate evidence conflict: ${a?.id}`)}let l=Xe(c.evidence,a),d=Ge({...c,candidates:F(o),cursor:F(s),strategyStatus:F(i),evidence:F(l)});return n(d),{duplicate:!1,evidence:F(l.at(-1)),state:F(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 hr(t,{...s,strategyStatus:i}),F(i)},reconcile(o={}){if(!ge(o))throw new TypeError("launch-radar store: reconciliation state must be an object");let s=r(),i=Ge({...s,...F(o),version:wt,evidence:s.evidence});if(i.strategyStatus.ambiguous)throw new Error("launch-radar store: reconciliation must clear ambiguous state");return n(i,{reconciliation:!0})}})}function So(e={}){let t=e.path;if(typeof t!="string"||!bt.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");return yr(t)}var yl=gt,wl=wt;function gr(e){return e.ORACLE_CONFIG_DIR||ie.join(qa.homedir(),".config","oracle")}function Eo(e,t){if(!e||!ie.isAbsolute(e))throw new Error(`${t} path must be absolute`);let r=At.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(At.readFileSync(e,"utf8"))}function Ua(e){return e==null?null:String(e)}function Ce(e){if(e!==void 0)return typeof e=="bigint"?e.toString():Array.isArray(e)?e.map(Ce).filter(t=>t!==void 0):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,Ce(r)])):e}function No(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 wr(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 $a(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 Da(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:No(t.amountIn,"routeProbe.amountIn"),quoteAssetDecimals:wr(t.quoteAssetDecimals,0,255,"routeProbe.quoteAssetDecimals"),slippageBps:wr(t.slippageBps??100,0,1e4,"routeProbe.slippageBps"),maxImpactPct:$a(t.maxImpactPct??25,0,100,"routeProbe.maxImpactPct"),timeoutMs:wr(t.timeoutMs??12e3,250,6e4,"routeProbe.timeoutMs")})}function vo(e){return[e?.source,e?.amountOut,e?.netOut,e?.meta?.poolId].map(t=>String(t??"").toLowerCase()).join(":")}function Oo(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 Fa(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 Io(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 xo(e){if(!e?.best||!No(e.best.amountOut,"best route amountOut"))throw new Error("best route returned no positive output");let t=Array.isArray(e.routes)?e.routes:[],r=vo(e.best),n=t.findIndex(a=>vo(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."),Ce({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 Ma(e,t){return{quote:{evidence:"UNAVAILABLE",reason:e,observedAt:t},sellability:{verdict:"UNKNOWN",evidence:"UNAVAILABLE",reason:e,observedAt:t}}}async function ko({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=Da(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:Ce(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);Io(d,t,"buy");let p=xo(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);Io(f,t,"reverse");let m=xo(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=Fa(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=Ce({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,Ma(c,o))}return Ce(s)}function Co(e){let t=e.quoteAsset||e.pool?.quoteAsset||e.token?.quoteAsset||"unknown",r=Oo(e.quoteAmountIn,e.quoteAssetDecimals??18)||Oo(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:Ua(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 Ha(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=Eo(t.ORACLE_LAUNCH_RADAR_STRATEGY_FILE,"strategy file"),n=Eo(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=Ve(r);if(![$.SHADOW,$.ARMED,$.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 Va({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");gn();let a=dn(i[0]);if(!a)throw new Error(`no scanner registered for chain ${i[0]}`);let c=t.ORACLE_LAUNCH_RADAR_STORE_PATH||ie.join(gr(t),"launch-radar",`state-${i[0]}.json`),u=gt({path:c});return We({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 Ne({discover:()=>Ot({scanner:a,factories:o,fromBlock:h,toBlock:m,cursor:p}),evaluator:async({discovery:w})=>{let A=o.find(C=>C?.id===w?.factoryId||String(C?.factoryAddress||"").toLowerCase()===String(w?.factoryAddress||"").toLowerCase());return ko({scanner:a,discovery:w,descriptor:A,routeFn:e.routeFn||Gt,observedAt:new Date().toISOString()})},observedAt:new Date().toISOString()});return{candidates:b.candidates,cursor:b.cursor}},evaluate:async p=>Co(p),prepareFn:e.prepareFn||(p=>ar({...p,scanner:a})),queueFn:e.queueFn||(p=>cr(p,t))})}function Va({env:e,factories:t,strategy:r,options:n}){let o=n.solanaScanner||Ao(),s=n.solanaRouteFn||ir,i=n.solanaQuoteScanner||to({routeFn:s}),a=e.ORACLE_LAUNCH_RADAR_STORE_PATH||ie.join(gr(e),"launch-radar","state-solana.json"),c=gt({path:a});return We({store:c,strategy:r,discover:async({cursor:l})=>{let d=await Ne({discover:()=>go({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 ko({scanner:i,discovery:{...p,quoteAsset:p.quoteAsset||be},descriptor:f,routeFn:s,observedAt:new Date().toISOString()})},observedAt:new Date().toISOString()});return{candidates:d.candidates,cursor:d.cursor}},evaluate:async l=>Co(l),prepareFn:n.prepareFn||(l=>ar({...l,scanner:i})),queueFn:n.queueFn||(l=>cr(l,e))})}async function jl(e={}){let t=e.env||process.env,r=t.ORACLE_LAUNCH_RADAR_FACTORIES_DIR;if(!r||!ie.isAbsolute(r))throw new Error("ORACLE_LAUNCH_RADAR_FACTORIES_DIR must be an absolute directory");let n=At.lstatSync(r);if(n.isSymbolicLink()||!n.isDirectory())throw new Error("factories dir must be a regular directory");let o=At.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:ie.join(r,i),ORACLE_LAUNCH_RADAR_STORE_PATH:ie.join(t.ORACLE_LAUNCH_RADAR_STORE_DIR||ie.join(gr(t),"launch-radar"),`state-${a}.json`)},u=await Ha({...e,env:c}).runCycle();s.push({file:i,mode:u.mode,status:u.status,blockers:u.blockers||[],count:(u.results||[]).length})}return{mode:$.SHADOW,status:"fleet",results:s}}var Lo=3,ql=2e3,Ul=4,$l=3,Dl=6e4,Fl=.5,Te=Object.freeze({OK:"ok",DEGRADED:"degraded",UNKNOWN:"unknown"}),To=Object.freeze({fresh:0,stale:1,down:2});function za(e,t,r=.5){return Number.isFinite(t)?e==null||!Number.isFinite(e)?t:r*t+(1-r)*e:e??null}function Ka(e,t=Math.random){let r=Math.min(1e3,50*2**Math.max(0,e-1)),n=t()*r*.5;return Math.round(r+n)}function Wa(e){if(!e||typeof e!="object")return{ok:!1,reason:"malformed probe response: not an object"};let{blockNumber:t,chainId:r,timestampMs:n}=e;return!Number.isInteger(t)||t<0?{ok:!1,reason:"malformed probe response: blockNumber must be a non-negative integer"}:r!=null&&(!Number.isFinite(r)||r<=0)?{ok:!1,reason:"malformed probe response: chainId must be a positive number"}:n!=null&&(!Number.isFinite(n)||n<0)?{ok:!1,reason:"malformed probe response: timestampMs must be a non-negative number"}:{ok:!0}}function Ga(e,t,r){let n=r(t).then(()=>{throw new Error(`rpc-health: probe timeout after ${t}ms`)});return n.catch(()=>{}),Promise.race([e,n])}async function Ja(e,t){let{probe:r,clock:n,sleep:o,rng:s,timeoutMs:i,maxRetries:a,backoff:c,latencyAlpha:u,previousLatencyEwmaMs:l,previousErrorRate:d,previousSamples:p}=t,f=1+a,m=0,h=0,b=l??null,w=null,A=null;for(let O=1;O<=f;O++){m=O;let v=n.now();try{let x=await Ga(r(e,{attempt:O,timeoutMs:i}),i,o),y=n.now()-v,k=Wa(x);if(!k.ok)h+=1,w=k.reason;else{b=za(b,y,u),A={blockNumber:x.blockNumber,chainId:x.chainId??null,timestampMs:x.timestampMs??null,latencyMs:y};break}}catch(x){h+=1,w=x?.message||String(x)}if(O<f){let x=c(O,s);await o(x)}}let C=(p??0)+m,T=d!=null&&p?d*p:0,E=C>0?(T+h)/C:0;return{id:e.id,endpoint:e,ok:A!=null,attempts:m,failures:h,errorRate:E,latencyEwmaMs:A?b:l??null,latencyMs:A?A.latencyMs:null,blockNumber:A?A.blockNumber:null,chainId:A?A.chainId:null,timestampMs:A?A.timestampMs:null,lastError:A?null:w,sampleCount:C}}async function Ya(e,t,r){let n=new Array(e.length),o=0;async function s(){for(;o<e.length;){let a=o++;n[a]=await r(e[a],a)}}let i=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:i},()=>s())),n}function Qa(e,{networkHeadBlock:t,maxHeadLagBlocks:r,maxHeadAgeMs:n,now:o}){if(!e.ok)return"down";let s=t!=null&&e.blockNumber!=null?t-e.blockNumber:null,i=s!=null&&s>r,a=e.timestampMs!=null&&o-e.timestampMs>n;return i||a?"stale":"fresh"}function Xa(e,t){let r=To[e.tier]-To[t.tier];if(r!==0)return r;let n=e.errorRate-t.errorRate;if(n!==0)return n;let o=e.headLagBlocks??1/0,s=t.headLagBlocks??1/0;if(o!==s)return o-s;let i=e.latencyEwmaMs??1/0,a=t.latencyEwmaMs??1/0;return i!==a?i-a:e.id<t.id?-1:e.id>t.id?1:0}async function Ro(e,t={}){if(!Array.isArray(e)||e.length===0)throw new Error("rankRpcEndpoints requires a non-empty array of endpoints");let{probe:r,clock:n={now:()=>Date.now()},sleep:o=y=>new Promise(k=>setTimeout(k,y)),rng:s=Math.random,timeoutMs:i=2e3,retries:a=3,concurrency:c=4,backoff:u=Ka,maxHeadLagBlocks:l=3,maxHeadAgeMs:d=6e4,latencyAlpha:p=.5,previousStats:f={}}=t;if(typeof r!="function")throw new Error("rankRpcEndpoints requires an injected probe(endpoint, ctx) function");let m=new Set;for(let y of e){if(!y||typeof y.id!="string"||!y.id)throw new Error("each RPC endpoint requires a stable string id");if(m.has(y.id))throw new Error(`duplicate RPC endpoint id: ${y.id}`);m.add(y.id)}let h=Math.min(Math.max(0,a),3),b=await Ya(e,c,y=>Ja(y,{probe:r,clock:n,sleep:o,rng:s,timeoutMs:i,maxRetries:h,backoff:u,latencyAlpha:p,previousLatencyEwmaMs:f[y.id]?.latencyEwmaMs??null,previousErrorRate:f[y.id]?.errorRate??null,previousSamples:f[y.id]?.sampleCount??0})),w=b.reduce((y,k)=>k.ok&&k.blockNumber!=null&&(y==null||k.blockNumber>y)?k.blockNumber:y,null),A=n.now(),T=[...b.map(y=>{let k=Qa(y,{networkHeadBlock:w,maxHeadLagBlocks:l,maxHeadAgeMs:d,now:A}),g=y.ok&&w!=null&&y.blockNumber!=null?w-y.blockNumber:null;return{...y,tier:k,headLagBlocks:g,costUnknown:!y.ok}})].sort(Xa),E=T.every(y=>y.tier==="down"),O=E?null:T[0],v=E?null:T[1]??null;return{status:E?Te.UNKNOWN:T.some(y=>y.tier!=="fresh")?Te.DEGRADED:Te.OK,networkHeadBlock:w,results:T,primary:O,backup:v,allDown:E}}var Po=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."})]);function Hl(e){return Po.find(t=>t.id===e)||null}function Vl(){return Po.filter(e=>e.status==="VERIFIED")}import Za from"node:os";import _o from"node:path";var Q="oracle.launch-radar.data-plane.v1",ec=200,tc=500,rc=100,nc=500;function Je(e){return String(e?.message||e||"unknown error").slice(0,300)}function oc(e={}){return e.configDir||process.env.ORACLE_CONFIG_DIR||_o.join(Za.homedir(),".config","oracle")}function sc(e={}){return e.storePath||process.env.LAUNCH_RADAR_STORE_PATH||_o.join(oc(e),"launch-radar","state.json")}function Ar(e,t,r){return Number.isSafeInteger(e)&&e>0?Math.min(e,r):t}function jo(e={}){let t=sc(e);try{return{ok:!0,path:t,state:So({path:t})}}catch(r){return{ok:!1,path:t,error:Je(r)}}}function Bo(){return process.env.ORACLE_AUTONOMOUS_TRADING==="1"}function ic(){return Object.freeze({schema:Q,evidence:"LIVE",mode:$.SHADOW,executionReady:!1,signingReady:!1,broadcastReady:!1,funded:!1,autonomousTradingEnvSet:Bo()})}function ac(e={},t={}){let r=jo(t),n={schema:Q,storePath:r.path,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,autonomousTradingEnvSet:Bo()};if(!r.ok)return Object.freeze({...n,evidence:"UNAVAILABLE",reason:r.error,mode:$.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})}function cc(e={},t={}){let r=jo(t);if(!r.ok)return Object.freeze({schema:Q,evidence:"UNAVAILABLE",reason:r.error,storePath:r.path,strategyStatus:null,cursor:null,candidates:[],evidenceRecords:[]});let{state:n}=r,o=Ar(e.limit,ec,tc),s=Ar(e.evidenceLimit,rc,nc);return Object.freeze({schema:Q,evidence:"LIVE",storePath:r.path,strategyStatus:structuredClone(n.strategyStatus),cursor:structuredClone(n.cursor),candidateCount:n.candidates.length,candidates:structuredClone(n.candidates.slice(0,o)),evidenceCount:n.evidence.length,evidenceRecords:structuredClone(n.evidence.slice(-s))})}async function uc(e={}){let t=Array.isArray(e.discoveries)?e.discoveries:[],r=Array.isArray(e.evaluations)?e.evaluations:[],n=Array.isArray(e.whyBlocked)?e.whyBlocked:[],o=typeof e.status=="string"&&e.status?e.status:t.length?"LIVE":"UNKNOWN",s=async()=>({status:o,cursor:e.cursor??null,discoveries:t,whyBlocked:n,unavailable:[]}),i=async({chainId:a,tokenAddress:c})=>{let u=r.find(l=>l?.chainId===a&&String(l?.tokenAddress||"").toLowerCase()===String(c||"").toLowerCase());return u?u.evaluation&&typeof u.evaluation=="object"?u.evaluation:u:{}};try{let a=await Ne({discover:s,evaluator:i,observedAt:e.observedAt}),c=a.status==="LIVE"?"LIVE":a.status==="UNAVAILABLE"?"UNAVAILABLE":"UNKNOWN";return{schema:Q,evidence:c,...a}}catch(a){return{schema:Q,evidence:"UNAVAILABLE",reason:Je(a),status:"UNKNOWN",cursor:null,unavailable:[],whyBlocked:[Je(a)],candidates:[]}}}async function lc(e={}){let t=Array.isArray(e.endpoints)?e.endpoints:[],r={schema:Q,evidence:"UNAVAILABLE",status:Te.UNKNOWN,networkHeadBlock:null,results:[],primary:null,backup:null,allDown:!0};if(t.length===0)return{...r,reason:"no endpoints supplied"};let n=e.samples&&typeof e.samples=="object"&&!Array.isArray(e.samples)?e.samples:{},o=async i=>{let a=n[i.id];if(!a||a.ok===!1)throw new Error(a?.error||`no probe sample supplied for endpoint "${i.id}"`);return a},s=Ar(e.retries,0,3);try{let i=await Ro(t,{probe:o,retries:s,concurrency:e.concurrency,maxHeadLagBlocks:e.maxHeadLagBlocks,maxHeadAgeMs:e.maxHeadAgeMs}),a=i.allDown?"UNAVAILABLE":i.status===Te.OK?"LIVE":"STALE";return{schema:Q,evidence:a,...i}}catch(i){return{...r,reason:Je(i)}}}function dc(e={}){try{let t=ze(e.strategy,e.observation,{});return{schema:Q,evidence:"LIVE",...t,autonomousEligible:!1,autonomousBlockers:[...new Set([...t.autonomousBlockers||[],"Launch Radar autonomous execution is not released"])],reportOnly:!0}}catch(t){let r=Je(t);return{schema:Q,evidence:"UNAVAILABLE",reason:r,mode:$.SHADOW,policyEligible:!1,blockers:[r],autonomousEligible:!1,autonomousBlockers:[r],reportOnly:!0}}}export{Br as ACTION_MODE,Pe as CANDIDATE_STATUS,Ul as DEFAULT_CONCURRENCY,Fl as DEFAULT_LATENCY_EWMA_ALPHA,Dl as DEFAULT_MAX_HEAD_AGE_MS,$l as DEFAULT_MAX_HEAD_LAG_BLOCKS,ts as DEFAULT_ROUTE_PROBE,rs as DEFAULT_SOLANA_ROUTE_PROBE,ql as DEFAULT_TIMEOUT_MS,Ec as EVIDENCE_GENESIS_DIGEST,wl as LAUNCH_RADAR_STORE_VERSION,Po as LAUNCH_RADAR_VENUES,Lo as MAX_RETRIES_CEILING,ll as PUMP_CREATE_DISCRIMINATOR,ul as PUMP_FUN_PROGRAM_ID,ba as RETRY_CEILING,uo as SNIPE_ACTION,Na as SOLANA_CHAIN_ID,lt as SOLANA_QUOTE_CHAIN_ID,Lu as SOLANA_QUOTE_MAX_SLIPPAGE_BPS,be as SOL_MINT,Te as STATUS,$ as STRATEGY_MODE,es as UNISWAP_V3_POOL_CREATED_EVENTS,Zo as UNISWAP_V3_POOL_CREATED_TOPIC0,Ic as VERIFIED_UNISWAP_V3_FACTORIES,qr as actionModeFor,Xe as appendEvidence,Ac as appendEvidenceProjection,ir as bestSolanaShadowSwapRoute,Ho as classifyCandidate,za as computeEwma,Sc as createEvidenceProjection,Ha as createInstalledShadowRunner,We as createLaunchRadarRunner,yl as createLaunchRadarStore,rl as createShadowRunner,Ao as createSolanaLaunchScanner,to as createSolanaQuoteScanner,Ve as createStrategy,Wu as createStrategyPolicy,Ka as defaultBackoffMs,yc as discoverFactoryLaunches,Ot as discoverLaunches,go as discoverSolanaLaunches,ko as evaluateInstalledDiscovery,fo as evaluateSnipeFeatures,ze as evaluateStrategy,Gu as evaluateStrategyPolicy,uc as launchRadarCandidates,dc as launchRadarEvaluateStrategy,ic as launchRadarHealth,lc as launchRadarRpcHealth,cc as launchRadarSnapshot,ac as launchRadarStatus,Hl as launchRadarVenue,Nr as normalizeCandidate,kr as normalizeCandidates,Ku as normalizeStrategy,gt as openLaunchRadarStore,il as orchestrateLaunchRadar,Qe as projectEvidence,Nc as pumpFunFactoryDescriptor,Ro as rankRpcEndpoints,Yu as rankSnipeCandidates,So as readLaunchRadarStore,jl as runInstalledShadowFleet,Ne as runLaunchRadar,nl as runLaunchRadarShadowCycle,Ze as shouldPrepare,Ur as shouldQueue,Aa as strategyDigest,xc as uniswapV3FactoryDescriptor,Vl as verifiedLaunchRadarVenues};
|