@oracle-agent/oracle 0.24.9 → 0.24.10

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.
@@ -45,7 +45,7 @@ ${A.format(t)}
45
45
  ${s}`;break;case"retry":qd(s)&&(t[n]=s);break;case"id":Od(s)&&(t[n]=s);break;case"event":s.length>0&&(t[n]=s);break}}processEvent(A){A.retry&&qd(A.retry)&&(this.state.reconnectionTime=parseInt(A.retry,10)),A.id&&Od(A.id)&&(this.state.lastEventId=A.id),A.data!==void 0&&this.push({type:A.event||"message",options:{data:A.data,lastEventId:this.state.lastEventId,origin:this.state.origin}})}clearEvent(){this.event={data:void 0,event:void 0,id:void 0,retry:void 0}}};Wd.exports={EventSourceStream:Vu}});var ef=f((Rv,jd)=>{"use strict";var{pipeline:mM}=d("node:stream"),{fetching:yM}=mn(),{makeRequest:DM}=pr(),{webidl:LA}=Qe(),{EventSourceStream:bM}=Pd(),{parseMIMEType:kM}=De(),{createFastMessageEvent:FM}=kr(),{isNetworkError:_d}=pn(),{delay:RM}=Ju(),{kEnumerableProperty:Nt}=v(),{environmentSettingsObject:Zd}=Me(),zd=!1,Kd=3e3,vn=0,Xd=1,Yn=2,SM="anonymous",NM="use-credentials",Ur=class e extends EventTarget{#e={open:null,error:null,message:null};#A=null;#t=!1;#s=vn;#n=null;#r=null;#o;#i;constructor(A,t={}){super(),LA.util.markAsUncloneable(this);let r="EventSource constructor";LA.argumentLengthCheck(arguments,1,r),zd||(zd=!0,process.emitWarning("EventSource is experimental, expect them to change at any time.",{code:"UNDICI-ES"})),A=LA.converters.USVString(A,r,"url"),t=LA.converters.EventSourceInitDict(t,r,"eventSourceInitDict"),this.#o=t.dispatcher,this.#i={lastEventId:"",reconnectionTime:Kd};let n=Zd,s;try{s=new URL(A,n.settingsObject.baseUrl),this.#i.origin=s.origin}catch(a){throw new DOMException(a,"SyntaxError")}this.#A=s.href;let o=SM;t.withCredentials&&(o=NM,this.#t=!0);let i={redirect:"follow",keepalive:!0,mode:"cors",credentials:o==="anonymous"?"same-origin":"omit",referrer:"no-referrer"};i.client=Zd.settingsObject,i.headersList=[["accept",{name:"accept",value:"text/event-stream"}]],i.cache="no-store",i.initiator="other",i.urlList=[new URL(this.#A)],this.#n=DM(i),this.#c()}get readyState(){return this.#s}get url(){return this.#A}get withCredentials(){return this.#t}#c(){if(this.#s===Yn)return;this.#s=vn;let A={request:this.#n,dispatcher:this.#o},t=r=>{_d(r)&&(this.dispatchEvent(new Event("error")),this.close()),this.#a()};A.processResponseEndOfBody=t,A.processResponse=r=>{if(_d(r))if(r.aborted){this.close(),this.dispatchEvent(new Event("error"));return}else{this.#a();return}let n=r.headersList.get("content-type",!0),s=n!==null?kM(n):"failure",o=s!=="failure"&&s.essence==="text/event-stream";if(r.status!==200||o===!1){this.close(),this.dispatchEvent(new Event("error"));return}this.#s=Xd,this.dispatchEvent(new Event("open")),this.#i.origin=r.urlList[r.urlList.length-1].origin;let i=new bM({eventSourceSettings:this.#i,push:a=>{this.dispatchEvent(FM(a.type,a.options))}});mM(r.body.stream,i,a=>{a?.aborted===!1&&(this.close(),this.dispatchEvent(new Event("error")))})},this.#r=yM(A)}async#a(){this.#s!==Yn&&(this.#s=vn,this.dispatchEvent(new Event("error")),await RM(this.#i.reconnectionTime),this.#s===vn&&(this.#i.lastEventId.length&&this.#n.headersList.set("last-event-id",this.#i.lastEventId,!0),this.#c()))}close(){LA.brandCheck(this,e),this.#s!==Yn&&(this.#s=Yn,this.#r.abort(),this.#n=null)}get onopen(){return this.#e.open}set onopen(A){this.#e.open&&this.removeEventListener("open",this.#e.open),typeof A=="function"?(this.#e.open=A,this.addEventListener("open",A)):this.#e.open=null}get onmessage(){return this.#e.message}set onmessage(A){this.#e.message&&this.removeEventListener("message",this.#e.message),typeof A=="function"?(this.#e.message=A,this.addEventListener("message",A)):this.#e.message=null}get onerror(){return this.#e.error}set onerror(A){this.#e.error&&this.removeEventListener("error",this.#e.error),typeof A=="function"?(this.#e.error=A,this.addEventListener("error",A)):this.#e.error=null}},$d={CONNECTING:{__proto__:null,configurable:!1,enumerable:!0,value:vn,writable:!1},OPEN:{__proto__:null,configurable:!1,enumerable:!0,value:Xd,writable:!1},CLOSED:{__proto__:null,configurable:!1,enumerable:!0,value:Yn,writable:!1}};Object.defineProperties(Ur,$d);Object.defineProperties(Ur.prototype,$d);Object.defineProperties(Ur.prototype,{close:Nt,onerror:Nt,onmessage:Nt,onopen:Nt,readyState:Nt,url:Nt,withCredentials:Nt});LA.converters.EventSourceInitDict=LA.dictionaryConverter([{key:"withCredentials",converter:LA.converters.boolean,defaultValue:()=>!1},{key:"dispatcher",converter:LA.converters.any}]);jd.exports={EventSource:Ur,defaultReconnectionTime:Kd}});var nf=f((Sv,U)=>{"use strict";var UM=sr(),Af=Hr(),MM=or(),LM=$Q(),TM=ir(),xM=cc(),vM=wB(),YM=RB(),tf=V(),Wo=v(),{InvalidArgumentError:Oo}=tf,Mr=BI(),GM=qr(),JM=Oc(),HM=XI(),VM=_c(),qM=Nc(),OM=Ps(),{getGlobalDispatcher:rf,setGlobalDispatcher:WM}=to(),PM=ro(),_M=Ts(),ZM=xs();Object.assign(Af.prototype,Mr);U.exports.Dispatcher=Af;U.exports.Client=UM;U.exports.Pool=MM;U.exports.BalancedPool=LM;U.exports.Agent=TM;U.exports.ProxyAgent=xM;U.exports.EnvHttpProxyAgent=vM;U.exports.RetryAgent=YM;U.exports.RetryHandler=OM;U.exports.DecoratorHandler=PM;U.exports.RedirectHandler=_M;U.exports.createRedirectInterceptor=ZM;U.exports.interceptors={redirect:nh(),retry:oh(),dump:ah(),dns:lh()};U.exports.buildConnector=GM;U.exports.errors=tf;U.exports.util={parseHeaders:Wo.parseHeaders,headerNameToString:Wo.headerNameToString};function Gn(e){return(A,t,r)=>{if(typeof t=="function"&&(r=t,t=null),!A||typeof A!="string"&&typeof A!="object"&&!(A instanceof URL))throw new Oo("invalid url");if(t!=null&&typeof t!="object")throw new Oo("invalid opts");if(t&&t.path!=null){if(typeof t.path!="string")throw new Oo("invalid opts.path");let o=t.path;t.path.startsWith("/")||(o=`/${o}`),A=new URL(Wo.parseOrigin(A).origin+o)}else t||(t=typeof A=="object"?A:{}),A=Wo.parseURL(A);let{agent:n,dispatcher:s=rf()}=t;if(n)throw new Oo("unsupported opts.agent. Did you mean opts.client?");return e.call(s,{...t,origin:A.origin,path:A.search?`${A.pathname}${A.search}`:A.pathname,method:t.method||(t.body?"PUT":"GET")},r)}}U.exports.setGlobalDispatcher=WM;U.exports.getGlobalDispatcher=rf;var zM=mn().fetch;U.exports.fetch=async function(A,t=void 0){try{return await zM(A,t)}catch(r){throw r&&typeof r=="object"&&Error.captureStackTrace(r),r}};U.exports.Headers=yt().Headers;U.exports.Response=pn().Response;U.exports.Request=pr().Request;U.exports.FormData=Kr().FormData;U.exports.File=globalThis.File??d("node:buffer").File;U.exports.FileReader=kC().FileReader;var{setGlobalOrigin:KM,getGlobalOrigin:XM}=ua();U.exports.setGlobalOrigin=KM;U.exports.getGlobalOrigin=XM;var{CacheStorage:$M}=xC(),{kConstruct:jM}=Do();U.exports.caches=new $M(jM);var{deleteCookie:eL,getCookies:AL,getSetCookies:tL,setCookie:rL}=_C();U.exports.deleteCookie=eL;U.exports.getCookies=AL;U.exports.getSetCookies=tL;U.exports.setCookie=rL;var{parseMIMEType:nL,serializeAMimeType:sL}=De();U.exports.parseMIMEType=nL;U.exports.serializeAMimeType=sL;var{CloseEvent:oL,ErrorEvent:iL,MessageEvent:aL}=kr();U.exports.WebSocket=Hd().WebSocket;U.exports.CloseEvent=oL;U.exports.ErrorEvent=iL;U.exports.MessageEvent=aL;U.exports.request=Gn(Mr.request);U.exports.stream=Gn(Mr.stream);U.exports.pipeline=Gn(Mr.pipeline);U.exports.connect=Gn(Mr.connect);U.exports.upgrade=Gn(Mr.upgrade);U.exports.MockClient=JM;U.exports.MockPool=VM;U.exports.MockAgent=HM;U.exports.mockErrors=qM;var{EventSource:cL}=ef();U.exports.EventSource=cL});import Lr from"node:net";import uL from"node:dns";function Po(e){let A=String(e).toLowerCase().split("%")[0];if((A.match(/::/g)||[]).length>1)return null;let t=l=>{if(!l)return[];let u=l.split(":"),g=u.at(-1);if(g?.includes(".")){let E=g.split(".").map(Number);if(E.length!==4||E.some(Q=>!Number.isInteger(Q)||Q<0||Q>255))return null;u.splice(u.length-1,1,(E[0]<<8|E[1]).toString(16),(E[2]<<8|E[3]).toString(16))}return u.some(E=>!/^[0-9a-f]{1,4}$/.test(E))?null:u.map(E=>Number.parseInt(E,16))},[r,n]=A.split("::"),s=t(r),o=t(n);if(!s||!o)return null;let i=A.includes("::"),a=8-s.length-o.length;if(!i&&a!==0||i&&a<1)return null;let c=[...s,...Array(Math.max(0,a)).fill(0),...o];return c.length!==8?null:Uint8Array.from(c.flatMap(l=>[l>>8,l&255]))}function qu(e,A,t){let r=Math.floor(t/8),n=t%8;for(let o=0;o<r;o+=1)if(e[o]!==A[o])return!1;if(!n)return!0;let s=255<<8-n;return(e[r]&s)===(A[r]&s)}function Ou(e){if(Lr.isIPv4(e)){let A=e.split(".").map(Number);return!(A[0]===0||A[0]===10||A[0]===127||A[0]>=224||A[0]===100&&A[1]>=64&&A[1]<=127||A[0]===169&&A[1]===254||A[0]===172&&A[1]>=16&&A[1]<=31||A[0]===192&&(A[1]===0||A[1]===2||A[1]===168)||A[0]===192&&A[1]===88&&A[2]===99||A[0]===198&&(A[1]===18||A[1]===19||A[1]===51)||A[0]===203&&A[1]===0&&A[2]===113)}if(Lr.isIPv6(e)){let A=Po(e);if(!A)return!1;let t=Po("::ffff:0:0");return qu(A,t,96)?Ou([...A.slice(12)].join(".")):qu(A,Po("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([n,s])=>qu(A,Po(n),s)):!1}return!1}function gL(e){let A;try{A=new URL(String(e))}catch{return{ok:!1,error:`not a valid URL: ${String(e).slice(0,120)}`}}if(A.protocol!=="http:"&&A.protocol!=="https:")return{ok:!1,error:`refused protocol ${A.protocol} (only http/https)`};let t=A.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(lL.has(t)||t.endsWith(".localhost")||t.endsWith(".internal"))return{ok:!1,error:`refused internal host ${t}`};let r=Lr.isIP(t);return r!==0&&!Ou(t)?{ok:!1,error:`refused private address ${t}`}:{ok:!0,url:A,host:t,isLiteralIp:r!==0}}async function sf(e,{lookupFn:A=uL.promises.lookup}={}){let t=gL(e);if(!t.ok)return t;if(t.isLiteralIp)return{ok:!0,url:t.url};let r;try{r=await A(t.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${t.host} did not resolve`}}return!Array.isArray(r)||r.length===0||r.some(n=>!Ou(n.address))?{ok:!1,error:`refused: ${t.host} resolves to a non-public address`}:{ok:!0,url:t.url,addresses:r}}async function of(){let e,A;try{let i=await Promise.resolve().then(()=>ep(nf(),1));e=i.Agent,A=i.fetch}catch{return null}if(typeof e!="function"||typeof A!="function")return null;let t=i=>String(i).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),r=new Map,n=i=>(Array.isArray(i)?i:[i]).map(a=>typeof a=="string"?{address:a}:a).filter(a=>a&&a.address).map(a=>({address:a.address,family:a.family||(Lr.isIPv6(a.address)?6:4)})),s=i=>{let a=t(i);if(Lr.isIP(a))return[{address:a,family:Lr.isIPv6(a)?6:4}];let c=r.get(a);if(!c||!c.length)throw new Error(`refused: unpinned host ${i} during pinned fetch`);return c},o=new e({connect:{lookup(i,a,c){let l;try{l=s(i)}catch(u){return c(u)}return a?.all?c(null,l):c(null,l[0].address,l[0].family)}}});return{dispatcher:o,fetch:(i,a={})=>A(i,{...a,dispatcher:o}),pin(i,a,c){r.set(t(i),n(typeof a=="string"?[{address:a,family:c}]:a))},resolve:s,async close(){try{await o.destroy()}catch{}}}}var lL,af=ae(()=>{lL=new Set(["localhost","metadata.google.internal","metadata.goog"])});import{createHash as EL}from"node:crypto";function hL(e){let A=String(e||"").toLowerCase();return gf.includes(A)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(A)}function CL(e){let A={};for(let[t,r]of Object.entries(e||{}))hL(t)||(A[t]=r);return A}function dL(e,A){if(!e)throw new Error(`HTTP redirect from ${A} missing Location`);let t=new URL(String(e),String(A));if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error(`HTTP redirect from ${A} used unsupported protocol ${t.protocol}`);return t.toString()}function fL(e,A){return new URL(String(e)).origin===new URL(String(A)).origin}function pL(e,A,t){let r={};for(let[a,c]of Object.entries(t||{}))r[a.toLowerCase()]=c;let n=Object.keys(r).filter(a=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(a)),o=[...new Set([...gf,...n])].sort().map(a=>`${a}=${r[a]??""}`).join(`
46
46
  `),i=EL("sha256").update(o).digest("hex").slice(0,32);return`${e} ${A} ${i}`}function wL(e,A){let t=Number(A);return Number.isFinite(t)&&t>0?Math.min(t*1e3,uf):Math.min(250*2**e,uf)+Math.floor(Math.random()*100)}async function yL(e,{fetchImpl:A,method:t,headers:r,body:n,timeoutMs:s,lookupFn:o,realFetch:i}){let a=new AbortController,c=setTimeout(()=>a.abort(),s),l=null,u=A;try{let g=String(e),E={...r||{}};for(let Q=0;Q<=lf;Q+=1){let h=await u(g,{method:t,headers:E,body:n,signal:a.signal,redirect:"manual"}),B=await h.text(),I=null;if(B)try{I=JSON.parse(B)}catch{I=null}if(IL.has(h.status)){if(t!=="GET"&&t!=="HEAD"){let y=new Error(`HTTP ${h.status} ${t} ${g} redirected non-idempotent request`);throw y.status=h.status,y.body=I??B.slice(0,300),y}if(Q===lf)throw new Error(`HTTP redirect loop for ${e}`);let C=dL(h.headers?.get?.("location"),g);if(!fL(C,g)){let y=await sf(C,o?{lookupFn:o}:{});if(!y.ok){let L=new Error(`HTTP redirect from ${g} ${y.error}`);throw L.status=h.status,L}E=CL(E),i&&y.addresses?.length&&(l||(l=await of()),l&&(l.pin(new URL(C).hostname,y.addresses[0].address,y.addresses[0].family),u=l.fetch))}g=C;continue}if(!h.ok){let C=new Error(`HTTP ${h.status} ${t} ${g}`);throw C.status=h.status,C.retryAfter=h.headers?.get?.("retry-after")??null,C.body=I??B.slice(0,300),C}return I??B}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(c),l&&await l.close()}}async function re(e,A={}){let t=A.fetchImpl||globalThis.fetch;if(typeof t!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let r=A.timeoutMs??12e3,n=(A.method||"GET").toUpperCase(),s={Accept:"application/json",...A.headers||{}},o=A.body;o!=null&&typeof o!="string"&&(s["Content-Type"]=s["Content-Type"]||"application/json",o=JSON.stringify(o));let i=Number.isInteger(A.retries)?Math.max(A.retries,0):BL,a=A.lookupFn,c=!A.fetchImpl,l=async()=>{let h;for(let B=0;B<=i;B++)try{return await yL(e,{fetchImpl:t,method:n,headers:s,body:o,timeoutMs:r,lookupFn:a,realFetch:c})}catch(I){h=I;let C=I?.status,m=I?.name==="AbortError",y=new Set([408,425,429]),L=C!=null?y.has(C)||QL.has(C)&&cf.has(n):!m&&cf.has(n);if(B===i||!L)throw I;await mL(wL(B,I?.retryAfter))}throw h};if(!(A.dedupe!==!1&&n==="GET"&&o==null))return l();let g=pL(n,e,s),E=Wu.get(g);if(E)return E;let Q=l().finally(()=>Wu.delete(g));return Wu.set(g,Q),Q}var QL,cf,BL,uf,gf,IL,lf,Wu,mL,TA=ae(()=>{af();QL=new Set([408,425,429,500,502,503,504]),cf=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),BL=2,uf=4e3,gf=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],IL=new Set([301,302,303,307,308]),lf=3;Wu=new Map;mL=e=>new Promise(A=>setTimeout(A,e))});import{readFileSync as DL}from"node:fs";import{homedir as bL}from"node:os";import{join as _o}from"node:path";function kL(){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){let t=(process.env.ORACLE_EXEC_ENV_FILE||"").trim();return t?[t]:[]}let e=(process.env.ORACLE_EXEC_ENV_FILE||process.env.MAD_EXEC_ENV_FILE||"").trim(),A=bL();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let t=(process.env.ORACLE_CONFIG_DIR||_o(A,".config","oracle")).trim();return[e,_o(t,"exec.env")].filter(Boolean)}return[e,_o(A,".config","oracle","exec.env"),_o(A,".config","mad-desk","exec.env")].filter(Boolean)}function Ef(e,A,t){let r=e??process.env[A]??process.env[t];if(!String(r||"").trim())for(let n of kL())try{let s=DL(n,"utf8"),o=s.match(new RegExp(`^${A}=(.*)$`,"m"))||s.match(new RegExp(`^${t}=(.*)$`,"m"));if(o&&(r=o[1].trim(),r))break}catch{}if(!String(r||"").trim())throw new Error(`${A} required for attestation. Set it in the environment, or place ${A}=<value> in ~/.config/oracle/exec.env`);return r}var Qf=ae(()=>{});var Bf=ae(()=>{});import{createHash as FL,createHmac as hf,timingSafeEqual as RL}from"node:crypto";function zo(e){return Array.isArray(e)?`[${e.map(zo).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(A=>`${JSON.stringify(A)}:${zo(e[A])}`).join(",")}}`:JSON.stringify(e??null)}function Cf(e,{required:A=!1}={}){try{return Ef(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(t){if(A)throw t;return null}}function _u(e){let{signature:A,...t}=e;return t}function df(e,{secret:A}={}){let t=Cf(A);return t?{...e,signature:hf("sha256",t).update(zo(_u(e))).digest("hex")}:e}function SL(e){let A=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(A)||A.length<10||A.length%2!==0)throw new Error("auto-slippage calldata must be even-length hex with a selector");return FL("sha256").update(Buffer.from(A.slice(2),"hex")).digest("hex")}function xA(e,{chainId:A,venue:t,data:r,secret:n}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");if(Number(e.chainId)!==Number(A))throw new Error("auto-slippage guard chain mismatch");if(String(e.venue).toLowerCase()!==String(t||"").toLowerCase())throw new Error("auto-slippage guard venue mismatch");let s=Cf(n);if(s){let E=hf("sha256",s).update(zo(_u(e))).digest("hex");if(!NL(e.signature,E))throw new Error("auto-slippage guard signature mismatch \u2014 refusing to bind a guard this Oracle did not issue")}let o=Number(e.selectedBps),i=Number(e.capBps);if(!Number.isInteger(o)||o<0||o>Zo||!Number.isInteger(i)||i<0||i>Zo||o>i)throw new Error("auto-slippage guard bounds are invalid");let a=BigInt(e.quoteAmountOut??0),c=BigInt(e.minAmountOut??0);if(a<=0n||c<=0n)throw new Error("auto-slippage guard amounts must be positive");let l=a*BigInt(1e4-o),u=l/10000n;if(l%10000n!==0n&&(u+=1n),c<u)throw new Error("auto-slippage guard is under-protected relative to its quote");let g=LL(r);if(g!=null&&g!==c)throw new Error(`auto-slippage: calldata encodes floor ${g}, not the guard floor ${c} \u2014 refusing to bind`);return df({..._u(e),calldataHash:SL(r)},{secret:n})}function NL(e,A){let t=Buffer.from(String(e??""),"utf8"),r=Buffer.from(String(A??""),"utf8");return t.length!==r.length||t.length===0?!1:RL(t,r)}function Pu(e,A=0){let t=Number(e);return Number.isFinite(t)?t:A}function UL(e){let A=e==null?Zo:Number(e);if(!Number.isInteger(A)||A<0)throw new Error("auto-slippage cap must be a non-negative integer bps value");return Math.min(A,Zo)}function Tr({liquidityUsd:e,priceChange5m:A=0,quoteAgeMs:t=0,crossChain:r=!1,requestedCapBps:n}={}){let s=Pu(e,0),o=s>0?s>=25e4?5:s>=1e5?10:s>=5e4?20:s>=1e4?40:70:r?30:10,i=Math.min(60,Math.abs(Pu(A,0))*2),a=Math.min(40,Math.floor(Math.max(0,Pu(t,0))/5e3)*5),c=Math.max(25,Math.ceil(20+o+i+a)),l=UL(n);return{mode:"auto",requiredBps:c,selectedBps:Math.min(c,l),capBps:l,executable:c<=l}}function ML({chainId:e,venue:A,quoteAmountOut:t,liquidityUsd:r,priceChange5m:n=0,quoteAgeMs:s=0,crossChain:o=!1,requestedCapBps:i,quotedAtMs:a=Date.now(),ttlMs:c=If,secret:l}={}){let u=BigInt(t??0);if(u<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let g=Tr({liquidityUsd:r,priceChange5m:n,quoteAgeMs:s,crossChain:o,requestedCapBps:i});if(!g.executable)throw new Error(`auto-slippage requires ${g.requiredBps} bps above hard/requested cap ${g.capBps}; route blocked`);let E=Number(a);if(!Number.isFinite(E))throw new Error("auto-slippage: quotedAtMs must be a finite number");let Q=Math.min(3e4,Math.max(1e3,Number(c)||If)),h=u*BigInt(1e4-g.selectedBps),B=h/10000n;if(h%10000n!==0n&&(B+=1n),B>u&&(B=u),u>0n&&B<=0n)throw new Error(`auto-slippage: quote ${u} is too small to express a ${g.selectedBps} bps floor without rounding to zero`);let I=Number((u-B)*10000n/(u===0n?1n:u));if(I>g.capBps)throw new Error(`auto-slippage: realised floor implies ${I} bps, above cap ${g.capBps} \u2014 refusing to issue a guard weaker than advertised`);return df({mode:"auto",chainId:Number(e),venue:String(A||"unknown"),quoteAmountOut:u.toString(),minAmountOut:B.toString(),requiredBps:g.requiredBps,selectedBps:g.selectedBps,capBps:g.capBps,quotedAtMs:E,expiresAtMs:E+Q},{secret:l})}function LL(e){let A=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(A)||A.length<10||A.length%2!==0)return null;let t=A.slice(0,10).toLowerCase(),r=[];for(let s=10;s+64<=A.length;s+=64)r.push(A.slice(s,s+64));let n=s=>r[s]==null?null:BigInt("0x"+r[s]);switch(t){case"0x414bf389":return n(6);case"0x04e45aaf":return n(5);case"0xc04b8d59":{let s=n(0);if(s==null)return null;let o=Number(s)/32;return!Number.isInteger(o)||o<0?null:n(o+4)}case"0xb858183f":{let s=n(0);if(s==null)return null;let o=Number(s)/32;return!Number.isInteger(o)||o<0?null:n(o+3)}case"0xa026383e":return n(6);case"0x38ed1739":case"0x5c11d795":return n(1);case"0x7ff36ab5":case"0xb6f9de95":return n(0);case"0x18cbafe5":case"0x791ac947":return n(1);default:return null}}function ye(e,{chainId:A,venue:t,amountOut:r,liquidityUsd:n,priceChange5m:s,crossChain:o,requestedCapBps:i,quotedAtMs:a=Date.now(),ttlMs:c}={}){let l=ML({chainId:A,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:s,crossChain:o,requestedCapBps:i,quotedAtMs:a,ttlMs:c});return{...e,autoSlippage:l,amountOutMinimum:l.minAmountOut}}var Zo,If,tt=ae(()=>{Qf();Bf();Zo=100,If=2e4});function Zu(e){let A=String(e||"").trim();return/^0x[0-9a-fA-F]{40}$/.test(A)?A:Jn}var Jn,zu=ae(()=>{Jn="0x000000000000000000000000000000000000dEaD"});import{createHash as TL,createHmac as xL,timingSafeEqual as zv}from"node:crypto";function Ku(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Ku).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Ku(e[t])}`).join(",")}}`}function ff(e){let A=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return A.length>=16?A:""}function pf(e=process.env){return ff(process.env)||ff(e)}function GL(e){let{oraclePrepared:A,prepareHash:t,prepareMac:r,note:n,...s}=e||{};return s}function JL(e){let A=GL(e);return TL("sha256").update(Ku(A)).digest("hex")}function HL(e,A=pf()){return A?xL("sha256",A).update(String(e)).digest("hex"):""}function de(e,{provider:A,kind:t,env:r=process.env}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let n={...e,provider:e.provider||A,kind:e.kind||t,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1};if(!n.provider)throw new Error("stampPrepared: provider required");if(!n.kind)throw new Error("stampPrepared: kind required");let s=Date.now(),o=s+YL,a={...n,preparedAt:s,expiresAt:o,prepareVersion:vL},c=JL(a),l=pf(r),u=l?HL(c,l):void 0,g={...a,oraclePrepared:!0,prepareHash:c};return u&&(g.prepareMac=u),g}var vL,YL,Kv,vA=ae(()=>{vL=2,YL=300*1e3,Kv=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Contract as VL,JsonRpcProvider as qL}from"ethers";function zL(e){return ZL.test(String(e||""))}async function wf(e,{contract:A=OL,rpc:t=PL,chainId:r=WL,balanceOf:n}={}){if(!zL(e))throw new Error("invalid-address");if(n)return BigInt(await n(e));let s=new qL(t,r,{staticNetwork:!0}),o=new VL(A,_L,s);return BigInt(await o.balanceOf(e))}var OL,WL,PL,_L,ZL,mf=ae(()=>{OL="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",WL=999,PL="https://rpc.hyperliquid.xyz/evm",_L=["function balanceOf(address owner) view returns (uint256)"],ZL=/^0x[a-fA-F0-9]{40}$/});import{existsSync as KL,readFileSync as XL,lstatSync as $L}from"node:fs";import{homedir as yf}from"node:os";import{join as Xu}from"node:path";function AT(e){let A=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(Df,A)?Df[A]:eT}function oT(e=process.env){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){if(e[bf])return String(e[bf]);let A=e.ORACLE_CONFIG_DIR||Xu(yf(),".config","oracle");return Xu(A,"fee-recipient")}return Xu(yf(),".config","oracle","fee-recipient")}function iT(e=process.env){try{let A=oT(e);if(!KL(A)||$L(A).isSymbolicLink())return"";let t=XL(A,"utf8").trim().toLowerCase();return/^0x[a-f0-9]{40}$/.test(t)?t:""}catch{return""}}function aT(e,{fallback:A=0}={}){if(e==null)return A;if(String(e).trim()==="")return 0;let t=Number(e);return!Number.isFinite(t)||t<=0?0:Math.min(Math.floor(t),jL)}function cT({env:e=process.env,action:A="swap",admin:t=!1}={}){let r=String(e[rT]||"").trim(),n=String(e[nT]||sT).trim();if(t===!0)return{bps:0,recipient:"",integrator:n,action:A,applies:!1,reason:"admin-oracle"};let s=AT(A),o=aT(e[tT],{fallback:r?s:0}),i=Math.min(o,s);if(!i)return{bps:0,recipient:"",integrator:n,action:A,applies:!1,reason:"not-configured"};if(!/^0x[a-fA-F0-9]{40}$/.test(r))return{bps:0,recipient:"",integrator:n,action:A,applies:!1,reason:"no-recipient"};let a=iT(e);return!a||a!==r.toLowerCase()?{bps:0,recipient:"",integrator:n,action:A,applies:!1,reason:"recipient-not-pinned"}:{bps:i,recipient:r,integrator:n,action:A,applies:!0,reason:"configured"}}async function Ko({wallet:e,env:A=process.env,action:t="swap",holderCheck:r={},admin:n=!1}={}){let s=cT({env:A,action:t,admin:n});if(n===!0)return{...s,holderVerificationStatus:"admin-oracle"};let o=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(o))return{...s,holderVerificationStatus:"wallet-required"};try{return BigInt(await wf(o,r))>0n?{...s,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...s,holderVerificationStatus:"non-holder"}}catch{return{...s,holderVerificationStatus:"unavailable"}}}function kf(e){return e?.applies?`Oracle routing fee ${e.bps} bps (${(e.bps/100).toFixed(2)}%) to ${e.recipient}.`:e?.reason==="admin-oracle"?"No Oracle fee (admin Oracle).":e?.reason==="locals-only-holder"?"No Oracle fee (Locals Only holder).":"No Oracle fee."}function Ff(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}function Rf(e){return e?.applies?{partner:e.integrator,partnerFeeBps:String(e.bps),partnerAddress:e.recipient}:{}}var jL,eT,Df,tT,rT,nT,bf,sT,Xo=ae(()=>{mf();jL=100,eT=5,Df=Object.freeze({swap:5,bridge:5,perps:0,nft:0});tT="ORACLE_INTEGRATOR_FEE_BPS",rT="ORACLE_INTEGRATOR_FEE_RECIPIENT",nT="ORACLE_INTEGRATOR_ID",bf="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",sT="oracle"});var Uf={};vt(Uf,{LIFI_API:()=>Nf,lifiChains:()=>QT,lifiHealth:()=>gT,lifiPrepare:()=>ET,lifiQuote:()=>$o});function ju(e={}){return(e.baseUrl||process.env.LIFI_API_URL||Nf).replace(/\/$/,"")}function lT(e){let A=String(e||$u).toLowerCase();return A===$u.toLowerCase()||A===uT}function Sf(e,A){let t=String(e||"").trim();if(!/^0x[0-9a-fA-F]{40}$/.test(t))throw new Error(`lifi: ${A} must be a 20-byte address`);return t.toLowerCase()}async function gT(e={}){let A=await re(`${ju(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3}),t=Array.isArray(A)?A.length:A?.chains?.length||0;return{ok:t>0,chainCount:t}}async function $o(e={},A={}){let{fromChain:t,toChain:r=t,fromToken:n=$u,toToken:s,fromAmount:o,fromAddress:i=Jn}=e;if(t==null||!s||!o)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let a=new URLSearchParams({fromChain:String(t),toChain:String(r),fromToken:n,toToken:s,fromAmount:String(o),fromAddress:i}),c=Tr({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(r)!==Number(t),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!c.executable)throw new Error(`lifi: route requires ${c.requiredBps} bps above cap ${c.capBps}`);a.set("slippage",String(c.selectedBps/1e4));let l=await Ko({wallet:e.fromAddress,env:A.env,action:e.feeAction||"swap",holderCheck:A.holderCheck});for(let[B,I]of Object.entries(Ff(l)))a.set(B,I);let u=await re(`${ju(A)}/quote?${a}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??2e4}),g=u?.estimate?.toAmount||u?.toAmount;if(!g)return{...u,autoSlippagePolicy:c,oracleFee:l};let E=u?.transactionRequest?.to||u?.estimate?.approvalAddress||"lifi",Q=ye(u,{chainId:Number(t),venue:E,amountOut:g,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(r)!==Number(t),requestedCapBps:e.maxSlippageBps??e.slippageBps}),h=u?.estimate?.toAmountMin||u?.toAmountMin;if(h!=null&&BigInt(h)<BigInt(Q.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...Q,oracleFee:l}}async function ET(e={},A={}){let t=await $o(e,A),r=t?.transactionRequest;if(!r?.to||!r?.data)throw new Error("lifi: quote did not return an executable transactionRequest");let n=Number(e.fromChain);if(r.chainId!=null&&Number(r.chainId)!==n)throw new Error("lifi: transaction chain mismatch");if(e.fromAddress&&r.from&&String(r.from).toLowerCase()!==String(e.fromAddress).toLowerCase())throw new Error("lifi: transaction sender mismatch");let s=null;if(!lT(e.fromToken)){let o=t?.estimate?.approvalAddress||t?.approvalAddress;if(!o)throw new Error("lifi: ERC20 route missing approvalAddress");let i=t?.action?.fromToken?.address||t?.estimate?.fromToken?.address||e.fromToken;s={token:Sf(i,"approval token"),spender:Sf(o,"approval spender"),amount:String(e.fromAmount)}}return de({provider:"lifi",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:t,autoSlippage:t.autoSlippage,requiresApproval:s,transaction:{chainId:n,from:r.from||e.fromAddress,to:r.to,data:r.data,value:r.value??"0x0",...r.gasLimit!=null?{gasLimit:r.gasLimit}:{},slippageGuard:xA(t.autoSlippage,{chainId:n,venue:r.to,data:r.data})}},{provider:"lifi",kind:"lifi-tx"})}async function QT(e={}){return re(`${ju(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var Nf,$u,uT,el=ae(()=>{TA();tt();zu();vA();Xo();Nf="https://li.quest/v1";$u="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",uT="0x0000000000000000000000000000000000000000"});var Tf={};vt(Tf,{PARASWAP_API:()=>Mf,paraswapHealth:()=>IT,paraswapPrepare:()=>BT,paraswapPrice:()=>jo,paraswapTokens:()=>Lf});function xr(e,A){let t=String(e||"");if(!/^0x[0-9a-fA-F]{40}$/.test(t))throw new Error(`${A} must be a 20-byte token address`);return t.toLowerCase()}async function Lf(e={},A={}){let t=Number(e.chainId||1);return re(`${Al(A)}/tokens/${t}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs})}async function jo(e={},A={}){let t=Number(e.chainId||e.network||1);if(e.amount==null)throw new Error("amount required");let r=new URLSearchParams({srcToken:xr(e.srcToken,"srcToken"),destToken:xr(e.destToken,"destToken"),amount:String(e.amount),srcDecimals:String(Number(e.srcDecimals)),destDecimals:String(Number(e.destDecimals)),side:String(e.side||"SELL").toUpperCase(),network:String(t),version:String(e.version||"6.2")});e.includeDEXS&&r.set("includeDEXS",String(e.includeDEXS)),e.excludeDEXS&&r.set("excludeDEXS",String(e.excludeDEXS));let n=await Ko({wallet:e.userAddress||e.fromAddress,env:A.env,action:e.feeAction||"swap",holderCheck:A.holderCheck});for(let[i,a]of Object.entries(Rf(n)))r.set(i,a);let s=await re(`${Al(A)}/prices?${r}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??2e4}),o=s?.priceRoute?.destAmount;return o?{...ye(s,{chainId:t,venue:s?.priceRoute?.contractAddress||"paraswap-quote",amountOut:o,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,quoteAgeMs:0,requestedCapBps:e.maxSlippageBps??e.slippageBps}),executionReady:!1,executionBlocker:"call prepare to bind the price route to a validated transaction",oracleFee:n}:{...s,executionReady:!1,oracleFee:n}}async function BT(e={},A={}){if(String(e.side||"SELL").toUpperCase()!=="SELL")throw new Error("paraswap: agentic prepare currently supports exact-input SELL only");let t=Number(e.chainId||e.network||1),r=xr(e.userAddress,"userAddress"),n=await jo(e,A),s=n?.priceRoute,o=String(s?.contractAddress||"").toLowerCase();if(!o)throw new Error("paraswap: price route missing contractAddress");let i={srcToken:xr(e.srcToken,"srcToken"),destToken:xr(e.destToken,"destToken"),srcAmount:String(s.srcAmount||e.amount),destAmount:String(n.amountOutMinimum),priceRoute:s,userAddress:r,ignoreChecks:!1,ignoreGasEstimate:!1};e.receiver&&(i.receiver=xr(e.receiver,"receiver"));let a=await re(`${Al(A)}/transactions/${t}`,{method:"POST",body:i,fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??25e3});if(Number(a.chainId??t)!==t)throw new Error("paraswap: transaction chain mismatch");if(String(a.to||"").toLowerCase()!==o)throw new Error("paraswap: transaction target mismatch");if(a.from&&String(a.from).toLowerCase()!==r)throw new Error("paraswap: transaction sender mismatch");return de({provider:"paraswap",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:t,quote:n,autoSlippage:n.autoSlippage,requiresApproval:i.srcToken!=="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"?{token:i.srcToken,spender:s.tokenTransferProxy||o,amount:i.srcAmount}:null,transaction:{chainId:t,from:a.from||r,to:a.to,data:a.data,value:a.value??"0x0",...a.gas!=null?{gasLimit:a.gas}:{},slippageGuard:xA(n.autoSlippage,{chainId:t,venue:a.to,data:a.data})}},{provider:"paraswap",kind:"paraswap-tx"})}async function IT(e={}){let A=await Lf({chainId:1},e),t=Array.isArray(A?.tokens)?A.tokens.length:Object.keys(A?.tokens||{}).length;return{ok:t>0,tokenSample:t}}var Mf,Al,tl=ae(()=>{TA();tt();vA();Xo();Mf="https://api.paraswap.io",Al=(e={})=>(e.baseUrl||process.env.PARASWAP_API_URL||Mf).replace(/\/$/,"")});function ei({provider:e,defaultUrl:A,hosts:t=[],url:r,strict:n=!1}){let o=(String(r??"").trim()||String(A)).replace(/\/$/,"");if(o===String(A).replace(/\/$/,""))return{baseUrl:o,trusted:!0,host:vf(A)};let i;try{i=new URL(o)}catch{throw new Error(`${e}: baseUrl must be an absolute http(s) URL`)}if(i.protocol!=="http:"&&i.protocol!=="https:")throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);let a=i.host;if(!a)throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);if(new Set([vf(A),...t]).has(a)){let l=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(a);return i.protocol==="http:"&&!l?{baseUrl:o,trusted:!1,host:a,reason:"plaintext http downgrade"}:{baseUrl:o,trusted:!0,host:a}}if(String(process.env[xf]||"")==="1")return{baseUrl:o,trusted:!1,host:a};if(n)throw new Error(`${e}: refusing to call non-allowlisted host ${a} (set ${xf}=1 to permit it)`);return{baseUrl:o,trusted:!1,host:a}}function vf(e){let A=new URL(String(e));if(A.protocol!=="http:"&&A.protocol!=="https:")throw new Error("unsupported protocol");return A.host}function Ai(e,A,t){let r={...e};if(!t)return r;for(let[n,s]of Object.entries(A||{}))s&&(r[n]=s);return r}var xf,rl=ae(()=>{xf="ORACLE_ALLOW_CUSTOM_PROVIDER_URL"});var qf={};vt(qf,{ZEROX_API:()=>Yf,zeroxHealth:()=>hT,zeroxPrepare:()=>CT,zeroxPrice:()=>Vf,zeroxQuote:()=>ri});function Gf(e={}){return ei({provider:"zerox",defaultUrl:Yf,hosts:["api.0x.org"],url:e.baseUrl||process.env.ZEROX_API_URL})}function Jf(e={}){return Gf(e).baseUrl}function ti(e={}){return e.apiKey||process.env.ZEROX_API_KEY||process.env.OX_API_KEY||process.env["0X_API_KEY"]||""}function Hf(e={}){return Ai({"0x-version":"v2",accept:"application/json"},{"0x-api-key":ti(e)},Gf(e).trusted)}async function hT(e={}){if(!ti(e))return{ok:!1,configured:!1,error:"ZEROX_API_KEY not set"};try{let A=await Vf({chainId:8453,sellToken:"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",buyToken:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",sellAmount:"1000000000000000"},e);return{ok:!0,configured:!0,buyAmount:A.buyAmount||A.grossBuyAmount}}catch(A){return{ok:!1,configured:!0,error:String(A.message||A).slice(0,160)}}}async function Vf(e={},A={}){if(!ti(A))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:t=8453,sellToken:r,buyToken:n,sellAmount:s,taker:o}=e;if(!r||!n||!s)throw new Error("zeroxPrice requires sellToken, buyToken, sellAmount");let i=new URLSearchParams({chainId:String(t),sellToken:r,buyToken:n,sellAmount:String(s)});return o&&i.set("taker",o),re(`${Jf(A)}/swap/allowance-holder/price?${i}`,{headers:Hf(A),fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3})}async function ri(e={},A={}){if(!ti(A))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:t=8453,sellToken:r,buyToken:n,sellAmount:s,taker:o}=e;if(!r||!n||!s)throw new Error("zeroxQuote requires sellToken, buyToken, sellAmount");let i=Tr({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!i.executable)throw new Error(`0x: route requires ${i.requiredBps} bps above cap ${i.capBps}`);let a=new URLSearchParams({chainId:String(t),sellToken:r,buyToken:n,sellAmount:String(s),slippageBps:String(i.selectedBps)});o&&a.set("taker",o);let c=await re(`${Jf(A)}/swap/allowance-holder/quote?${a}`,{headers:Hf(A),fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3}),l=c?.buyAmount||c?.grossBuyAmount;return l?ye(c,{chainId:t,venue:c?.transaction?.to||c?.to||"0x",amountOut:l,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):{...c,autoSlippagePolicy:i}}async function CT(e={},A={}){if(!e.taker)throw new Error("0x: taker required for executable prepare");let t=await ri(e,A),r=t?.transaction;if(!r?.to||!r?.data)throw new Error("0x: firm quote returned no transaction");let n=Number(e.chainId??8453),s=t?.issues?.allowance?.spender||t?.allowanceTarget;return de({provider:"zerox",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:t,autoSlippage:t.autoSlippage,requiresApproval:t?.issues?.allowance?.actual!=null&&BigInt(t.issues.allowance.actual)<BigInt(e.sellAmount)?{token:e.sellToken,spender:s,amount:String(e.sellAmount)}:null,transaction:{chainId:n,from:e.taker,to:r.to,data:r.data,value:r.value??"0x0",...r.gas!=null?{gasLimit:r.gas}:{},slippageGuard:xA(t.autoSlippage,{chainId:n,venue:r.to,data:r.data})}},{provider:"zerox",kind:"zerox-tx"})}var Yf,nl=ae(()=>{TA();tt();rl();vA();Yf="https://api.0x.org"});var D1,_f=ae(()=>{D1=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"})});var r0={};vt(r0,{COW_CANCEL_TYPES:()=>$f,COW_HOSTS:()=>ol,COW_ORDER_TYPES:()=>ni,COW_SETTLEMENT:()=>zf,COW_VAULT_RELAYER:()=>Kf,cowCancelOrders:()=>MT,cowChains:()=>xT,cowHealth:()=>bT,cowOrder:()=>t0,cowOrderStatus:()=>A0,cowOrderUid:()=>FT,cowPrepareCancel:()=>NT,cowPrepareOrder:()=>kT,cowQuote:()=>Vn,cowSignCancel:()=>UT,cowSignOrder:()=>RT,cowSubmitSignedOrder:()=>ST,cowVerifyOrderFill:()=>TT});import{TypedDataEncoder as Zf,getAddress as Hn,isAddress as wT}from"ethers";function si(e,A={}){if(A.baseUrl)return A.baseUrl.replace(/\/$/,"");let t=ol[Number(e)];if(!t)throw new Error(`cowswap: unsupported chainId ${e}`);return t}function mT(e,A="v1",t={}){let r=si(e,t);return A==="v1"?r:r.replace(/\/api\/v1$/,`/api/${A}`)}function rt(e,A){let t=String(e||"").trim();if(!wT(t))throw new Error(`cowswap: ${A} must be an address`);return Hn(t).toLowerCase()}function vr(e,A){try{let t=BigInt(String(e));if(t<0n)throw new Error("negative");return t.toString()}catch{throw new Error(`cowswap: ${A} must be a non-negative integer string`)}}function jf(e,A){let t=String(e||"").trim();if(!/^0x[0-9a-fA-F]{64}$/.test(t))throw new Error(`cowswap: ${A} must be bytes32 hex`);return t.toLowerCase()}function e0(e,A="uid"){let t=String(e||"").trim();if(!/^0x[0-9a-fA-F]{112}$/.test(t))throw new Error(`cowswap: ${A} must be 56-byte order UID hex`);return t.toLowerCase()}function yT({digest:e,owner:A,validTo:t}={}){let r=jf(e,"order digest").slice(2),n=rt(A,"owner").slice(2).toLowerCase(),s=Number(t);if(!Number.isInteger(s)||s<0||s>4294967295)throw new Error("cowswap: validTo must fit uint32");return`0x${r}${n}${s.toString(16).padStart(8,"0")}`.toLowerCase()}function il(e){let A=zf[Number(e)];if(!A)throw new Error(`cowswap: settlement contract not registered for chain ${e}`);return{name:"Gnosis Protocol",version:"v2",chainId:Number(e),verifyingContract:Hn(A)}}function DT(e={},A,t){let r=rt(e.sellToken,"sellToken"),n=rt(e.buyToken,"buyToken"),s=rt(e.receiver||t,"receiver"),o=Number(e.validTo);if(!Number.isInteger(o)||o<=0)throw new Error("cowswap: quote.validTo required");let i=jf(e.appData||e.appDataHash||`0x${"0".repeat(64)}`,"appData");return{sellToken:r,buyToken:n,receiver:s,sellAmount:vr(e.sellAmount,"sellAmount"),buyAmount:vr(e.buyAmount,"buyAmount"),validTo:o,appData:i,feeAmount:vr(e.feeAmount??"0","feeAmount"),kind:String(e.kind||"sell"),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance||"erc20"),buyTokenBalance:String(e.buyTokenBalance||"erc20")}}async function bT(e={}){try{let A=await Vn({chainId:1,sellToken:sl[1],buyToken:Xf[1],sellAmountBeforeFee:"1000000000000000",from:Jn},e);return{ok:!0,buyAmount:A.quote?.buyAmount||A.buyAmount}}catch(A){return{ok:!1,error:String(A.message||A).slice(0,160)}}}async function Vn(e={},A={}){let t=Number(e.chainId??1),r=Zu(e.from||e.owner),n=e.sellToken||sl[t],s=e.buyToken||Xf[t],o=String(e.sellAmountBeforeFee||e.sellAmount||"0");if(!n||!s||o==="0")throw new Error("cowQuote requires sellToken, buyToken, sellAmountBeforeFee");if(/eeeeeeee|native|^eth$/i.test(n)&&(n=sl[t],!n))throw new Error("no WETH mapping for chain");let i={sellToken:n,buyToken:s,from:r,receiver:e.receiver||r,sellAmountBeforeFee:o,kind:e.kind||"sell",signingScheme:e.signingScheme||"eip1271"},a=await re(`${si(t,A)}/quote`,{method:"POST",body:i,fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3}),c=a?.quote?.buyAmount||a?.buyAmount;return c?ye(a,{chainId:t,venue:"cowswap-order",amountOut:c,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):a}async function kT(e={},A={}){let t=Number(e.chainId??1),r=rt(Zu(e.from||e.owner||e.signer),"owner"),n=await Vn({...e,chainId:t,from:r,signingScheme:e.signingScheme||"eip712"},A),s=DT(n?.quote||n,t,r),o=il(t),i={domain:o,types:ni,primaryType:"Order",message:s},a=Zf.hash(o,ni,s),c=Kf[t];if(!c)throw new Error(`cowswap: vault relayer not registered for chain ${t}`);return de({provider:"cowswap",orderReady:!0,executionReady:!1,chainId:t,owner:r,signingScheme:"eip712",settlement:o.verifyingContract.toLowerCase(),vaultRelayer:Hn(c).toLowerCase(),quote:n,quoteId:n?.id??e.quoteId??null,typedData:i,cowGuard:{mode:"cow-order",version:1,provider:"cowswap",chainId:t,owner:r,settlement:o.verifyingContract.toLowerCase(),vaultRelayer:Hn(c).toLowerCase(),sellToken:s.sellToken,buyToken:s.buyToken,sellAmount:s.sellAmount,buyAmount:s.buyAmount,validTo:s.validTo,quoteId:n?.id??e.quoteId??null,typedDataHash:a,issuedAtMs:Date.now(),expiresAtMs:Math.min(s.validTo*1e3,Date.now()+2e4)},requiresApproval:{token:s.sellToken,spender:Hn(c).toLowerCase(),amount:s.sellAmount}},{provider:"cowswap",kind:"cow-order"})}async function A0(e={},A={}){let t=Number(e.chainId??1),r=String(e.uid||e.orderUid||"").trim();if(!r)throw new Error("cowOrderStatus requires uid");return re(`${si(t,A)}/orders/${encodeURIComponent(r)}/status`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3})}async function t0(e={},A={}){let t=Number(e.chainId??1),r=String(e.uid||e.orderUid||"").trim();if(!r)throw new Error("cowOrder requires uid");return re(`${si(t,A)}/orders/${encodeURIComponent(r)}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3})}function FT(e={}){let A=e.typedData||e,t=Number(e.chainId??A?.domain?.chainId),r=A?.message||e.order||e.message;if(!r)throw new Error("cowswap: typed order message required");let n=e.cowGuard?.typedDataHash||Zf.hash(il(t),ni,r),s=e.owner||e.from||e.signer||r.receiver;return yT({digest:n,owner:s,validTo:r.validTo})}async function RT(e={},A={}){throw new Error("cowswap.cowSignOrder refused: @oracle-agent/oracle is prepare-only. Sign with the user wallet; do not pass private keys here.")}async function ST(e={},A={}){throw new Error("cowswap.cowSubmitSignedOrder refused: @oracle-agent/oracle is prepare-only. Submit signed orders from the user wallet or local operator.")}function NT(e={}){let A=Number(e.chainId??1),t=rt(e.owner||e.from||e.signer,"owner"),r=(e.orderUids||e.uids||[e.uid]).filter(Boolean).map((o,i)=>e0(o,`orderUids[${i}]`));if(!r.length)throw new Error("cowswap: orderUids required");let n=il(A);return de({provider:"cowswap",chainId:A,owner:t,orderUids:r,signingScheme:"eip712",typedData:{domain:n,types:$f,primaryType:"OrderCancellations",message:{orderUids:r}},cancelReady:!0,executableArtifact:!0},{provider:"cowswap",kind:"cow-cancel"})}async function UT(e={},A={}){throw new Error("cowswap.cowSignCancel refused: @oracle-agent/oracle is prepare-only. Cancel-sign with the user wallet.")}async function MT(e={},A={}){throw new Error("cowswap.cowCancelOrders refused: @oracle-agent/oracle is prepare-only. Cancel from the user wallet or local operator.")}function LT(e={}){return vr(e.buyAmount??e.executedBuyAmount??"0","trade.buyAmount")}async function TT(e={},A={}){let t=Number(e.chainId??1),r=e0(e.uid||e.orderUid),n=A.order||await t0({chainId:t,uid:r},A),s=A.status||n.status||await A0({chainId:t,uid:r},A).catch(()=>null),o=A.trades||await re(`${mT(t,"v2",A)}/trades?orderUid=${encodeURIComponent(r)}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3}),i=Array.isArray(o)?o:[],a=e.expectedOwner?rt(e.expectedOwner,"expectedOwner"):null;if(a&&rt(n.owner||i[0]?.owner||a,"owner")!==a)return{ok:!1,provider:"cowswap",chainId:t,uid:r,reason:"owner mismatch",order:n,status:s,trades:i};let c=0n;for(let g of i.filter(E=>String(E.orderUid||"").toLowerCase()===r))c+=BigInt(LT(g));c===0n&&n.executedBuyAmount!=null&&(c=BigInt(vr(n.executedBuyAmount,"executedBuyAmount")));let l=e.minBuyAmount!=null?BigInt(vr(e.minBuyAmount,"minBuyAmount")):0n,u=c>=l&&String(n.status||s?.status||"").toLowerCase()!=="expired";return{ok:u,provider:"cowswap",chainId:t,uid:r,status:n.status||s?.status||null,executedBuyAmount:c.toString(),minBuyAmount:e.minBuyAmount??null,trades:i,settlementTxs:[...new Set(i.map(g=>g.txHash).filter(Boolean))],order:n,orderStatus:s,reason:u?null:"insufficient fill or expired order"}}function xT(){return Object.keys(ol).map(Number)}var ol,zf,Kf,sl,Xf,ni,$f,al=ae(()=>{TA();tt();_f();zu();vA();ol={1:"https://api.cow.fi/mainnet/api/v1",100:"https://api.cow.fi/xdai/api/v1",42161:"https://api.cow.fi/arbitrum_one/api/v1",8453:"https://api.cow.fi/base/api/v1"},zf=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),Kf=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"}),sl={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"},Xf={1:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",42161:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},ni=Object.freeze({Order:[{name:"sellToken",type:"address"},{name:"buyToken",type:"address"},{name:"receiver",type:"address"},{name:"sellAmount",type:"uint256"},{name:"buyAmount",type:"uint256"},{name:"validTo",type:"uint32"},{name:"appData",type:"bytes32"},{name:"feeAmount",type:"uint256"},{name:"kind",type:"string"},{name:"partiallyFillable",type:"bool"},{name:"sellTokenBalance",type:"string"},{name:"buyTokenBalance",type:"string"}]}),$f=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]})});function s0(e){return vT.get(Number(e))||null}function o0(e,A=process.env){let t=s0(e);if(!t)return null;for(let r of t.rpcEnv){let n=(A[r]||"").trim();if(n)return n}return null}var n0,vT,i0=ae(()=>{n0={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}},vT=new Map(Object.values(n0).map(e=>[e.chainId,e]))});import{Interface as YT,getAddress as GT}from"ethers";function c0(e,A){try{return GT(e).toLowerCase()}catch{throw new Error(`${A} must be a valid EVM address`)}}function HT(e,{rpcUrl:A,env:t=process.env}={}){if(A)return A;let r=o0(e,t);return r||JT[Number(e)]||null}function qT(e){let A=String(e||""),t=A.toLowerCase();if(A!==A.trim()||!/^[a-zA-Z0-9_]+$/.test(A)||!VT.test(t))throw new Error(`evm-rpc: ${A} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return t}async function Be(e,A,t=[],r={}){let n=String(A||"");qT(n);let s=HT(e,r);if(!s)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let i=await re(s,{method:"POST",body:{jsonrpc:"2.0",id:1,method:A,params:t},fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3});if(i?.error){let a=new Error(i.error.message||JSON.stringify(i.error));throw a.code=i.error.code,a}return i.result}async function u0(e,A={}){let t=await Be(e,"eth_blockNumber",[],A);return parseInt(t,16)}async function l0(e,A={}){let t=await Be(e,"eth_gasPrice",[],A);if(t==null)return null;try{return BigInt(t)}catch{return null}}async function g0(e,A,t={}){if(!A)throw new Error("rpcGetBalance requires address");let r=await Be(e,"eth_getBalance",[A,"latest"],t);return{chainId:Number(e),address:A,balanceWei:BigInt(r).toString(),balanceHex:r}}async function E0(e={},A={}){let t=Number(e.chainId??A.chainId??1),r=c0(e.token||e.tokenAddress,"token"),n=c0(e.account||e.owner||e.address,"account"),s=a0.encodeFunctionData("balanceOf",[n]),o=await Be(t,"eth_call",[{to:r,data:s},e.blockTag||"latest"],A),i=a0.decodeFunctionResult("balanceOf",o),a=BigInt(i[0]);return{chainId:t,token:r,account:n,balance:a.toString(),balanceHex:`0x${a.toString(16)}`,blockTag:e.blockTag||"latest"}}var a0,JT,VT,Ut=ae(()=>{TA();i0();a0=new YT(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);JT={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"};VT=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/});function _T(e,A,t){let r=iA(A),n=iA(t),s=iA(e?.baseToken?.address),o=iA(e?.quoteToken?.address);return s===r&&o===n||s===n&&o===r}function ZT(e){let A=Number(e?.liquidity?.usd);return Number.isFinite(A)&&A>=0?A:null}function zT(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||OT).replace(/\/$/,"")}async function cl(e,A={}){if(!e)throw new Error("tokenAddress required");return re(`${zT(A)}/latest/dex/tokens/${e}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??12e3})}async function oi({chainId:e,tokenA:A,tokenB:t,dexIds:r=[]}={},n={}){if(e==null||!A||!t)throw new Error("chainId, tokenA, and tokenB required");let s=iA(WT[Number(e)]||e),o=new Set(PT(r).filter(Boolean).map(iA)),i=[...new Set([A,t].map(g=>String(g)).filter(Boolean))],a=await Promise.allSettled(i.map(g=>cl(g,{...n,baseUrl:n.dexscreenerBaseUrl,timeoutMs:n.dexscreenerTimeoutMs??Math.min(Number(n.timeoutMs??4e3),4e3)}))),c=new Set,l=[];for(let g of a)if(g.status==="fulfilled")for(let E of g.value?.pairs||g.value?.data?.pairs||[]){let Q=`${iA(E?.chainId)}:${iA(E?.dexId)}:${iA(E?.pairAddress)}`;c.has(Q)||(c.add(Q),l.push(E))}return l.filter(g=>iA(g?.chainId)===s).filter(g=>_T(g,A,t)).filter(g=>!o.size||o.has(iA(g?.dexId))).map(g=>({pairAddress:g.pairAddress??null,dexId:g.dexId??null,chainId:g.chainId??null,liquidityUsd:ZT(g),pairCreatedAt:g.pairCreatedAt??null})).filter(g=>g.liquidityUsd!=null).sort((g,E)=>E.liquidityUsd-g.liquidityUsd)[0]??null}var OT,WT,iA,PT,ii=ae(()=>{TA();OT="https://api.dexscreener.com",WT=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"}),iA=e=>String(e??"").toLowerCase(),PT=e=>Array.isArray(e)?e:e==null?[]:[e]});var p0={};vt(p0,{PANCAKE_FEE_TIERS:()=>ai,UNI_V3_CHAINS:()=>Ne,UNI_V3_FEE_TIERS:()=>I0,UNI_V3_VENUES:()=>d0,uniV3Chains:()=>tx,uniV3EthUsdc:()=>f0,uniV3Health:()=>Ax,uniV3PrepareExactIn:()=>ex,uniV3QuoteExactIn:()=>On,uniV3QuoteExactInPath:()=>jT});import{Interface as B0,getAddress as qn,isAddress as KT}from"ethers";function ll(e,A){let t=Number(e),r=Ne[t];if(!r)throw new Error(`uniswap-v3: unsupported chainId ${e} (supported: ${Object.keys(Ne).join(", ")})`);let n=d0[t]||{};if(!A){if(!r.quoter||!r.router){let a=Object.keys(n).join(", ")||"none registered";throw new Error(`uniswap-v3: chain ${t} (${r.name}) has no canonical Uniswap v3 deployment -- name a venue explicitly (known: ${a})`)}return{chainId:t,venue:r.name,...r}}let s=String(A).toLowerCase();if(s===r.name&&r.quoter&&r.router)return{chainId:t,venue:r.name,...r};let o=n,i=o[s];if(!i){let a=[...r.quoter&&r.router?[r.name]:[],...Object.keys(o)].join(", ");throw new Error(`uniswap-v3: unknown venue "${A}" on chain ${t} (known: ${a})`)}return{chainId:t,venue:s,...r,quoter:i.quoter,router:i.router,feeTiers:i.feeTiers||null}}function ul(e,A){let t=Ne[Number(A)];if(!e||e===h0||e===C0||/^eth$/i.test(String(e)))return qn(t.weth);let r=String(e);if(/^weth$/i.test(r))return qn(t.weth);if(/^usdc$/i.test(r))return qn(t.usdc);if(!KT(r))throw new Error(`invalid token address: ${e}`);return qn(r)}function XT(e){let A=String(e||"uniswap").toLowerCase();return A==="uniswap"?["uniswap-v3","uniswap"]:A==="pancakeswap"?["pancakeswap-v3","pancakeswap"]:A==="hyperswap"?["hyperswap-v3","hyperswap"]:[A,`${A}-v3`]}function $T(e,A){if(e.length!==A.length+1)throw new Error("path: fees.length must be tokens.length - 1");let t="0x";for(let r=0;r<A.length;r++)t+=e[r].slice(2).toLowerCase(),t+=Number(A[r]).toString(16).padStart(6,"0");return t+=e[e.length-1].slice(2).toLowerCase(),t}async function On(e={},A={}){let{chainId:t,quoter:r,router:n,feeTiers:s}=ll(e.chainId??8453,e.venue),o=ul(e.tokenIn||"WETH",t),i=ul(e.tokenOut||Ne[t].usdc,t),a=BigInt(e.amountIn??0);if(a<=0n)throw new Error("amountIn required (raw base units)");let c=s&&s.length?s:I0,l=e.fee!=null?[Number(e.fee)]:e.tryFees===!1?[c[Math.min(2,c.length-1)]]:[...c],u=[],g=null;for(let h of l){let B=ci.encodeFunctionData("quoteExactInputSingle",[{tokenIn:o,tokenOut:i,amountIn:a,fee:h,sqrtPriceLimitX96:0n}]);try{let I=await Be(t,"eth_call",[{to:r,data:B},"latest"],A);if(!I||I==="0x"){u.push({fee:h,ok:!1,error:"empty result"});continue}let C=ci.decodeFunctionResult("quoteExactInputSingle",I),m={fee:h,ok:!0,amountOut:C[0].toString(),sqrtPriceX96After:C[1].toString(),initializedTicksCrossed:Number(C[2]),gasEstimate:C[3].toString()};u.push(m),(!g||BigInt(m.amountOut)>BigInt(g.amountOut))&&(g=m)}catch(I){u.push({fee:h,ok:!1,error:String(I.message||I).slice(0,160)})}}if(!g){let h=u.map(B=>`${B.fee}:${B.error||"fail"}`).join("; ");throw new Error(`uniswap-v3 quote failed chain=${t}: ${h}`)}let E=e.liquidityUsd==null?await oi({chainId:t,tokenA:o,tokenB:i,dexIds:XT(e.venue)},A).catch(()=>null):null,Q=e.liquidityUsd??E?.liquidityUsd??null;return ye({venue:"uniswap-v3",chainId:t,chain:Ne[t].name,quoter:r,tokenIn:o,tokenOut:i,amountIn:a.toString(),fee:g.fee,amountOut:g.amountOut,gasEstimate:g.gasEstimate,liquidityUsd:Q,liquiditySource:E,sqrtPriceX96After:g.sqrtPriceX96After,initializedTicksCrossed:g.initializedTicksCrossed,triedFees:u,best:!0},{chainId:t,venue:n,amountOut:g.amountOut,liquidityUsd:Q,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function jT(e={},A={}){let{chainId:t,quoter:r,router:n}=ll(e.chainId??8453),s=(e.tokens||[]).map(g=>ul(g,t)),o=(e.fees||[]).map(Number);if(s.length<2)throw new Error("tokens[] need at least 2 addresses");let i=BigInt(e.amountIn??0);if(i<=0n)throw new Error("amountIn required");let a=$T(s,o),c=ci.encodeFunctionData("quoteExactInput",[a,i]),l=await Be(t,"eth_call",[{to:r,data:c},"latest"],A),u=ci.decodeFunctionResult("quoteExactInput",l);return ye({venue:"uniswap-v3",chainId:t,chain:Ne[t].name,quoter:r,tokens:s,fees:o,path:a,amountIn:i.toString(),amountOut:u[0].toString(),gasEstimate:u[3].toString()},{chainId:t,venue:n,amountOut:u[0].toString(),liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function f0(e={},A={}){let t=Number(e.chainId??8453),r=e.amountIn??"1000000000000000",n=await On({chainId:t,tokenIn:Ne[t].weth,tokenOut:Ne[t].usdc,amountIn:r,fee:e.fee},A),s=Number(n.amountOut)/1e6;return{...n,amountOutUsdc:s,pair:"WETH/USDC"}}async function ex(e={},A={}){let t=Number(e.chainId??8453),r=ll(t,e.venue),n=qn(e.recipient),s=String(e.tokenIn||"WETH"),o=!e.tokenIn||s===h0||s===C0||/^eth$/i.test(s),i=await On(e,A),a=Q0.encodeFunctionData("exactInputSingle",[{tokenIn:i.tokenIn,tokenOut:i.tokenOut,fee:i.fee,recipient:n,amountIn:BigInt(i.amountIn),amountOutMinimum:BigInt(i.amountOutMinimum),sqrtPriceLimitX96:0n}]),c=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),u=Number(A.nowSeconds??Math.floor(Date.now()/1e3))+c,g=Q0.encodeFunctionData("multicall",[u,[a]]);return de({provider:"uniswap-v3",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:t,deadline:u,quote:i,autoSlippage:i.autoSlippage,requiresApproval:o?null:{token:i.tokenIn,spender:r.router,amount:i.amountIn},transaction:{chainId:t,from:n,to:r.router,data:g,value:o?i.amountIn:"0",slippageGuard:xA(i.autoSlippage,{chainId:t,venue:r.router,data:g})}},{provider:"uniswap-v3",kind:"univ3-swap-tx"})}async function Ax(e={}){let A=Number(e.chainId??8453);try{let t=await f0({chainId:A,amountIn:"1000000000000000"},e);return{ok:!0,chainId:A,fee:t.fee,amountOutUsdc:t.amountOutUsdc,midPxHint:t.amountOutUsdc/.001}}catch(t){return{ok:!1,chainId:A,error:String(t.message||t).slice(0,200)}}}async function tx(){return Object.entries(Ne).map(([e,A])=>({chainId:Number(e),name:A.name,quoter:A.quoter,weth:A.weth,usdc:A.usdc}))}var Ne,I0,ci,Q0,h0,C0,ai,d0,ui=ae(()=>{Ut();ii();tt();vA();Ne={1:{name:"ethereum",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",usdc:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},8453:{name:"base",quoter:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",router:"0x2626664c2603336E57B271c5C0b26F421741e481",weth:"0x4200000000000000000000000000000000000006",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"},42161:{name:"arbitrum",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",usdc:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},4663:{name:"robinhood",quoter:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",router:"0xcaf681a66d020601342297493863e78c959e5cb2",weth:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",usdc:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"},999:{name:"hyperevm",weth:"0x5555555555555555555555555555555555555555",usdc:"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb"},10:{name:"optimism",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x4200000000000000000000000000000000000006",usdc:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"},56:{name:"bsc",quoter:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",router:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",weth:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",usdc:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"},137:{name:"polygon",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",usdc:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"},43114:{name:"avalanche",quoter:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",router:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",weth:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",usdc:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"}},I0=[100,500,3e3,1e4],ci=new B0(["function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)","function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)"]),Q0=new B0(["function exactInputSingle((address tokenIn,address tokenOut,uint24 fee,address recipient,uint256 amountIn,uint256 amountOutMinimum,uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)","function multicall(uint256 deadline,bytes[] data) payable returns (bytes[] results)"]),h0="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",C0="0x0000000000000000000000000000000000000000",ai=[100,500,2500,1e4],d0={56:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ai}},8453:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ai}},42161:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ai}},999:{hyperswap:{name:"hyperswap",quoter:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",router:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D"}}}});var F0={};vt(F0,{UNI_V4_CHAINS:()=>YA,UNI_V4_FEE_TIERS:()=>D0,computeV4PoolId:()=>k0,uniV4Chains:()=>gx,uniV4Health:()=>Ex,uniV4PrepareExactIn:()=>lx,uniV4QuoteExactIn:()=>gi});import{AbiCoder as rx,Interface as y0,getAddress as aA,isAddress as li,keccak256 as nx}from"ethers";function gl(e){let A=Number(e),t=YA[A];if(!t)throw new Error(`uniswap-v4: unsupported chainId ${e} (supported: ${Object.keys(YA).join(", ")})`);return{chainId:A,...t}}function m0(e,A){let t=YA[Number(A)];if(!e||e===b0||e===Mt||/^eth$/i.test(String(e)))return aA(t.weth);let r=String(e);if(/^weth$/i.test(r))return aA(t.weth);if(/^usdc$/i.test(r)||/^usdg$/i.test(r))return aA(t.usdc);if(!li(r))throw new Error(`invalid token address: ${e}`);return aA(r)}function k0({currency0:e,currency1:A,fee:t,tickSpacing:r,hooks:n=Mt}){let s=aA(e),o=aA(A);if(s.toLowerCase()===o.toLowerCase())throw new Error("poolKey currencies must differ");let[i,a]=s.toLowerCase()<o.toLowerCase()?[s,o]:[o,s],c=n&&li(n)?aA(n):Mt;return nx(Wn.encode(["address","address","uint24","int24","address"],[i,a,Number(t),Number(r),c]))}function cx({tokenIn:e,tokenOut:A,fee:t,tickSpacing:r,hooks:n=Mt}){let s=aA(e),o=aA(A),[i,a]=s.toLowerCase()<o.toLowerCase()?[s,o]:[o,s],c=s.toLowerCase()===i.toLowerCase();return{poolKey:{currency0:i,currency1:a,fee:Number(t),tickSpacing:Number(r),hooks:n&&li(n)?aA(n):Mt},zeroForOne:c}}async function gi(e={},A={}){let{chainId:t,quoter:r,poolManager:n,universalRouter:s}=gl(e.chainId??8453),o=m0(e.tokenIn||"WETH",t),i=m0(e.tokenOut||YA[t].usdc,t),a=BigInt(e.amountIn??0);if(a<=0n)throw new Error("amountIn required (raw base units)");if(a>0xffffffffffffffffffffffffffffffffn)throw new Error("amountIn exceeds uint128");let c=e.fee!=null&&e.tickSpacing!=null?[{fee:Number(e.fee),tickSpacing:Number(e.tickSpacing)}]:e.tryTiers===!1?[{fee:500,tickSpacing:10}]:[...D0],l=e.hooks||Mt,u=[],g=null;for(let h of c){let{poolKey:B,zeroForOne:I}=cx({tokenIn:o,tokenOut:i,fee:h.fee,tickSpacing:h.tickSpacing,hooks:l}),C=w0.encodeFunctionData("quoteExactInputSingle",[{poolKey:B,zeroForOne:I,exactAmount:a,hookData:"0x"}]);try{let m=await Be(t,"eth_call",[{to:r,data:C},"latest"],A);if(!m||m==="0x"){u.push({...h,ok:!1,error:"empty result"});continue}let y=w0.decodeFunctionResult("quoteExactInputSingle",m),L={fee:h.fee,tickSpacing:h.tickSpacing,ok:!0,amountOut:y[0].toString(),gasEstimate:y[1].toString(),poolKey:B,zeroForOne:I,poolId:k0({...B})};u.push(L),(!g||BigInt(L.amountOut)>BigInt(g.amountOut))&&(g=L)}catch(m){u.push({...h,ok:!1,error:String(m.message||m).slice(0,160)})}}if(!g){let h=u.map(B=>`${B.fee}/${B.tickSpacing}:${B.error||"fail"}`).join("; ");throw new Error(`uniswap-v4 quote failed chain=${t}: ${h}`)}let E=e.liquidityUsd==null?await oi({chainId:t,tokenA:o,tokenB:i,dexIds:ux},A).catch(()=>null):null,Q=e.liquidityUsd??E?.liquidityUsd??null;return ye({venue:"uniswap-v4",chainId:t,chain:YA[t].name,poolManager:n,quoter:r,universalRouter:s||null,tokenIn:o,tokenOut:i,amountIn:a.toString(),fee:g.fee,tickSpacing:g.tickSpacing,hooks:g.poolKey.hooks,poolId:g.poolId,zeroForOne:g.zeroForOne,amountOut:g.amountOut,gasEstimate:g.gasEstimate,liquidityUsd:Q,liquiditySource:E,triedTiers:u,best:!0,executionReady:!1,prepareReady:typeof e.recipient=="string"&&li(e.recipient)&&e.slippageBps!=null},{chainId:t,venue:s||r,amountOut:g.amountOut,liquidityUsd:Q,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function lx(e={},A={}){let t=Number(e.chainId??8453),r=gl(t);if(!e.recipient)throw new Error("uniswap-v4 prepare requires recipient");let n=aA(e.recipient);if(e.slippageBps==null)throw new Error("uniswap-v4 prepare requires explicit slippageBps");let s=Number(e.slippageBps);if(!Number.isInteger(s)||s<0||s>=1e4)throw new Error("slippageBps must be an integer from 0 through 9999");let o=String(e.tokenIn||"");if(!o||o===b0||o===Mt||/^eth$/i.test(o))throw new Error("uniswap-v4 prepare currently requires an ERC-20 tokenIn; native input is not inferred");let i=await gi(e,A);if(!r.universalRouter)throw new Error(`uniswap-v4: no Universal Router on chain ${t}`);let a=BigInt(i.amountOut)*BigInt(1e4-s)/10000n,c={currency0:i.zeroForOne?i.tokenIn:i.tokenOut,currency1:i.zeroForOne?i.tokenOut:i.tokenIn,fee:i.fee,tickSpacing:i.tickSpacing,hooks:i.hooks},u=Wn.encode(["tuple(tuple(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 amountIn,uint128 amountOutMinimum,uint256 minHopPriceX36,bytes hookData)"],[[c,i.zeroForOne,BigInt(i.amountIn),a,0n,"0x"]]),g=Wn.encode(["address","uint256"],[i.tokenIn,BigInt(i.amountIn)]),E=Wn.encode(["address","uint256"],[i.tokenOut,a]),Q=Wn.encode(["bytes","bytes[]"],[ix,[u,g,E]]),h=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),I=Number(A.nowSeconds??Math.floor(Date.now()/1e3))+h,C=sx.encodeFunctionData("execute",[ox,[Q],I]);return de({provider:"uniswap-v4",prepareReady:!0,calldataReady:!0,executionReady:!1,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:t,deadline:I,quote:{...i,amountOutMinimum:a.toString(),slippageBps:s},requiresApproval:{token:i.tokenIn,spender:ax,amount:i.amountIn,note:"Universal Router V4 settlement uses Permit2; Permit2 authorization for the Universal Router is also required"},transaction:{chainId:t,from:n,to:r.universalRouter,data:C,value:"0"}},{provider:"uniswap-v4",kind:"univ4-swap-tx"})}async function gx(){return Object.entries(YA).map(([e,A])=>({chainId:Number(e),name:A.name,poolManager:A.poolManager,quoter:A.quoter,stateView:A.stateView||null,universalRouter:A.universalRouter||null,weth:A.weth,usdc:A.usdc}))}async function Ex(e={}){let A=gl(e.chainId??8453),t=await Be(A.chainId,"eth_getCode",[A.quoter,"latest"],e),r=typeof t=="string"&&t!=="0x"&&t.length>4;return{ok:r,chainId:A.chainId,quoter:A.quoter,poolManager:A.poolManager,codeBytes:r?(t.length-2)/2:0}}var Wn,Mt,YA,D0,w0,sx,ox,ix,ax,b0,ux,El=ae(()=>{Ut();ii();tt();vA();Wn=rx.defaultAbiCoder(),Mt="0x0000000000000000000000000000000000000000",YA={1:{name:"ethereum",poolManager:"0x000000000004444c5dc75cB358380D2e3dE08A90",quoter:"0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203",stateView:"0x7ffe42c4a5deea5b0fec41c94c136cf115597227",universalRouter:"0x66a9893cc07d91d95644aedd05d03f95e1dba8af",weth:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",usdc:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},10:{name:"optimism",poolManager:"0x9a13f98cb987694c9f086b1f5eb990eea8264ec3",quoter:"0x1f3131a13296fb91c90870043742c3cdbff1a8d7",stateView:"0xc18a3169788f4f75a170290584eca6395c75ecdb",universalRouter:"0x851116d9223fabed8e56c0e6b8ad0c31d98b3507",weth:"0x4200000000000000000000000000000000000006",usdc:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"},56:{name:"bsc",poolManager:"0x28e2ea090877bf75740558f6bfb36a5ffee9e9df",quoter:"0x9f75dd27d6664c475b90e105573e550ff69437b0",stateView:"0xd13dd3d6e93f276fafc9db9e6bb47c1180aee0c4",universalRouter:"0x1906c1d672b88cd1b9ac7593301ca990f94eae07",weth:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",usdc:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"},137:{name:"polygon",poolManager:"0x67366782805870060151383f4bbff9dab53e5cd6",quoter:"0xb3d5c3dfc3a7aebff71895a7191796bffc2c81b9",stateView:"0x5ea1bd7974c8a611cbab0bdcafcb1d9cc9b3ba5a",universalRouter:"0x1095692a6237d83c6a72f3f5efedb9a670c49223",weth:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",usdc:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"},8453:{name:"base",poolManager:"0x498581fF718922c3f8e6A244956aF099B2652b2b",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",stateView:"0xa3c0c9b65bad0b08107aa264b0f3db444b867a71",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",weth:"0x4200000000000000000000000000000000000006",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"},42161:{name:"arbitrum",poolManager:"0x360e68faccca8ca495c1b759fd9eee466db9fb32",quoter:"0x3972c00f7ed4885e145823eb7c655375d275a1c5",stateView:"0x76fd297e2d437cd7f76d50f01afe6160f86e9990",universalRouter:"0xa51afafe0263b40edaef0df8781ea9aa03e381a3",weth:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",usdc:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},43114:{name:"avalanche",poolManager:"0x06380c0e0912312b5150364b9dc4542ba0dbbc85",quoter:"0xbe40675bb704506a3c2ccfb762dcfd1e979845c2",stateView:"0xc3c9e198c735a4b97e3e683f391ccbdd60b69286",universalRouter:"0x94b75331ae8d42c1b61065089b7d48fe14aa73b7",weth:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",usdc:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"},4663:{name:"robinhood",poolManager:"0x8366a39cc670b4001a1121b8f6a443a643e40951",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",stateView:"0xf3334192d15450cdd385c8b70e03f9a6bd9e673b",universalRouter:"0x8876789976dEcBfCbBbe364623C63652db8C0904",weth:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",usdc:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"}},D0=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200},{fee:25e3,tickSpacing:8}],w0=new y0(["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)"]),sx=new y0(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),ox="0x10",ix="0x060c0f",ax="0x000000000022D473030F116dDEE9F6B43aC78BA3",b0="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";ux=["uniswap-v4","uniswapv4"]});var zn=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),J=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),x=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),Ap=/^0x[0-9a-fA-F]{40}$/;function tp(e={}){let A=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:["definition must be an object"],warnings:t};if((!Number.isInteger(e.chainId)||e.chainId<=0)&&A.push("chainId must be a positive integer"),(typeof e.key!="string"||!/^[a-z][a-z0-9-]*$/.test(e.key||""))&&A.push('key must be a lowercase slug (e.g. "base")'),(typeof e.name!="string"||!e.name.trim())&&A.push("name is required"),!Array.isArray(e.rpcEnv)||e.rpcEnv.length===0)A.push("rpcEnv must list at least one environment variable name");else for(let n of e.rpcEnv)(typeof n!="string"||!/^[A-Z][A-Z0-9_]*$/.test(n))&&A.push(`rpcEnv entry "${n}" should be an UPPER_SNAKE env var name`);if(e.nativeCurrency){let n=e.nativeCurrency;(typeof n.symbol!="string"||!n.symbol)&&A.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(n.decimals)||A.push("nativeCurrency.decimals must be an integer")}for(let[n,s]of(e.venues||[]).entries()){let o=`venues[${n}]`;if(!s||typeof s!="object"){A.push(`${o} must be an object`);continue}Ap.test(s.address||"")||A.push(`${o}.address is not a valid 20-byte address`),/^0x0{40}$/.test(s.address||"")&&A.push(`${o}.address is the zero address -- placeholder left in place?`),s.kind||A.push(`${o}.kind is required (router|quoter|factory|...)`),s.verified?(s.verified.method||A.push(`${o}.verified.method is required`),s.verified.source||A.push(`${o}.verified.source is required`),s.verified.date||t.push(`${o}.verified.date missing -- add one so staleness is visible`)):A.push(`${o} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let r=e.capabilities||{};for(let n of Object.keys(r))zn.includes(n)?typeof r[n]!="function"&&A.push(`capability "${n}" must be a function`):A.push(`unknown capability "${n}"`);return Object.keys(r).length===0&&t.push("scanner implements no capabilities -- it can only be registered, not used"),r.prepareUnsignedTx&&!r.quote&&t.push("prepareUnsignedTx without quote: no priced expectation to validate the built tx against"),r.prepareUnsignedTx&&!r.sellSimulation&&t.push("prepareUnsignedTx without sellSimulation: cannot prove an asset is exitable before buying"),{ok:A.length===0,errors:A,warnings:t}}function rp(e){let{ok:A,errors:t,warnings:r}=tp(e);if(!A)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
47
47
  - ${t.join(`
48
- - `)}`);let n=e.capabilities||{},s=zn.filter(i=>typeof n[i]=="function"),o={key:e.key,chainId:e.chainId,name:e.name,rpcEnv:[...e.rpcEnv],nativeCurrency:e.nativeCurrency?{...e.nativeCurrency}:null,explorer:e.explorer||null,venues:(e.venues||[]).map(i=>({...i})),warnings:r,capabilities(){return{chainId:e.chainId,key:e.key,supported:[...s],unsupported:zn.filter(i=>!s.includes(i))}},supports(i){return s.includes(i)}};for(let i of zn)s.includes(i)?o[i]=async(...a)=>n[i](...a,{scanner:o}):o[i]=async()=>{throw new Error(`${e.key} (chain ${e.chainId}) does not implement "${i}". 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(o)}var hi=new Map;function Dl(e){let A=rp(e);return hi.set(A.chainId,A),A}function Kn(e){return hi.get(Number(e))||null}function bl(){return[...hi.values()]}var fA=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"}),Fl={1:"coingecko:ethereum",10:"coingecko:ethereum",56:"coingecko:binancecoin",137:"coingecko:matic-network",8453:"coingecko:ethereum",42161:"coingecko:ethereum",43114:"coingecko:avalanche-2",999:"coingecko:ethereum"},Yr=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}};function kl(e){let{source:A,amountOut:t,minOut:r=null,gasUsd:n=null,feeUsd:s=null,oracleFeeBps:o=0,estimatedGas:i=null,liquidityUsd:a=null,error:c=null,executionReady:l=!1,meta:u={}}=e||{};if(c||t==null)return{source:A,quality:fA.FAILED,amountOut:null,error:c||"no amountOut returned"};let g=Yr(t);if(g==null||g<=0n)return{source:A,quality:fA.FAILED,amountOut:null,error:"non-positive amountOut"};let E=Number(o);return{source:A,quality:n==null?fA.NO_GAS:fA.FULL,amountOut:g.toString(),minOut:Yr(r)?.toString()??null,gasUsd:n,feeUsd:s,oracleFeeBps:Number.isFinite(E)&&E>0?Math.floor(E):0,estimatedGas:i==null?null:String(i),liquidityUsd:a==null?null:Number(a),executionReady:l,meta:u}}async function Rl(e,A,{divisor:t=1000n}={}){let r=Yr(A);if(r==null||r<=0n)return null;let n=r/t>0n?r/t:1n;if(n>=r)return null;let s,o;try{[s,o]=await Promise.all([e(n),e(r)])}catch{return null}let i=Yr(s),a=Yr(o);if(i==null||a==null||i<=0n)return null;let c=Number(i)/Number(n),l=Number(a)/Number(r);return!Number.isFinite(c)||!Number.isFinite(l)||c<=0?null:{impactPct:(1-l/c)*100,probeAmountIn:n.toString(),probeAmountOut:i.toString(),fullAmountOut:a.toString()}}function Sl(e,A,{maxImpactPct:t=25}={}){let r=[],n=[],s=(e.routes??[]).filter(i=>{let a=A?.[i.source];return a?a.impactPct>t?(r.push({source:i.source,impactPct:Number(a.impactPct.toFixed(2)),reason:`price impact ${a.impactPct.toFixed(1)}% exceeds ${t}% ceiling -- the venue cannot absorb this size near the quoted price`}),!1):!0:(n.push(i.source),!0)}),o=[...e.warnings??[]];return r.length&&o.push(`dropped ${r.length} route(s) on price impact: `+r.map(i=>`${i.source} (${i.impactPct}%)`).join(", ")),n.length&&o.push(`price impact NOT measured for: ${n.join(", ")}. These are unproven against thin liquidity, not proven safe.`),{...e,routes:s,best:s[0]??null,impactRejected:r,impactUnmeasured:n,warnings:o}}function Nl(e,{destPriceUsd:A=null,destDecimals:t=null,liquidityFirst:r=!0,liquidityBandBps:n=50,gasPriceWei:s=null,nativePriceUsd:o=null}={}){let i=e.filter(N=>N.quality!==fA.FAILED),a=e.filter(N=>N.quality===fA.FAILED),c=A!=null&&A>0&&t!=null&&t>=0,l=Number(s),u=Number(o),g=Number.isFinite(l)&&l>0&&Number.isFinite(u)&&u>0,E=i.map(N=>{let W=BigInt(N.amountOut),Ue=0n,fe=!1,ie=!1,qe=BigInt(N.oracleFeeBps??0),dA=qe>0n?W*qe/10000n:0n;if(c){let Zn=N.gasUsd,Bi=Number(N.meta?.gasUnits??N.estimatedGas);if(Zn==null&&g&&Number.isFinite(Bi)&&Bi>0){let st=Bi*l/1e18*u;Number.isFinite(st)&&st>=0&&(Zn=st,ie=!0)}let yl=(Zn??0)+(N.feeUsd??0);if(yl>0){let st=yl/A*10**t;Number.isFinite(st)&&st>=0&&(Ue=BigInt(Math.floor(st)),fe=!0)}else Zn===0&&(fe=!0)}let Tt=Ue+dA,xt=W>Tt?W-Tt:0n;return{...N,grossOut:W.toString(),netOut:xt.toString(),costInDest:Ue.toString(),oracleFeeInDest:dA.toString(),costAccounted:fe,gasEstimated:ie}}),Q=Number(n)>0?Number(n):0,h=E.reduce((N,W)=>BigInt(W.netOut)>N?BigInt(W.netOut):N,0n),B=N=>h>0n?Number((h-BigInt(N))*10000n/h):0,I=[],C=E.slice().sort((N,W)=>BigInt(W.netOut)>BigInt(N.netOut)?1:-1)[0]??null;E.sort((N,W)=>{let Ue=B(N.netOut)<=Q?0:1,fe=B(W.netOut)<=Q?0:1;if(r&&Q>0&&Ue!==fe)return Ue-fe;if(r&&Q>0){let ie=N.liquidityUsd??-1,qe=W.liquidityUsd??-1;if(ie!==qe)return qe-ie}return BigInt(W.netOut)>BigInt(N.netOut)?1:-1}),r&&Q>0&&C&&E[0]&&E[0].source!==C.source&&I.push(`liquidity-first: chose ${E[0].source} (liquidity $${E[0].liquidityUsd??"unknown"}) over best-price ${C.source} within ${Q} bps`);let m=E.filter(N=>!N.costAccounted).map(N=>N.source);c?m.length&&I.push(`gas not reported by: ${m.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):I.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let y=E[0];if(c&&y&&y.costAccounted===!1){let N=E.find(W=>W.costAccounted&&B(W.netOut)<=Q);N&&I.push(`winner ${y.source} has UNMEASURED gas; gas-measured ${N.source} is within ${Q} bps and may net more once ${y.source}'s real gas is paid \u2014 prefer it if unsure.`)}let L=E.filter(N=>N.gasEstimated).map(N=>N.source);L.length&&I.push(`gas ESTIMATED (from gas units x current gas price, not measured) for: ${L.join(", ")}. Net includes this estimate so the ranking is gas-inclusive, but the on-chain gas may differ.`);let q=null,_=null;if(E.length>=2&&E[0].costAccounted&&E[1].costAccounted){let N=BigInt(E[0].netOut),W=BigInt(E[1].netOut);W>0n&&(q=Number((N-W)*10000n/W),_=`${E[0].source} vs ${E[1].source}`)}return{best:E[0]??null,routes:E,failed:a,improvementBps:q,spreadBasis:_,rankedOn:c?"net-of-cost":"gross",warnings:I}}async function Ci(e,{timeoutMs:A=12e3}={}){let t=(n,s)=>Promise.race([n,new Promise((o,i)=>setTimeout(()=>i(new Error(`${s}: timeout`)),A))]);return(await Promise.allSettled(e.map(n=>t(Promise.resolve().then(n.run),n.source)))).map((n,s)=>{let o=e[s].source;return n.status==="rejected"?kl({source:o,error:String(n.reason?.message||n.reason)}):kl({source:o,...n.value})})}el();tl();nl();TA();tt();rl();vA();var dT="https://api.1inch.dev/swap/v6.0";function Of(e={}){return ei({provider:"oneinch",defaultUrl:dT,hosts:["api.1inch.dev"],url:e.baseUrl||process.env.ONEINCH_API_URL})}function fT(e={}){return Of(e).baseUrl}function Wf(e={}){return e.apiKey||process.env.ONEINCH_API_KEY||process.env.ONE_INCH_API_KEY||""}function pT(e={}){let A=Wf(e);return Ai({accept:"application/json"},{Authorization:A?`Bearer ${A}`:""},Of(e).trusted)}async function Pf(e={},A={}){if(!Wf(A))throw new Error("ONEINCH_API_KEY required for 1inch");let t=Number(e.chainId??1),{src:r,dst:n,amount:s}=e;if(!r||!n||!s)throw new Error("oneinchQuote requires src, dst, amount");let o=new URLSearchParams({src:r,dst:n,amount:String(s)}),i=await re(`${fT(A)}/${t}/quote?${o}`,{headers:pT(A),fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3});return i?.dstAmount?ye(i,{chainId:t,venue:"1inch-quote",amountOut:i.dstAmount,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):i}al();ui();El();TA();var Qx="https://coins.llama.fi";function Bx(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Qx).replace(/\/$/,"")}async function Ei(e,A={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let t=e.map(encodeURIComponent).join(",");return re(`${Bx(A)}/prices/current/${t}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs})}var Ql=e=>{let A=Number(e);return Number.isFinite(A)?A:null};function R0(e){if(!Array.isArray(e))return null;let A=0,t=!1;for(let r of e){let n=Ql(r?.amountUSD);n!=null&&(A+=n,t=!0)}return t?A:null}async function S0(e,A={}){let t=Fl[Number(e)];if(!t)return null;try{let r=await Ei([t],A);return Ql(r?.coins?.[t]?.price)}catch{return null}}var lY=Object.freeze({across:["across"],relay:["relaychain","relay"],lifi:["jumper-(li.fi-powered)","lifi"],stargate:["stargate-v2","stargate-v1","stargate"],hop:["hop-protocol","hop"],debridge:["debridge"],synapse:["synapse"],connext:["connext"],cbridge:["celer-bridge","celer-cbridge","cbridge"],celer:["celer-bridge","celer-cbridge","cbridge"],squid:["squid"],symbiosis:["symbiosis"],wormhole:["wormhole"],mayan:["mayan"],allbridge:["allbridge"],thorchain:["thorchain"]});function Bl({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n,slippageBps:s,decimalsIn:o,decimalsOut:i,nativePriceUsd:a=null,destDecimalsPromise:c=null,opts:l={}}){let u=[];return u.push({source:"lifi",run:async()=>{let g=await $o({fromChain:e,toChain:e,fromToken:A,toToken:t,fromAmount:r},l),E=g?.estimate??g?.[0]?.estimate;return{amountOut:E?.toAmount,minOut:E?.toAmountMin,gasUsd:R0(E?.gasCosts),feeUsd:R0(E?.feeCosts),oracleFeeBps:g?.oracleFee?.applies?g.oracleFee.bps:0,meta:{tool:g?.tool??g?.toolDetails?.name,oracleFee:g?.oracleFee??null}}}}),o!=null&&u.push({source:"paraswap",run:async()=>{let g=i??(await Promise.resolve(c))?.decimals;if(g==null)throw new Error("paraswap needs destination decimals; none supplied or resolvable");let E=await jo({chainId:e,srcToken:A,destToken:t,amount:r,srcDecimals:o,destDecimals:g},l),Q=E?.priceRoute;return{amountOut:Q?.destAmount,gasUsd:Ql(Q?.gasCostUSD),oracleFeeBps:E?.oracleFee?.applies?E.oracleFee.bps:0,meta:{bestRoute:Q?.bestRoute?.[0]?.swaps?.[0]?.swapExchanges?.[0]?.exchange,oracleFee:E?.oracleFee??null}}}}),process.env.ZEROX_API_KEY&&u.push({source:"0x",run:async()=>{let g=await ri({chainId:e,sellToken:A,buyToken:t,sellAmount:r,taker:n},l),E=null,Q=g?.totalNetworkFee,h=await Promise.resolve(a);return Q!=null&&h&&(E=Number(Q)/1e18*h),{amountOut:g?.buyAmount,minOut:g?.minBuyAmount,gasUsd:E,meta:{source:g?.route?.fills?.[0]?.source}}}}),process.env.ONEINCH_API_KEY&&u.push({source:"1inch",run:async()=>{let g=await Pf({chainId:e,src:A,dst:t,amount:r},l),E=null;return g?.gas!=null&&a&&(E=null),{amountOut:g?.dstAmount,gasUsd:E,meta:{gasUnits:g?.gas}}}}),u.push({source:"cow",run:async()=>{let g=await Vn({chainId:e,sellToken:A,buyToken:t,sellAmountBeforeFee:String(r),from:n},l),E=g?.quote??g,Q=E?.feeAmount;return{amountOut:E?.buyAmount,gasUsd:0,meta:{intent:!0,feeAmountInSellToken:Q,settlement:"solver-executed"}}}}),Ne[Number(e)]&&u.push({source:"uniswap-v3",run:async()=>{let g=await On({chainId:e,tokenIn:A,tokenOut:t,amountIn:r},l);return{amountOut:g?.amountOut,minOut:g?.minOut??g?.amountOutMinimum??null,gasUsd:null,liquidityUsd:g?.liquidityUsd??null,meta:{onchain:!0,fee:g?.fee,gasUnits:g?.gasEstimate,quoter:g?.quoter}}}}),YA[Number(e)]&&u.push({source:"uniswap-v4",run:async()=>{let g=await gi({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,recipient:n,slippageBps:s},l);return{amountOut:g?.amountOut,minOut:g?.minOut??g?.amountOutMinimum??null,gasUsd:null,liquidityUsd:g?.liquidityUsd??null,meta:{onchain:!0,venue:"uniswap-v4",fee:g?.fee,tickSpacing:g?.tickSpacing,poolId:g?.poolId,hooks:g?.hooks,gasUnits:g?.gasEstimate,quoter:g?.quoter,poolManager:g?.poolManager,prepareReady:g?.prepareReady===!0,executionReady:!1}}}}),u}Xo();Ut();var Ix={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"};async function hx(e,A,t){let r=Ix[Number(e)];if(!r)return{priceUsd:null,decimals:null};let n=`${r}:${A}`;try{let o=(await Ei([n],t))?.coins?.[n],i=Number(o?.price),a=Number(o?.decimals);return{priceUsd:Number.isFinite(i)?i:null,decimals:Number.isFinite(a)?a:null}}catch{return{priceUsd:null,decimals:null}}}async function U0(e,A={}){let{chainId:t,tokenIn:r,tokenOut:n,amountIn:s}=e;if(t==null||!r||!n||s==null)throw new Error("bestSwapRoute requires chainId, tokenIn, tokenOut, amountIn");let o=S0(t,A),i=hx(t,n,A),a=l0(t,A).catch(()=>null),c=Bl({...e,nativePriceUsd:o,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:A}),[l,u,g]=await Promise.all([Ci(c,{timeoutMs:A.timeoutMs??12e3}),i,a]);o.catch(()=>{});let E=await o.then(B=>B,()=>null),Q=Nl(l,{destPriceUsd:u.priceUsd,destDecimals:e.decimalsOut??u.decimals,liquidityBandBps:A.liquidityBandBps??50,gasPriceWei:g,nativePriceUsd:E}),h=A.maxImpactPct===void 0?25:A.maxImpactPct;if(h!=null&&Q.best){let B=Q.best.source,C=await Rl(async m=>{let y=Bl({...e,amountIn:m.toString(),nativePriceUsd:o,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:A}).filter(q=>q.source===B);return y.length?(await Ci(y,{timeoutMs:A.timeoutMs??12e3}))?.[0]?.amountOut??null:null},s);if(C){let m=Sl(Q,{[B]:C},{maxImpactPct:h});return{kind:"swap",chainId:t,tokenIn:r,tokenOut:n,amountIn:String(s),...m,sourcesTried:c.length,sourcesAnswered:l.filter(y=>y.quality!==fA.FAILED).length,note:N0(m,c.length),priceImpact:{[B]:Number(C.impactPct.toFixed(2))}}}}return{kind:"swap",chainId:t,tokenIn:r,tokenOut:n,amountIn:String(s),...Q,sourcesTried:c.length,sourcesAnswered:l.filter(B=>B.quality!==fA.FAILED).length,note:N0(Q,c.length)}}function Cx(e){let A=e?.meta?.oracleFee;return A?.applies?` \xB7 ${kf(A)}`:""}function N0(e,A){if(!e.best)return"no source returned a usable route";let t=e.routes.length,r=Cx(e.best);if(t===1)return`only 1 of ${A} sources answered, so this is the ONLY route, not a proven best one. Treat it as unbenchmarked.`+r;if(e.improvementBps!=null){let n=e.improvementBps,s=n/100;if(n<.01)return`best of ${t} routes, ranked on ${e.rankedOn}: effectively tied with the runner-up (${e.spreadBasis}), inside quote noise. Re-quote before you size up.`+r;let o=s>=.01?`${s.toFixed(2)}%`:`${n.toFixed(2)}bps`;return`best of ${t} routes, ranked on ${e.rankedOn}: ${o} better than the runner-up (${e.spreadBasis})`+r}return`best of ${t} routes, ranked on ${e.rankedOn}. No spread quoted: the top routes report cost differently, so the margin is not comparable.`+r}vA();var nt=Object.freeze({TRANSACTION:"unsigned-transaction",TYPED_DATA_ORDER:"typed-data-order"}),dx=100,Il={"uniswap-v3":async({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n},s)=>{let{uniV3PrepareExactIn:o}=await Promise.resolve().then(()=>(ui(),p0)),i=await o({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,recipient:n},s);return{artifactKind:nt.TRANSACTION,transaction:i.transaction,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.amountOut??null,minOut:i.quote?.amountOutMinimum??null}},"uniswap-v4":async({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n,slippageBps:s,fee:o,tickSpacing:i,hooks:a},c)=>{let{uniV4PrepareExactIn:l}=await Promise.resolve().then(()=>(El(),F0)),u=await l({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,recipient:n,slippageBps:s,fee:o,tickSpacing:i,hooks:a},c);return{artifactKind:nt.TRANSACTION,transaction:u.transaction,requiresApproval:u.requiresApproval,amountOut:u.quote?.amountOut??null,minOut:u.quote?.amountOutMinimum??null,prepareReady:!0,executionReady:!1}},lifi:async({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n},s)=>{let{lifiPrepare:o}=await Promise.resolve().then(()=>(el(),Uf)),i=await o({fromChain:e,toChain:e,fromToken:A,toToken:t,fromAmount:r,fromAddress:n},s);return{artifactKind:nt.TRANSACTION,transaction:i.transaction,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.estimate?.toAmount??null,minOut:i.quote?.estimate?.toAmountMin??null}},paraswap:async({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n,decimalsIn:s,decimalsOut:o},i)=>{let{paraswapPrepare:a}=await Promise.resolve().then(()=>(tl(),Tf)),c=await a({chainId:e,srcToken:A,destToken:t,amount:r,srcDecimals:s,destDecimals:o,userAddress:n,side:"SELL"},i);return{artifactKind:nt.TRANSACTION,transaction:c.transaction,requiresApproval:c.requiresApproval??null,amountOut:c.quote?.priceRoute?.destAmount??null,minOut:c.quote?.amountOutMinimum??null}},"0x":async({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n},s)=>{let{zeroxPrepare:o}=await Promise.resolve().then(()=>(nl(),qf)),i=await o({chainId:e,sellToken:A,buyToken:t,sellAmount:r,taker:n},s);return{artifactKind:nt.TRANSACTION,transaction:i.transaction,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.buyAmount??null,minOut:i.quote?.minBuyAmount??null}},cow:async({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n},s)=>{let{cowPrepareOrder:o}=await Promise.resolve().then(()=>(al(),r0)),i=await o({chainId:e,sellToken:A,buyToken:t,sellAmountBeforeFee:String(r),from:n},s);return{artifactKind:nt.TYPED_DATA_ORDER,typedData:i.typedData,requiresApproval:{token:A,spender:i.vaultRelayer,amount:String(r),note:"CoW pulls funds via the vault relayer, not the settlement contract"},settlement:i.settlement,amountOut:i.quote?.quote?.buyAmount??null,minOut:null,submission:"sign the typed data, then submit the order to the CoW API"}}};var fx=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),px=/^0x[0-9a-fA-F]{40}$/;async function M0(e,A={}){let{taker:t}=e;if(!t)throw new Error("prepareBestRoute requires taker: a prepared transaction is built FOR an address, and the quote-only placeholder must never end up in one");if(!px.test(t))throw new Error(`taker must be a valid 20-byte address, got "${t}"`);if(fx.has(t.toLowerCase()))throw new Error(`taker "${t}" is a placeholder/burn address. It is valid for quoting but not for preparing -- that would build a transaction for an address nobody controls. Pass the real wallet that will sign.`);let r=await U0(e,A);if(!r.best){let B=r.impactRejected??[];return{ok:!1,reason:B.length?B[0].reason:"no source returned a usable route",priceImpactBlocked:B.length>0,impactRejected:B,comparison:r}}let n=e.source||r.best.source,s=r.routes.find(B=>B.source===n);if(!s)return{ok:!1,reason:`source "${n}" did not return a usable route`,comparison:r};let o=Il[n];if(!o){let B=r.routes.find(I=>Il[I.source]&&I.source!==n);return{ok:!1,reason:`${n} won the comparison but has no prepare path in this build. `+(B?`Next preparable route is ${B.source}; pass source:"${B.source}" to use it.`:"No route in this comparison can be prepared."),comparison:r,winner:n}}let i;try{i=await o(e,A)}catch(B){let I=typeof B?.body=="string"?B.body:B?.body?JSON.stringify(B.body):"",C=[String(B?.message||B),I].filter(Boolean).join(" :: "),m=/allowance/i.test(C),y=!m&&/not enough|insufficient|balance/i.test(C),L,q;m?(q="approval-required-first",L=`${n} will not build swap calldata until the token approval exists on-chain. Approve the spender first, then prepare again. Underlying: ${C}`):y?(q="taker-not-funded",L=`${n} refused to build the transaction: ${C}. This venue verifies the taker holds the input token. Quoting works for any address; preparing needs the real funded wallet.`):(q="provider-error",L=`${n} prepare failed: ${C}`);let _=r.routes.find(N=>Il[N.source]&&N.source!==n);return{ok:!1,reason:L,failureKind:q,..._?{alternative:_.source}:{},comparison:r}}let a=e.driftToleranceBps??dx,c=null,l=null;if(i.amountOut!=null&&s.grossOut!=null)try{let B=BigInt(s.grossOut),I=BigInt(i.amountOut);B>0n&&(c=Number((I-B)*10000n/B),c<-a&&(l=`route moved ${(c/100).toFixed(2)}% against you between the comparison and this prepare (tolerance ${(a/100).toFixed(2)}%). The ranking may no longer hold -- re-run the comparison before signing.`))}catch{}let u=r.routes.filter(B=>B.source!==n).map(B=>({source:B.source,netOut:B.netOut,gasUsd:B.gasUsd})),E=r.routes.map(B=>({source:B.source,liquidityUsd:B.liquidityUsd??null})).reduce((B,I)=>Math.max(B,I.liquidityUsd??0),0)||null,Q=s.liquidityUsd??null,h=Q!=null&&E>0?Math.round(Q/E*100):null;return de({ok:!0,chosen:{source:n,wasWinner:n===r.best.source,netOut:s.netOut,grossOut:s.grossOut,gasUsd:s.gasUsd,liquidityUsd:s.liquidityUsd??null},liquidity:{chosenUsd:Q,maxUsd:E,sharePct:h},priceImpact:r.priceImpact??null,impactUnmeasured:r.impactUnmeasured??[],...i,unsigned:!0,signedBy:"user-wallet",destination:i.artifactKind===nt.TRANSACTION?i.transaction?.to??null:i.settlement??null,driftBps:c,warnings:[...l?[l]:[],...r.warnings||[],...i.artifactKind===nt.TYPED_DATA_ORDER?["This is an ORDER to sign, not a transaction to broadcast. Signing it authorizes a solver to settle on your behalf."]:[]],runnersUp:u,comparison:{rankedOn:r.rankedOn,sourcesAnswered:r.sourcesAnswered,sourcesTried:r.sourcesTried,improvementBps:r.improvementBps},note:"UNSIGNED. Verify the destination address and minOut against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."},{provider:"router",kind:"best-route"})}Ut();ii();Ut();var Cl={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},Ke=e=>BigInt(e).toString(16).padStart(64,"0"),Pn=e=>e.slice(2).toLowerCase().padStart(64,"0");function wx(e,A){return`0x${Cl.getAmountsOut}`+Ke(e)+Ke(64)+Ke(A.length)+A.map(Pn).join("")}function mx(e){if(!e||e==="0x")return null;let A=e.slice(2);if(A.length<128)return null;let t=Number(BigInt(`0x${A.slice(64,128)}`));if(!Number.isFinite(t)||t<1||t>16)return null;let r=[];for(let n=0;n<t;n++){let s=128+n*64;if(A.length<s+64)return null;r.push(BigInt(`0x${A.slice(s,s+64)}`))}return r}function hl(e,A="router"){return(e?.venues||[]).find(r=>r.kind===A)?.address??null}var dl=100;function yx(e,A){let t=Number(A);if(!Number.isFinite(t)||t<0)throw new Error("slippageBps must be a non-negative number");if(t>dl)throw new Error(`slippageBps ${t} exceeds the ${dl} 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(t))/10000n}function L0(e){let{chainId:A,wrappedNative:t}=e;async function r(n,s,o,i){let a=await Be(A,"eth_call",[{to:n,data:wx(s,o)},"latest"],i);return mx(a?.result??a)}return{async quote({tokenIn:n,tokenOut:s,amountIn:o,path:i},a={}){let c=hl(a.scanner);if(!c)return{chainId:A,evidence:J.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let l=i||[n,s];if(l.some(g=>!/^0x[0-9a-fA-F]{40}$/.test(g||"")))throw new Error("quote requires valid 20-byte addresses");let u=await r(c,o,l,a);return u?{chainId:A,router:c,path:l,amountIn:String(o),amountOut:u[u.length-1].toString(),hops:l.length-1,evidence:J.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:A,router:c,path:l,evidence:J.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:n,amountIn:s,base:o},i={}){let a=hl(i.scanner),c=o||t;if(c&&String(n).toLowerCase()===String(c).toLowerCase())return{chainId:A,token:n,verdict:x.UNKNOWN,evidence:J.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(!a||!c)return{chainId:A,token:n,verdict:x.UNKNOWN,evidence:J.UNAVAILABLE,reason:a?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let l=await r(a,s,[c,n],i);if(!l)return{chainId:A,token:n,verdict:x.FAIL,evidence:J.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let u=l[l.length-1];if(u===0n)return{chainId:A,token:n,verdict:x.FAIL,evidence:J.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let g=await r(a,u,[n,c],i);if(!g)return{chainId:A,token:n,verdict:x.FAIL,evidence:J.LIVE,leg:"sell",bought:u.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let E=g[g.length-1],Q=Number(E*10000n/BigInt(s)),h=x.PASS,B="round trip completes with expected fee/impact loss";return Q<5e3?(h=x.FAIL,B=`round trip returns only ${(Q/100).toFixed(2)}% -- punitive tax or no real liquidity`):Q<9e3&&(h=x.CAUTION,B=`round trip returns ${(Q/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:A,token:n,base:c,router:a,verdict:h,reason:B,amountIn:String(s),bought:u.toString(),returned:E.toString(),retentionBps:Q,evidence:J.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:n,tokenOut:s,amountIn:o,recipient:i,slippageBps:a=50,deadlineSeconds:c=900,path:l},u={}){let g=u.scanner,E=hl(g);if(!E)throw new Error(`chain ${A} 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(i||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let Q=l||[n,s],h=await this.quote({tokenIn:n,tokenOut:s,amountIn:o,path:Q},u);if(h.evidence!==J.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let B=yx(h.amountOut,a);if(B<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let I=BigInt(Math.floor(Date.now()/1e3)+Number(c)),C=t&&Q[0].toLowerCase()===t.toLowerCase()&&u.useNative,m=C?`0x${Cl.swapExactETHForTokens}`+Ke(B)+Ke(128)+Pn(i)+Ke(I)+Ke(Q.length)+Q.map(Pn).join(""):`0x${Cl.swapExactTokensForTokens}`+Ke(o)+Ke(B)+Ke(160)+Pn(i)+Ke(I)+Ke(Q.length)+Q.map(Pn).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:A,tx:{to:E,data:m,value:C?`0x${BigInt(o).toString(16)}`:"0x0"},guard:{quotedOut:h.amountOut,minOut:B.toString(),slippageBps:a,maxSlippageBps:dl,deadline:I.toString()},requires:C?[]:[{step:"approve",token:Q[0],spender:E,amount:String(o)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}Ut();var Dx=[100,500,3e3,1e4],T0={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},Lt=e=>BigInt(e).toString(16).padStart(64,"0"),_n=e=>e.slice(2).toLowerCase().padStart(64,"0"),x0=/^0x[0-9a-fA-F]{40}$/,pl=100;function bx(e,A){let t=Number(A);if(!Number.isFinite(t)||t<0)throw new Error("slippageBps must be a non-negative number");if(t>pl)throw new Error(`slippageBps ${t} exceeds the ${pl} 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(t))/10000n}function fl(e,A){return(e?.venues||[]).find(t=>t.kind===A)?.address??null}function v0(e){let{chainId:A,wrappedNative:t}=e;async function r({quoter:s,tokenIn:o,tokenOut:i,amountIn:a,fee:c},l){let u=`0x${T0.quoteExactInputSingle}`+_n(o)+_n(i)+Lt(a)+Lt(c)+Lt(0),g=await Be(A,"eth_call",[{to:s,data:u},"latest"],l).catch(()=>null),E=g?.result??g;if(!E||E==="0x"||E.length<66)return null;let Q=BigInt(`0x${E.slice(2,66)}`);return Q>0n?Q:null}async function n({quoter:s,tokenIn:o,tokenOut:i,amountIn:a},c){let l=[],u=null;for(let g of Dx){let E=await r({quoter:s,tokenIn:o,tokenOut:i,amountIn:a,fee:g},c);l.push({fee:g,amountOut:E?E.toString():null}),E&&(!u||E>u.amountOut)&&(u={fee:g,amountOut:E})}return{best:u,tried:l}}return{async quote({tokenIn:s,tokenOut:o,amountIn:i},a={}){let c=fl(a.scanner,"quoter");if(!c)return{chainId:A,evidence:J.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let g of[s,o])if(!x0.test(g||""))throw new Error("quote requires valid 20-byte addresses");let{best:l,tried:u}=await n({quoter:c,tokenIn:s,tokenOut:o,amountIn:i},a);return l?{chainId:A,venue:"uniswap-v3",quoter:c,tokenIn:s,tokenOut:o,amountIn:String(i),amountOut:l.amountOut.toString(),fee:l.fee,triedFeeTiers:u,evidence:J.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:A,quoter:c,tokenIn:s,tokenOut:o,triedFeeTiers:u,evidence:J.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:s,amountIn:o,base:i},a={}){let c=fl(a.scanner,"quoter"),l=i||t;if(l&&String(s).toLowerCase()===String(l).toLowerCase())return{chainId:A,token:s,verdict:x.UNKNOWN,evidence:J.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||!l)return{chainId:A,token:s,verdict:x.UNKNOWN,evidence:J.UNAVAILABLE,reason:c?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let u=await n({quoter:c,tokenIn:l,tokenOut:s,amountIn:o},a);if(!u.best)return{chainId:A,token:s,verdict:x.FAIL,evidence:J.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier"};let g=await n({quoter:c,tokenIn:s,tokenOut:l,amountIn:u.best.amountOut},a);if(!g.best)return{chainId:A,token:s,verdict:x.FAIL,evidence:J.LIVE,leg:"sell",bought:u.best.amountOut.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let E=g.best.amountOut,Q=Number(E*10000n/BigInt(o)),h=x.PASS,B="round trip completes with expected fee/impact loss";return Q<5e3?(h=x.FAIL,B=`round trip returns only ${(Q/100).toFixed(2)}% -- punitive tax or no real liquidity`):Q<9e3&&(h=x.CAUTION,B=`round trip returns ${(Q/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:A,venue:"uniswap-v3",token:s,base:l,verdict:h,reason:B,amountIn:String(o),bought:u.best.amountOut.toString(),returned:E.toString(),retentionBps:Q,buyFee:u.best.fee,sellFee:g.best.fee,evidence:J.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:s,tokenOut:o,amountIn:i,recipient:a,slippageBps:c=50,fee:l},u={}){let g=fl(u.scanner,"router");if(!g)throw new Error(`chain ${A} 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(!x0.test(a||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let E=await this.quote({tokenIn:s,tokenOut:o,amountIn:i},u);if(E.evidence!==J.LIVE)throw new Error(`cannot prepare without a live quote (${E.evidence}: ${E.reason??"no reason given"})`);let Q=l??E.fee,h=bx(E.amountOut,c);if(h<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let B=`0x${T0.exactInputSingle}`+_n(s)+_n(o)+Lt(Q)+_n(a)+Lt(i)+Lt(h)+Lt(0);return{unsigned:!0,signedBy:"user-wallet",chainId:A,venue:"uniswap-v3",tx:{to:g,data:B,value:"0x0"},guard:{quotedOut:E.amountOut,minOut:h.toString(),slippageBps:c,maxSlippageBps:pl,fee:Q},requires:[{step:"approve",token:s,spender:g,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 Qi={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function Y0(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function G0(e){if(!e||e==="0x")return null;let A=e.slice(2);if(A.length>=128){let r=Number(BigInt(`0x${A.slice(64,128)}`));if(r>0&&r<=256&&A.length>=128+r*2){let n=A.slice(128,128+r*2),s=Buffer.from(n,"hex").toString("utf8").replace(/\0+$/,"");if(s)return s}}return Buffer.from(A.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function kx(e){let{chainId:A}=e;async function t(r,n,s){return Be(A,"eth_call",[{to:r,data:n},"latest"],s)}return{async blockNumber(r={}){let n=await u0(A,r);return{chainId:A,blockNumber:n?.blockNumber??n,evidence:J.LIVE}},async nativeBalance(r,n={}){let s=await g0(A,r,n);return{chainId:A,address:r,wei:s?.wei??s?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:J.LIVE}},async tokenBalance({token:r,owner:n},s={}){let o=await E0({chainId:A,token:r,owner:n},s);return{chainId:A,token:r,owner:n,raw:o?.balance??o,evidence:J.LIVE}},async resolveToken(r,n={}){if(!/^0x[0-9a-fA-F]{40}$/.test(r||""))return{chainId:A,token:r,evidence:J.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[s,o,i,a]=await Promise.all([t(r,Qi.decimals,n).catch(()=>null),t(r,Qi.symbol,n).catch(()=>null),t(r,Qi.name,n).catch(()=>null),t(r,Qi.totalSupply,n).catch(()=>null)]),c=Y0(s?.result??s),l=c!==null||o?.result||i?.result;return{chainId:A,address:r,decimals:c===null?null:Number(c),symbol:G0(o?.result??o),name:G0(i?.result??i),totalSupply:(Y0(a?.result??a)??null)?.toString()??null,evidence:l?J.LIVE:J.UNKNOWN,warning:l?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(r,n={}){let s=e.dexscreenerSlug;if(!s)return{chainId:A,token:r,pools:[],evidence:J.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let o=await cl(r,n).catch(()=>null),a=(o?.pairs||o?.data?.pairs||[]).filter(c=>String(c.chainId).toLowerCase()===String(s).toLowerCase()).map(c=>({pair:c.pairAddress,dex:c.dexId,base:c.baseToken?.address,quote:c.quoteToken?.address,liquidityUsd:c.liquidity?.usd??null,priceUsd:c.priceUsd??null,volume24hUsd:c.volume?.h24??null,createdAt:c.pairCreatedAt??null})).sort((c,l)=>(l.liquidityUsd??0)-(c.liquidityUsd??0));return{chainId:A,token:r,pools:a,evidence:a.length?J.LIVE:J.UNKNOWN}},async scanBlocks({fromBlock:r,toBlock:n,address:s,topics:o,chunkSize:i=2e3}={},a={}){if(!Number.isInteger(r)||!Number.isInteger(n))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(n<r)throw new Error("toBlock must be >= fromBlock");let c=[],l=[];for(let u=r;u<=n;u+=i){let g=Math.min(u+i-1,n);l.push([u,g])}for(let[u,g]of l){let E={fromBlock:`0x${u.toString(16)}`,toBlock:`0x${g.toString(16)}`};s&&(E.address=s),o&&(E.topics=o);let Q=await Be(A,"eth_getLogs",[E],a).catch(h=>({error:String(h?.message||h)}));if(Q?.error)return{chainId:A,fromBlock:r,toBlock:n,logs:c,complete:!1,failedAt:[u,g],error:Q.error,evidence:J.UNKNOWN};for(let h of Q?.result??Q??[])c.push(h)}return{chainId:A,fromBlock:r,toBlock:n,logs:c,complete:!0,chunks:l.length,evidence:J.LIVE}},async scoreRisk(r,n={}){let s=[],o=x.PASS,i=l=>{let u={[x.PASS]:0,[x.CAUTION]:1,[x.UNKNOWN]:2,[x.FAIL]:3};u[l]>u[o]&&(o=l)},a=await this.resolveToken(r,n);a.evidence!==J.LIVE?(s.push({check:"erc20-metadata",result:x.UNKNOWN,detail:a.warning}),i(x.UNKNOWN)):s.push({check:"erc20-metadata",result:x.PASS,detail:`${a.symbol} / ${a.decimals}d`});let c=await this.resolvePools(r,n);if(c.evidence===J.UNAVAILABLE)s.push({check:"liquidity",result:x.UNKNOWN,detail:c.reason}),i(x.UNKNOWN);else if(!c.pools.length)s.push({check:"liquidity",result:x.FAIL,detail:"no pool with liquidity found"}),i(x.FAIL);else{let l=c.pools[0],u=l.liquidityUsd??0;u<5e3?(s.push({check:"liquidity",result:x.CAUTION,detail:`top pool only $${u}`}),i(x.CAUTION)):s.push({check:"liquidity",result:x.PASS,detail:`$${u} on ${l.dex}`}),l.createdAt&&Date.now()-l.createdAt<24*3600*1e3&&(s.push({check:"age",result:x.CAUTION,detail:"pool under 24h old"}),i(x.CAUTION))}if(typeof this.sellSimulation=="function"){let l=await this.sellSimulation({token:r,amountIn:(10n**16n).toString()},n).catch(u=>({verdict:x.UNKNOWN,reason:String(u?.message||u)}));s.push({check:"sellability",result:l.verdict,detail:l.retentionBps!=null?`round trip returns ${(l.retentionBps/100).toFixed(2)}% -- ${l.reason}`:l.reason}),i(l.verdict)}else s.push({check:"sellability",result:x.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."}),i(x.UNKNOWN);return{chainId:A,token:r,verdict:o,checks:s,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function J0(e){let t={...kx(e)},r=new Set((e.venues||[]).map(s=>s.kind));e.venueKind==="uniswap-v3"&&r.has("quoter")&&r.has("router")?Object.assign(t,v0({chainId:e.chainId,wrappedNative:e.wrappedNative})):e.venueKind==="uniswap-v2"&&r.has("router")&&Object.assign(t,L0({chainId:e.chainId,wrappedNative:e.wrappedNative}));let n={};for(let[s,o]of Object.entries(t))n[s]=o.bind(t);return{key:e.key,chainId:e.chainId,name:e.name,rpcEnv:e.rpcEnv,nativeCurrency:e.nativeCurrency,explorer:e.explorer,venues:e.venues||[],capabilities:n}}var Fx=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",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",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",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",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",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",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",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",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 H0(){return Fx.map(e=>Dl(J0(e)))}ui();var wl=/^0x[0-9a-fA-F]{40}$/,Rx=24,V0=!1;function W0(){V0||(H0(),V0=!0)}var Ie=class extends Error{constructor(A,t){super(t),this.status=A}};function Sx(e){if(W0(),e==null||e==="")throw new Ie(400,"chainId is required");let A=Number(e);if(Number.isFinite(A)&&Kn(A))return A;let t=bl().find(r=>r.key===String(e).toLowerCase());if(t)return t.chainId;throw new Ie(400,`unknown chain "${e}"`)}function q0(e,A){if(typeof e!="string")throw new Ie(400,`${A} is required`);let t=e.trim();if(t===""||t.length>Rx)throw new Ie(400,`${A} is invalid`);if(!/^[A-Za-z0-9._-]+$/.test(t)&&!wl.test(t))throw new Ie(400,`${A} is invalid`);return t}function Nx(e,A){let t=String(e).trim();if(!/^\d+(\.\d+)?$/.test(t))throw new Ie(400,"sellAmount must be a positive decimal number");if(Number(t)<=0)throw new Ie(400,"sellAmount must be greater than zero");let r=Number.isFinite(Number(A))?Number(A):18,[n,s=""]=t.split(".");if(s.length>r)throw new Ie(400,`sellAmount has more precision than the token's ${r} decimals`);let o=s.padEnd(r,"0"),i=(BigInt(n)*10n**BigInt(r)+BigInt(o||"0")).toString();if(i==="0")throw new Ie(400,"sellAmount rounds to zero at this token's precision");return i}async function O0(e,A){if(W0(),wl.test(A)){let c=await Kn(e).resolveToken(A).catch(()=>null),l=Number(c?.decimals);return{address:A,decimals:Number.isFinite(l)?l:null}}let t=Ne[e];if(!t)return null;let r=A.toLowerCase(),n=r==="usdc"?t.usdc:r==="weth"||r==="eth"?t.weth:null;if(!n)return null;let o=await Kn(e).resolveToken(n).catch(()=>null),i=Number(o?.decimals);return{address:n,decimals:Number.isFinite(i)?i:null}}async function P0(e={},A={}){let t=Sx(e.chainId??e.chain),r=q0(e.sellSymbol??e.sellToken,"sellSymbol"),n=q0(e.buySymbol??e.buyToken,"buySymbol");if(r.toLowerCase()===n.toLowerCase())throw new Ie(400,"sell and buy assets must differ");let s=typeof e.taker=="string"?e.taker.trim():"";if(!wl.test(s))throw new Ie(400,"taker must be the wallet address that will sign");let[o,i]=await Promise.all([O0(t,r),O0(t,n)]);if(!o)throw new Ie(400,`could not resolve sell asset "${r}" on chain ${t}`);if(!i)throw new Ie(400,`could not resolve buy asset "${n}" on chain ${t}`);let a=Nx(e.sellAmount,o.decimals),c=await M0({chainId:t,tokenIn:o.address||r,tokenOut:i.address||n,amountIn:a,taker:s,decimalsIn:o.decimals??null,decimalsOut:i.decimals??null,source:typeof e.source=="string"&&e.source.trim()!==""?e.source.trim():void 0},A);if(!c.ok)return{ok:!1,reason:c.reason,priceImpactBlocked:!!c.priceImpactBlocked,requiresWalletSignature:!0,backendSigner:!1};let l=i.decimals??18,u=c.minOut??c.chosen?.netOut??c.chosen?.grossOut??null;return{ok:!0,requiresWalletSignature:!0,backendSigner:!1,quote:{sellSymbol:r,buySymbol:n,sellAmount:String(e.sellAmount),buyAmount:u==null?null:String(u),buyAmountFormatted:u==null?null:(Number(u)/10**l).toString(),routeLabel:c.chosen?.source??null,priceImpactPct:Number.isFinite(Number(c.chosen?.priceImpactPct))?Number(c.chosen.priceImpactPct):null,slippageBps:Number.isFinite(Number(c.slippageBps))?Number(c.slippageBps):null,intentHash:c.intentHash??null,minOut:c.minOut??null,requiresApproval:c.requiresApproval??null,warnings:Array.isArray(c.warnings)?c.warnings:[]},transaction:c.transaction??null}}var ml=`oracle swap <chain> <sellAsset> <buyAsset> <amount> --taker <address> [--source X] [--json]
48
+ - `)}`);let n=e.capabilities||{},s=zn.filter(i=>typeof n[i]=="function"),o={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(i=>({...i})),warnings:r,capabilities(){return{chainId:e.chainId,key:e.key,supported:[...s],unsupported:zn.filter(i=>!s.includes(i))}},supports(i){return s.includes(i)}};for(let i of zn)s.includes(i)?o[i]=async(...a)=>n[i](...a,{scanner:o}):o[i]=async()=>{throw new Error(`${e.key} (chain ${e.chainId}) does not implement "${i}". 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(o)}var hi=new Map;function Dl(e){let A=rp(e);return hi.set(A.chainId,A),A}function Kn(e){return hi.get(Number(e))||null}function bl(){return[...hi.values()]}var fA=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"}),Fl={1:"coingecko:ethereum",10:"coingecko:ethereum",56:"coingecko:binancecoin",137:"coingecko:matic-network",8453:"coingecko:ethereum",42161:"coingecko:ethereum",43114:"coingecko:avalanche-2",999:"coingecko:ethereum"},Yr=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}};function kl(e){let{source:A,amountOut:t,minOut:r=null,gasUsd:n=null,feeUsd:s=null,oracleFeeBps:o=0,estimatedGas:i=null,liquidityUsd:a=null,error:c=null,executionReady:l=!1,meta:u={}}=e||{};if(c||t==null)return{source:A,quality:fA.FAILED,amountOut:null,error:c||"no amountOut returned"};let g=Yr(t);if(g==null||g<=0n)return{source:A,quality:fA.FAILED,amountOut:null,error:"non-positive amountOut"};let E=Number(o);return{source:A,quality:n==null?fA.NO_GAS:fA.FULL,amountOut:g.toString(),minOut:Yr(r)?.toString()??null,gasUsd:n,feeUsd:s,oracleFeeBps:Number.isFinite(E)&&E>0?Math.floor(E):0,estimatedGas:i==null?null:String(i),liquidityUsd:a==null?null:Number(a),executionReady:l,meta:u}}async function Rl(e,A,{divisor:t=1000n}={}){let r=Yr(A);if(r==null||r<=0n)return null;let n=r/t>0n?r/t:1n;if(n>=r)return null;let s,o;try{[s,o]=await Promise.all([e(n),e(r)])}catch{return null}let i=Yr(s),a=Yr(o);if(i==null||a==null||i<=0n)return null;let c=Number(i)/Number(n),l=Number(a)/Number(r);return!Number.isFinite(c)||!Number.isFinite(l)||c<=0?null:{impactPct:(1-l/c)*100,probeAmountIn:n.toString(),probeAmountOut:i.toString(),fullAmountOut:a.toString()}}function Sl(e,A,{maxImpactPct:t=25}={}){let r=[],n=[],s=(e.routes??[]).filter(i=>{let a=A?.[i.source];return a?a.impactPct>t?(r.push({source:i.source,impactPct:Number(a.impactPct.toFixed(2)),reason:`price impact ${a.impactPct.toFixed(1)}% exceeds ${t}% ceiling -- the venue cannot absorb this size near the quoted price`}),!1):!0:(n.push(i.source),!0)}),o=[...e.warnings??[]];return r.length&&o.push(`dropped ${r.length} route(s) on price impact: `+r.map(i=>`${i.source} (${i.impactPct}%)`).join(", ")),n.length&&o.push(`price impact NOT measured for: ${n.join(", ")}. These are unproven against thin liquidity, not proven safe.`),{...e,routes:s,best:s[0]??null,impactRejected:r,impactUnmeasured:n,warnings:o}}function Nl(e,{destPriceUsd:A=null,destDecimals:t=null,liquidityFirst:r=!0,liquidityBandBps:n=50,gasPriceWei:s=null,nativePriceUsd:o=null}={}){let i=e.filter(N=>N.quality!==fA.FAILED),a=e.filter(N=>N.quality===fA.FAILED),c=A!=null&&A>0&&t!=null&&t>=0,l=Number(s),u=Number(o),g=Number.isFinite(l)&&l>0&&Number.isFinite(u)&&u>0,E=i.map(N=>{let W=BigInt(N.amountOut),Ue=0n,fe=!1,ie=!1,qe=BigInt(N.oracleFeeBps??0),dA=qe>0n?W*qe/10000n:0n;if(c){let Zn=N.gasUsd,Bi=Number(N.meta?.gasUnits??N.estimatedGas);if(Zn==null&&g&&Number.isFinite(Bi)&&Bi>0){let st=Bi*l/1e18*u;Number.isFinite(st)&&st>=0&&(Zn=st,ie=!0)}let yl=(Zn??0)+(N.feeUsd??0);if(yl>0){let st=yl/A*10**t;Number.isFinite(st)&&st>=0&&(Ue=BigInt(Math.floor(st)),fe=!0)}else Zn===0&&(fe=!0)}let Tt=Ue+dA,xt=W>Tt?W-Tt:0n;return{...N,grossOut:W.toString(),netOut:xt.toString(),costInDest:Ue.toString(),oracleFeeInDest:dA.toString(),costAccounted:fe,gasEstimated:ie}}),Q=Number(n)>0?Number(n):0,h=E.reduce((N,W)=>BigInt(W.netOut)>N?BigInt(W.netOut):N,0n),B=N=>h>0n?Number((h-BigInt(N))*10000n/h):0,I=[],C=E.slice().sort((N,W)=>BigInt(W.netOut)>BigInt(N.netOut)?1:-1)[0]??null;E.sort((N,W)=>{let Ue=B(N.netOut)<=Q?0:1,fe=B(W.netOut)<=Q?0:1;if(r&&Q>0&&Ue!==fe)return Ue-fe;if(r&&Q>0){let ie=N.liquidityUsd??-1,qe=W.liquidityUsd??-1;if(ie!==qe)return qe-ie}return BigInt(W.netOut)>BigInt(N.netOut)?1:-1}),r&&Q>0&&C&&E[0]&&E[0].source!==C.source&&I.push(`liquidity-first: chose ${E[0].source} (liquidity $${E[0].liquidityUsd??"unknown"}) over best-price ${C.source} within ${Q} bps`);let m=E.filter(N=>!N.costAccounted).map(N=>N.source);c?m.length&&I.push(`gas not reported by: ${m.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):I.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let y=E[0];if(c&&y&&y.costAccounted===!1){let N=E.find(W=>W.costAccounted&&B(W.netOut)<=Q);N&&I.push(`winner ${y.source} has UNMEASURED gas; gas-measured ${N.source} is within ${Q} bps and may net more once ${y.source}'s real gas is paid \u2014 prefer it if unsure.`)}let L=E.filter(N=>N.gasEstimated).map(N=>N.source);L.length&&I.push(`gas ESTIMATED (from gas units x current gas price, not measured) for: ${L.join(", ")}. Net includes this estimate so the ranking is gas-inclusive, but the on-chain gas may differ.`);let q=null,_=null;if(E.length>=2&&E[0].costAccounted&&E[1].costAccounted){let N=BigInt(E[0].netOut),W=BigInt(E[1].netOut);W>0n&&(q=Number((N-W)*10000n/W),_=`${E[0].source} vs ${E[1].source}`)}return{best:E[0]??null,routes:E,failed:a,improvementBps:q,spreadBasis:_,rankedOn:c?"net-of-cost":"gross",warnings:I}}async function Ci(e,{timeoutMs:A=12e3}={}){let t=(n,s)=>Promise.race([n,new Promise((o,i)=>setTimeout(()=>i(new Error(`${s}: timeout`)),A))]);return(await Promise.allSettled(e.map(n=>t(Promise.resolve().then(n.run),n.source)))).map((n,s)=>{let o=e[s].source;return n.status==="rejected"?kl({source:o,error:String(n.reason?.message||n.reason)}):kl({source:o,...n.value})})}el();tl();nl();TA();tt();rl();vA();var dT="https://api.1inch.dev/swap/v6.0";function Of(e={}){return ei({provider:"oneinch",defaultUrl:dT,hosts:["api.1inch.dev"],url:e.baseUrl||process.env.ONEINCH_API_URL})}function fT(e={}){return Of(e).baseUrl}function Wf(e={}){return e.apiKey||process.env.ONEINCH_API_KEY||process.env.ONE_INCH_API_KEY||""}function pT(e={}){let A=Wf(e);return Ai({accept:"application/json"},{Authorization:A?`Bearer ${A}`:""},Of(e).trusted)}async function Pf(e={},A={}){if(!Wf(A))throw new Error("ONEINCH_API_KEY required for 1inch");let t=Number(e.chainId??1),{src:r,dst:n,amount:s}=e;if(!r||!n||!s)throw new Error("oneinchQuote requires src, dst, amount");let o=new URLSearchParams({src:r,dst:n,amount:String(s)}),i=await re(`${fT(A)}/${t}/quote?${o}`,{headers:pT(A),fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3});return i?.dstAmount?ye(i,{chainId:t,venue:"1inch-quote",amountOut:i.dstAmount,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):i}al();ui();El();TA();var Qx="https://coins.llama.fi";function Bx(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Qx).replace(/\/$/,"")}async function Ei(e,A={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let t=e.map(encodeURIComponent).join(",");return re(`${Bx(A)}/prices/current/${t}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs})}var Ql=e=>{let A=Number(e);return Number.isFinite(A)?A:null};function R0(e){if(!Array.isArray(e))return null;let A=0,t=!1;for(let r of e){let n=Ql(r?.amountUSD);n!=null&&(A+=n,t=!0)}return t?A:null}async function S0(e,A={}){let t=Fl[Number(e)];if(!t)return null;try{let r=await Ei([t],A);return Ql(r?.coins?.[t]?.price)}catch{return null}}var lY=Object.freeze({across:["across"],relay:["relaychain","relay"],lifi:["jumper-(li.fi-powered)","lifi"],stargate:["stargate-v2","stargate-v1","stargate"],hop:["hop-protocol","hop"],debridge:["debridge"],synapse:["synapse"],connext:["connext"],cbridge:["celer-bridge","celer-cbridge","cbridge"],celer:["celer-bridge","celer-cbridge","cbridge"],squid:["squid"],symbiosis:["symbiosis"],wormhole:["wormhole"],mayan:["mayan"],allbridge:["allbridge"],thorchain:["thorchain"]});function Bl({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n,slippageBps:s,decimalsIn:o,decimalsOut:i,nativePriceUsd:a=null,destDecimalsPromise:c=null,opts:l={}}){let u=[];return u.push({source:"lifi",run:async()=>{let g=await $o({fromChain:e,toChain:e,fromToken:A,toToken:t,fromAmount:r},l),E=g?.estimate??g?.[0]?.estimate;return{amountOut:E?.toAmount,minOut:E?.toAmountMin,gasUsd:R0(E?.gasCosts),feeUsd:R0(E?.feeCosts),oracleFeeBps:g?.oracleFee?.applies?g.oracleFee.bps:0,meta:{tool:g?.tool??g?.toolDetails?.name,oracleFee:g?.oracleFee??null}}}}),o!=null&&u.push({source:"paraswap",run:async()=>{let g=i??(await Promise.resolve(c))?.decimals;if(g==null)throw new Error("paraswap needs destination decimals; none supplied or resolvable");let E=await jo({chainId:e,srcToken:A,destToken:t,amount:r,srcDecimals:o,destDecimals:g},l),Q=E?.priceRoute;return{amountOut:Q?.destAmount,gasUsd:Ql(Q?.gasCostUSD),oracleFeeBps:E?.oracleFee?.applies?E.oracleFee.bps:0,meta:{bestRoute:Q?.bestRoute?.[0]?.swaps?.[0]?.swapExchanges?.[0]?.exchange,oracleFee:E?.oracleFee??null}}}}),process.env.ZEROX_API_KEY&&u.push({source:"0x",run:async()=>{let g=await ri({chainId:e,sellToken:A,buyToken:t,sellAmount:r,taker:n},l),E=null,Q=g?.totalNetworkFee,h=await Promise.resolve(a);return Q!=null&&h&&(E=Number(Q)/1e18*h),{amountOut:g?.buyAmount,minOut:g?.minBuyAmount,gasUsd:E,meta:{source:g?.route?.fills?.[0]?.source}}}}),process.env.ONEINCH_API_KEY&&u.push({source:"1inch",run:async()=>{let g=await Pf({chainId:e,src:A,dst:t,amount:r},l),E=null;return g?.gas!=null&&a&&(E=null),{amountOut:g?.dstAmount,gasUsd:E,meta:{gasUnits:g?.gas}}}}),u.push({source:"cow",run:async()=>{let g=await Vn({chainId:e,sellToken:A,buyToken:t,sellAmountBeforeFee:String(r),from:n},l),E=g?.quote??g,Q=E?.feeAmount;return{amountOut:E?.buyAmount,gasUsd:0,meta:{intent:!0,feeAmountInSellToken:Q,settlement:"solver-executed"}}}}),Ne[Number(e)]&&u.push({source:"uniswap-v3",run:async()=>{let g=await On({chainId:e,tokenIn:A,tokenOut:t,amountIn:r},l);return{amountOut:g?.amountOut,minOut:g?.minOut??g?.amountOutMinimum??null,gasUsd:null,liquidityUsd:g?.liquidityUsd??null,meta:{onchain:!0,fee:g?.fee,gasUnits:g?.gasEstimate,quoter:g?.quoter}}}}),YA[Number(e)]&&u.push({source:"uniswap-v4",run:async()=>{let g=await gi({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,recipient:n,slippageBps:s},l);return{amountOut:g?.amountOut,minOut:g?.minOut??g?.amountOutMinimum??null,gasUsd:null,liquidityUsd:g?.liquidityUsd??null,meta:{onchain:!0,venue:"uniswap-v4",fee:g?.fee,tickSpacing:g?.tickSpacing,poolId:g?.poolId,hooks:g?.hooks,gasUnits:g?.gasEstimate,quoter:g?.quoter,poolManager:g?.poolManager,prepareReady:g?.prepareReady===!0,executionReady:!1}}}}),u}Xo();Ut();var Ix={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"};async function hx(e,A,t){let r=Ix[Number(e)];if(!r)return{priceUsd:null,decimals:null};let n=`${r}:${A}`;try{let o=(await Ei([n],t))?.coins?.[n],i=Number(o?.price),a=Number(o?.decimals);return{priceUsd:Number.isFinite(i)?i:null,decimals:Number.isFinite(a)?a:null}}catch{return{priceUsd:null,decimals:null}}}async function U0(e,A={}){let{chainId:t,tokenIn:r,tokenOut:n,amountIn:s}=e;if(t==null||!r||!n||s==null)throw new Error("bestSwapRoute requires chainId, tokenIn, tokenOut, amountIn");let o=S0(t,A),i=hx(t,n,A),a=l0(t,A).catch(()=>null),c=Bl({...e,nativePriceUsd:o,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:A}),[l,u,g]=await Promise.all([Ci(c,{timeoutMs:A.timeoutMs??12e3}),i,a]);o.catch(()=>{});let E=await o.then(B=>B,()=>null),Q=Nl(l,{destPriceUsd:u.priceUsd,destDecimals:e.decimalsOut??u.decimals,liquidityBandBps:A.liquidityBandBps??50,gasPriceWei:g,nativePriceUsd:E}),h=A.maxImpactPct===void 0?25:A.maxImpactPct;if(h!=null&&Q.best){let B=Q.best.source,C=await Rl(async m=>{let y=Bl({...e,amountIn:m.toString(),nativePriceUsd:o,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:A}).filter(q=>q.source===B);return y.length?(await Ci(y,{timeoutMs:A.timeoutMs??12e3}))?.[0]?.amountOut??null:null},s);if(C){let m=Sl(Q,{[B]:C},{maxImpactPct:h});return{kind:"swap",chainId:t,tokenIn:r,tokenOut:n,amountIn:String(s),...m,sourcesTried:c.length,sourcesAnswered:l.filter(y=>y.quality!==fA.FAILED).length,note:N0(m,c.length),priceImpact:{[B]:Number(C.impactPct.toFixed(2))}}}}return{kind:"swap",chainId:t,tokenIn:r,tokenOut:n,amountIn:String(s),...Q,sourcesTried:c.length,sourcesAnswered:l.filter(B=>B.quality!==fA.FAILED).length,note:N0(Q,c.length)}}function Cx(e){let A=e?.meta?.oracleFee;return A?.applies?` \xB7 ${kf(A)}`:""}function N0(e,A){if(!e.best)return"no source returned a usable route";let t=e.routes.length,r=Cx(e.best);if(t===1)return`only 1 of ${A} sources answered, so this is the ONLY route, not a proven best one. Treat it as unbenchmarked.`+r;if(e.improvementBps!=null){let n=e.improvementBps,s=n/100;if(n<.01)return`best of ${t} routes, ranked on ${e.rankedOn}: effectively tied with the runner-up (${e.spreadBasis}), inside quote noise. Re-quote before you size up.`+r;let o=s>=.01?`${s.toFixed(2)}%`:`${n.toFixed(2)}bps`;return`best of ${t} routes, ranked on ${e.rankedOn}: ${o} better than the runner-up (${e.spreadBasis})`+r}return`best of ${t} routes, ranked on ${e.rankedOn}. No spread quoted: the top routes report cost differently, so the margin is not comparable.`+r}vA();var nt=Object.freeze({TRANSACTION:"unsigned-transaction",TYPED_DATA_ORDER:"typed-data-order"}),dx=100,Il={"uniswap-v3":async({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n},s)=>{let{uniV3PrepareExactIn:o}=await Promise.resolve().then(()=>(ui(),p0)),i=await o({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,recipient:n},s);return{artifactKind:nt.TRANSACTION,transaction:i.transaction,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.amountOut??null,minOut:i.quote?.amountOutMinimum??null}},"uniswap-v4":async({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n,slippageBps:s,fee:o,tickSpacing:i,hooks:a},c)=>{let{uniV4PrepareExactIn:l}=await Promise.resolve().then(()=>(El(),F0)),u=await l({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,recipient:n,slippageBps:s,fee:o,tickSpacing:i,hooks:a},c);return{artifactKind:nt.TRANSACTION,transaction:u.transaction,requiresApproval:u.requiresApproval,amountOut:u.quote?.amountOut??null,minOut:u.quote?.amountOutMinimum??null,prepareReady:!0,executionReady:!1}},lifi:async({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n},s)=>{let{lifiPrepare:o}=await Promise.resolve().then(()=>(el(),Uf)),i=await o({fromChain:e,toChain:e,fromToken:A,toToken:t,fromAmount:r,fromAddress:n},s);return{artifactKind:nt.TRANSACTION,transaction:i.transaction,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.estimate?.toAmount??null,minOut:i.quote?.estimate?.toAmountMin??null}},paraswap:async({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n,decimalsIn:s,decimalsOut:o},i)=>{let{paraswapPrepare:a}=await Promise.resolve().then(()=>(tl(),Tf)),c=await a({chainId:e,srcToken:A,destToken:t,amount:r,srcDecimals:s,destDecimals:o,userAddress:n,side:"SELL"},i);return{artifactKind:nt.TRANSACTION,transaction:c.transaction,requiresApproval:c.requiresApproval??null,amountOut:c.quote?.priceRoute?.destAmount??null,minOut:c.quote?.amountOutMinimum??null}},"0x":async({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n},s)=>{let{zeroxPrepare:o}=await Promise.resolve().then(()=>(nl(),qf)),i=await o({chainId:e,sellToken:A,buyToken:t,sellAmount:r,taker:n},s);return{artifactKind:nt.TRANSACTION,transaction:i.transaction,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.buyAmount??null,minOut:i.quote?.minBuyAmount??null}},cow:async({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n},s)=>{let{cowPrepareOrder:o}=await Promise.resolve().then(()=>(al(),r0)),i=await o({chainId:e,sellToken:A,buyToken:t,sellAmountBeforeFee:String(r),from:n},s);return{artifactKind:nt.TYPED_DATA_ORDER,typedData:i.typedData,requiresApproval:{token:A,spender:i.vaultRelayer,amount:String(r),note:"CoW pulls funds via the vault relayer, not the settlement contract"},settlement:i.settlement,amountOut:i.quote?.quote?.buyAmount??null,minOut:null,submission:"sign the typed data, then submit the order to the CoW API"}}};var fx=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),px=/^0x[0-9a-fA-F]{40}$/;async function M0(e,A={}){let{taker:t}=e;if(!t)throw new Error("prepareBestRoute requires taker: a prepared transaction is built FOR an address, and the quote-only placeholder must never end up in one");if(!px.test(t))throw new Error(`taker must be a valid 20-byte address, got "${t}"`);if(fx.has(t.toLowerCase()))throw new Error(`taker "${t}" is a placeholder/burn address. It is valid for quoting but not for preparing -- that would build a transaction for an address nobody controls. Pass the real wallet that will sign.`);let r=await U0(e,A);if(!r.best){let B=r.impactRejected??[];return{ok:!1,reason:B.length?B[0].reason:"no source returned a usable route",priceImpactBlocked:B.length>0,impactRejected:B,comparison:r}}let n=e.source||r.best.source,s=r.routes.find(B=>B.source===n);if(!s)return{ok:!1,reason:`source "${n}" did not return a usable route`,comparison:r};let o=Il[n];if(!o){let B=r.routes.find(I=>Il[I.source]&&I.source!==n);return{ok:!1,reason:`${n} won the comparison but has no prepare path in this build. `+(B?`Next preparable route is ${B.source}; pass source:"${B.source}" to use it.`:"No route in this comparison can be prepared."),comparison:r,winner:n}}let i;try{i=await o(e,A)}catch(B){let I=typeof B?.body=="string"?B.body:B?.body?JSON.stringify(B.body):"",C=[String(B?.message||B),I].filter(Boolean).join(" :: "),m=/allowance/i.test(C),y=!m&&/not enough|insufficient|balance/i.test(C),L,q;m?(q="approval-required-first",L=`${n} will not build swap calldata until the token approval exists on-chain. Approve the spender first, then prepare again. Underlying: ${C}`):y?(q="taker-not-funded",L=`${n} refused to build the transaction: ${C}. This venue verifies the taker holds the input token. Quoting works for any address; preparing needs the real funded wallet.`):(q="provider-error",L=`${n} prepare failed: ${C}`);let _=r.routes.find(N=>Il[N.source]&&N.source!==n);return{ok:!1,reason:L,failureKind:q,..._?{alternative:_.source}:{},comparison:r}}let a=e.driftToleranceBps??dx,c=null,l=null;if(i.amountOut!=null&&s.grossOut!=null)try{let B=BigInt(s.grossOut),I=BigInt(i.amountOut);B>0n&&(c=Number((I-B)*10000n/B),c<-a&&(l=`route moved ${(c/100).toFixed(2)}% against you between the comparison and this prepare (tolerance ${(a/100).toFixed(2)}%). The ranking may no longer hold -- re-run the comparison before signing.`))}catch{}let u=r.routes.filter(B=>B.source!==n).map(B=>({source:B.source,netOut:B.netOut,gasUsd:B.gasUsd})),E=r.routes.map(B=>({source:B.source,liquidityUsd:B.liquidityUsd??null})).reduce((B,I)=>Math.max(B,I.liquidityUsd??0),0)||null,Q=s.liquidityUsd??null,h=Q!=null&&E>0?Math.round(Q/E*100):null;return de({ok:!0,chosen:{source:n,wasWinner:n===r.best.source,netOut:s.netOut,grossOut:s.grossOut,gasUsd:s.gasUsd,liquidityUsd:s.liquidityUsd??null},liquidity:{chosenUsd:Q,maxUsd:E,sharePct:h},priceImpact:r.priceImpact??null,impactUnmeasured:r.impactUnmeasured??[],...i,unsigned:!0,signedBy:"user-wallet",destination:i.artifactKind===nt.TRANSACTION?i.transaction?.to??null:i.settlement??null,driftBps:c,warnings:[...l?[l]:[],...r.warnings||[],...i.artifactKind===nt.TYPED_DATA_ORDER?["This is an ORDER to sign, not a transaction to broadcast. Signing it authorizes a solver to settle on your behalf."]:[]],runnersUp:u,comparison:{rankedOn:r.rankedOn,sourcesAnswered:r.sourcesAnswered,sourcesTried:r.sourcesTried,improvementBps:r.improvementBps},note:"UNSIGNED. Verify the destination address and minOut against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."},{provider:"router",kind:"best-route"})}Ut();ii();Ut();var Cl={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},Ke=e=>BigInt(e).toString(16).padStart(64,"0"),Pn=e=>e.slice(2).toLowerCase().padStart(64,"0");function wx(e,A){return`0x${Cl.getAmountsOut}`+Ke(e)+Ke(64)+Ke(A.length)+A.map(Pn).join("")}function mx(e){if(!e||e==="0x")return null;let A=e.slice(2);if(A.length<128)return null;let t=Number(BigInt(`0x${A.slice(64,128)}`));if(!Number.isFinite(t)||t<1||t>16)return null;let r=[];for(let n=0;n<t;n++){let s=128+n*64;if(A.length<s+64)return null;r.push(BigInt(`0x${A.slice(s,s+64)}`))}return r}function hl(e,A="router"){return(e?.venues||[]).find(r=>r.kind===A)?.address??null}var dl=100;function yx(e,A){let t=Number(A);if(!Number.isFinite(t)||t<0)throw new Error("slippageBps must be a non-negative number");if(t>dl)throw new Error(`slippageBps ${t} exceeds the ${dl} 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(t))/10000n}function L0(e){let{chainId:A,wrappedNative:t}=e;async function r(n,s,o,i){let a=await Be(A,"eth_call",[{to:n,data:wx(s,o)},"latest"],i);return mx(a?.result??a)}return{async quote({tokenIn:n,tokenOut:s,amountIn:o,path:i},a={}){let c=hl(a.scanner);if(!c)return{chainId:A,evidence:J.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let l=i||[n,s];if(l.some(g=>!/^0x[0-9a-fA-F]{40}$/.test(g||"")))throw new Error("quote requires valid 20-byte addresses");let u=await r(c,o,l,a);return u?{chainId:A,router:c,path:l,amountIn:String(o),amountOut:u[u.length-1].toString(),hops:l.length-1,evidence:J.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:A,router:c,path:l,evidence:J.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:n,amountIn:s,base:o},i={}){let a=hl(i.scanner),c=o||t;if(c&&String(n).toLowerCase()===String(c).toLowerCase())return{chainId:A,token:n,verdict:x.UNKNOWN,evidence:J.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(!a||!c)return{chainId:A,token:n,verdict:x.UNKNOWN,evidence:J.UNAVAILABLE,reason:a?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let l=await r(a,s,[c,n],i);if(!l)return{chainId:A,token:n,verdict:x.FAIL,evidence:J.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let u=l[l.length-1];if(u===0n)return{chainId:A,token:n,verdict:x.FAIL,evidence:J.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let g=await r(a,u,[n,c],i);if(!g)return{chainId:A,token:n,verdict:x.FAIL,evidence:J.LIVE,leg:"sell",bought:u.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let E=g[g.length-1],Q=Number(E*10000n/BigInt(s)),h=x.PASS,B="round trip completes with expected fee/impact loss";return Q<5e3?(h=x.FAIL,B=`round trip returns only ${(Q/100).toFixed(2)}% -- punitive tax or no real liquidity`):Q<9e3&&(h=x.CAUTION,B=`round trip returns ${(Q/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:A,token:n,base:c,router:a,verdict:h,reason:B,amountIn:String(s),bought:u.toString(),returned:E.toString(),retentionBps:Q,evidence:J.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:n,tokenOut:s,amountIn:o,recipient:i,slippageBps:a=50,deadlineSeconds:c=900,path:l},u={}){let g=u.scanner,E=hl(g);if(!E)throw new Error(`chain ${A} 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(i||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let Q=l||[n,s],h=await this.quote({tokenIn:n,tokenOut:s,amountIn:o,path:Q},u);if(h.evidence!==J.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let B=yx(h.amountOut,a);if(B<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let I=BigInt(Math.floor(Date.now()/1e3)+Number(c)),C=t&&Q[0].toLowerCase()===t.toLowerCase()&&u.useNative,m=C?`0x${Cl.swapExactETHForTokens}`+Ke(B)+Ke(128)+Pn(i)+Ke(I)+Ke(Q.length)+Q.map(Pn).join(""):`0x${Cl.swapExactTokensForTokens}`+Ke(o)+Ke(B)+Ke(160)+Pn(i)+Ke(I)+Ke(Q.length)+Q.map(Pn).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:A,tx:{to:E,data:m,value:C?`0x${BigInt(o).toString(16)}`:"0x0"},guard:{quotedOut:h.amountOut,minOut:B.toString(),slippageBps:a,maxSlippageBps:dl,deadline:I.toString()},requires:C?[]:[{step:"approve",token:Q[0],spender:E,amount:String(o)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}Ut();var Dx=[100,500,3e3,1e4],T0={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},Lt=e=>BigInt(e).toString(16).padStart(64,"0"),_n=e=>e.slice(2).toLowerCase().padStart(64,"0"),x0=/^0x[0-9a-fA-F]{40}$/,pl=100;function bx(e,A){let t=Number(A);if(!Number.isFinite(t)||t<0)throw new Error("slippageBps must be a non-negative number");if(t>pl)throw new Error(`slippageBps ${t} exceeds the ${pl} 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(t))/10000n}function fl(e,A){return(e?.venues||[]).find(t=>t.kind===A)?.address??null}function v0(e){let{chainId:A,wrappedNative:t}=e;async function r({quoter:s,tokenIn:o,tokenOut:i,amountIn:a,fee:c},l){let u=`0x${T0.quoteExactInputSingle}`+_n(o)+_n(i)+Lt(a)+Lt(c)+Lt(0),g=await Be(A,"eth_call",[{to:s,data:u},"latest"],l).catch(()=>null),E=g?.result??g;if(!E||E==="0x"||E.length<66)return null;let Q=BigInt(`0x${E.slice(2,66)}`);return Q>0n?Q:null}async function n({quoter:s,tokenIn:o,tokenOut:i,amountIn:a},c){let l=[],u=null;for(let g of Dx){let E=await r({quoter:s,tokenIn:o,tokenOut:i,amountIn:a,fee:g},c);l.push({fee:g,amountOut:E?E.toString():null}),E&&(!u||E>u.amountOut)&&(u={fee:g,amountOut:E})}return{best:u,tried:l}}return{async quote({tokenIn:s,tokenOut:o,amountIn:i},a={}){let c=fl(a.scanner,"quoter");if(!c)return{chainId:A,evidence:J.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let g of[s,o])if(!x0.test(g||""))throw new Error("quote requires valid 20-byte addresses");let{best:l,tried:u}=await n({quoter:c,tokenIn:s,tokenOut:o,amountIn:i},a);return l?{chainId:A,venue:"uniswap-v3",quoter:c,tokenIn:s,tokenOut:o,amountIn:String(i),amountOut:l.amountOut.toString(),fee:l.fee,useNative:!!t&&String(s).toLowerCase()===String(t).toLowerCase(),triedFeeTiers:u,evidence:J.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:A,quoter:c,tokenIn:s,tokenOut:o,triedFeeTiers:u,evidence:J.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:s,amountIn:o,base:i},a={}){let c=fl(a.scanner,"quoter"),l=i||t;if(l&&String(s).toLowerCase()===String(l).toLowerCase())return{chainId:A,token:s,verdict:x.UNKNOWN,evidence:J.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||!l)return{chainId:A,token:s,verdict:x.UNKNOWN,evidence:J.UNAVAILABLE,reason:c?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let u=await n({quoter:c,tokenIn:l,tokenOut:s,amountIn:o},a);if(!u.best)return{chainId:A,token:s,verdict:x.FAIL,evidence:J.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier"};let g=await n({quoter:c,tokenIn:s,tokenOut:l,amountIn:u.best.amountOut},a);if(!g.best)return{chainId:A,token:s,verdict:x.FAIL,evidence:J.LIVE,leg:"sell",bought:u.best.amountOut.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let E=g.best.amountOut,Q=Number(E*10000n/BigInt(o)),h=x.PASS,B="round trip completes with expected fee/impact loss";return Q<5e3?(h=x.FAIL,B=`round trip returns only ${(Q/100).toFixed(2)}% -- punitive tax or no real liquidity`):Q<9e3&&(h=x.CAUTION,B=`round trip returns ${(Q/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:A,venue:"uniswap-v3",token:s,base:l,verdict:h,reason:B,amountIn:String(o),bought:u.best.amountOut.toString(),returned:E.toString(),retentionBps:Q,buyFee:u.best.fee,sellFee:g.best.fee,evidence:J.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:s,tokenOut:o,amountIn:i,recipient:a,slippageBps:c=50,fee:l},u={}){let g=fl(u.scanner,"router");if(!g)throw new Error(`chain ${A} 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(!x0.test(a||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let E=await this.quote({tokenIn:s,tokenOut:o,amountIn:i},u);if(E.evidence!==J.LIVE)throw new Error(`cannot prepare without a live quote (${E.evidence}: ${E.reason??"no reason given"})`);let Q=l??E.fee,h=bx(E.amountOut,c);if(h<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let B=!!(u.useNative||E.useNative)&&t&&String(s).toLowerCase()===String(t).toLowerCase(),I=`0x${T0.exactInputSingle}`+_n(s)+_n(o)+Lt(Q)+_n(a)+Lt(i)+Lt(h)+Lt(0);return{unsigned:!0,signedBy:"user-wallet",chainId:A,venue:"uniswap-v3",tx:{to:g,data:I,value:B?String(i):"0x0"},guard:{quotedOut:E.amountOut,minOut:h.toString(),slippageBps:c,maxSlippageBps:pl,fee:Q},requires:B?[]:[{step:"approve",token:s,spender:g,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 Qi={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function Y0(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function G0(e){if(!e||e==="0x")return null;let A=e.slice(2);if(A.length>=128){let r=Number(BigInt(`0x${A.slice(64,128)}`));if(r>0&&r<=256&&A.length>=128+r*2){let n=A.slice(128,128+r*2),s=Buffer.from(n,"hex").toString("utf8").replace(/\0+$/,"");if(s)return s}}return Buffer.from(A.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function kx(e){let{chainId:A}=e;async function t(r,n,s){return Be(A,"eth_call",[{to:r,data:n},"latest"],s)}return{async blockNumber(r={}){let n=await u0(A,r);return{chainId:A,blockNumber:n?.blockNumber??n,evidence:J.LIVE}},async nativeBalance(r,n={}){let s=await g0(A,r,n);return{chainId:A,address:r,wei:s?.wei??s?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:J.LIVE}},async tokenBalance({token:r,owner:n},s={}){let o=await E0({chainId:A,token:r,owner:n},s);return{chainId:A,token:r,owner:n,raw:o?.balance??o,evidence:J.LIVE}},async resolveToken(r,n={}){if(!/^0x[0-9a-fA-F]{40}$/.test(r||""))return{chainId:A,token:r,evidence:J.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[s,o,i,a]=await Promise.all([t(r,Qi.decimals,n).catch(()=>null),t(r,Qi.symbol,n).catch(()=>null),t(r,Qi.name,n).catch(()=>null),t(r,Qi.totalSupply,n).catch(()=>null)]),c=Y0(s?.result??s),l=c!==null||o?.result||i?.result;return{chainId:A,address:r,decimals:c===null?null:Number(c),symbol:G0(o?.result??o),name:G0(i?.result??i),totalSupply:(Y0(a?.result??a)??null)?.toString()??null,evidence:l?J.LIVE:J.UNKNOWN,warning:l?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(r,n={}){let s=e.dexscreenerSlug;if(!s)return{chainId:A,token:r,pools:[],evidence:J.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let o=await cl(r,n).catch(()=>null),a=(o?.pairs||o?.data?.pairs||[]).filter(c=>String(c.chainId).toLowerCase()===String(s).toLowerCase()).map(c=>({pair:c.pairAddress,dex:c.dexId,base:c.baseToken?.address,quote:c.quoteToken?.address,liquidityUsd:c.liquidity?.usd??null,priceUsd:c.priceUsd??null,volume24hUsd:c.volume?.h24??null,createdAt:c.pairCreatedAt??null})).sort((c,l)=>(l.liquidityUsd??0)-(c.liquidityUsd??0));return{chainId:A,token:r,pools:a,evidence:a.length?J.LIVE:J.UNKNOWN}},async scanBlocks({fromBlock:r,toBlock:n,address:s,topics:o,chunkSize:i=2e3}={},a={}){if(!Number.isInteger(r)||!Number.isInteger(n))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(n<r)throw new Error("toBlock must be >= fromBlock");let c=[],l=[];for(let u=r;u<=n;u+=i){let g=Math.min(u+i-1,n);l.push([u,g])}for(let[u,g]of l){let E={fromBlock:`0x${u.toString(16)}`,toBlock:`0x${g.toString(16)}`};s&&(E.address=s),o&&(E.topics=o);let Q=await Be(A,"eth_getLogs",[E],a).catch(h=>({error:String(h?.message||h)}));if(Q?.error)return{chainId:A,fromBlock:r,toBlock:n,logs:c,complete:!1,failedAt:[u,g],error:Q.error,evidence:J.UNKNOWN};for(let h of Q?.result??Q??[])c.push(h)}return{chainId:A,fromBlock:r,toBlock:n,logs:c,complete:!0,chunks:l.length,evidence:J.LIVE}},async scoreRisk(r,n={}){let s=[],o=x.PASS,i=l=>{let u={[x.PASS]:0,[x.CAUTION]:1,[x.UNKNOWN]:2,[x.FAIL]:3};u[l]>u[o]&&(o=l)},a=await this.resolveToken(r,n);a.evidence!==J.LIVE?(s.push({check:"erc20-metadata",result:x.UNKNOWN,detail:a.warning}),i(x.UNKNOWN)):s.push({check:"erc20-metadata",result:x.PASS,detail:`${a.symbol} / ${a.decimals}d`});let c=await this.resolvePools(r,n);if(c.evidence===J.UNAVAILABLE)s.push({check:"liquidity",result:x.UNKNOWN,detail:c.reason}),i(x.UNKNOWN);else if(!c.pools.length)s.push({check:"liquidity",result:x.FAIL,detail:"no pool with liquidity found"}),i(x.FAIL);else{let l=c.pools[0],u=l.liquidityUsd??0;u<5e3?(s.push({check:"liquidity",result:x.CAUTION,detail:`top pool only $${u}`}),i(x.CAUTION)):s.push({check:"liquidity",result:x.PASS,detail:`$${u} on ${l.dex}`}),l.createdAt&&Date.now()-l.createdAt<24*3600*1e3&&(s.push({check:"age",result:x.CAUTION,detail:"pool under 24h old"}),i(x.CAUTION))}if(typeof this.sellSimulation=="function"){let l=await this.sellSimulation({token:r,amountIn:(10n**16n).toString()},n).catch(u=>({verdict:x.UNKNOWN,reason:String(u?.message||u)}));s.push({check:"sellability",result:l.verdict,detail:l.retentionBps!=null?`round trip returns ${(l.retentionBps/100).toFixed(2)}% -- ${l.reason}`:l.reason}),i(l.verdict)}else s.push({check:"sellability",result:x.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."}),i(x.UNKNOWN);return{chainId:A,token:r,verdict:o,checks:s,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function J0(e){let t={...kx(e)},r=new Set((e.venues||[]).map(s=>s.kind));e.venueKind==="uniswap-v3"&&r.has("quoter")&&r.has("router")?Object.assign(t,v0({chainId:e.chainId,wrappedNative:e.wrappedNative})):e.venueKind==="uniswap-v2"&&r.has("router")&&Object.assign(t,L0({chainId:e.chainId,wrappedNative:e.wrappedNative}));let n={};for(let[s,o]of Object.entries(t))n[s]=o.bind(t);return{key:e.key,chainId:e.chainId,name:e.name,rpcEnv:e.rpcEnv,nativeCurrency:e.nativeCurrency,explorer:e.explorer,venues:e.venues||[],capabilities:n}}var Fx=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",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",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",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",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",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",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",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",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 H0(){return Fx.map(e=>Dl(J0(e)))}ui();var wl=/^0x[0-9a-fA-F]{40}$/,Rx=24,V0=!1;function W0(){V0||(H0(),V0=!0)}var Ie=class extends Error{constructor(A,t){super(t),this.status=A}};function Sx(e){if(W0(),e==null||e==="")throw new Ie(400,"chainId is required");let A=Number(e);if(Number.isFinite(A)&&Kn(A))return A;let t=bl().find(r=>r.key===String(e).toLowerCase());if(t)return t.chainId;throw new Ie(400,`unknown chain "${e}"`)}function q0(e,A){if(typeof e!="string")throw new Ie(400,`${A} is required`);let t=e.trim();if(t===""||t.length>Rx)throw new Ie(400,`${A} is invalid`);if(!/^[A-Za-z0-9._-]+$/.test(t)&&!wl.test(t))throw new Ie(400,`${A} is invalid`);return t}function Nx(e,A){let t=String(e).trim();if(!/^\d+(\.\d+)?$/.test(t))throw new Ie(400,"sellAmount must be a positive decimal number");if(Number(t)<=0)throw new Ie(400,"sellAmount must be greater than zero");let r=Number.isFinite(Number(A))?Number(A):18,[n,s=""]=t.split(".");if(s.length>r)throw new Ie(400,`sellAmount has more precision than the token's ${r} decimals`);let o=s.padEnd(r,"0"),i=(BigInt(n)*10n**BigInt(r)+BigInt(o||"0")).toString();if(i==="0")throw new Ie(400,"sellAmount rounds to zero at this token's precision");return i}async function O0(e,A){if(W0(),wl.test(A)){let c=await Kn(e).resolveToken(A).catch(()=>null),l=Number(c?.decimals);return{address:A,decimals:Number.isFinite(l)?l:null}}let t=Ne[e];if(!t)return null;let r=A.toLowerCase(),n=r==="usdc"?t.usdc:r==="weth"||r==="eth"?t.weth:null;if(!n)return null;let o=await Kn(e).resolveToken(n).catch(()=>null),i=Number(o?.decimals);return{address:n,decimals:Number.isFinite(i)?i:null}}async function P0(e={},A={}){let t=Sx(e.chainId??e.chain),r=q0(e.sellSymbol??e.sellToken,"sellSymbol"),n=q0(e.buySymbol??e.buyToken,"buySymbol");if(r.toLowerCase()===n.toLowerCase())throw new Ie(400,"sell and buy assets must differ");let s=typeof e.taker=="string"?e.taker.trim():"";if(!wl.test(s))throw new Ie(400,"taker must be the wallet address that will sign");let[o,i]=await Promise.all([O0(t,r),O0(t,n)]);if(!o)throw new Ie(400,`could not resolve sell asset "${r}" on chain ${t}`);if(!i)throw new Ie(400,`could not resolve buy asset "${n}" on chain ${t}`);let a=Nx(e.sellAmount,o.decimals),c=await M0({chainId:t,tokenIn:o.address||r,tokenOut:i.address||n,amountIn:a,taker:s,decimalsIn:o.decimals??null,decimalsOut:i.decimals??null,source:typeof e.source=="string"&&e.source.trim()!==""?e.source.trim():void 0},A);if(!c.ok)return{ok:!1,reason:c.reason,priceImpactBlocked:!!c.priceImpactBlocked,requiresWalletSignature:!0,backendSigner:!1};let l=i.decimals??18,u=c.minOut??c.chosen?.netOut??c.chosen?.grossOut??null;return{ok:!0,requiresWalletSignature:!0,backendSigner:!1,quote:{sellSymbol:r,buySymbol:n,sellAmount:String(e.sellAmount),buyAmount:u==null?null:String(u),buyAmountFormatted:u==null?null:(Number(u)/10**l).toString(),routeLabel:c.chosen?.source??null,priceImpactPct:Number.isFinite(Number(c.chosen?.priceImpactPct))?Number(c.chosen.priceImpactPct):null,slippageBps:Number.isFinite(Number(c.slippageBps))?Number(c.slippageBps):null,intentHash:c.intentHash??null,minOut:c.minOut??null,requiresApproval:c.requiresApproval??null,warnings:Array.isArray(c.warnings)?c.warnings:[]},transaction:c.transaction??null}}var ml=`oracle swap <chain> <sellAsset> <buyAsset> <amount> --taker <address> [--source X] [--json]
49
49
 
50
50
  oracle swap base USDC WETH 5 --taker 0xYourWallet
51
51
  oracle swap 8453 0x8335...913 WETH 5 --taker 0xYourWallet --json
@@ -1,3 +1,3 @@
1
- var x={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}},xe=new Map(Object.values(x).map(e=>[e.chainId,e]));import I from"node:fs";import k from"node:path";import{homedir as re}from"node:os";function y(e){let t=e?.transactionHash||e?.hash||e?.txid||null;return t?{happened:!0,hash:String(t),note:null}:{happened:!1,hash:null,note:"no transaction hash \u2014 the action did not succeed"}}import c from"node:path";import Q from"node:os";import{createHash as ee,randomBytes as bn}from"node:crypto";import{Transaction as An}from"@scure/btc-signer";import{ed25519 as In}from"@noble/curves/ed25519.js";import{base58 as it}from"@scure/base";import{Interface as W,MaxUint256 as nr,isAddress as or,keccak256 as ir,toUtf8Bytes as ar}from"ethers";import{Interface as j,isAddress as Fe}from"ethers";import{isAddress as Re}from"ethers";var je=new j(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as D,isAddress as Ve}from"ethers";var Je=new D(["function approve(address spender,uint256 amount) returns (bool)"]),Ke=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});var dr=new W(["function approve(address spender,uint256 amount) returns (bool)"]);var mr=300*1e3,hr=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();import{Address as xr,NETWORK as yr,OutScript as br,RawTx as vr,SigHash as Ar,TEST_NETWORK as Or,Transaction as Ir}from"@scure/btc-signer";import{getCompiledTransactionMessageDecoder as Nr}from"@solana/transaction-messages";var H=new Set(["evm","evm-swap","evm-bridge","evm-nft","btc","sol"]);var jr=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0});var z=Object.freeze({"0x04e45aaf":{provider:"uniswap-v3",action:"swap",layout:"router02-exact-input-single"},"0x414bf389":{provider:"uniswap-v3",action:"swap",layout:"swap-router-exact-input-single"},"0x7b939232":{provider:"across-v3",action:"bridge",layout:"across-deposit-v3"}}),Dr=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"}});var J=Object.freeze([...H]),Wr=Object.freeze({...z});import{ed25519 as Hr}from"@noble/curves/ed25519.js";import{base58 as Jr}from"@scure/base";import{RawTx as Zr,SigHash as Xr,Transaction as Yr}from"@scure/btc-signer";import{Transaction as et}from"ethers";var gt=Object.freeze({N:1<<17,r:8,p:1}),Et=256*1024*1024,St=16*1024;import{homedir as A}from"node:os";import{join as O}from"node:path";var N=process.env.ORACLE_PUBLIC_DESKTOP==="1",X=N?process.env.ORACLE_CONFIG_DIR||O(A(),".config","oracle"):O(A(),".config","oracle"),vt=N?X:O(A(),".config","mad-desk");var Lt="0".repeat(64),Nt=Object.freeze({PREPARE:"exec.prepare",SIGN:"exec.sign",BROADCAST:"exec.broadcast",POLICY_REJECT:"policy.reject",AUTH_GRANT:"auth.grant",AUTH_OK:"auth.verify.ok",AUTH_FAIL:"auth.verify.fail"});var Tt=Promise.resolve();import{Wallet as qt}from"ethers";import{base58 as jt}from"@scure/base";import{ed25519 as Wt}from"@noble/curves/ed25519.js";import{NETWORK as Gt,TEST_NETWORK as Ht,WIF as zt,p2wpkh as Jt}from"@scure/btc-signer";import{pubECDSA as Zt}from"@scure/btc-signer/utils.js";function R(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||c.join(process.env.XDG_STATE_HOME||c.join(Q.homedir(),".local","state"),"oracle"),r=ee("sha256").update(c.resolve(e)).digest("hex").slice(0,16);return{vault:c.join(e,"vault.json"),policy:c.join(e,"signer-policy.json"),policyKey:c.join(e,"policy-integrity-key"),policyAnchor:c.join(t,`signer-policy-${r}.high-water`),ledger:c.join(e,"signer-ledger.json"),ledgerAnchor:c.join(t,`signer-ledger-${r}.high-water`),token:c.join(e,"signer-token"),lock:c.join(t,`signer-${r}.lock`)}}function te(){return process.env.ORACLE_CONFIG_DIR||k.join(re(),".config","oracle")}function h(){let e=R(k.join(te(),"signer")),t=I.existsSync(e.vault),r=I.existsSync(e.lock),o=t?r?"disarmed":"armed-owner-confirmed":"inert-no-key";return{vaultExists:t,policyConfigured:I.existsSync(e.policy),armed:t&&!r,disarmed:r,capabilities:{swap:o,bridge:o},autonomous:!1,note:"Keys stay on this machine. Exact confirmation is required before any broadcast."}}var Kn=Object.freeze([{type:"function",function:{name:"vault_status",description:"Read local Oracle vault/signer readiness. Never returns key material.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_status",description:"Ping the loopback signer. Fails closed if it is not running.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_execute",description:"Broadcast one already-confirmed local artifact. Requires a one-use confirmationNonce from the local signer TTY confirm. Cannot mint confirmation itself.",parameters:{type:"object",properties:{artifact:{type:"object"},confirmationNonce:{type:"string",minLength:32,maxLength:128}},required:["artifact","confirmationNonce"],additionalProperties:!1}}},{type:"function",function:{name:"signer_disarm",description:"Global kill switch. Stops the local signer from broadcasting.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"receipt_report",description:"Receipt or it did not happen. Requires transactionHash/hash/txid.",parameters:{type:"object",properties:{receipt:{type:"object"},transactionHash:{type:"string"},hash:{type:"string"},txid:{type:"string"}},additionalProperties:!1}}},{type:"function",function:{name:"watch_create",description:"Create an alert-only watch. Never execute.",parameters:{type:"object",properties:{chain:{type:"string"},token:{type:"string"},condition:{type:"string"},note:{type:"string"}},required:["chain","token","condition"],additionalProperties:!1}}},{type:"function",function:{name:"watch_list",description:"List local alert-only watches.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"portfolio_snapshot",description:"How to read the one portfolio snapshot. knownUsd is incomplete if a provider is missing.",parameters:{type:"object",properties:{},additionalProperties:!1}}}]);import P from"node:fs";import pe from"node:path";import w from"node:fs";import ne from"node:os";import d from"node:path";import{fileURLToPath as oe}from"node:url";var ie=d.dirname(oe(import.meta.url)),ro=d.resolve(ie,"../..");function C(){return process.env.ORACLE_FAKE_HOME||ne.homedir()}function ae(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function g(){return ae()?process.env.ORACLE_CONFIG_DIR||d.join(C(),".config","oracle"):d.join(C(),".config","oracle")}function se(){return d.join(g(),"desk.json")}function ce(){return d.join(g(),"env")}function l({force:e=!1}={}){if(l._done&&!e)return l._result||null;l._done=!0;let t={},r=(i,n)=>{if(n==null)return;let a=String(n).trim();a&&(process.env[i]!=null&&String(process.env[i]).trim()!==""||(process.env[i]=a,t[i]=a))};try{let i=ce();if(w.existsSync(i))for(let n of w.readFileSync(i,"utf8").split(/\r?\n/)){let a=n.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!a||a[2].startsWith("#"))continue;let s=a[2];(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),r(a[1],s)}}catch{}try{let i=se();if(w.existsSync(i)){let n=JSON.parse(w.readFileSync(i,"utf8"));n&&typeof n=="object"&&(r("ORACLE_DESK_URL",n.deskUrl||n.dataUrl||n.url),r("ORACLE_DATA_URL",n.dataUrl||n.deskUrl||n.url),r("ORACLE_API_URL",n.apiUrl||n.dataUrl||n.deskUrl),r("ORACLE_PUBLIC_URL",n.publicUrl||n.deskUrl||n.dataUrl),r("ORACLE_EXEC_URL",n.execUrl),r("MAD_DESK_URL",n.deskUrl||n.dataUrl))}}catch{}let o=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return o&&(r("ORACLE_DESK_URL",o),r("ORACLE_DATA_URL",o),r("ORACLE_API_URL",o),r("ORACLE_PUBLIC_URL",o),r("MAD_DESK_URL",o)),l._result=Object.keys(t).length?t:null,l._result}try{l()}catch{}var ue=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","custom","anthropic-oauth","openai-codex","xai-oauth"]);function E(e){return String(e||"").trim()||void 0}function fe(e,{required:t=!1}={}){let r=E(e)?.toLowerCase();if(!r){if(t)throw new Error("model provider is required");return}if(!ue.has(r))throw new Error(`unsupported provider: ${r}`);return r}function le(e,{required:t=!1}={}){let r=E(e);if(!r){if(t)throw new Error("model is required");return}if(r.includes("..")||r.startsWith("/")||!/^[a-zA-Z0-9._:/-]{1,200}$/.test(r))throw new Error("invalid model id");return r}function de(e){let t=E(e);if(!t||t.length>2048)throw new Error("invalid custom base URL");let r;try{r=new URL(t)}catch{throw new Error("invalid custom base URL")}let o=r.hostname.toLowerCase().replace(/^\[|\]$/g,""),i=o==="localhost"||o==="127.0.0.1"||o==="::1";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&i)||r.username||r.password||r.search||r.hash)throw new Error("custom base URL must use HTTPS or loopback HTTP without credentials, query, or fragment");return r.toString().replace(/\/+$/,"")}function B({provider:e,model:t,baseUrl:r}={},{requireModel:o=!1}={}){let i=fe(e),n=le(t,{required:o});if(i==="custom")return{provider:i,...n?{model:n}:{},baseUrl:de(r)};if(E(r))throw new Error("baseUrl is only supported for the custom provider");return{...i?{provider:i}:{},...n?{model:n}:{}}}var me=new Set(["auto","standalone","hermes","remote","arch"]);function he(){return pe.join(g(),"model.json")}function p(e){return String(e||"").trim()||void 0}function we(e={}){let t=p(e.backend)?.toLowerCase()||"auto",r=B({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:t==="standalone"}),o=p(e.apiKeyEnv),i=Number.parseInt(String(e.contextLength||""),10),n=p(e.reasoningEffort),a=p(e.computeHost||e.remoteHost),s=p(e.computeUser||e.remoteUser),u=p(e.computePath||e.remotePath);if(!me.has(t))throw new Error(`unsupported backend: ${t}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(t))throw new Error("remote compute backends are disabled in the public desktop");if(o&&!/^[A-Z][A-Z0-9_]*$/.test(o))throw new Error("api key env must be an uppercase environment variable name");if(t==="remote"&&!a)throw new Error("remote backend requires computeHost");return{backend:t,...r,...o?{apiKeyEnv:o}:{},...Number.isFinite(i)&&i>0?{contextLength:i}:{},...n?{reasoningEffort:n}:{},...a?{computeHost:a}:{},...s?{computeUser:s}:{},...u?{computePath:u}:{}}}function $(){let e=he();if(!P.existsSync(e))return null;try{return we(JSON.parse(P.readFileSync(e,"utf8")))}catch{return null}}var ge=new Set(["127.0.0.1","::1","localhost"]);function _({env:e=process.env,vault:t=null}={}){let r=t||h(),o=[];for(let[i,n]of Object.entries(x)){let a=(n.rpcEnv||[]).some(u=>String(e[u]||"").trim()),s="prepare";n.evm?a&&(s="live"):s="unavailable",o.push({key:i,chainId:n.chainId,name:n.name,family:"evm",status:s,execute:!!(r.vaultExists&&r.armed&&!r.disarmed),note:a?"rpc configured":"public read/prepare; set RPC for live reads"})}return o.push({key:"solana",chainId:null,name:"Solana",family:"sol",status:"prepare",execute:!1,note:"Jupiter quote/prepare; local sol signer"},{key:"bitcoin",chainId:null,name:"Bitcoin",family:"btc",status:"prepare",execute:!1,note:"Esplora read; local btc signer"},{key:"hyperliquid-l1",chainId:null,name:"Hyperliquid L1",family:"data",status:"live",execute:!1,note:"data/prepare only \u2014 not an EVM signer family"},{key:"polymarket",chainId:null,name:"Polymarket",family:"data",status:"live",execute:!1,note:"data/prepare only \u2014 not a signer family"}),o}function Ee({env:e=process.env,model:t=$(),vault:r=h(),signerReachable:o=!1,quote:i=null}={}){let n=[],a=(f,S,F,M=null)=>n.push({id:f,status:S,detail:F,fix:M}),s=(()=>{let[f,S]=process.versions.node.split(".").map(Number);return f>20||f===20&&S>=19})();a("node",s?"ok":"fail",`node ${process.versions.node}`,s?null:"install node >= 20.19"),t?t.backend==="hermes"?a("model","warn","backend=hermes (opt-in attach)","oracle model --backend standalone"):a("model","ok",`${t.backend||"auto"} ${t.provider||""} ${t.model||""}`.trim()):a("model","fail","no model.json","oracle setup model"),r.vaultExists?r.disarmed?a("vault","warn","vault present, DISARMED","oracle signer (re-arm after confirm)"):a("vault",r.armed?"ok":"warn",r.armed?"present, armed":"present, not armed"):a("vault","fail","no local vault","oracle sign init");let u=e.ORACLE_SIGNER_HOST||"127.0.0.1";return ge.has(u)?a("signer",o?"ok":"warn",o?`loopback ${u}:${e.ORACLE_SIGNER_PORT||9462}`:"loopback signer not reachable",o?null:"oracle signer"):a("signer","fail",`signer host ${u} is not loopback`,"unset ORACLE_SIGNER_HOST"),i?i.ok?a("quote","ok",i.detail||"net quote returned"):a("quote","warn",i.detail||"quote unavailable","check network / oracle data serve"):a("quote","warn","quote not probed",null),{ok:!n.some(f=>f.status==="fail"),checks:n,venues:_({env:e,vault:r})}}async function Eo(e=process.env){let t=e.ORACLE_SIGNER_HOST||"127.0.0.1",r=e.ORACLE_SIGNER_PORT||9462;try{return(await fetch(`http://${t}:${r}/status`,{signal:AbortSignal.timeout(1500)})).ok}catch{return!1}}async function So(){try{let e=await fetch("https://api.dexscreener.com/latest/dex/search?q=WETH%20USDC",{signal:AbortSignal.timeout(4e3)});if(!e.ok)return{ok:!1,detail:`dexscreener ${e.status}`};let r=(await e.json())?.pairs?.[0];return!r?.chainId||!r?.priceUsd?{ok:!1,detail:"no pair"}:{ok:!0,detail:`${r.chainId} ${r.baseToken?.symbol}/${r.quoteToken?.symbol} $${r.priceUsd}`}}catch(e){return{ok:!1,detail:e instanceof Error?e.message:"quote failed"}}}var xo={name:"venues",summary:"label every shipped venue live / prepare / unavailable",group:"read",usage:"oracle venues [--json]",async run(e){let t=e.argv.includes("--json"),r=_();if(t)return process.stdout.write(`${JSON.stringify({venues:r},null,2)}
1
+ var y={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}},be=new Map(Object.values(y).map(e=>[e.chainId,e]));import T from"node:fs";import C from"node:path";import{homedir as ne}from"node:os";function x(e){let t=e?.transactionHash||e?.hash||e?.txid||null;return t?{happened:!0,hash:String(t),note:null}:{happened:!1,hash:null,note:"no transaction hash \u2014 the action did not succeed"}}import c from"node:path";import re from"node:os";import{createHash as te,randomBytes as kn}from"node:crypto";import{Transaction as Nn}from"@scure/btc-signer";import{ed25519 as Cn}from"@noble/curves/ed25519.js";import{base58 as dt}from"@scure/base";import{Interface as J,MaxUint256 as ir,isAddress as ar,keccak256 as sr,toUtf8Bytes as cr}from"ethers";import{Interface as D,isAddress as qe}from"ethers";import{isAddress as Ce}from"ethers";var We=new D(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as W,isAddress as He}from"ethers";var Ze=new W(["function approve(address spender,uint256 amount) returns (bool)"]),Xe=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});var mr=new J(["function approve(address spender,uint256 amount) returns (bool)"]);var wr=300*1e3,gr=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();import{Address as br,NETWORK as vr,OutScript as Ar,RawTx as Or,SigHash as Tr,TEST_NETWORK as Ir,Transaction as _r}from"@scure/btc-signer";import{createHash as H}from"node:crypto";import{base58 as Rr}from"@scure/base";import{getCompiledTransactionMessageDecoder as Br}from"@solana/transaction-messages";var _=e=>H("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),Pr=new Map([[_("route"),{name:"route",prefixBytes:0}],[_("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]);var z=new Set(["evm","evm-swap","evm-bridge","evm-nft","btc","sol"]);var Gr=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0});var K=Object.freeze({"0x04e45aaf":{provider:"uniswap-v3",action:"swap",layout:"router02-exact-input-single"},"0x414bf389":{provider:"uniswap-v3",action:"swap",layout:"swap-router-exact-input-single"},"0x7b939232":{provider:"across-v3",action:"bridge",layout:"across-deposit-v3"}}),zr=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"}}),Kr=Object.freeze({"0xa0712d68":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0x1249c58b":{provider:"nft-mint",action:"mint",layout:"mint-no-args"},"0x2db11544":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xefef39a1":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xa6f2ae3a":{provider:"nft-mint",action:"mint",layout:"mint-no-args"}});var Z=Object.freeze([...z]),Zr=Object.freeze({...K});import{ed25519 as Qr}from"@noble/curves/ed25519.js";import{base58 as rt}from"@scure/base";import{RawTx as nt,SigHash as ot,Transaction as it}from"@scure/btc-signer";import{Transaction as st}from"ethers";var At=Object.freeze({N:1<<17,r:8,p:1}),Ot=256*1024*1024,Tt=16*1024;import{homedir as A}from"node:os";import{join as O}from"node:path";var L=process.env.ORACLE_PUBLIC_DESKTOP==="1",Q=L?process.env.ORACLE_CONFIG_DIR||O(A(),".config","oracle"):O(A(),".config","oracle"),Lt=L?Q:O(A(),".config","mad-desk");var Pt="0".repeat(64),Mt=Object.freeze({PREPARE:"exec.prepare",SIGN:"exec.sign",BROADCAST:"exec.broadcast",POLICY_REJECT:"policy.reject",AUTH_GRANT:"auth.grant",AUTH_OK:"auth.verify.ok",AUTH_FAIL:"auth.verify.fail"});var $t=Promise.resolve();import{Wallet as Ht}from"ethers";import{base58 as zt}from"@scure/base";import{ed25519 as Zt}from"@noble/curves/ed25519.js";import{NETWORK as Yt,TEST_NETWORK as Qt,WIF as en,p2wpkh as rn}from"@scure/btc-signer";import{pubECDSA as nn}from"@scure/btc-signer/utils.js";function R(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||c.join(process.env.XDG_STATE_HOME||c.join(re.homedir(),".local","state"),"oracle"),r=te("sha256").update(c.resolve(e)).digest("hex").slice(0,16);return{vault:c.join(e,"vault.json"),policy:c.join(e,"signer-policy.json"),policyKey:c.join(e,"policy-integrity-key"),policyAnchor:c.join(t,`signer-policy-${r}.high-water`),ledger:c.join(e,"signer-ledger.json"),ledgerAnchor:c.join(t,`signer-ledger-${r}.high-water`),token:c.join(e,"signer-token"),lock:c.join(t,`signer-${r}.lock`)}}function oe(){return process.env.ORACLE_CONFIG_DIR||C.join(ne(),".config","oracle")}function h(){let e=R(C.join(oe(),"signer")),t=T.existsSync(e.vault),r=T.existsSync(e.lock),o=t?r?"disarmed":"armed-owner-confirmed":"inert-no-key";return{vaultExists:t,policyConfigured:T.existsSync(e.policy),armed:t&&!r,disarmed:r,capabilities:{swap:o,bridge:o},autonomous:!1,note:"Keys stay on this machine. Exact confirmation is required before any broadcast."}}var to=Object.freeze([{type:"function",function:{name:"vault_status",description:"Read local Oracle vault/signer readiness. Never returns key material.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_status",description:"Ping the loopback signer. Fails closed if it is not running.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_execute",description:"Broadcast one already-confirmed local artifact. Requires a one-use confirmationNonce from the local signer TTY confirm. Cannot mint confirmation itself.",parameters:{type:"object",properties:{artifact:{type:"object"},confirmationNonce:{type:"string",minLength:32,maxLength:128}},required:["artifact","confirmationNonce"],additionalProperties:!1}}},{type:"function",function:{name:"signer_disarm",description:"Global kill switch. Stops the local signer from broadcasting.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"receipt_report",description:"Receipt or it did not happen. Requires transactionHash/hash/txid.",parameters:{type:"object",properties:{receipt:{type:"object"},transactionHash:{type:"string"},hash:{type:"string"},txid:{type:"string"}},additionalProperties:!1}}},{type:"function",function:{name:"watch_create",description:"Create an alert-only watch. Never execute.",parameters:{type:"object",properties:{chain:{type:"string"},token:{type:"string"},condition:{type:"string"},note:{type:"string"}},required:["chain","token","condition"],additionalProperties:!1}}},{type:"function",function:{name:"watch_list",description:"List local alert-only watches.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"portfolio_snapshot",description:"How to read the one portfolio snapshot. knownUsd is incomplete if a provider is missing.",parameters:{type:"object",properties:{},additionalProperties:!1}}}]);import M from"node:fs";import he from"node:path";import w from"node:fs";import ie from"node:os";import d from"node:path";import{fileURLToPath as ae}from"node:url";var se=d.dirname(ae(import.meta.url)),co=d.resolve(se,"../..");function B(){return process.env.ORACLE_FAKE_HOME||ie.homedir()}function ce(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function g(){return ce()?process.env.ORACLE_CONFIG_DIR||d.join(B(),".config","oracle"):d.join(B(),".config","oracle")}function ue(){return d.join(g(),"desk.json")}function le(){return d.join(g(),"env")}function f({force:e=!1}={}){if(f._done&&!e)return f._result||null;f._done=!0;let t={},r=(i,n)=>{if(n==null)return;let a=String(n).trim();a&&(process.env[i]!=null&&String(process.env[i]).trim()!==""||(process.env[i]=a,t[i]=a))};try{let i=le();if(w.existsSync(i))for(let n of w.readFileSync(i,"utf8").split(/\r?\n/)){let a=n.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!a||a[2].startsWith("#"))continue;let s=a[2];(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),r(a[1],s)}}catch{}try{let i=ue();if(w.existsSync(i)){let n=JSON.parse(w.readFileSync(i,"utf8"));n&&typeof n=="object"&&(r("ORACLE_DESK_URL",n.deskUrl||n.dataUrl||n.url),r("ORACLE_DATA_URL",n.dataUrl||n.deskUrl||n.url),r("ORACLE_API_URL",n.apiUrl||n.dataUrl||n.deskUrl),r("ORACLE_PUBLIC_URL",n.publicUrl||n.deskUrl||n.dataUrl),r("ORACLE_EXEC_URL",n.execUrl),r("MAD_DESK_URL",n.deskUrl||n.dataUrl))}}catch{}let o=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return o&&(r("ORACLE_DESK_URL",o),r("ORACLE_DATA_URL",o),r("ORACLE_API_URL",o),r("ORACLE_PUBLIC_URL",o),r("MAD_DESK_URL",o)),f._result=Object.keys(t).length?t:null,f._result}try{f()}catch{}var fe=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","custom","anthropic-oauth","openai-codex","xai-oauth"]);function E(e){return String(e||"").trim()||void 0}function de(e,{required:t=!1}={}){let r=E(e)?.toLowerCase();if(!r){if(t)throw new Error("model provider is required");return}if(!fe.has(r))throw new Error(`unsupported provider: ${r}`);return r}function pe(e,{required:t=!1}={}){let r=E(e);if(!r){if(t)throw new Error("model is required");return}if(r.includes("..")||r.startsWith("/")||!/^[a-zA-Z0-9._:/-]{1,200}$/.test(r))throw new Error("invalid model id");return r}function me(e){let t=E(e);if(!t||t.length>2048)throw new Error("invalid custom base URL");let r;try{r=new URL(t)}catch{throw new Error("invalid custom base URL")}let o=r.hostname.toLowerCase().replace(/^\[|\]$/g,""),i=o==="localhost"||o==="127.0.0.1"||o==="::1";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&i)||r.username||r.password||r.search||r.hash)throw new Error("custom base URL must use HTTPS or loopback HTTP without credentials, query, or fragment");return r.toString().replace(/\/+$/,"")}function P({provider:e,model:t,baseUrl:r}={},{requireModel:o=!1}={}){let i=de(e),n=pe(t,{required:o});if(i==="custom")return{provider:i,...n?{model:n}:{},baseUrl:me(r)};if(E(r))throw new Error("baseUrl is only supported for the custom provider");return{...i?{provider:i}:{},...n?{model:n}:{}}}var we=new Set(["auto","standalone","hermes","remote","arch"]);function ge(){return he.join(g(),"model.json")}function p(e){return String(e||"").trim()||void 0}function Ee(e={}){let t=p(e.backend)?.toLowerCase()||"auto",r=P({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:t==="standalone"}),o=p(e.apiKeyEnv),i=Number.parseInt(String(e.contextLength||""),10),n=p(e.reasoningEffort),a=p(e.computeHost||e.remoteHost),s=p(e.computeUser||e.remoteUser),u=p(e.computePath||e.remotePath);if(!we.has(t))throw new Error(`unsupported backend: ${t}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(t))throw new Error("remote compute backends are disabled in the public desktop");if(o&&!/^[A-Z][A-Z0-9_]*$/.test(o))throw new Error("api key env must be an uppercase environment variable name");if(t==="remote"&&!a)throw new Error("remote backend requires computeHost");return{backend:t,...r,...o?{apiKeyEnv:o}:{},...Number.isFinite(i)&&i>0?{contextLength:i}:{},...n?{reasoningEffort:n}:{},...a?{computeHost:a}:{},...s?{computeUser:s}:{},...u?{computePath:u}:{}}}function $(){let e=ge();if(!M.existsSync(e))return null;try{return Ee(JSON.parse(M.readFileSync(e,"utf8")))}catch{return null}}var Se=new Set(["127.0.0.1","::1","localhost"]);function I({env:e=process.env,vault:t=null}={}){let r=t||h(),o=[];for(let[i,n]of Object.entries(y)){let a=(n.rpcEnv||[]).some(u=>String(e[u]||"").trim()),s="prepare";n.evm?a&&(s="live"):s="unavailable",o.push({key:i,chainId:n.chainId,name:n.name,family:"evm",status:s,execute:!!(r.vaultExists&&r.armed&&!r.disarmed),note:a?"rpc configured":"public read/prepare; set RPC for live reads"})}return o.push({key:"solana",chainId:null,name:"Solana",family:"sol",status:"prepare",execute:!1,note:"Jupiter quote/prepare; local sol signer"},{key:"bitcoin",chainId:null,name:"Bitcoin",family:"btc",status:"prepare",execute:!1,note:"Esplora read; local btc signer"},{key:"hyperliquid-l1",chainId:null,name:"Hyperliquid L1",family:"data",status:"live",execute:!1,note:"data/prepare only \u2014 not an EVM signer family"},{key:"polymarket",chainId:null,name:"Polymarket",family:"data",status:"live",execute:!1,note:"data/prepare only \u2014 not a signer family"}),o}function ye({env:e=process.env,model:t=$(),vault:r=h(),signerReachable:o=!1,quote:i=null}={}){let n=[],a=(l,S,F,q=null)=>n.push({id:l,status:S,detail:F,fix:q}),s=(()=>{let[l,S]=process.versions.node.split(".").map(Number);return l>20||l===20&&S>=19})();a("node",s?"ok":"fail",`node ${process.versions.node}`,s?null:"install node >= 20.19"),t?t.backend==="hermes"?a("model","warn","backend=hermes (opt-in attach)","oracle model --backend standalone"):a("model","ok",`${t.backend||"auto"} ${t.provider||""} ${t.model||""}`.trim()):a("model","fail","no model.json","oracle setup model"),r.vaultExists?r.disarmed?a("vault","warn","vault present, DISARMED","oracle signer (re-arm after confirm)"):a("vault",r.armed?"ok":"warn",r.armed?"present, armed":"present, not armed"):a("vault","fail","no local vault","oracle sign init");let u=e.ORACLE_SIGNER_HOST||"127.0.0.1";return Se.has(u)?a("signer",o?"ok":"warn",o?`loopback ${u}:${e.ORACLE_SIGNER_PORT||9462}`:"loopback signer not reachable",o?null:"oracle signer"):a("signer","fail",`signer host ${u} is not loopback`,"unset ORACLE_SIGNER_HOST"),i?i.ok?a("quote","ok",i.detail||"net quote returned"):a("quote","warn",i.detail||"quote unavailable","check network / oracle data serve"):a("quote","warn","quote not probed",null),{ok:!n.some(l=>l.status==="fail"),checks:n,venues:I({env:e,vault:r})}}async function Oo(e=process.env){let t=e.ORACLE_SIGNER_HOST||"127.0.0.1",r=e.ORACLE_SIGNER_PORT||9462;try{return(await fetch(`http://${t}:${r}/status`,{signal:AbortSignal.timeout(1500)})).ok}catch{return!1}}async function To(){try{let e=await fetch("https://api.dexscreener.com/latest/dex/search?q=WETH%20USDC",{signal:AbortSignal.timeout(4e3)});if(!e.ok)return{ok:!1,detail:`dexscreener ${e.status}`};let r=(await e.json())?.pairs?.[0];return!r?.chainId||!r?.priceUsd?{ok:!1,detail:"no pair"}:{ok:!0,detail:`${r.chainId} ${r.baseToken?.symbol}/${r.quoteToken?.symbol} $${r.priceUsd}`}}catch(e){return{ok:!1,detail:e instanceof Error?e.message:"quote failed"}}}var Io={name:"venues",summary:"label every shipped venue live / prepare / unavailable",group:"read",usage:"oracle venues [--json]",async run(e){let t=e.argv.includes("--json"),r=I();if(t)return process.stdout.write(`${JSON.stringify({venues:r},null,2)}
2
2
  `),0;for(let o of r)process.stdout.write(`${o.status.padEnd(12)} ${o.key.padEnd(16)} ${o.name} exec=${o.execute?"local":"no"}
3
- `);return 0}};export{y as classifyReceipt,xo as default,Ee as firstHourReport,So as probeQuote,Eo as probeSigner,h as vaultStatus};
3
+ `);return 0}};export{x as classifyReceipt,Io as default,ye as firstHourReport,To as probeQuote,Oo as probeSigner,h as vaultStatus};