@oracle-agent/oracle 0.35.34 → 0.35.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +43 -8
  2. package/artifacts/specialist-packs/oracle-full-crypto.json +11 -0
  3. package/dist/address-book.mjs +2 -2
  4. package/dist/agent-sessions.mjs +8 -8
  5. package/dist/assets/profiles/canton-agent/SOUL.md +44 -0
  6. package/dist/assets/profiles/canton-agent/profile.json +30 -0
  7. package/dist/assets/profiles/oracle/SOUL.md +1 -0
  8. package/dist/assets/skills/oracle-canton/SKILL.md +49 -0
  9. package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
  10. package/dist/bin/desk-server.mjs +35 -35
  11. package/dist/bin/oracle-data-mcp.mjs +17 -17
  12. package/dist/bin/oracle-gateway.mjs +14 -14
  13. package/dist/bin/oracle-launch-radar-shadow.mjs +4 -4
  14. package/dist/bin/oracle-mev-arb-shadow.mjs +4 -4
  15. package/dist/bin/oracle-mev-shadow.mjs +4 -4
  16. package/dist/bin/oracle-public-server.mjs +4 -4
  17. package/dist/bin/oracle-route.mjs +8 -8
  18. package/dist/bin/oracle-scan.mjs +10 -10
  19. package/dist/bin/oracle.mjs +8 -6
  20. package/dist/cli/commands/agent-session.mjs +10 -10
  21. package/dist/cli/commands/airdrop.mjs +16 -0
  22. package/dist/cli/commands/chain.mjs +1 -1
  23. package/dist/cli/commands/chat.mjs +215 -204
  24. package/dist/cli/commands/doctor.mjs +5 -5
  25. package/dist/cli/commands/eval.mjs +151 -141
  26. package/dist/cli/commands/extension-policy.mjs +3 -3
  27. package/dist/cli/commands/farm.mjs +22 -22
  28. package/dist/cli/commands/mint.mjs +22 -0
  29. package/dist/cli/commands/model.mjs +219 -208
  30. package/dist/cli/commands/plugins.mjs +42 -39
  31. package/dist/cli/commands/quickstart.mjs +6 -6
  32. package/dist/cli/commands/session-vault.mjs +1 -1
  33. package/dist/cli/commands/sign.mjs +12 -12
  34. package/dist/cli/commands/signer.mjs +25 -23
  35. package/dist/cli/commands/snipe.mjs +6 -6
  36. package/dist/cli/commands/swap.mjs +12 -12
  37. package/dist/cli/commands/venues.mjs +2 -2
  38. package/dist/control/receipt-lineage.mjs +1 -0
  39. package/dist/data/desk-data.mjs +33 -33
  40. package/dist/data/providers/farming.mjs +2 -2
  41. package/dist/data/providers/lp-destination-discovery.mjs +4 -4
  42. package/dist/index.mjs +50 -49
  43. package/dist/launch-radar/index.mjs +4 -4
  44. package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
  45. package/dist/local-signer/index.mjs +3 -3
  46. package/dist/local-signer/runtime.mjs +22 -20
  47. package/dist/router/index.mjs +3 -3
  48. package/dist/router/prepare-bridge.mjs +1 -1
  49. package/dist/scanner/index.mjs +4 -4
  50. package/dist/task.mjs +2 -2
  51. package/dist/teams/index.mjs +3 -1
  52. package/dist/tui/standalone-client.mjs +85 -75
  53. package/package.json +3 -2
  54. package/public/eval-report.json +6 -6
  55. package/public/oracle-splash/assets/desktop-app.jpg +0 -0
  56. package/public/oracle-splash/assets/hero/agent-session-poster.jpg +0 -0
  57. package/public/oracle-splash/assets/hero/agent-session.mp4 +0 -0
  58. package/public/oracle-splash/assets/hero/agent-session.webm +0 -0
  59. package/public/oracle-splash/assets/oracle-cli-v03535-poster.jpg +0 -0
  60. package/public/oracle-splash/assets/oracle-cli-v03535.gif +0 -0
  61. package/public/oracle-splash/assets/protocol-build-time.jpg +0 -0
  62. package/public/oracle-splash/downloads/index.html +2 -2
  63. package/public/oracle-splash/index.html +132 -54
  64. package/server.json +2 -2
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  var To=Object.defineProperty;var J=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var lt=(e,t)=>{for(var r in t)To(e,r,{get:t[r],enumerable:!0})};import le from"node:net";import Vo from"node:dns";function He(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 ht(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 bt(e){if(le.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(le.isIPv6(e)){let t=He(e);if(!t)return!1;let r=He("::ffff:0:0");return ht(t,r,96)?bt([...t.slice(12)].join(".")):ht(t,He("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([o,s])=>ht(t,He(o),s)):!1}return!1}function Ko(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(zo.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=le.isIP(r);return n!==0&&!bt(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function yt(e,{lookupFn:t=Vo.promises.lookup}={}){let r=Ko(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:le.isIPv6(r.host)?6:4}]};let n;try{n=await t(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(o=>!bt(o.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function wt({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n;try{let d=await t();r=d.Agent,n=d.fetch}catch(d){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${d?.message||d}`);return null}if(typeof r!="function"||typeof n!="function"){if(e)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let o=d=>String(d).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),s=new Map,i=d=>(Array.isArray(d)?d:[d]).map(p=>typeof p=="string"?{address:p}:p).filter(p=>p&&p.address).map(p=>({address:p.address,family:p.family||(le.isIPv6(p.address)?6:4)})),a=(d,p,f)=>{s.set(o(d),i(typeof p=="string"?[{address:p,family:f}]:p))},c=d=>{let p=o(d);if(le.isIP(p))return[{address:p,family:le.isIPv6(p)?6:4}];let f=s.get(p);if(!f||!f.length)throw new Error(`refused: unpinned host ${d} during pinned fetch`);return f},u=new r({connect:{lookup(d,p,f){let m;try{m=c(d)}catch(h){return f(h)}return p?.all?f(null,m):f(null,m[0].address,m[0].family)}}}),l=Wo((d,p={})=>n(d,{...p,dispatcher:u}),a);return{dispatcher:u,fetch:l,pin:a,resolve:c,async close(){try{await u.destroy()}catch{}}}}function Wo(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[gt]=Object.freeze({pin:t}),e}function At(e){return typeof e=="function"&&typeof e[gt]?.pin=="function"}function jr(e,t,r){if(!At(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[gt].pin(t,r)}var zo,gt,Br=J(()=>{zo=new Set(["localhost","metadata.google.internal","metadata.goog"]);gt=Symbol.for("oracle.egressGuard.pinCapableFetch")});import{createHash as Go}from"node:crypto";import{types as Z}from"node:util";function P(e){return ne(`HTTP JSON body refused: ${e}`)}function ns(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 Z[t]=="function"&&Z[t](e))}function os(e){let t=[],r=0,n=0,o=0,s=0,i=new WeakSet,a=l=>{if(r+=Buffer.byteLength(l,"utf8"),r>X.bytes)throw P("serialized byte limit exceeded");t.push(l)},c=l=>{if(Buffer.byteLength(l,"utf8")>X.bytes)throw P("serialized byte limit exceeded");return JSON.stringify(l)},u=(l,d)=>{if(n+=1,n>X.nodes)throw P("node limit exceeded");if(d>X.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(Z.isProxy(l))throw P("proxy value");if(ns(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(Z.isProxy(m))throw P("proxy array prototype");if(h+=1,h>X.depth)throw P("array prototype depth limit exceeded");m=Object.getPrototypeOf(m)}if(l.length>X.arrayLength)throw P("array length limit exceeded");for(let A=0;A<l.length;A+=1){let I=Object.getOwnPropertyDescriptor(l,String(A));if(!I||!Object.hasOwn(I,"value")||I.enumerable!==!0)throw P("array entries must be dense enumerable own data")}let b=0;for(let A in l){if(s+=1,s>X.fields)throw P("enumeration limit exceeded");if(Object.hasOwn(l,A)&&(b+=1,b>l.length))throw P("named array fields are unsupported")}if(b!==l.length)throw P("array entries must be dense enumerable own data");a("[");for(let A=0;A<l.length;A+=1)A&&a(","),u(Object.getOwnPropertyDescriptor(l,String(A)).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>X.fields)throw P("enumeration limit exceeded");if(!Object.hasOwn(l,m))continue;if(o+=1,o>X.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 ss(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(Z.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 is(){return Object.assign(Object.create(null),{Accept:"application/json"})}function as(e,t){if(!e)throw new Error(`HTTP redirect from ${t} missing Location`);let r=new URL(String(e),String(t));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${t} used unsupported protocol ${r.protocol}`);return r.toString()}function cs(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function Ve(e){if((typeof e!="object"||e===null)&&typeof e!="function")return`${typeof e}:${String(e)}`;let t=$r.get(e);return t||(t=Fr,Fr+=1,$r.set(e,t)),`reference:${t}`}function Mr(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?us.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 Hr(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(Mr);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return Mr(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&ls.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function ds(e,t,r,n={},o=null){let s=Go("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 ps(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,qr):Math.min(250*2**e,qr)+Math.floor(Math.random()*100)}function ne(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function Et(e,t,r){return ne(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function de(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function ms(e){return e?e.byteLength??e.length??0:0}async function hs(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&&(de(e),!n))throw Et(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 Et(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+=ms(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 Et(r,`streamed ${c} bytes`,t);let l=Buffer.concat(a);return(u?l.subarray(0,t):l).toString("utf8")}function bs(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function ys(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=ze}){let b=new AbortController,A=setTimeout(()=>b.abort(),s),I=f?Dr?Dr([f,b.signal]):f:b.signal,x=null,C=t,g=i?{lookupFn:i}:{};if(c&&!a&&!At(C))throw ne(`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 v=async(S,{status:k=null}={})=>{let O=await yt(S,g);if(!O.ok)throw ne(k==null?`HTTP refused ${S}: ${O.error}`:`HTTP redirect to ${S} ${O.error}`,k==null?{}:{status:k});let L=new URL(S).hostname;if(a){if(x&&(await x.close(),x=null),!x)try{x=await wt({requireUndici:!0,...d?{importUndici:d}:{}})}catch(y){throw ne(k==null?`HTTP refused ${S}: ${y?.message||y}`:`HTTP redirect to ${S} refused: ${y?.message||y}`,k==null?{}:{status:k})}x.pin(L,O.addresses),C=x.fetch}else jr(C,L,O.addresses);return O};try{let S=String(e),k=Object.assign(Object.create(null),n||{});c&&await v(S);for(let O=0;O<=h;O+=1){let L=Object.assign(Object.create(null),{method:r,headers:k,body:o,signal:I,redirect:"manual",dispatcher:void 0}),y=await C(S,L);if((m==="error"||h===0)&&y.status>=300&&y.status<400)throw de(y),ne(`HTTP ${y.status} ${r} redirect refused`,{status:y.status,redirectRefused:!0});if(rs.has(y.status)){let T=l===!0&&r==="POST"&&[307,308].includes(y.status)&&Hr(r,o);if(r!=="GET"&&r!=="HEAD"&&!T){de(y);let B=new Error(`HTTP ${y.status} ${r} ${S} redirected non-idempotent request`);throw B.status=y.status,B}if(O===h)throw de(y),ne(`HTTP ${y.status} ${r} redirect budget exhausted`,{status:y.status,redirectRefused:!0});let re=y.headers?.get?.("location"),V;try{V=as(re,S)}catch(B){throw de(y),B}let ie=!cs(V,S);if(de(y),ie&&r==="POST"){let B=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw B.status=y.status,B}if(ie&&l){let B=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw B.status=y.status,B.retryable=!1,B}if(ie&&(k=is(k)),c)await v(V,{status:y.status});else if(ie){let B=await yt(V,g);if(!B.ok){let _=new Error(`HTTP redirect from ${S} ${B.error}`);throw _.status=y.status,_.retryable=!1,_}a&&B.addresses?.length&&(x||(x=await wt(d?{importUndici:d}:{})),x&&(x.pin(new URL(V).hostname,B.addresses),C=x.fetch))}S=V;continue}if(typeof p=="function")try{await p(y,{url:S})}catch(T){throw de(y),ne(T?.message||String(T))}let F=await hs(y,u,{url:S,onOversize:()=>b.abort()}),w=bs(F);if(!y.ok){let T=new Error(`HTTP ${y.status} ${r} ${S}`);throw T.status=y.status,T.retryAfter=y.headers?.get?.("retry-after")??null,T.body=w??F.slice(0,300),T}return w??F}throw new Error(`HTTP redirect loop for ${e}`)}catch(S){if(b.signal.aborted&&!vt(f)){let k=S&&(typeof S=="object"||typeof S=="function")&&!Z.isProxy(S)?S: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 y=new Error("HTTP request timed out");throw Object.defineProperties(y,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),y}}throw S}finally{clearTimeout(A),x&&await x.close()}}async function ee(e,t={}){if(t!=null&&typeof t!="object"&&typeof t!="function")throw new TypeError("HTTP options must be an object");if(t!=null&&Z.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 _ of Object.getOwnPropertyNames(t)){let R=Object.getOwnPropertyDescriptor(t,_);if(!(_==="toJSON"&&R&&Object.hasOwn(R,"value")&&R.value===void 0)){if(!r.has(_))throw new TypeError("HTTP options contain unknown fields");if(!R||!R.enumerable||!Object.hasOwn(R,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=_=>{if(t==null||!Object.hasOwn(t,_))return;let R=Object.getOwnPropertyDescriptor(t,_);if(!R||!Object.hasOwn(R,"value"))throw new TypeError("HTTP options must contain own data properties");return R.value};if(typeof e!="string"||e.length===0||e.length>8192)throw new TypeError("HTTP URL must be a bounded string");let o=n("method");if(o!==void 0&&(typeof o!="string"||!/^[A-Za-z]+$/u.test(o)))throw new TypeError("HTTP method must be a string token");let s=n("timeoutMs");if(s!==void 0&&(!Number.isInteger(s)||s<1||s>12e4))throw new TypeError("HTTP timeoutMs must be a bounded integer");let i=n("retries");if(i!==void 0&&(!Number.isInteger(i)||i<0||i>10))throw new TypeError("HTTP retries must be a bounded integer");let a=n("redirectPolicy");if(a!==void 0&&a!=="follow"&&a!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let c=n("maxRedirects");if(c!==void 0&&(!Number.isInteger(c)||c<0||c>ze))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${ze}`);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??ze;for(let _ of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let R=n(_);if(R!==void 0&&typeof R!="boolean")throw new TypeError(`HTTP ${_} 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(Z.isProxy(p)||!(p instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{vt(p)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let _ of["importUndici","lookupFn","validateResponse"]){let R=n(_);if(R!==void 0&&typeof R!="function")throw new TypeError(`HTTP ${_} must be a function`)}let f=n("fetchImpl"),m=f||globalThis.fetch;if(typeof m!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let h=s??12e3,b=(o||"GET").toUpperCase(),A=n("headers"),I=ss(A),x=Object.assign(Object.create(null),I);Object.keys(x).some(_=>_.toLowerCase()==="accept")||(x.Accept="application/json");let C=n("body");C!=null&&typeof C!="string"&&(Object.keys(x).find(R=>R.toLowerCase()==="content-type")||(x["Content-Type"]="application/json"),C=os(C));let g=i??Yo,v=n("lookupFn"),S=!f,k=n("untrustedUrl")===!0,O=n("sameOriginRedirectsOnly")===!0,L=n("importUndici"),y=n("validateResponse"),F=p,w=d??null,T=async()=>{let _;for(let R=0;R<=g;R++){F&&Zo.call(F);try{return await ys(e,{fetchImpl:m,method:b,headers:x,body:C,timeoutMs:h,lookupFn:v,realFetch:S,untrustedUrl:k,maxResponseBytes:w,sameOriginRedirectsOnly:O,importUndici:L,validateResponse:y,signal:F,redirectPolicy:u,maxRedirects:l})}catch(ae){_=ae;let ge=ut=>{if(!ae||typeof ae!="object"&&typeof ae!="function"||Z.isProxy(ae))return;let ke=Object.getOwnPropertyDescriptor(ae,ut);return ke&&Object.hasOwn(ke,"value")?ke.value:void 0},ct=ge("status"),xo=ge("oracleTimeout")===!0||ge("name")==="AbortError"||ge("name")==="TimeoutError"||vt(F),No=new Set([408,425,429]),ko=ge("retryable")===!1?!1:ct!=null?No.has(ct)||Jo.has(ct)&&Ur.has(b):!xo&&Ur.has(b);if(R===g||!ko)throw ae;let br=ps(R,ge("retryAfter"));F?await new Promise((ut,ke)=>{let Co=setTimeout(ut,br);es.call(F,"abort",()=>{clearTimeout(Co),ke(ts(F)||new DOMException("Aborted","AbortError"))},{once:!0})}):await fs(br)}}throw _};if(!(n("dedupe")!==!1&&!F&&Hr(b,C)))return T();let V=ds(b,e,x,{untrustedUrl:k,maxResponseBytes:w,sameOriginRedirectsOnly:O,redirectPolicy:u,maxRedirects:l,timeoutMs:h,retries:g,fetchImpl:Ve(m),realFetch:S,lookupFn:Ve(v),importUndici:Ve(L),validateResponse:Ve(y)},C),ie=St.get(V);if(ie)return ie;let B=T().finally(()=>St.delete(V));return St.set(V,B),B}async function Vr(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 Jo,Ur,Yo,qr,Qo,Xo,Zo,es,Dr,vt,ts,rs,ze,sc,X,St,$r,Fr,us,ls,fs,Se=J(()=>{Br();Jo=new Set([408,425,429,500,502,503,504]),Ur=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Yo=2,qr=4e3,Qo=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Xo=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Zo=AbortSignal.prototype.throwIfAborted,es=EventTarget.prototype.addEventListener,Dr=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,vt=e=>e?Qo.call(e):!1,ts=e=>e?Xo.call(e):void 0,rs=new Set([301,302,303,307,308]),ze=3,sc=64*1024,X=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});St=new Map,$r=new WeakMap,Fr=1;us=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),ls=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);fs=e=>new Promise(t=>setTimeout(t,e))});import{types as Ut}from"node:util";function qt(e){if(!e||typeof e!="object"||Ut.isProxy(e)||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Je(e,t){if(e==null||(typeof e=="object"||typeof e=="function")&&Ut.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 Ge(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(Ut.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]=Ge(i.value,t,r+1)}return o}if(!qt(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]=Ge(s.value,t,r+1)}return n}var kn=J(()=>{});function ii(e={}){return String(e.rpcUrl||process.env.SOLANA_RPC_URL||si).trim()}function Ee(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 Cn(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=Ge(await ee(ii(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(!qt(o))throw new Error(`solana-rpc ${e}: invalid response envelope`);let s=Je(o,"error");if(s)throw new Error(`solana-rpc ${e}: ${Je(s,"message")||JSON.stringify(s)}`);if(!Object.hasOwn(o,"result"))throw new Error(`solana-rpc ${e}: missing result`);return Je(o,"result")}var si,Dt=J(()=>{Se();kn();si="https://api.mainnet-beta.solana.com"});import{createHash as ai,createHmac as ci,timingSafeEqual as Gc}from"node:crypto";function $t(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map($t).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${$t(e[r])}`).join(",")}}`}function Tn(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Ln(e=process.env){return Tn(process.env)||Tn(e)}function pi(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function fi(e){let t=pi(e);return ai("sha256").update($t(t)).digest("hex")}function mi(e,t=Ln()){return t?ci("sha256",t).update(String(e)).digest("hex"):""}function Rn(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+li:Number(s),l=u-c;if(!Number.isSafeInteger(c)||!Number.isSafeInteger(u)||l<=0||l>di)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let p={...a,preparedAt:c,expiresAt:u,prepareVersion:ui},f=fi(p),m=Ln(n),h=m?mi(f,m):void 0,b={...p,prepareHash:f};return h&&(b.prepareMac=h),b}var ui,li,di,_n=J(()=>{ui=2,li=300*1e3,di=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});function Ft(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function wi(e){return hi.some(t=>e.startsWith(t))||bi.has(e)}function gi(e){let t=String(e);if(!/^[\x20-\x7e]+$/.test(t))return!0;let r=Ft(t);return wi(r)?!1:yi.has(r)?!0:r.includes("signed")||r.includes("signature")||r.endsWith("sig")||r.endsWith("sigs")}function Ai(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 Mt(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=>Mt(c,t+1,r,n));let o=[];for(let[c,u]of Object.entries(e)){if(gi(c)){o.push(c);continue}o.push(...Mt(u,t+1,r,n))}let i=Object.keys(e).map(Ft).some(c=>c.endsWith("psbt")||c.endsWith("psbtbase64")),a=Object.entries(e).some(([c,u])=>/complete|finalized|isfinal/.test(Ft(c))&&u===!0);return i&&a&&o.push("psbt(complete)"),Ai(e)&&o.push("v/r/s"),o}function Pn(e,t){let r=Mt(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 hi,bi,yi,jn=J(()=>{hi=["unsigned","notsigned","tosign","signable"],bi=new Set(["requiresusersignature","requiressignature","needssignature","signaturerequired","signaturesrequired","signingready","signaturecount","signaturethreshold","requiredsignatures","signatureneeded","hassignature","allowsignatures","requestsignature","multisig","cosig","msig"]),yi=new Set(["sig","sigs","scriptsig","witness","psbt","finalizedpsbt","completepsbt","finalpsbt","psbtfinalized","serializedtransaction"])});var zt={};lt(zt,{JUPITER_MAX_SLIPPAGE_BPS:()=>qn,JUPITER_SWAP_API:()=>Be,SOL_MINT:()=>Xe,USDC_MINT:()=>Ht,jupiterHealth:()=>xi,jupiterPrepareSwap:()=>ki,jupiterQuote:()=>Vt,jupiterSignerEnvelope:()=>Mn,jupiterVenues:()=>Ii,solanaGuard:()=>Qe});function Dn(e={}){return String(e.baseUrl||process.env.JUPITER_SWAP_API_URL||Be).replace(/\/$/,"")}function Ue(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 $n(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>qn)throw new Error("jupiter: slippage exceeds hard 100 bps cap");return t}function Ye(e,t){return e==null?t:!!e}function Si(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 Ei(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 Fn(e){let t=Buffer.from(e,"base64"),r=Ei(t,0);if(!r||r.value!==1)throw new Error("jupiter: unsigned swapTransaction must declare exactly one signature slot");let n=r.offset+r.value*64;if(n>=t.length)throw new Error("jupiter: Solana transaction missing message bytes");if(t.subarray(r.offset,n).some(s=>s!==0))throw new Error("jupiter: swapTransaction already contains signature material");return t.subarray(n).toString("base64")}function Qe(e={},{quotedAtMs:t=Date.now(),ttlMs:r=Bn}={}){let n=Ee(e.inputMint,"inputMint"),o=Ee(e.outputMint,"outputMint"),s=Ue(e.inAmount,"inAmount"),i=Ue(e.outAmount,"outAmount"),a=Ue(e.otherAmountThreshold??e.outAmount,"otherAmountThreshold"),c=$n(e.slippageBps??50),u=(BigInt(i)-BigInt(i)*BigInt(c)/10000n).toString();if(a!==u)throw new Error("jupiter: otherAmountThreshold does not match serialized min-out");return{mode:"solana-jupiter-quote",provider:"jupiter",venue:"jupiter-swap-v1",inputMint:n,outputMint:o,inAmount:s,outAmount:i,otherAmountThreshold:a,slippageBps:c,contextSlot:e.contextSlot??null,quotedAtMs:t,expiresAtMs:t+Math.min(Math.max(Number(r)||Bn,1e3),3e4)}}function Mn({userPublicKey:e,guard:t,swapTransaction:r,args:n={},response:o={}}){if(t.inputMint!==Xe)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=Fn(r),i=Ue(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 Un(e){if(typeof e!="string"||!e.length)return!1;let t=0n;for(let o of e){let s=Oi.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 Ii(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(`${Be}/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])=>Un(p)),c=[],u=i.filter(([p])=>!Un(p)).map(([p,f])=>({programId:p,label:f,reason:"malformed program id"}));if(e.verify===!1)return{source:`${Be}/program-id-to-label`,verified:a.map(([p,f])=>({programId:p,label:f})),unresolved:u,verifiedOnChain:!1,totals:{fromRouterMap:i.length,verified:a.length}};let l=async p=>{let m=await(await n(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(p),signal:AbortSignal.timeout(Number(t.timeoutMs)||2e4)})).json();if(m.error)throw new Error(m.error.message);return m.result};for(let p=0;p<a.length;p+=90){let f=a.slice(p,p+90),m=null;for(let h=0;h<3&&!m;h++)try{m=await l({jsonrpc:"2.0",id:1,method:"getMultipleAccounts",params:[f.map(([b])=>b),{encoding:"base64",dataSlice:{offset:0,length:0}}]})}catch{await new Promise(b=>setTimeout(b,2e3*(h+1)))}if(!m){for(let[h,b]of f)u.push({programId:h,label:b,reason:"rpc batch failed after 3 attempts"});continue}m.value.forEach((h,b)=>{let[A,I]=f[b];h&&h.executable===!0&&vi.has(h.owner)?c.push({programId:A,label:I,owner:h.owner}):u.push({programId:A,label:I,reason:h?h.executable!==!0?"not executable":`unknown owner ${h.owner}`:"account not found"})}),p+90<a.length&&await new Promise(h=>setTimeout(h,700))}let d=new Set(c.map(p=>p.label.replace(/\s+(CLMM|CP|V\d+|Launchlab|DLMM|Pools?)$/i,"").trim()));return{source:`${Be}/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 xi(e={}){try{return{ok:!0,provider:"jupiter",outAmount:(await Vt({inputMint:Xe,outputMint:Ht,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 Vt(e={},t={}){let r=Ee(e.inputMint||e.fromMint||Xe,"inputMint"),n=Ee(e.outputMint||e.toMint||Ht,"outputMint"),o=Ue(e.amount||e.inAmount,"amount"),s=$n(e.slippageBps??e.maxSlippageBps??50),i=new URL(`${Dn(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 ee(i.toString(),{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),c=Qe({...a,slippageBps:s},t);return{provider:"jupiter",chain:"solana-mainnet-beta",quoteReady:!0,executionReady:!1,inputMint:r,outputMint:n,amount:o,quote:a,solanaGuard:c}}function Ni(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function ki(e={},t={}){let r=Ee(e.userPublicKey||e.owner||e.wallet,"userPublicKey"),n=e.quoteResponse?{quote:e.quoteResponse,solanaGuard:Qe(e.quoteResponse,t)}:await Vt(e,t),o=n.quote,s=n.solanaGuard||Qe(o,t);if(Ye(e.dynamicSlippage,!1)===!0)throw new Error("jupiter: dynamicSlippage would override the enforced slippage ceiling \u2014 pass an explicit slippageBps instead");let i=await ee(`${Dn(t)}/swap`,{method:"POST",body:Ni({quoteResponse:o,userPublicKey:r,wrapAndUnwrapSol:Ye(e.wrapAndUnwrapSol,!0),dynamicComputeUnitLimit:Ye(e.dynamicComputeUnitLimit,!0),dynamicSlippage:!1,asLegacyTransaction:Ye(e.asLegacyTransaction,!0),prioritizationFeeLamports:e.prioritizationFeeLamports??0}),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),a=Si(i?.swapTransaction);Fn(a),Pn("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=Mn({userPublicKey:r,guard:s,swapTransaction:a,args:e,response:i})}catch(f){p=String(f?.message||f).slice(0,200)}return Rn({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 Be,Xe,Ht,qn,Bn,vi,Oi,Kt=J(()=>{Se();Dt();_n();jn();Be="https://lite-api.jup.ag/swap/v1",Xe="So11111111111111111111111111111111111111112",Ht="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",qn=100,Bn=2e4;vi=new Set(["BPFLoaderUpgradeab1e11111111111111111111111","BPFLoader2111111111111111111111111111111111","BPFLoader1111111111111111111111111111111111"]),Oi="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});var zn={};lt(zn,{SELL_SIM:()=>U,assertSellable:()=>_i,simulateSell:()=>Vn});function Li(e,t){return t===0n?null:Number((t-e)*10000n/t)}function Ri(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 Vn(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=Ri(e.amountIn,"amountIn"),i;try{i=await t.quote({chainId:o,inputMint:n,outputMint:r,amount:s.toString(),side:"buy"})}catch(f){return Y(U.UNKNOWN,`buy leg could not be quoted: ${Wt(f)}`,{chainId:o,token:r,base:n})}let a=Hn(i?.outAmount);if(a==null||a===0n)return Y(U.UNKNOWN,"buy leg returned no output \u2014 no route or no liquidity",{chainId:o,token:r,base:n});let c;try{c=await t.quote({chainId:o,inputMint:r,outputMint:n,amount:a.toString(),side:"sell"})}catch(f){return Y(U.HONEYPOT,`buy routes but the SELL leg fails to quote (${Wt(f)}) \u2014 you would not be able to exit`,{chainId:o,token:r,base:n,tokensOut:a.toString()})}let u=Hn(c?.outAmount);if(u==null||u===0n)return Y(U.HONEYPOT,"sell leg returns zero \u2014 the position cannot be exited for value",{chainId:o,token:r,base:n,tokensOut:a.toString()});let l=Li(u,s),d={chainId:o,token:r,base:n,amountIn:s.toString(),tokensOut:a.toString(),roundTripOut:u.toString(),roundTripLossBps:l,evidence:"quote-only"},p=t.executionProven===!0?!0:null;if(typeof t.executionCheck=="function")try{let f=await t.executionCheck({chainId:o,token:r,base:n,tokensOut:a.toString(),amountIn:s.toString()});if(f?.executable===!1)return Y(U.HONEYPOT,`the sell reverts or returns false at execution (${f?.reason||"transfer-level block"}) even though it quotes cleanly \u2014 a honeypot a pool-math quote cannot see`,{...d,evidence:"execution",executable:!1});p=f?.executable===!0?!0:p}catch(f){d.executionCheckError=Wt(f)}return p===!0&&(d.evidence="execution"),l==null?Y(U.UNKNOWN,"could not compute round-trip loss",d):l>=Ci?Y(U.HONEYPOT,`round trip loses ${(l/100).toFixed(1)}% \u2014 a sell tax or rigged curve, not normal slippage`,d):l>=Ti?Y(U.CAUTION,`round trip loses ${(l/100).toFixed(1)}% \u2014 high tax or thin liquidity`,d):p===!0?Y(U.SAFE,`round trip loses ${(l/100).toFixed(1)}% and the sell executes \u2014 exit path verified`,d):Y(U.CAUTION,`round trip quotes clean (${(l/100).toFixed(1)}% loss) but is unverified at execution \u2014 a pool-math quote cannot see a transfer-hook blacklist or transfer-only sell tax; run an execution-level sell simulation to clear SAFE`,d)}function Y(e,t,r){return{status:e,safe:e===U.SAFE,tradable:e===U.SAFE||e===U.CAUTION,reason:t,...r}}function Hn(e){if(e==null)return null;try{let t=String(e).trim();return/^\d+$/.test(t)?BigInt(t):null}catch{return null}}function Wt(e){return String(e?.message||e).slice(0,120)}async function _i(e={},t={}){let r=await Vn(e,t);if(!(r.status===U.SAFE||r.status===U.CAUTION&&t.allowCaution!==!1||r.status===U.UNKNOWN&&t.allowUnknown===!0)){let o=new Error(`sell-sim ${r.status}: ${r.reason}`);throw o.sellSim=r,o}return r}var U,Ci,Ti,Kn=J(()=>{U=Object.freeze({SAFE:"SAFE",CAUTION:"CAUTION",HONEYPOT:"HONEYPOT",UNKNOWN:"UNKNOWN"}),Ci=5e3,Ti=1500});import Ze from"node:fs";import Ui from"node:os";import Oe from"node:path";import{fileURLToPath as qi}from"node:url";function Qn(){return process.env.ORACLE_FAKE_HOME||Ui.homedir()}function $i(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function et(){return $i()?process.env.ORACLE_CONFIG_DIR||Oe.join(Qn(),".config","oracle"):Oe.join(Qn(),".config","oracle")}function Fi(){return Oe.join(et(),"desk.json")}function Mi(){return Oe.join(et(),"env")}function ve({force:e=!1}={}){if(ve._done&&!e)return ve._result||null;ve._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=Mi();if(Ze.existsSync(o))for(let s of Ze.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=Fi();if(Ze.existsSync(o)){let s=JSON.parse(Ze.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)),ve._result=Object.keys(t).length?t:null,ve._result}var Di,iu,Xn=J(()=>{Di=Oe.dirname(qi(import.meta.url)),iu=Oe.resolve(Di,"../..");try{ve()}catch{}});var to={};lt(to,{armPreparedAction:()=>Yi,callSigner:()=>Zn,queueOwnerAction:()=>eo});import{existsSync as Hi,readFileSync as Vi}from"node:fs";import{request as zi}from"node:http";import Ki from"node:path";function Gi(e=process.env){let t=String(e.ORACLE_SIGNER_URL||Wi).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 Ji(e=process.env){if(e.ORACLE_SIGNER_TOKEN)return String(e.ORACLE_SIGNER_TOKEN);let t=Ki.join(et(),"signer","signer-token");return Hi(t)?Vi(t,"utf8").trim():null}function Zn(e,{method:t="GET",body:r=null,env:n=process.env,timeoutMs:o=4e3}={}){let s=Gi(n),i=Ji(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=zi({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 eo(e,t=process.env){if(!e||e.version!==1||!e.surface)throw new Error("queueOwnerAction: version-1 surface envelope required");return Zn("/pending",{method:"POST",body:{artifact:e},env:t,timeoutMs:8e3})}async function Yi(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 eo(r,t)}var Wi,ro=J(()=>{Xn();Wi="http://127.0.0.1:9462"});var Ce=Object.freeze({PASS:"PASS",WARN:"WARN",BLOCK:"BLOCK",UNKNOWN:"UNKNOWN"}),Lo=new Set(["LIVE","CACHED","STALE","UNKNOWN","UNAVAILABLE"]),yr=/^0x[0-9a-fA-F]{40}$/,Ro=/^0x[0-9a-fA-F]{64}$/;function Ae(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Ae(t);Object.freeze(e)}return e}function G(e,t=null){return e&&typeof e=="object"?structuredClone(e):t}function gr(e){return typeof e!="string"||!Number.isFinite(Date.parse(e))?null:new Date(e).toISOString()===e?e:null}function wr(e){return!!(e&&Lo.has(e.evidence)&&gr(e.observedAt))}function Ar(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 Fe(e){return[...new Set(e.filter(Boolean))]}function _o(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]])!wr(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||!wr(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"),Ar(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=Fe(t);return o.length?Ae({status:Ce.BLOCK,whyBlocked:o}):r.length?Ae({status:Ce.UNKNOWN,whyBlocked:Fe(r)}):n.length?Ae({status:Ce.WARN,whyBlocked:[],warnings:Fe(n)}):Ae({status:Ce.PASS,whyBlocked:[]})}function Po(e={}){let t=G(e,{}),r=Object.fromEntries(Object.entries(t).map(([o,s])=>[o,gr(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 Sr(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("candidate must be an object");let t=G(e.chain,{}),r=G(e.token,{}),n=G(e.pool),o=G(e.venue,{}),s=G(e.signal,{}),i=G(e.route,{});i.cost=Ar(i.cost);let a=_o({...e,chain:t,token:r,pool:n,venue:o,signal:s,route:i}),c=s.unsolicitedAirdrop===!0,u=yr.test(r.address||"")?r.address.toLowerCase():"unknown-token",l=yr.test(n?.address||"")?n.address.toLowerCase():Ro.test(n?.poolId||"")?n.poolId.toLowerCase():"unknown-pool",d=`${Number.isInteger(t.id)?t.id:"unknown-chain"}:${u}:${l}:${o.key||"unknown-venue"}`;return Ae({id:d,status:a.status,chain:t,token:r,pool:n,venue:o,signal:s,risk:G(e.risk,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),sellability:G(e.sellability,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),sellSimulation:G(e.sellSimulation,{verdict:"UNKNOWN",evidence:"UNAVAILABLE",observedAt:null}),quoteAsset:e.quoteAsset??n?.quoteAsset??null,roundTripLossBps:e.roundTripLossBps??null,quoteAmountIn:e.quoteAmountIn??null,quoteSlippageBps:e.quoteSlippageBps??null,quoteAssetDecimals:e.quoteAssetDecimals??null,route:i,prepared:G(e.prepared,{status:"NOT_PREPARED",unsigned:!0}),whyBlocked:Fe([...e.whyBlocked||[],...a.whyBlocked]),latency:Po(e.latency),held:c?!1:e.held===!0,eligible:c?!1:a.status===Ce.PASS&&e.eligible!==!1})}function Er(e=[]){if(!Array.isArray(e))throw new TypeError("candidates must be an array");return Object.freeze(e.map(Sr).sort((t,r)=>t.id.localeCompare(r.id)))}import{AbiCoder as jo,keccak256 as Bo}from"ethers";var vr=/^0x[0-9a-fA-F]{40}$/,Q=/^0x[0-9a-fA-F]{64}$/,Uo=jo.defaultAbiCoder();function ce(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))ce(t);Object.freeze(e)}return e}function Or(e){return String(e?.message||e||"unknown scan failure").slice(0,300)}function ue(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 qo(e){if(!e||typeof e!="object")return"factory descriptor is invalid";if(!vr.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(!Q.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=>!vr.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 Te(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!Q.test(r||"")||!/^0{24}[0-9a-f]{40}$/i.test(r.slice(2))?null:`0x${r.slice(-40)}`.toLowerCase()}function Nr(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 Ir(e,t,r){let n=Nr(e,t);if(!Q.test(n||""))return null;let o=BigInt(n);return o<1n<<BigInt(r)?o:null}function xr(e,t,r){let n=Nr(e,t);if(!Q.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 Do(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()||!Q.test(e.topics[1]||"")||typeof e.data!="string"||e.data.length!==322)return null;let n=Te(e,{topic:2}),o=Te(e,{topic:3}),s=Ir(e,0,24),i=xr(e,1,24),a=Te(e,{dataWord:2}),c=Ir(e,3,160),u=xr(e,4,24),l=ue(e.blockNumber),d=ue(e.logIndex);if(!n||!o||s===null||i===null||!a||c===null||u===null||l===null||d===null||!Q.test(e.transactionHash||""))return null;let p=new Set(t.quoteAssets.map(x=>x.toLowerCase())),f=p.has(n),m=p.has(o);if(f===m)return null;let h=f?o:n,b=f?n:o;if(Bo(Uo.encode(["address","address","uint24","int24","address"],[n,o,Number(s),i,a])).toLowerCase()!==e.topics[1].toLowerCase())return null;let I=e.transactionHash.toLowerCase();return{id:`${t.chainId}:${I}:${d}`,chainId:t.chainId,factoryId:t.id||null,factoryAddress:t.factoryAddress.toLowerCase(),tokenAddress:h,quoteAsset:b,poolAddress:null,poolId:e.topics[1].toLowerCase(),poolKey:{currency0:n,currency1:o,fee:Number(s),tickSpacing:i,hooks:a},sqrtPriceX96:c.toString(),tick:u,venue:structuredClone(t.venue),kind:r.kind||"pool-initialized",blockNumber:l,blockHash:Q.test(e.blockHash||"")?e.blockHash.toLowerCase():null,transactionHash:I,logIndex:d,evidence:"LIVE"}}function $o(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=Te(e,r.layout.token),u=Te(e,r.layout.pool),l=ue(e.blockNumber),d=ue(e.logIndex);if(!c||!u||l===null||d===null||!Q.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:Q.test(e.blockHash||"")?e.blockHash.toLowerCase():null,transactionHash:p,logIndex:d,evidence:"LIVE"}}function Fo(e,t,r){return r.decoder==="uniswap-v4-initialize"?Do(e,t,r):$o(e,t,r)}async function kr(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=ue(e.fromBlock??e.cursor?.nextBlock),s=ue(e.toBlock);if(o===null||s===null||o<0||s<o)throw new TypeError("a valid integer block range is required");let i=ce({nextBlock:ue(e.cursor?.nextBlock)??o});if(n)return ce({status:"UNKNOWN",discoveries:[],unavailable:[],cursor:i,whyBlocked:["reorg hint requires canonical range reconciliation"]});let a=[],c=[];for(let d of r){let p=qo(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 ce({status:"UNAVAILABLE",discoveries:[],unavailable:a,cursor:i,whyBlocked:a.map(d=>d.reason)});let u=[];for(let d of c){let p=[...d.events].sort((h,b)=>h.topic0.localeCompare(b.topic0)),f=[...new Set(p.map(h=>h.topic0.toLowerCase()))].sort(),m;try{m=await t.scanBlocks({fromBlock:o,toBlock:s,address:d.factoryAddress,topics:[f]})}catch(h){return ce({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`scan failed: ${Or(h)}`]})}if(!m||m.complete!==!0||m.evidence&&m.evidence!=="LIVE"){let h=Array.isArray(m?.failedAt)?` at ${m.failedAt.join("-")}`:"";return ce({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`incomplete block range${h}${m?.error?`: ${Or(m.error)}`:""}`]})}for(let h of Array.isArray(m.logs)?m.logs:[]){let b=p.find(I=>I.topic0.toLowerCase()===String(h?.topics?.[0]||"").toLowerCase()),A=b&&Fo(h,d,b);A&&u.push(A)}}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 ce({status:"LIVE",discoveries:[...l.values()],unavailable:a,cursor:{nextBlock:s+1},whyBlocked:a.map(d=>d.reason)})}import{createHash as Mo}from"node:crypto";var Cr="sha256:"+"0".repeat(64);function pt(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))pt(t);Object.freeze(e)}return e}function dt(e){return Array.isArray(e)?`[${e.map(dt).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${dt(e[t])}`).join(",")}}`:JSON.stringify(e)}function Tr(e){return`sha256:${Mo("sha256").update(dt(e)).digest("hex")}`}function Lr(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 ft(e=[]){if(!Array.isArray(e))throw new TypeError("evidence records must be an array");let t=new Set,r=Cr,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=Lr(o,s+1,r),a=Tr(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 pt(n)}function mt(e=[],t){let r=ft(e);if(r.some(s=>s.id===t?.id))throw new Error(`duplicate evidence event id: ${t.id}`);let n=r.at(-1)?.digest??Cr,o=Lr(t,r.length+1,n);return pt([...r,{...o,digest:Tr(o)}])}var Rr=Object.freeze({ALERT_ONLY:"alert_only",EXECUTE:"execute"});function _r(e){return e?.mode==="shadow"?Rr.ALERT_ONLY:Rr.EXECUTE}function Me(e,t){return!!(e?.mode&&e.mode!=="shadow"&&t?.policyEligible===!0)}function Pr(e,t,r){return Me(e,t)&&r?.prepared===!0}var Ho="0x783cca1c0412dd0d695e784568c96da2e9c22ff989357a2e8b1d9b2b4e6b7118",Ga=Object.freeze([Object.freeze({topic0:Ho,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})})})]),Ja=Object.freeze({amountIn:"1000000000000000",quoteAssetDecimals:18,slippageBps:100,maxImpactPct:25,timeoutMs:4e3}),Ya=Object.freeze({amountIn:"1000000",quoteAssetDecimals:9,slippageBps:100,maxImpactPct:25,timeoutMs:12e3}),Qa=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 at from"node:fs";import Oa from"node:os";import se from"node:path";Se();var zr={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}},ws=new Map(Object.values(zr).map(e=>[e.chainId,e]));function Kr(e){return ws.get(Number(e))||null}function Wr(e,t=process.env){let r=Kr(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}import{Interface as gs,getAddress as As}from"ethers";var Gr=new gs(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Jr(e,t){try{return As(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}var Ss={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 Es(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=Wr(e,r);return n||Ss[Number(e)]||null}var vs=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Os(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!vs.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 Le=new Map,Yr=new Map;function Is(e){let t=new Error(e?.message||JSON.stringify(e));return t.code=e?.code,t}function xs(e){if(e?.error)throw Is(e.error);return e?.result}function Ns(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 ps(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,qr):Math.min(250*2**e,qr)+Math.floor(Math.random()*100)}function ne(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function Et(e,t,r){return ne(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function de(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function ms(e){return e?e.byteLength??e.length??0:0}async function hs(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&&(de(e),!n))throw Et(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 Et(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+=ms(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 Et(r,`streamed ${c} bytes`,t);let l=Buffer.concat(a);return(u?l.subarray(0,t):l).toString("utf8")}function bs(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function ys(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=ze}){let b=new AbortController,A=setTimeout(()=>b.abort(),s),I=f?Dr?Dr([f,b.signal]):f:b.signal,x=null,C=t,g=i?{lookupFn:i}:{};if(c&&!a&&!At(C))throw ne(`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 v=async(S,{status:k=null}={})=>{let O=await yt(S,g);if(!O.ok)throw ne(k==null?`HTTP refused ${S}: ${O.error}`:`HTTP redirect to ${S} ${O.error}`,k==null?{}:{status:k});let L=new URL(S).hostname;if(a){if(x&&(await x.close(),x=null),!x)try{x=await wt({requireUndici:!0,...d?{importUndici:d}:{}})}catch(y){throw ne(k==null?`HTTP refused ${S}: ${y?.message||y}`:`HTTP redirect to ${S} refused: ${y?.message||y}`,k==null?{}:{status:k})}x.pin(L,O.addresses),C=x.fetch}else jr(C,L,O.addresses);return O};try{let S=String(e),k=Object.assign(Object.create(null),n||{});c&&await v(S);for(let O=0;O<=h;O+=1){let L=Object.assign(Object.create(null),{method:r,headers:k,body:o,signal:I,redirect:"manual",dispatcher:void 0}),y=await C(S,L);if((m==="error"||h===0)&&y.status>=300&&y.status<400)throw de(y),ne(`HTTP ${y.status} ${r} redirect refused`,{status:y.status,redirectRefused:!0});if(rs.has(y.status)){let T=l===!0&&r==="POST"&&[307,308].includes(y.status)&&Hr(r,o);if(r!=="GET"&&r!=="HEAD"&&!T){de(y);let B=new Error(`HTTP ${y.status} ${r} ${S} redirected non-idempotent request`);throw B.status=y.status,B}if(O===h)throw de(y),ne(`HTTP ${y.status} ${r} redirect budget exhausted`,{status:y.status,redirectRefused:!0});let re=y.headers?.get?.("location"),V;try{V=as(re,S)}catch(B){throw de(y),B}let ie=!cs(V,S);if(de(y),ie&&r==="POST"){let B=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw B.status=y.status,B}if(ie&&l){let B=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw B.status=y.status,B.retryable=!1,B}if(ie&&(k=is(k)),c)await v(V,{status:y.status});else if(ie){let B=await yt(V,g);if(!B.ok){let _=new Error(`HTTP redirect from ${S} ${B.error}`);throw _.status=y.status,_.retryable=!1,_}a&&B.addresses?.length&&(x||(x=await wt(d?{importUndici:d}:{})),x&&(x.pin(new URL(V).hostname,B.addresses),C=x.fetch))}S=V;continue}if(typeof p=="function")try{await p(y,{url:S})}catch(T){throw de(y),ne(T?.message||String(T))}let F=await hs(y,u,{url:S,onOversize:()=>b.abort()}),w=bs(F);if(!y.ok){let T=new Error(`HTTP ${y.status} ${r} ${S}`);throw T.status=y.status,T.retryAfter=y.headers?.get?.("retry-after")??null,T.body=w??F.slice(0,300),T}return w??F}throw new Error(`HTTP redirect loop for ${e}`)}catch(S){if(b.signal.aborted&&!vt(f)){let k=S&&(typeof S=="object"||typeof S=="function")&&!Z.isProxy(S)?S: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 y=new Error("HTTP request timed out");throw Object.defineProperties(y,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),y}}throw S}finally{clearTimeout(A),x&&await x.close()}}async function ee(e,t={}){if(t!=null&&typeof t!="object"&&typeof t!="function")throw new TypeError("HTTP options must be an object");if(t!=null&&Z.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 _ of Object.getOwnPropertyNames(t)){let R=Object.getOwnPropertyDescriptor(t,_);if(!(_==="toJSON"&&R&&Object.hasOwn(R,"value")&&R.value===void 0)){if(!r.has(_))throw new TypeError("HTTP options contain unknown fields");if(!R||!R.enumerable||!Object.hasOwn(R,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=_=>{if(t==null||!Object.hasOwn(t,_))return;let R=Object.getOwnPropertyDescriptor(t,_);if(!R||!Object.hasOwn(R,"value"))throw new TypeError("HTTP options must contain own data properties");return R.value};if(typeof e!="string"||e.length===0||e.length>8192)throw new TypeError("HTTP URL must be a bounded string");let o=n("method");if(o!==void 0&&(typeof o!="string"||!/^[A-Za-z]+$/u.test(o)))throw new TypeError("HTTP method must be a string token");let s=n("timeoutMs");if(s!==void 0&&(!Number.isInteger(s)||s<1||s>12e4))throw new TypeError("HTTP timeoutMs must be a bounded integer");let i=n("retries");if(i!==void 0&&(!Number.isInteger(i)||i<0||i>10))throw new TypeError("HTTP retries must be a bounded integer");let a=n("redirectPolicy");if(a!==void 0&&a!=="follow"&&a!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let c=n("maxRedirects");if(c!==void 0&&(!Number.isInteger(c)||c<0||c>ze))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${ze}`);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??ze;for(let _ of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let R=n(_);if(R!==void 0&&typeof R!="boolean")throw new TypeError(`HTTP ${_} 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(Z.isProxy(p)||!(p instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{vt(p)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let _ of["importUndici","lookupFn","validateResponse"]){let R=n(_);if(R!==void 0&&typeof R!="function")throw new TypeError(`HTTP ${_} must be a function`)}let f=n("fetchImpl"),m=f||globalThis.fetch;if(typeof m!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let h=s??12e3,b=(o||"GET").toUpperCase(),A=n("headers"),I=ss(A),x=Object.assign(Object.create(null),I);Object.keys(x).some(_=>_.toLowerCase()==="accept")||(x.Accept="application/json");let C=n("body");C!=null&&typeof C!="string"&&(Object.keys(x).find(R=>R.toLowerCase()==="content-type")||(x["Content-Type"]="application/json"),C=os(C));let g=i??Yo,v=n("lookupFn"),S=!f,k=n("untrustedUrl")===!0,O=n("sameOriginRedirectsOnly")===!0,L=n("importUndici"),y=n("validateResponse"),F=p,w=d??null,T=async()=>{let _;for(let R=0;R<=g;R++){F&&Zo.call(F);try{return await ys(e,{fetchImpl:m,method:b,headers:x,body:C,timeoutMs:h,lookupFn:v,realFetch:S,untrustedUrl:k,maxResponseBytes:w,sameOriginRedirectsOnly:O,importUndici:L,validateResponse:y,signal:F,redirectPolicy:u,maxRedirects:l})}catch(ae){_=ae;let ge=ut=>{if(!ae||typeof ae!="object"&&typeof ae!="function"||Z.isProxy(ae))return;let ke=Object.getOwnPropertyDescriptor(ae,ut);return ke&&Object.hasOwn(ke,"value")?ke.value:void 0},ct=ge("status"),xo=ge("oracleTimeout")===!0||ge("name")==="AbortError"||ge("name")==="TimeoutError"||vt(F),No=new Set([408,425,429]),ko=ge("retryable")===!1?!1:ct!=null?No.has(ct)||Jo.has(ct)&&Ur.has(b):!xo&&Ur.has(b);if(R===g||!ko)throw ae;let br=ps(R,ge("retryAfter"));F?await new Promise((ut,ke)=>{let Co=setTimeout(ut,br);es.call(F,"abort",()=>{clearTimeout(Co),ke(ts(F)||new DOMException("Aborted","AbortError"))},{once:!0})}):await fs(br)}}throw _};if(!(n("dedupe")!==!1&&!F&&Hr(b,C)))return T();let V=ds(b,e,x,{untrustedUrl:k,maxResponseBytes:w,sameOriginRedirectsOnly:O,redirectPolicy:u,maxRedirects:l,timeoutMs:h,retries:g,fetchImpl:Ve(m),realFetch:S,lookupFn:Ve(v),importUndici:Ve(L),validateResponse:Ve(y)},C),ie=St.get(V);if(ie)return ie;let B=T().finally(()=>St.delete(V));return St.set(V,B),B}async function Vr(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 Jo,Ur,Yo,qr,Qo,Xo,Zo,es,Dr,vt,ts,rs,ze,ac,X,St,$r,Fr,us,ls,fs,Se=J(()=>{Br();Jo=new Set([408,425,429,500,502,503,504]),Ur=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Yo=2,qr=4e3,Qo=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Xo=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Zo=AbortSignal.prototype.throwIfAborted,es=EventTarget.prototype.addEventListener,Dr=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,vt=e=>e?Qo.call(e):!1,ts=e=>e?Xo.call(e):void 0,rs=new Set([301,302,303,307,308]),ze=3,ac=64*1024,X=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});St=new Map,$r=new WeakMap,Fr=1;us=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),ls=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);fs=e=>new Promise(t=>setTimeout(t,e))});import{types as Ut}from"node:util";function qt(e){if(!e||typeof e!="object"||Ut.isProxy(e)||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Je(e,t){if(e==null||(typeof e=="object"||typeof e=="function")&&Ut.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 Ge(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(Ut.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]=Ge(i.value,t,r+1)}return o}if(!qt(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]=Ge(s.value,t,r+1)}return n}var kn=J(()=>{});function ci(e={}){return String(e.rpcUrl||process.env.SOLANA_RPC_URL||ai).trim()}function Ee(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 Cn(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=Ge(await ee(ci(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(!qt(o))throw new Error(`solana-rpc ${e}: invalid response envelope`);let s=Je(o,"error");if(s)throw new Error(`solana-rpc ${e}: ${Je(s,"message")||JSON.stringify(s)}`);if(!Object.hasOwn(o,"result"))throw new Error(`solana-rpc ${e}: missing result`);return Je(o,"result")}var ai,Dt=J(()=>{Se();kn();ai="https://api.mainnet-beta.solana.com"});import{createHash as ui,createHmac as li,timingSafeEqual as Yc}from"node:crypto";function $t(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map($t).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${$t(e[r])}`).join(",")}}`}function Tn(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Ln(e=process.env){return Tn(process.env)||Tn(e)}function mi(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function hi(e){let t=mi(e);return ui("sha256").update($t(t)).digest("hex")}function bi(e,t=Ln()){return t?li("sha256",t).update(String(e)).digest("hex"):""}function Rn(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+pi:Number(s),l=u-c;if(!Number.isSafeInteger(c)||!Number.isSafeInteger(u)||l<=0||l>fi)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let p={...a,preparedAt:c,expiresAt:u,prepareVersion:di},f=hi(p),m=Ln(n),h=m?bi(f,m):void 0,b={...p,prepareHash:f};return h&&(b.prepareMac=h),b}var di,pi,fi,_n=J(()=>{di=2,pi=300*1e3,fi=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});function Ft(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function Ai(e){return yi.some(t=>e.startsWith(t))||wi.has(e)}function Si(e){let t=String(e);if(!/^[\x20-\x7e]+$/.test(t))return!0;let r=Ft(t);return Ai(r)?!1:gi.has(r)?!0:r.includes("signed")||r.includes("signature")||r.endsWith("sig")||r.endsWith("sigs")}function Ei(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 Mt(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=>Mt(c,t+1,r,n));let o=[];for(let[c,u]of Object.entries(e)){if(Si(c)){o.push(c);continue}o.push(...Mt(u,t+1,r,n))}let i=Object.keys(e).map(Ft).some(c=>c.endsWith("psbt")||c.endsWith("psbtbase64")),a=Object.entries(e).some(([c,u])=>/complete|finalized|isfinal/.test(Ft(c))&&u===!0);return i&&a&&o.push("psbt(complete)"),Ei(e)&&o.push("v/r/s"),o}function Pn(e,t){let r=Mt(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 yi,wi,gi,jn=J(()=>{yi=["unsigned","notsigned","tosign","signable"],wi=new Set(["requiresusersignature","requiressignature","needssignature","signaturerequired","signaturesrequired","signingready","signaturecount","signaturethreshold","requiredsignatures","signatureneeded","hassignature","allowsignatures","requestsignature","multisig","cosig","msig"]),gi=new Set(["sig","sigs","scriptsig","witness","psbt","finalizedpsbt","completepsbt","finalpsbt","psbtfinalized","serializedtransaction"])});var zt={};lt(zt,{JUPITER_MAX_SLIPPAGE_BPS:()=>qn,JUPITER_SWAP_API:()=>Be,SOL_MINT:()=>Xe,USDC_MINT:()=>Ht,jupiterHealth:()=>ki,jupiterPrepareSwap:()=>Ti,jupiterQuote:()=>Vt,jupiterSignerEnvelope:()=>Mn,jupiterVenues:()=>Ni,solanaGuard:()=>Qe});function Dn(e={}){return String(e.baseUrl||process.env.JUPITER_SWAP_API_URL||Be).replace(/\/$/,"")}function Ue(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 $n(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>qn)throw new Error("jupiter: slippage exceeds hard 100 bps cap");return t}function Ye(e,t){return e==null?t:!!e}function vi(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 Oi(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 Fn(e){let t=Buffer.from(e,"base64"),r=Oi(t,0);if(!r||r.value!==1)throw new Error("jupiter: unsigned swapTransaction must declare exactly one signature slot");let n=r.offset+r.value*64;if(n>=t.length)throw new Error("jupiter: Solana transaction missing message bytes");if(t.subarray(r.offset,n).some(s=>s!==0))throw new Error("jupiter: swapTransaction already contains signature material");return t.subarray(n).toString("base64")}function Qe(e={},{quotedAtMs:t=Date.now(),ttlMs:r=Bn}={}){let n=Ee(e.inputMint,"inputMint"),o=Ee(e.outputMint,"outputMint"),s=Ue(e.inAmount,"inAmount"),i=Ue(e.outAmount,"outAmount"),a=Ue(e.otherAmountThreshold??e.outAmount,"otherAmountThreshold"),c=$n(e.slippageBps??50),u=(BigInt(i)-BigInt(i)*BigInt(c)/10000n).toString();if(a!==u)throw new Error("jupiter: otherAmountThreshold does not match serialized min-out");return{mode:"solana-jupiter-quote",provider:"jupiter",venue:"jupiter-swap-v1",inputMint:n,outputMint:o,inAmount:s,outAmount:i,otherAmountThreshold:a,slippageBps:c,contextSlot:e.contextSlot??null,quotedAtMs:t,expiresAtMs:t+Math.min(Math.max(Number(r)||Bn,1e3),3e4)}}function Mn({userPublicKey:e,guard:t,swapTransaction:r,args:n={},response:o={}}){if(t.inputMint!==Xe)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=Fn(r),i=Ue(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 Un(e){if(typeof e!="string"||!e.length)return!1;let t=0n;for(let o of e){let s=xi.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 Ni(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(`${Be}/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])=>Un(p)),c=[],u=i.filter(([p])=>!Un(p)).map(([p,f])=>({programId:p,label:f,reason:"malformed program id"}));if(e.verify===!1)return{source:`${Be}/program-id-to-label`,verified:a.map(([p,f])=>({programId:p,label:f})),unresolved:u,verifiedOnChain:!1,totals:{fromRouterMap:i.length,verified:a.length}};let l=async p=>{let m=await(await n(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(p),signal:AbortSignal.timeout(Number(t.timeoutMs)||2e4)})).json();if(m.error)throw new Error(m.error.message);return m.result};for(let p=0;p<a.length;p+=90){let f=a.slice(p,p+90),m=null;for(let h=0;h<3&&!m;h++)try{m=await l({jsonrpc:"2.0",id:1,method:"getMultipleAccounts",params:[f.map(([b])=>b),{encoding:"base64",dataSlice:{offset:0,length:0}}]})}catch{await new Promise(b=>setTimeout(b,2e3*(h+1)))}if(!m){for(let[h,b]of f)u.push({programId:h,label:b,reason:"rpc batch failed after 3 attempts"});continue}m.value.forEach((h,b)=>{let[A,I]=f[b];h&&h.executable===!0&&Ii.has(h.owner)?c.push({programId:A,label:I,owner:h.owner}):u.push({programId:A,label:I,reason:h?h.executable!==!0?"not executable":`unknown owner ${h.owner}`:"account not found"})}),p+90<a.length&&await new Promise(h=>setTimeout(h,700))}let d=new Set(c.map(p=>p.label.replace(/\s+(CLMM|CP|V\d+|Launchlab|DLMM|Pools?)$/i,"").trim()));return{source:`${Be}/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 ki(e={}){try{return{ok:!0,provider:"jupiter",outAmount:(await Vt({inputMint:Xe,outputMint:Ht,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 Vt(e={},t={}){let r=Ee(e.inputMint||e.fromMint||Xe,"inputMint"),n=Ee(e.outputMint||e.toMint||Ht,"outputMint"),o=Ue(e.amount||e.inAmount,"amount"),s=$n(e.slippageBps??e.maxSlippageBps??50),i=new URL(`${Dn(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 ee(i.toString(),{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),c=Qe({...a,slippageBps:s},t);return{provider:"jupiter",chain:"solana-mainnet-beta",quoteReady:!0,executionReady:!1,inputMint:r,outputMint:n,amount:o,quote:a,solanaGuard:c}}function Ci(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function Ti(e={},t={}){let r=Ee(e.userPublicKey||e.owner||e.wallet,"userPublicKey"),n=e.quoteResponse?{quote:e.quoteResponse,solanaGuard:Qe(e.quoteResponse,t)}:await Vt(e,t),o=n.quote,s=n.solanaGuard||Qe(o,t);if(Ye(e.dynamicSlippage,!1)===!0)throw new Error("jupiter: dynamicSlippage would override the enforced slippage ceiling \u2014 pass an explicit slippageBps instead");let i=await ee(`${Dn(t)}/swap`,{method:"POST",body:Ci({quoteResponse:o,userPublicKey:r,wrapAndUnwrapSol:Ye(e.wrapAndUnwrapSol,!0),dynamicComputeUnitLimit:Ye(e.dynamicComputeUnitLimit,!0),dynamicSlippage:!1,asLegacyTransaction:Ye(e.asLegacyTransaction,!0),prioritizationFeeLamports:e.prioritizationFeeLamports??0}),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),a=vi(i?.swapTransaction);Fn(a),Pn("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=Mn({userPublicKey:r,guard:s,swapTransaction:a,args:e,response:i})}catch(f){p=String(f?.message||f).slice(0,200)}return Rn({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 Be,Xe,Ht,qn,Bn,Ii,xi,Kt=J(()=>{Se();Dt();_n();jn();Be="https://lite-api.jup.ag/swap/v1",Xe="So11111111111111111111111111111111111111112",Ht="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",qn=100,Bn=2e4;Ii=new Set(["BPFLoaderUpgradeab1e11111111111111111111111","BPFLoader2111111111111111111111111111111111","BPFLoader1111111111111111111111111111111111"]),xi="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});var zn={};lt(zn,{SELL_SIM:()=>U,assertSellable:()=>ji,simulateSell:()=>Vn});function _i(e,t){return t===0n?null:Number((t-e)*10000n/t)}function Pi(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 Vn(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=Pi(e.amountIn,"amountIn"),i;try{i=await t.quote({chainId:o,inputMint:n,outputMint:r,amount:s.toString(),side:"buy"})}catch(f){return Y(U.UNKNOWN,`buy leg could not be quoted: ${Wt(f)}`,{chainId:o,token:r,base:n})}let a=Hn(i?.outAmount);if(a==null||a===0n)return Y(U.UNKNOWN,"buy leg returned no output \u2014 no route or no liquidity",{chainId:o,token:r,base:n});let c;try{c=await t.quote({chainId:o,inputMint:r,outputMint:n,amount:a.toString(),side:"sell"})}catch(f){return Y(U.HONEYPOT,`buy routes but the SELL leg fails to quote (${Wt(f)}) \u2014 you would not be able to exit`,{chainId:o,token:r,base:n,tokensOut:a.toString()})}let u=Hn(c?.outAmount);if(u==null||u===0n)return Y(U.HONEYPOT,"sell leg returns zero \u2014 the position cannot be exited for value",{chainId:o,token:r,base:n,tokensOut:a.toString()});let l=_i(u,s),d={chainId:o,token:r,base:n,amountIn:s.toString(),tokensOut:a.toString(),roundTripOut:u.toString(),roundTripLossBps:l,evidence:"quote-only"},p=t.executionProven===!0?!0:null;if(typeof t.executionCheck=="function")try{let f=await t.executionCheck({chainId:o,token:r,base:n,tokensOut:a.toString(),amountIn:s.toString()});if(f?.executable===!1)return Y(U.HONEYPOT,`the sell reverts or returns false at execution (${f?.reason||"transfer-level block"}) even though it quotes cleanly \u2014 a honeypot a pool-math quote cannot see`,{...d,evidence:"execution",executable:!1});p=f?.executable===!0?!0:p}catch(f){d.executionCheckError=Wt(f)}return p===!0&&(d.evidence="execution"),l==null?Y(U.UNKNOWN,"could not compute round-trip loss",d):l>=Li?Y(U.HONEYPOT,`round trip loses ${(l/100).toFixed(1)}% \u2014 a sell tax or rigged curve, not normal slippage`,d):l>=Ri?Y(U.CAUTION,`round trip loses ${(l/100).toFixed(1)}% \u2014 high tax or thin liquidity`,d):p===!0?Y(U.SAFE,`round trip loses ${(l/100).toFixed(1)}% and the sell executes \u2014 exit path verified`,d):Y(U.CAUTION,`round trip quotes clean (${(l/100).toFixed(1)}% loss) but is unverified at execution \u2014 a pool-math quote cannot see a transfer-hook blacklist or transfer-only sell tax; run an execution-level sell simulation to clear SAFE`,d)}function Y(e,t,r){return{status:e,safe:e===U.SAFE,tradable:e===U.SAFE||e===U.CAUTION,reason:t,...r}}function Hn(e){if(e==null)return null;try{let t=String(e).trim();return/^\d+$/.test(t)?BigInt(t):null}catch{return null}}function Wt(e){return String(e?.message||e).slice(0,120)}async function ji(e={},t={}){let r=await Vn(e,t);if(!(r.status===U.SAFE||r.status===U.CAUTION&&t.allowCaution!==!1||r.status===U.UNKNOWN&&t.allowUnknown===!0)){let o=new Error(`sell-sim ${r.status}: ${r.reason}`);throw o.sellSim=r,o}return r}var U,Li,Ri,Kn=J(()=>{U=Object.freeze({SAFE:"SAFE",CAUTION:"CAUTION",HONEYPOT:"HONEYPOT",UNKNOWN:"UNKNOWN"}),Li=5e3,Ri=1500});import Ze from"node:fs";import Di from"node:os";import Oe from"node:path";import{fileURLToPath as $i}from"node:url";function Qn(){return process.env.ORACLE_FAKE_HOME||Di.homedir()}function Mi(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function et(){return Mi()?process.env.ORACLE_CONFIG_DIR||Oe.join(Qn(),".config","oracle"):Oe.join(Qn(),".config","oracle")}function Hi(){return Oe.join(et(),"desk.json")}function Vi(){return Oe.join(et(),"env")}function ve({force:e=!1}={}){if(ve._done&&!e)return ve._result||null;ve._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=Vi();if(Ze.existsSync(o))for(let s of Ze.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=Hi();if(Ze.existsSync(o)){let s=JSON.parse(Ze.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)),ve._result=Object.keys(t).length?t:null,ve._result}var Fi,cu,Xn=J(()=>{Fi=Oe.dirname($i(import.meta.url)),cu=Oe.resolve(Fi,"../..");try{ve()}catch{}});var to={};lt(to,{armPreparedAction:()=>Xi,callSigner:()=>Zn,queueOwnerAction:()=>eo});import{existsSync as zi,readFileSync as Ki}from"node:fs";import{request as Wi}from"node:http";import Gi from"node:path";function Yi(e=process.env){let t=String(e.ORACLE_SIGNER_URL||Ji).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 Qi(e=process.env){if(e.ORACLE_SIGNER_TOKEN)return String(e.ORACLE_SIGNER_TOKEN);let t=Gi.join(et(),"signer","signer-token");return zi(t)?Ki(t,"utf8").trim():null}function Zn(e,{method:t="GET",body:r=null,env:n=process.env,timeoutMs:o=4e3}={}){let s=Yi(n),i=Qi(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=Wi({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 eo(e,t=process.env){if(!e||e.version!==1||!e.surface)throw new Error("queueOwnerAction: version-1 surface envelope required");return Zn("/pending",{method:"POST",body:{artifact:e},env:t,timeoutMs:8e3})}async function Xi(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 eo(r,t)}var Ji,ro=J(()=>{Xn();Ji="http://127.0.0.1:9462"});var Ce=Object.freeze({PASS:"PASS",WARN:"WARN",BLOCK:"BLOCK",UNKNOWN:"UNKNOWN"}),Lo=new Set(["LIVE","CACHED","STALE","UNKNOWN","UNAVAILABLE"]),yr=/^0x[0-9a-fA-F]{40}$/,Ro=/^0x[0-9a-fA-F]{64}$/;function Ae(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Ae(t);Object.freeze(e)}return e}function G(e,t=null){return e&&typeof e=="object"?structuredClone(e):t}function gr(e){return typeof e!="string"||!Number.isFinite(Date.parse(e))?null:new Date(e).toISOString()===e?e:null}function wr(e){return!!(e&&Lo.has(e.evidence)&&gr(e.observedAt))}function Ar(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 Fe(e){return[...new Set(e.filter(Boolean))]}function _o(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]])!wr(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||!wr(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"),Ar(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=Fe(t);return o.length?Ae({status:Ce.BLOCK,whyBlocked:o}):r.length?Ae({status:Ce.UNKNOWN,whyBlocked:Fe(r)}):n.length?Ae({status:Ce.WARN,whyBlocked:[],warnings:Fe(n)}):Ae({status:Ce.PASS,whyBlocked:[]})}function Po(e={}){let t=G(e,{}),r=Object.fromEntries(Object.entries(t).map(([o,s])=>[o,gr(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 Sr(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("candidate must be an object");let t=G(e.chain,{}),r=G(e.token,{}),n=G(e.pool),o=G(e.venue,{}),s=G(e.signal,{}),i=G(e.route,{});i.cost=Ar(i.cost);let a=_o({...e,chain:t,token:r,pool:n,venue:o,signal:s,route:i}),c=s.unsolicitedAirdrop===!0,u=yr.test(r.address||"")?r.address.toLowerCase():"unknown-token",l=yr.test(n?.address||"")?n.address.toLowerCase():Ro.test(n?.poolId||"")?n.poolId.toLowerCase():"unknown-pool",d=`${Number.isInteger(t.id)?t.id:"unknown-chain"}:${u}:${l}:${o.key||"unknown-venue"}`;return Ae({id:d,status:a.status,chain:t,token:r,pool:n,venue:o,signal:s,risk:G(e.risk,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),sellability:G(e.sellability,{verdict:"UNKNOWN",evidence:"UNKNOWN",observedAt:null}),sellSimulation:G(e.sellSimulation,{verdict:"UNKNOWN",evidence:"UNAVAILABLE",observedAt:null}),quoteAsset:e.quoteAsset??n?.quoteAsset??null,roundTripLossBps:e.roundTripLossBps??null,quoteAmountIn:e.quoteAmountIn??null,quoteSlippageBps:e.quoteSlippageBps??null,quoteAssetDecimals:e.quoteAssetDecimals??null,route:i,prepared:G(e.prepared,{status:"NOT_PREPARED",unsigned:!0}),whyBlocked:Fe([...e.whyBlocked||[],...a.whyBlocked]),latency:Po(e.latency),held:c?!1:e.held===!0,eligible:c?!1:a.status===Ce.PASS&&e.eligible!==!1})}function Er(e=[]){if(!Array.isArray(e))throw new TypeError("candidates must be an array");return Object.freeze(e.map(Sr).sort((t,r)=>t.id.localeCompare(r.id)))}import{AbiCoder as jo,keccak256 as Bo}from"ethers";var vr=/^0x[0-9a-fA-F]{40}$/,Q=/^0x[0-9a-fA-F]{64}$/,Uo=jo.defaultAbiCoder();function ce(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))ce(t);Object.freeze(e)}return e}function Or(e){return String(e?.message||e||"unknown scan failure").slice(0,300)}function ue(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 qo(e){if(!e||typeof e!="object")return"factory descriptor is invalid";if(!vr.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(!Q.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=>!vr.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 Te(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!Q.test(r||"")||!/^0{24}[0-9a-f]{40}$/i.test(r.slice(2))?null:`0x${r.slice(-40)}`.toLowerCase()}function Nr(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 Ir(e,t,r){let n=Nr(e,t);if(!Q.test(n||""))return null;let o=BigInt(n);return o<1n<<BigInt(r)?o:null}function xr(e,t,r){let n=Nr(e,t);if(!Q.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 Do(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()||!Q.test(e.topics[1]||"")||typeof e.data!="string"||e.data.length!==322)return null;let n=Te(e,{topic:2}),o=Te(e,{topic:3}),s=Ir(e,0,24),i=xr(e,1,24),a=Te(e,{dataWord:2}),c=Ir(e,3,160),u=xr(e,4,24),l=ue(e.blockNumber),d=ue(e.logIndex);if(!n||!o||s===null||i===null||!a||c===null||u===null||l===null||d===null||!Q.test(e.transactionHash||""))return null;let p=new Set(t.quoteAssets.map(x=>x.toLowerCase())),f=p.has(n),m=p.has(o);if(f===m)return null;let h=f?o:n,b=f?n:o;if(Bo(Uo.encode(["address","address","uint24","int24","address"],[n,o,Number(s),i,a])).toLowerCase()!==e.topics[1].toLowerCase())return null;let I=e.transactionHash.toLowerCase();return{id:`${t.chainId}:${I}:${d}`,chainId:t.chainId,factoryId:t.id||null,factoryAddress:t.factoryAddress.toLowerCase(),tokenAddress:h,quoteAsset:b,poolAddress:null,poolId:e.topics[1].toLowerCase(),poolKey:{currency0:n,currency1:o,fee:Number(s),tickSpacing:i,hooks:a},sqrtPriceX96:c.toString(),tick:u,venue:structuredClone(t.venue),kind:r.kind||"pool-initialized",blockNumber:l,blockHash:Q.test(e.blockHash||"")?e.blockHash.toLowerCase():null,transactionHash:I,logIndex:d,evidence:"LIVE"}}function $o(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=Te(e,r.layout.token),u=Te(e,r.layout.pool),l=ue(e.blockNumber),d=ue(e.logIndex);if(!c||!u||l===null||d===null||!Q.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:Q.test(e.blockHash||"")?e.blockHash.toLowerCase():null,transactionHash:p,logIndex:d,evidence:"LIVE"}}function Fo(e,t,r){return r.decoder==="uniswap-v4-initialize"?Do(e,t,r):$o(e,t,r)}async function kr(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=ue(e.fromBlock??e.cursor?.nextBlock),s=ue(e.toBlock);if(o===null||s===null||o<0||s<o)throw new TypeError("a valid integer block range is required");let i=ce({nextBlock:ue(e.cursor?.nextBlock)??o});if(n)return ce({status:"UNKNOWN",discoveries:[],unavailable:[],cursor:i,whyBlocked:["reorg hint requires canonical range reconciliation"]});let a=[],c=[];for(let d of r){let p=qo(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 ce({status:"UNAVAILABLE",discoveries:[],unavailable:a,cursor:i,whyBlocked:a.map(d=>d.reason)});let u=[];for(let d of c){let p=[...d.events].sort((h,b)=>h.topic0.localeCompare(b.topic0)),f=[...new Set(p.map(h=>h.topic0.toLowerCase()))].sort(),m;try{m=await t.scanBlocks({fromBlock:o,toBlock:s,address:d.factoryAddress,topics:[f]})}catch(h){return ce({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`scan failed: ${Or(h)}`]})}if(!m||m.complete!==!0||m.evidence&&m.evidence!=="LIVE"){let h=Array.isArray(m?.failedAt)?` at ${m.failedAt.join("-")}`:"";return ce({status:"UNKNOWN",discoveries:[],unavailable:a,cursor:i,whyBlocked:[`incomplete block range${h}${m?.error?`: ${Or(m.error)}`:""}`]})}for(let h of Array.isArray(m.logs)?m.logs:[]){let b=p.find(I=>I.topic0.toLowerCase()===String(h?.topics?.[0]||"").toLowerCase()),A=b&&Fo(h,d,b);A&&u.push(A)}}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 ce({status:"LIVE",discoveries:[...l.values()],unavailable:a,cursor:{nextBlock:s+1},whyBlocked:a.map(d=>d.reason)})}import{createHash as Mo}from"node:crypto";var Cr="sha256:"+"0".repeat(64);function pt(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))pt(t);Object.freeze(e)}return e}function dt(e){return Array.isArray(e)?`[${e.map(dt).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${dt(e[t])}`).join(",")}}`:JSON.stringify(e)}function Tr(e){return`sha256:${Mo("sha256").update(dt(e)).digest("hex")}`}function Lr(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 ft(e=[]){if(!Array.isArray(e))throw new TypeError("evidence records must be an array");let t=new Set,r=Cr,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=Lr(o,s+1,r),a=Tr(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 pt(n)}function mt(e=[],t){let r=ft(e);if(r.some(s=>s.id===t?.id))throw new Error(`duplicate evidence event id: ${t.id}`);let n=r.at(-1)?.digest??Cr,o=Lr(t,r.length+1,n);return pt([...r,{...o,digest:Tr(o)}])}var Rr=Object.freeze({ALERT_ONLY:"alert_only",EXECUTE:"execute"});function _r(e){return e?.mode==="shadow"?Rr.ALERT_ONLY:Rr.EXECUTE}function Me(e,t){return!!(e?.mode&&e.mode!=="shadow"&&t?.policyEligible===!0)}function Pr(e,t,r){return Me(e,t)&&r?.prepared===!0}var Ho="0x783cca1c0412dd0d695e784568c96da2e9c22ff989357a2e8b1d9b2b4e6b7118",Ya=Object.freeze([Object.freeze({topic0:Ho,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})})})]),Qa=Object.freeze({amountIn:"1000000000000000",quoteAssetDecimals:18,slippageBps:100,maxImpactPct:25,timeoutMs:4e3}),Xa=Object.freeze({amountIn:"1000000",quoteAssetDecimals:9,slippageBps:100,maxImpactPct:25,timeoutMs:12e3}),Za=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 at from"node:fs";import xa from"node:os";import se from"node:path";Se();var zr={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}},ws=new Map(Object.values(zr).map(e=>[e.chainId,e]));function Kr(e){return ws.get(Number(e))||null}function Wr(e,t=process.env){let r=Kr(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}import{Interface as gs,getAddress as As}from"ethers";var Gr=new gs(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Jr(e,t){try{return As(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}var Ss={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 Es(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=Wr(e,r);return n||Ss[Number(e)]||null}var vs=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Os(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!vs.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 Le=new Map,Yr=new Map;function Is(e){let t=new Error(e?.message||JSON.stringify(e));return t.code=e?.code,t}function xs(e){if(e?.error)throw Is(e.error);return e?.result}function Ns(e,t,r){return`${e}
4
4
  ${t}
5
- ${JSON.stringify(r??[])}`}async function ks(e,t,r){return ee(e,{method:"POST",body:t,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function q(e,t,r=[],n={}){let o=String(t||""),s=Os(o),i=Es(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=Yr.get(i);if(l!=null)return l}let c=n.dedupe!==!1&&!n.signal?Ns(i,o,r):null;if(c&&Le.has(c))return Le.get(c);let u=(async()=>{let l=await ks(i,{jsonrpc:"2.0",id:1,method:t,params:r},n),d=xs(l);return s==="eth_chainid"&&typeof d=="string"&&Yr.set(i,d),d})();return c&&(Le.set(c,u),u.finally(()=>{Le.get(c)===u&&Le.delete(c)}).catch(()=>{})),u}async function Qr(e,t={}){let r=await q(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function Xr(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await q(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function Zr(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=Jr(e.token||e.tokenAddress,"token"),o=Jr(e.account||e.owner||e.address,"account"),s=Gr.encodeFunctionData("balanceOf",[o]),i=await q(r,"eth_call",[{to:n,data:s},e.blockTag||"latest"],t),a=Gr.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"}}Se();var Cs=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"]);function en(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 Ot(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=en(o,c),d=String(l.address||"").toLowerCase(),p=String(l.symbol||"").toLowerCase(),f=Number(c.liquidityUsd??c.liquidity?.usd),m=Number.isFinite(f)?f:0,h=String(c.dex||c.dexId||"").toLowerCase(),b=0;return s.has(d)||Cs.has(p)?b=300:i&&d===i&&(b=100),h.includes("v4")?b+=20:h.includes("v3")?b+=10:(h.includes("v2")||h.includes("raydium")||h.includes("orca")||h.includes("meteora"))&&(b+=8),{pool:c,score:b*1e12+m,index:u,otherAddr:d,liquidityUsd:m}});return a.sort((c,u)=>u.score-c.score||c.index-u.index),a.map(c=>c.pool)}function tn(e,t=[]){let r=Array.isArray(t)?t:[];return r.length&&en(e,r[0]).address||null}var Ts="https://api.dexscreener.com",bc=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function Ls(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||Ts).replace(/\/$/,"")}async function rn(e,t={}){if(!e)throw new Error("tokenAddress required");return ee(`${Ls(t)}/latest/dex/tokens/${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}Se();var Ke=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),N=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),E=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),Rs=/^0x[0-9a-fA-F]{40}$/;function _s(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}Rs.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))Ke.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 Ps(e){let{ok:t,errors:r,warnings:n}=_s(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
5
+ ${JSON.stringify(r??[])}`}async function ks(e,t,r){return ee(e,{method:"POST",body:t,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function q(e,t,r=[],n={}){let o=String(t||""),s=Os(o),i=Es(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=Yr.get(i);if(l!=null)return l}let c=n.dedupe!==!1&&!n.signal?Ns(i,o,r):null;if(c&&Le.has(c))return Le.get(c);let u=(async()=>{let l=await ks(i,{jsonrpc:"2.0",id:1,method:t,params:r},n),d=xs(l);return s==="eth_chainid"&&typeof d=="string"&&Yr.set(i,d),d})();return c&&(Le.set(c,u),u.finally(()=>{Le.get(c)===u&&Le.delete(c)}).catch(()=>{})),u}async function Qr(e,t={}){let r=await q(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function Xr(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await q(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function Zr(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=Jr(e.token||e.tokenAddress,"token"),o=Jr(e.account||e.owner||e.address,"account"),s=Gr.encodeFunctionData("balanceOf",[o]),i=await q(r,"eth_call",[{to:n,data:s},e.blockTag||"latest"],t),a=Gr.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"}}Se();var Cs=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"]);function en(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 Ot(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=en(o,c),d=String(l.address||"").toLowerCase(),p=String(l.symbol||"").toLowerCase(),f=Number(c.liquidityUsd??c.liquidity?.usd),m=Number.isFinite(f)?f:0,h=String(c.dex||c.dexId||"").toLowerCase(),b=0;return s.has(d)||Cs.has(p)?b=300:i&&d===i&&(b=100),h.includes("v4")?b+=20:h.includes("v3")?b+=10:(h.includes("v2")||h.includes("raydium")||h.includes("orca")||h.includes("meteora"))&&(b+=8),{pool:c,score:b*1e12+m,index:u,otherAddr:d,liquidityUsd:m}});return a.sort((c,u)=>u.score-c.score||c.index-u.index),a.map(c=>c.pool)}function tn(e,t=[]){let r=Array.isArray(t)?t:[];return r.length&&en(e,r[0]).address||null}var Ts="https://api.dexscreener.com",wc=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function Ls(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||Ts).replace(/\/$/,"")}function Rs(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 _s(e,t){return ee(`${Ls(t)}${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}async function rn(e,t={}){return _s(`/latest/dex/tokens/${Rs(e,"tokenAddress")}`,t)}Se();var Ke=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),N=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),E=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),Ps=/^0x[0-9a-fA-F]{40}$/;function js(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}Ps.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))Ke.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 Bs(e){let{ok:t,errors:r,warnings:n}=js(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
6
6
  - ${r.join(`
7
- - `)}`);let o=e.capabilities||{},s=Ke.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:Ke.filter(a=>!s.includes(a))}},supports(a){return s.includes(a)}};for(let a of Ke)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 nn=new Map;function on(e){let t=Ps(e);return nn.set(t.chainId,t),t}function sn(e){return nn.get(Number(e))||null}var xt={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},K=e=>BigInt(e).toString(16).padStart(64,"0"),Re=e=>e.slice(2).toLowerCase().padStart(64,"0");function js(e,t){return`0x${xt.getAmountsOut}`+K(e)+K(64)+K(t.length)+t.map(Re).join("")}function Bs(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 It(e,t="router"){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}var Nt=100;function Us(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Nt)throw new Error(`slippageBps ${r} exceeds the ${Nt} 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 an(e){let{chainId:t,wrappedNative:r}=e;async function n(o,s,i,a){let c=await q(t,"eth_call",[{to:o,data:js(s,i)},"latest"],a);return Bs(c?.result??c)}return{async quote({tokenIn:o,tokenOut:s,amountIn:i,path:a},c={}){let u=It(c.scanner);if(!u)return{chainId:t,evidence:N.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let l=a||[o,s];if(l.some(p=>!/^0x[0-9a-fA-F]{40}$/.test(p||"")))throw new Error("quote requires valid 20-byte addresses");let d=await n(u,i,l,c);return d?{chainId:t,router:u,path:l,amountIn:String(i),amountOut:d[d.length-1].toString(),hops:l.length-1,evidence:N.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:u,path:l,evidence:N.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:o,amountIn:s,base:i},a={}){let c=It(a.scanner),u=i||r;if(u&&String(o).toLowerCase()===String(u).toLowerCase())return{chainId:t,token:o,verdict:E.UNKNOWN,evidence:N.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!c||!u)return{chainId:t,token:o,verdict:E.UNKNOWN,evidence:N.UNAVAILABLE,reason:c?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let l=await n(c,s,[u,o],a);if(!l)return{chainId:t,token:o,verdict:E.FAIL,evidence:N.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let d=l[l.length-1];if(d===0n)return{chainId:t,token:o,verdict:E.FAIL,evidence:N.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let p=await n(c,d,[o,u],a);if(!p)return{chainId:t,token:o,verdict:E.FAIL,evidence:N.LIVE,leg:"sell",bought:d.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let f=p[p.length-1],m=Number(f*10000n/BigInt(s)),h=E.PASS,b="round trip completes with expected fee/impact loss";return m<5e3?(h=E.FAIL,b=`round trip returns only ${(m/100).toFixed(2)}% -- punitive tax or no real liquidity`):m<9e3&&(h=E.CAUTION,b=`round trip returns ${(m/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:o,base:u,router:c,verdict:h,reason:b,amountIn:String(s),bought:d.toString(),returned:f.toString(),retentionBps:m,evidence:N.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:s,amountIn:i,recipient:a,slippageBps:c=50,deadlineSeconds:u=900,path:l},d={}){let p=d.scanner,f=It(p);if(!f)throw new Error(`chain ${t} has no verified router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!/^0x[0-9a-fA-F]{40}$/.test(a||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let m=l||[o,s],h=await this.quote({tokenIn:o,tokenOut:s,amountIn:i,path:m},d);if(h.evidence!==N.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let b=Us(h.amountOut,c);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let A=BigInt(Math.floor(Date.now()/1e3)+Number(u)),I=r&&m[0].toLowerCase()===r.toLowerCase()&&d.useNative,x=I?`0x${xt.swapExactETHForTokens}`+K(b)+K(128)+Re(a)+K(A)+K(m.length)+m.map(Re).join(""):`0x${xt.swapExactTokensForTokens}`+K(i)+K(b)+K(160)+Re(a)+K(A)+K(m.length)+m.map(Re).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:f,data:x,value:I?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:h.amountOut,minOut:b.toString(),slippageBps:c,maxSlippageBps:Nt,deadline:A.toString()},requires:I?[]:[{step:"approve",token:m[0],spender:f,amount:String(i)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var qs=[100,500,3e3,1e4],cn={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},pe=e=>BigInt(e).toString(16).padStart(64,"0"),_e=e=>e.slice(2).toLowerCase().padStart(64,"0"),un=/^0x[0-9a-fA-F]{40}$/,Ct=100;function Ds(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Ct)throw new Error(`slippageBps ${r} exceeds the ${Ct} 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 kt(e,t){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function ln(e){let{chainId:t,wrappedNative:r}=e;async function n({quoter:s,tokenIn:i,tokenOut:a,amountIn:c,fee:u},l){let d=`0x${cn.quoteExactInputSingle}`+_e(i)+_e(a)+pe(c)+pe(u)+pe(0),p=await q(t,"eth_call",[{to:s,data:d},"latest"],l).catch(()=>null),f=p?.result??p;if(!f||f==="0x"||f.length<66)return null;let m=BigInt(`0x${f.slice(2,66)}`);return m>0n?m:null}async function o({quoter:s,tokenIn:i,tokenOut:a,amountIn:c},u){let l=await Promise.all(qs.map(async p=>{let f=await n({quoter:s,tokenIn:i,tokenOut:a,amountIn:c,fee:p},u);return{fee:p,amountOut:f?f.toString():null,out:f}})),d=null;for(let p of l)p.out&&(!d||p.out>d.amountOut)&&(d={fee:p.fee,amountOut:p.out});return{best:d,tried:l.map(({fee:p,amountOut:f})=>({fee:p,amountOut:f}))}}return{async quote({tokenIn:s,tokenOut:i,amountIn:a},c={}){let u=kt(c.scanner,"quoter");if(!u)return{chainId:t,evidence:N.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let p of[s,i])if(!un.test(p||""))throw new Error("quote requires valid 20-byte addresses");let{best:l,tried:d}=await o({quoter:u,tokenIn:s,tokenOut:i,amountIn:a},c);return l?{chainId:t,venue:"uniswap-v3",quoter:u,tokenIn:s,tokenOut:i,amountIn:String(a),amountOut:l.amountOut.toString(),fee:l.fee,useNative:!!r&&String(s).toLowerCase()===String(r).toLowerCase(),triedFeeTiers:d,evidence:N.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:u,tokenIn:s,tokenOut:i,triedFeeTiers:d,evidence:N.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:s,amountIn:i,base:a},c={}){let u=kt(c.scanner,"quoter"),l=(e.stableQuoteAssets||[]).map(g=>String(g).toLowerCase()),d=null;!a&&typeof e.resolveQuoteAsset=="function"&&(d=await e.resolveQuoteAsset(s,c).catch(()=>null));let p=String(s).toLowerCase(),f=String(r||"").toLowerCase();if(f&&p===f)return{chainId:t,token:s,verdict:E.UNKNOWN,evidence:N.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};let m=a||d||(l[0]&&p!==l[0]?l[0]:null)||r;if(m&&p===String(m).toLowerCase())return{chainId:t,token:s,verdict:E.UNKNOWN,evidence:N.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!u||!m)return{chainId:t,token:s,verdict:E.UNKNOWN,evidence:N.UNAVAILABLE,reason:u?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let h=await o({quoter:u,tokenIn:m,tokenOut:s,amountIn:i},c);if(!h.best){let g=l.find(v=>v&&v!==String(m).toLowerCase()&&v!==String(s).toLowerCase());if(g){let v=await o({quoter:u,tokenIn:g,tokenOut:s,amountIn:i},c);if(v.best){let S=await o({quoter:u,tokenIn:s,tokenOut:g,amountIn:v.best.amountOut},c);if(S.best){let k=S.best.amountOut,O=Number(k*10000n/BigInt(i)),L=E.PASS,y="round trip vs dollar book completes with expected fee/impact loss";return O<5e3?(L=E.FAIL,y=`round trip vs dollar book returns only ${(O/100).toFixed(2)}% -- punitive tax or no real liquidity`):O<9e3&&(L=E.CAUTION,y=`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:g,quoteAsset:g,verdict:L,reason:y,amountIn:String(i),bought:v.best.amountOut.toString(),returned:k.toString(),retentionBps:O,buyFee:v.best.fee,sellFee:S.best.fee,evidence:N.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:t,token:s,verdict:E.FAIL,evidence:N.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let b=await o({quoter:u,tokenIn:s,tokenOut:m,amountIn:h.best.amountOut},c);if(!b.best){let g=l.find(v=>v&&v!==String(m).toLowerCase()&&v!==String(s).toLowerCase());if(g){let v=await o({quoter:u,tokenIn:g,tokenOut:s,amountIn:i},c),S=v.best?await o({quoter:u,tokenIn:s,tokenOut:g,amountIn:v.best.amountOut},c):{best:null};if(v.best&&S.best){let k=S.best.amountOut,O=Number(k*10000n/BigInt(i)),L=E.PASS,y="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return O<5e3?(L=E.FAIL,y=`dollar-book round trip returns only ${(O/100).toFixed(2)}%`):O<9e3&&(L=E.CAUTION,y=`dollar-book round trip returns ${(O/100).toFixed(2)}%`),{chainId:t,venue:"uniswap-v3",token:s,base:g,quoteAsset:g,verdict:L,reason:y,amountIn:String(i),bought:v.best.amountOut.toString(),returned:k.toString(),retentionBps:O,buyFee:v.best.fee,sellFee:S.best.fee,evidence:N.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:t,token:s,verdict:E.FAIL,evidence:N.LIVE,leg:"sell",bought:h.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let A=b.best.amountOut,I=Number(A*10000n/BigInt(i)),x=E.PASS,C="round trip completes with expected fee/impact loss";return I<5e3?(x=E.FAIL,C=`round trip returns only ${(I/100).toFixed(2)}% -- punitive tax or no real liquidity`):I<9e3&&(x=E.CAUTION,C=`round trip returns ${(I/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:s,base:m,verdict:x,reason:C,amountIn:String(i),bought:h.best.amountOut.toString(),returned:A.toString(),retentionBps:I,buyFee:h.best.fee,sellFee:b.best.fee,evidence:N.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:s,tokenOut:i,amountIn:a,recipient:c,slippageBps:u=50,fee:l},d={}){let p=kt(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(!un.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=await this.quote({tokenIn:s,tokenOut:i,amountIn:a},d);if(f.evidence!==N.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let m=l??f.fee,h=Ds(f.amountOut,u);if(h<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=!!(d.useNative||f.useNative)&&r&&String(s).toLowerCase()===String(r).toLowerCase(),A=`0x${cn.exactInputSingle}`+_e(s)+_e(i)+pe(m)+_e(c)+pe(a)+pe(h)+pe(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:p,data:A,value:b?String(a):"0x0"},guard:{quotedOut:f.amountOut,minOut:h.toString(),slippageBps:u,maxSlippageBps:Ct,fee:m},requires:b?[]:[{step:"approve",token:s,spender:p,amount:String(a)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var We={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function dn(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function pn(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 $s(e){let{chainId:t}=e;async function r(n,o,s){return q(t,"eth_call",[{to:n,data:o},"latest"],s)}return{async blockNumber(n={}){let o=await Qr(t,n);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:N.LIVE}},async nativeBalance(n,o={}){let s=await Xr(t,n,o);return{chainId:t,address:n,wei:s?.wei??s?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:N.LIVE}},async tokenBalance({token:n,owner:o},s={}){let i=await Zr({chainId:t,token:n,owner:o},s);return{chainId:t,token:n,owner:o,raw:i?.balance??i,evidence:N.LIVE}},async resolveToken(n,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:t,token:n,evidence:N.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[s,i,a,c]=await Promise.all([r(n,We.decimals,o).catch(()=>null),r(n,We.symbol,o).catch(()=>null),r(n,We.name,o).catch(()=>null),r(n,We.totalSupply,o).catch(()=>null)]),u=dn(s?.result??s),l=u!==null||i?.result||a?.result,d={chainId:t,address:n,decimals:u===null?null:Number(u),symbol:pn(i?.result??i),name:pn(a?.result??a),totalSupply:(dn(c?.result??c)??null)?.toString()??null,evidence:l?N.LIVE:N.UNKNOWN};return l||(d.warning="no ERC-20 metadata returned -- may not be a token contract"),d},async resolvePools(n,o={}){let s=e.dexscreenerSlug;if(!s)return{chainId:t,token:n,pools:[],evidence:N.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await rn(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=Ot(n,c,{stables:e.stableQuoteAssets||[],wrappedNative:e.wrappedNative});return{chainId:t,token:n,pools:u,topPool:u[0]||null,quoteAsset:tn(n,u),evidence:u.length?N.LIVE:N.UNKNOWN}},async scanBlocks({fromBlock:n,toBlock:o,address:s,topics:i,chunkSize:a=2e3}={},c={}){if(!Number.isInteger(n)||!Number.isInteger(o))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(o<n)throw new Error("toBlock must be >= fromBlock");let u=[],l=[];for(let p=n;p<=o;p+=a){let f=Math.min(p+a-1,o);l.push([p,f])}let d=await Vr(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 q(t,"eth_getLogs",[m],c).catch(b=>({error:String(b?.message||b)}));return{start:p,end:f,res:h}});for(let{start:p,end:f,res:m}of d){if(m?.error)return{chainId:t,fromBlock:n,toBlock:o,logs:u,complete:!1,failedAt:[p,f],error:m.error,evidence:N.UNKNOWN};for(let h of m?.result??m??[])u.push(h)}return{chainId:t,fromBlock:n,toBlock:o,logs:u,complete:!0,chunks:l.length,evidence:N.LIVE}},async scoreRisk(n,o={}){let s=[],i=E.PASS,a=l=>{let d={[E.PASS]:0,[E.CAUTION]:1,[E.UNKNOWN]:2,[E.FAIL]:3};d[l]>d[i]&&(i=l)},[c,u]=await Promise.all([this.resolveToken(n,o),this.resolvePools(n,o)]);if(c.evidence!==N.LIVE?(s.push({check:"erc20-metadata",result:E.UNKNOWN,detail:c.warning}),a(E.UNKNOWN)):s.push({check:"erc20-metadata",result:E.PASS,detail:`${c.symbol} / ${c.decimals}d`}),u.evidence===N.UNAVAILABLE)s.push({check:"liquidity",result:E.UNKNOWN,detail:u.reason}),a(E.UNKNOWN);else if(!u.pools.length)s.push({check:"liquidity",result:E.FAIL,detail:"no pool with liquidity found"}),a(E.FAIL);else{let l=u.pools[0],d=l.liquidityUsd??0;d<5e3?(s.push({check:"liquidity",result:E.CAUTION,detail:`top pool only $${d}`}),a(E.CAUTION)):s.push({check:"liquidity",result:E.PASS,detail:`$${d} on ${l.dex}`}),l.createdAt&&Date.now()-l.createdAt<24*3600*1e3&&(s.push({check:"age",result:E.CAUTION,detail:"pool under 24h old"}),a(E.CAUTION))}if(typeof this.sellSimulation=="function"){let l=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},o).catch(d=>({verdict:E.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:E.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(E.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 fn(e){let r={...$s(e)},n=new Set((e.venues||[]).map(s=>s.kind));e.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,ln({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,an({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 Fs=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 mn(){return Fs.map(e=>on(fn(e)))}import{AbiCoder as Ms,Interface as gn,getAddress as me,isAddress as An,keccak256 as Hs}from"ethers";var Tt="0x0000000000000000000000000000000000000000",Vs="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",zs=Ms.defaultAbiCoder(),hn=new gn(["function quoteExactInputSingle((address tokenIn,address tokenOut,uint256 amountIn,uint24 fee,uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut,uint160 sqrtPriceX96After,uint32 initializedTicksCrossed,uint256 gasEstimate)"]),bn=new gn(["function quoteExactInputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountOut,uint256 gasEstimate)"]),W=Object.freeze({1:Object.freeze({quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"}),10:Object.freeze({quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrappedNative:"0x4200000000000000000000000000000000000006"}),56:Object.freeze({quoter:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"}),137:Object.freeze({quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270"}),8453:Object.freeze({quoter:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",wrappedNative:"0x4200000000000000000000000000000000000006"}),42161:Object.freeze({quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"}),43114:Object.freeze({quoter:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7"}),4663:Object.freeze({quoter:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73"}),988:Object.freeze({quoter:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5"}),999:Object.freeze({quoter:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",wrappedNative:"0x5555555555555555555555555555555555555555"}),2741:Object.freeze({quoter:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809"})}),je=Object.freeze({1:Object.freeze({quoter:"0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203",wrappedNative:W[1].wrappedNative}),10:Object.freeze({quoter:"0x1f3131a13296fb91c90870043742c3cdbff1a8d7",wrappedNative:W[10].wrappedNative}),56:Object.freeze({quoter:"0x9f75dd27d6664c475b90e105573e550ff69437b0",wrappedNative:W[56].wrappedNative}),137:Object.freeze({quoter:"0xb3d5c3dfc3a7aebff71895a7191796bffc2c81b9",wrappedNative:W[137].wrappedNative}),8453:Object.freeze({quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",wrappedNative:W[8453].wrappedNative}),42161:Object.freeze({quoter:"0x3972c00f7ed4885e145823eb7c655375d275a1c5",wrappedNative:W[42161].wrappedNative}),43114:Object.freeze({quoter:"0xbe40675bb704506a3c2ccfb762dcfd1e979845c2",wrappedNative:W[43114].wrappedNative}),4663:Object.freeze({quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",wrappedNative:W[4663].wrappedNative})}),Ks=Object.freeze([100,500,3e3,1e4]);function fe(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 Sn(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 En(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 Lt(e){let t=String(e??"").trim().toLowerCase();return t===""||t==="eth"||t===Tt||t===Vs}function Pe(e,t){if(!An(String(e??"")))throw new Error(`${t} must be an EVM address`);return me(String(e))}function yn(e,t,r){return Lt(e)?me(t.wrappedNative):Pe(e,r)}function wn(e,t){return Lt(e)?me(Tt):Pe(e,t)}function vn(e,t){let r=Number(e);if(!Number.isInteger(r)||r<0||r>16777215)throw new Error(`${t} must be uint24`);return r}function Ws(e,t){let r=Number(e);if(!Number.isInteger(r)||r<-8388608||r>8388607)throw new Error(`${t} must be int24`);return r}function Gs({tokenIn:e,tokenOut:t,poolKey:r,poolId:n}){fe(r,new Set(["currency0","currency1","fee","tickSpacing","hooks"]),"V4 PoolKey");let o=Pe(r.currency0,"V4 currency0"),s=Pe(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:vn(r.fee,"V4 fee"),tickSpacing:Ws(r.tickSpacing,"V4 tickSpacing"),hooks:Pe(r.hooks??Tt,"V4 hooks")}),a=wn(e,"tokenIn"),c=wn(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=Hs(zs.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 Rt(e,t){if(Lt(t))return!0;if(!An(String(t??"")))return!1;let r=W[Number(e)]?.wrappedNative||je[Number(e)]?.wrappedNative;return!!(r&&me(String(t)).toLowerCase()===me(r).toLowerCase())}async function On(e={},t={},r={}){fe(e,new Set(["chainId","tokenIn","tokenOut","amountIn","fee"]),"V3 read"),fe(t,new Set(["timeoutMs"]),"V3 read options"),fe(r,new Set(["rpc"]),"V3 read dependencies");let n=Number(e.chainId),o=W[n];if(!o)throw new Error(`V3 read unavailable on chain ${e.chainId}`);let s=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=Sn(e.amountIn,"amountIn"),c=e.fee==null?Ks:[vn(e.fee,"V3 fee")],u=r.rpc||q,l=En(t.timeoutMs),d=await Promise.all(c.map(async f=>{let m=hn.encodeFunctionData("quoteExactInputSingle",[{tokenIn:s,tokenOut:i,amountIn:a,fee:f,sqrtPriceLimitX96:0n}]);try{let h=await u(n,"eth_call",[{to:o.quoter,data:m},"latest"],l);if(!h||h==="0x")throw new Error("empty result");let b=hn.decodeFunctionResult("quoteExactInputSingle",h);return Object.freeze({ok:!0,fee:f,amountOut:b[0].toString(),gasEstimate:b[3].toString()})}catch(h){return Object.freeze({ok:!1,fee:f,error:String(h?.message||h).slice(0,160)})}})),p=d.filter(f=>f.ok).sort((f,m)=>BigInt(m.amountOut)>BigInt(f.amountOut)?1:-1)[0];if(!p)throw new Error(`V3 read failed chain=${n}: ${d.map(f=>`${f.fee}:${f.error}`).join("; ")}`);return Object.freeze({venue:"uniswap-v3",chainId:n,quoter:me(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 In(e={},t={},r={}){fe(e,new Set(["chainId","tokenIn","tokenOut","amountIn","poolKey","poolId"]),"V4 read"),fe(t,new Set(["timeoutMs"]),"V4 read options"),fe(r,new Set(["rpc"]),"V4 read dependencies");let n=Number(e.chainId),o=je[n];if(!o)throw new Error(`V4 read unavailable on chain ${e.chainId}`);let s=Sn(e.amountIn,"amountIn");if(s>0xffffffffffffffffffffffffffffffffn)throw new Error("amountIn exceeds uint128");let i=Gs(e),a=bn.encodeFunctionData("quoteExactInputSingle",[{poolKey:i.poolKey,zeroForOne:i.zeroForOne,exactAmount:s,hookData:"0x"}]),u=await(r.rpc||q)(n,"eth_call",[{to:o.quoter,data:a},"latest"],En(t.timeoutMs));if(!u||u==="0x")throw new Error("V4 read returned an empty result");let l=bn.decodeFunctionResult("quoteExactInputSingle",u);return Object.freeze({venue:"uniswap-v4",chainId:n,quoter:me(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 Js=new Set(["chainId","tokenIn","tokenOut","amountIn","v4PoolKey","v4PoolId"]),Ys=new Set(["maxImpactPct","timeoutMs"]),Qs=new Set(["quoteV3","quoteV4","gasPrice"]);function _t(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 jt(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 xn(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 te(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 Xs(e){if(e<=1n)return null;let t=e/1000n;return t>0n&&t<e?t:1n}function Zs({amountIn:e,amountOut:t,probeIn:r,probeOut:n}){let o=te(e),s=te(t),i=te(r),a=te(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 Pt(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 ei({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,amountOut:o,gasEstimate:s,gasPrice:i}){let a=te(s),c=te(i),u=te(n),l=te(o);if(!a||!c||!u||!l||a<=0n||c<=0n)return null;let d=a*c;return Rt(e,r)?d:Rt(e,t)?d*l/u:null}async function ti(e,t){let r=await q(e,"eth_gasPrice",[],{timeoutMs:t});return te(r)}function ri(e,t){return Object.freeze({source:e,quality:"FAILED",amountOut:null,error:String(t?.message||t).slice(0,240)})}async function Nn({source:e,amountIn:t,timeoutMs:r,fullRead:n,probeRead:o}){try{let s=await Pt(n,r,e),i=jt(s?.amountOut,`${e} amountOut`),a=Xs(t);if(a==null)return{source:e,full:s,impactPct:null};try{let c=await Pt(()=>o(a.toString(),s),r,`${e} impact probe`),u=Zs({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 ni({inspected:e,params:t,gasPrice:r}){let n=e.full,o=jt(n.amountOut,`${e.source} amountOut`),s=ei({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 oi({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 Bt(e={},t={},r={}){_t(e,Js,"route params"),_t(t,Ys,"route options"),_t(r,Qs,"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=jt(e.amountIn,"amountIn"),s=xn(t.timeoutMs,12e3,250,6e4,"timeoutMs"),i=xn(t.maxImpactPct,25,0,100,"maxImpactPct"),a=r.quoteV3||On,c=r.quoteV4||In,u=r.gasPrice||ti,l=[];W[n]&&l.push(Nn({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&&je[n]&&l.push(Nn({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=Pt(()=>u(n,s),s,"gas price read").catch(()=>null),m=await Promise.all(l),h=await f,b=m.filter(w=>w.error).map(w=>ri(w.source,w.error)),A=m.filter(w=>w.full),I=A.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`})),x=new Set(I.map(w=>w.source)),C=A.filter(w=>!x.has(w.source)),g=C.map(w=>ni({inspected:w,params:{...e,chainId:n},gasPrice:h})),v=g.length>0&&g.every(w=>w.costAccounted),S=v?"net":"gross";for(let w of g){let T=BigInt(w.grossOut),re=v?BigInt(w.costInDest):0n;w.netOut=(T>re?T-re:0n).toString()}g.sort((w,T)=>{let re=BigInt(v?w.netOut:w.grossOut),V=BigInt(v?T.netOut:T.grossOut);return re===V?w.source.localeCompare(T.source):V>re?1:-1});let k=[];v?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=C.filter(w=>w.impactPct==null).map(w=>w.source);O.length&&k.push(`Price impact is UNKNOWN for: ${O.join(", ")}.`),I.length&&k.push(`Dropped on price impact: ${I.map(w=>w.source).join(", ")}.`),!d&&je[n]&&k.push("V4 was not queried because no exact verified PoolKey identity was discovered.");let L=null,y=null;if(g.length>1){let w=BigInt(v?g[0].netOut:g[0].grossOut),T=BigInt(v?g[1].netOut:g[1].grossOut);T>0n&&(L=Number((w-T)*10000000n/T)/1e3,y=`${g[0].source} vs ${g[1].source}`)}let F=Object.fromEntries(C.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:g[0]||null,routes:Object.freeze(g.map(w=>Object.freeze(w))),failed:Object.freeze(b),rankedOn:S,sourcesTried:l.length,sourcesAnswered:A.length,improvementBps:L,spreadBasis:y,priceImpact:Object.freeze(F),impactRejected:Object.freeze(I),impactUnmeasured:Object.freeze(O),warnings:Object.freeze(k),note:oi({routes:g,rankedOn:S,improvementBps:L})})}var he="So11111111111111111111111111111111111111112";var Pi=new Set(["chainId","tokenIn","tokenOut","amountIn"]),ji=new Set(["maxImpactPct","timeoutMs","quoteFn"]);function Wn(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 Gn(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 Jn(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 Bi(e,t={}){let{jupiterQuote:r}=await Promise.resolve().then(()=>(Kt(),zt)),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 Gt(e={},t={}){if(Wn(e,Pi,"params"),Wn(t,ji,"options"),e.chainId!=null&&Number(e.chainId)!==101)throw new Error("solana quote adapter only handles chainId 101");let r=Jn(e.tokenIn,"tokenIn"),n=Jn(e.tokenOut,"tokenOut"),o=Gn(e.amountIn,"amountIn");if(r===n)throw new Error("solana quote tokenIn and tokenOut must differ");let s=t.quoteFn||Bi;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=Gn(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 Yn({routeFn:e=Gt}={}){return Object.freeze({async sellSimulation({token:t,amountIn:r,base:n}={}){let{simulateSell:o,SELL_SIM:s}=await Promise.resolve().then(()=>(Kn(),zn)),i=await o({token:t,base:n||he,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 Qi(e){return e?.token?.address||e?.tokenAddress||null}function Xi(e){return e?.quoteAsset||e?.pool?.quoteAsset||null}function Zi(e,t){return e?.quoteAmountIn||e?.quote?.amountIn||null}async function Yt({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=Qi(e),o=Xi(e),s=Zi(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(()=>(Kt(),zt)),u=await c({userPublicKey:t.recipient,inputMint:o==="unknown"?he: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 Qt({prepared:e}={},t=process.env){if(e?.prepared!==!0)return{ok:!1,error:"nothing prepared"};let{armPreparedAction:r}=await Promise.resolve().then(()=>(ro(),to)),n=e.localSignerEnvelope||e.envelope;return n?r({localSignerEnvelope:n},t):{ok:!1,error:"prepared envelope missing"}}import{createHash as aa}from"node:crypto";import{createHash as ea}from"node:crypto";var M=Object.freeze({SHADOW:"shadow",ARMED:"armed",AUTONOMOUS:"autonomous"}),ta=3,ra=new Set(Object.values(M));function tr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))tr(t);Object.freeze(e)}return e}function er(e){return Array.isArray(e)?`[${e.map(er).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${er(e[t])}`).join(",")}}`:JSON.stringify(e)}function na(e){return`sha256:${ea("sha256").update(er(e)).digest("hex")}`}function Xt(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 oa(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new TypeError(`${t} entries must be positive safe integers`);return e}function Zt(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 Ie(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 qe(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 rt(e,t){let r=Ie(e,t),[n,o=""]=r.split(".");return{digits:BigInt(n+o),scale:o.length}}function tt(e,t,r="value"){let n=rt(e,r),o=rt(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 no(e){let t=structuredClone(e);return delete t.digest,t}function sa(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");return na(no(e))}function rr(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");let t=e.mode??M.SHADOW;if(!ra.has(t))throw new TypeError("mode must be shadow, armed, or autonomous");let r={version:1,mode:t,chains:Xt(e.chains,"chains",oa),venues:Xt(e.venues,"venues",Zt),quoteAssets:Xt(e.quoteAssets,"quoteAssets",Zt),maxSpendPerTrade:Ie(e.maxSpendPerTrade,"maxSpendPerTrade",{positive:!0}),maxSpendPerDay:Ie(e.maxSpendPerDay,"maxSpendPerDay",{positive:!0}),minLiquidityUsd:Ie(e.minLiquidityUsd,"minLiquidityUsd",{positive:!0}),maxSlippageBps:qe(e.maxSlippageBps,"maxSlippageBps",{max:1e4}),maxGas:Ie(e.maxGas,"maxGas",{positive:!0}),maxPriorityFee:Ie(e.maxPriorityFee,"maxPriorityFee"),maxBuysPerHour:qe(e.maxBuysPerHour,"maxBuysPerHour",{min:1}),retryCeiling:qe(e.retryCeiling,"retryCeiling",{max:ta}),ttlMs:qe(e.ttlMs,"ttlMs",{min:1}),requireSellSimulation:e.requireSellSimulation,requireRiskPass:e.requireRiskPass??!0,maxRoundTripLossBps:qe(e.maxRoundTripLossBps??1500,"maxRoundTripLossBps",{max:1e4}),killSwitch:e.killSwitch,recipient:e.recipient==null||e.recipient===""?null:Zt(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(tt(r.maxSpendPerTrade,r.maxSpendPerDay)>0)throw new TypeError("maxSpendPerTrade cannot exceed maxSpendPerDay");return r.digest=sa(r),tr(r)}var ia=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 nr(e,t={},r={}){let n=rr(no(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,tt(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=rt(t.spentToday,"daily spend"),c=rt(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,tt(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,tt(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 ia)j(i,t.autonomousGates?.[a]!==!0,c);return j(i,n.mode!==M.AUTONOMOUS,"strategy mode is not autonomous"),tr({strategyDigest:n.digest,mode:n.mode,policyEligible:o.length===0,blockers:o,autonomousEligible:i.length===0,autonomousBlockers:i,reportOnly:!0})}function ao(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))ao(t);Object.freeze(e)}return e}var oo=Object.freeze({ALERT_ONLY:"alert_only",EXECUTE:"execute"}),so=Object.freeze({liveQuote:20,sellSimulation:30,contractRisk:20,liquidity:15,roundTripLoss:15});function z(e,t){return{id:e,verdict:"PASS",detail:t}}function H(e,t){return{id:e,verdict:"BLOCK",detail:t}}function io(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function co({strategy:e,observation:t={},evaluation:r={}}={}){if(!e||typeof e!="object")throw new TypeError("snipe features require a strategy");let n=[],o=[],s=(h,b)=>{n.push(h),h.verdict==="BLOCK"&&o.push(b)};s(e.killSwitch===!0?H("killSwitch","engaged"):z("killSwitch","off"),"kill switch is engaged"),s(e.chains.includes(t.chain)?z("chain",String(t.chain)):H("chain",String(t.chain??"missing")),"chain is not on the exact allowlist"),s(e.venues.includes(t.venue)?z("venue",String(t.venue)):H("venue",String(t.venue??"missing")),"venue is not on the exact allowlist"),s(e.quoteAssets.includes(t.quoteAsset)?z("quoteAsset",String(t.quoteAsset)):H("quoteAsset",String(t.quoteAsset??"missing")),"quote asset is not on the exact allowlist");let i=r.quote?.evidence||t.quoteEvidence;s(i==="LIVE"?z("liveQuote","LIVE"):H("liveQuote",String(i||"missing")),"live quote is missing");let a=t.sellSimulation||r.sellSimulation;s(a?.verdict==="PASS"&&a?.evidence==="LIVE"?z("sellSimulation","LIVE PASS"):H("sellSimulation",`${a?.verdict||"missing"}/${a?.evidence||"missing"}`),"mandatory sell simulation has no LIVE PASS evidence");let c=t.riskVerdict||r.risk?.verdict;s(e.requireRiskPass===!0&&c==="PASS"?z("contractRisk","PASS"):H("contractRisk",String(c||"missing")),"contract risk is not PASS");let u=t.liquidityUsd;try{let h=Number(u),b=Number(e.minLiquidityUsd);s(Number.isFinite(h)&&Number.isFinite(b)&&h>=b?z("liquidity",String(u)):H("liquidity",String(u??"missing")),"minimum real liquidity is not met")}catch{s(H("liquidity","unknown"),"liquidity evidence is missing or unknown")}let l=io(t.slippageBps);s(l!=null&&l<=e.maxSlippageBps?z("slippage",String(l)):H("slippage",String(t.slippageBps??"missing")),"slippage exceeds cap or is unknown");let d=io(t.roundTripLossBps);s(d!=null&&d<=e.maxRoundTripLossBps?z("roundTripLoss",String(d)):H("roundTripLoss",String(t.roundTripLossBps??"missing")),"round-trip loss exceeds cap or is unknown"),s(Number.isSafeInteger(t.retries)&&t.retries<=e.retryCeiling?z("retryCeiling",String(t.retries)):H("retryCeiling",String(t.retries??"missing")),"retry ceiling is exceeded or unknown"),s(Number.isFinite(t.ageMs)&&t.ageMs>=0&&t.ageMs<e.ttlMs?z("ttl",String(t.ageMs)):H("ttl",String(t.ageMs??"missing")),"TTL has expired or is unknown"),s(typeof t.fireId=="string"&&t.fireId.length>0&&Array.isArray(t.firedIds)&&!t.firedIds.includes(t.fireId)?z("duplicateFire",t.fireId):H("duplicateFire","missing or duplicate"),"duplicate fire is blocked or fire id is unknown");let p=0;for(let h of n)h.verdict==="PASS"&&so[h.id]&&(p+=so[h.id]);let f=o.length===0,m=e.mode==="shadow"?oo.ALERT_ONLY:oo.EXECUTE;return ao({snipeReady:f,wouldSnipe:f,armed:!1,actionMode:m,score:p,features:n,blockers:o,reportOnly:e.mode==="shadow"})}function nt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function or(e){return Array.isArray(e)?`[${e.map(or).join(",")}]`:nt(e)?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${or(e[t])}`).join(",")}}`:JSON.stringify(e)}function ca(e){return`cycle:${aa("sha256").update(or(e)).digest("hex")}`}function De(e,t){if(typeof e!="function")throw new TypeError(`launch-radar runner: injected ${t} function is required`)}function uo(e){return e instanceof Error?e.message:String(e)}function sr(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(!nt(r))throw new TypeError("launch-radar runner: strategy is required");De(n,"discovery"),De(o,"evaluate");let s=e.now??(()=>new Date().toISOString()),i=e.sleep??(()=>Promise.resolve()),a=e.jitter??(()=>0);De(s,"clock"),De(i,"sleep"),De(a,"jitter");let c=Math.min(3,Math.max(0,Number.isSafeInteger(e.retries)?e.retries:r.retryCeiling)),u=Math.max(0,Number.isFinite(e.baseBackoffMs)?e.baseBackoffMs:100),l=Math.max(u,Number.isFinite(e.maxBackoffMs)?e.maxBackoffMs:2e3);async function d(m){let h;for(let b=0;b<=c;b+=1)try{return await m(b)}catch(A){if(h=A,b===c)break;let I=Number(a()),x=Number.isFinite(I)?Math.max(0,I):0,C=Math.min(l,u*2**b+x);await i(C)}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=_r(r);if(m.strategyStatus.ambiguous)return{mode:r.mode,status:"blocked",blockers:["ambiguous state requires reconciliation"],results:[],actionMode:h};if(Array.isArray(m.evidence)&&m.evidence.length>0&&m.strategyStatus.mode!==r.mode)return{mode:r.mode,status:"blocked",blockers:["persisted mode does not match configured strategy"],results:[],actionMode:h};if(r.killSwitch)return{mode:r.mode,status:"blocked",blockers:["kill switch is engaged"],results:[],actionMode:h};let b;try{b=await d(g=>n({cursor:structuredClone(m.cursor),attempt:g,mode:r.mode}))}catch(g){return{mode:r.mode,status:"failed",blockers:[uo(g)],results:[],actionMode:h}}if(!nt(b)||!Array.isArray(b.candidates)||!(b.cursor===null||nt(b.cursor)))return{mode:r.mode,status:"failed",blockers:["discovery returned an invalid deterministic result"],results:[],actionMode:h};let A=[];for(let g of b.candidates)try{let v=await d(y=>o(structuredClone(g),{attempt:y,mode:r.mode})),S=nr(r,v,{}),k=co({strategy:r,observation:v,evaluation:g}),O={prepared:!1},L=!1;Me(r,S)&&typeof e.prepareFn=="function"?O=await e.prepareFn({candidate:g,observation:v,strategy:r,policy:S})||{prepared:!1}:Me(r,S)&&(O={prepared:!1,blockedReasons:["prepareFn is required when strategy mode is not shadow"]}),Pr(r,S,O)&&typeof e.queueFn=="function"&&(L=(await e.queueFn({prepared:O,candidate:g,observation:v,strategy:r,policy:S}))?.ok===!0),A.push({id:g?.id??null,policy:S,snipe:k,prepared:O.prepared===!0,queued:L,actionMode:h})}catch(v){A.push({id:g?.id??null,policy:{mode:r.mode,policyEligible:!1,reportOnly:r.mode===M.SHADOW,blockers:[`evaluation failed: ${uo(v)}`]},actionMode:h,prepared:!1,queued:!1})}let I={cursor:b.cursor,candidates:b.candidates,results:A},x={id:ca(I),type:r.mode===M.SHADOW?"shadow-cycle":"execute-cycle",at:s(),data:I},C=t.commitCycle({candidates:b.candidates,cursor:b.cursor,strategyStatus:{mode:r.mode,status:"inert",ambiguous:!1},event:x});return{mode:r.mode,status:C.duplicate?"duplicate":"completed",results:A,evidenceId:C.evidence.id,actionMode:h}}return Object.freeze({status:p,runCycle:f})}function lo(e){return[...new Set(e.filter(Boolean).map(String))]}function be(e){return Array.isArray(e)?e.map(be):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,be(r)])):e}function oe(e,t,r="UNKNOWN"){return!e||typeof e!="object"?{evidence:r,observedAt:t}:be({...structuredClone(e),evidence:e.evidence||r,observedAt:e.observedAt||t})}function ua(e,t){let r=String(t||"").toLowerCase();return!!(r&&[e?.address,e?.pair,e?.poolId].some(n=>String(n||"").toLowerCase()===r))}function la(e,t){let r=e.poolId||e.poolAddress||null,n=[t.topPool,...t.pools?.pools||[]].filter(Boolean),o=r?n.find(i=>ua(i,r)):t.topPool,s={address:e.poolAddress??null,poolId:e.poolId,poolKey:e.poolKey,quoteAsset:e.quoteAsset};return be({...o||{},...s})}function da(e,t,r,n){let o=e.observedAt||n,s=la(e,t),i=oe(t.scannerRisk||t.risk,o),a=oe(t.sellability,o,"UNAVAILABLE"),c=oe(t.quote,o,"UNAVAILABLE"),u=c.evidence==="LIVE"?"PASS":"UNKNOWN";return be({chain:{id:e.chainId,...t.chain||{}},token:oe({address:e.tokenAddress,...t.token||{}},o,"LIVE"),pool:oe(s,o,"LIVE"),venue:oe({...e.venue,supported:e.venue?.supported===!0,verified:e.venue?.verified===!0},o,"LIVE"),signal:oe({kind:e.kind,source:"verified-factory",unsolicitedAirdrop:!1},o,"LIVE"),risk:i,sellability:a,sellSimulation:oe(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:be({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:lo([...r||[],...t.blockedReasons||[],t.error]),latency:{discoveredAt:o,riskCompletedAt:i.observedAt,sellabilityCompletedAt:a.observedAt,routeCompletedAt:c.observedAt,normalizedAt:n}})}async function ot(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:be(structuredClone(a)),prepare:e.prepare===!0})}catch(u){c={error:`evaluation unavailable: ${String(u?.message||u).slice(0,300)}`}}i.push(da(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(lo(n?.whyBlocked||[])),candidates:Er(i)})}var pa=101,po=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/,fa="181ec828051c0777",ma="6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P";function xe(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))xe(t);Object.freeze(e)}return e}function ha(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!==ma)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 ba(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(fa))continue;let c=Array.isArray(i.accounts)?i.accounts:[],u=c[0],l=c[2];return!po.test(u||"")||!po.test(l||"")?null:{id:`solana:${r}:${s}`,chain:"solana",chainId:pa,factoryId:t.id||null,factoryAddress:t.programId,tokenAddress:u,quoteAsset:he,poolAddress:l,venue:structuredClone(t.venue),kind:"token-launched",slot:n,signature:r,instructionIndex:s,evidence:"LIVE"}}return null}async function fo(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=ha(u);l?n.push({id:u?.id||null,status:"UNAVAILABLE",reason:l}):o.push(u)}let s=xe({until:e.cursor?.until||null});if(o.length===0)return xe({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 xe({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 xe({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=ba({...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 xe({status:"LIVE",discoveries:[...c.values()],unavailable:n,cursor:{until:a},whyBlocked:n.map(u=>u.reason)})}Dt();var ya="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function wa(e){let t=String(e||"");if(!t)return Buffer.alloc(0);let r=[0];for(let o of t){let s=ya.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 ga(e){return typeof e=="string"?e:e?.pubkey||null}function Aa(e){let t=e?.transaction?.message||{},r=Array.isArray(t.accountKeys)?t.accountKeys.map(ga):[],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=wa(i.data).toString("hex")),a&&s.push({programId:a,accounts:c,dataHex:u})}return s}function mo(e={}){let t=e.solanaRpc||Cn;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:Aa(n)}:{signature:r,slot:null,instructions:[]}}}}import $ from"node:fs";import st from"node:path";var ur=1,Sa=0;function we(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function D(e){return structuredClone(e)}function ar(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)=>ar(r,`${t}[${n}]`));if(we(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}`);ar(n,`${t}.${r}`)}return}throw new Error(`launch-radar store: non-JSON value at ${t}`)}}function ye(e){return Array.isArray(e)?`[${e.map(ye).join(",")}]`:we(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${ye(e[t])}`).join(",")}}`:JSON.stringify(e)}function Ea(){return{version:ur,candidates:[],cursor:null,strategyStatus:{mode:"shadow",status:"inert",ambiguous:!1},evidence:[]}}function va(e){if(!we(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 $e(e){if(!we(e)||e.version!==ur)throw new Error("launch-radar store: corrupt or unsupported version");if(!Array.isArray(e.candidates)||!(e.cursor===null||we(e.cursor))||!Array.isArray(e.evidence))throw new Error("launch-radar store: corrupt state shape");va(e.strategyStatus),ar(e);try{ft(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=$.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 cr(e){it(e);let t;try{t=JSON.parse($.readFileSync(e,"utf8"))}catch{throw new Error("launch-radar store: corrupt JSON")}return $e(t)}function ir(e,t){let r=$e(t),n=st.dirname(e);$.mkdirSync(n,{recursive:!0,mode:448});let o=$.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=st.join(n,`.launch-radar.${process.pid}.${Sa+=1}.tmp`),i;try{i=$.openSync(s,"wx",384),$.writeFileSync(i,`${ye(r)}
8
- `,"utf8"),$.fsyncSync(i),$.closeSync(i),i=void 0,$.renameSync(s,e),$.chmodSync(e,384);let a=$.openSync(n,"r");try{$.fsyncSync(a)}finally{$.closeSync(a)}}catch(a){i!==void 0&&$.closeSync(i);try{$.unlinkSync(s)}catch{}throw a}}function lr(e={}){let t=e.path;if(typeof t!="string"||!st.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");it(t,!0)?cr(t):ir(t,Ea());let r=()=>cr(t),n=(o,{reconciliation:s=!1}={})=>{if(r().strategyStatus.ambiguous&&!s)throw new Error("launch-radar store: ambiguous state is terminal until reconciliation");return ir(t,o),D(o)};return Object.freeze({path:t,read:r,replaceState(o={}){if(!we(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($e(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&&ye(i.data)===ye(o?.data))return D(i);throw new Error(`launch-radar store: duplicate evidence conflict: ${o?.id}`)}let a=mt(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&&ye(u.data)===ye(a?.data))return{duplicate:!0,evidence:D(u),state:c};throw new Error(`launch-radar store: duplicate evidence conflict: ${a?.id}`)}let l=mt(c.evidence,a),d=$e({...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 ir(t,{...s,strategyStatus:i}),D(i)},reconcile(o={}){if(!we(o))throw new TypeError("launch-radar store: reconciliation state must be an object");let s=r(),i=$e({...s,...D(o),version:ur,evidence:s.evidence});if(i.strategyStatus.ambiguous)throw new Error("launch-radar store: reconciliation must clear ambiguous state");return n(i,{reconciliation:!0})}})}function ho(e={}){let t=e.path;if(typeof t!="string"||!st.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");return cr(t)}function pr(e){return e.ORACLE_CONFIG_DIR||se.join(Oa.homedir(),".config","oracle")}function bo(e,t){if(!e||!se.isAbsolute(e))throw new Error(`${t} path must be absolute`);let r=at.lstatSync(e);if(r.isSymbolicLink()||!r.isFile())throw new Error(`${t} must be a regular non-symlink file`);if(r.size>1024*1024)throw new Error(`${t} exceeds 1 MiB`);return JSON.parse(at.readFileSync(e,"utf8"))}function Ia(e){return e==null?null:String(e)}function Ne(e){if(e!==void 0)return typeof e=="bigint"?e.toString():Array.isArray(e)?e.map(Ne).filter(t=>t!==void 0):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,Ne(r)])):e}function So(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 dr(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 xa(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 Na(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:So(t.amountIn,"routeProbe.amountIn"),quoteAssetDecimals:dr(t.quoteAssetDecimals,0,255,"routeProbe.quoteAssetDecimals"),slippageBps:dr(t.slippageBps??100,0,1e4,"routeProbe.slippageBps"),maxImpactPct:xa(t.maxImpactPct??25,0,100,"routeProbe.maxImpactPct"),timeoutMs:dr(t.timeoutMs??12e3,250,6e4,"routeProbe.timeoutMs")})}function yo(e){return[e?.source,e?.amountOut,e?.netOut,e?.meta?.poolId].map(t=>String(t??"").toLowerCase()).join(":")}function wo(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 ka(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 go(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 Ao(e){if(!e?.best||!So(e.best.amountOut,"best route amountOut"))throw new Error("best route returned no positive output");let t=Array.isArray(e.routes)?e.routes:[],r=yo(e.best),n=t.findIndex(a=>yo(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."),Ne({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 Ca(e,t){return{quote:{evidence:"UNAVAILABLE",reason:e,observedAt:t},sellability:{verdict:"UNKNOWN",evidence:"UNAVAILABLE",reason:e,observedAt:t}}}async function Eo({scanner:e,discovery:t,descriptor:r,routeFn:n=Bt,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=Na(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:Ne(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);go(d,t,"buy");let p=Ao(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);go(f,t,"reverse");let m=Ao(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=ka(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=Ne({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,Ca(c,o))}return Ne(s)}function vo(e){let t=e.quoteAsset||e.pool?.quoteAsset||e.token?.quoteAsset||"unknown",r=wo(e.quoteAmountIn,e.quoteAssetDecimals??18)||wo(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:Ia(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=bo(t.ORACLE_LAUNCH_RADAR_STRATEGY_FILE,"strategy file"),n=bo(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=rr(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 Ta({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");mn();let a=sn(i[0]);if(!a)throw new Error(`no scanner registered for chain ${i[0]}`);let c=t.ORACLE_LAUNCH_RADAR_STORE_PATH||se.join(pr(t),"launch-radar",`state-${i[0]}.json`),u=lr({path:c});return sr({store:u,strategy:s,discover:async({cursor:p})=>{let f=await a.blockNumber(),m=Number(f?.blockNumber??f);if(!Number.isSafeInteger(m))throw new Error("scanner did not return a safe integer head block");let h=Number.isSafeInteger(p?.nextBlock)?p.nextBlock:Math.max(0,m-10),b=await ot({discover:()=>kr({scanner:a,factories:o,fromBlock:h,toBlock:m,cursor:p}),evaluator:async({discovery:A})=>{let I=o.find(x=>x?.id===A?.factoryId||String(x?.factoryAddress||"").toLowerCase()===String(A?.factoryAddress||"").toLowerCase());return Eo({scanner:a,discovery:A,descriptor:I,routeFn:e.routeFn||Bt,observedAt:new Date().toISOString()})},observedAt:new Date().toISOString()});return{candidates:b.candidates,cursor:b.cursor}},evaluate:async p=>vo(p),prepareFn:e.prepareFn||(p=>Yt({...p,scanner:a})),queueFn:e.queueFn||(p=>Qt(p,t))})}function Ta({env:e,factories:t,strategy:r,options:n}){let o=n.solanaScanner||mo(),s=n.solanaRouteFn||Gt,i=n.solanaQuoteScanner||Yn({routeFn:s}),a=e.ORACLE_LAUNCH_RADAR_STORE_PATH||se.join(pr(e),"launch-radar","state-solana.json"),c=lr({path:a});return sr({store:c,strategy:r,discover:async({cursor:l})=>{let d=await ot({discover:()=>fo({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 Eo({scanner:i,discovery:{...p,quoteAsset:p.quoteAsset||he},descriptor:f,routeFn:s,observedAt:new Date().toISOString()})},observedAt:new Date().toISOString()});return{candidates:d.candidates,cursor:d.cursor}},evaluate:async l=>vo(l),prepareFn:n.prepareFn||(l=>Yt({...l,scanner:i})),queueFn:n.queueFn||(l=>Qt(l,e))})}async function Oo(e={}){let t=e.env||process.env,r=t.ORACLE_LAUNCH_RADAR_FACTORIES_DIR;if(!r||!se.isAbsolute(r))throw new Error("ORACLE_LAUNCH_RADAR_FACTORIES_DIR must be an absolute directory");let n=at.lstatSync(r);if(n.isSymbolicLink()||!n.isDirectory())throw new Error("factories dir must be a regular directory");let o=at.readdirSync(r).filter(i=>i.endsWith(".json")).sort();if(o.length===0)throw new Error("factories dir contains no json manifests");let s=[];for(let i of o){let a=i.endsWith(".json")?i.slice(0,-5):i,c={...t,ORACLE_LAUNCH_RADAR_FACTORIES_FILE:se.join(r,i),ORACLE_LAUNCH_RADAR_STORE_PATH:se.join(t.ORACLE_LAUNCH_RADAR_STORE_DIR||se.join(pr(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 La=Object.freeze({OK:"ok",DEGRADED:"degraded",UNKNOWN:"unknown"}),Gu=Object.freeze({fresh:0,stale:1,down:2});var Yu=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 Ra from"node:os";import Io from"node:path";var _a="oracle.launch-radar.data-plane.v1";function Pa(e){return String(e?.message||e||"unknown error").slice(0,300)}function ja(e={}){return e.configDir||process.env.ORACLE_CONFIG_DIR||Io.join(Ra.homedir(),".config","oracle")}function Ba(e={}){return e.storePath||process.env.LAUNCH_RADAR_STORE_PATH||Io.join(ja(e),"launch-radar","state.json")}function Ua(e={}){let t=Ba(e);try{return{ok:!0,path:t,state:ho({path:t})}}catch(r){return{ok:!1,path:t,error:Pa(r)}}}function qa(){return process.env.ORACLE_AUTONOMOUS_TRADING==="1"}function mr(e={},t={}){let r=Ua(t),n={schema:_a,storePath:r.path,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,autonomousTradingEnvSet:qa()};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=Ke.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:Ke.filter(a=>!s.includes(a))}},supports(a){return s.includes(a)}};for(let a of Ke)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 nn=new Map;function on(e){let t=Bs(e);return nn.set(t.chainId,t),t}function sn(e){return nn.get(Number(e))||null}var xt={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},K=e=>BigInt(e).toString(16).padStart(64,"0"),Re=e=>e.slice(2).toLowerCase().padStart(64,"0");function Us(e,t){return`0x${xt.getAmountsOut}`+K(e)+K(64)+K(t.length)+t.map(Re).join("")}function qs(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length<128)return null;let r=Number(BigInt(`0x${t.slice(64,128)}`));if(!Number.isFinite(r)||r<1||r>16)return null;let n=[];for(let o=0;o<r;o++){let s=128+o*64;if(t.length<s+64)return null;n.push(BigInt(`0x${t.slice(s,s+64)}`))}return n}function It(e,t="router"){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}var Nt=100;function Ds(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Nt)throw new Error(`slippageBps ${r} exceeds the ${Nt} 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 an(e){let{chainId:t,wrappedNative:r}=e;async function n(o,s,i,a){let c=await q(t,"eth_call",[{to:o,data:Us(s,i)},"latest"],a);return qs(c?.result??c)}return{async quote({tokenIn:o,tokenOut:s,amountIn:i,path:a},c={}){let u=It(c.scanner);if(!u)return{chainId:t,evidence:N.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let l=a||[o,s];if(l.some(p=>!/^0x[0-9a-fA-F]{40}$/.test(p||"")))throw new Error("quote requires valid 20-byte addresses");let d=await n(u,i,l,c);return d?{chainId:t,router:u,path:l,amountIn:String(i),amountOut:d[d.length-1].toString(),hops:l.length-1,evidence:N.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:u,path:l,evidence:N.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:o,amountIn:s,base:i},a={}){let c=It(a.scanner),u=i||r;if(u&&String(o).toLowerCase()===String(u).toLowerCase())return{chainId:t,token:o,verdict:E.UNKNOWN,evidence:N.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!c||!u)return{chainId:t,token:o,verdict:E.UNKNOWN,evidence:N.UNAVAILABLE,reason:c?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let l=await n(c,s,[u,o],a);if(!l)return{chainId:t,token:o,verdict:E.FAIL,evidence:N.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let d=l[l.length-1];if(d===0n)return{chainId:t,token:o,verdict:E.FAIL,evidence:N.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let p=await n(c,d,[o,u],a);if(!p)return{chainId:t,token:o,verdict:E.FAIL,evidence:N.LIVE,leg:"sell",bought:d.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let f=p[p.length-1],m=Number(f*10000n/BigInt(s)),h=E.PASS,b="round trip completes with expected fee/impact loss";return m<5e3?(h=E.FAIL,b=`round trip returns only ${(m/100).toFixed(2)}% -- punitive tax or no real liquidity`):m<9e3&&(h=E.CAUTION,b=`round trip returns ${(m/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:o,base:u,router:c,verdict:h,reason:b,amountIn:String(s),bought:d.toString(),returned:f.toString(),retentionBps:m,evidence:N.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:s,amountIn:i,recipient:a,slippageBps:c=50,deadlineSeconds:u=900,path:l},d={}){let p=d.scanner,f=It(p);if(!f)throw new Error(`chain ${t} has no verified router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!/^0x[0-9a-fA-F]{40}$/.test(a||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let m=l||[o,s],h=await this.quote({tokenIn:o,tokenOut:s,amountIn:i,path:m},d);if(h.evidence!==N.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let b=Ds(h.amountOut,c);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let A=BigInt(Math.floor(Date.now()/1e3)+Number(u)),I=r&&m[0].toLowerCase()===r.toLowerCase()&&d.useNative,x=I?`0x${xt.swapExactETHForTokens}`+K(b)+K(128)+Re(a)+K(A)+K(m.length)+m.map(Re).join(""):`0x${xt.swapExactTokensForTokens}`+K(i)+K(b)+K(160)+Re(a)+K(A)+K(m.length)+m.map(Re).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:f,data:x,value:I?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:h.amountOut,minOut:b.toString(),slippageBps:c,maxSlippageBps:Nt,deadline:A.toString()},requires:I?[]:[{step:"approve",token:m[0],spender:f,amount:String(i)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var $s=[100,500,3e3,1e4],cn={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},pe=e=>BigInt(e).toString(16).padStart(64,"0"),_e=e=>e.slice(2).toLowerCase().padStart(64,"0"),un=/^0x[0-9a-fA-F]{40}$/,Ct=100;function Fs(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Ct)throw new Error(`slippageBps ${r} exceeds the ${Ct} 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 kt(e,t){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function ln(e){let{chainId:t,wrappedNative:r}=e;async function n({quoter:s,tokenIn:i,tokenOut:a,amountIn:c,fee:u},l){let d=`0x${cn.quoteExactInputSingle}`+_e(i)+_e(a)+pe(c)+pe(u)+pe(0),p=await q(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($s.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=kt(c.scanner,"quoter");if(!u)return{chainId:t,evidence:N.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let p of[s,i])if(!un.test(p||""))throw new Error("quote requires valid 20-byte addresses");let{best:l,tried:d}=await o({quoter:u,tokenIn:s,tokenOut:i,amountIn:a},c);return l?{chainId:t,venue:"uniswap-v3",quoter:u,tokenIn:s,tokenOut:i,amountIn:String(a),amountOut:l.amountOut.toString(),fee:l.fee,useNative:!!r&&String(s).toLowerCase()===String(r).toLowerCase(),triedFeeTiers:d,evidence:N.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:u,tokenIn:s,tokenOut:i,triedFeeTiers:d,evidence:N.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:s,amountIn:i,base:a},c={}){let u=kt(c.scanner,"quoter"),l=(e.stableQuoteAssets||[]).map(g=>String(g).toLowerCase()),d=null;!a&&typeof e.resolveQuoteAsset=="function"&&(d=await e.resolveQuoteAsset(s,c).catch(()=>null));let p=String(s).toLowerCase(),f=String(r||"").toLowerCase();if(f&&p===f)return{chainId:t,token:s,verdict:E.UNKNOWN,evidence:N.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};let m=a||d||(l[0]&&p!==l[0]?l[0]:null)||r;if(m&&p===String(m).toLowerCase())return{chainId:t,token:s,verdict:E.UNKNOWN,evidence:N.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!u||!m)return{chainId:t,token:s,verdict:E.UNKNOWN,evidence:N.UNAVAILABLE,reason:u?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let h=await o({quoter:u,tokenIn:m,tokenOut:s,amountIn:i},c);if(!h.best){let g=l.find(v=>v&&v!==String(m).toLowerCase()&&v!==String(s).toLowerCase());if(g){let v=await o({quoter:u,tokenIn:g,tokenOut:s,amountIn:i},c);if(v.best){let S=await o({quoter:u,tokenIn:s,tokenOut:g,amountIn:v.best.amountOut},c);if(S.best){let k=S.best.amountOut,O=Number(k*10000n/BigInt(i)),L=E.PASS,y="round trip vs dollar book completes with expected fee/impact loss";return O<5e3?(L=E.FAIL,y=`round trip vs dollar book returns only ${(O/100).toFixed(2)}% -- punitive tax or no real liquidity`):O<9e3&&(L=E.CAUTION,y=`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:g,quoteAsset:g,verdict:L,reason:y,amountIn:String(i),bought:v.best.amountOut.toString(),returned:k.toString(),retentionBps:O,buyFee:v.best.fee,sellFee:S.best.fee,evidence:N.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:t,token:s,verdict:E.FAIL,evidence:N.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let b=await o({quoter:u,tokenIn:s,tokenOut:m,amountIn:h.best.amountOut},c);if(!b.best){let g=l.find(v=>v&&v!==String(m).toLowerCase()&&v!==String(s).toLowerCase());if(g){let v=await o({quoter:u,tokenIn:g,tokenOut:s,amountIn:i},c),S=v.best?await o({quoter:u,tokenIn:s,tokenOut:g,amountIn:v.best.amountOut},c):{best:null};if(v.best&&S.best){let k=S.best.amountOut,O=Number(k*10000n/BigInt(i)),L=E.PASS,y="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return O<5e3?(L=E.FAIL,y=`dollar-book round trip returns only ${(O/100).toFixed(2)}%`):O<9e3&&(L=E.CAUTION,y=`dollar-book round trip returns ${(O/100).toFixed(2)}%`),{chainId:t,venue:"uniswap-v3",token:s,base:g,quoteAsset:g,verdict:L,reason:y,amountIn:String(i),bought:v.best.amountOut.toString(),returned:k.toString(),retentionBps:O,buyFee:v.best.fee,sellFee:S.best.fee,evidence:N.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:t,token:s,verdict:E.FAIL,evidence:N.LIVE,leg:"sell",bought:h.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let A=b.best.amountOut,I=Number(A*10000n/BigInt(i)),x=E.PASS,C="round trip completes with expected fee/impact loss";return I<5e3?(x=E.FAIL,C=`round trip returns only ${(I/100).toFixed(2)}% -- punitive tax or no real liquidity`):I<9e3&&(x=E.CAUTION,C=`round trip returns ${(I/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:s,base:m,verdict:x,reason:C,amountIn:String(i),bought:h.best.amountOut.toString(),returned:A.toString(),retentionBps:I,buyFee:h.best.fee,sellFee:b.best.fee,evidence:N.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:s,tokenOut:i,amountIn:a,recipient:c,slippageBps:u=50,fee:l},d={}){let p=kt(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(!un.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=await this.quote({tokenIn:s,tokenOut:i,amountIn:a},d);if(f.evidence!==N.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let m=l??f.fee,h=Fs(f.amountOut,u);if(h<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=!!(d.useNative||f.useNative)&&r&&String(s).toLowerCase()===String(r).toLowerCase(),A=`0x${cn.exactInputSingle}`+_e(s)+_e(i)+pe(m)+_e(c)+pe(a)+pe(h)+pe(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:p,data:A,value:b?String(a):"0x0"},guard:{quotedOut:f.amountOut,minOut:h.toString(),slippageBps:u,maxSlippageBps:Ct,fee:m},requires:b?[]:[{step:"approve",token:s,spender:p,amount:String(a)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var We={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function dn(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function pn(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 Ms(e){let{chainId:t}=e;async function r(n,o,s){return q(t,"eth_call",[{to:n,data:o},"latest"],s)}return{async blockNumber(n={}){let o=await Qr(t,n);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:N.LIVE}},async nativeBalance(n,o={}){let s=await Xr(t,n,o);return{chainId:t,address:n,wei:s?.wei??s?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:N.LIVE}},async tokenBalance({token:n,owner:o},s={}){let i=await Zr({chainId:t,token:n,owner:o},s);return{chainId:t,token:n,owner:o,raw:i?.balance??i,evidence:N.LIVE}},async resolveToken(n,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:t,token:n,evidence:N.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[s,i,a,c]=await Promise.all([r(n,We.decimals,o).catch(()=>null),r(n,We.symbol,o).catch(()=>null),r(n,We.name,o).catch(()=>null),r(n,We.totalSupply,o).catch(()=>null)]),u=dn(s?.result??s),l=u!==null||i?.result||a?.result,d={chainId:t,address:n,decimals:u===null?null:Number(u),symbol:pn(i?.result??i),name:pn(a?.result??a),totalSupply:(dn(c?.result??c)??null)?.toString()??null,evidence:l?N.LIVE:N.UNKNOWN};return l||(d.warning="no ERC-20 metadata returned -- may not be a token contract"),d},async resolvePools(n,o={}){let s=e.dexscreenerSlug;if(!s)return{chainId:t,token:n,pools:[],evidence:N.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await rn(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=Ot(n,c,{stables:e.stableQuoteAssets||[],wrappedNative:e.wrappedNative});return{chainId:t,token:n,pools:u,topPool:u[0]||null,quoteAsset:tn(n,u),evidence:u.length?N.LIVE:N.UNKNOWN}},async scanBlocks({fromBlock:n,toBlock:o,address:s,topics:i,chunkSize:a=2e3}={},c={}){if(!Number.isInteger(n)||!Number.isInteger(o))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(o<n)throw new Error("toBlock must be >= fromBlock");let u=[],l=[];for(let p=n;p<=o;p+=a){let f=Math.min(p+a-1,o);l.push([p,f])}let d=await Vr(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 q(t,"eth_getLogs",[m],c).catch(b=>({error:String(b?.message||b)}));return{start:p,end:f,res:h}});for(let{start:p,end:f,res:m}of d){if(m?.error)return{chainId:t,fromBlock:n,toBlock:o,logs:u,complete:!1,failedAt:[p,f],error:m.error,evidence:N.UNKNOWN};for(let h of m?.result??m??[])u.push(h)}return{chainId:t,fromBlock:n,toBlock:o,logs:u,complete:!0,chunks:l.length,evidence:N.LIVE}},async scoreRisk(n,o={}){let s=[],i=E.PASS,a=l=>{let d={[E.PASS]:0,[E.CAUTION]:1,[E.UNKNOWN]:2,[E.FAIL]:3};d[l]>d[i]&&(i=l)},[c,u]=await Promise.all([this.resolveToken(n,o),this.resolvePools(n,o)]);if(c.evidence!==N.LIVE?(s.push({check:"erc20-metadata",result:E.UNKNOWN,detail:c.warning}),a(E.UNKNOWN)):s.push({check:"erc20-metadata",result:E.PASS,detail:`${c.symbol} / ${c.decimals}d`}),u.evidence===N.UNAVAILABLE)s.push({check:"liquidity",result:E.UNKNOWN,detail:u.reason}),a(E.UNKNOWN);else if(!u.pools.length)s.push({check:"liquidity",result:E.FAIL,detail:"no pool with liquidity found"}),a(E.FAIL);else{let l=u.pools[0],d=l.liquidityUsd??0;d<5e3?(s.push({check:"liquidity",result:E.CAUTION,detail:`top pool only $${d}`}),a(E.CAUTION)):s.push({check:"liquidity",result:E.PASS,detail:`$${d} on ${l.dex}`}),l.createdAt&&Date.now()-l.createdAt<24*3600*1e3&&(s.push({check:"age",result:E.CAUTION,detail:"pool under 24h old"}),a(E.CAUTION))}if(typeof this.sellSimulation=="function"){let l=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},o).catch(d=>({verdict:E.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:E.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(E.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 fn(e){let r={...Ms(e)},n=new Set((e.venues||[]).map(s=>s.kind));e.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,ln({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,an({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 Hs=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 mn(){return Hs.map(e=>on(fn(e)))}import{AbiCoder as Vs,Interface as gn,getAddress as me,isAddress as An,keccak256 as zs}from"ethers";var Tt="0x0000000000000000000000000000000000000000",Ks="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Ws=Vs.defaultAbiCoder(),hn=new gn(["function quoteExactInputSingle((address tokenIn,address tokenOut,uint256 amountIn,uint24 fee,uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut,uint160 sqrtPriceX96After,uint32 initializedTicksCrossed,uint256 gasEstimate)"]),bn=new gn(["function quoteExactInputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountOut,uint256 gasEstimate)"]),W=Object.freeze({1:Object.freeze({quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"}),10:Object.freeze({quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrappedNative:"0x4200000000000000000000000000000000000006"}),56:Object.freeze({quoter:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"}),137:Object.freeze({quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270"}),8453:Object.freeze({quoter:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",wrappedNative:"0x4200000000000000000000000000000000000006"}),42161:Object.freeze({quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"}),43114:Object.freeze({quoter:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7"}),4663:Object.freeze({quoter:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73"}),988:Object.freeze({quoter:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5"}),999:Object.freeze({quoter:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",wrappedNative:"0x5555555555555555555555555555555555555555"}),2741:Object.freeze({quoter:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809"})}),je=Object.freeze({1:Object.freeze({quoter:"0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203",wrappedNative:W[1].wrappedNative}),10:Object.freeze({quoter:"0x1f3131a13296fb91c90870043742c3cdbff1a8d7",wrappedNative:W[10].wrappedNative}),56:Object.freeze({quoter:"0x9f75dd27d6664c475b90e105573e550ff69437b0",wrappedNative:W[56].wrappedNative}),137:Object.freeze({quoter:"0xb3d5c3dfc3a7aebff71895a7191796bffc2c81b9",wrappedNative:W[137].wrappedNative}),8453:Object.freeze({quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",wrappedNative:W[8453].wrappedNative}),42161:Object.freeze({quoter:"0x3972c00f7ed4885e145823eb7c655375d275a1c5",wrappedNative:W[42161].wrappedNative}),43114:Object.freeze({quoter:"0xbe40675bb704506a3c2ccfb762dcfd1e979845c2",wrappedNative:W[43114].wrappedNative}),4663:Object.freeze({quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",wrappedNative:W[4663].wrappedNative})}),Gs=Object.freeze([100,500,3e3,1e4]);function fe(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 Sn(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 En(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 Lt(e){let t=String(e??"").trim().toLowerCase();return t===""||t==="eth"||t===Tt||t===Ks}function Pe(e,t){if(!An(String(e??"")))throw new Error(`${t} must be an EVM address`);return me(String(e))}function yn(e,t,r){return Lt(e)?me(t.wrappedNative):Pe(e,r)}function wn(e,t){return Lt(e)?me(Tt):Pe(e,t)}function vn(e,t){let r=Number(e);if(!Number.isInteger(r)||r<0||r>16777215)throw new Error(`${t} must be uint24`);return r}function Js(e,t){let r=Number(e);if(!Number.isInteger(r)||r<-8388608||r>8388607)throw new Error(`${t} must be int24`);return r}function Ys({tokenIn:e,tokenOut:t,poolKey:r,poolId:n}){fe(r,new Set(["currency0","currency1","fee","tickSpacing","hooks"]),"V4 PoolKey");let o=Pe(r.currency0,"V4 currency0"),s=Pe(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:vn(r.fee,"V4 fee"),tickSpacing:Js(r.tickSpacing,"V4 tickSpacing"),hooks:Pe(r.hooks??Tt,"V4 hooks")}),a=wn(e,"tokenIn"),c=wn(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=zs(Ws.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 Rt(e,t){if(Lt(t))return!0;if(!An(String(t??"")))return!1;let r=W[Number(e)]?.wrappedNative||je[Number(e)]?.wrappedNative;return!!(r&&me(String(t)).toLowerCase()===me(r).toLowerCase())}async function On(e={},t={},r={}){fe(e,new Set(["chainId","tokenIn","tokenOut","amountIn","fee"]),"V3 read"),fe(t,new Set(["timeoutMs"]),"V3 read options"),fe(r,new Set(["rpc"]),"V3 read dependencies");let n=Number(e.chainId),o=W[n];if(!o)throw new Error(`V3 read unavailable on chain ${e.chainId}`);let s=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=Sn(e.amountIn,"amountIn"),c=e.fee==null?Gs:[vn(e.fee,"V3 fee")],u=r.rpc||q,l=En(t.timeoutMs),d=await Promise.all(c.map(async f=>{let m=hn.encodeFunctionData("quoteExactInputSingle",[{tokenIn:s,tokenOut:i,amountIn:a,fee:f,sqrtPriceLimitX96:0n}]);try{let h=await u(n,"eth_call",[{to:o.quoter,data:m},"latest"],l);if(!h||h==="0x")throw new Error("empty result");let b=hn.decodeFunctionResult("quoteExactInputSingle",h);return Object.freeze({ok:!0,fee:f,amountOut:b[0].toString(),gasEstimate:b[3].toString()})}catch(h){return Object.freeze({ok:!1,fee:f,error:String(h?.message||h).slice(0,160)})}})),p=d.filter(f=>f.ok).sort((f,m)=>BigInt(m.amountOut)>BigInt(f.amountOut)?1:-1)[0];if(!p)throw new Error(`V3 read failed chain=${n}: ${d.map(f=>`${f.fee}:${f.error}`).join("; ")}`);return Object.freeze({venue:"uniswap-v3",chainId:n,quoter:me(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 In(e={},t={},r={}){fe(e,new Set(["chainId","tokenIn","tokenOut","amountIn","poolKey","poolId"]),"V4 read"),fe(t,new Set(["timeoutMs"]),"V4 read options"),fe(r,new Set(["rpc"]),"V4 read dependencies");let n=Number(e.chainId),o=je[n];if(!o)throw new Error(`V4 read unavailable on chain ${e.chainId}`);let s=Sn(e.amountIn,"amountIn");if(s>0xffffffffffffffffffffffffffffffffn)throw new Error("amountIn exceeds uint128");let i=Ys(e),a=bn.encodeFunctionData("quoteExactInputSingle",[{poolKey:i.poolKey,zeroForOne:i.zeroForOne,exactAmount:s,hookData:"0x"}]),u=await(r.rpc||q)(n,"eth_call",[{to:o.quoter,data:a},"latest"],En(t.timeoutMs));if(!u||u==="0x")throw new Error("V4 read returned an empty result");let l=bn.decodeFunctionResult("quoteExactInputSingle",u);return Object.freeze({venue:"uniswap-v4",chainId:n,quoter:me(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 Qs=new Set(["chainId","tokenIn","tokenOut","amountIn","v4PoolKey","v4PoolId"]),Xs=new Set(["maxImpactPct","timeoutMs"]),Zs=new Set(["quoteV3","quoteV4","gasPrice"]);function _t(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 jt(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 xn(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 te(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 ei(e){if(e<=1n)return null;let t=e/1000n;return t>0n&&t<e?t:1n}function ti({amountIn:e,amountOut:t,probeIn:r,probeOut:n}){let o=te(e),s=te(t),i=te(r),a=te(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 Pt(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 ri({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,amountOut:o,gasEstimate:s,gasPrice:i}){let a=te(s),c=te(i),u=te(n),l=te(o);if(!a||!c||!u||!l||a<=0n||c<=0n)return null;let d=a*c;return Rt(e,r)?d:Rt(e,t)?d*l/u:null}async function ni(e,t){let r=await q(e,"eth_gasPrice",[],{timeoutMs:t});return te(r)}function oi(e,t){return Object.freeze({source:e,quality:"FAILED",amountOut:null,error:String(t?.message||t).slice(0,240)})}async function Nn({source:e,amountIn:t,timeoutMs:r,fullRead:n,probeRead:o}){try{let s=await Pt(n,r,e),i=jt(s?.amountOut,`${e} amountOut`),a=ei(t);if(a==null)return{source:e,full:s,impactPct:null};try{let c=await Pt(()=>o(a.toString(),s),r,`${e} impact probe`),u=ti({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 si({inspected:e,params:t,gasPrice:r}){let n=e.full,o=jt(n.amountOut,`${e.source} amountOut`),s=ri({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 ii({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 Bt(e={},t={},r={}){_t(e,Qs,"route params"),_t(t,Xs,"route options"),_t(r,Zs,"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=jt(e.amountIn,"amountIn"),s=xn(t.timeoutMs,12e3,250,6e4,"timeoutMs"),i=xn(t.maxImpactPct,25,0,100,"maxImpactPct"),a=r.quoteV3||On,c=r.quoteV4||In,u=r.gasPrice||ni,l=[];W[n]&&l.push(Nn({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&&je[n]&&l.push(Nn({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=Pt(()=>u(n,s),s,"gas price read").catch(()=>null),m=await Promise.all(l),h=await f,b=m.filter(w=>w.error).map(w=>oi(w.source,w.error)),A=m.filter(w=>w.full),I=A.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`})),x=new Set(I.map(w=>w.source)),C=A.filter(w=>!x.has(w.source)),g=C.map(w=>si({inspected:w,params:{...e,chainId:n},gasPrice:h})),v=g.length>0&&g.every(w=>w.costAccounted),S=v?"net":"gross";for(let w of g){let T=BigInt(w.grossOut),re=v?BigInt(w.costInDest):0n;w.netOut=(T>re?T-re:0n).toString()}g.sort((w,T)=>{let re=BigInt(v?w.netOut:w.grossOut),V=BigInt(v?T.netOut:T.grossOut);return re===V?w.source.localeCompare(T.source):V>re?1:-1});let k=[];v?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=C.filter(w=>w.impactPct==null).map(w=>w.source);O.length&&k.push(`Price impact is UNKNOWN for: ${O.join(", ")}.`),I.length&&k.push(`Dropped on price impact: ${I.map(w=>w.source).join(", ")}.`),!d&&je[n]&&k.push("V4 was not queried because no exact verified PoolKey identity was discovered.");let L=null,y=null;if(g.length>1){let w=BigInt(v?g[0].netOut:g[0].grossOut),T=BigInt(v?g[1].netOut:g[1].grossOut);T>0n&&(L=Number((w-T)*10000000n/T)/1e3,y=`${g[0].source} vs ${g[1].source}`)}let F=Object.fromEntries(C.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:g[0]||null,routes:Object.freeze(g.map(w=>Object.freeze(w))),failed:Object.freeze(b),rankedOn:S,sourcesTried:l.length,sourcesAnswered:A.length,improvementBps:L,spreadBasis:y,priceImpact:Object.freeze(F),impactRejected:Object.freeze(I),impactUnmeasured:Object.freeze(O),warnings:Object.freeze(k),note:ii({routes:g,rankedOn:S,improvementBps:L})})}var he="So11111111111111111111111111111111111111112";var Bi=new Set(["chainId","tokenIn","tokenOut","amountIn"]),Ui=new Set(["maxImpactPct","timeoutMs","quoteFn"]);function Wn(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 Gn(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 Jn(e,t){let r=String(e||"").trim();if(!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(r))throw new Error(`${t} must be a Solana pubkey`);return r}async function qi(e,t={}){let{jupiterQuote:r}=await Promise.resolve().then(()=>(Kt(),zt)),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 Gt(e={},t={}){if(Wn(e,Bi,"params"),Wn(t,Ui,"options"),e.chainId!=null&&Number(e.chainId)!==101)throw new Error("solana quote adapter only handles chainId 101");let r=Jn(e.tokenIn,"tokenIn"),n=Jn(e.tokenOut,"tokenOut"),o=Gn(e.amountIn,"amountIn");if(r===n)throw new Error("solana quote tokenIn and tokenOut must differ");let s=t.quoteFn||qi;if(typeof s!="function")throw new TypeError("solana quote adapter requires a quote function");let i=Number(t.timeoutMs??12e3),a=await s({inputMint:r,outputMint:n,amount:o,slippageBps:100},{timeoutMs:i}),c=Gn(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 Yn({routeFn:e=Gt}={}){return Object.freeze({async sellSimulation({token:t,amountIn:r,base:n}={}){let{simulateSell:o,SELL_SIM:s}=await Promise.resolve().then(()=>(Kn(),zn)),i=await o({token:t,base:n||he,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 Zi(e){return e?.token?.address||e?.tokenAddress||null}function ea(e){return e?.quoteAsset||e?.pool?.quoteAsset||null}function ta(e,t){return e?.quoteAmountIn||e?.quote?.amountIn||null}async function Yt({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=Zi(e),o=ea(e),s=ta(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(()=>(Kt(),zt)),u=await c({userPublicKey:t.recipient,inputMint:o==="unknown"?he: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 Qt({prepared:e}={},t=process.env){if(e?.prepared!==!0)return{ok:!1,error:"nothing prepared"};let{armPreparedAction:r}=await Promise.resolve().then(()=>(ro(),to)),n=e.localSignerEnvelope||e.envelope;return n?r({localSignerEnvelope:n},t):{ok:!1,error:"prepared envelope missing"}}import{createHash as ua}from"node:crypto";import{createHash as ra}from"node:crypto";var M=Object.freeze({SHADOW:"shadow",ARMED:"armed",AUTONOMOUS:"autonomous"}),na=3,oa=new Set(Object.values(M));function tr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))tr(t);Object.freeze(e)}return e}function er(e){return Array.isArray(e)?`[${e.map(er).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${er(e[t])}`).join(",")}}`:JSON.stringify(e)}function sa(e){return`sha256:${ra("sha256").update(er(e)).digest("hex")}`}function Xt(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 ia(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new TypeError(`${t} entries must be positive safe integers`);return e}function Zt(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 Ie(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 qe(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 rt(e,t){let r=Ie(e,t),[n,o=""]=r.split(".");return{digits:BigInt(n+o),scale:o.length}}function tt(e,t,r="value"){let n=rt(e,r),o=rt(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 no(e){let t=structuredClone(e);return delete t.digest,t}function aa(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");return sa(no(e))}function rr(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy must be an object");let t=e.mode??M.SHADOW;if(!oa.has(t))throw new TypeError("mode must be shadow, armed, or autonomous");let r={version:1,mode:t,chains:Xt(e.chains,"chains",ia),venues:Xt(e.venues,"venues",Zt),quoteAssets:Xt(e.quoteAssets,"quoteAssets",Zt),maxSpendPerTrade:Ie(e.maxSpendPerTrade,"maxSpendPerTrade",{positive:!0}),maxSpendPerDay:Ie(e.maxSpendPerDay,"maxSpendPerDay",{positive:!0}),minLiquidityUsd:Ie(e.minLiquidityUsd,"minLiquidityUsd",{positive:!0}),maxSlippageBps:qe(e.maxSlippageBps,"maxSlippageBps",{max:1e4}),maxGas:Ie(e.maxGas,"maxGas",{positive:!0}),maxPriorityFee:Ie(e.maxPriorityFee,"maxPriorityFee"),maxBuysPerHour:qe(e.maxBuysPerHour,"maxBuysPerHour",{min:1}),retryCeiling:qe(e.retryCeiling,"retryCeiling",{max:na}),ttlMs:qe(e.ttlMs,"ttlMs",{min:1}),requireSellSimulation:e.requireSellSimulation,requireRiskPass:e.requireRiskPass??!0,maxRoundTripLossBps:qe(e.maxRoundTripLossBps??1500,"maxRoundTripLossBps",{max:1e4}),killSwitch:e.killSwitch,recipient:e.recipient==null||e.recipient===""?null:Zt(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(tt(r.maxSpendPerTrade,r.maxSpendPerDay)>0)throw new TypeError("maxSpendPerTrade cannot exceed maxSpendPerDay");return r.digest=aa(r),tr(r)}var ca=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 nr(e,t={},r={}){let n=rr(no(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,tt(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=rt(t.spentToday,"daily spend"),c=rt(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,tt(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,tt(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 ca)j(i,t.autonomousGates?.[a]!==!0,c);return j(i,n.mode!==M.AUTONOMOUS,"strategy mode is not autonomous"),tr({strategyDigest:n.digest,mode:n.mode,policyEligible:o.length===0,blockers:o,autonomousEligible:i.length===0,autonomousBlockers:i,reportOnly:!0})}function ao(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))ao(t);Object.freeze(e)}return e}var oo=Object.freeze({ALERT_ONLY:"alert_only",EXECUTE:"execute"}),so=Object.freeze({liveQuote:20,sellSimulation:30,contractRisk:20,liquidity:15,roundTripLoss:15});function z(e,t){return{id:e,verdict:"PASS",detail:t}}function H(e,t){return{id:e,verdict:"BLOCK",detail:t}}function io(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function co({strategy:e,observation:t={},evaluation:r={}}={}){if(!e||typeof e!="object")throw new TypeError("snipe features require a strategy");let n=[],o=[],s=(h,b)=>{n.push(h),h.verdict==="BLOCK"&&o.push(b)};s(e.killSwitch===!0?H("killSwitch","engaged"):z("killSwitch","off"),"kill switch is engaged"),s(e.chains.includes(t.chain)?z("chain",String(t.chain)):H("chain",String(t.chain??"missing")),"chain is not on the exact allowlist"),s(e.venues.includes(t.venue)?z("venue",String(t.venue)):H("venue",String(t.venue??"missing")),"venue is not on the exact allowlist"),s(e.quoteAssets.includes(t.quoteAsset)?z("quoteAsset",String(t.quoteAsset)):H("quoteAsset",String(t.quoteAsset??"missing")),"quote asset is not on the exact allowlist");let i=r.quote?.evidence||t.quoteEvidence;s(i==="LIVE"?z("liveQuote","LIVE"):H("liveQuote",String(i||"missing")),"live quote is missing");let a=t.sellSimulation||r.sellSimulation;s(a?.verdict==="PASS"&&a?.evidence==="LIVE"?z("sellSimulation","LIVE PASS"):H("sellSimulation",`${a?.verdict||"missing"}/${a?.evidence||"missing"}`),"mandatory sell simulation has no LIVE PASS evidence");let c=t.riskVerdict||r.risk?.verdict;s(e.requireRiskPass===!0&&c==="PASS"?z("contractRisk","PASS"):H("contractRisk",String(c||"missing")),"contract risk is not PASS");let u=t.liquidityUsd;try{let h=Number(u),b=Number(e.minLiquidityUsd);s(Number.isFinite(h)&&Number.isFinite(b)&&h>=b?z("liquidity",String(u)):H("liquidity",String(u??"missing")),"minimum real liquidity is not met")}catch{s(H("liquidity","unknown"),"liquidity evidence is missing or unknown")}let l=io(t.slippageBps);s(l!=null&&l<=e.maxSlippageBps?z("slippage",String(l)):H("slippage",String(t.slippageBps??"missing")),"slippage exceeds cap or is unknown");let d=io(t.roundTripLossBps);s(d!=null&&d<=e.maxRoundTripLossBps?z("roundTripLoss",String(d)):H("roundTripLoss",String(t.roundTripLossBps??"missing")),"round-trip loss exceeds cap or is unknown"),s(Number.isSafeInteger(t.retries)&&t.retries<=e.retryCeiling?z("retryCeiling",String(t.retries)):H("retryCeiling",String(t.retries??"missing")),"retry ceiling is exceeded or unknown"),s(Number.isFinite(t.ageMs)&&t.ageMs>=0&&t.ageMs<e.ttlMs?z("ttl",String(t.ageMs)):H("ttl",String(t.ageMs??"missing")),"TTL has expired or is unknown"),s(typeof t.fireId=="string"&&t.fireId.length>0&&Array.isArray(t.firedIds)&&!t.firedIds.includes(t.fireId)?z("duplicateFire",t.fireId):H("duplicateFire","missing or duplicate"),"duplicate fire is blocked or fire id is unknown");let p=0;for(let h of n)h.verdict==="PASS"&&so[h.id]&&(p+=so[h.id]);let f=o.length===0,m=e.mode==="shadow"?oo.ALERT_ONLY:oo.EXECUTE;return ao({snipeReady:f,wouldSnipe:f,armed:!1,actionMode:m,score:p,features:n,blockers:o,reportOnly:e.mode==="shadow"})}function nt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function or(e){return Array.isArray(e)?`[${e.map(or).join(",")}]`:nt(e)?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${or(e[t])}`).join(",")}}`:JSON.stringify(e)}function la(e){return`cycle:${ua("sha256").update(or(e)).digest("hex")}`}function De(e,t){if(typeof e!="function")throw new TypeError(`launch-radar runner: injected ${t} function is required`)}function uo(e){return e instanceof Error?e.message:String(e)}function sr(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(!nt(r))throw new TypeError("launch-radar runner: strategy is required");De(n,"discovery"),De(o,"evaluate");let s=e.now??(()=>new Date().toISOString()),i=e.sleep??(()=>Promise.resolve()),a=e.jitter??(()=>0);De(s,"clock"),De(i,"sleep"),De(a,"jitter");let c=Math.min(3,Math.max(0,Number.isSafeInteger(e.retries)?e.retries:r.retryCeiling)),u=Math.max(0,Number.isFinite(e.baseBackoffMs)?e.baseBackoffMs:100),l=Math.max(u,Number.isFinite(e.maxBackoffMs)?e.maxBackoffMs:2e3);async function d(m){let h;for(let b=0;b<=c;b+=1)try{return await m(b)}catch(A){if(h=A,b===c)break;let I=Number(a()),x=Number.isFinite(I)?Math.max(0,I):0,C=Math.min(l,u*2**b+x);await i(C)}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=_r(r);if(m.strategyStatus.ambiguous)return{mode:r.mode,status:"blocked",blockers:["ambiguous state requires reconciliation"],results:[],actionMode:h};if(Array.isArray(m.evidence)&&m.evidence.length>0&&m.strategyStatus.mode!==r.mode)return{mode:r.mode,status:"blocked",blockers:["persisted mode does not match configured strategy"],results:[],actionMode:h};if(r.killSwitch)return{mode:r.mode,status:"blocked",blockers:["kill switch is engaged"],results:[],actionMode:h};let b;try{b=await d(g=>n({cursor:structuredClone(m.cursor),attempt:g,mode:r.mode}))}catch(g){return{mode:r.mode,status:"failed",blockers:[uo(g)],results:[],actionMode:h}}if(!nt(b)||!Array.isArray(b.candidates)||!(b.cursor===null||nt(b.cursor)))return{mode:r.mode,status:"failed",blockers:["discovery returned an invalid deterministic result"],results:[],actionMode:h};let A=[];for(let g of b.candidates)try{let v=await d(y=>o(structuredClone(g),{attempt:y,mode:r.mode})),S=nr(r,v,{}),k=co({strategy:r,observation:v,evaluation:g}),O={prepared:!1},L=!1;Me(r,S)&&typeof e.prepareFn=="function"?O=await e.prepareFn({candidate:g,observation:v,strategy:r,policy:S})||{prepared:!1}:Me(r,S)&&(O={prepared:!1,blockedReasons:["prepareFn is required when strategy mode is not shadow"]}),Pr(r,S,O)&&typeof e.queueFn=="function"&&(L=(await e.queueFn({prepared:O,candidate:g,observation:v,strategy:r,policy:S}))?.ok===!0),A.push({id:g?.id??null,policy:S,snipe:k,prepared:O.prepared===!0,queued:L,actionMode:h})}catch(v){A.push({id:g?.id??null,policy:{mode:r.mode,policyEligible:!1,reportOnly:r.mode===M.SHADOW,blockers:[`evaluation failed: ${uo(v)}`]},actionMode:h,prepared:!1,queued:!1})}let I={cursor:b.cursor,candidates:b.candidates,results:A},x={id:la(I),type:r.mode===M.SHADOW?"shadow-cycle":"execute-cycle",at:s(),data:I},C=t.commitCycle({candidates:b.candidates,cursor:b.cursor,strategyStatus:{mode:r.mode,status:"inert",ambiguous:!1},event:x});return{mode:r.mode,status:C.duplicate?"duplicate":"completed",results:A,evidenceId:C.evidence.id,actionMode:h}}return Object.freeze({status:p,runCycle:f})}function lo(e){return[...new Set(e.filter(Boolean).map(String))]}function be(e){return Array.isArray(e)?e.map(be):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,be(r)])):e}function oe(e,t,r="UNKNOWN"){return!e||typeof e!="object"?{evidence:r,observedAt:t}:be({...structuredClone(e),evidence:e.evidence||r,observedAt:e.observedAt||t})}function da(e,t){let r=String(t||"").toLowerCase();return!!(r&&[e?.address,e?.pair,e?.poolId].some(n=>String(n||"").toLowerCase()===r))}function pa(e,t){let r=e.poolId||e.poolAddress||null,n=[t.topPool,...t.pools?.pools||[]].filter(Boolean),o=r?n.find(i=>da(i,r)):t.topPool,s={address:e.poolAddress??null,poolId:e.poolId,poolKey:e.poolKey,quoteAsset:e.quoteAsset};return be({...o||{},...s})}function fa(e,t,r,n){let o=e.observedAt||n,s=pa(e,t),i=oe(t.scannerRisk||t.risk,o),a=oe(t.sellability,o,"UNAVAILABLE"),c=oe(t.quote,o,"UNAVAILABLE"),u=c.evidence==="LIVE"?"PASS":"UNKNOWN";return be({chain:{id:e.chainId,...t.chain||{}},token:oe({address:e.tokenAddress,...t.token||{}},o,"LIVE"),pool:oe(s,o,"LIVE"),venue:oe({...e.venue,supported:e.venue?.supported===!0,verified:e.venue?.verified===!0},o,"LIVE"),signal:oe({kind:e.kind,source:"verified-factory",unsolicitedAirdrop:!1},o,"LIVE"),risk:i,sellability:a,sellSimulation:oe(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:be({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:lo([...r||[],...t.blockedReasons||[],t.error]),latency:{discoveredAt:o,riskCompletedAt:i.observedAt,sellabilityCompletedAt:a.observedAt,routeCompletedAt:c.observedAt,normalizedAt:n}})}async function ot(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:be(structuredClone(a)),prepare:e.prepare===!0})}catch(u){c={error:`evaluation unavailable: ${String(u?.message||u).slice(0,300)}`}}i.push(fa(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(lo(n?.whyBlocked||[])),candidates:Er(i)})}var ma=101,po=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/,ha="181ec828051c0777",ba="6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P";function xe(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))xe(t);Object.freeze(e)}return e}function ya(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!==ba)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 wa(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(ha))continue;let c=Array.isArray(i.accounts)?i.accounts:[],u=c[0],l=c[2];return!po.test(u||"")||!po.test(l||"")?null:{id:`solana:${r}:${s}`,chain:"solana",chainId:ma,factoryId:t.id||null,factoryAddress:t.programId,tokenAddress:u,quoteAsset:he,poolAddress:l,venue:structuredClone(t.venue),kind:"token-launched",slot:n,signature:r,instructionIndex:s,evidence:"LIVE"}}return null}async function fo(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=ya(u);l?n.push({id:u?.id||null,status:"UNAVAILABLE",reason:l}):o.push(u)}let s=xe({until:e.cursor?.until||null});if(o.length===0)return xe({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 xe({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 xe({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=wa({...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 xe({status:"LIVE",discoveries:[...c.values()],unavailable:n,cursor:{until:a},whyBlocked:n.map(u=>u.reason)})}Dt();var ga="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function Aa(e){let t=String(e||"");if(!t)return Buffer.alloc(0);let r=[0];for(let o of t){let s=ga.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 Sa(e){return typeof e=="string"?e:e?.pubkey||null}function Ea(e){let t=e?.transaction?.message||{},r=Array.isArray(t.accountKeys)?t.accountKeys.map(Sa):[],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=Aa(i.data).toString("hex")),a&&s.push({programId:a,accounts:c,dataHex:u})}return s}function mo(e={}){let t=e.solanaRpc||Cn;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:Ea(n)}:{signature:r,slot:null,instructions:[]}}}}import $ from"node:fs";import st from"node:path";var ur=1,va=0;function we(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function D(e){return structuredClone(e)}function ar(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)=>ar(r,`${t}[${n}]`));if(we(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}`);ar(n,`${t}.${r}`)}return}throw new Error(`launch-radar store: non-JSON value at ${t}`)}}function ye(e){return Array.isArray(e)?`[${e.map(ye).join(",")}]`:we(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${ye(e[t])}`).join(",")}}`:JSON.stringify(e)}function Oa(){return{version:ur,candidates:[],cursor:null,strategyStatus:{mode:"shadow",status:"inert",ambiguous:!1},evidence:[]}}function Ia(e){if(!we(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 $e(e){if(!we(e)||e.version!==ur)throw new Error("launch-radar store: corrupt or unsupported version");if(!Array.isArray(e.candidates)||!(e.cursor===null||we(e.cursor))||!Array.isArray(e.evidence))throw new Error("launch-radar store: corrupt state shape");Ia(e.strategyStatus),ar(e);try{ft(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=$.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 cr(e){it(e);let t;try{t=JSON.parse($.readFileSync(e,"utf8"))}catch{throw new Error("launch-radar store: corrupt JSON")}return $e(t)}function ir(e,t){let r=$e(t),n=st.dirname(e);$.mkdirSync(n,{recursive:!0,mode:448});let o=$.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=st.join(n,`.launch-radar.${process.pid}.${va+=1}.tmp`),i;try{i=$.openSync(s,"wx",384),$.writeFileSync(i,`${ye(r)}
8
+ `,"utf8"),$.fsyncSync(i),$.closeSync(i),i=void 0,$.renameSync(s,e),$.chmodSync(e,384);let a=$.openSync(n,"r");try{$.fsyncSync(a)}finally{$.closeSync(a)}}catch(a){i!==void 0&&$.closeSync(i);try{$.unlinkSync(s)}catch{}throw a}}function lr(e={}){let t=e.path;if(typeof t!="string"||!st.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");it(t,!0)?cr(t):ir(t,Oa());let r=()=>cr(t),n=(o,{reconciliation:s=!1}={})=>{if(r().strategyStatus.ambiguous&&!s)throw new Error("launch-radar store: ambiguous state is terminal until reconciliation");return ir(t,o),D(o)};return Object.freeze({path:t,read:r,replaceState(o={}){if(!we(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($e(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&&ye(i.data)===ye(o?.data))return D(i);throw new Error(`launch-radar store: duplicate evidence conflict: ${o?.id}`)}let a=mt(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&&ye(u.data)===ye(a?.data))return{duplicate:!0,evidence:D(u),state:c};throw new Error(`launch-radar store: duplicate evidence conflict: ${a?.id}`)}let l=mt(c.evidence,a),d=$e({...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 ir(t,{...s,strategyStatus:i}),D(i)},reconcile(o={}){if(!we(o))throw new TypeError("launch-radar store: reconciliation state must be an object");let s=r(),i=$e({...s,...D(o),version:ur,evidence:s.evidence});if(i.strategyStatus.ambiguous)throw new Error("launch-radar store: reconciliation must clear ambiguous state");return n(i,{reconciliation:!0})}})}function ho(e={}){let t=e.path;if(typeof t!="string"||!st.isAbsolute(t))throw new Error("launch-radar store: path must be absolute");return cr(t)}function pr(e){return e.ORACLE_CONFIG_DIR||se.join(xa.homedir(),".config","oracle")}function bo(e,t){if(!e||!se.isAbsolute(e))throw new Error(`${t} path must be absolute`);let r=at.lstatSync(e);if(r.isSymbolicLink()||!r.isFile())throw new Error(`${t} must be a regular non-symlink file`);if(r.size>1024*1024)throw new Error(`${t} exceeds 1 MiB`);return JSON.parse(at.readFileSync(e,"utf8"))}function Na(e){return e==null?null:String(e)}function Ne(e){if(e!==void 0)return typeof e=="bigint"?e.toString():Array.isArray(e)?e.map(Ne).filter(t=>t!==void 0):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,r])=>[t,Ne(r)])):e}function So(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 dr(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 ka(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 Ca(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:So(t.amountIn,"routeProbe.amountIn"),quoteAssetDecimals:dr(t.quoteAssetDecimals,0,255,"routeProbe.quoteAssetDecimals"),slippageBps:dr(t.slippageBps??100,0,1e4,"routeProbe.slippageBps"),maxImpactPct:ka(t.maxImpactPct??25,0,100,"routeProbe.maxImpactPct"),timeoutMs:dr(t.timeoutMs??12e3,250,6e4,"routeProbe.timeoutMs")})}function yo(e){return[e?.source,e?.amountOut,e?.netOut,e?.meta?.poolId].map(t=>String(t??"").toLowerCase()).join(":")}function wo(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 Ta(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 go(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 Ao(e){if(!e?.best||!So(e.best.amountOut,"best route amountOut"))throw new Error("best route returned no positive output");let t=Array.isArray(e.routes)?e.routes:[],r=yo(e.best),n=t.findIndex(a=>yo(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."),Ne({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 La(e,t){return{quote:{evidence:"UNAVAILABLE",reason:e,observedAt:t},sellability:{verdict:"UNKNOWN",evidence:"UNAVAILABLE",reason:e,observedAt:t}}}async function Eo({scanner:e,discovery:t,descriptor:r,routeFn:n=Bt,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=Ca(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:Ne(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);go(d,t,"buy");let p=Ao(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);go(f,t,"reverse");let m=Ao(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=Ta(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=Ne({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,La(c,o))}return Ne(s)}function vo(e){let t=e.quoteAsset||e.pool?.quoteAsset||e.token?.quoteAsset||"unknown",r=wo(e.quoteAmountIn,e.quoteAssetDecimals??18)||wo(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:Na(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=bo(t.ORACLE_LAUNCH_RADAR_STRATEGY_FILE,"strategy file"),n=bo(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=rr(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 Ra({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");mn();let a=sn(i[0]);if(!a)throw new Error(`no scanner registered for chain ${i[0]}`);let c=t.ORACLE_LAUNCH_RADAR_STORE_PATH||se.join(pr(t),"launch-radar",`state-${i[0]}.json`),u=lr({path:c});return sr({store:u,strategy:s,discover:async({cursor:p})=>{let f=await a.blockNumber(),m=Number(f?.blockNumber??f);if(!Number.isSafeInteger(m))throw new Error("scanner did not return a safe integer head block");let h=Number.isSafeInteger(p?.nextBlock)?p.nextBlock:Math.max(0,m-10),b=await ot({discover:()=>kr({scanner:a,factories:o,fromBlock:h,toBlock:m,cursor:p}),evaluator:async({discovery:A})=>{let I=o.find(x=>x?.id===A?.factoryId||String(x?.factoryAddress||"").toLowerCase()===String(A?.factoryAddress||"").toLowerCase());return Eo({scanner:a,discovery:A,descriptor:I,routeFn:e.routeFn||Bt,observedAt:new Date().toISOString()})},observedAt:new Date().toISOString()});return{candidates:b.candidates,cursor:b.cursor}},evaluate:async p=>vo(p),prepareFn:e.prepareFn||(p=>Yt({...p,scanner:a})),queueFn:e.queueFn||(p=>Qt(p,t))})}function Ra({env:e,factories:t,strategy:r,options:n}){let o=n.solanaScanner||mo(),s=n.solanaRouteFn||Gt,i=n.solanaQuoteScanner||Yn({routeFn:s}),a=e.ORACLE_LAUNCH_RADAR_STORE_PATH||se.join(pr(e),"launch-radar","state-solana.json"),c=lr({path:a});return sr({store:c,strategy:r,discover:async({cursor:l})=>{let d=await ot({discover:()=>fo({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 Eo({scanner:i,discovery:{...p,quoteAsset:p.quoteAsset||he},descriptor:f,routeFn:s,observedAt:new Date().toISOString()})},observedAt:new Date().toISOString()});return{candidates:d.candidates,cursor:d.cursor}},evaluate:async l=>vo(l),prepareFn:n.prepareFn||(l=>Yt({...l,scanner:i})),queueFn:n.queueFn||(l=>Qt(l,e))})}async function Oo(e={}){let t=e.env||process.env,r=t.ORACLE_LAUNCH_RADAR_FACTORIES_DIR;if(!r||!se.isAbsolute(r))throw new Error("ORACLE_LAUNCH_RADAR_FACTORIES_DIR must be an absolute directory");let n=at.lstatSync(r);if(n.isSymbolicLink()||!n.isDirectory())throw new Error("factories dir must be a regular directory");let o=at.readdirSync(r).filter(i=>i.endsWith(".json")).sort();if(o.length===0)throw new Error("factories dir contains no json manifests");let s=[];for(let i of o){let a=i.endsWith(".json")?i.slice(0,-5):i,c={...t,ORACLE_LAUNCH_RADAR_FACTORIES_FILE:se.join(r,i),ORACLE_LAUNCH_RADAR_STORE_PATH:se.join(t.ORACLE_LAUNCH_RADAR_STORE_DIR||se.join(pr(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 _a=Object.freeze({OK:"ok",DEGRADED:"degraded",UNKNOWN:"unknown"}),Yu=Object.freeze({fresh:0,stale:1,down:2});var Xu=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 Pa from"node:os";import Io from"node:path";var ja="oracle.launch-radar.data-plane.v1";function Ba(e){return String(e?.message||e||"unknown error").slice(0,300)}function Ua(e={}){return e.configDir||process.env.ORACLE_CONFIG_DIR||Io.join(Pa.homedir(),".config","oracle")}function qa(e={}){return e.storePath||process.env.LAUNCH_RADAR_STORE_PATH||Io.join(Ua(e),"launch-radar","state.json")}function Da(e={}){let t=qa(e);try{return{ok:!0,path:t,state:ho({path:t})}}catch(r){return{ok:!1,path:t,error:Ba(r)}}}function $a(){return process.env.ORACLE_AUTONOMOUS_TRADING==="1"}function mr(e={},t={}){let r=Da(t),n={schema:ja,storePath:r.path,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,autonomousTradingEnvSet:$a()};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