@oracle-agent/oracle 0.35.49 → 0.35.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/artifacts/specialist-packs/oracle-full-crypto.json +11 -0
- package/dist/agent-sessions.mjs +19 -19
- package/dist/artifacts/token-dashboard.mjs +1 -1
- package/dist/assets/profiles/near-agent/SOUL.md +46 -0
- package/dist/assets/profiles/near-agent/profile.json +30 -0
- package/dist/assets/profiles/oracle/SOUL.md +1 -0
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/assets/skills/oracle-near/SKILL.md +66 -0
- package/dist/automation-plan.mjs +1 -1
- package/dist/bin/desk-server.mjs +33 -33
- package/dist/bin/oracle-data-mcp.mjs +16 -16
- package/dist/bin/oracle-gateway.mjs +3 -3
- package/dist/bin/oracle-launch-radar-shadow.mjs +3 -3
- package/dist/bin/oracle-mev-arb-shadow.mjs +4 -4
- package/dist/bin/oracle-mev-shadow.mjs +4 -4
- package/dist/bin/oracle-public-server.mjs +5 -5
- package/dist/bin/oracle-route.mjs +27 -27
- package/dist/bin/oracle-scan.mjs +3 -3
- package/dist/bin/oracle-telegram-mcp.mjs +1 -1
- package/dist/chains.mjs +1 -1
- package/dist/cli/commands/account.mjs +22 -22
- package/dist/cli/commands/agent-session.mjs +23 -23
- package/dist/cli/commands/auth.mjs +16 -15
- package/dist/cli/commands/chain.mjs +5 -5
- package/dist/cli/commands/chat.mjs +310 -228
- package/dist/cli/commands/data.mjs +37 -37
- package/dist/cli/commands/doctor.mjs +5 -5
- package/dist/cli/commands/eval.mjs +249 -167
- package/dist/cli/commands/farm.mjs +1 -1
- package/dist/cli/commands/follow.mjs +4 -4
- package/dist/cli/commands/harness.mjs +6 -6
- package/dist/cli/commands/mint.mjs +11 -11
- package/dist/cli/commands/model.mjs +313 -231
- package/dist/cli/commands/project.mjs +8 -7
- package/dist/cli/commands/quickstart.mjs +2 -2
- package/dist/cli/commands/receipt.mjs +2 -2
- package/dist/cli/commands/resolve.mjs +4 -4
- package/dist/cli/commands/session-vault.mjs +4 -4
- package/dist/cli/commands/setup.mjs +53 -52
- package/dist/cli/commands/snipe.mjs +13 -13
- package/dist/cli/commands/strategy.mjs +5 -5
- package/dist/cli/commands/swap.mjs +11 -11
- package/dist/cli/commands/telegram.mjs +7 -7
- package/dist/cli/commands/venues.mjs +1 -1
- package/dist/cli/project-access.mjs +4 -3
- package/dist/data/desk-data.mjs +31 -31
- package/dist/data/holder-table.mjs +2 -2
- package/dist/data/market-tape.mjs +1 -1
- 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 +49 -49
- package/dist/launch-radar/index.mjs +5 -5
- package/dist/lp/index.mjs +4 -4
- package/dist/nft/universal-mint-router.mjs +4 -4
- package/dist/notifications/index.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 +3 -3
- package/dist/strategy/index.mjs +4 -4
- package/dist/task.mjs +1 -1
- package/dist/teams/index.mjs +6 -6
- package/dist/telegram/chart-card.mjs +5 -5
- package/dist/telegram/market-commands.mjs +1 -1
- package/dist/tui/standalone-client.mjs +179 -97
- package/package.json +2 -2
- package/public/oracle-splash/docs/browser-and-web/index.html +2 -2
- package/public/oracle-splash/docs/connectors/index.html +2 -2
- package/public/oracle-splash/docs/getting-started/index.html +2 -2
- package/public/oracle-splash/docs/index.html +3 -3
- package/public/oracle-splash/docs/reference/index.html +2 -2
- package/public/oracle-splash/docs/security/index.html +2 -2
- package/public/oracle-splash/docs/using-oracle/index.html +2 -2
- package/public/oracle-splash/download/index.html +3 -3
- package/public/oracle-splash/downloads/index.html +1 -1
- package/public/oracle-splash/eval/index.html +19 -19
- package/public/oracle-splash/eval/releases/oracle-0.35.49.json +852 -0
- package/public/oracle-splash/index.html +9 -9
- package/server.json +2 -2
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
var Es=Object.defineProperty;var z=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Ze=(e,t)=>{for(var r in t)Es(e,r,{get:t[r],enumerable:!0})};import{AsyncLocalStorage as js}from"node:async_hooks";function rt(e){let t=Bs.getStore();if(!t||t.closed||!$s.includes(e))return null;if(t.spans.length>=qs)return t.droppedSpans++,null;let r={stage:e,startMs:t.now()-t.start,durationMs:null,outcome:"pending",status:null};return t.spans.push(r),(n,o=null)=>{t.closed||r.durationMs!==null||(r.durationMs=Math.max(0,t.now()-t.start-r.startMs),r.outcome=n==="succeeded"?"succeeded":"failed",r.status=Number.isInteger(o)&&o>=100&&o<=599?o:null)}}var Bs,$s,qs,pn=z(()=>{Bs=new js,$s=["http","retry","shared"],qs=512});import fe from"node:net";import Us from"node:dns";function nt(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 Rt(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 Lt(e){if(fe.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(fe.isIPv6(e)){let t=nt(e);if(!t)return!1;let r=nt("::ffff:0:0");return Rt(t,r,96)?Lt([...t.slice(12)].join(".")):Rt(t,nt("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([o,s])=>Rt(t,nt(o),s)):!1}return!1}function Fs(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(Ds.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=fe.isIP(r);return n!==0&&!Lt(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function _t(e,{lookupFn:t=Us.promises.lookup}={}){let r=Fs(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:fe.isIPv6(r.host)?6:4}]};let n;if(process.env.ORACLE_HOSTED_EGRESS_PROXY)return{ok:!0,url:r.url,addresses:[]};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=>!Lt(o.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}function Ms(e=process.env){let t=e.ORACLE_HOSTED_EGRESS_PROXY||"";if(!t)return null;let r;try{r=new URL(t)}catch{throw new Error("egress-guard: ORACLE_HOSTED_EGRESS_PROXY is not a URL")}if(r.protocol!=="http:"||!["127.0.0.1","::1","localhost","[::1]"].includes(r.hostname)||!r.port||r.username||r.password)throw new Error("egress-guard: egress proxy must be an exact loopback http origin");let n=e.ORACLE_HOSTED_EGRESS_TOKEN||"";if(!/^[A-Za-z0-9_-]{43}$/.test(n))throw new Error("egress-guard: egress proxy token is missing");return{uri:r.origin,token:n}}async function Pt({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n,o;try{o=await t(),r=o.Agent,n=o.fetch}catch(f){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${f?.message||f}`);return null}if(typeof r!="function"||typeof n!="function"){if(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 s=f=>String(f).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),i=new Map,a=f=>(Array.isArray(f)?f:[f]).map(m=>typeof m=="string"?{address:m}:m).filter(m=>m&&m.address).map(m=>({address:m.address,family:m.family||(fe.isIPv6(m.address)?6:4)})),c=(f,m,h)=>{i.set(s(f),a(typeof m=="string"?[{address:m,family:h}]:m))},u=f=>{let m=s(f);if(fe.isIP(m))return[{address:m,family:fe.isIPv6(m)?6:4}];let h=i.get(m);if(!h||!h.length)throw new Error(`refused: unpinned host ${f} during pinned fetch`);return h},l=Ms(),d=l&&typeof o.ProxyAgent=="function"?new o.ProxyAgent({uri:l.uri,token:`Bearer ${l.token}`,connectTimeout:1e4}):new r({connect:{lookup(f,m,h){let y;try{y=u(f)}catch(g){return h(g)}return m?.all?h(null,y):h(null,y[0].address,y[0].family)}}}),p=Hs((f,m={})=>n(f,{...m,dispatcher:d}),c);return{dispatcher:d,fetch:p,pin:c,resolve:u,async close(){try{await d.destroy()}catch{}}}}function Hs(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[jt]=Object.freeze({pin:t}),e}function Bt(e){return typeof e=="function"&&typeof e[jt]?.pin=="function"}function mn(e,t,r){if(!Bt(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[jt].pin(t,r)}var Ds,jt,hn=z(()=>{Ds=new Set(["localhost","metadata.google.internal","metadata.goog"]);jt=Symbol.for("oracle.egressGuard.pinCapableFetch")});import{createHash as Vs}from"node:crypto";import{types as ee}from"node:util";function P(e){return se(`HTTP JSON body refused: ${e}`)}function Zs(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 ei(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 P("serialized byte limit exceeded");t.push(l)},c=l=>{if(Buffer.byteLength(l,"utf8")>Z.bytes)throw P("serialized byte limit exceeded");return JSON.stringify(l)},u=(l,d)=>{if(n+=1,n>Z.nodes)throw P("node limit exceeded");if(d>Z.depth)throw P("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 P("non-finite number");a(Object.is(l,-0)?"0":String(l));return}if(typeof l!="object")throw P("unsupported non-JSON value");if(ee.isProxy(l))throw P("proxy value");if(Zs(l))throw P("unsupported exotic object");if(i.has(l))throw P("cyclic value");i.add(l);try{if(Object.getOwnPropertySymbols(l).length>0)throw P("symbol-keyed fields are unsupported");if(Array.isArray(l)){let m=Object.getPrototypeOf(l),h=0;for(;m!==null;){if(ee.isProxy(m))throw P("proxy array prototype");if(h+=1,h>Z.depth)throw P("array prototype depth limit exceeded");m=Object.getPrototypeOf(m)}if(l.length>Z.arrayLength)throw P("array length limit exceeded");for(let g=0;g<l.length;g+=1){let v=Object.getOwnPropertyDescriptor(l,String(g));if(!v||!Object.hasOwn(v,"value")||v.enumerable!==!0)throw P("array entries must be dense enumerable own data")}let y=0;for(let g in l){if(s+=1,s>Z.fields)throw P("enumeration limit exceeded");if(Object.hasOwn(l,g)&&(y+=1,y>l.length))throw P("named array fields are unsupported")}if(y!==l.length)throw P("array entries must be dense enumerable own data");a("[");for(let g=0;g<l.length;g+=1)g&&a(","),u(Object.getOwnPropertyDescriptor(l,String(g)).value,d+1);a("]");return}let p=Object.getPrototypeOf(l);if(p!==Object.prototype&&p!==null)throw P("non-plain object");let f=[];for(let m in l){if(s+=1,s>Z.fields)throw P("enumeration limit exceeded");if(!Object.hasOwn(l,m))continue;if(o+=1,o>Z.fields)throw P("field limit exceeded");let h=Object.getOwnPropertyDescriptor(l,m);if(!h||!Object.hasOwn(h,"value")||h.enumerable!==!0)throw P("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 ti(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 ri(){return Object.assign(Object.create(null),{Accept:"application/json"})}function ni(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 oi(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function ot(e){if((typeof e!="object"||e===null)&&typeof e!="function")return`${typeof e}:${String(e)}`;let t=An.get(e);return t||(t=En,En+=1,An.set(e,t)),`reference:${t}`}function Sn(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?si.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 vn(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(Sn);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return Sn(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&ii.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function ai(e,t,r,n={},o=null){let s=Vs("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(`
|
|
3
|
-
`)};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 ci(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,bn):Math.min(250*2**e,bn)+Math.floor(Math.random()*100)}function se(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function qt(e,t,r){return se(`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 li(e){return e?e.byteLength??e.length??0:0}async function di(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 qt(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 qt(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+=li(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 qt(r,`streamed ${c} bytes`,t);let l=Buffer.concat(a);return(u?l.subarray(0,t):l).toString("utf8")}function fi(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function pi(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=st}){let y=null,g=t,v=i?{lookupFn:i}:{};if(c&&!a&&!Bt(g))throw se(`HTTP refused ${e}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let N=new AbortController,L=setTimeout(()=>N.abort(),s),A=f?gn?gn([f,N.signal]):f:N.signal,I=async(E,{status:k=null}={})=>{let O=await _t(E,v);if(!O.ok)throw se(k==null?`HTTP refused ${E}: ${O.error}`:`HTTP redirect to ${E} ${O.error}`,k==null?{}:{status:k});let _=new URL(E).hostname;if(a){if(y&&(await y.close(),y=null),!y)try{y=await Pt({requireUndici:!0,...d?{importUndici:d}:{}})}catch(b){throw se(k==null?`HTTP refused ${E}: ${b?.message||b}`:`HTTP redirect to ${E} refused: ${b?.message||b}`,k==null?{}:{status:k})}y.pin(_,O.addresses),g=y.fetch}else mn(g,_,O.addresses);return O};try{let E=String(e),k=Object.assign(Object.create(null),n||{});c&&await I(E);for(let O=0;O<=h;O+=1){let _=Object.assign(Object.create(null),{method:r,headers:k,body:o,signal:A,redirect:"manual",dispatcher:void 0}),b=await g(E,_);if((m==="error"||h===0)&&b.status>=300&&b.status<400)throw pe(b),se(`HTTP ${b.status} ${r} redirect refused`,{status:b.status,redirectRefused:!0});if(Xs.has(b.status)){let T=l===!0&&r==="POST"&&[307,308].includes(b.status)&&vn(r,o);if(r!=="GET"&&r!=="HEAD"&&!T){pe(b);let B=new Error(`HTTP ${b.status} ${r} ${E} redirected non-idempotent request`);throw B.status=b.status,B}if(O===h)throw pe(b),se(`HTTP ${b.status} ${r} redirect budget exhausted`,{status:b.status,redirectRefused:!0});let oe=b.headers?.get?.("location"),V;try{V=ni(oe,E)}catch(B){throw pe(b),B}let ue=!oi(V,E);if(pe(b),ue&&r==="POST"){let B=new Error(`HTTP ${b.status} ${r} cross-origin redirect refused`);throw B.status=b.status,B}if(ue&&l){let B=new Error(`HTTP ${b.status} ${r} cross-origin redirect refused`);throw B.status=b.status,B.retryable=!1,B}if(ue&&(k=ri(k)),c)await I(V,{status:b.status});else if(ue){let B=await _t(V,v);if(!B.ok){let R=new Error(`HTTP redirect from ${E} ${B.error}`);throw R.status=b.status,R.retryable=!1,R}a&&B.addresses?.length&&(y||(y=await Pt(d?{importUndici:d}:{})),y&&(y.pin(new URL(V).hostname,B.addresses),g=y.fetch))}E=V;continue}if(typeof p=="function")try{await p(b,{url:E})}catch(T){throw pe(b),se(T?.message||String(T))}let $=await di(b,u,{url:E,onOversize:()=>N.abort()}),w=fi($);if(!b.ok){let T=new Error(`HTTP ${b.status} ${r} ${E}`);throw T.status=b.status,T.retryAfter=b.headers?.get?.("retry-after")??null,T.body=w??$.slice(0,300),T}return w??$}throw new Error(`HTTP redirect loop for ${e}`)}catch(E){if(N.signal.aborted&&!Ue(f)){let k=E&&(typeof E=="object"||typeof E=="function")&&!ee.isProxy(E)?E:null,O=k?Object.getOwnPropertyDescriptor(k,"oversize"):null;if(!(O&&Object.hasOwn(O,"value")&&O.value===!0))try{if(!k)throw new TypeError("unsafe rejection");Object.defineProperties(k,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let b=new Error("HTTP request timed out");throw Object.defineProperties(b,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),b}}throw E}finally{clearTimeout(L),y&&await y.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 R of Object.getOwnPropertyNames(t)){let C=Object.getOwnPropertyDescriptor(t,R);if(!(R==="toJSON"&&C&&Object.hasOwn(C,"value")&&C.value===void 0)){if(!r.has(R))throw new TypeError("HTTP options contain unknown fields");if(!C||!C.enumerable||!Object.hasOwn(C,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=R=>{if(t==null||!Object.hasOwn(t,R))return;let C=Object.getOwnPropertyDescriptor(t,R);if(!C||!Object.hasOwn(C,"value"))throw new TypeError("HTTP options must contain own data properties");return C.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>st))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${st}`);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??st;for(let R of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let C=n(R);if(C!==void 0&&typeof C!="boolean")throw new TypeError(`HTTP ${R} 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{Ue(p)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let R of["importUndici","lookupFn","validateResponse"]){let C=n(R);if(C!==void 0&&typeof C!="function")throw new TypeError(`HTTP ${R} 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,y=(o||"GET").toUpperCase(),g=n("headers"),v=ti(g),N=Object.assign(Object.create(null),v);Object.keys(N).some(R=>R.toLowerCase()==="accept")||(N.Accept="application/json");let L=n("body");L!=null&&typeof L!="string"&&(Object.keys(N).find(C=>C.toLowerCase()==="content-type")||(N["Content-Type"]="application/json"),L=ei(L));let A=i??Ks,I=n("lookupFn"),E=!f,k=n("untrustedUrl")===!0,O=n("sameOriginRedirectsOnly")===!0,_=n("importUndici"),b=n("validateResponse"),$=p,w=d??null,T=async()=>{let R;for(let C=0;C<=A;C++){$&&Js.call($);let Vr=rt("http");try{let Q=await pi(e,{fetchImpl:m,method:y,headers:N,body:L,timeoutMs:h,lookupFn:I,realFetch:E,untrustedUrl:k,maxResponseBytes:w,sameOriginRedirectsOnly:O,importUndici:_,validateResponse:b,signal:$,redirectPolicy:u,maxRedirects:l});return Vr?.("succeeded"),Q}catch(Q){R=Q;let Ie=xt=>{if(!Q||typeof Q!="object"&&typeof Q!="function"||ee.isProxy(Q))return;let je=Object.getOwnPropertyDescriptor(Q,xt);return je&&Object.hasOwn(je,"value")?je.value:void 0},Xe=Ie("status");Vr?.("failed",Xe);let bs=Ie("oracleTimeout")===!0||Ie("name")==="AbortError"||Ie("name")==="TimeoutError"||Ue($),ws=new Set([408,425,429]),gs=Ie("retryable")===!1?!1:Xe!=null?ws.has(Xe)||zs.has(Xe)&&yn.has(y):!bs&&yn.has(y);if(C===A||!gs)throw Q;let zr=ci(C,Ie("retryAfter")),As=rt("retry"),Kr=!1;try{$?await new Promise((xt,je)=>{let Wr,Be=()=>{clearTimeout(Wr),wn.call($,"abort",Be),je(Qs($)||new DOMException("Aborted","AbortError"))};if(Ue($)){Be();return}Wr=setTimeout(()=>{wn.call($,"abort",Be),xt()},zr),Ys.call($,"abort",Be,{once:!0}),Ue($)&&Be()}):await ui(zr),Kr=!0}finally{As?.(Kr?"succeeded":"failed")}}}throw R};if(!(n("dedupe")!==!1&&!$&&vn(y,L)))return T();let V=ai(y,e,N,{untrustedUrl:k,maxResponseBytes:w,sameOriginRedirectsOnly:O,redirectPolicy:u,maxRedirects:l,timeoutMs:h,retries:A,fetchImpl:ot(m),realFetch:E,lookupFn:ot(I),importUndici:ot(_),validateResponse:ot(b)},L),ue=$t.get(V);if(ue){let R=rt("shared");try{let C=await ue;return R?.("succeeded"),C}catch(C){throw R?.("failed"),C}}let B=T().finally(()=>$t.delete(V));return $t.set(V,B),B}async function In(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 zs,yn,Ks,bn,Ws,Gs,Js,Ys,wn,gn,Ue,Qs,Xs,st,vu,Z,$t,An,En,si,ii,ui,xe=z(()=>{pn();hn();zs=new Set([408,425,429,500,502,503,504]),yn=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Ks=2,bn=4e3,Ws=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Gs=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Js=AbortSignal.prototype.throwIfAborted,Ys=EventTarget.prototype.addEventListener,wn=EventTarget.prototype.removeEventListener,gn=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,Ue=e=>e?Ws.call(e):!1,Qs=e=>e?Gs.call(e):void 0,Xs=new Set([301,302,303,307,308]),st=3,vu=64*1024,Z=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});$t=new Map,An=new WeakMap,En=1;si=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),ii=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);ui=e=>new Promise(t=>setTimeout(t,e))});import{types as Zt}from"node:util";function er(e){if(!e||typeof e!="object"||Zt.isProxy(e)||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ut(e,t){if(e==null||(typeof e=="object"||typeof e=="function")&&Zt.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 ct(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(Zt.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]=ct(i.value,t,r+1)}return o}if(!er(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]=ct(s.value,t,r+1)}return n}var ao=z(()=>{});function na(e={}){return String(e.rpcUrl||process.env.SOLANA_RPC_URL||ra).trim()}function ke(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 co(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=ct(await te(na(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(!er(o))throw new Error(`solana-rpc ${e}: invalid response envelope`);let s=ut(o,"error");if(s)throw new Error(`solana-rpc ${e}: ${ut(s,"message")||JSON.stringify(s)}`);if(!Object.hasOwn(o,"result"))throw new Error(`solana-rpc ${e}: missing result`);return ut(o,"result")}var ra,tr=z(()=>{xe();ao();ra="https://api.mainnet-beta.solana.com"});import{createHash as oa,createHmac as sa,timingSafeEqual as yl}from"node:crypto";function rr(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(rr).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${rr(e[r])}`).join(",")}}`}function uo(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function lo(e=process.env){return uo(process.env)||uo(e)}function ua(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function nr(e){let t=ua(e);return oa("sha256").update(rr(t)).digest("hex")}function or(e,t=lo()){return t?sa("sha256",t).update(String(e)).digest("hex"):""}function fo(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+aa:Number(s),l=u-c;if(!Number.isSafeInteger(c)||!Number.isSafeInteger(u)||l<=0||l>ca)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let p={...a,preparedAt:c,expiresAt:u,prepareVersion:ia},f=nr(p),m=lo(n),h=m?or(f,m):void 0,y={...p,prepareHash:f};return h&&(y.prepareMac=h),y}var ia,aa,ca,sr=z(()=>{ia=2,aa=300*1e3,ca=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});function ir(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function pa(e){return la.some(t=>e.startsWith(t))||da.has(e)}function ma(e){let t=String(e);if(!/^[\x20-\x7e]+$/.test(t))return!0;let r=ir(t);return pa(r)?!1:fa.has(r)?!0:r.includes("signed")||r.includes("signature")||r.endsWith("sig")||r.endsWith("sigs")}function ha(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 ar(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=>ar(c,t+1,r,n));let o=[];for(let[c,u]of Object.entries(e)){if(ma(c)){o.push(c);continue}o.push(...ar(u,t+1,r,n))}let i=Object.keys(e).map(ir).some(c=>c.endsWith("psbt")||c.endsWith("psbtbase64")),a=Object.entries(e).some(([c,u])=>/complete|finalized|isfinal/.test(ir(c))&&u===!0);return i&&a&&o.push("psbt(complete)"),ha(e)&&o.push("v/r/s"),o}function po(e,t){let r=ar(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 la,da,fa,mo=z(()=>{la=["unsigned","notsigned","tosign","signable"],da=new Set(["requiresusersignature","requiressignature","needssignature","signaturerequired","signaturesrequired","signingready","signaturecount","signaturethreshold","requiredsignatures","signatureneeded","hassignature","allowsignatures","requestsignature","multisig","cosig","msig"]),fa=new Set(["sig","sigs","scriptsig","witness","psbt","finalizedpsbt","completepsbt","finalpsbt","psbtfinalized","serializedtransaction"])});var lr={};Ze(lr,{JUPITER_MAX_SLIPPAGE_BPS:()=>bo,JUPITER_SWAP_API:()=>ze,SOL_MINT:()=>ft,USDC_MINT:()=>cr,jupiterHealth:()=>Ea,jupiterPrepareSwap:()=>va,jupiterQuote:()=>ur,jupiterSignerEnvelope:()=>Eo,jupiterVenues:()=>Aa,solanaGuard:()=>dt});function wo(e={}){return String(e.baseUrl||process.env.JUPITER_SWAP_API_URL||ze).replace(/\/$/,"")}function Ke(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 go(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>bo)throw new Error("jupiter: slippage exceeds hard 100 bps cap");return t}function lt(e,t){return e==null?t:!!e}function ya(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 ba(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 Ao(e){let t=Buffer.from(e,"base64"),r=ba(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 dt(e={},{quotedAtMs:t=Date.now(),ttlMs:r=ho}={}){let n=ke(e.inputMint,"inputMint"),o=ke(e.outputMint,"outputMint"),s=Ke(e.inAmount,"inAmount"),i=Ke(e.outAmount,"outAmount"),a=Ke(e.otherAmountThreshold??e.outAmount,"otherAmountThreshold"),c=go(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)||ho,1e3),3e4)}}function Eo({userPublicKey:e,guard:t,swapTransaction:r,args:n={},response:o={}}){if(t.inputMint!==ft)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=Ao(r),i=Ke(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 yo(e){if(typeof e!="string"||!e.length)return!1;let t=0n;for(let o of e){let s=ga.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 Aa(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(`${ze}/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])=>yo(p)),c=[],u=i.filter(([p])=>!yo(p)).map(([p,f])=>({programId:p,label:f,reason:"malformed program id"}));if(e.verify===!1)return{source:`${ze}/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(([y])=>y),{encoding:"base64",dataSlice:{offset:0,length:0}}]})}catch{await new Promise(y=>setTimeout(y,2e3*(h+1)))}if(!m){for(let[h,y]of f)u.push({programId:h,label:y,reason:"rpc batch failed after 3 attempts"});continue}m.value.forEach((h,y)=>{let[g,v]=f[y];h&&h.executable===!0&&wa.has(h.owner)?c.push({programId:g,label:v,owner:h.owner}):u.push({programId:g,label:v,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:`${ze}/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 Ea(e={}){try{return{ok:!0,provider:"jupiter",outAmount:(await ur({inputMint:ft,outputMint:cr,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 ur(e={},t={}){let r=ke(e.inputMint||e.fromMint||ft,"inputMint"),n=ke(e.outputMint||e.toMint||cr,"outputMint"),o=Ke(e.amount||e.inAmount,"amount"),s=go(e.slippageBps??e.maxSlippageBps??50),i=new URL(`${wo(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=dt({...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 Sa(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function va(e={},t={}){let r=ke(e.userPublicKey||e.owner||e.wallet,"userPublicKey"),n=e.quoteResponse?{quote:e.quoteResponse,solanaGuard:dt(e.quoteResponse,t)}:await ur(e,t),o=n.quote,s=n.solanaGuard||dt(o,t);if(lt(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(`${wo(t)}/swap`,{method:"POST",body:Sa({quoteResponse:o,userPublicKey:r,wrapAndUnwrapSol:lt(e.wrapAndUnwrapSol,!0),dynamicComputeUnitLimit:lt(e.dynamicComputeUnitLimit,!0),dynamicSlippage:!1,asLegacyTransaction:lt(e.asLegacyTransaction,!0),prioritizationFeeLamports:e.prioritizationFeeLamports??0}),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),a=ya(i?.swapTransaction);Ao(a),po("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=Eo({userPublicKey:r,guard:s,swapTransaction:a,args:e,response:i})}catch(f){p=String(f?.message||f).slice(0,200)}return fo({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 ze,ft,cr,bo,ho,wa,ga,dr=z(()=>{xe();tr();sr();mo();ze="https://lite-api.jup.ag/swap/v1",ft="So11111111111111111111111111111111111111112",cr="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",bo=100,ho=2e4;wa=new Set(["BPFLoaderUpgradeab1e11111111111111111111111","BPFLoader2111111111111111111111111111111111","BPFLoader1111111111111111111111111111111111"]),ga="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});var Io={};Ze(Io,{SELL_SIM:()=>q,assertSellable:()=>Na,simulateSell:()=>vo});function xa(e,t){return t===0n?null:Number((t-e)*10000n/t)}function ka(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 vo(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=ka(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: ${fr(f)}`,{chainId:o,token:r,base:n})}let a=So(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 (${fr(f)}) \u2014 you would not be able to exit`,{chainId:o,token:r,base:n,tokensOut:a.toString()})}let u=So(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=xa(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=fr(f)}return p===!0&&(d.evidence="execution"),l==null?Y(q.UNKNOWN,"could not compute round-trip loss",d):l>=Ia?Y(q.HONEYPOT,`round trip loses ${(l/100).toFixed(1)}% \u2014 a sell tax or rigged curve, not normal slippage`,d):l>=Oa?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 So(e){if(e==null)return null;try{let t=String(e).trim();return/^\d+$/.test(t)?BigInt(t):null}catch{return null}}function fr(e){return String(e?.message||e).slice(0,120)}async function Na(e={},t={}){let r=await vo(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,Ia,Oa,Oo=z(()=>{q=Object.freeze({SAFE:"SAFE",CAUTION:"CAUTION",HONEYPOT:"HONEYPOT",UNKNOWN:"UNKNOWN"}),Ia=5e3,Oa=1500});import pt from"node:fs";import La from"node:os";import Ce from"node:path";import{fileURLToPath as _a}from"node:url";function To(){return process.env.ORACLE_FAKE_HOME||La.homedir()}function ja(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function mt(){return ja()?process.env.ORACLE_CONFIG_DIR||Ce.join(To(),".config","oracle"):Ce.join(To(),".config","oracle")}function Ba(){return Ce.join(mt(),"desk.json")}function $a(){return Ce.join(mt(),"env")}function Ne({force:e=!1}={}){if(Ne._done&&!e)return Ne._result||null;Ne._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=$a();if(pt.existsSync(o))for(let s of pt.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=Ba();if(pt.existsSync(o)){let s=JSON.parse(pt.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)),Ne._result=Object.keys(t).length?t:null,Ne._result}var Pa,Nl,Ro=z(()=>{Pa=Ce.dirname(_a(import.meta.url)),Nl=Ce.resolve(Pa,"../..");try{Ne()}catch{}});function mr(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(Ma.test(e)||Ha.has(o.length)&&o.every(s=>/^[a-z]+$/i.test(s)))throw new ht(t);return e}if(typeof e=="bigint")return e.toString();if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new TypeError(`sign-time review: safe integer required at ${t}`);return e}if(Array.isArray(e))return e.map((o,s)=>mr(o,`${t}[${s}]`,r));we(e,t);let n={};for(let o of Object.keys(e).sort()){let s=o.replace(/[^a-z0-9]/gi,"");if(Fa.test(s))throw new ht(`${t}.${o}`);e[o]!==void 0&&(n[o]=mr(e[o],`${t}.${o}`,o))}return n}function we(e,t){if(e==null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`sign-time review: ${t} must be a plain object`);return e}function We(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function Te(e,t){let r=String(We(e,t)).toLowerCase();if(!qa.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function ne(e,t,{positive:r=!1}={}){try{let n=BigInt(We(e,t));if(n<0n||r&&n===0n)throw new Error;return n.toString()}catch{throw new TypeError(`sign-time review: ${t} must be an unsigned integer`)}}function hr(e,t){if(typeof e!="string"||e.length===0||e.length>500||e!==e.trim())throw new TypeError(`sign-time review: ${t} must be non-empty text`);return e}function Lo(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Lo(t);Object.freeze(e)}return e}function Va(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};we(e,t);let r=e.passed??e.ok??e.allowed;if(typeof r!="boolean")throw new TypeError(`sign-time review: ${t} needs a boolean result`);let n=e.reason??e.message??e.name??(r?"passed":"failed");return{...e,passed:r,reason:hr(String(n),`${t}.reason`)}}function za(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>Va(n,`policyChecks[${o}]`)),r=t.filter(n=>!n.passed);return{checks:t,passed:t.length-r.length,failed:r.length,reasons:r.map(n=>n.reason)}}function Ka(e){if(e==null)return null;if(we(e,"simulation"),typeof e.status!="string"||!["ok","success","failed","error","unavailable","unknown"].includes(e.status))throw new TypeError("sign-time review: simulation.status is invalid");if(e.willRevert!==!0&&e.willRevert!==!1&&e.willRevert!==null)throw new TypeError("sign-time review: simulation.willRevert must be boolean or null");let t={status:e.status,willRevert:e.willRevert??null,summary:hr(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=ne(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=ne(e.gasLimit,"simulation.gasLimit")),t}function Wa(e){if(e==null)return null;if(!Array.isArray(e)||e.length===0)throw new TypeError("sign-time review: assetDeltas must be a non-empty array");return e.map((t,r)=>{we(t,`assetDeltas[${r}]`);let n=ne(t.before,`assetDeltas[${r}].before`),o=ne(t.after,`assetDeltas[${r}].after`),s=(BigInt(o)-BigInt(n)).toString(),i;try{i=t.delta==null?s:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(i!==s)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:hr(String(We(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:i}})}function Ga(e){if(e==null)return[];if(!Array.isArray(e))throw new TypeError("sign-time review: approvalDeltas must be an array");return e.map((t,r)=>{we(t,`approvalDeltas[${r}]`);let n=ne(t.amount??t.after,`approvalDeltas[${r}].amount`);if(t.revokeLike!=null&&typeof t.revokeLike!="boolean")throw new TypeError(`sign-time review: approvalDeltas[${r}].revokeLike must be boolean`);return{token:Te(t.token,`approvalDeltas[${r}].token`),spender:Te(t.spender,`approvalDeltas[${r}].spender`),owner:Te(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function _o(e={}){we(e,"input");let t=mr(e),r=t.tx==null?t:we(t.tx,"tx"),n=ne(t.chainId??r.chainId,"chainId",{positive:!0}),o=Te(t.account??t.from??r.from,"account/from"),s=Te(t.destination??t.to??r.to,"destination/to"),i=String(We(t.prepareHash,"prepareHash")).toLowerCase();if(!Da.test(i))throw new TypeError("sign-time review: prepareHash must be a 32-byte hash");let a=t.route??t.venue;if(a==null)throw new TypeError("sign-time review: route/venue required");let c=t.decodedCalldata??t.decodedAction;if(c==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let u=String(We(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!Ua.test(u))throw new TypeError("sign-time review: calldata/data must be even-length hex");let l=t.policyChecks!==void 0&&t.policyChecks!==null,d=za(l?t.policyChecks:[]),p=Ka(t.simulation),f=Wa(t.assetDeltas),m=Ga(t.approvalDeltas),h=t.allowlistHits??[];if(!Array.isArray(h))throw new TypeError("sign-time review: allowlistHits must be an array");let y=p?.willRevert===!0||["failed","error"].includes(p?.status),g=p!=null&&p.willRevert===!1&&["ok","success"].includes(p.status),v=y||d.failed>0?"BLOCKED":g&&l&&d.checks.length>0&&f!=null?"READY":"UNKNOWN",N=typeof c=="string"?c:c.method??c.action??c.type??"transaction",L=`${v}: review ${N} on chain ${n}; policy ${d.passed} passed, ${d.failed} failed; ${f?.length??0} asset delta${f?.length===1?"":"s"}; local signature required`,A={reviewVersion:1,status:v,requiresLocalSignature:!0,signingLocal:!0,custody:"none",execution:"review-only",chainId:n,account:o,from:o,route:a,venue:t.venue??(typeof a=="string"?a:a.venue??a.provider??null),destination:s,to:s,...t.spender==null?{}:{spender:Te(t.spender,"spender")},prepareHash:i,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:u,data:u,selector:u.length>=10?u.slice(0,10):null,value:ne(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:ne(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:ne(t.gasLimit??r.gasLimit,"gasLimit")},simulation:p,policyChecks:d,allowlistHits:h,assetDeltas:f,approvalDeltas:m,summary:L};return Lo(A)}var qa,Ua,Da,Fa,Ma,Ha,ht,Po=z(()=>{qa=/^0x[0-9a-f]{40}$/,Ua=/^0x(?:[0-9a-f]{2})*$/,Da=/^(?:0x)?[0-9a-f]{64}$/,Fa=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,Ma=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,Ha=new Set([12,15,18,21,24]),ht=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}}});var Vo={};Ze(Vo,{ATTESTATION_KINDS:()=>yt,DESK_SESSION_CHECKPOINT_KIND:()=>Ar,DESK_SESSION_CHECKPOINT_VERSION:()=>gr,PREPARE_VERIFICATION_KIND:()=>wr,PREPARE_VERIFICATION_VERSION:()=>br,assertDeskSessionCheckpoint:()=>Mo,assertPrepareVerificationArtifact:()=>Re,assertPrepareVerificationForArm:()=>wt,assertUnsignedPrepare:()=>Er,attachPrepareVerification:()=>Do,createAttestationRecord:()=>Uo,createDeskSessionCheckpoint:()=>Fo,createPrepareVerificationArtifact:()=>bt,default:()=>nc,establishPrepareVerification:()=>rc,normalizePrepareSimulation:()=>$o,restoreDeskSessionCheckpoint:()=>Ho,summarizePrepareIntent:()=>qo});import{createHash as Ja}from"node:crypto";function ie(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))ie(t);Object.freeze(e)}return e}function Ae(e,t){if(e==null||typeof e!="object"||Array.isArray(e))throw new TypeError(`prepare verification: ${t} must be an object`);return e}function yr(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(yr).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${yr(e[r])}`).join(",")}}`}function jo(e){return Ja("sha256").update(yr(e),"utf8").digest("hex")}function ge(e,t,r=500){let o=(e==null?t:String(e)).trim();return o?o.slice(0,r):t}function ec(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Ge(e){let t=String(e||"").trim().toLowerCase().replace(/^0x/,"");return Ya.test(t)?t:""}function Bo(e){if(e?.transaction&&typeof e.transaction=="object")return e.transaction;if(e?.tx&&typeof e.tx=="object")return e.tx;let t=e?.localSignerEnvelope||e?.envelope;return t?.artifact&&typeof t.artifact=="object"?t.artifact:e}function Er(e,t="prepare verification"){if(Ae(e,"prepared"),e.signed===!0)throw new Error(`${t}: prepared fact is signed`);if(e.broadcast===!0)throw new Error(`${t}: prepared fact claims broadcast`);for(let r of Qa)if(e[r])throw new Error(`${t}: prepared fact carries ${r}`);for(let r of Xa)if(e[r])throw new Error(`${t}: prepared fact claims executed ${r}`);return!0}function $o(e){if(e==null)return ie({status:"unavailable",willRevert:null,summary:"no simulation supplied",source:"unavailable"});Ae(e,"simulation");let t=String(e.status||(e.willRevert===!0?"failed":e.ok===!1?"error":"unknown")),r=["ok","success","failed","error","unavailable","unknown"].includes(t)?t:"unknown",n=e.willRevert===!0||e.willRevert===!1?e.willRevert:null;return ie({status:r,willRevert:n,summary:ge(e.summary||e.reason||e.error,"simulation result recorded"),source:e.source==="dry-run"||e.source==="supplied"||e.source==="unavailable"?e.source:"supplied",...e.gasEstimate!=null?{gasEstimate:String(e.gasEstimate)}:{},...e.gasLimit!=null?{gasLimit:String(e.gasLimit)}:{}})}function qo(e={},t={}){let r=Bo(e),n=e.localSignerEnvelope||e.envelope||{},o=t.provider||e.provider||e.source||n.provider||t.venue||e.venue||"unknown",s=t.kind||e.kind||e.artifactKind||n.action||e.action||"prepare",i=t.destination||e.destination||e.to||r?.to||n.destination||null,a=t.chainId??e.chainId??r?.chainId??n.chainId??null,c=t.account||e.account||e.from||r?.from||n.owner||null,u=[`Unsigned ${s} via ${o}`];return i&&u.push(`to ${i}`),a!=null&&a!==""&&u.push(`on chain ${a}`),t.note&&u.push(String(t.note)),u.push("for owner review only \u2014 not signed, not armed, not executed"),ie({summary:u.join(" "),provider:String(o),kind:String(s),destination:i==null?null:String(i),chainId:a==null||a===""?null:String(a),account:c==null?null:String(c)})}function Uo({prepared:e={},env:t}={}){Ae(e,"prepared");let r=Ge(e.prepareHash),n=typeof e.prepareMac=="string"&&e.prepareMac.length>=32,o=!1;if(r)try{o=nr(e)===String(e.prepareHash)}catch{o=!1}let s=!1,i=ec(t);if(n&&i&&r)try{let l=or(r,i);s=l.length>0&&l===String(e.prepareMac)}catch{s=!1}let a=n?yt.PREPARE_HMAC:r?yt.PREPARE_CHECKSUM:yt.NONE,c=[];r&&c.push(o?"prepare-body-sha256-bound":"prepare-hash-present-unverified"),n&&c.push(s?"keyed-prepare-mac-verified":"keyed-prepare-mac-present-unverified");let u=s?"Keyed prepare MAC verified. This is integrity provenance, not TEE attestation or execution authority.":o?"Public prepare checksum only. Not provenance. Not TEE attested. Not an execution grant.":"No verified prepare integrity stamp. Simulation and intent are operator-visible facts only.";return ie({kind:a,teeAttested:!1,cryptographicallyAttested:s,checksumBound:o,claims:c,notClaimed:[...Za],custody:"none",execution:"prepare-only",note:u})}function tc(e,t,r){let n=Bo(e),o=e.localSignerEnvelope||e.envelope||{};try{let s=_o({chainId:e.chainId??n?.chainId??o.chainId,account:e.account||e.from||n?.from||o.owner,destination:e.destination||e.to||n?.to||o.destination,calldata:e.calldata||e.data||n?.data||"0x",value:e.value??n?.value??0,prepareHash:t,route:e.provider||e.venue||o.provider||o.surface||"prepare",decodedAction:e.kind||e.action||o.action||"transaction",simulation:r,...e.policyChecks?{policyChecks:e.policyChecks}:{}});return ie({status:s.status,summary:s.summary,requiresLocalSignature:!0,custody:s.custody,execution:s.execution})}catch{return null}}function bt({prepared:e,simulation:t,intent:r,env:n,nowMs:o=Date.now()}={}){Ae(e,"prepared"),Er(e);let s=Number(o);if(!Number.isSafeInteger(s)||s<=0)throw new TypeError("prepare verification: bounded createdAt required");let i=$o(t??e.simulation??e.sim),a=qo(e,r&&typeof r=="object"?r:{}),c=Uo({prepared:e,env:n}),u=Ge(e.prepareHash)||null,l=u?tc(e,u,i):null,d={version:br,kind:wr,prepareHash:u,simulation:i,intent:a,intentSummary:a.summary,attestation:c,review:l,custody:"none",execution:"prepare-only",signingReady:!1,broadcastReady:!1,executionReady:!1,createdAt:s};return ie({...d,artifactHash:jo(d)})}function Re(e,t={}){let r=t.label||"prepare verification";if(Ae(e,"artifact"),Number(e.version)!==br)throw new Error(`${r}: unsupported verification artifact version`);if(e.kind!==wr)throw new Error(`${r}: verification artifact kind required`);if(e.custody!=="none")throw new Error(`${r}: verification artifact custody must be none`);if(e.execution!=="prepare-only")throw new Error(`${r}: verification artifact must stay prepare-only`);if(e.signingReady===!0||e.broadcastReady===!0||e.executionReady===!0)throw new Error(`${r}: verification artifact must not claim a ready execution flag`);if(e.attestation?.teeAttested===!0)throw new Error(`${r}: TEE attestation is not claimed or accepted`);if(!["ok","success","failed","error","unavailable","unknown"].includes(String(e.simulation?.status||"")))throw new Error(`${r}: simulation status required`);if(typeof e.intentSummary!="string"||!e.intentSummary.trim())throw new Error(`${r}: human-readable intent summary required`);if(!e.attestation||typeof e.attestation!="object")throw new Error(`${r}: attestation record required`);if(!Array.isArray(e.attestation.notClaimed)||!e.attestation.notClaimed.includes("tee-attestation"))throw new Error(`${r}: attestation must honestly exclude TEE claims`);let{artifactHash:n,...o}=e;if(Ge(n)!==jo(o))throw new Error(`${r}: artifactHash mismatch \u2014 verification artifact was altered`);if(t.prepareHash){let s=Ge(t.prepareHash),i=Ge(e.prepareHash);if(!s||s!==i)throw new Error(`${r}: verification artifact does not bind this prepare`)}return e}function Do(e,t={}){Ae(e,"prepared");let r=t.artifact&&typeof t.artifact=="object"?t.artifact:bt({prepared:e,simulation:t.simulation,intent:t.intent,env:t.env,nowMs:t.nowMs});return Re(r,{label:t.label||"prepare verification"}),{...e,prepareVerification:r}}function wt(e,t={}){let r=t.label||"armPreparedAction";if(!e||typeof e!="object")throw new Error(`${r}: prepared object required`);let n=e.prepareVerification||e.verificationArtifact||e.deskCheckpoint?.prepareVerification||t.checkpoint?.prepareVerification;if(!n)throw new Error(`${r}: prepare verification artifact required before arm`);return Re(n,{label:r,...e.prepareHash?{prepareHash:e.prepareHash}:{}}),Er(e,r),n}function Fo({session:e={},prepareVerification:t=null,runId:r=null,nowMs:n=Date.now()}={}){let o=String(e.id||"").trim();if(!o)throw new TypeError("desk session checkpoint: session id required");let s=Number(n);if(!Number.isSafeInteger(s)||s<=0)throw new TypeError("desk session checkpoint: bounded updatedAt required");let i=null;return t!=null&&(i=Re(t,{label:"desk session checkpoint"})),ie({version:gr,kind:Ar,sessionId:o,generation:e.generation?String(e.generation):null,mode:e.mode?String(e.mode):null,runId:r||e.run?.id||null,updatedAt:s,title:ge(e.title,"",48),agentId:ge(e.agentId,"oracle",80),provider:ge(e.provider,"",80),model:ge(e.model,"",120),chain:ge(e.chain,"",40),workspace:ge(e.workspace,"",240),prepareVerification:i,custody:"none",execution:"prepare-only"})}function Mo(e,t={}){let r=t.label||"desk session checkpoint";if(Ae(e,"checkpoint"),Number(e.version)!==gr)throw new Error(`${r}: unsupported checkpoint version`);if(e.kind!==Ar)throw new Error(`${r}: desk session checkpoint kind required`);if(!e.sessionId)throw new Error(`${r}: session id required`);if(e.custody!=="none")throw new Error(`${r}: checkpoint custody must be none`);if(e.execution!=="prepare-only")throw new Error(`${r}: checkpoint must stay prepare-only`);if(e.prepareVerification&&Re(e.prepareVerification,{label:r}),t.sessionId&&String(t.sessionId)!==String(e.sessionId))throw new Error(`${r}: checkpoint does not bind this session`);return e}function Ho(e,t={}){return!e||typeof e!="object"||e.deskCheckpoint==null?null:Mo(e.deskCheckpoint,{label:t.label||"desk session checkpoint",sessionId:e.id})}function rc(e,t,r={}){let n=bt({prepared:t,simulation:r.simulation??t?.simulation,intent:r.intent,env:r.env,nowMs:r.nowMs});return e&&typeof e=="object"&&(e.prepareVerification=n),n}var br,wr,gr,Ar,yt,Ya,Qa,Xa,Za,nc,Sr=z(()=>{Po();sr();br=1,wr="prepare-verification",gr=1,Ar="desk-session-checkpoint",yt=Object.freeze({NONE:"none",PREPARE_CHECKSUM:"prepare-checksum",PREPARE_HMAC:"prepare-hmac"}),Ya=/^(?:0x)?[0-9a-f]{64}$/i,Qa=Object.freeze(["signature","signedTx","signedTransaction","rawTransaction","signedPayload","signedRaw"]),Xa=Object.freeze(["txid","txHash","transactionHash","broadcastHash"]),Za=Object.freeze(["tee-attestation","remote-attestation","hardware-enclave","trusted-execution-environment","execution-authorization","signature","broadcast"]);nc={createPrepareVerificationArtifact:bt,assertPrepareVerificationArtifact:Re,attachPrepareVerification:Do,assertPrepareVerificationForArm:wt,createDeskSessionCheckpoint:Fo,restoreDeskSessionCheckpoint:Ho}});var Wo={};Ze(Wo,{armPreparedAction:()=>dc,callSigner:()=>zo,queueOwnerAction:()=>Ko});import{existsSync as oc,readFileSync as sc}from"node:fs";import{request as ic}from"node:http";import ac from"node:path";function uc(e=process.env){let t=String(e.ORACLE_SIGNER_URL||cc).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 lc(e=process.env){if(e.ORACLE_SIGNER_TOKEN)return String(e.ORACLE_SIGNER_TOKEN);let t=ac.join(mt(),"signer","signer-token");return oc(t)?sc(t,"utf8").trim():null}function zo(e,{method:t="GET",body:r=null,env:n=process.env,timeoutMs:o=4e3}={}){let s=uc(n),i=lc(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=ic({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 Ko(e,t=process.env){if(!e||e.version!==1||!e.surface)throw new Error("queueOwnerAction: version-1 surface envelope required");return zo("/pending",{method:"POST",body:{artifact:e},env:t,timeoutMs:8e3})}async function dc(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 wt(e,{env:t,label:"armPreparedAction"}),Ko(r,t)}var cc,Go=z(()=>{Ro();Sr();cc="http://127.0.0.1:9462"});var $e=Object.freeze({PASS:"PASS",WARN:"WARN",BLOCK:"BLOCK",UNKNOWN:"UNKNOWN"}),Ss=new Set(["LIVE","CACHED","STALE","UNKNOWN","UNAVAILABLE"]),Gr=/^0x[0-9a-fA-F]{40}$/,vs=/^0x[0-9a-fA-F]{64}$/;function Oe(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Oe(t);Object.freeze(e)}return e}function J(e,t=null){return e&&typeof e=="object"?structuredClone(e):t}function Yr(e){return typeof e!="string"||!Number.isFinite(Date.parse(e))?null:new Date(e).toISOString()===e?e:null}function Jr(e){return!!(e&&Ss.has(e.evidence)&&Yr(e.observedAt))}function Qr(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 et(e){return[...new Set(e.filter(Boolean))]}function Is(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]])!Jr(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||!Jr(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"),Qr(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=et(t);return o.length?Oe({status:$e.BLOCK,whyBlocked:o}):r.length?Oe({status:$e.UNKNOWN,whyBlocked:et(r)}):n.length?Oe({status:$e.WARN,whyBlocked:[],warnings:et(n)}):Oe({status:$e.PASS,whyBlocked:[]})}function Os(e={}){let t=J(e,{}),r=Object.fromEntries(Object.entries(t).map(([o,s])=>[o,Yr(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 Xr(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("candidate must be an object");let t=J(e.chain,{}),r=J(e.token,{}),n=J(e.pool),o=J(e.venue,{}),s=J(e.signal,{}),i=J(e.route,{});i.cost=Qr(i.cost);let a=Is({...e,chain:t,token:r,pool:n,venue:o,signal:s,route:i}),c=s.unsolicitedAirdrop===!0,u=Gr.test(r.address||"")?r.address.toLowerCase():"unknown-token",l=Gr.test(n?.address||"")?n.address.toLowerCase():vs.test(n?.poolId||"")?n.poolId.toLowerCase():"unknown-pool",d=`${Number.isInteger(t.id)?t.id:"unknown-chain"}:${u}:${l}:${o.key||"unknown-venue"}`;return Oe({id:d,status:a.status,chain:t,token:r,pool:n,venue:o,signal:s,risk:J(e.risk,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),sellability:J(e.sellability,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),sellSimulation:J(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:J(e.prepared,{status:"NOT_PREPARED",unsigned:!0}),whyBlocked:et([...e.whyBlocked||[],...a.whyBlocked]),latency:Os(e.latency),held:c?!1:e.held===!0,eligible:c?!1:a.status===$e.PASS&&e.eligible!==!1})}function Zr(e=[]){if(!Array.isArray(e))throw new TypeError("candidates must be an array");return Object.freeze(e.map(Xr).sort((t,r)=>t.id.localeCompare(r.id)))}import{AbiCoder as xs,keccak256 as ks}from"ethers";var en=/^0x[0-9a-fA-F]{40}$/,X=/^0x[0-9a-fA-F]{64}$/,Ns=xs.defaultAbiCoder();function le(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))le(t);Object.freeze(e)}return e}function tn(e){return String(e?.message||e||"unknown scan failure").slice(0,300)}function de(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 Cs(e){if(!e||typeof e!="object")return"factory descriptor is invalid";if(!en.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=>!en.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 qe(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 on(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 rn(e,t,r){let n=on(e,t);if(!X.test(n||""))return null;let o=BigInt(n);return o<1n<<BigInt(r)?o:null}function nn(e,t,r){let n=on(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 Ts(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=qe(e,{topic:2}),o=qe(e,{topic:3}),s=rn(e,0,24),i=nn(e,1,24),a=qe(e,{dataWord:2}),c=rn(e,3,160),u=nn(e,4,24),l=de(e.blockNumber),d=de(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,y=f?n:o;if(ks(Ns.encode(["address","address","uint24","int24","address"],[n,o,Number(s),i,a])).toLowerCase()!==e.topics[1].toLowerCase())return null;let v=e.transactionHash.toLowerCase();return{id:`${t.chainId}:${v}:${d}`,chainId:t.chainId,factoryId:t.id||null,factoryAddress:t.factoryAddress.toLowerCase(),tokenAddress:h,quoteAsset:y,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:v,logIndex:d,evidence:"LIVE"}}function Rs(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=qe(e,r.layout.token),u=qe(e,r.layout.pool),l=de(e.blockNumber),d=de(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 Ls(e,t,r){return r.decoder==="uniswap-v4-initialize"?Ts(e,t,r):Rs(e,t,r)}async function sn(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=de(e.fromBlock??e.cursor?.nextBlock),s=de(e.toBlock);if(o===null||s===null||o<0||s<o)throw new TypeError("a valid integer block range is required");let i=le({nextBlock:de(e.cursor?.nextBlock)??o});if(n)return le({status:"UNKNOWN",discoveries:[],unavailable:[],cursor:i,whyBlocked:["reorg hint requires canonical range reconciliation"]});let a=[],c=[];for(let d of r){let p=Cs(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 le({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,y)=>h.topic0.localeCompare(y.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 le({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`scan failed: ${tn(h)}`]})}if(!m||m.complete!==!0||m.evidence&&m.evidence!=="LIVE"){let h=Array.isArray(m?.failedAt)?` at ${m.failedAt.join("-")}`:"";return le({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`incomplete block range${h}${m?.error?`: ${tn(m.error)}`:""}`]})}for(let h of Array.isArray(m.logs)?m.logs:[]){let y=p.find(v=>v.topic0.toLowerCase()===String(h?.topics?.[0]||"").toLowerCase()),g=y&&Ls(h,d,y);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 le({status:"LIVE",discoveries:[...l.values()],unavailable:a,cursor:{nextBlock:s+1},whyBlocked:a.map(d=>d.reason)})}import{createHash as _s}from"node:crypto";var an="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 kt(e){return Array.isArray(e)?`[${e.map(kt).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${kt(e[t])}`).join(",")}}`:JSON.stringify(e)}function cn(e){return`sha256:${_s("sha256").update(kt(e)).digest("hex")}`}function un(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 Ct(e=[]){if(!Array.isArray(e))throw new TypeError("evidence records must be an array");let t=new Set,r=an,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=un(o,s+1,r),a=cn(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 Tt(e=[],t){let r=Ct(e);if(r.some(s=>s.id===t?.id))throw new Error(`duplicate evidence event id: ${t.id}`);let n=r.at(-1)?.digest??an,o=un(t,r.length+1,n);return Nt([...r,{...o,digest:cn(o)}])}var ln=Object.freeze({ALERT_ONLY:"alert_only",EXECUTE:"execute"});function dn(e){return e?.mode==="shadow"?ln.ALERT_ONLY:ln.EXECUTE}function tt(e,t){return!!(e?.mode&&e.mode!=="shadow"&&t?.policyEligible===!0)}function fn(e,t,r){return tt(e,t)&&r?.prepared===!0}var Ps="0x783cca1c0412dd0d695e784568c96da2e9c22ff989357a2e8b1d9b2b4e6b7118",uu=Object.freeze([Object.freeze({topic0:Ps,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})})})]),lu=Object.freeze({amountIn:"1000000000000000",quoteAssetDecimals:18,slippageBps:100,maxImpactPct:25,timeoutMs:4e3}),du=Object.freeze({amountIn:"1000000",quoteAssetDecimals:9,slippageBps:100,maxImpactPct:25,timeoutMs:12e3}),fu=Object.freeze([Object.freeze({chainId:1,key:"ethereum",factoryAddress:"0x1f98431c8ad98523631ae4a59f267346ea31f984",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"}),Object.freeze({chainId:10,key:"optimism",factoryAddress:"0x1f98431c8ad98523631ae4a59f267346ea31f984",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"}),Object.freeze({chainId:56,key:"bsc",factoryAddress:"0xdb1d10011ad0ff90774d0c6bb92e5c5c8b4461f7",router:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2"}),Object.freeze({chainId:137,key:"polygon",factoryAddress:"0x1f98431c8ad98523631ae4a59f267346ea31f984",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"}),Object.freeze({chainId:8453,key:"base",factoryAddress:"0x33128a8fc17869897dce68ed026d694621f6fdfd",router:"0x2626664c2603336E57B271c5C0b26F421741e481"}),Object.freeze({chainId:42161,key:"arbitrum",factoryAddress:"0x1f98431c8ad98523631ae4a59f267346ea31f984",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"}),Object.freeze({chainId:43114,key:"avalanche",factoryAddress:"0x740b1c1de25031c31ff4fc9a62f554a55cdc1bad",router:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE"}),Object.freeze({chainId:999,key:"hyperevm",factoryAddress:"0xb1c0fa0b789320044a6f623cfe5ebda9562602e3",router:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D"}),Object.freeze({chainId:988,key:"stable",factoryAddress:"0x88f0a512ef09175d456bc9547f914f48c013e4aa",router:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",provenance:"chains.config router.factory() on 2026-08-05"}),Object.freeze({chainId:2741,key:"abstract",factoryAddress:"0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1",router:"0x7712FA47387542819d4E35A23f8116C90C18767C",provenance:"chains.config pool.factory() on 2026-08-05"}),Object.freeze({chainId:4663,key:"robinhood",factoryAddress:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",router:"0xcaf681a66d020601342297493863e78c959e5cb2"})]);import Ot from"node:fs";import Uc from"node:os";import ce from"node:path";xe();var Ut={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}};var mi=new Map(Object.values(Ut).map(e=>[e.chainId,e]));function On(e){return mi.get(Number(e))||null}function xn(e,t=process.env){let r=On(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 hi,getAddress as yi}from"ethers";var kn=new hi(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Nn(e,t){try{return yi(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}var bi={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 wi(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=xn(e,r);return n||bi[Number(e)]||null}var gi=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Ai(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!gi.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 De=new Map,Cn=new Map;function Ei(e){let t=new Error(e?.message||JSON.stringify(e));return t.code=e?.code,t}function Si(e){if(e?.error)throw Ei(e.error);return e?.result}function vi(e,t,r){return`${e}
|
|
3
|
+
`)};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 ci(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,bn):Math.min(250*2**e,bn)+Math.floor(Math.random()*100)}function se(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function qt(e,t,r){return se(`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 li(e){return e?e.byteLength??e.length??0:0}async function di(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 qt(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 qt(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+=li(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 qt(r,`streamed ${c} bytes`,t);let l=Buffer.concat(a);return(u?l.subarray(0,t):l).toString("utf8")}function fi(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function pi(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=st}){let y=null,g=t,v=i?{lookupFn:i}:{};if(c&&!a&&!Bt(g))throw se(`HTTP refused ${e}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let N=new AbortController,L=setTimeout(()=>N.abort(),s),A=f?gn?gn([f,N.signal]):f:N.signal,I=async(E,{status:k=null}={})=>{let O=await _t(E,v);if(!O.ok)throw se(k==null?`HTTP refused ${E}: ${O.error}`:`HTTP redirect to ${E} ${O.error}`,k==null?{}:{status:k});let _=new URL(E).hostname;if(a){if(y&&(await y.close(),y=null),!y)try{y=await Pt({requireUndici:!0,...d?{importUndici:d}:{}})}catch(b){throw se(k==null?`HTTP refused ${E}: ${b?.message||b}`:`HTTP redirect to ${E} refused: ${b?.message||b}`,k==null?{}:{status:k})}y.pin(_,O.addresses),g=y.fetch}else mn(g,_,O.addresses);return O};try{let E=String(e),k=Object.assign(Object.create(null),n||{});c&&await I(E);for(let O=0;O<=h;O+=1){let _=Object.assign(Object.create(null),{method:r,headers:k,body:o,signal:A,redirect:"manual",dispatcher:void 0}),b=await g(E,_);if((m==="error"||h===0)&&b.status>=300&&b.status<400)throw pe(b),se(`HTTP ${b.status} ${r} redirect refused`,{status:b.status,redirectRefused:!0});if(Xs.has(b.status)){let T=l===!0&&r==="POST"&&[307,308].includes(b.status)&&vn(r,o);if(r!=="GET"&&r!=="HEAD"&&!T){pe(b);let B=new Error(`HTTP ${b.status} ${r} ${E} redirected non-idempotent request`);throw B.status=b.status,B}if(O===h)throw pe(b),se(`HTTP ${b.status} ${r} redirect budget exhausted`,{status:b.status,redirectRefused:!0});let oe=b.headers?.get?.("location"),V;try{V=ni(oe,E)}catch(B){throw pe(b),B}let ue=!oi(V,E);if(pe(b),ue&&r==="POST"){let B=new Error(`HTTP ${b.status} ${r} cross-origin redirect refused`);throw B.status=b.status,B}if(ue&&l){let B=new Error(`HTTP ${b.status} ${r} cross-origin redirect refused`);throw B.status=b.status,B.retryable=!1,B}if(ue&&(k=ri(k)),c)await I(V,{status:b.status});else if(ue){let B=await _t(V,v);if(!B.ok){let R=new Error(`HTTP redirect from ${E} ${B.error}`);throw R.status=b.status,R.retryable=!1,R}a&&B.addresses?.length&&(y||(y=await Pt(d?{importUndici:d}:{})),y&&(y.pin(new URL(V).hostname,B.addresses),g=y.fetch))}E=V;continue}if(typeof p=="function")try{await p(b,{url:E})}catch(T){throw pe(b),se(T?.message||String(T))}let $=await di(b,u,{url:E,onOversize:()=>N.abort()}),w=fi($);if(!b.ok){let T=new Error(`HTTP ${b.status} ${r} ${E}`);throw T.status=b.status,T.retryAfter=b.headers?.get?.("retry-after")??null,T.body=w??$.slice(0,300),T}return w??$}throw new Error(`HTTP redirect loop for ${e}`)}catch(E){if(N.signal.aborted&&!Ue(f)){let k=E&&(typeof E=="object"||typeof E=="function")&&!ee.isProxy(E)?E:null,O=k?Object.getOwnPropertyDescriptor(k,"oversize"):null;if(!(O&&Object.hasOwn(O,"value")&&O.value===!0))try{if(!k)throw new TypeError("unsafe rejection");Object.defineProperties(k,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let b=new Error("HTTP request timed out");throw Object.defineProperties(b,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),b}}throw E}finally{clearTimeout(L),y&&await y.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 R of Object.getOwnPropertyNames(t)){let C=Object.getOwnPropertyDescriptor(t,R);if(!(R==="toJSON"&&C&&Object.hasOwn(C,"value")&&C.value===void 0)){if(!r.has(R))throw new TypeError("HTTP options contain unknown fields");if(!C||!C.enumerable||!Object.hasOwn(C,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=R=>{if(t==null||!Object.hasOwn(t,R))return;let C=Object.getOwnPropertyDescriptor(t,R);if(!C||!Object.hasOwn(C,"value"))throw new TypeError("HTTP options must contain own data properties");return C.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>st))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${st}`);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??st;for(let R of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let C=n(R);if(C!==void 0&&typeof C!="boolean")throw new TypeError(`HTTP ${R} 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{Ue(p)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let R of["importUndici","lookupFn","validateResponse"]){let C=n(R);if(C!==void 0&&typeof C!="function")throw new TypeError(`HTTP ${R} 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,y=(o||"GET").toUpperCase(),g=n("headers"),v=ti(g),N=Object.assign(Object.create(null),v);Object.keys(N).some(R=>R.toLowerCase()==="accept")||(N.Accept="application/json");let L=n("body");L!=null&&typeof L!="string"&&(Object.keys(N).find(C=>C.toLowerCase()==="content-type")||(N["Content-Type"]="application/json"),L=ei(L));let A=i??Ks,I=n("lookupFn"),E=!f,k=n("untrustedUrl")===!0,O=n("sameOriginRedirectsOnly")===!0,_=n("importUndici"),b=n("validateResponse"),$=p,w=d??null,T=async()=>{let R;for(let C=0;C<=A;C++){$&&Ys.call($);let Vr=rt("http");try{let Q=await pi(e,{fetchImpl:m,method:y,headers:N,body:L,timeoutMs:h,lookupFn:I,realFetch:E,untrustedUrl:k,maxResponseBytes:w,sameOriginRedirectsOnly:O,importUndici:_,validateResponse:b,signal:$,redirectPolicy:u,maxRedirects:l});return Vr?.("succeeded"),Q}catch(Q){R=Q;let Ie=xt=>{if(!Q||typeof Q!="object"&&typeof Q!="function"||ee.isProxy(Q))return;let je=Object.getOwnPropertyDescriptor(Q,xt);return je&&Object.hasOwn(je,"value")?je.value:void 0},Xe=Ie("status");Vr?.("failed",Xe);let bs=Ie("oracleTimeout")===!0||Ie("name")==="AbortError"||Ie("name")==="TimeoutError"||Ue($),ws=new Set([408,425,429]),gs=Ie("retryable")===!1?!1:Xe!=null?ws.has(Xe)||zs.has(Xe)&&yn.has(y):!bs&&yn.has(y);if(C===A||!gs)throw Q;let zr=ci(C,Ie("retryAfter")),As=rt("retry"),Kr=!1;try{$?await new Promise((xt,je)=>{let Wr,Be=()=>{clearTimeout(Wr),wn.call($,"abort",Be),je(Qs($)||new DOMException("Aborted","AbortError"))};if(Ue($)){Be();return}Wr=setTimeout(()=>{wn.call($,"abort",Be),xt()},zr),Js.call($,"abort",Be,{once:!0}),Ue($)&&Be()}):await ui(zr),Kr=!0}finally{As?.(Kr?"succeeded":"failed")}}}throw R};if(!(n("dedupe")!==!1&&!$&&vn(y,L)))return T();let V=ai(y,e,N,{untrustedUrl:k,maxResponseBytes:w,sameOriginRedirectsOnly:O,redirectPolicy:u,maxRedirects:l,timeoutMs:h,retries:A,fetchImpl:ot(m),realFetch:E,lookupFn:ot(I),importUndici:ot(_),validateResponse:ot(b)},L),ue=$t.get(V);if(ue){let R=rt("shared");try{let C=await ue;return R?.("succeeded"),C}catch(C){throw R?.("failed"),C}}let B=T().finally(()=>$t.delete(V));return $t.set(V,B),B}async function In(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 zs,yn,Ks,bn,Ws,Gs,Ys,Js,wn,gn,Ue,Qs,Xs,st,vu,Z,$t,An,En,si,ii,ui,xe=z(()=>{pn();hn();zs=new Set([408,425,429,500,502,503,504]),yn=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Ks=2,bn=4e3,Ws=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Gs=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Ys=AbortSignal.prototype.throwIfAborted,Js=EventTarget.prototype.addEventListener,wn=EventTarget.prototype.removeEventListener,gn=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,Ue=e=>e?Ws.call(e):!1,Qs=e=>e?Gs.call(e):void 0,Xs=new Set([301,302,303,307,308]),st=3,vu=64*1024,Z=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});$t=new Map,An=new WeakMap,En=1;si=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),ii=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);ui=e=>new Promise(t=>setTimeout(t,e))});import{types as Zt}from"node:util";function er(e){if(!e||typeof e!="object"||Zt.isProxy(e)||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ut(e,t){if(e==null||(typeof e=="object"||typeof e=="function")&&Zt.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 ct(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(Zt.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]=ct(i.value,t,r+1)}return o}if(!er(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]=ct(s.value,t,r+1)}return n}var ao=z(()=>{});function na(e={}){return String(e.rpcUrl||process.env.SOLANA_RPC_URL||ra).trim()}function ke(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 co(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=ct(await te(na(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(!er(o))throw new Error(`solana-rpc ${e}: invalid response envelope`);let s=ut(o,"error");if(s)throw new Error(`solana-rpc ${e}: ${ut(s,"message")||JSON.stringify(s)}`);if(!Object.hasOwn(o,"result"))throw new Error(`solana-rpc ${e}: missing result`);return ut(o,"result")}var ra,tr=z(()=>{xe();ao();ra="https://api.mainnet-beta.solana.com"});import{createHash as oa,createHmac as sa,timingSafeEqual as yl}from"node:crypto";function rr(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(rr).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${rr(e[r])}`).join(",")}}`}function uo(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function lo(e=process.env){return uo(process.env)||uo(e)}function ua(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function nr(e){let t=ua(e);return oa("sha256").update(rr(t)).digest("hex")}function or(e,t=lo()){return t?sa("sha256",t).update(String(e)).digest("hex"):""}function fo(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+aa:Number(s),l=u-c;if(!Number.isSafeInteger(c)||!Number.isSafeInteger(u)||l<=0||l>ca)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let p={...a,preparedAt:c,expiresAt:u,prepareVersion:ia},f=nr(p),m=lo(n),h=m?or(f,m):void 0,y={...p,prepareHash:f};return h&&(y.prepareMac=h),y}var ia,aa,ca,sr=z(()=>{ia=2,aa=300*1e3,ca=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});function ir(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function pa(e){return la.some(t=>e.startsWith(t))||da.has(e)}function ma(e){let t=String(e);if(!/^[\x20-\x7e]+$/.test(t))return!0;let r=ir(t);return pa(r)?!1:fa.has(r)?!0:r.includes("signed")||r.includes("signature")||r.endsWith("sig")||r.endsWith("sigs")}function ha(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 ar(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=>ar(c,t+1,r,n));let o=[];for(let[c,u]of Object.entries(e)){if(ma(c)){o.push(c);continue}o.push(...ar(u,t+1,r,n))}let i=Object.keys(e).map(ir).some(c=>c.endsWith("psbt")||c.endsWith("psbtbase64")),a=Object.entries(e).some(([c,u])=>/complete|finalized|isfinal/.test(ir(c))&&u===!0);return i&&a&&o.push("psbt(complete)"),ha(e)&&o.push("v/r/s"),o}function po(e,t){let r=ar(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 la,da,fa,mo=z(()=>{la=["unsigned","notsigned","tosign","signable"],da=new Set(["requiresusersignature","requiressignature","needssignature","signaturerequired","signaturesrequired","signingready","signaturecount","signaturethreshold","requiredsignatures","signatureneeded","hassignature","allowsignatures","requestsignature","multisig","cosig","msig"]),fa=new Set(["sig","sigs","scriptsig","witness","psbt","finalizedpsbt","completepsbt","finalpsbt","psbtfinalized","serializedtransaction"])});var lr={};Ze(lr,{JUPITER_MAX_SLIPPAGE_BPS:()=>bo,JUPITER_SWAP_API:()=>ze,SOL_MINT:()=>ft,USDC_MINT:()=>cr,jupiterHealth:()=>Ea,jupiterPrepareSwap:()=>va,jupiterQuote:()=>ur,jupiterSignerEnvelope:()=>Eo,jupiterVenues:()=>Aa,solanaGuard:()=>dt});function wo(e={}){return String(e.baseUrl||process.env.JUPITER_SWAP_API_URL||ze).replace(/\/$/,"")}function Ke(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 go(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>bo)throw new Error("jupiter: slippage exceeds hard 100 bps cap");return t}function lt(e,t){return e==null?t:!!e}function ya(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 ba(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 Ao(e){let t=Buffer.from(e,"base64"),r=ba(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 dt(e={},{quotedAtMs:t=Date.now(),ttlMs:r=ho}={}){let n=ke(e.inputMint,"inputMint"),o=ke(e.outputMint,"outputMint"),s=Ke(e.inAmount,"inAmount"),i=Ke(e.outAmount,"outAmount"),a=Ke(e.otherAmountThreshold??e.outAmount,"otherAmountThreshold"),c=go(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)||ho,1e3),3e4)}}function Eo({userPublicKey:e,guard:t,swapTransaction:r,args:n={},response:o={}}){if(t.inputMint!==ft)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=Ao(r),i=Ke(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 yo(e){if(typeof e!="string"||!e.length)return!1;let t=0n;for(let o of e){let s=ga.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 Aa(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(`${ze}/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])=>yo(p)),c=[],u=i.filter(([p])=>!yo(p)).map(([p,f])=>({programId:p,label:f,reason:"malformed program id"}));if(e.verify===!1)return{source:`${ze}/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(([y])=>y),{encoding:"base64",dataSlice:{offset:0,length:0}}]})}catch{await new Promise(y=>setTimeout(y,2e3*(h+1)))}if(!m){for(let[h,y]of f)u.push({programId:h,label:y,reason:"rpc batch failed after 3 attempts"});continue}m.value.forEach((h,y)=>{let[g,v]=f[y];h&&h.executable===!0&&wa.has(h.owner)?c.push({programId:g,label:v,owner:h.owner}):u.push({programId:g,label:v,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:`${ze}/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 Ea(e={}){try{return{ok:!0,provider:"jupiter",outAmount:(await ur({inputMint:ft,outputMint:cr,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 ur(e={},t={}){let r=ke(e.inputMint||e.fromMint||ft,"inputMint"),n=ke(e.outputMint||e.toMint||cr,"outputMint"),o=Ke(e.amount||e.inAmount,"amount"),s=go(e.slippageBps??e.maxSlippageBps??50),i=new URL(`${wo(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=dt({...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 Sa(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function va(e={},t={}){let r=ke(e.userPublicKey||e.owner||e.wallet,"userPublicKey"),n=e.quoteResponse?{quote:e.quoteResponse,solanaGuard:dt(e.quoteResponse,t)}:await ur(e,t),o=n.quote,s=n.solanaGuard||dt(o,t);if(lt(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(`${wo(t)}/swap`,{method:"POST",body:Sa({quoteResponse:o,userPublicKey:r,wrapAndUnwrapSol:lt(e.wrapAndUnwrapSol,!0),dynamicComputeUnitLimit:lt(e.dynamicComputeUnitLimit,!0),dynamicSlippage:!1,asLegacyTransaction:lt(e.asLegacyTransaction,!0),prioritizationFeeLamports:e.prioritizationFeeLamports??0}),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),a=ya(i?.swapTransaction);Ao(a),po("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=Eo({userPublicKey:r,guard:s,swapTransaction:a,args:e,response:i})}catch(f){p=String(f?.message||f).slice(0,200)}return fo({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 ze,ft,cr,bo,ho,wa,ga,dr=z(()=>{xe();tr();sr();mo();ze="https://lite-api.jup.ag/swap/v1",ft="So11111111111111111111111111111111111111112",cr="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",bo=100,ho=2e4;wa=new Set(["BPFLoaderUpgradeab1e11111111111111111111111","BPFLoader2111111111111111111111111111111111","BPFLoader1111111111111111111111111111111111"]),ga="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});var Io={};Ze(Io,{SELL_SIM:()=>q,assertSellable:()=>Na,simulateSell:()=>vo});function xa(e,t){return t===0n?null:Number((t-e)*10000n/t)}function ka(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 vo(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=ka(e.amountIn,"amountIn"),i;try{i=await t.quote({chainId:o,inputMint:n,outputMint:r,amount:s.toString(),side:"buy"})}catch(f){return J(q.UNKNOWN,`buy leg could not be quoted: ${fr(f)}`,{chainId:o,token:r,base:n})}let a=So(i?.outAmount);if(a==null||a===0n)return J(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 J(q.HONEYPOT,`buy routes but the SELL leg fails to quote (${fr(f)}) \u2014 you would not be able to exit`,{chainId:o,token:r,base:n,tokensOut:a.toString()})}let u=So(c?.outAmount);if(u==null||u===0n)return J(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=xa(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 J(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=fr(f)}return p===!0&&(d.evidence="execution"),l==null?J(q.UNKNOWN,"could not compute round-trip loss",d):l>=Ia?J(q.HONEYPOT,`round trip loses ${(l/100).toFixed(1)}% \u2014 a sell tax or rigged curve, not normal slippage`,d):l>=Oa?J(q.CAUTION,`round trip loses ${(l/100).toFixed(1)}% \u2014 high tax or thin liquidity`,d):p===!0?J(q.SAFE,`round trip loses ${(l/100).toFixed(1)}% and the sell executes \u2014 exit path verified`,d):J(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 J(e,t,r){return{status:e,safe:e===q.SAFE,tradable:e===q.SAFE||e===q.CAUTION,reason:t,...r}}function So(e){if(e==null)return null;try{let t=String(e).trim();return/^\d+$/.test(t)?BigInt(t):null}catch{return null}}function fr(e){return String(e?.message||e).slice(0,120)}async function Na(e={},t={}){let r=await vo(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,Ia,Oa,Oo=z(()=>{q=Object.freeze({SAFE:"SAFE",CAUTION:"CAUTION",HONEYPOT:"HONEYPOT",UNKNOWN:"UNKNOWN"}),Ia=5e3,Oa=1500});import pt from"node:fs";import La from"node:os";import Ce from"node:path";import{fileURLToPath as _a}from"node:url";function To(){return process.env.ORACLE_FAKE_HOME||La.homedir()}function ja(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function mt(){return ja()?process.env.ORACLE_CONFIG_DIR||Ce.join(To(),".config","oracle"):Ce.join(To(),".config","oracle")}function Ba(){return Ce.join(mt(),"desk.json")}function $a(){return Ce.join(mt(),"env")}function Ne({force:e=!1}={}){if(Ne._done&&!e)return Ne._result||null;Ne._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=$a();if(pt.existsSync(o))for(let s of pt.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=Ba();if(pt.existsSync(o)){let s=JSON.parse(pt.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)),Ne._result=Object.keys(t).length?t:null,Ne._result}var Pa,Nl,Ro=z(()=>{Pa=Ce.dirname(_a(import.meta.url)),Nl=Ce.resolve(Pa,"../..");try{Ne()}catch{}});function mr(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(Ma.test(e)||Ha.has(o.length)&&o.every(s=>/^[a-z]+$/i.test(s)))throw new ht(t);return e}if(typeof e=="bigint")return e.toString();if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new TypeError(`sign-time review: safe integer required at ${t}`);return e}if(Array.isArray(e))return e.map((o,s)=>mr(o,`${t}[${s}]`,r));we(e,t);let n={};for(let o of Object.keys(e).sort()){let s=o.replace(/[^a-z0-9]/gi,"");if(Fa.test(s))throw new ht(`${t}.${o}`);e[o]!==void 0&&(n[o]=mr(e[o],`${t}.${o}`,o))}return n}function we(e,t){if(e==null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`sign-time review: ${t} must be a plain object`);return e}function We(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function Te(e,t){let r=String(We(e,t)).toLowerCase();if(!qa.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function ne(e,t,{positive:r=!1}={}){try{let n=BigInt(We(e,t));if(n<0n||r&&n===0n)throw new Error;return n.toString()}catch{throw new TypeError(`sign-time review: ${t} must be an unsigned integer`)}}function hr(e,t){if(typeof e!="string"||e.length===0||e.length>500||e!==e.trim())throw new TypeError(`sign-time review: ${t} must be non-empty text`);return e}function Lo(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Lo(t);Object.freeze(e)}return e}function Va(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};we(e,t);let r=e.passed??e.ok??e.allowed;if(typeof r!="boolean")throw new TypeError(`sign-time review: ${t} needs a boolean result`);let n=e.reason??e.message??e.name??(r?"passed":"failed");return{...e,passed:r,reason:hr(String(n),`${t}.reason`)}}function za(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>Va(n,`policyChecks[${o}]`)),r=t.filter(n=>!n.passed);return{checks:t,passed:t.length-r.length,failed:r.length,reasons:r.map(n=>n.reason)}}function Ka(e){if(e==null)return null;if(we(e,"simulation"),typeof e.status!="string"||!["ok","success","failed","error","unavailable","unknown"].includes(e.status))throw new TypeError("sign-time review: simulation.status is invalid");if(e.willRevert!==!0&&e.willRevert!==!1&&e.willRevert!==null)throw new TypeError("sign-time review: simulation.willRevert must be boolean or null");let t={status:e.status,willRevert:e.willRevert??null,summary:hr(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=ne(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=ne(e.gasLimit,"simulation.gasLimit")),t}function Wa(e){if(e==null)return null;if(!Array.isArray(e)||e.length===0)throw new TypeError("sign-time review: assetDeltas must be a non-empty array");return e.map((t,r)=>{we(t,`assetDeltas[${r}]`);let n=ne(t.before,`assetDeltas[${r}].before`),o=ne(t.after,`assetDeltas[${r}].after`),s=(BigInt(o)-BigInt(n)).toString(),i;try{i=t.delta==null?s:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(i!==s)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:hr(String(We(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:i}})}function Ga(e){if(e==null)return[];if(!Array.isArray(e))throw new TypeError("sign-time review: approvalDeltas must be an array");return e.map((t,r)=>{we(t,`approvalDeltas[${r}]`);let n=ne(t.amount??t.after,`approvalDeltas[${r}].amount`);if(t.revokeLike!=null&&typeof t.revokeLike!="boolean")throw new TypeError(`sign-time review: approvalDeltas[${r}].revokeLike must be boolean`);return{token:Te(t.token,`approvalDeltas[${r}].token`),spender:Te(t.spender,`approvalDeltas[${r}].spender`),owner:Te(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function _o(e={}){we(e,"input");let t=mr(e),r=t.tx==null?t:we(t.tx,"tx"),n=ne(t.chainId??r.chainId,"chainId",{positive:!0}),o=Te(t.account??t.from??r.from,"account/from"),s=Te(t.destination??t.to??r.to,"destination/to"),i=String(We(t.prepareHash,"prepareHash")).toLowerCase();if(!Da.test(i))throw new TypeError("sign-time review: prepareHash must be a 32-byte hash");let a=t.route??t.venue;if(a==null)throw new TypeError("sign-time review: route/venue required");let c=t.decodedCalldata??t.decodedAction;if(c==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let u=String(We(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!Ua.test(u))throw new TypeError("sign-time review: calldata/data must be even-length hex");let l=t.policyChecks!==void 0&&t.policyChecks!==null,d=za(l?t.policyChecks:[]),p=Ka(t.simulation),f=Wa(t.assetDeltas),m=Ga(t.approvalDeltas),h=t.allowlistHits??[];if(!Array.isArray(h))throw new TypeError("sign-time review: allowlistHits must be an array");let y=p?.willRevert===!0||["failed","error"].includes(p?.status),g=p!=null&&p.willRevert===!1&&["ok","success"].includes(p.status),v=y||d.failed>0?"BLOCKED":g&&l&&d.checks.length>0&&f!=null?"READY":"UNKNOWN",N=typeof c=="string"?c:c.method??c.action??c.type??"transaction",L=`${v}: review ${N} on chain ${n}; policy ${d.passed} passed, ${d.failed} failed; ${f?.length??0} asset delta${f?.length===1?"":"s"}; local signature required`,A={reviewVersion:1,status:v,requiresLocalSignature:!0,signingLocal:!0,custody:"none",execution:"review-only",chainId:n,account:o,from:o,route:a,venue:t.venue??(typeof a=="string"?a:a.venue??a.provider??null),destination:s,to:s,...t.spender==null?{}:{spender:Te(t.spender,"spender")},prepareHash:i,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:u,data:u,selector:u.length>=10?u.slice(0,10):null,value:ne(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:ne(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:ne(t.gasLimit??r.gasLimit,"gasLimit")},simulation:p,policyChecks:d,allowlistHits:h,assetDeltas:f,approvalDeltas:m,summary:L};return Lo(A)}var qa,Ua,Da,Fa,Ma,Ha,ht,Po=z(()=>{qa=/^0x[0-9a-f]{40}$/,Ua=/^0x(?:[0-9a-f]{2})*$/,Da=/^(?:0x)?[0-9a-f]{64}$/,Fa=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,Ma=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,Ha=new Set([12,15,18,21,24]),ht=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}}});var Vo={};Ze(Vo,{ATTESTATION_KINDS:()=>yt,DESK_SESSION_CHECKPOINT_KIND:()=>Ar,DESK_SESSION_CHECKPOINT_VERSION:()=>gr,PREPARE_VERIFICATION_KIND:()=>wr,PREPARE_VERIFICATION_VERSION:()=>br,assertDeskSessionCheckpoint:()=>Mo,assertPrepareVerificationArtifact:()=>Re,assertPrepareVerificationForArm:()=>wt,assertUnsignedPrepare:()=>Er,attachPrepareVerification:()=>Do,createAttestationRecord:()=>Uo,createDeskSessionCheckpoint:()=>Fo,createPrepareVerificationArtifact:()=>bt,default:()=>nc,establishPrepareVerification:()=>rc,normalizePrepareSimulation:()=>$o,restoreDeskSessionCheckpoint:()=>Ho,summarizePrepareIntent:()=>qo});import{createHash as Ya}from"node:crypto";function ie(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))ie(t);Object.freeze(e)}return e}function Ae(e,t){if(e==null||typeof e!="object"||Array.isArray(e))throw new TypeError(`prepare verification: ${t} must be an object`);return e}function yr(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(yr).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${yr(e[r])}`).join(",")}}`}function jo(e){return Ya("sha256").update(yr(e),"utf8").digest("hex")}function ge(e,t,r=500){let o=(e==null?t:String(e)).trim();return o?o.slice(0,r):t}function ec(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Ge(e){let t=String(e||"").trim().toLowerCase().replace(/^0x/,"");return Ja.test(t)?t:""}function Bo(e){if(e?.transaction&&typeof e.transaction=="object")return e.transaction;if(e?.tx&&typeof e.tx=="object")return e.tx;let t=e?.localSignerEnvelope||e?.envelope;return t?.artifact&&typeof t.artifact=="object"?t.artifact:e}function Er(e,t="prepare verification"){if(Ae(e,"prepared"),e.signed===!0)throw new Error(`${t}: prepared fact is signed`);if(e.broadcast===!0)throw new Error(`${t}: prepared fact claims broadcast`);for(let r of Qa)if(e[r])throw new Error(`${t}: prepared fact carries ${r}`);for(let r of Xa)if(e[r])throw new Error(`${t}: prepared fact claims executed ${r}`);return!0}function $o(e){if(e==null)return ie({status:"unavailable",willRevert:null,summary:"no simulation supplied",source:"unavailable"});Ae(e,"simulation");let t=String(e.status||(e.willRevert===!0?"failed":e.ok===!1?"error":"unknown")),r=["ok","success","failed","error","unavailable","unknown"].includes(t)?t:"unknown",n=e.willRevert===!0||e.willRevert===!1?e.willRevert:null;return ie({status:r,willRevert:n,summary:ge(e.summary||e.reason||e.error,"simulation result recorded"),source:e.source==="dry-run"||e.source==="supplied"||e.source==="unavailable"?e.source:"supplied",...e.gasEstimate!=null?{gasEstimate:String(e.gasEstimate)}:{},...e.gasLimit!=null?{gasLimit:String(e.gasLimit)}:{}})}function qo(e={},t={}){let r=Bo(e),n=e.localSignerEnvelope||e.envelope||{},o=t.provider||e.provider||e.source||n.provider||t.venue||e.venue||"unknown",s=t.kind||e.kind||e.artifactKind||n.action||e.action||"prepare",i=t.destination||e.destination||e.to||r?.to||n.destination||null,a=t.chainId??e.chainId??r?.chainId??n.chainId??null,c=t.account||e.account||e.from||r?.from||n.owner||null,u=[`Unsigned ${s} via ${o}`];return i&&u.push(`to ${i}`),a!=null&&a!==""&&u.push(`on chain ${a}`),t.note&&u.push(String(t.note)),u.push("for owner review only \u2014 not signed, not armed, not executed"),ie({summary:u.join(" "),provider:String(o),kind:String(s),destination:i==null?null:String(i),chainId:a==null||a===""?null:String(a),account:c==null?null:String(c)})}function Uo({prepared:e={},env:t}={}){Ae(e,"prepared");let r=Ge(e.prepareHash),n=typeof e.prepareMac=="string"&&e.prepareMac.length>=32,o=!1;if(r)try{o=nr(e)===String(e.prepareHash)}catch{o=!1}let s=!1,i=ec(t);if(n&&i&&r)try{let l=or(r,i);s=l.length>0&&l===String(e.prepareMac)}catch{s=!1}let a=n?yt.PREPARE_HMAC:r?yt.PREPARE_CHECKSUM:yt.NONE,c=[];r&&c.push(o?"prepare-body-sha256-bound":"prepare-hash-present-unverified"),n&&c.push(s?"keyed-prepare-mac-verified":"keyed-prepare-mac-present-unverified");let u=s?"Keyed prepare MAC verified. This is integrity provenance, not TEE attestation or execution authority.":o?"Public prepare checksum only. Not provenance. Not TEE attested. Not an execution grant.":"No verified prepare integrity stamp. Simulation and intent are operator-visible facts only.";return ie({kind:a,teeAttested:!1,cryptographicallyAttested:s,checksumBound:o,claims:c,notClaimed:[...Za],custody:"none",execution:"prepare-only",note:u})}function tc(e,t,r){let n=Bo(e),o=e.localSignerEnvelope||e.envelope||{};try{let s=_o({chainId:e.chainId??n?.chainId??o.chainId,account:e.account||e.from||n?.from||o.owner,destination:e.destination||e.to||n?.to||o.destination,calldata:e.calldata||e.data||n?.data||"0x",value:e.value??n?.value??0,prepareHash:t,route:e.provider||e.venue||o.provider||o.surface||"prepare",decodedAction:e.kind||e.action||o.action||"transaction",simulation:r,...e.policyChecks?{policyChecks:e.policyChecks}:{}});return ie({status:s.status,summary:s.summary,requiresLocalSignature:!0,custody:s.custody,execution:s.execution})}catch{return null}}function bt({prepared:e,simulation:t,intent:r,env:n,nowMs:o=Date.now()}={}){Ae(e,"prepared"),Er(e);let s=Number(o);if(!Number.isSafeInteger(s)||s<=0)throw new TypeError("prepare verification: bounded createdAt required");let i=$o(t??e.simulation??e.sim),a=qo(e,r&&typeof r=="object"?r:{}),c=Uo({prepared:e,env:n}),u=Ge(e.prepareHash)||null,l=u?tc(e,u,i):null,d={version:br,kind:wr,prepareHash:u,simulation:i,intent:a,intentSummary:a.summary,attestation:c,review:l,custody:"none",execution:"prepare-only",signingReady:!1,broadcastReady:!1,executionReady:!1,createdAt:s};return ie({...d,artifactHash:jo(d)})}function Re(e,t={}){let r=t.label||"prepare verification";if(Ae(e,"artifact"),Number(e.version)!==br)throw new Error(`${r}: unsupported verification artifact version`);if(e.kind!==wr)throw new Error(`${r}: verification artifact kind required`);if(e.custody!=="none")throw new Error(`${r}: verification artifact custody must be none`);if(e.execution!=="prepare-only")throw new Error(`${r}: verification artifact must stay prepare-only`);if(e.signingReady===!0||e.broadcastReady===!0||e.executionReady===!0)throw new Error(`${r}: verification artifact must not claim a ready execution flag`);if(e.attestation?.teeAttested===!0)throw new Error(`${r}: TEE attestation is not claimed or accepted`);if(!["ok","success","failed","error","unavailable","unknown"].includes(String(e.simulation?.status||"")))throw new Error(`${r}: simulation status required`);if(typeof e.intentSummary!="string"||!e.intentSummary.trim())throw new Error(`${r}: human-readable intent summary required`);if(!e.attestation||typeof e.attestation!="object")throw new Error(`${r}: attestation record required`);if(!Array.isArray(e.attestation.notClaimed)||!e.attestation.notClaimed.includes("tee-attestation"))throw new Error(`${r}: attestation must honestly exclude TEE claims`);let{artifactHash:n,...o}=e;if(Ge(n)!==jo(o))throw new Error(`${r}: artifactHash mismatch \u2014 verification artifact was altered`);if(t.prepareHash){let s=Ge(t.prepareHash),i=Ge(e.prepareHash);if(!s||s!==i)throw new Error(`${r}: verification artifact does not bind this prepare`)}return e}function Do(e,t={}){Ae(e,"prepared");let r=t.artifact&&typeof t.artifact=="object"?t.artifact:bt({prepared:e,simulation:t.simulation,intent:t.intent,env:t.env,nowMs:t.nowMs});return Re(r,{label:t.label||"prepare verification"}),{...e,prepareVerification:r}}function wt(e,t={}){let r=t.label||"armPreparedAction";if(!e||typeof e!="object")throw new Error(`${r}: prepared object required`);let n=e.prepareVerification||e.verificationArtifact||e.deskCheckpoint?.prepareVerification||t.checkpoint?.prepareVerification;if(!n)throw new Error(`${r}: prepare verification artifact required before arm`);return Re(n,{label:r,...e.prepareHash?{prepareHash:e.prepareHash}:{}}),Er(e,r),n}function Fo({session:e={},prepareVerification:t=null,runId:r=null,nowMs:n=Date.now()}={}){let o=String(e.id||"").trim();if(!o)throw new TypeError("desk session checkpoint: session id required");let s=Number(n);if(!Number.isSafeInteger(s)||s<=0)throw new TypeError("desk session checkpoint: bounded updatedAt required");let i=null;return t!=null&&(i=Re(t,{label:"desk session checkpoint"})),ie({version:gr,kind:Ar,sessionId:o,generation:e.generation?String(e.generation):null,mode:e.mode?String(e.mode):null,runId:r||e.run?.id||null,updatedAt:s,title:ge(e.title,"",48),agentId:ge(e.agentId,"oracle",80),provider:ge(e.provider,"",80),model:ge(e.model,"",120),chain:ge(e.chain,"",40),workspace:ge(e.workspace,"",240),prepareVerification:i,custody:"none",execution:"prepare-only"})}function Mo(e,t={}){let r=t.label||"desk session checkpoint";if(Ae(e,"checkpoint"),Number(e.version)!==gr)throw new Error(`${r}: unsupported checkpoint version`);if(e.kind!==Ar)throw new Error(`${r}: desk session checkpoint kind required`);if(!e.sessionId)throw new Error(`${r}: session id required`);if(e.custody!=="none")throw new Error(`${r}: checkpoint custody must be none`);if(e.execution!=="prepare-only")throw new Error(`${r}: checkpoint must stay prepare-only`);if(e.prepareVerification&&Re(e.prepareVerification,{label:r}),t.sessionId&&String(t.sessionId)!==String(e.sessionId))throw new Error(`${r}: checkpoint does not bind this session`);return e}function Ho(e,t={}){return!e||typeof e!="object"||e.deskCheckpoint==null?null:Mo(e.deskCheckpoint,{label:t.label||"desk session checkpoint",sessionId:e.id})}function rc(e,t,r={}){let n=bt({prepared:t,simulation:r.simulation??t?.simulation,intent:r.intent,env:r.env,nowMs:r.nowMs});return e&&typeof e=="object"&&(e.prepareVerification=n),n}var br,wr,gr,Ar,yt,Ja,Qa,Xa,Za,nc,Sr=z(()=>{Po();sr();br=1,wr="prepare-verification",gr=1,Ar="desk-session-checkpoint",yt=Object.freeze({NONE:"none",PREPARE_CHECKSUM:"prepare-checksum",PREPARE_HMAC:"prepare-hmac"}),Ja=/^(?:0x)?[0-9a-f]{64}$/i,Qa=Object.freeze(["signature","signedTx","signedTransaction","rawTransaction","signedPayload","signedRaw"]),Xa=Object.freeze(["txid","txHash","transactionHash","broadcastHash"]),Za=Object.freeze(["tee-attestation","remote-attestation","hardware-enclave","trusted-execution-environment","execution-authorization","signature","broadcast"]);nc={createPrepareVerificationArtifact:bt,assertPrepareVerificationArtifact:Re,attachPrepareVerification:Do,assertPrepareVerificationForArm:wt,createDeskSessionCheckpoint:Fo,restoreDeskSessionCheckpoint:Ho}});var Wo={};Ze(Wo,{armPreparedAction:()=>dc,callSigner:()=>zo,queueOwnerAction:()=>Ko});import{existsSync as oc,readFileSync as sc}from"node:fs";import{request as ic}from"node:http";import ac from"node:path";function uc(e=process.env){let t=String(e.ORACLE_SIGNER_URL||cc).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 lc(e=process.env){if(e.ORACLE_SIGNER_TOKEN)return String(e.ORACLE_SIGNER_TOKEN);let t=ac.join(mt(),"signer","signer-token");return oc(t)?sc(t,"utf8").trim():null}function zo(e,{method:t="GET",body:r=null,env:n=process.env,timeoutMs:o=4e3}={}){let s=uc(n),i=lc(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=ic({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 Ko(e,t=process.env){if(!e||e.version!==1||!e.surface)throw new Error("queueOwnerAction: version-1 surface envelope required");return zo("/pending",{method:"POST",body:{artifact:e},env:t,timeoutMs:8e3})}async function dc(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 wt(e,{env:t,label:"armPreparedAction"}),Ko(r,t)}var cc,Go=z(()=>{Ro();Sr();cc="http://127.0.0.1:9462"});var $e=Object.freeze({PASS:"PASS",WARN:"WARN",BLOCK:"BLOCK",UNKNOWN:"UNKNOWN"}),Ss=new Set(["LIVE","CACHED","STALE","UNKNOWN","UNAVAILABLE"]),Gr=/^0x[0-9a-fA-F]{40}$/,vs=/^0x[0-9a-fA-F]{64}$/;function Oe(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Oe(t);Object.freeze(e)}return e}function Y(e,t=null){return e&&typeof e=="object"?structuredClone(e):t}function Jr(e){return typeof e!="string"||!Number.isFinite(Date.parse(e))?null:new Date(e).toISOString()===e?e:null}function Yr(e){return!!(e&&Ss.has(e.evidence)&&Jr(e.observedAt))}function Qr(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 et(e){return[...new Set(e.filter(Boolean))]}function Is(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]])!Yr(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||!Yr(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"),Qr(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=et(t);return o.length?Oe({status:$e.BLOCK,whyBlocked:o}):r.length?Oe({status:$e.UNKNOWN,whyBlocked:et(r)}):n.length?Oe({status:$e.WARN,whyBlocked:[],warnings:et(n)}):Oe({status:$e.PASS,whyBlocked:[]})}function Os(e={}){let t=Y(e,{}),r=Object.fromEntries(Object.entries(t).map(([o,s])=>[o,Jr(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 Xr(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("candidate must be an object");let t=Y(e.chain,{}),r=Y(e.token,{}),n=Y(e.pool),o=Y(e.venue,{}),s=Y(e.signal,{}),i=Y(e.route,{});i.cost=Qr(i.cost);let a=Is({...e,chain:t,token:r,pool:n,venue:o,signal:s,route:i}),c=s.unsolicitedAirdrop===!0,u=Gr.test(r.address||"")?r.address.toLowerCase():"unknown-token",l=Gr.test(n?.address||"")?n.address.toLowerCase():vs.test(n?.poolId||"")?n.poolId.toLowerCase():"unknown-pool",d=`${Number.isInteger(t.id)?t.id:"unknown-chain"}:${u}:${l}:${o.key||"unknown-venue"}`;return Oe({id:d,status:a.status,chain:t,token:r,pool:n,venue:o,signal:s,risk:Y(e.risk,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),sellability:Y(e.sellability,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),sellSimulation:Y(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:Y(e.prepared,{status:"NOT_PREPARED",unsigned:!0}),whyBlocked:et([...e.whyBlocked||[],...a.whyBlocked]),latency:Os(e.latency),held:c?!1:e.held===!0,eligible:c?!1:a.status===$e.PASS&&e.eligible!==!1})}function Zr(e=[]){if(!Array.isArray(e))throw new TypeError("candidates must be an array");return Object.freeze(e.map(Xr).sort((t,r)=>t.id.localeCompare(r.id)))}import{AbiCoder as xs,keccak256 as ks}from"ethers";var en=/^0x[0-9a-fA-F]{40}$/,X=/^0x[0-9a-fA-F]{64}$/,Ns=xs.defaultAbiCoder();function le(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))le(t);Object.freeze(e)}return e}function tn(e){return String(e?.message||e||"unknown scan failure").slice(0,300)}function de(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 Cs(e){if(!e||typeof e!="object")return"factory descriptor is invalid";if(!en.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=>!en.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 qe(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 on(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 rn(e,t,r){let n=on(e,t);if(!X.test(n||""))return null;let o=BigInt(n);return o<1n<<BigInt(r)?o:null}function nn(e,t,r){let n=on(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 Ts(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=qe(e,{topic:2}),o=qe(e,{topic:3}),s=rn(e,0,24),i=nn(e,1,24),a=qe(e,{dataWord:2}),c=rn(e,3,160),u=nn(e,4,24),l=de(e.blockNumber),d=de(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,y=f?n:o;if(ks(Ns.encode(["address","address","uint24","int24","address"],[n,o,Number(s),i,a])).toLowerCase()!==e.topics[1].toLowerCase())return null;let v=e.transactionHash.toLowerCase();return{id:`${t.chainId}:${v}:${d}`,chainId:t.chainId,factoryId:t.id||null,factoryAddress:t.factoryAddress.toLowerCase(),tokenAddress:h,quoteAsset:y,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:v,logIndex:d,evidence:"LIVE"}}function Rs(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=qe(e,r.layout.token),u=qe(e,r.layout.pool),l=de(e.blockNumber),d=de(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 Ls(e,t,r){return r.decoder==="uniswap-v4-initialize"?Ts(e,t,r):Rs(e,t,r)}async function sn(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=de(e.fromBlock??e.cursor?.nextBlock),s=de(e.toBlock);if(o===null||s===null||o<0||s<o)throw new TypeError("a valid integer block range is required");let i=le({nextBlock:de(e.cursor?.nextBlock)??o});if(n)return le({status:"UNKNOWN",discoveries:[],unavailable:[],cursor:i,whyBlocked:["reorg hint requires canonical range reconciliation"]});let a=[],c=[];for(let d of r){let p=Cs(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 le({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,y)=>h.topic0.localeCompare(y.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 le({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`scan failed: ${tn(h)}`]})}if(!m||m.complete!==!0||m.evidence&&m.evidence!=="LIVE"){let h=Array.isArray(m?.failedAt)?` at ${m.failedAt.join("-")}`:"";return le({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`incomplete block range${h}${m?.error?`: ${tn(m.error)}`:""}`]})}for(let h of Array.isArray(m.logs)?m.logs:[]){let y=p.find(v=>v.topic0.toLowerCase()===String(h?.topics?.[0]||"").toLowerCase()),g=y&&Ls(h,d,y);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 le({status:"LIVE",discoveries:[...l.values()],unavailable:a,cursor:{nextBlock:s+1},whyBlocked:a.map(d=>d.reason)})}import{createHash as _s}from"node:crypto";var an="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 kt(e){return Array.isArray(e)?`[${e.map(kt).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${kt(e[t])}`).join(",")}}`:JSON.stringify(e)}function cn(e){return`sha256:${_s("sha256").update(kt(e)).digest("hex")}`}function un(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 Ct(e=[]){if(!Array.isArray(e))throw new TypeError("evidence records must be an array");let t=new Set,r=an,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=un(o,s+1,r),a=cn(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 Tt(e=[],t){let r=Ct(e);if(r.some(s=>s.id===t?.id))throw new Error(`duplicate evidence event id: ${t.id}`);let n=r.at(-1)?.digest??an,o=un(t,r.length+1,n);return Nt([...r,{...o,digest:cn(o)}])}var ln=Object.freeze({ALERT_ONLY:"alert_only",EXECUTE:"execute"});function dn(e){return e?.mode==="shadow"?ln.ALERT_ONLY:ln.EXECUTE}function tt(e,t){return!!(e?.mode&&e.mode!=="shadow"&&t?.policyEligible===!0)}function fn(e,t,r){return tt(e,t)&&r?.prepared===!0}var Ps="0x783cca1c0412dd0d695e784568c96da2e9c22ff989357a2e8b1d9b2b4e6b7118",uu=Object.freeze([Object.freeze({topic0:Ps,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})})})]),lu=Object.freeze({amountIn:"1000000000000000",quoteAssetDecimals:18,slippageBps:100,maxImpactPct:25,timeoutMs:4e3}),du=Object.freeze({amountIn:"1000000",quoteAssetDecimals:9,slippageBps:100,maxImpactPct:25,timeoutMs:12e3}),fu=Object.freeze([Object.freeze({chainId:1,key:"ethereum",factoryAddress:"0x1f98431c8ad98523631ae4a59f267346ea31f984",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"}),Object.freeze({chainId:10,key:"optimism",factoryAddress:"0x1f98431c8ad98523631ae4a59f267346ea31f984",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"}),Object.freeze({chainId:56,key:"bsc",factoryAddress:"0xdb1d10011ad0ff90774d0c6bb92e5c5c8b4461f7",router:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2"}),Object.freeze({chainId:137,key:"polygon",factoryAddress:"0x1f98431c8ad98523631ae4a59f267346ea31f984",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"}),Object.freeze({chainId:8453,key:"base",factoryAddress:"0x33128a8fc17869897dce68ed026d694621f6fdfd",router:"0x2626664c2603336E57B271c5C0b26F421741e481"}),Object.freeze({chainId:42161,key:"arbitrum",factoryAddress:"0x1f98431c8ad98523631ae4a59f267346ea31f984",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"}),Object.freeze({chainId:43114,key:"avalanche",factoryAddress:"0x740b1c1de25031c31ff4fc9a62f554a55cdc1bad",router:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE"}),Object.freeze({chainId:999,key:"hyperevm",factoryAddress:"0xb1c0fa0b789320044a6f623cfe5ebda9562602e3",router:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D"}),Object.freeze({chainId:988,key:"stable",factoryAddress:"0x88f0a512ef09175d456bc9547f914f48c013e4aa",router:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",provenance:"chains.config router.factory() on 2026-08-05"}),Object.freeze({chainId:2741,key:"abstract",factoryAddress:"0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1",router:"0x7712FA47387542819d4E35A23f8116C90C18767C",provenance:"chains.config pool.factory() on 2026-08-05"}),Object.freeze({chainId:4663,key:"robinhood",factoryAddress:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",router:"0xcaf681a66d020601342297493863e78c959e5cb2"})]);import Ot from"node:fs";import Uc from"node:os";import ce from"node:path";xe();var Ut={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0},elysium:{chainId:1339,name:"Elysium",rpcEnv:["ELYSIUM_RPC_URL"],evm:!0,readOnly:!0}};var mi=new Map(Object.values(Ut).map(e=>[e.chainId,e]));function On(e){return mi.get(Number(e))||null}function xn(e,t=process.env){let r=On(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 hi,getAddress as yi}from"ethers";var kn=new hi(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Nn(e,t){try{return yi(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}var bi={1:"https://ethereum.publicnode.com",137:"https://polygon-bor-rpc.publicnode.com",42161:"https://arbitrum-one-rpc.publicnode.com",8453:"https://base-rpc.publicnode.com",10:"https://optimism-rpc.publicnode.com",988:"https://rpc.stable.xyz",56:"https://bsc-rpc.publicnode.com",43114:"https://avalanche-c-chain-rpc.publicnode.com",999:"https://rpc.hyperliquid.xyz/evm",2741:"https://api.mainnet.abs.xyz",4663:"https://rpc.mainnet.chain.robinhood.com",1339:"https://rpc.elysiumchain.tech"};function wi(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=xn(e,r);return n||bi[Number(e)]||null}var gi=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Ai(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!gi.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 De=new Map,Cn=new Map;function Ei(e){let t=new Error(e?.message||JSON.stringify(e));return t.code=e?.code,t}function Si(e){if(e?.error)throw Ei(e.error);return e?.result}function vi(e,t,r){return`${e}
|
|
4
4
|
${t}
|
|
5
5
|
${JSON.stringify(r??[])}`}async function Ii(e,t,r){return te(e,{method:"POST",body:t,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function U(e,t,r=[],n={}){let o=String(t||""),s=Ai(o),i=wi(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=Cn.get(i);if(l!=null)return l}let c=n.dedupe!==!1&&!n.signal?vi(i,o,r):null;if(c&&De.has(c))return De.get(c);let u=(async()=>{let l=await Ii(i,{jsonrpc:"2.0",id:1,method:t,params:r},n),d=Si(l);return s==="eth_chainid"&&typeof d=="string"&&Cn.set(i,d),d})();return c&&(De.set(c,u),u.finally(()=>{De.get(c)===u&&De.delete(c)}).catch(()=>{})),u}async function Tn(e,t={}){let r=await U(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function Rn(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await U(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function Ln(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=Nn(e.token||e.tokenAddress,"token"),o=Nn(e.account||e.owner||e.address,"account"),s=kn.encodeFunctionData("balanceOf",[o]),i=await U(r,"eth_call",[{to:n,data:s},e.blockTag||"latest"],t),a=kn.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"}}xe();var Oi=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"]);function _n(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 Dt(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=_n(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(),y=0;return s.has(d)||Oi.has(p)?y=300:i&&d===i&&(y=100),h.includes("v4")?y+=20:h.includes("v3")?y+=10:(h.includes("v2")||h.includes("raydium")||h.includes("orca")||h.includes("meteora"))&&(y+=8),{pool:c,score:y*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 Pn(e,t=[]){let r=Array.isArray(t)?t:[];return r.length&&_n(e,r[0]).address||null}var xi="https://api.dexscreener.com",Bu=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function ki(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||xi).replace(/\/$/,"")}function Ni(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 Ci(e,t){return te(`${ki(t)}${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}async function jn(e,t={}){return Ci(`/latest/dex/tokens/${Ni(e,"tokenAddress")}`,t)}xe();var it=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),x=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),S=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),Ti=/^0x[0-9a-fA-F]{40}$/;function Ri(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}Ti.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))it.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 Li(e){let{ok:t,errors:r,warnings:n}=Ri(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
|
|
6
6
|
- ${r.join(`
|
|
7
|
-
- `)}`);let o=e.capabilities||{},s=it.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:it.filter(a=>!s.includes(a))}},supports(a){return s.includes(a)}};for(let a of it)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 Bn=new Map;function $n(e){let t=Li(e);return Bn.set(t.chainId,t),t}function qn(e){return Bn.get(Number(e))||null}var Mt={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},W=e=>BigInt(e).toString(16).padStart(64,"0"),Fe=e=>e.slice(2).toLowerCase().padStart(64,"0");function _i(e,t){return`0x${Mt.getAmountsOut}`+W(e)+W(64)+W(t.length)+t.map(Fe).join("")}function Pi(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 Ft(e,t="router"){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}var Ht=100;function ji(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Ht)throw new Error(`slippageBps ${r} exceeds the ${Ht} 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 U(t,"eth_call",[{to:o,data:_i(s,i)},"latest"],a);return Pi(c?.result??c)}return{async quote({tokenIn:o,tokenOut:s,amountIn:i,path:a},c={}){let u=Ft(c.scanner);if(!u)return{chainId:t,evidence:x.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:x.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:u,path:l,evidence:x.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=Ft(a.scanner),u=i||r;if(u&&String(o).toLowerCase()===String(u).toLowerCase())return{chainId:t,token:o,verdict:S.UNKNOWN,evidence:x.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!c||!u)return{chainId:t,token:o,verdict:S.UNKNOWN,evidence:x.UNAVAILABLE,reason:c?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let l=await n(c,s,[u,o],a);if(!l)return{chainId:t,token:o,verdict:S.FAIL,evidence:x.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let d=l[l.length-1];if(d===0n)return{chainId:t,token:o,verdict:S.FAIL,evidence:x.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let p=await n(c,d,[o,u],a);if(!p)return{chainId:t,token:o,verdict:S.FAIL,evidence:x.LIVE,leg:"sell",bought:d.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let f=p[p.length-1],m=Number(f*10000n/BigInt(s)),h=S.PASS,y="round trip completes with expected fee/impact loss";return m<5e3?(h=S.FAIL,y=`round trip returns only ${(m/100).toFixed(2)}% -- punitive tax or no real liquidity`):m<9e3&&(h=S.CAUTION,y=`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:y,amountIn:String(s),bought:d.toString(),returned:f.toString(),retentionBps:m,evidence:x.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=Ft(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!==x.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let y=ji(h.amountOut,c);if(y<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let g=BigInt(Math.floor(Date.now()/1e3)+Number(u)),v=r&&m[0].toLowerCase()===r.toLowerCase()&&d.useNative,N=v?`0x${Mt.swapExactETHForTokens}`+W(y)+W(128)+Fe(a)+W(g)+W(m.length)+m.map(Fe).join(""):`0x${Mt.swapExactTokensForTokens}`+W(i)+W(y)+W(160)+Fe(a)+W(g)+W(m.length)+m.map(Fe).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:f,data:N,value:v?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:h.amountOut,minOut:y.toString(),slippageBps:c,maxSlippageBps:Ht,deadline:g.toString()},requires:v?[]:[{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 Bi=[100,500,3e3,1e4],Dn={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},me=e=>BigInt(e).toString(16).padStart(64,"0"),Me=e=>e.slice(2).toLowerCase().padStart(64,"0"),Fn=/^0x[0-9a-fA-F]{40}$/,zt=100;function $i(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>zt)throw new Error(`slippageBps ${r} exceeds the ${zt} 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 Vt(e,t){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function Mn(e){let{chainId:t,wrappedNative:r}=e;async function n({quoter:s,tokenIn:i,tokenOut:a,amountIn:c,fee:u},l){let d=`0x${Dn.quoteExactInputSingle}`+Me(i)+Me(a)+me(c)+me(u)+me(0),p=await U(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(Bi.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=Vt(c.scanner,"quoter");if(!u)return{chainId:t,evidence:x.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(!Fn.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:x.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:x.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=Vt(c.scanner,"quoter"),l=(e.stableQuoteAssets||[]).map(A=>String(A).toLowerCase()),d=null;!a&&typeof e.resolveQuoteAsset=="function"&&(d=await e.resolveQuoteAsset(s,c).catch(()=>null));let p=String(s).toLowerCase(),f=String(r||"").toLowerCase();if(f&&p===f)return{chainId:t,token:s,verdict:S.UNKNOWN,evidence:x.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};let m=a||d||(l[0]&&p!==l[0]?l[0]:null)||r;if(m&&p===String(m).toLowerCase())return{chainId:t,token:s,verdict:S.UNKNOWN,evidence:x.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!u||!m)return{chainId:t,token:s,verdict:S.UNKNOWN,evidence:x.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 A=l.find(I=>I&&I!==String(m).toLowerCase()&&I!==String(s).toLowerCase());if(A){let I=await o({quoter:u,tokenIn:A,tokenOut:s,amountIn:i},c);if(I.best){let E=await o({quoter:u,tokenIn:s,tokenOut:A,amountIn:I.best.amountOut},c);if(E.best){let k=E.best.amountOut,O=Number(k*10000n/BigInt(i)),_=S.PASS,b="round trip vs dollar book completes with expected fee/impact loss";return O<5e3?(_=S.FAIL,b=`round trip vs dollar book returns only ${(O/100).toFixed(2)}% -- punitive tax or no real liquidity`):O<9e3&&(_=S.CAUTION,b=`round trip vs dollar book returns ${(O/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:s,base:A,quoteAsset:A,verdict:_,reason:b,amountIn:String(i),bought:I.best.amountOut.toString(),returned:k.toString(),retentionBps:O,buyFee:I.best.fee,sellFee:E.best.fee,evidence:x.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:t,token:s,verdict:S.FAIL,evidence:x.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let y=await o({quoter:u,tokenIn:s,tokenOut:m,amountIn:h.best.amountOut},c);if(!y.best){let A=l.find(I=>I&&I!==String(m).toLowerCase()&&I!==String(s).toLowerCase());if(A){let I=await o({quoter:u,tokenIn:A,tokenOut:s,amountIn:i},c),E=I.best?await o({quoter:u,tokenIn:s,tokenOut:A,amountIn:I.best.amountOut},c):{best:null};if(I.best&&E.best){let k=E.best.amountOut,O=Number(k*10000n/BigInt(i)),_=S.PASS,b="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return O<5e3?(_=S.FAIL,b=`dollar-book round trip returns only ${(O/100).toFixed(2)}%`):O<9e3&&(_=S.CAUTION,b=`dollar-book round trip returns ${(O/100).toFixed(2)}%`),{chainId:t,venue:"uniswap-v3",token:s,base:A,quoteAsset:A,verdict:_,reason:b,amountIn:String(i),bought:I.best.amountOut.toString(),returned:k.toString(),retentionBps:O,buyFee:I.best.fee,sellFee:E.best.fee,evidence:x.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:t,token:s,verdict:S.FAIL,evidence:x.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=y.best.amountOut,v=Number(g*10000n/BigInt(i)),N=S.PASS,L="round trip completes with expected fee/impact loss";return v<5e3?(N=S.FAIL,L=`round trip returns only ${(v/100).toFixed(2)}% -- punitive tax or no real liquidity`):v<9e3&&(N=S.CAUTION,L=`round trip returns ${(v/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:s,base:m,verdict:N,reason:L,amountIn:String(i),bought:h.best.amountOut.toString(),returned:g.toString(),retentionBps:v,buyFee:h.best.fee,sellFee:y.best.fee,evidence:x.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=Vt(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(!Fn.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!==x.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let m=l??f.fee,h=$i(f.amountOut,u);if(h<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let y=!!(d.useNative||f.useNative)&&r&&String(s).toLowerCase()===String(r).toLowerCase(),g=`0x${Dn.exactInputSingle}`+Me(s)+Me(i)+me(m)+Me(c)+me(a)+me(h)+me(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:p,data:g,value:y?String(a):"0x0"},guard:{quotedOut:f.amountOut,minOut:h.toString(),slippageBps:u,maxSlippageBps:zt,fee:m},requires:y?[]:[{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 at={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function Hn(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function Vn(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 qi(e){let{chainId:t}=e;async function r(n,o,s){return U(t,"eth_call",[{to:n,data:o},"latest"],s)}return{async blockNumber(n={}){let o=await Tn(t,n);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:x.LIVE}},async nativeBalance(n,o={}){let s=await Rn(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:x.LIVE}},async tokenBalance({token:n,owner:o},s={}){let i=await Ln({chainId:t,token:n,owner:o},s);return{chainId:t,token:n,owner:o,raw:i?.balance??i,evidence:x.LIVE}},async resolveToken(n,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:t,token:n,evidence:x.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,at.decimals,o).catch(()=>null),r(n,at.symbol,o).catch(()=>null),r(n,at.name,o).catch(()=>null),r(n,at.totalSupply,o).catch(()=>null)]),u=Hn(s?.result??s),l=u!==null||i?.result||a?.result,d={chainId:t,address:n,decimals:u===null?null:Number(u),symbol:Vn(i?.result??i),name:Vn(a?.result??a),totalSupply:(Hn(c?.result??c)??null)?.toString()??null,evidence:l?x.LIVE:x.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:x.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await jn(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=Dt(n,c,{stables:e.stableQuoteAssets||[],wrappedNative:e.wrappedNative});return{chainId:t,token:n,pools:u,topPool:u[0]||null,quoteAsset:Pn(n,u),evidence:u.length?x.LIVE:x.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 In(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 U(t,"eth_getLogs",[m],c).catch(y=>({error:String(y?.message||y)}));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:x.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:x.LIVE}},async scoreRisk(n,o={}){let s=[],i=S.PASS,a=l=>{let d={[S.PASS]:0,[S.CAUTION]:1,[S.UNKNOWN]:2,[S.FAIL]:3};d[l]>d[i]&&(i=l)},[c,u]=await Promise.all([this.resolveToken(n,o),this.resolvePools(n,o)]);if(c.evidence!==x.LIVE?(s.push({check:"erc20-metadata",result:S.UNKNOWN,detail:c.warning}),a(S.UNKNOWN)):s.push({check:"erc20-metadata",result:S.PASS,detail:`${c.symbol} / ${c.decimals}d`}),u.evidence===x.UNAVAILABLE)s.push({check:"liquidity",result:S.UNKNOWN,detail:u.reason}),a(S.UNKNOWN);else if(!u.pools.length)s.push({check:"liquidity",result:S.FAIL,detail:"no pool with liquidity found"}),a(S.FAIL);else{let l=u.pools[0],d=l.liquidityUsd??0;d<5e3?(s.push({check:"liquidity",result:S.CAUTION,detail:`top pool only $${d}`}),a(S.CAUTION)):s.push({check:"liquidity",result:S.PASS,detail:`$${d} on ${l.dex}`}),l.createdAt&&Date.now()-l.createdAt<24*3600*1e3&&(s.push({check:"age",result:S.CAUTION,detail:"pool under 24h old"}),a(S.CAUTION))}if(typeof this.sellSimulation=="function"){let l=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},o).catch(d=>({verdict:S.UNKNOWN,reason:String(d?.message||d)}));s.push({check:"sellability",result:l.verdict,detail:l.retentionBps!=null?`round trip returns ${(l.retentionBps/100).toFixed(2)}% -- ${l.reason}`:l.reason}),a(l.verdict)}else s.push({check:"sellability",result:S.UNKNOWN,detail:"no verified router on this chain, so a round-trip sell simulation cannot run. Treat as unproven -- a buy path is not an exit path."}),a(S.UNKNOWN);return{chainId:t,token:n,verdict:i,checks:s,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function zn(e){let r={...qi(e)},n=new Set((e.venues||[]).map(s=>s.kind));e.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,Mn({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 Kn=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 Wn(){return Kn.map(e=>$n(zn(e)))}import{AbiCoder as Ui,Interface as Xn,getAddress as ye,isAddress as Zn,keccak256 as Di}from"ethers";var Kt="0x0000000000000000000000000000000000000000",Fi="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Mi=Ui.defaultAbiCoder(),Gn=new Xn(["function quoteExactInputSingle((address tokenIn,address tokenOut,uint256 amountIn,uint24 fee,uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut,uint160 sqrtPriceX96After,uint32 initializedTicksCrossed,uint256 gasEstimate)"]),Jn=new Xn(["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)"]),G=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"})}),Ve=Object.freeze({1:Object.freeze({quoter:"0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203",wrappedNative:G[1].wrappedNative}),10:Object.freeze({quoter:"0x1f3131a13296fb91c90870043742c3cdbff1a8d7",wrappedNative:G[10].wrappedNative}),56:Object.freeze({quoter:"0x9f75dd27d6664c475b90e105573e550ff69437b0",wrappedNative:G[56].wrappedNative}),137:Object.freeze({quoter:"0xb3d5c3dfc3a7aebff71895a7191796bffc2c81b9",wrappedNative:G[137].wrappedNative}),8453:Object.freeze({quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",wrappedNative:G[8453].wrappedNative}),42161:Object.freeze({quoter:"0x3972c00f7ed4885e145823eb7c655375d275a1c5",wrappedNative:G[42161].wrappedNative}),43114:Object.freeze({quoter:"0xbe40675bb704506a3c2ccfb762dcfd1e979845c2",wrappedNative:G[43114].wrappedNative}),4663:Object.freeze({quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",wrappedNative:G[4663].wrappedNative})}),Hi=Object.freeze([100,500,3e3,1e4]);function he(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 eo(e,t){let r=String(e??"");if(!/^[1-9][0-9]*$/.test(r))throw new Error(`${t} must be a positive raw-unit integer string`);return BigInt(r)}function to(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 Wt(e){let t=String(e??"").trim().toLowerCase();return t===""||t==="eth"||t===Kt||t===Fi}function He(e,t){if(!Zn(String(e??"")))throw new Error(`${t} must be an EVM address`);return ye(String(e))}function Yn(e,t,r){return Wt(e)?ye(t.wrappedNative):He(e,r)}function Qn(e,t){return Wt(e)?ye(Kt):He(e,t)}function ro(e,t){let r=Number(e);if(!Number.isInteger(r)||r<0||r>16777215)throw new Error(`${t} must be uint24`);return r}function Vi(e,t){let r=Number(e);if(!Number.isInteger(r)||r<-8388608||r>8388607)throw new Error(`${t} must be int24`);return r}function zi({tokenIn:e,tokenOut:t,poolKey:r,poolId:n}){he(r,new Set(["currency0","currency1","fee","tickSpacing","hooks"]),"V4 PoolKey");let o=He(r.currency0,"V4 currency0"),s=He(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:ro(r.fee,"V4 fee"),tickSpacing:Vi(r.tickSpacing,"V4 tickSpacing"),hooks:He(r.hooks??Kt,"V4 hooks")}),a=Qn(e,"tokenIn"),c=Qn(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=Di(Mi.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 Gt(e,t){if(Wt(t))return!0;if(!Zn(String(t??"")))return!1;let r=G[Number(e)]?.wrappedNative||Ve[Number(e)]?.wrappedNative;return!!(r&&ye(String(t)).toLowerCase()===ye(r).toLowerCase())}async function no(e={},t={},r={}){he(e,new Set(["chainId","tokenIn","tokenOut","amountIn","fee"]),"V3 read"),he(t,new Set(["timeoutMs"]),"V3 read options"),he(r,new Set(["rpc"]),"V3 read dependencies");let n=Number(e.chainId),o=G[n];if(!o)throw new Error(`V3 read unavailable on chain ${e.chainId}`);let s=Yn(e.tokenIn,o,"tokenIn"),i=Yn(e.tokenOut,o,"tokenOut");if(s.toLowerCase()===i.toLowerCase())throw new Error("tokenIn and tokenOut must differ");let a=eo(e.amountIn,"amountIn"),c=e.fee==null?Hi:[ro(e.fee,"V3 fee")],u=r.rpc||U,l=to(t.timeoutMs),d=await Promise.all(c.map(async f=>{let m=Gn.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 y=Gn.decodeFunctionResult("quoteExactInputSingle",h);return Object.freeze({ok:!0,fee:f,amountOut:y[0].toString(),gasEstimate:y[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:ye(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 oo(e={},t={},r={}){he(e,new Set(["chainId","tokenIn","tokenOut","amountIn","poolKey","poolId"]),"V4 read"),he(t,new Set(["timeoutMs"]),"V4 read options"),he(r,new Set(["rpc"]),"V4 read dependencies");let n=Number(e.chainId),o=Ve[n];if(!o)throw new Error(`V4 read unavailable on chain ${e.chainId}`);let s=eo(e.amountIn,"amountIn");if(s>0xffffffffffffffffffffffffffffffffn)throw new Error("amountIn exceeds uint128");let i=zi(e),a=Jn.encodeFunctionData("quoteExactInputSingle",[{poolKey:i.poolKey,zeroForOne:i.zeroForOne,exactAmount:s,hookData:"0x"}]),u=await(r.rpc||U)(n,"eth_call",[{to:o.quoter,data:a},"latest"],to(t.timeoutMs));if(!u||u==="0x")throw new Error("V4 read returned an empty result");let l=Jn.decodeFunctionResult("quoteExactInputSingle",u);return Object.freeze({venue:"uniswap-v4",chainId:n,quoter:ye(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 Ki=new Set(["chainId","tokenIn","tokenOut","amountIn","v4PoolKey","v4PoolId"]),Wi=new Set(["maxImpactPct","timeoutMs"]),Gi=new Set(["quoteV3","quoteV4","gasPrice"]);function Jt(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 Qt(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 so(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 Ji(e){if(e<=1n)return null;let t=e/1000n;return t>0n&&t<e?t:1n}function Yi({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 Yt(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 Qi({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 Gt(e,r)?d:Gt(e,t)?d*l/u:null}async function Xi(e,t){let r=await U(e,"eth_gasPrice",[],{timeoutMs:t});return re(r)}function Zi(e,t){return Object.freeze({source:e,quality:"FAILED",amountOut:null,error:String(t?.message||t).slice(0,240)})}async function io({source:e,amountIn:t,timeoutMs:r,fullRead:n,probeRead:o}){try{let s=await Yt(n,r,e),i=Qt(s?.amountOut,`${e} amountOut`),a=Ji(t);if(a==null)return{source:e,full:s,impactPct:null};try{let c=await Yt(()=>o(a.toString(),s),r,`${e} impact probe`),u=Yi({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 ea({inspected:e,params:t,gasPrice:r}){let n=e.full,o=Qt(n.amountOut,`${e.source} amountOut`),s=Qi({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 ta({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 Xt(e={},t={},r={}){Jt(e,Ki,"route params"),Jt(t,Wi,"route options"),Jt(r,Gi,"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=Qt(e.amountIn,"amountIn"),s=so(t.timeoutMs,12e3,250,6e4,"timeoutMs"),i=so(t.maxImpactPct,25,0,100,"maxImpactPct"),a=r.quoteV3||no,c=r.quoteV4||oo,u=r.gasPrice||Xi,l=[];G[n]&&l.push(io({source:"uniswap-v3",amountIn:o,timeoutMs:s,fullRead:()=>a({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:o.toString()},{timeoutMs:s}),probeRead:(w,T)=>a({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:w,fee:T.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&&Ve[n]&&l.push(io({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:w=>c({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:w,poolKey:e.v4PoolKey,poolId:e.v4PoolId},{timeoutMs:s})})),!l.length)throw new Error(`no verified read-only quote source on chain ${n}`);let f=Yt(()=>u(n,s),s,"gas price read").catch(()=>null),m=await Promise.all(l),h=await f,y=m.filter(w=>w.error).map(w=>Zi(w.source,w.error)),g=m.filter(w=>w.full),v=g.filter(w=>w.impactPct!=null&&w.impactPct>i).map(w=>({source:w.source,impactPct:Number(w.impactPct.toFixed(2)),reason:`price impact ${w.impactPct.toFixed(2)}% exceeds ${i}% ceiling`})),N=new Set(v.map(w=>w.source)),L=g.filter(w=>!N.has(w.source)),A=L.map(w=>ea({inspected:w,params:{...e,chainId:n},gasPrice:h})),I=A.length>0&&A.every(w=>w.costAccounted),E=I?"net":"gross";for(let w of A){let T=BigInt(w.grossOut),oe=I?BigInt(w.costInDest):0n;w.netOut=(T>oe?T-oe:0n).toString()}A.sort((w,T)=>{let oe=BigInt(I?w.netOut:w.grossOut),V=BigInt(I?T.netOut:T.grossOut);return oe===V?w.source.localeCompare(T.source):V>oe?1:-1});let k=[];I?k.push("Gas is estimated from quoter gas units and the current read-only gas price; actual gas may differ."):k.push("Gas was not accounted for; routes are ranked on gross output.");let O=L.filter(w=>w.impactPct==null).map(w=>w.source);O.length&&k.push(`Price impact is UNKNOWN for: ${O.join(", ")}.`),v.length&&k.push(`Dropped on price impact: ${v.map(w=>w.source).join(", ")}.`),!d&&Ve[n]&&k.push("V4 was not queried because no exact verified PoolKey identity was discovered.");let _=null,b=null;if(A.length>1){let w=BigInt(I?A[0].netOut:A[0].grossOut),T=BigInt(I?A[1].netOut:A[1].grossOut);T>0n&&(_=Number((w-T)*10000000n/T)/1e3,b=`${A[0].source} vs ${A[1].source}`)}let $=Object.fromEntries(L.filter(w=>w.impactPct!=null).map(w=>[w.source,Number(w.impactPct.toFixed(4))]));return Object.freeze({kind:"swap",chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:o.toString(),best:A[0]||null,routes:Object.freeze(A.map(w=>Object.freeze(w))),failed:Object.freeze(y),rankedOn:E,sourcesTried:l.length,sourcesAnswered:g.length,improvementBps:_,spreadBasis:b,priceImpact:Object.freeze($),impactRejected:Object.freeze(v),impactUnmeasured:Object.freeze(O),warnings:Object.freeze(k),note:ta({routes:A,rankedOn:E,improvementBps:_})})}var be="So11111111111111111111111111111111111111112";var Ca=new Set(["chainId","tokenIn","tokenOut","amountIn"]),Ta=new Set(["maxImpactPct","timeoutMs","quoteFn"]);function xo(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 ko(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 No(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 Ra(e,t={}){let{jupiterQuote:r}=await Promise.resolve().then(()=>(dr(),lr)),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 pr(e={},t={}){if(xo(e,Ca,"params"),xo(t,Ta,"options"),e.chainId!=null&&Number(e.chainId)!==101)throw new Error("solana quote adapter only handles chainId 101");let r=No(e.tokenIn,"tokenIn"),n=No(e.tokenOut,"tokenOut"),o=ko(e.amountIn,"amountIn");if(r===n)throw new Error("solana quote tokenIn and tokenOut must differ");let s=t.quoteFn||Ra;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=ko(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 Co({routeFn:e=pr}={}){return Object.freeze({async sellSimulation({token:t,amountIn:r,base:n}={}){let{simulateSell:o,SELL_SIM:s}=await Promise.resolve().then(()=>(Oo(),Io)),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 fc(e){return e?.token?.address||e?.tokenAddress||null}function pc(e){return e?.quoteAsset||e?.pool?.quoteAsset||null}function mc(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=fc(e),o=pc(e),s=mc(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(()=>(dr(),lr)),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 Or({prepared:e}={},t=process.env){if(e?.prepared!==!0)return{ok:!1,error:"nothing prepared"};let{armPreparedAction:r}=await Promise.resolve().then(()=>(Go(),Wo)),n=e.localSignerEnvelope||e.envelope;if(!n)return{ok:!1,error:"prepared envelope missing"};let{attachPrepareVerification:o}=await Promise.resolve().then(()=>(Sr(),Vo));return r(o({...e,localSignerEnvelope:n}),t)}import{createHash as Sc}from"node:crypto";import{createHash as hc}from"node:crypto";var M=Object.freeze({SHADOW:"shadow",ARMED:"armed",AUTONOMOUS:"autonomous"}),yc=3,bc=new Set(Object.values(M));function Cr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Cr(t);Object.freeze(e)}return e}function Nr(e){return Array.isArray(e)?`[${e.map(Nr).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${Nr(e[t])}`).join(",")}}`:JSON.stringify(e)}function wc(e){return`sha256:${hc("sha256").update(Nr(e)).digest("hex")}`}function xr(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 gc(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new TypeError(`${t} entries must be positive safe integers`);return e}function kr(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 Le(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 Je(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 At(e,t){let r=Le(e,t),[n,o=""]=r.split(".");return{digits:BigInt(n+o),scale:o.length}}function gt(e,t,r="value"){let n=At(e,r),o=At(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 Jo(e){let t=structuredClone(e);return delete t.digest,t}function Ac(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");return wc(Jo(e))}function Tr(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");let t=e.mode??M.SHADOW;if(!bc.has(t))throw new TypeError("mode must be shadow, armed, or autonomous");let r={version:1,mode:t,chains:xr(e.chains,"chains",gc),venues:xr(e.venues,"venues",kr),quoteAssets:xr(e.quoteAssets,"quoteAssets",kr),maxSpendPerTrade:Le(e.maxSpendPerTrade,"maxSpendPerTrade",{positive:!0}),maxSpendPerDay:Le(e.maxSpendPerDay,"maxSpendPerDay",{positive:!0}),minLiquidityUsd:Le(e.minLiquidityUsd,"minLiquidityUsd",{positive:!0}),maxSlippageBps:Je(e.maxSlippageBps,"maxSlippageBps",{max:1e4}),maxGas:Le(e.maxGas,"maxGas",{positive:!0}),maxPriorityFee:Le(e.maxPriorityFee,"maxPriorityFee"),maxBuysPerHour:Je(e.maxBuysPerHour,"maxBuysPerHour",{min:1}),retryCeiling:Je(e.retryCeiling,"retryCeiling",{max:yc}),ttlMs:Je(e.ttlMs,"ttlMs",{min:1}),requireSellSimulation:e.requireSellSimulation,requireRiskPass:e.requireRiskPass??!0,maxRoundTripLossBps:Je(e.maxRoundTripLossBps??1500,"maxRoundTripLossBps",{max:1e4}),killSwitch:e.killSwitch,recipient:e.recipient==null||e.recipient===""?null:kr(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!==M.SHADOW&&!r.recipient)throw new TypeError("recipient is required when mode is armed or autonomous");if(gt(r.maxSpendPerTrade,r.maxSpendPerDay)>0)throw new TypeError("maxSpendPerTrade cannot exceed maxSpendPerDay");return r.digest=Ac(r),Cr(r)}var Ec=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 Rr(e,t={},r={}){let n=Tr(Jo(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,gt(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=At(t.spentToday,"daily spend"),c=At(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,gt(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,gt(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 Ec)j(i,t.autonomousGates?.[a]!==!0,c);return j(i,n.mode!==M.AUTONOMOUS,"strategy mode is not autonomous"),Cr({strategyDigest:n.digest,mode:n.mode,policyEligible:o.length===0,blockers:o,autonomousEligible:i.length===0,autonomousBlockers:i,reportOnly:!0})}function Zo(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Zo(t);Object.freeze(e)}return e}var Yo=Object.freeze({ALERT_ONLY:"alert_only",EXECUTE:"execute"}),Qo=Object.freeze({liveQuote:20,sellSimulation:30,contractRisk:20,liquidity:15,roundTripLoss:15});function K(e,t){return{id:e,verdict:"PASS",detail:t}}function H(e,t){return{id:e,verdict:"BLOCK",detail:t}}function Xo(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function es({strategy:e,observation:t={},evaluation:r={}}={}){if(!e||typeof e!="object")throw new TypeError("snipe features require a strategy");let n=[],o=[],s=(h,y)=>{n.push(h),h.verdict==="BLOCK"&&o.push(y)};s(e.killSwitch===!0?H("killSwitch","engaged"):K("killSwitch","off"),"kill switch is engaged"),s(e.chains.includes(t.chain)?K("chain",String(t.chain)):H("chain",String(t.chain??"missing")),"chain is not on the exact allowlist"),s(e.venues.includes(t.venue)?K("venue",String(t.venue)):H("venue",String(t.venue??"missing")),"venue is not on the exact allowlist"),s(e.quoteAssets.includes(t.quoteAsset)?K("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"?K("liveQuote","LIVE"):H("liveQuote",String(i||"missing")),"live quote is missing");let a=t.sellSimulation||r.sellSimulation;s(a?.verdict==="PASS"&&a?.evidence==="LIVE"?K("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"?K("contractRisk","PASS"):H("contractRisk",String(c||"missing")),"contract risk is not PASS");let u=t.liquidityUsd;try{let h=Number(u),y=Number(e.minLiquidityUsd);s(Number.isFinite(h)&&Number.isFinite(y)&&h>=y?K("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=Xo(t.slippageBps);s(l!=null&&l<=e.maxSlippageBps?K("slippage",String(l)):H("slippage",String(t.slippageBps??"missing")),"slippage exceeds cap or is unknown");let d=Xo(t.roundTripLossBps);s(d!=null&&d<=e.maxRoundTripLossBps?K("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?K("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?K("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)?K("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"&&Qo[h.id]&&(p+=Qo[h.id]);let f=o.length===0,m=e.mode==="shadow"?Yo.ALERT_ONLY:Yo.EXECUTE;return Zo({snipeReady:f,wouldSnipe:f,armed:!1,actionMode:m,score:p,features:n,blockers:o,reportOnly:e.mode==="shadow"})}function Et(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Lr(e){return Array.isArray(e)?`[${e.map(Lr).join(",")}]`:Et(e)?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${Lr(e[t])}`).join(",")}}`:JSON.stringify(e)}function vc(e){return`cycle:${Sc("sha256").update(Lr(e)).digest("hex")}`}function Ye(e,t){if(typeof e!="function")throw new TypeError(`launch-radar runner: injected ${t} function is required`)}function ts(e){return e instanceof Error?e.message:String(e)}function _r(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(!Et(r))throw new TypeError("launch-radar runner: strategy is required");Ye(n,"discovery"),Ye(o,"evaluate");let s=e.now??(()=>new Date().toISOString()),i=e.sleep??(()=>Promise.resolve()),a=e.jitter??(()=>0);Ye(s,"clock"),Ye(i,"sleep"),Ye(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 y=0;y<=c;y+=1)try{return await m(y)}catch(g){if(h=g,y===c)break;let v=Number(a()),N=Number.isFinite(v)?Math.max(0,v):0,L=Math.min(l,u*2**y+N);await i(L)}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=dn(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 y;try{y=await d(A=>n({cursor:structuredClone(m.cursor),attempt:A,mode:r.mode}))}catch(A){return{mode:r.mode,status:"failed",blockers:[ts(A)],results:[],actionMode:h}}if(!Et(y)||!Array.isArray(y.candidates)||!(y.cursor===null||Et(y.cursor)))return{mode:r.mode,status:"failed",blockers:["discovery returned an invalid deterministic result"],results:[],actionMode:h};let g=[];for(let A of y.candidates)try{let I=await d(b=>o(structuredClone(A),{attempt:b,mode:r.mode})),E=Rr(r,I,{}),k=es({strategy:r,observation:I,evaluation:A}),O={prepared:!1},_=!1;tt(r,E)&&typeof e.prepareFn=="function"?O=await e.prepareFn({candidate:A,observation:I,strategy:r,policy:E})||{prepared:!1}:tt(r,E)&&(O={prepared:!1,blockedReasons:["prepareFn is required when strategy mode is not shadow"]}),fn(r,E,O)&&typeof e.queueFn=="function"&&(_=(await e.queueFn({prepared:O,candidate:A,observation:I,strategy:r,policy:E}))?.ok===!0),g.push({id:A?.id??null,policy:E,snipe:k,prepared:O.prepared===!0,queued:_,actionMode:h})}catch(I){g.push({id:A?.id??null,policy:{mode:r.mode,policyEligible:!1,reportOnly:r.mode===M.SHADOW,blockers:[`evaluation failed: ${ts(I)}`]},actionMode:h,prepared:!1,queued:!1})}let v={cursor:y.cursor,candidates:y.candidates,results:g},N={id:vc(v),type:r.mode===M.SHADOW?"shadow-cycle":"execute-cycle",at:s(),data:v},L=t.commitCycle({candidates:y.candidates,cursor:y.cursor,strategyStatus:{mode:r.mode,status:"inert",ambiguous:!1},event:N});return{mode:r.mode,status:L.duplicate?"duplicate":"completed",results:g,evidenceId:L.evidence.id,actionMode:h}}return Object.freeze({status:p,runCycle:f})}function rs(e){return[...new Set(e.filter(Boolean).map(String))]}function Ee(e){return Array.isArray(e)?e.map(Ee):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,Ee(r)])):e}function ae(e,t,r="UNKNOWN"){return!e||typeof e!="object"?{evidence:r,observedAt:t}:Ee({...structuredClone(e),evidence:e.evidence||r,observedAt:e.observedAt||t})}function Ic(e,t){let r=String(t||"").toLowerCase();return!!(r&&[e?.address,e?.pair,e?.poolId].some(n=>String(n||"").toLowerCase()===r))}function Oc(e,t){let r=e.poolId||e.poolAddress||null,n=[t.topPool,...t.pools?.pools||[]].filter(Boolean),o=r?n.find(i=>Ic(i,r)):t.topPool,s={address:e.poolAddress??null,poolId:e.poolId,poolKey:e.poolKey,quoteAsset:e.quoteAsset};return Ee({...o||{},...s})}function xc(e,t,r,n){let o=e.observedAt||n,s=Oc(e,t),i=ae(t.scannerRisk||t.risk,o),a=ae(t.sellability,o,"UNAVAILABLE"),c=ae(t.quote,o,"UNAVAILABLE"),u=c.evidence==="LIVE"?"PASS":"UNKNOWN";return Ee({chain:{id:e.chainId,...t.chain||{}},token:ae({address:e.tokenAddress,...t.token||{}},o,"LIVE"),pool:ae(s,o,"LIVE"),venue:ae({...e.venue,supported:e.venue?.supported===!0,verified:e.venue?.verified===!0},o,"LIVE"),signal:ae({kind:e.kind,source:"verified-factory",unsolicitedAirdrop:!1},o,"LIVE"),risk:i,sellability:a,sellSimulation:ae(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:Ee({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:rs([...r||[],...t.blockedReasons||[],t.error]),latency:{discoveredAt:o,riskCompletedAt:i.observedAt,sellabilityCompletedAt:a.observedAt,routeCompletedAt:c.observedAt,normalizedAt:n}})}async function St(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:Ee(structuredClone(a)),prepare:e.prepare===!0})}catch(u){c={error:`evaluation unavailable: ${String(u?.message||u).slice(0,300)}`}}i.push(xc(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(rs(n?.whyBlocked||[])),candidates:Zr(i)})}var kc=101,ns=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/,Nc="181ec828051c0777",Cc="6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P";function _e(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))_e(t);Object.freeze(e)}return e}function Tc(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!==Cc)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 Rc(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(Nc))continue;let c=Array.isArray(i.accounts)?i.accounts:[],u=c[0],l=c[2];return!ns.test(u||"")||!ns.test(l||"")?null:{id:`solana:${r}:${s}`,chain:"solana",chainId:kc,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 os(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=Tc(u);l?n.push({id:u?.id||null,status:"UNAVAILABLE",reason:l}):o.push(u)}let s=_e({until:e.cursor?.until||null});if(o.length===0)return _e({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 _e({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 _e({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=Rc({...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 _e({status:"LIVE",discoveries:[...c.values()],unavailable:n,cursor:{until:a},whyBlocked:n.map(u=>u.reason)})}tr();var Lc="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function _c(e){let t=String(e||"");if(!t)return Buffer.alloc(0);let r=[0];for(let o of t){let s=Lc.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 Pc(e){return typeof e=="string"?e:e?.pubkey||null}function jc(e){let t=e?.transaction?.message||{},r=Array.isArray(t.accountKeys)?t.accountKeys.map(Pc):[],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=_c(i.data).toString("hex")),a&&s.push({programId:a,accounts:c,dataHex:u})}return s}function ss(e={}){let t=e.solanaRpc||co;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:jc(n)}:{signature:r,slot:null,instructions:[]}}}}import F from"node:fs";import vt from"node:path";var $r=1,Bc=0;function ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function D(e){return structuredClone(e)}function jr(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)=>jr(r,`${t}[${n}]`));if(ve(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}`);jr(n,`${t}.${r}`)}return}throw new Error(`launch-radar store: non-JSON value at ${t}`)}}function Se(e){return Array.isArray(e)?`[${e.map(Se).join(",")}]`:ve(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Se(e[t])}`).join(",")}}`:JSON.stringify(e)}function $c(){return{version:$r,candidates:[],cursor:null,strategyStatus:{mode:"shadow",status:"inert",ambiguous:!1},evidence:[]}}function qc(e){if(!ve(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 Qe(e){if(!ve(e)||e.version!==$r)throw new Error("launch-radar store: corrupt or unsupported version");if(!Array.isArray(e.candidates)||!(e.cursor===null||ve(e.cursor))||!Array.isArray(e.evidence))throw new Error("launch-radar store: corrupt state shape");qc(e.strategyStatus),jr(e);try{Ct(e.evidence)}catch(t){throw new Error(`launch-radar store: corrupt evidence: ${t.message}`)}return D(e)}function It(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){It(e);let t;try{t=JSON.parse(F.readFileSync(e,"utf8"))}catch{throw new Error("launch-radar store: corrupt JSON")}return Qe(t)}function Pr(e,t){let r=Qe(t),n=vt.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");It(e,!0)&&It(e);let s=vt.join(n,`.launch-radar.${process.pid}.${Bc+=1}.tmp`),i;try{i=F.openSync(s,"wx",384),F.writeFileSync(i,`${Se(r)}
|
|
8
|
-
`,"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 qr(e={}){let t=e.path;if(typeof t!="string"||!vt.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");It(t,!0)?Br(t):Pr(t,$c());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 Pr(t,o),D(o)};return Object.freeze({path:t,read:r,replaceState(o={}){if(!ve(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(Qe(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&&Se(i.data)===Se(o?.data))return D(i);throw new Error(`launch-radar store: duplicate evidence conflict: ${o?.id}`)}let a=Tt(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&&Se(u.data)===Se(a?.data))return{duplicate:!0,evidence:D(u),state:c};throw new Error(`launch-radar store: duplicate evidence conflict: ${a?.id}`)}let l=Tt(c.evidence,a),d=Qe({...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 Pr(t,{...s,strategyStatus:i}),D(i)},reconcile(o={}){if(!ve(o))throw new TypeError("launch-radar store: reconciliation state must be an object");let s=r(),i=Qe({...s,...D(o),version:$r,evidence:s.evidence});if(i.strategyStatus.ambiguous)throw new Error("launch-radar store: reconciliation must clear ambiguous state");return n(i,{reconciliation:!0})}})}function is(e={}){let t=e.path;if(typeof t!="string"||!vt.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");return Br(t)}function Dr(e){return e.ORACLE_CONFIG_DIR||ce.join(Uc.homedir(),".config","oracle")}function as(e,t){if(!e||!ce.isAbsolute(e))throw new Error(`${t} path must be absolute`);let r=Ot.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(Ot.readFileSync(e,"utf8"))}function Dc(e){return e==null?null:String(e)}function Pe(e){if(e!==void 0)return typeof e=="bigint"?e.toString():Array.isArray(e)?e.map(Pe).filter(t=>t!==void 0):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,Pe(r)])):e}function fs(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 Ur(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 Fc(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 Mc(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:fs(t.amountIn,"routeProbe.amountIn"),quoteAssetDecimals:Ur(t.quoteAssetDecimals,0,255,"routeProbe.quoteAssetDecimals"),slippageBps:Ur(t.slippageBps??100,0,1e4,"routeProbe.slippageBps"),maxImpactPct:Fc(t.maxImpactPct??25,0,100,"routeProbe.maxImpactPct"),timeoutMs:Ur(t.timeoutMs??12e3,250,6e4,"routeProbe.timeoutMs")})}function cs(e){return[e?.source,e?.amountOut,e?.netOut,e?.meta?.poolId].map(t=>String(t??"").toLowerCase()).join(":")}function us(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 Hc(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 ls(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 ds(e){if(!e?.best||!fs(e.best.amountOut,"best route amountOut"))throw new Error("best route returned no positive output");let t=Array.isArray(e.routes)?e.routes:[],r=cs(e.best),n=t.findIndex(a=>cs(a)===r),o=t.filter((a,c)=>c!==n),s=String(e.rankedOn||"gross").toLowerCase(),i=[...Array.isArray(e.warnings)?e.warnings:[]];return s!=="net"&&!i.some(a=>/gas.*not (?:included|accounted)|gross/i.test(String(a)))&&i.push("Ranked on gross output. Gas was not accounted for."),Pe({rankedOn:s,winner:e.best,runnersUp:o,routes:t,failed:Array.isArray(e.failed)?e.failed:[],sourcesTried:e.sourcesTried??null,sourcesAnswered:e.sourcesAnswered??null,improvementBps:e.improvementBps??null,spreadBasis:e.spreadBasis??null,priceImpact:e.priceImpact,impactRejected:e.impactRejected,impactUnmeasured:e.impactUnmeasured,warnings:i,note:e.note})}function Vc(e,t){return{quote:{evidence:"UNAVAILABLE",reason:e,observedAt:t},sellability:{verdict:"UNKNOWN",evidence:"UNAVAILABLE",reason:e,observedAt:t}}}async function ps({scanner:e,discovery:t,descriptor:r,routeFn:n=Xt,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=Mc(r);if(!t.quoteAsset)throw new Error("verified discovery did not identify a quote asset");if(!i)throw new Error("verified discovery did not identify a token");let c=t.poolKey?{v4PoolKey:Pe(t.poolKey),v4PoolId:t.poolId}:{},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);ls(d,t,"buy");let p=ds(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);ls(f,t,"reverse");let m=ds(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=Hc(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=Pe({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,Vc(c,o))}return Pe(s)}function ms(e){let t=e.quoteAsset||e.pool?.quoteAsset||e.token?.quoteAsset||"unknown",r=us(e.quoteAmountIn,e.quoteAssetDecimals??18)||us(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:Dc(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 Fr(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=as(t.ORACLE_LAUNCH_RADAR_STRATEGY_FILE,"strategy file"),n=as(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=Tr(r);if(![M.SHADOW,M.ARMED,M.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 zc({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");Wn();let a=qn(i[0]);if(!a)throw new Error(`no scanner registered for chain ${i[0]}`);let c=t.ORACLE_LAUNCH_RADAR_STORE_PATH||ce.join(Dr(t),"launch-radar",`state-${i[0]}.json`),u=qr({path:c});return _r({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),y=await St({discover:()=>sn({scanner:a,factories:o,fromBlock:h,toBlock:m,cursor:p}),evaluator:async({discovery:g})=>{let v=o.find(N=>N?.id===g?.factoryId||String(N?.factoryAddress||"").toLowerCase()===String(g?.factoryAddress||"").toLowerCase());return ps({scanner:a,discovery:g,descriptor:v,routeFn:e.routeFn||Xt,observedAt:new Date().toISOString()})},observedAt:new Date().toISOString()});return{candidates:y.candidates,cursor:y.cursor}},evaluate:async p=>ms(p),prepareFn:e.prepareFn||(p=>Ir({...p,scanner:a})),queueFn:e.queueFn||(p=>Or(p,t))})}function zc({env:e,factories:t,strategy:r,options:n}){let o=n.solanaScanner||ss(),s=n.solanaRouteFn||pr,i=n.solanaQuoteScanner||Co({routeFn:s}),a=e.ORACLE_LAUNCH_RADAR_STORE_PATH||ce.join(Dr(e),"launch-radar","state-solana.json"),c=qr({path:a});return _r({store:c,strategy:r,discover:async({cursor:l})=>{let d=await St({discover:()=>os({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 ps({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=>ms(l),prepareFn:n.prepareFn||(l=>Ir({...l,scanner:i})),queueFn:n.queueFn||(l=>Or(l,e))})}async function hs(e={}){let t=e.env||process.env,r=t.ORACLE_LAUNCH_RADAR_FACTORIES_DIR;if(!r||!ce.isAbsolute(r))throw new Error("ORACLE_LAUNCH_RADAR_FACTORIES_DIR must be an absolute directory");let n=Ot.lstatSync(r);if(n.isSymbolicLink()||!n.isDirectory())throw new Error("factories dir must be a regular directory");let o=Ot.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:ce.join(r,i),ORACLE_LAUNCH_RADAR_STORE_PATH:ce.join(t.ORACLE_LAUNCH_RADAR_STORE_DIR||ce.join(Dr(t),"launch-radar"),`state-${a}.json`)},u=await Fr({...e,env:c}).runCycle();s.push({file:i,mode:u.mode,status:u.status,blockers:u.blockers||[],count:(u.results||[]).length})}return{mode:M.SHADOW,status:"fleet",results:s}}var Kc=Object.freeze({OK:"ok",DEGRADED:"degraded",UNKNOWN:"unknown"}),Ed=Object.freeze({fresh:0,stale:1,down:2});var vd=Object.freeze([Object.freeze({id:"uniswap-v3",kind:"factory",chains:Object.freeze(["evm"]),status:"VERIFIED",evidence:"Uniswap V3 PoolCreated against factories returned by verified SwapRouter02.factory() eth_call."}),Object.freeze({id:"uniswap-v4",kind:"pool-manager",chains:Object.freeze(["evm"]),status:"VERIFIED",evidence:"Uniswap V4 Initialize logs against a verified PoolManager, exact PoolKey preserved."}),Object.freeze({id:"pons-v2",kind:"factory",chains:Object.freeze(["evm"]),chainIds:Object.freeze([4663]),status:"VERIFIED",factoryAddress:"0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e",evidence:"Blockscout-verified PonsV2LaunchFactory. Live TokenLaunched topic0 matched on RH."}),Object.freeze({id:"pump-fun",kind:"program",chains:Object.freeze(["solana"]),status:"VERIFIED",programId:"6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P",evidence:"Official pump-fun/pump-public-docs: create discriminator 181ec828051c0777."}),Object.freeze({id:"fomo",kind:"frontend",chains:Object.freeze(["solana","evm"]),status:"COVERED",via:Object.freeze(["pons-v2","pump-fun"]),evidence:"fomopad.family says Built on Pons / Robinhood Chain. fomopad.site says it is a pump.fun launchpad. No separate factory."}),Object.freeze({id:"based-bot",kind:"frontend",chains:Object.freeze(["evm"]),status:"UNAVAILABLE",evidence:"basedbot.app is a trading terminal, not a verified launch factory."}),Object.freeze({id:"opensea",kind:"nft-marketplace",chains:Object.freeze(["evm"]),status:"UNAVAILABLE",evidence:"OpenSea/Seaport is an NFT marketplace, not a fungible-token launch factory."}),Object.freeze({id:"four-meme",kind:"factory",chains:Object.freeze(["evm"]),status:"UNAVAILABLE",evidence:"No independently verified TokenManager/factory address on file this release."}),Object.freeze({id:"clanker",kind:"factory",chains:Object.freeze(["evm"]),status:"UNAVAILABLE",evidence:"No independently verified Clanker factory address on file this release."})]);import Wc from"node:os";import ys from"node:path";var Gc="oracle.launch-radar.data-plane.v1";function Jc(e){return String(e?.message||e||"unknown error").slice(0,300)}function Yc(e={}){return e.configDir||process.env.ORACLE_CONFIG_DIR||ys.join(Wc.homedir(),".config","oracle")}function Qc(e={}){return e.storePath||process.env.LAUNCH_RADAR_STORE_PATH||ys.join(Yc(e),"launch-radar","state.json")}function Xc(e={}){let t=Qc(e);try{return{ok:!0,path:t,state:is({path:t})}}catch(r){return{ok:!1,path:t,error:Jc(r)}}}function Zc(){return process.env.ORACLE_AUTONOMOUS_TRADING==="1"}function Mr(e={},t={}){let r=Xc(t),n={schema:Gc,storePath:r.path,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,autonomousTradingEnvSet:Zc()};if(!r.ok)return Object.freeze({...n,evidence:"UNAVAILABLE",reason:r.error,mode:M.SHADOW,status:"unavailable",ambiguous:null,candidateCount:null,cursor:null,evidenceCount:null,lastEvidenceAt:null});let{state:o}=r,s=o.evidence.at(-1)||null;return Object.freeze({...n,evidence:"LIVE",reason:o.strategyStatus.reason??null,mode:o.strategyStatus.mode,status:o.strategyStatus.status,ambiguous:o.strategyStatus.ambiguous,candidateCount:o.candidates.length,cursor:o.cursor,evidenceCount:o.evidence.length,lastEvidenceAt:s?s.at:null})}var Hr=new Set(process.argv.slice(2));(Hr.has("--help")||Hr.has("-h"))&&(console.log(`oracle-launch-radar-shadow
|
|
7
|
+
- `)}`);let o=e.capabilities||{},s=it.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:it.filter(a=>!s.includes(a))}},supports(a){return s.includes(a)}};for(let a of it)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 Bn=new Map;function $n(e){let t=Li(e);return Bn.set(t.chainId,t),t}function qn(e){return Bn.get(Number(e))||null}var Mt={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},W=e=>BigInt(e).toString(16).padStart(64,"0"),Fe=e=>e.slice(2).toLowerCase().padStart(64,"0");function _i(e,t){return`0x${Mt.getAmountsOut}`+W(e)+W(64)+W(t.length)+t.map(Fe).join("")}function Pi(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 Ft(e,t="router"){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}var Ht=100;function ji(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Ht)throw new Error(`slippageBps ${r} exceeds the ${Ht} 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 U(t,"eth_call",[{to:o,data:_i(s,i)},"latest"],a);return Pi(c?.result??c)}return{async quote({tokenIn:o,tokenOut:s,amountIn:i,path:a},c={}){let u=Ft(c.scanner);if(!u)return{chainId:t,evidence:x.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:x.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:u,path:l,evidence:x.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=Ft(a.scanner),u=i||r;if(u&&String(o).toLowerCase()===String(u).toLowerCase())return{chainId:t,token:o,verdict:S.UNKNOWN,evidence:x.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!c||!u)return{chainId:t,token:o,verdict:S.UNKNOWN,evidence:x.UNAVAILABLE,reason:c?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let l=await n(c,s,[u,o],a);if(!l)return{chainId:t,token:o,verdict:S.FAIL,evidence:x.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let d=l[l.length-1];if(d===0n)return{chainId:t,token:o,verdict:S.FAIL,evidence:x.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let p=await n(c,d,[o,u],a);if(!p)return{chainId:t,token:o,verdict:S.FAIL,evidence:x.LIVE,leg:"sell",bought:d.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let f=p[p.length-1],m=Number(f*10000n/BigInt(s)),h=S.PASS,y="round trip completes with expected fee/impact loss";return m<5e3?(h=S.FAIL,y=`round trip returns only ${(m/100).toFixed(2)}% -- punitive tax or no real liquidity`):m<9e3&&(h=S.CAUTION,y=`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:y,amountIn:String(s),bought:d.toString(),returned:f.toString(),retentionBps:m,evidence:x.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=Ft(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!==x.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let y=ji(h.amountOut,c);if(y<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let g=BigInt(Math.floor(Date.now()/1e3)+Number(u)),v=r&&m[0].toLowerCase()===r.toLowerCase()&&d.useNative,N=v?`0x${Mt.swapExactETHForTokens}`+W(y)+W(128)+Fe(a)+W(g)+W(m.length)+m.map(Fe).join(""):`0x${Mt.swapExactTokensForTokens}`+W(i)+W(y)+W(160)+Fe(a)+W(g)+W(m.length)+m.map(Fe).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:f,data:N,value:v?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:h.amountOut,minOut:y.toString(),slippageBps:c,maxSlippageBps:Ht,deadline:g.toString()},requires:v?[]:[{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 Bi=[100,500,3e3,1e4],Dn={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},me=e=>BigInt(e).toString(16).padStart(64,"0"),Me=e=>e.slice(2).toLowerCase().padStart(64,"0"),Fn=/^0x[0-9a-fA-F]{40}$/,zt=100;function $i(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>zt)throw new Error(`slippageBps ${r} exceeds the ${zt} 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 Vt(e,t){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function Mn(e){let{chainId:t,wrappedNative:r}=e;async function n({quoter:s,tokenIn:i,tokenOut:a,amountIn:c,fee:u},l){let d=`0x${Dn.quoteExactInputSingle}`+Me(i)+Me(a)+me(c)+me(u)+me(0),p=await U(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(Bi.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=Vt(c.scanner,"quoter");if(!u)return{chainId:t,evidence:x.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(!Fn.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:x.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:x.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=Vt(c.scanner,"quoter"),l=(e.stableQuoteAssets||[]).map(A=>String(A).toLowerCase()),d=null;!a&&typeof e.resolveQuoteAsset=="function"&&(d=await e.resolveQuoteAsset(s,c).catch(()=>null));let p=String(s).toLowerCase(),f=String(r||"").toLowerCase();if(f&&p===f)return{chainId:t,token:s,verdict:S.UNKNOWN,evidence:x.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};let m=a||d||(l[0]&&p!==l[0]?l[0]:null)||r;if(m&&p===String(m).toLowerCase())return{chainId:t,token:s,verdict:S.UNKNOWN,evidence:x.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!u||!m)return{chainId:t,token:s,verdict:S.UNKNOWN,evidence:x.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 A=l.find(I=>I&&I!==String(m).toLowerCase()&&I!==String(s).toLowerCase());if(A){let I=await o({quoter:u,tokenIn:A,tokenOut:s,amountIn:i},c);if(I.best){let E=await o({quoter:u,tokenIn:s,tokenOut:A,amountIn:I.best.amountOut},c);if(E.best){let k=E.best.amountOut,O=Number(k*10000n/BigInt(i)),_=S.PASS,b="round trip vs dollar book completes with expected fee/impact loss";return O<5e3?(_=S.FAIL,b=`round trip vs dollar book returns only ${(O/100).toFixed(2)}% -- punitive tax or no real liquidity`):O<9e3&&(_=S.CAUTION,b=`round trip vs dollar book returns ${(O/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:s,base:A,quoteAsset:A,verdict:_,reason:b,amountIn:String(i),bought:I.best.amountOut.toString(),returned:k.toString(),retentionBps:O,buyFee:I.best.fee,sellFee:E.best.fee,evidence:x.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:t,token:s,verdict:S.FAIL,evidence:x.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let y=await o({quoter:u,tokenIn:s,tokenOut:m,amountIn:h.best.amountOut},c);if(!y.best){let A=l.find(I=>I&&I!==String(m).toLowerCase()&&I!==String(s).toLowerCase());if(A){let I=await o({quoter:u,tokenIn:A,tokenOut:s,amountIn:i},c),E=I.best?await o({quoter:u,tokenIn:s,tokenOut:A,amountIn:I.best.amountOut},c):{best:null};if(I.best&&E.best){let k=E.best.amountOut,O=Number(k*10000n/BigInt(i)),_=S.PASS,b="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return O<5e3?(_=S.FAIL,b=`dollar-book round trip returns only ${(O/100).toFixed(2)}%`):O<9e3&&(_=S.CAUTION,b=`dollar-book round trip returns ${(O/100).toFixed(2)}%`),{chainId:t,venue:"uniswap-v3",token:s,base:A,quoteAsset:A,verdict:_,reason:b,amountIn:String(i),bought:I.best.amountOut.toString(),returned:k.toString(),retentionBps:O,buyFee:I.best.fee,sellFee:E.best.fee,evidence:x.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:t,token:s,verdict:S.FAIL,evidence:x.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=y.best.amountOut,v=Number(g*10000n/BigInt(i)),N=S.PASS,L="round trip completes with expected fee/impact loss";return v<5e3?(N=S.FAIL,L=`round trip returns only ${(v/100).toFixed(2)}% -- punitive tax or no real liquidity`):v<9e3&&(N=S.CAUTION,L=`round trip returns ${(v/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:s,base:m,verdict:N,reason:L,amountIn:String(i),bought:h.best.amountOut.toString(),returned:g.toString(),retentionBps:v,buyFee:h.best.fee,sellFee:y.best.fee,evidence:x.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=Vt(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(!Fn.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!==x.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let m=l??f.fee,h=$i(f.amountOut,u);if(h<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let y=!!(d.useNative||f.useNative)&&r&&String(s).toLowerCase()===String(r).toLowerCase(),g=`0x${Dn.exactInputSingle}`+Me(s)+Me(i)+me(m)+Me(c)+me(a)+me(h)+me(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:p,data:g,value:y?String(a):"0x0"},guard:{quotedOut:f.amountOut,minOut:h.toString(),slippageBps:u,maxSlippageBps:zt,fee:m},requires:y?[]:[{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 at={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function Hn(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function Vn(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 qi(e){let{chainId:t}=e;async function r(n,o,s){return U(t,"eth_call",[{to:n,data:o},"latest"],s)}return{async blockNumber(n={}){let o=await Tn(t,n);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:x.LIVE}},async nativeBalance(n,o={}){let s=await Rn(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:x.LIVE}},async tokenBalance({token:n,owner:o},s={}){let i=await Ln({chainId:t,token:n,owner:o},s);return{chainId:t,token:n,owner:o,raw:i?.balance??i,evidence:x.LIVE}},async resolveToken(n,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:t,token:n,evidence:x.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,at.decimals,o).catch(()=>null),r(n,at.symbol,o).catch(()=>null),r(n,at.name,o).catch(()=>null),r(n,at.totalSupply,o).catch(()=>null)]),u=Hn(s?.result??s),l=u!==null||i?.result||a?.result,d={chainId:t,address:n,decimals:u===null?null:Number(u),symbol:Vn(i?.result??i),name:Vn(a?.result??a),totalSupply:(Hn(c?.result??c)??null)?.toString()??null,evidence:l?x.LIVE:x.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:x.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await jn(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=Dt(n,c,{stables:e.stableQuoteAssets||[],wrappedNative:e.wrappedNative});return{chainId:t,token:n,pools:u,topPool:u[0]||null,quoteAsset:Pn(n,u),evidence:u.length?x.LIVE:x.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 In(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 U(t,"eth_getLogs",[m],c).catch(y=>({error:String(y?.message||y)}));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:x.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:x.LIVE}},async scoreRisk(n,o={}){let s=[],i=S.PASS,a=l=>{let d={[S.PASS]:0,[S.CAUTION]:1,[S.UNKNOWN]:2,[S.FAIL]:3};d[l]>d[i]&&(i=l)},[c,u]=await Promise.all([this.resolveToken(n,o),this.resolvePools(n,o)]);if(c.evidence!==x.LIVE?(s.push({check:"erc20-metadata",result:S.UNKNOWN,detail:c.warning}),a(S.UNKNOWN)):s.push({check:"erc20-metadata",result:S.PASS,detail:`${c.symbol} / ${c.decimals}d`}),u.evidence===x.UNAVAILABLE)s.push({check:"liquidity",result:S.UNKNOWN,detail:u.reason}),a(S.UNKNOWN);else if(!u.pools.length)s.push({check:"liquidity",result:S.FAIL,detail:"no pool with liquidity found"}),a(S.FAIL);else{let l=u.pools[0],d=l.liquidityUsd??0;d<5e3?(s.push({check:"liquidity",result:S.CAUTION,detail:`top pool only $${d}`}),a(S.CAUTION)):s.push({check:"liquidity",result:S.PASS,detail:`$${d} on ${l.dex}`}),l.createdAt&&Date.now()-l.createdAt<24*3600*1e3&&(s.push({check:"age",result:S.CAUTION,detail:"pool under 24h old"}),a(S.CAUTION))}if(typeof this.sellSimulation=="function"){let l=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},o).catch(d=>({verdict:S.UNKNOWN,reason:String(d?.message||d)}));s.push({check:"sellability",result:l.verdict,detail:l.retentionBps!=null?`round trip returns ${(l.retentionBps/100).toFixed(2)}% -- ${l.reason}`:l.reason}),a(l.verdict)}else s.push({check:"sellability",result:S.UNKNOWN,detail:"no verified router on this chain, so a round-trip sell simulation cannot run. Treat as unproven -- a buy path is not an exit path."}),a(S.UNKNOWN);return{chainId:t,token:n,verdict:i,checks:s,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function zn(e){let r={...qi(e)},n=new Set((e.venues||[]).map(s=>s.kind));e.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,Mn({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 Kn=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 Wn(){return Kn.map(e=>$n(zn(e)))}import{AbiCoder as Ui,Interface as Xn,getAddress as ye,isAddress as Zn,keccak256 as Di}from"ethers";var Kt="0x0000000000000000000000000000000000000000",Fi="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Mi=Ui.defaultAbiCoder(),Gn=new Xn(["function quoteExactInputSingle((address tokenIn,address tokenOut,uint256 amountIn,uint24 fee,uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut,uint160 sqrtPriceX96After,uint32 initializedTicksCrossed,uint256 gasEstimate)"]),Yn=new Xn(["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)"]),G=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"})}),Ve=Object.freeze({1:Object.freeze({quoter:"0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203",wrappedNative:G[1].wrappedNative}),10:Object.freeze({quoter:"0x1f3131a13296fb91c90870043742c3cdbff1a8d7",wrappedNative:G[10].wrappedNative}),56:Object.freeze({quoter:"0x9f75dd27d6664c475b90e105573e550ff69437b0",wrappedNative:G[56].wrappedNative}),137:Object.freeze({quoter:"0xb3d5c3dfc3a7aebff71895a7191796bffc2c81b9",wrappedNative:G[137].wrappedNative}),8453:Object.freeze({quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",wrappedNative:G[8453].wrappedNative}),42161:Object.freeze({quoter:"0x3972c00f7ed4885e145823eb7c655375d275a1c5",wrappedNative:G[42161].wrappedNative}),43114:Object.freeze({quoter:"0xbe40675bb704506a3c2ccfb762dcfd1e979845c2",wrappedNative:G[43114].wrappedNative}),4663:Object.freeze({quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",wrappedNative:G[4663].wrappedNative})}),Hi=Object.freeze([100,500,3e3,1e4]);function he(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 eo(e,t){let r=String(e??"");if(!/^[1-9][0-9]*$/.test(r))throw new Error(`${t} must be a positive raw-unit integer string`);return BigInt(r)}function to(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 Wt(e){let t=String(e??"").trim().toLowerCase();return t===""||t==="eth"||t===Kt||t===Fi}function He(e,t){if(!Zn(String(e??"")))throw new Error(`${t} must be an EVM address`);return ye(String(e))}function Jn(e,t,r){return Wt(e)?ye(t.wrappedNative):He(e,r)}function Qn(e,t){return Wt(e)?ye(Kt):He(e,t)}function ro(e,t){let r=Number(e);if(!Number.isInteger(r)||r<0||r>16777215)throw new Error(`${t} must be uint24`);return r}function Vi(e,t){let r=Number(e);if(!Number.isInteger(r)||r<-8388608||r>8388607)throw new Error(`${t} must be int24`);return r}function zi({tokenIn:e,tokenOut:t,poolKey:r,poolId:n}){he(r,new Set(["currency0","currency1","fee","tickSpacing","hooks"]),"V4 PoolKey");let o=He(r.currency0,"V4 currency0"),s=He(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:ro(r.fee,"V4 fee"),tickSpacing:Vi(r.tickSpacing,"V4 tickSpacing"),hooks:He(r.hooks??Kt,"V4 hooks")}),a=Qn(e,"tokenIn"),c=Qn(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=Di(Mi.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 Gt(e,t){if(Wt(t))return!0;if(!Zn(String(t??"")))return!1;let r=G[Number(e)]?.wrappedNative||Ve[Number(e)]?.wrappedNative;return!!(r&&ye(String(t)).toLowerCase()===ye(r).toLowerCase())}async function no(e={},t={},r={}){he(e,new Set(["chainId","tokenIn","tokenOut","amountIn","fee"]),"V3 read"),he(t,new Set(["timeoutMs"]),"V3 read options"),he(r,new Set(["rpc"]),"V3 read dependencies");let n=Number(e.chainId),o=G[n];if(!o)throw new Error(`V3 read unavailable on chain ${e.chainId}`);let s=Jn(e.tokenIn,o,"tokenIn"),i=Jn(e.tokenOut,o,"tokenOut");if(s.toLowerCase()===i.toLowerCase())throw new Error("tokenIn and tokenOut must differ");let a=eo(e.amountIn,"amountIn"),c=e.fee==null?Hi:[ro(e.fee,"V3 fee")],u=r.rpc||U,l=to(t.timeoutMs),d=await Promise.all(c.map(async f=>{let m=Gn.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 y=Gn.decodeFunctionResult("quoteExactInputSingle",h);return Object.freeze({ok:!0,fee:f,amountOut:y[0].toString(),gasEstimate:y[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:ye(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 oo(e={},t={},r={}){he(e,new Set(["chainId","tokenIn","tokenOut","amountIn","poolKey","poolId"]),"V4 read"),he(t,new Set(["timeoutMs"]),"V4 read options"),he(r,new Set(["rpc"]),"V4 read dependencies");let n=Number(e.chainId),o=Ve[n];if(!o)throw new Error(`V4 read unavailable on chain ${e.chainId}`);let s=eo(e.amountIn,"amountIn");if(s>0xffffffffffffffffffffffffffffffffn)throw new Error("amountIn exceeds uint128");let i=zi(e),a=Yn.encodeFunctionData("quoteExactInputSingle",[{poolKey:i.poolKey,zeroForOne:i.zeroForOne,exactAmount:s,hookData:"0x"}]),u=await(r.rpc||U)(n,"eth_call",[{to:o.quoter,data:a},"latest"],to(t.timeoutMs));if(!u||u==="0x")throw new Error("V4 read returned an empty result");let l=Yn.decodeFunctionResult("quoteExactInputSingle",u);return Object.freeze({venue:"uniswap-v4",chainId:n,quoter:ye(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 Ki=new Set(["chainId","tokenIn","tokenOut","amountIn","v4PoolKey","v4PoolId"]),Wi=new Set(["maxImpactPct","timeoutMs"]),Gi=new Set(["quoteV3","quoteV4","gasPrice"]);function Yt(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 Qt(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 so(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 Yi(e){if(e<=1n)return null;let t=e/1000n;return t>0n&&t<e?t:1n}function Ji({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 Jt(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 Qi({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 Gt(e,r)?d:Gt(e,t)?d*l/u:null}async function Xi(e,t){let r=await U(e,"eth_gasPrice",[],{timeoutMs:t});return re(r)}function Zi(e,t){return Object.freeze({source:e,quality:"FAILED",amountOut:null,error:String(t?.message||t).slice(0,240)})}async function io({source:e,amountIn:t,timeoutMs:r,fullRead:n,probeRead:o}){try{let s=await Jt(n,r,e),i=Qt(s?.amountOut,`${e} amountOut`),a=Yi(t);if(a==null)return{source:e,full:s,impactPct:null};try{let c=await Jt(()=>o(a.toString(),s),r,`${e} impact probe`),u=Ji({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 ea({inspected:e,params:t,gasPrice:r}){let n=e.full,o=Qt(n.amountOut,`${e.source} amountOut`),s=Qi({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 ta({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 Xt(e={},t={},r={}){Yt(e,Ki,"route params"),Yt(t,Wi,"route options"),Yt(r,Gi,"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=Qt(e.amountIn,"amountIn"),s=so(t.timeoutMs,12e3,250,6e4,"timeoutMs"),i=so(t.maxImpactPct,25,0,100,"maxImpactPct"),a=r.quoteV3||no,c=r.quoteV4||oo,u=r.gasPrice||Xi,l=[];G[n]&&l.push(io({source:"uniswap-v3",amountIn:o,timeoutMs:s,fullRead:()=>a({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:o.toString()},{timeoutMs:s}),probeRead:(w,T)=>a({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:w,fee:T.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&&Ve[n]&&l.push(io({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:w=>c({chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:w,poolKey:e.v4PoolKey,poolId:e.v4PoolId},{timeoutMs:s})})),!l.length)throw new Error(`no verified read-only quote source on chain ${n}`);let f=Jt(()=>u(n,s),s,"gas price read").catch(()=>null),m=await Promise.all(l),h=await f,y=m.filter(w=>w.error).map(w=>Zi(w.source,w.error)),g=m.filter(w=>w.full),v=g.filter(w=>w.impactPct!=null&&w.impactPct>i).map(w=>({source:w.source,impactPct:Number(w.impactPct.toFixed(2)),reason:`price impact ${w.impactPct.toFixed(2)}% exceeds ${i}% ceiling`})),N=new Set(v.map(w=>w.source)),L=g.filter(w=>!N.has(w.source)),A=L.map(w=>ea({inspected:w,params:{...e,chainId:n},gasPrice:h})),I=A.length>0&&A.every(w=>w.costAccounted),E=I?"net":"gross";for(let w of A){let T=BigInt(w.grossOut),oe=I?BigInt(w.costInDest):0n;w.netOut=(T>oe?T-oe:0n).toString()}A.sort((w,T)=>{let oe=BigInt(I?w.netOut:w.grossOut),V=BigInt(I?T.netOut:T.grossOut);return oe===V?w.source.localeCompare(T.source):V>oe?1:-1});let k=[];I?k.push("Gas is estimated from quoter gas units and the current read-only gas price; actual gas may differ."):k.push("Gas was not accounted for; routes are ranked on gross output.");let O=L.filter(w=>w.impactPct==null).map(w=>w.source);O.length&&k.push(`Price impact is UNKNOWN for: ${O.join(", ")}.`),v.length&&k.push(`Dropped on price impact: ${v.map(w=>w.source).join(", ")}.`),!d&&Ve[n]&&k.push("V4 was not queried because no exact verified PoolKey identity was discovered.");let _=null,b=null;if(A.length>1){let w=BigInt(I?A[0].netOut:A[0].grossOut),T=BigInt(I?A[1].netOut:A[1].grossOut);T>0n&&(_=Number((w-T)*10000000n/T)/1e3,b=`${A[0].source} vs ${A[1].source}`)}let $=Object.fromEntries(L.filter(w=>w.impactPct!=null).map(w=>[w.source,Number(w.impactPct.toFixed(4))]));return Object.freeze({kind:"swap",chainId:n,tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:o.toString(),best:A[0]||null,routes:Object.freeze(A.map(w=>Object.freeze(w))),failed:Object.freeze(y),rankedOn:E,sourcesTried:l.length,sourcesAnswered:g.length,improvementBps:_,spreadBasis:b,priceImpact:Object.freeze($),impactRejected:Object.freeze(v),impactUnmeasured:Object.freeze(O),warnings:Object.freeze(k),note:ta({routes:A,rankedOn:E,improvementBps:_})})}var be="So11111111111111111111111111111111111111112";var Ca=new Set(["chainId","tokenIn","tokenOut","amountIn"]),Ta=new Set(["maxImpactPct","timeoutMs","quoteFn"]);function xo(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 ko(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 No(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 Ra(e,t={}){let{jupiterQuote:r}=await Promise.resolve().then(()=>(dr(),lr)),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 pr(e={},t={}){if(xo(e,Ca,"params"),xo(t,Ta,"options"),e.chainId!=null&&Number(e.chainId)!==101)throw new Error("solana quote adapter only handles chainId 101");let r=No(e.tokenIn,"tokenIn"),n=No(e.tokenOut,"tokenOut"),o=ko(e.amountIn,"amountIn");if(r===n)throw new Error("solana quote tokenIn and tokenOut must differ");let s=t.quoteFn||Ra;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=ko(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 Co({routeFn:e=pr}={}){return Object.freeze({async sellSimulation({token:t,amountIn:r,base:n}={}){let{simulateSell:o,SELL_SIM:s}=await Promise.resolve().then(()=>(Oo(),Io)),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 fc(e){return e?.token?.address||e?.tokenAddress||null}function pc(e){return e?.quoteAsset||e?.pool?.quoteAsset||null}function mc(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=fc(e),o=pc(e),s=mc(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(()=>(dr(),lr)),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 Or({prepared:e}={},t=process.env){if(e?.prepared!==!0)return{ok:!1,error:"nothing prepared"};let{armPreparedAction:r}=await Promise.resolve().then(()=>(Go(),Wo)),n=e.localSignerEnvelope||e.envelope;if(!n)return{ok:!1,error:"prepared envelope missing"};let{attachPrepareVerification:o}=await Promise.resolve().then(()=>(Sr(),Vo));return r(o({...e,localSignerEnvelope:n}),t)}import{createHash as Sc}from"node:crypto";import{createHash as hc}from"node:crypto";var M=Object.freeze({SHADOW:"shadow",ARMED:"armed",AUTONOMOUS:"autonomous"}),yc=3,bc=new Set(Object.values(M));function Cr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Cr(t);Object.freeze(e)}return e}function Nr(e){return Array.isArray(e)?`[${e.map(Nr).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${Nr(e[t])}`).join(",")}}`:JSON.stringify(e)}function wc(e){return`sha256:${hc("sha256").update(Nr(e)).digest("hex")}`}function xr(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 gc(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new TypeError(`${t} entries must be positive safe integers`);return e}function kr(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 Le(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 Ye(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 At(e,t){let r=Le(e,t),[n,o=""]=r.split(".");return{digits:BigInt(n+o),scale:o.length}}function gt(e,t,r="value"){let n=At(e,r),o=At(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 Yo(e){let t=structuredClone(e);return delete t.digest,t}function Ac(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");return wc(Yo(e))}function Tr(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");let t=e.mode??M.SHADOW;if(!bc.has(t))throw new TypeError("mode must be shadow, armed, or autonomous");let r={version:1,mode:t,chains:xr(e.chains,"chains",gc),venues:xr(e.venues,"venues",kr),quoteAssets:xr(e.quoteAssets,"quoteAssets",kr),maxSpendPerTrade:Le(e.maxSpendPerTrade,"maxSpendPerTrade",{positive:!0}),maxSpendPerDay:Le(e.maxSpendPerDay,"maxSpendPerDay",{positive:!0}),minLiquidityUsd:Le(e.minLiquidityUsd,"minLiquidityUsd",{positive:!0}),maxSlippageBps:Ye(e.maxSlippageBps,"maxSlippageBps",{max:1e4}),maxGas:Le(e.maxGas,"maxGas",{positive:!0}),maxPriorityFee:Le(e.maxPriorityFee,"maxPriorityFee"),maxBuysPerHour:Ye(e.maxBuysPerHour,"maxBuysPerHour",{min:1}),retryCeiling:Ye(e.retryCeiling,"retryCeiling",{max:yc}),ttlMs:Ye(e.ttlMs,"ttlMs",{min:1}),requireSellSimulation:e.requireSellSimulation,requireRiskPass:e.requireRiskPass??!0,maxRoundTripLossBps:Ye(e.maxRoundTripLossBps??1500,"maxRoundTripLossBps",{max:1e4}),killSwitch:e.killSwitch,recipient:e.recipient==null||e.recipient===""?null:kr(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!==M.SHADOW&&!r.recipient)throw new TypeError("recipient is required when mode is armed or autonomous");if(gt(r.maxSpendPerTrade,r.maxSpendPerDay)>0)throw new TypeError("maxSpendPerTrade cannot exceed maxSpendPerDay");return r.digest=Ac(r),Cr(r)}var Ec=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 Rr(e,t={},r={}){let n=Tr(Yo(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,gt(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=At(t.spentToday,"daily spend"),c=At(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,gt(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,gt(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 Ec)j(i,t.autonomousGates?.[a]!==!0,c);return j(i,n.mode!==M.AUTONOMOUS,"strategy mode is not autonomous"),Cr({strategyDigest:n.digest,mode:n.mode,policyEligible:o.length===0,blockers:o,autonomousEligible:i.length===0,autonomousBlockers:i,reportOnly:!0})}function Zo(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Zo(t);Object.freeze(e)}return e}var Jo=Object.freeze({ALERT_ONLY:"alert_only",EXECUTE:"execute"}),Qo=Object.freeze({liveQuote:20,sellSimulation:30,contractRisk:20,liquidity:15,roundTripLoss:15});function K(e,t){return{id:e,verdict:"PASS",detail:t}}function H(e,t){return{id:e,verdict:"BLOCK",detail:t}}function Xo(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function es({strategy:e,observation:t={},evaluation:r={}}={}){if(!e||typeof e!="object")throw new TypeError("snipe features require a strategy");let n=[],o=[],s=(h,y)=>{n.push(h),h.verdict==="BLOCK"&&o.push(y)};s(e.killSwitch===!0?H("killSwitch","engaged"):K("killSwitch","off"),"kill switch is engaged"),s(e.chains.includes(t.chain)?K("chain",String(t.chain)):H("chain",String(t.chain??"missing")),"chain is not on the exact allowlist"),s(e.venues.includes(t.venue)?K("venue",String(t.venue)):H("venue",String(t.venue??"missing")),"venue is not on the exact allowlist"),s(e.quoteAssets.includes(t.quoteAsset)?K("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"?K("liveQuote","LIVE"):H("liveQuote",String(i||"missing")),"live quote is missing");let a=t.sellSimulation||r.sellSimulation;s(a?.verdict==="PASS"&&a?.evidence==="LIVE"?K("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"?K("contractRisk","PASS"):H("contractRisk",String(c||"missing")),"contract risk is not PASS");let u=t.liquidityUsd;try{let h=Number(u),y=Number(e.minLiquidityUsd);s(Number.isFinite(h)&&Number.isFinite(y)&&h>=y?K("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=Xo(t.slippageBps);s(l!=null&&l<=e.maxSlippageBps?K("slippage",String(l)):H("slippage",String(t.slippageBps??"missing")),"slippage exceeds cap or is unknown");let d=Xo(t.roundTripLossBps);s(d!=null&&d<=e.maxRoundTripLossBps?K("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?K("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?K("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)?K("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"&&Qo[h.id]&&(p+=Qo[h.id]);let f=o.length===0,m=e.mode==="shadow"?Jo.ALERT_ONLY:Jo.EXECUTE;return Zo({snipeReady:f,wouldSnipe:f,armed:!1,actionMode:m,score:p,features:n,blockers:o,reportOnly:e.mode==="shadow"})}function Et(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Lr(e){return Array.isArray(e)?`[${e.map(Lr).join(",")}]`:Et(e)?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${Lr(e[t])}`).join(",")}}`:JSON.stringify(e)}function vc(e){return`cycle:${Sc("sha256").update(Lr(e)).digest("hex")}`}function Je(e,t){if(typeof e!="function")throw new TypeError(`launch-radar runner: injected ${t} function is required`)}function ts(e){return e instanceof Error?e.message:String(e)}function _r(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(!Et(r))throw new TypeError("launch-radar runner: strategy is required");Je(n,"discovery"),Je(o,"evaluate");let s=e.now??(()=>new Date().toISOString()),i=e.sleep??(()=>Promise.resolve()),a=e.jitter??(()=>0);Je(s,"clock"),Je(i,"sleep"),Je(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 y=0;y<=c;y+=1)try{return await m(y)}catch(g){if(h=g,y===c)break;let v=Number(a()),N=Number.isFinite(v)?Math.max(0,v):0,L=Math.min(l,u*2**y+N);await i(L)}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=dn(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 y;try{y=await d(A=>n({cursor:structuredClone(m.cursor),attempt:A,mode:r.mode}))}catch(A){return{mode:r.mode,status:"failed",blockers:[ts(A)],results:[],actionMode:h}}if(!Et(y)||!Array.isArray(y.candidates)||!(y.cursor===null||Et(y.cursor)))return{mode:r.mode,status:"failed",blockers:["discovery returned an invalid deterministic result"],results:[],actionMode:h};let g=[];for(let A of y.candidates)try{let I=await d(b=>o(structuredClone(A),{attempt:b,mode:r.mode})),E=Rr(r,I,{}),k=es({strategy:r,observation:I,evaluation:A}),O={prepared:!1},_=!1;tt(r,E)&&typeof e.prepareFn=="function"?O=await e.prepareFn({candidate:A,observation:I,strategy:r,policy:E})||{prepared:!1}:tt(r,E)&&(O={prepared:!1,blockedReasons:["prepareFn is required when strategy mode is not shadow"]}),fn(r,E,O)&&typeof e.queueFn=="function"&&(_=(await e.queueFn({prepared:O,candidate:A,observation:I,strategy:r,policy:E}))?.ok===!0),g.push({id:A?.id??null,policy:E,snipe:k,prepared:O.prepared===!0,queued:_,actionMode:h})}catch(I){g.push({id:A?.id??null,policy:{mode:r.mode,policyEligible:!1,reportOnly:r.mode===M.SHADOW,blockers:[`evaluation failed: ${ts(I)}`]},actionMode:h,prepared:!1,queued:!1})}let v={cursor:y.cursor,candidates:y.candidates,results:g},N={id:vc(v),type:r.mode===M.SHADOW?"shadow-cycle":"execute-cycle",at:s(),data:v},L=t.commitCycle({candidates:y.candidates,cursor:y.cursor,strategyStatus:{mode:r.mode,status:"inert",ambiguous:!1},event:N});return{mode:r.mode,status:L.duplicate?"duplicate":"completed",results:g,evidenceId:L.evidence.id,actionMode:h}}return Object.freeze({status:p,runCycle:f})}function rs(e){return[...new Set(e.filter(Boolean).map(String))]}function Ee(e){return Array.isArray(e)?e.map(Ee):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,Ee(r)])):e}function ae(e,t,r="UNKNOWN"){return!e||typeof e!="object"?{evidence:r,observedAt:t}:Ee({...structuredClone(e),evidence:e.evidence||r,observedAt:e.observedAt||t})}function Ic(e,t){let r=String(t||"").toLowerCase();return!!(r&&[e?.address,e?.pair,e?.poolId].some(n=>String(n||"").toLowerCase()===r))}function Oc(e,t){let r=e.poolId||e.poolAddress||null,n=[t.topPool,...t.pools?.pools||[]].filter(Boolean),o=r?n.find(i=>Ic(i,r)):t.topPool,s={address:e.poolAddress??null,poolId:e.poolId,poolKey:e.poolKey,quoteAsset:e.quoteAsset};return Ee({...o||{},...s})}function xc(e,t,r,n){let o=e.observedAt||n,s=Oc(e,t),i=ae(t.scannerRisk||t.risk,o),a=ae(t.sellability,o,"UNAVAILABLE"),c=ae(t.quote,o,"UNAVAILABLE"),u=c.evidence==="LIVE"?"PASS":"UNKNOWN";return Ee({chain:{id:e.chainId,...t.chain||{}},token:ae({address:e.tokenAddress,...t.token||{}},o,"LIVE"),pool:ae(s,o,"LIVE"),venue:ae({...e.venue,supported:e.venue?.supported===!0,verified:e.venue?.verified===!0},o,"LIVE"),signal:ae({kind:e.kind,source:"verified-factory",unsolicitedAirdrop:!1},o,"LIVE"),risk:i,sellability:a,sellSimulation:ae(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:Ee({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:rs([...r||[],...t.blockedReasons||[],t.error]),latency:{discoveredAt:o,riskCompletedAt:i.observedAt,sellabilityCompletedAt:a.observedAt,routeCompletedAt:c.observedAt,normalizedAt:n}})}async function St(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:Ee(structuredClone(a)),prepare:e.prepare===!0})}catch(u){c={error:`evaluation unavailable: ${String(u?.message||u).slice(0,300)}`}}i.push(xc(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(rs(n?.whyBlocked||[])),candidates:Zr(i)})}var kc=101,ns=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/,Nc="181ec828051c0777",Cc="6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P";function _e(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))_e(t);Object.freeze(e)}return e}function Tc(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!==Cc)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 Rc(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(Nc))continue;let c=Array.isArray(i.accounts)?i.accounts:[],u=c[0],l=c[2];return!ns.test(u||"")||!ns.test(l||"")?null:{id:`solana:${r}:${s}`,chain:"solana",chainId:kc,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 os(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=Tc(u);l?n.push({id:u?.id||null,status:"UNAVAILABLE",reason:l}):o.push(u)}let s=_e({until:e.cursor?.until||null});if(o.length===0)return _e({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 _e({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 _e({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=Rc({...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 _e({status:"LIVE",discoveries:[...c.values()],unavailable:n,cursor:{until:a},whyBlocked:n.map(u=>u.reason)})}tr();var Lc="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function _c(e){let t=String(e||"");if(!t)return Buffer.alloc(0);let r=[0];for(let o of t){let s=Lc.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 Pc(e){return typeof e=="string"?e:e?.pubkey||null}function jc(e){let t=e?.transaction?.message||{},r=Array.isArray(t.accountKeys)?t.accountKeys.map(Pc):[],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=_c(i.data).toString("hex")),a&&s.push({programId:a,accounts:c,dataHex:u})}return s}function ss(e={}){let t=e.solanaRpc||co;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:jc(n)}:{signature:r,slot:null,instructions:[]}}}}import F from"node:fs";import vt from"node:path";var $r=1,Bc=0;function ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function D(e){return structuredClone(e)}function jr(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)=>jr(r,`${t}[${n}]`));if(ve(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}`);jr(n,`${t}.${r}`)}return}throw new Error(`launch-radar store: non-JSON value at ${t}`)}}function Se(e){return Array.isArray(e)?`[${e.map(Se).join(",")}]`:ve(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Se(e[t])}`).join(",")}}`:JSON.stringify(e)}function $c(){return{version:$r,candidates:[],cursor:null,strategyStatus:{mode:"shadow",status:"inert",ambiguous:!1},evidence:[]}}function qc(e){if(!ve(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 Qe(e){if(!ve(e)||e.version!==$r)throw new Error("launch-radar store: corrupt or unsupported version");if(!Array.isArray(e.candidates)||!(e.cursor===null||ve(e.cursor))||!Array.isArray(e.evidence))throw new Error("launch-radar store: corrupt state shape");qc(e.strategyStatus),jr(e);try{Ct(e.evidence)}catch(t){throw new Error(`launch-radar store: corrupt evidence: ${t.message}`)}return D(e)}function It(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){It(e);let t;try{t=JSON.parse(F.readFileSync(e,"utf8"))}catch{throw new Error("launch-radar store: corrupt JSON")}return Qe(t)}function Pr(e,t){let r=Qe(t),n=vt.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");It(e,!0)&&It(e);let s=vt.join(n,`.launch-radar.${process.pid}.${Bc+=1}.tmp`),i;try{i=F.openSync(s,"wx",384),F.writeFileSync(i,`${Se(r)}
|
|
8
|
+
`,"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 qr(e={}){let t=e.path;if(typeof t!="string"||!vt.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");It(t,!0)?Br(t):Pr(t,$c());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 Pr(t,o),D(o)};return Object.freeze({path:t,read:r,replaceState(o={}){if(!ve(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(Qe(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&&Se(i.data)===Se(o?.data))return D(i);throw new Error(`launch-radar store: duplicate evidence conflict: ${o?.id}`)}let a=Tt(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&&Se(u.data)===Se(a?.data))return{duplicate:!0,evidence:D(u),state:c};throw new Error(`launch-radar store: duplicate evidence conflict: ${a?.id}`)}let l=Tt(c.evidence,a),d=Qe({...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 Pr(t,{...s,strategyStatus:i}),D(i)},reconcile(o={}){if(!ve(o))throw new TypeError("launch-radar store: reconciliation state must be an object");let s=r(),i=Qe({...s,...D(o),version:$r,evidence:s.evidence});if(i.strategyStatus.ambiguous)throw new Error("launch-radar store: reconciliation must clear ambiguous state");return n(i,{reconciliation:!0})}})}function is(e={}){let t=e.path;if(typeof t!="string"||!vt.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");return Br(t)}function Dr(e){return e.ORACLE_CONFIG_DIR||ce.join(Uc.homedir(),".config","oracle")}function as(e,t){if(!e||!ce.isAbsolute(e))throw new Error(`${t} path must be absolute`);let r=Ot.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(Ot.readFileSync(e,"utf8"))}function Dc(e){return e==null?null:String(e)}function Pe(e){if(e!==void 0)return typeof e=="bigint"?e.toString():Array.isArray(e)?e.map(Pe).filter(t=>t!==void 0):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,Pe(r)])):e}function fs(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 Ur(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 Fc(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 Mc(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:fs(t.amountIn,"routeProbe.amountIn"),quoteAssetDecimals:Ur(t.quoteAssetDecimals,0,255,"routeProbe.quoteAssetDecimals"),slippageBps:Ur(t.slippageBps??100,0,1e4,"routeProbe.slippageBps"),maxImpactPct:Fc(t.maxImpactPct??25,0,100,"routeProbe.maxImpactPct"),timeoutMs:Ur(t.timeoutMs??12e3,250,6e4,"routeProbe.timeoutMs")})}function cs(e){return[e?.source,e?.amountOut,e?.netOut,e?.meta?.poolId].map(t=>String(t??"").toLowerCase()).join(":")}function us(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 Hc(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 ls(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 ds(e){if(!e?.best||!fs(e.best.amountOut,"best route amountOut"))throw new Error("best route returned no positive output");let t=Array.isArray(e.routes)?e.routes:[],r=cs(e.best),n=t.findIndex(a=>cs(a)===r),o=t.filter((a,c)=>c!==n),s=String(e.rankedOn||"gross").toLowerCase(),i=[...Array.isArray(e.warnings)?e.warnings:[]];return s!=="net"&&!i.some(a=>/gas.*not (?:included|accounted)|gross/i.test(String(a)))&&i.push("Ranked on gross output. Gas was not accounted for."),Pe({rankedOn:s,winner:e.best,runnersUp:o,routes:t,failed:Array.isArray(e.failed)?e.failed:[],sourcesTried:e.sourcesTried??null,sourcesAnswered:e.sourcesAnswered??null,improvementBps:e.improvementBps??null,spreadBasis:e.spreadBasis??null,priceImpact:e.priceImpact,impactRejected:e.impactRejected,impactUnmeasured:e.impactUnmeasured,warnings:i,note:e.note})}function Vc(e,t){return{quote:{evidence:"UNAVAILABLE",reason:e,observedAt:t},sellability:{verdict:"UNKNOWN",evidence:"UNAVAILABLE",reason:e,observedAt:t}}}async function ps({scanner:e,discovery:t,descriptor:r,routeFn:n=Xt,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=Mc(r);if(!t.quoteAsset)throw new Error("verified discovery did not identify a quote asset");if(!i)throw new Error("verified discovery did not identify a token");let c=t.poolKey?{v4PoolKey:Pe(t.poolKey),v4PoolId:t.poolId}:{},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);ls(d,t,"buy");let p=ds(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);ls(f,t,"reverse");let m=ds(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=Hc(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=Pe({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,Vc(c,o))}return Pe(s)}function ms(e){let t=e.quoteAsset||e.pool?.quoteAsset||e.token?.quoteAsset||"unknown",r=us(e.quoteAmountIn,e.quoteAssetDecimals??18)||us(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:Dc(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 Fr(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=as(t.ORACLE_LAUNCH_RADAR_STRATEGY_FILE,"strategy file"),n=as(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=Tr(r);if(![M.SHADOW,M.ARMED,M.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 zc({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");Wn();let a=qn(i[0]);if(!a)throw new Error(`no scanner registered for chain ${i[0]}`);let c=t.ORACLE_LAUNCH_RADAR_STORE_PATH||ce.join(Dr(t),"launch-radar",`state-${i[0]}.json`),u=qr({path:c});return _r({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),y=await St({discover:()=>sn({scanner:a,factories:o,fromBlock:h,toBlock:m,cursor:p}),evaluator:async({discovery:g})=>{let v=o.find(N=>N?.id===g?.factoryId||String(N?.factoryAddress||"").toLowerCase()===String(g?.factoryAddress||"").toLowerCase());return ps({scanner:a,discovery:g,descriptor:v,routeFn:e.routeFn||Xt,observedAt:new Date().toISOString()})},observedAt:new Date().toISOString()});return{candidates:y.candidates,cursor:y.cursor}},evaluate:async p=>ms(p),prepareFn:e.prepareFn||(p=>Ir({...p,scanner:a})),queueFn:e.queueFn||(p=>Or(p,t))})}function zc({env:e,factories:t,strategy:r,options:n}){let o=n.solanaScanner||ss(),s=n.solanaRouteFn||pr,i=n.solanaQuoteScanner||Co({routeFn:s}),a=e.ORACLE_LAUNCH_RADAR_STORE_PATH||ce.join(Dr(e),"launch-radar","state-solana.json"),c=qr({path:a});return _r({store:c,strategy:r,discover:async({cursor:l})=>{let d=await St({discover:()=>os({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 ps({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=>ms(l),prepareFn:n.prepareFn||(l=>Ir({...l,scanner:i})),queueFn:n.queueFn||(l=>Or(l,e))})}async function hs(e={}){let t=e.env||process.env,r=t.ORACLE_LAUNCH_RADAR_FACTORIES_DIR;if(!r||!ce.isAbsolute(r))throw new Error("ORACLE_LAUNCH_RADAR_FACTORIES_DIR must be an absolute directory");let n=Ot.lstatSync(r);if(n.isSymbolicLink()||!n.isDirectory())throw new Error("factories dir must be a regular directory");let o=Ot.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:ce.join(r,i),ORACLE_LAUNCH_RADAR_STORE_PATH:ce.join(t.ORACLE_LAUNCH_RADAR_STORE_DIR||ce.join(Dr(t),"launch-radar"),`state-${a}.json`)},u=await Fr({...e,env:c}).runCycle();s.push({file:i,mode:u.mode,status:u.status,blockers:u.blockers||[],count:(u.results||[]).length})}return{mode:M.SHADOW,status:"fleet",results:s}}var Kc=Object.freeze({OK:"ok",DEGRADED:"degraded",UNKNOWN:"unknown"}),Ed=Object.freeze({fresh:0,stale:1,down:2});var vd=Object.freeze([Object.freeze({id:"uniswap-v3",kind:"factory",chains:Object.freeze(["evm"]),status:"VERIFIED",evidence:"Uniswap V3 PoolCreated against factories returned by verified SwapRouter02.factory() eth_call."}),Object.freeze({id:"uniswap-v4",kind:"pool-manager",chains:Object.freeze(["evm"]),status:"VERIFIED",evidence:"Uniswap V4 Initialize logs against a verified PoolManager, exact PoolKey preserved."}),Object.freeze({id:"pons-v2",kind:"factory",chains:Object.freeze(["evm"]),chainIds:Object.freeze([4663]),status:"VERIFIED",factoryAddress:"0x7ed598bcef8bd9edd8c97a195c6d13f40801ec7e",evidence:"Blockscout-verified PonsV2LaunchFactory. Live TokenLaunched topic0 matched on RH."}),Object.freeze({id:"pump-fun",kind:"program",chains:Object.freeze(["solana"]),status:"VERIFIED",programId:"6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P",evidence:"Official pump-fun/pump-public-docs: create discriminator 181ec828051c0777."}),Object.freeze({id:"fomo",kind:"frontend",chains:Object.freeze(["solana","evm"]),status:"COVERED",via:Object.freeze(["pons-v2","pump-fun"]),evidence:"fomopad.family says Built on Pons / Robinhood Chain. fomopad.site says it is a pump.fun launchpad. No separate factory."}),Object.freeze({id:"based-bot",kind:"frontend",chains:Object.freeze(["evm"]),status:"UNAVAILABLE",evidence:"basedbot.app is a trading terminal, not a verified launch factory."}),Object.freeze({id:"opensea",kind:"nft-marketplace",chains:Object.freeze(["evm"]),status:"UNAVAILABLE",evidence:"OpenSea/Seaport is an NFT marketplace, not a fungible-token launch factory."}),Object.freeze({id:"four-meme",kind:"factory",chains:Object.freeze(["evm"]),status:"UNAVAILABLE",evidence:"No independently verified TokenManager/factory address on file this release."}),Object.freeze({id:"clanker",kind:"factory",chains:Object.freeze(["evm"]),status:"UNAVAILABLE",evidence:"No independently verified Clanker factory address on file this release."})]);import Wc from"node:os";import ys from"node:path";var Gc="oracle.launch-radar.data-plane.v1";function Yc(e){return String(e?.message||e||"unknown error").slice(0,300)}function Jc(e={}){return e.configDir||process.env.ORACLE_CONFIG_DIR||ys.join(Wc.homedir(),".config","oracle")}function Qc(e={}){return e.storePath||process.env.LAUNCH_RADAR_STORE_PATH||ys.join(Jc(e),"launch-radar","state.json")}function Xc(e={}){let t=Qc(e);try{return{ok:!0,path:t,state:is({path:t})}}catch(r){return{ok:!1,path:t,error:Yc(r)}}}function Zc(){return process.env.ORACLE_AUTONOMOUS_TRADING==="1"}function Mr(e={},t={}){let r=Xc(t),n={schema:Gc,storePath:r.path,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,autonomousTradingEnvSet:Zc()};if(!r.ok)return Object.freeze({...n,evidence:"UNAVAILABLE",reason:r.error,mode:M.SHADOW,status:"unavailable",ambiguous:null,candidateCount:null,cursor:null,evidenceCount:null,lastEvidenceAt:null});let{state:o}=r,s=o.evidence.at(-1)||null;return Object.freeze({...n,evidence:"LIVE",reason:o.strategyStatus.reason??null,mode:o.strategyStatus.mode,status:o.strategyStatus.status,ambiguous:o.strategyStatus.ambiguous,candidateCount:o.candidates.length,cursor:o.cursor,evidenceCount:o.evidence.length,lastEvidenceAt:s?s.at:null})}var Hr=new Set(process.argv.slice(2));(Hr.has("--help")||Hr.has("-h"))&&(console.log(`oracle-launch-radar-shadow
|
|
9
9
|
|
|
10
10
|
Default: print read-only status and exit. Missing state remains UNAVAILABLE and creates nothing.
|
|
11
11
|
|