@oracle-agent/oracle 0.24.9 → 0.25.0

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.
@@ -46,7 +46,7 @@ ${A.format(t)}
46
46
  ${s}`;break;case"retry":ef(s)&&(t[n]=s);break;case"id":Af(s)&&(t[n]=s);break;case"event":s.length>0&&(t[n]=s);break}}processEvent(A){A.retry&&ef(A.retry)&&(this.state.reconnectionTime=parseInt(A.retry,10)),A.id&&Af(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}}};tf.exports={EventSourceStream:tl}});var gf=f((l1,lf)=>{"use strict";var{pipeline:VM}=d("node:stream"),{fetching:qM}=kn(),{makeRequest:OM}=br(),{webidl:YA}=he(),{EventSourceStream:WM}=rf(),{parseMIMEType:PM}=be(),{createFastMessageEvent:_M}=Nr(),{isNetworkError:nf}=bn(),{delay:KM}=el(),{kEnumerableProperty:xt}=Y(),{environmentSettingsObject:sf}=Me(),of=!1,af=3e3,Hn=0,cf=1,Vn=2,ZM="anonymous",zM="use-credentials",xr=class e extends EventTarget{#e={open:null,error:null,message:null};#A=null;#t=!1;#s=Hn;#n=null;#r=null;#o;#i;constructor(A,t={}){super(),YA.util.markAsUncloneable(this);let r="EventSource constructor";YA.argumentLengthCheck(arguments,1,r),of||(of=!0,process.emitWarning("EventSource is experimental, expect them to change at any time.",{code:"UNDICI-ES"})),A=YA.converters.USVString(A,r,"url"),t=YA.converters.EventSourceInitDict(t,r,"eventSourceInitDict"),this.#o=t.dispatcher,this.#i={lastEventId:"",reconnectionTime:af};let n=sf,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=ZM;t.withCredentials&&(o=zM,this.#t=!0);let i={redirect:"follow",keepalive:!0,mode:"cors",credentials:o==="anonymous"?"same-origin":"omit",referrer:"no-referrer"};i.client=sf.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=OM(i),this.#c()}get readyState(){return this.#s}get url(){return this.#A}get withCredentials(){return this.#t}#c(){if(this.#s===Vn)return;this.#s=Hn;let A={request:this.#n,dispatcher:this.#o},t=r=>{nf(r)&&(this.dispatchEvent(new Event("error")),this.close()),this.#a()};A.processResponseEndOfBody=t,A.processResponse=r=>{if(nf(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?PM(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=cf,this.dispatchEvent(new Event("open")),this.#i.origin=r.urlList[r.urlList.length-1].origin;let i=new WM({eventSourceSettings:this.#i,push:a=>{this.dispatchEvent(_M(a.type,a.options))}});VM(r.body.stream,i,a=>{a?.aborted===!1&&(this.close(),this.dispatchEvent(new Event("error")))})},this.#r=qM(A)}async#a(){this.#s!==Vn&&(this.#s=Hn,this.dispatchEvent(new Event("error")),await KM(this.#i.reconnectionTime),this.#s===Hn&&(this.#i.lastEventId.length&&this.#n.headersList.set("last-event-id",this.#i.lastEventId,!0),this.#c()))}close(){YA.brandCheck(this,e),this.#s!==Vn&&(this.#s=Vn,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}},uf={CONNECTING:{__proto__:null,configurable:!1,enumerable:!0,value:Hn,writable:!1},OPEN:{__proto__:null,configurable:!1,enumerable:!0,value:cf,writable:!1},CLOSED:{__proto__:null,configurable:!1,enumerable:!0,value:Vn,writable:!1}};Object.defineProperties(xr,uf);Object.defineProperties(xr.prototype,uf);Object.defineProperties(xr.prototype,{close:xt,onerror:xt,onmessage:xt,onopen:xt,readyState:xt,url:xt,withCredentials:xt});YA.converters.EventSourceInitDict=YA.dictionaryConverter([{key:"withCredentials",converter:YA.converters.boolean,defaultValue:()=>!1},{key:"dispatcher",converter:YA.converters.any}]);lf.exports={EventSource:xr,defaultReconnectionTime:af}});var If=f((g1,M)=>{"use strict";var XM=cr(),Ef=Wr(),$M=ur(),jM=cB(),eL=lr(),AL=mc(),tL=MB(),rL=JB(),Qf=q(),$o=Y(),{InvalidArgumentError:Xo}=Qf,vr=DI(),nL=_r(),sL=nu(),oL=ah(),iL=iu(),aL=Wc(),cL=js(),{getGlobalDispatcher:Bf,setGlobalDispatcher:uL}=co(),lL=uo(),gL=Vs(),EL=qs();Object.assign(Ef.prototype,vr);M.exports.Dispatcher=Ef;M.exports.Client=XM;M.exports.Pool=$M;M.exports.BalancedPool=jM;M.exports.Agent=eL;M.exports.ProxyAgent=AL;M.exports.EnvHttpProxyAgent=tL;M.exports.RetryAgent=rL;M.exports.RetryHandler=cL;M.exports.DecoratorHandler=lL;M.exports.RedirectHandler=gL;M.exports.createRedirectInterceptor=EL;M.exports.interceptors={redirect:Bh(),retry:hh(),dump:dh(),dns:wh()};M.exports.buildConnector=nL;M.exports.errors=Qf;M.exports.util={parseHeaders:$o.parseHeaders,headerNameToString:$o.headerNameToString};function qn(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 Xo("invalid url");if(t!=null&&typeof t!="object")throw new Xo("invalid opts");if(t&&t.path!=null){if(typeof t.path!="string")throw new Xo("invalid opts.path");let o=t.path;t.path.startsWith("/")||(o=`/${o}`),A=new URL($o.parseOrigin(A).origin+o)}else t||(t=typeof A=="object"?A:{}),A=$o.parseURL(A);let{agent:n,dispatcher:s=Bf()}=t;if(n)throw new Xo("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)}}M.exports.setGlobalDispatcher=uL;M.exports.getGlobalDispatcher=Bf;var QL=kn().fetch;M.exports.fetch=async function(A,t=void 0){try{return await QL(A,t)}catch(r){throw r&&typeof r=="object"&&Error.captureStackTrace(r),r}};M.exports.Headers=St().Headers;M.exports.Response=bn().Response;M.exports.Request=br().Request;M.exports.FormData=en().FormData;M.exports.File=globalThis.File??d("node:buffer").File;M.exports.FileReader=YC().FileReader;var{setGlobalOrigin:BL,getGlobalOrigin:IL}=ya();M.exports.setGlobalOrigin=BL;M.exports.getGlobalOrigin=IL;var{CacheStorage:hL}=_C(),{kConstruct:CL}=Uo();M.exports.caches=new hL(CL);var{deleteCookie:dL,getCookies:fL,getSetCookies:pL,setCookie:wL}=nd();M.exports.deleteCookie=dL;M.exports.getCookies=fL;M.exports.getSetCookies=pL;M.exports.setCookie=wL;var{parseMIMEType:mL,serializeAMimeType:yL}=be();M.exports.parseMIMEType=mL;M.exports.serializeAMimeType=yL;var{CloseEvent:bL,ErrorEvent:DL,MessageEvent:kL}=Nr();M.exports.WebSocket=$d().WebSocket;M.exports.CloseEvent=bL;M.exports.ErrorEvent=DL;M.exports.MessageEvent=kL;M.exports.request=qn(vr.request);M.exports.stream=qn(vr.stream);M.exports.pipeline=qn(vr.pipeline);M.exports.connect=qn(vr.connect);M.exports.upgrade=qn(vr.upgrade);M.exports.MockClient=sL;M.exports.MockPool=iL;M.exports.MockAgent=oL;M.exports.mockErrors=aL;var{EventSource:RL}=gf();M.exports.EventSource=RL});import Yr from"node:net";import SL from"node:dns";function jo(e){let A=String(e).toLowerCase().split("%")[0];if((A.match(/::/g)||[]).length>1)return null;let t=g=>{if(!g)return[];let u=g.split(":"),l=u.at(-1);if(l?.includes(".")){let E=l.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(g=>[g>>8,g&255]))}function rl(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 nl(e){if(Yr.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(Yr.isIPv6(e)){let A=jo(e);if(!A)return!1;let t=jo("::ffff:0:0");return rl(A,t,96)?nl([...A.slice(12)].join(".")):rl(A,jo("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([n,s])=>rl(A,jo(n),s)):!1}return!1}function NL(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(FL.has(t)||t.endsWith(".localhost")||t.endsWith(".internal"))return{ok:!1,error:`refused internal host ${t}`};let r=Yr.isIP(t);return r!==0&&!nl(t)?{ok:!1,error:`refused private address ${t}`}:{ok:!0,url:A,host:t,isLiteralIp:r!==0}}async function hf(e,{lookupFn:A=SL.promises.lookup}={}){let t=NL(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=>!nl(n.address))?{ok:!1,error:`refused: ${t.host} resolves to a non-public address`}:{ok:!0,url:t.url,addresses:r}}async function Cf(){let e,A;try{let i=await Promise.resolve().then(()=>dp(If(),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||(Yr.isIPv6(a.address)?6:4)})),s=i=>{let a=t(i);if(Yr.isIP(a))return[{address:a,family:Yr.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 g;try{g=s(i)}catch(u){return c(u)}return a?.all?c(null,g):c(null,g[0].address,g[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 FL,df=se(()=>{FL=new Set(["localhost","metadata.google.internal","metadata.goog"])});import{createHash as UL}from"node:crypto";function xL(e){let A=String(e||"").toLowerCase();return mf.includes(A)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(A)}function vL(e){let A={};for(let[t,r]of Object.entries(e||{}))xL(t)||(A[t]=r);return A}function YL(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 GL(e,A){return new URL(String(e)).origin===new URL(String(A)).origin}function JL(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([...mf,...n])].sort().map(a=>`${a}=${r[a]??""}`).join(`
47
47
  `),i=UL("sha256").update(o).digest("hex").slice(0,32);return`${e} ${A} ${i}`}function HL(e,A){let t=Number(A);return Number.isFinite(t)&&t>0?Math.min(t*1e3,pf):Math.min(250*2**e,pf)+Math.floor(Math.random()*100)}async function qL(e,{fetchImpl:A,method:t,headers:r,body:n,timeoutMs:s,lookupFn:o,realFetch:i}){let a=new AbortController,c=setTimeout(()=>a.abort(),s),g=null,u=A;try{let l=String(e),E={...r||{}};for(let Q=0;Q<=wf;Q+=1){let h=await u(l,{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(TL.has(h.status)){if(t!=="GET"&&t!=="HEAD"){let w=new Error(`HTTP ${h.status} ${t} ${l} redirected non-idempotent request`);throw w.status=h.status,w.body=I??B.slice(0,300),w}if(Q===wf)throw new Error(`HTTP redirect loop for ${e}`);let C=YL(h.headers?.get?.("location"),l);if(!GL(C,l)){let w=await hf(C,o?{lookupFn:o}:{});if(!w.ok){let R=new Error(`HTTP redirect from ${l} ${w.error}`);throw R.status=h.status,R}E=vL(E),i&&w.addresses?.length&&(g||(g=await Cf()),g&&(g.pin(new URL(C).hostname,w.addresses[0].address,w.addresses[0].family),u=g.fetch))}l=C;continue}if(!h.ok){let C=new Error(`HTTP ${h.status} ${t} ${l}`);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),g&&await g.close()}}async function Z(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):LL,a=A.lookupFn,c=!A.fetchImpl,g=async()=>{let h;for(let B=0;B<=i;B++)try{return await qL(e,{fetchImpl:t,method:n,headers:s,body:o,timeoutMs:r,lookupFn:a,realFetch:c})}catch(I){h=I;let C=I?.status,p=I?.name==="AbortError",w=new Set([408,425,429]),R=C!=null?w.has(C)||ML.has(C)&&ff.has(n):!p&&ff.has(n);if(B===i||!R)throw I;await VL(HL(B,I?.retryAfter))}throw h};if(!(A.dedupe!==!1&&n==="GET"&&o==null))return g();let l=JL(n,e,s),E=sl.get(l);if(E)return E;let Q=g().finally(()=>sl.delete(l));return sl.set(l,Q),Q}var ML,ff,LL,pf,mf,TL,wf,sl,VL,wA=se(()=>{df();ML=new Set([408,425,429,500,502,503,504]),ff=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),LL=2,pf=4e3,mf=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],TL=new Set([301,302,303,307,308]),wf=3;sl=new Map;VL=e=>new Promise(A=>setTimeout(A,e))});import{readFileSync as OL}from"node:fs";import{homedir as WL}from"node:os";import{join as ei}from"node:path";function PL(){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=WL();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let t=(process.env.ORACLE_CONFIG_DIR||ei(A,".config","oracle")).trim();return[e,ei(t,"exec.env")].filter(Boolean)}return[e,ei(A,".config","oracle","exec.env"),ei(A,".config","mad-desk","exec.env")].filter(Boolean)}function yf(e,A,t){let r=e??process.env[A]??process.env[t];if(!String(r||"").trim())for(let n of PL())try{let s=OL(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 bf=se(()=>{});var Df=se(()=>{});import{createHash as _L,createHmac as Rf,timingSafeEqual as KL}from"node:crypto";function ti(e){return Array.isArray(e)?`[${e.map(ti).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(A=>`${JSON.stringify(A)}:${ti(e[A])}`).join(",")}}`:JSON.stringify(e??null)}function Sf(e,{required:A=!1}={}){try{return yf(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(t){if(A)throw t;return null}}function il(e){let{signature:A,...t}=e;return t}function Ff(e,{secret:A}={}){let t=Sf(A);return t?{...e,signature:Rf("sha256",t).update(ti(il(e))).digest("hex")}:e}function ZL(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 _L("sha256").update(Buffer.from(A.slice(2),"hex")).digest("hex")}function iA(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=Sf(n);if(s){let E=Rf("sha256",s).update(ti(il(e))).digest("hex");if(!zL(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>Ai||!Number.isInteger(i)||i<0||i>Ai||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 g=a*BigInt(1e4-o),u=g/10000n;if(g%10000n!==0n&&(u+=1n),c<u)throw new Error("auto-slippage guard is under-protected relative to its quote");let l=jL(r);if(l!=null&&l!==c)throw new Error(`auto-slippage: calldata encodes floor ${l}, not the guard floor ${c} \u2014 refusing to bind`);return Ff({...il(e),calldataHash:ZL(r)},{secret:n})}function zL(e,A){let t=Buffer.from(String(e??""),"utf8"),r=Buffer.from(String(A??""),"utf8");return t.length!==r.length||t.length===0?!1:KL(t,r)}function ol(e,A=0){let t=Number(e);return Number.isFinite(t)?t:A}function XL(e){let A=e==null?Ai: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,Ai)}function GA({liquidityUsd:e,priceChange5m:A=0,quoteAgeMs:t=0,crossChain:r=!1,requestedCapBps:n}={}){let s=ol(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(ol(A,0))*2),a=Math.min(40,Math.floor(Math.max(0,ol(t,0))/5e3)*5),c=Math.max(25,Math.ceil(20+o+i+a)),g=XL(n);return{mode:"auto",requiredBps:c,selectedBps:Math.min(c,g),capBps:g,executable:c<=g}}function $L({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=kf,secret:g}={}){let u=BigInt(t??0);if(u<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let l=GA({liquidityUsd:r,priceChange5m:n,quoteAgeMs:s,crossChain:o,requestedCapBps:i});if(!l.executable)throw new Error(`auto-slippage requires ${l.requiredBps} bps above hard/requested cap ${l.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)||kf)),h=u*BigInt(1e4-l.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 ${l.selectedBps} bps floor without rounding to zero`);let I=Number((u-B)*10000n/(u===0n?1n:u));if(I>l.capBps)throw new Error(`auto-slippage: realised floor implies ${I} bps, above cap ${l.capBps} \u2014 refusing to issue a guard weaker than advertised`);return Ff({mode:"auto",chainId:Number(e),venue:String(A||"unknown"),quoteAmountOut:u.toString(),minAmountOut:B.toString(),requiredBps:l.requiredBps,selectedBps:l.selectedBps,capBps:l.capBps,quotedAtMs:E,expiresAtMs:E+Q},{secret:g})}function jL(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 Ie(e,{chainId:A,venue:t,amountOut:r,liquidityUsd:n,priceChange5m:s,crossChain:o,requestedCapBps:i,quotedAtMs:a=Date.now(),ttlMs:c}={}){let g=$L({chainId:A,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:s,crossChain:o,requestedCapBps:i,quotedAtMs:a,ttlMs:c});return{...e,autoSlippage:g,amountOutMinimum:g.minAmountOut}}var Ai,kf,JA=se(()=>{bf();Df();Ai=100,kf=2e4});function al(e){let A=String(e||"").trim();return/^0x[0-9a-fA-F]{40}$/.test(A)?A:st}var st,ri=se(()=>{st="0x000000000000000000000000000000000000dEaD"});import{createHash as eT,createHmac as AT,timingSafeEqual as N1}from"node:crypto";function cl(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(cl).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${cl(e[t])}`).join(",")}}`}function Nf(e){let A=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return A.length>=16?A:""}function Uf(e=process.env){return Nf(process.env)||Nf(e)}function nT(e){let{oraclePrepared:A,prepareHash:t,prepareMac:r,note:n,...s}=e||{};return s}function sT(e){let A=nT(e);return eT("sha256").update(cl(A)).digest("hex")}function oT(e,A=Uf()){return A?AT("sha256",A).update(String(e)).digest("hex"):""}function ge(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+rT,a={...n,preparedAt:s,expiresAt:o,prepareVersion:tT},c=sT(a),g=Uf(r),u=g?oT(c,g):void 0,l={...a,oraclePrepared:!0,prepareHash:c};return u&&(l.prepareMac=u),l}var tT,rT,U1,aA=se(()=>{tT=2,rT=300*1e3,U1=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Contract as iT,JsonRpcProvider as aT}from"ethers";function QT(e){return ET.test(String(e||""))}async function Mf(e,{contract:A=cT,rpc:t=lT,chainId:r=uT,balanceOf:n}={}){if(!QT(e))throw new Error("invalid-address");if(n)return BigInt(await n(e));let s=new aT(t,r,{staticNetwork:!0}),o=new iT(A,gT,s);return BigInt(await o.balanceOf(e))}var cT,uT,lT,gT,ET,Lf=se(()=>{cT="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",uT=999,lT="https://rpc.hyperliquid.xyz/evm",gT=["function balanceOf(address owner) view returns (uint256)"],ET=/^0x[a-fA-F0-9]{40}$/});import{existsSync as BT,readFileSync as IT,lstatSync as hT}from"node:fs";import{homedir as Tf}from"node:os";import{join as ul}from"node:path";function fT(e){let A=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(xf,A)?xf[A]:dT}function bT(e=process.env){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){if(e[vf])return String(e[vf]);let A=e.ORACLE_CONFIG_DIR||ul(Tf(),".config","oracle");return ul(A,"fee-recipient")}return ul(Tf(),".config","oracle","fee-recipient")}function DT(e=process.env){try{let A=bT(e);if(!BT(A)||hT(A).isSymbolicLink())return"";let t=IT(A,"utf8").trim().toLowerCase();return/^0x[a-f0-9]{40}$/.test(t)?t:""}catch{return""}}function kT(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),CT)}function RT({env:e=process.env,action:A="swap",admin:t=!1}={}){let r=String(e[wT]||"").trim(),n=String(e[mT]||yT).trim();if(t===!0)return{bps:0,recipient:"",integrator:n,action:A,applies:!1,reason:"admin-oracle"};let s=fT(A),o=kT(e[pT],{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=DT(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 ni({wallet:e,env:A=process.env,action:t="swap",holderCheck:r={},admin:n=!1}={}){let s=RT({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 Mf(o,r))>0n?{...s,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...s,holderVerificationStatus:"non-holder"}}catch{return{...s,holderVerificationStatus:"unavailable"}}}function Yf(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 Gf(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}function Jf(e){return e?.applies?{partner:e.integrator,partnerFeeBps:String(e.bps),partnerAddress:e.recipient}:{}}var CT,dT,xf,pT,wT,mT,vf,yT,si=se(()=>{Lf();CT=100,dT=5,xf=Object.freeze({swap:5,bridge:5,perps:0,nft:0});pT="ORACLE_INTEGRATOR_FEE_BPS",wT="ORACLE_INTEGRATOR_FEE_RECIPIENT",mT="ORACLE_INTEGRATOR_ID",vf="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",yT="oracle"});var El={};ut(El,{LIFI_API:()=>Vf,lifiChains:()=>MT,lifiHealth:()=>NT,lifiPrepare:()=>UT,lifiQuote:()=>On});function gl(e={}){return(e.baseUrl||process.env.LIFI_API_URL||Vf).replace(/\/$/,"")}function FT(e){let A=String(e||ll).toLowerCase();return A===ll.toLowerCase()||A===ST}function Hf(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 NT(e={}){let A=await Z(`${gl(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 On(e={},A={}){let{fromChain:t,toChain:r=t,fromToken:n=ll,toToken:s,fromAmount:o,fromAddress:i=st}=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=GA({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 g=await ni({wallet:e.fromAddress,env:A.env,action:e.feeAction||"swap",holderCheck:A.holderCheck});for(let[B,I]of Object.entries(Gf(g)))a.set(B,I);let u=await Z(`${gl(A)}/quote?${a}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??2e4}),l=u?.estimate?.toAmount||u?.toAmount;if(!l)return{...u,autoSlippagePolicy:c,oracleFee:g};let E=u?.transactionRequest?.to||u?.estimate?.approvalAddress||"lifi",Q=Ie(u,{chainId:Number(t),venue:E,amountOut:l,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:g}}async function UT(e={},A={}){let t=await On(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(!FT(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:Hf(i,"approval token"),spender:Hf(o,"approval spender"),amount:String(e.fromAmount)}}return ge({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:iA(t.autoSlippage,{chainId:n,venue:r.to,data:r.data})}},{provider:"lifi",kind:"lifi-tx"})}async function MT(e={}){return Z(`${gl(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var Vf,ll,ST,oi=se(()=>{wA();JA();ri();aA();si();Vf="https://li.quest/v1";ll="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",ST="0x0000000000000000000000000000000000000000"});var Wf={};ut(Wf,{PARASWAP_API:()=>qf,paraswapHealth:()=>TT,paraswapPrepare:()=>LT,paraswapPrice:()=>ii,paraswapTokens:()=>Of});function Gr(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 Of(e={},A={}){let t=Number(e.chainId||1);return Z(`${Ql(A)}/tokens/${t}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs})}async function ii(e={},A={}){let t=Number(e.chainId||e.network||1);if(e.amount==null)throw new Error("amount required");let r=new URLSearchParams({srcToken:Gr(e.srcToken,"srcToken"),destToken:Gr(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 ni({wallet:e.userAddress||e.fromAddress,env:A.env,action:e.feeAction||"swap",holderCheck:A.holderCheck});for(let[i,a]of Object.entries(Jf(n)))r.set(i,a);let s=await Z(`${Ql(A)}/prices?${r}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??2e4}),o=s?.priceRoute?.destAmount;return o?{...Ie(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 LT(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=Gr(e.userAddress,"userAddress"),n=await ii(e,A),s=n?.priceRoute,o=String(s?.contractAddress||"").toLowerCase();if(!o)throw new Error("paraswap: price route missing contractAddress");let i={srcToken:Gr(e.srcToken,"srcToken"),destToken:Gr(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=Gr(e.receiver,"receiver"));let a=await Z(`${Ql(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 ge({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:iA(n.autoSlippage,{chainId:t,venue:a.to,data:a.data})}},{provider:"paraswap",kind:"paraswap-tx"})}async function TT(e={}){let A=await Of({chainId:1},e),t=Array.isArray(A?.tokens)?A.tokens.length:Object.keys(A?.tokens||{}).length;return{ok:t>0,tokenSample:t}}var qf,Ql,Bl=se(()=>{wA();JA();aA();si();qf="https://api.paraswap.io",Ql=(e={})=>(e.baseUrl||process.env.PARASWAP_API_URL||qf).replace(/\/$/,"")});function ai({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:_f(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([_f(A),...t]).has(a)){let g=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(a);return i.protocol==="http:"&&!g?{baseUrl:o,trusted:!1,host:a,reason:"plaintext http downgrade"}:{baseUrl:o,trusted:!0,host:a}}if(String(process.env[Pf]||"")==="1")return{baseUrl:o,trusted:!1,host:a};if(n)throw new Error(`${e}: refusing to call non-allowlisted host ${a} (set ${Pf}=1 to permit it)`);return{baseUrl:o,trusted:!1,host:a}}function _f(e){let A=new URL(String(e));if(A.protocol!=="http:"&&A.protocol!=="https:")throw new Error("unsupported protocol");return A.host}function ci(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 Pf,Il=se(()=>{Pf="ORACLE_ALLOW_CUSTOM_PROVIDER_URL"});var jf={};ut(jf,{ZEROX_API:()=>Kf,zeroxHealth:()=>xT,zeroxPrepare:()=>vT,zeroxPrice:()=>$f,zeroxQuote:()=>li});function Zf(e={}){return ai({provider:"zerox",defaultUrl:Kf,hosts:["api.0x.org"],url:e.baseUrl||process.env.ZEROX_API_URL})}function zf(e={}){return Zf(e).baseUrl}function ui(e={}){return e.apiKey||process.env.ZEROX_API_KEY||process.env.OX_API_KEY||process.env["0X_API_KEY"]||""}function Xf(e={}){return ci({"0x-version":"v2",accept:"application/json"},{"0x-api-key":ui(e)},Zf(e).trusted)}async function xT(e={}){if(!ui(e))return{ok:!1,configured:!1,error:"ZEROX_API_KEY not set"};try{let A=await $f({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 $f(e={},A={}){if(!ui(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),Z(`${zf(A)}/swap/allowance-holder/price?${i}`,{headers:Xf(A),fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3})}async function li(e={},A={}){if(!ui(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=GA({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 Z(`${zf(A)}/swap/allowance-holder/quote?${a}`,{headers:Xf(A),fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3}),g=c?.buyAmount||c?.grossBuyAmount;return g?Ie(c,{chainId:t,venue:c?.transaction?.to||c?.to||"0x",amountOut:g,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):{...c,autoSlippagePolicy:i}}async function vT(e={},A={}){if(!e.taker)throw new Error("0x: taker required for executable prepare");let t=await li(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 ge({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:iA(t.autoSlippage,{chainId:n,venue:r.to,data:r.data})}},{provider:"zerox",kind:"zerox-tx"})}var Kf,hl=se(()=>{wA();JA();Il();aA();Kf="https://api.0x.org"});var iY,r0=se(()=>{iY=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"})});var E0={};ut(E0,{COW_CANCEL_TYPES:()=>a0,COW_HOSTS:()=>dl,COW_ORDER_TYPES:()=>gi,COW_SETTLEMENT:()=>s0,COW_VAULT_RELAYER:()=>o0,cowCancelOrders:()=>$T,cowChains:()=>Ax,cowHealth:()=>WT,cowOrder:()=>g0,cowOrderStatus:()=>l0,cowOrderUid:()=>_T,cowPrepareCancel:()=>zT,cowPrepareOrder:()=>PT,cowQuote:()=>Pn,cowSignCancel:()=>XT,cowSignOrder:()=>KT,cowSubmitSignedOrder:()=>ZT,cowVerifyOrderFill:()=>ex});import{TypedDataEncoder as n0,getAddress as Wn,isAddress as HT}from"ethers";function Ei(e,A={}){if(A.baseUrl)return A.baseUrl.replace(/\/$/,"");let t=dl[Number(e)];if(!t)throw new Error(`cowswap: unsupported chainId ${e}`);return t}function VT(e,A="v1",t={}){let r=Ei(e,t);return A==="v1"?r:r.replace(/\/api\/v1$/,`/api/${A}`)}function ot(e,A){let t=String(e||"").trim();if(!HT(t))throw new Error(`cowswap: ${A} must be an address`);return Wn(t).toLowerCase()}function Jr(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 c0(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 u0(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 qT({digest:e,owner:A,validTo:t}={}){let r=c0(e,"order digest").slice(2),n=ot(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 fl(e){let A=s0[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:Wn(A)}}function OT(e={},A,t){let r=ot(e.sellToken,"sellToken"),n=ot(e.buyToken,"buyToken"),s=ot(e.receiver||t,"receiver"),o=Number(e.validTo);if(!Number.isInteger(o)||o<=0)throw new Error("cowswap: quote.validTo required");let i=c0(e.appData||e.appDataHash||`0x${"0".repeat(64)}`,"appData");return{sellToken:r,buyToken:n,receiver:s,sellAmount:Jr(e.sellAmount,"sellAmount"),buyAmount:Jr(e.buyAmount,"buyAmount"),validTo:o,appData:i,feeAmount:Jr(e.feeAmount??"0","feeAmount"),kind:String(e.kind||"sell"),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance||"erc20"),buyTokenBalance:String(e.buyTokenBalance||"erc20")}}async function WT(e={}){try{let A=await Pn({chainId:1,sellToken:Cl[1],buyToken:i0[1],sellAmountBeforeFee:"1000000000000000",from:st},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 Pn(e={},A={}){let t=Number(e.chainId??1),r=al(e.from||e.owner),n=e.sellToken||Cl[t],s=e.buyToken||i0[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=Cl[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 Z(`${Ei(t,A)}/quote`,{method:"POST",body:i,fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3}),c=a?.quote?.buyAmount||a?.buyAmount;return c?Ie(a,{chainId:t,venue:"cowswap-order",amountOut:c,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):a}async function PT(e={},A={}){let t=Number(e.chainId??1),r=ot(al(e.from||e.owner||e.signer),"owner"),n=await Pn({...e,chainId:t,from:r,signingScheme:e.signingScheme||"eip712"},A),s=OT(n?.quote||n,t,r),o=fl(t),i={domain:o,types:gi,primaryType:"Order",message:s},a=n0.hash(o,gi,s),c=o0[t];if(!c)throw new Error(`cowswap: vault relayer not registered for chain ${t}`);return ge({provider:"cowswap",orderReady:!0,executionReady:!1,chainId:t,owner:r,signingScheme:"eip712",settlement:o.verifyingContract.toLowerCase(),vaultRelayer:Wn(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:Wn(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:Wn(c).toLowerCase(),amount:s.sellAmount}},{provider:"cowswap",kind:"cow-order"})}async function l0(e={},A={}){let t=Number(e.chainId??1),r=String(e.uid||e.orderUid||"").trim();if(!r)throw new Error("cowOrderStatus requires uid");return Z(`${Ei(t,A)}/orders/${encodeURIComponent(r)}/status`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3})}async function g0(e={},A={}){let t=Number(e.chainId??1),r=String(e.uid||e.orderUid||"").trim();if(!r)throw new Error("cowOrder requires uid");return Z(`${Ei(t,A)}/orders/${encodeURIComponent(r)}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3})}function _T(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||n0.hash(fl(t),gi,r),s=e.owner||e.from||e.signer||r.receiver;return qT({digest:n,owner:s,validTo:r.validTo})}async function KT(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 ZT(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 zT(e={}){let A=Number(e.chainId??1),t=ot(e.owner||e.from||e.signer,"owner"),r=(e.orderUids||e.uids||[e.uid]).filter(Boolean).map((o,i)=>u0(o,`orderUids[${i}]`));if(!r.length)throw new Error("cowswap: orderUids required");let n=fl(A);return ge({provider:"cowswap",chainId:A,owner:t,orderUids:r,signingScheme:"eip712",typedData:{domain:n,types:a0,primaryType:"OrderCancellations",message:{orderUids:r}},cancelReady:!0,executableArtifact:!0},{provider:"cowswap",kind:"cow-cancel"})}async function XT(e={},A={}){throw new Error("cowswap.cowSignCancel refused: @oracle-agent/oracle is prepare-only. Cancel-sign with the user wallet.")}async function $T(e={},A={}){throw new Error("cowswap.cowCancelOrders refused: @oracle-agent/oracle is prepare-only. Cancel from the user wallet or local operator.")}function jT(e={}){return Jr(e.buyAmount??e.executedBuyAmount??"0","trade.buyAmount")}async function ex(e={},A={}){let t=Number(e.chainId??1),r=u0(e.uid||e.orderUid),n=A.order||await g0({chainId:t,uid:r},A),s=A.status||n.status||await l0({chainId:t,uid:r},A).catch(()=>null),o=A.trades||await Z(`${VT(t,"v2",A)}/trades?orderUid=${encodeURIComponent(r)}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3}),i=Array.isArray(o)?o:[],a=e.expectedOwner?ot(e.expectedOwner,"expectedOwner"):null;if(a&&ot(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 l of i.filter(E=>String(E.orderUid||"").toLowerCase()===r))c+=BigInt(jT(l));c===0n&&n.executedBuyAmount!=null&&(c=BigInt(Jr(n.executedBuyAmount,"executedBuyAmount")));let g=e.minBuyAmount!=null?BigInt(Jr(e.minBuyAmount,"minBuyAmount")):0n,u=c>=g&&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(l=>l.txHash).filter(Boolean))],order:n,orderStatus:s,reason:u?null:"insufficient fill or expired order"}}function Ax(){return Object.keys(dl).map(Number)}var dl,s0,o0,Cl,i0,gi,a0,pl=se(()=>{wA();JA();r0();ri();aA();dl={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"},s0=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),o0=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"}),Cl={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"},i0={1:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",42161:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},gi=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"}]}),a0=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]})});function B0(e){return tx.get(Number(e))||null}function I0(e,A=process.env){let t=B0(e);if(!t)return null;for(let r of t.rpcEnv){let n=(A[r]||"").trim();if(n)return n}return null}var Q0,tx,h0=se(()=>{Q0={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}},tx=new Map(Object.values(Q0).map(e=>[e.chainId,e]))});import{Interface as rx,getAddress as nx}from"ethers";function d0(e,A){try{return nx(e).toLowerCase()}catch{throw new Error(`${A} must be a valid EVM address`)}}function ox(e,{rpcUrl:A,env:t=process.env}={}){if(A)return A;let r=I0(e,t);return r||sx[Number(e)]||null}function ax(e){let A=String(e||""),t=A.toLowerCase();if(A!==A.trim()||!/^[a-zA-Z0-9_]+$/.test(A)||!ix.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 Ce(e,A,t=[],r={}){let n=String(A||"");ax(n);let s=ox(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 Z(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 f0(e,A={}){let t=await Ce(e,"eth_blockNumber",[],A);return parseInt(t,16)}async function p0(e,A={}){let t=await Ce(e,"eth_gasPrice",[],A);if(t==null)return null;try{return BigInt(t)}catch{return null}}async function w0(e,A,t={}){if(!A)throw new Error("rpcGetBalance requires address");let r=await Ce(e,"eth_getBalance",[A,"latest"],t);return{chainId:Number(e),address:A,balanceWei:BigInt(r).toString(),balanceHex:r}}async function m0(e={},A={}){let t=Number(e.chainId??A.chainId??1),r=d0(e.token||e.tokenAddress,"token"),n=d0(e.account||e.owner||e.address,"account"),s=C0.encodeFunctionData("balanceOf",[n]),o=await Ce(t,"eth_call",[{to:r,data:s},e.blockTag||"latest"],A),i=C0.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 C0,sx,ix,vt=se(()=>{wA();h0();C0=new rx(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);sx={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"};ix=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/});function gx(e,A,t){let r=cA(A),n=cA(t),s=cA(e?.baseToken?.address),o=cA(e?.quoteToken?.address);return s===r&&o===n||s===n&&o===r}function Ex(e){let A=Number(e?.liquidity?.usd);return Number.isFinite(A)&&A>=0?A:null}function Qx(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||cx).replace(/\/$/,"")}async function wl(e,A={}){if(!e)throw new Error("tokenAddress required");return Z(`${Qx(A)}/latest/dex/tokens/${e}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??12e3})}async function Qi({chainId:e,tokenA:A,tokenB:t,dexIds:r=[]}={},n={}){if(e==null||!A||!t)throw new Error("chainId, tokenA, and tokenB required");let s=cA(ux[Number(e)]||e),o=new Set(lx(r).filter(Boolean).map(cA)),i=[...new Set([A,t].map(l=>String(l)).filter(Boolean))],a=await Promise.allSettled(i.map(l=>wl(l,{...n,baseUrl:n.dexscreenerBaseUrl,timeoutMs:n.dexscreenerTimeoutMs??Math.min(Number(n.timeoutMs??4e3),4e3)}))),c=new Set,g=[];for(let l of a)if(l.status==="fulfilled")for(let E of l.value?.pairs||l.value?.data?.pairs||[]){let Q=`${cA(E?.chainId)}:${cA(E?.dexId)}:${cA(E?.pairAddress)}`;c.has(Q)||(c.add(Q),g.push(E))}return g.filter(l=>cA(l?.chainId)===s).filter(l=>gx(l,A,t)).filter(l=>!o.size||o.has(cA(l?.dexId))).map(l=>({pairAddress:l.pairAddress??null,dexId:l.dexId??null,chainId:l.chainId??null,liquidityUsd:Ex(l),pairCreatedAt:l.pairCreatedAt??null})).filter(l=>l.liquidityUsd!=null).sort((l,E)=>E.liquidityUsd-l.liquidityUsd)[0]??null}var cx,ux,cA,lx,Bi=se(()=>{wA();cx="https://api.dexscreener.com",ux=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"}),cA=e=>String(e??"").toLowerCase(),lx=e=>Array.isArray(e)?e:e==null?[]:[e]});var N0={};ut(N0,{PANCAKE_FEE_TIERS:()=>Ii,UNI_V3_CHAINS:()=>Ne,UNI_V3_FEE_TIERS:()=>D0,UNI_V3_VENUES:()=>S0,uniV3Chains:()=>px,uniV3EthUsdc:()=>F0,uniV3Health:()=>fx,uniV3PrepareExactIn:()=>dx,uniV3QuoteExactIn:()=>Kn,uniV3QuoteExactInPath:()=>Cx});import{Interface as b0,getAddress as _n,isAddress as Bx}from"ethers";function yl(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=S0[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 ml(e,A){let t=Ne[Number(A)];if(!e||e===k0||e===R0||/^eth$/i.test(String(e)))return _n(t.weth);let r=String(e);if(/^weth$/i.test(r))return _n(t.weth);if(/^usdc$/i.test(r))return _n(t.usdc);if(!Bx(r))throw new Error(`invalid token address: ${e}`);return _n(r)}function Ix(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 hx(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 Kn(e={},A={}){let{chainId:t,quoter:r,router:n,feeTiers:s}=yl(e.chainId??8453,e.venue),o=ml(e.tokenIn||"WETH",t),i=ml(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:D0,g=e.fee!=null?[Number(e.fee)]:e.tryFees===!1?[c[Math.min(2,c.length-1)]]:[...c],u=[],l=null;for(let h of g){let B=hi.encodeFunctionData("quoteExactInputSingle",[{tokenIn:o,tokenOut:i,amountIn:a,fee:h,sqrtPriceLimitX96:0n}]);try{let I=await Ce(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=hi.decodeFunctionResult("quoteExactInputSingle",I),p={fee:h,ok:!0,amountOut:C[0].toString(),sqrtPriceX96After:C[1].toString(),initializedTicksCrossed:Number(C[2]),gasEstimate:C[3].toString()};u.push(p),(!l||BigInt(p.amountOut)>BigInt(l.amountOut))&&(l=p)}catch(I){u.push({fee:h,ok:!1,error:String(I.message||I).slice(0,160)})}}if(!l){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 Qi({chainId:t,tokenA:o,tokenB:i,dexIds:Ix(e.venue)},A).catch(()=>null):null,Q=e.liquidityUsd??E?.liquidityUsd??null;return Ie({venue:"uniswap-v3",chainId:t,chain:Ne[t].name,quoter:r,tokenIn:o,tokenOut:i,amountIn:a.toString(),fee:l.fee,amountOut:l.amountOut,gasEstimate:l.gasEstimate,liquidityUsd:Q,liquiditySource:E,sqrtPriceX96After:l.sqrtPriceX96After,initializedTicksCrossed:l.initializedTicksCrossed,triedFees:u,best:!0},{chainId:t,venue:n,amountOut:l.amountOut,liquidityUsd:Q,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Cx(e={},A={}){let{chainId:t,quoter:r,router:n}=yl(e.chainId??8453),s=(e.tokens||[]).map(l=>ml(l,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=hx(s,o),c=hi.encodeFunctionData("quoteExactInput",[a,i]),g=await Ce(t,"eth_call",[{to:r,data:c},"latest"],A),u=hi.decodeFunctionResult("quoteExactInput",g);return Ie({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 Kn({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 dx(e={},A={}){let t=Number(e.chainId??8453),r=yl(t,e.venue),n=_n(e.recipient),s=String(e.tokenIn||"WETH"),o=!e.tokenIn||s===k0||s===R0||/^eth$/i.test(s),i=await Kn(e,A),a=y0.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,l=y0.encodeFunctionData("multicall",[u,[a]]);return ge({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:l,value:o?i.amountIn:"0",slippageGuard:iA(i.autoSlippage,{chainId:t,venue:r.router,data:l})}},{provider:"uniswap-v3",kind:"univ3-swap-tx"})}async function fx(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 px(){return Object.entries(Ne).map(([e,A])=>({chainId:Number(e),name:A.name,quoter:A.quoter,weth:A.weth,usdc:A.usdc}))}var Ne,D0,hi,y0,k0,R0,Ii,S0,Ci=se(()=>{vt();Bi();JA();aA();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"}},D0=[100,500,3e3,1e4],hi=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)"]),y0=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)"]),k0="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",R0="0x0000000000000000000000000000000000000000",Ii=[100,500,2500,1e4],S0={56:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:Ii}},8453:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:Ii}},42161:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:Ii}},999:{hyperswap:{name:"hyperswap",quoter:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",router:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D"}}}});var Y0={};ut(Y0,{UNI_V4_CHAINS:()=>HA,UNI_V4_FEE_TIERS:()=>T0,computeV4PoolId:()=>v0,uniV4Chains:()=>Nx,uniV4Health:()=>Ux,uniV4PrepareExactIn:()=>Fx,uniV4QuoteExactIn:()=>fi});import{AbiCoder as wx,Interface as L0,getAddress as uA,isAddress as di,keccak256 as mx}from"ethers";function bl(e){let A=Number(e),t=HA[A];if(!t)throw new Error(`uniswap-v4: unsupported chainId ${e} (supported: ${Object.keys(HA).join(", ")})`);return{chainId:A,...t}}function M0(e,A){let t=HA[Number(A)];if(!e||e===x0||e===Yt||/^eth$/i.test(String(e)))return uA(t.weth);let r=String(e);if(/^weth$/i.test(r))return uA(t.weth);if(/^usdc$/i.test(r)||/^usdg$/i.test(r))return uA(t.usdc);if(!di(r))throw new Error(`invalid token address: ${e}`);return uA(r)}function v0({currency0:e,currency1:A,fee:t,tickSpacing:r,hooks:n=Yt}){let s=uA(e),o=uA(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&&di(n)?uA(n):Yt;return mx(Zn.encode(["address","address","uint24","int24","address"],[i,a,Number(t),Number(r),c]))}function Rx({tokenIn:e,tokenOut:A,fee:t,tickSpacing:r,hooks:n=Yt}){let s=uA(e),o=uA(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&&di(n)?uA(n):Yt},zeroForOne:c}}async function fi(e={},A={}){let{chainId:t,quoter:r,poolManager:n,universalRouter:s}=bl(e.chainId??8453),o=M0(e.tokenIn||"WETH",t),i=M0(e.tokenOut||HA[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}]:[...T0],g=e.hooks||Yt,u=[],l=null;for(let h of c){let{poolKey:B,zeroForOne:I}=Rx({tokenIn:o,tokenOut:i,fee:h.fee,tickSpacing:h.tickSpacing,hooks:g}),C=U0.encodeFunctionData("quoteExactInputSingle",[{poolKey:B,zeroForOne:I,exactAmount:a,hookData:"0x"}]);try{let p=await Ce(t,"eth_call",[{to:r,data:C},"latest"],A);if(!p||p==="0x"){u.push({...h,ok:!1,error:"empty result"});continue}let w=U0.decodeFunctionResult("quoteExactInputSingle",p),R={fee:h.fee,tickSpacing:h.tickSpacing,ok:!0,amountOut:w[0].toString(),gasEstimate:w[1].toString(),poolKey:B,zeroForOne:I,poolId:v0({...B})};u.push(R),(!l||BigInt(R.amountOut)>BigInt(l.amountOut))&&(l=R)}catch(p){u.push({...h,ok:!1,error:String(p.message||p).slice(0,160)})}}if(!l){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 Qi({chainId:t,tokenA:o,tokenB:i,dexIds:Sx},A).catch(()=>null):null,Q=e.liquidityUsd??E?.liquidityUsd??null;return Ie({venue:"uniswap-v4",chainId:t,chain:HA[t].name,poolManager:n,quoter:r,universalRouter:s||null,tokenIn:o,tokenOut:i,amountIn:a.toString(),fee:l.fee,tickSpacing:l.tickSpacing,hooks:l.poolKey.hooks,poolId:l.poolId,zeroForOne:l.zeroForOne,amountOut:l.amountOut,gasEstimate:l.gasEstimate,liquidityUsd:Q,liquiditySource:E,triedTiers:u,best:!0,executionReady:!1,prepareReady:typeof e.recipient=="string"&&di(e.recipient)&&e.slippageBps!=null},{chainId:t,venue:s||r,amountOut:l.amountOut,liquidityUsd:Q,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Fx(e={},A={}){let t=Number(e.chainId??8453),r=bl(t);if(!e.recipient)throw new Error("uniswap-v4 prepare requires recipient");let n=uA(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===x0||o===Yt||/^eth$/i.test(o))throw new Error("uniswap-v4 prepare currently requires an ERC-20 tokenIn; native input is not inferred");let i=await fi(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=Zn.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"]]),l=Zn.encode(["address","uint256"],[i.tokenIn,BigInt(i.amountIn)]),E=Zn.encode(["address","uint256"],[i.tokenOut,a]),Q=Zn.encode(["bytes","bytes[]"],[Dx,[u,l,E]]),h=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),I=Number(A.nowSeconds??Math.floor(Date.now()/1e3))+h,C=yx.encodeFunctionData("execute",[bx,[Q],I]);return ge({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:kx,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 Nx(){return Object.entries(HA).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 Ux(e={}){let A=bl(e.chainId??8453),t=await Ce(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 Zn,Yt,HA,T0,U0,yx,bx,Dx,kx,x0,Sx,Dl=se(()=>{vt();Bi();JA();aA();Zn=wx.defaultAbiCoder(),Yt="0x0000000000000000000000000000000000000000",HA={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"}},T0=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200},{fee:25e3,tickSpacing:8}],U0=new L0(["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)"]),yx=new L0(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),bx="0x10",Dx="0x060c0f",kx="0x000000000022D473030F116dDEE9F6B43aC78BA3",x0="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";Sx=["uniswap-v4","uniswapv4"]});var wi={};ut(wi,{ACROSS_API:()=>J0,HOP_API:()=>H0,RELAY_API:()=>V0,acrossHealth:()=>Yx,acrossSuggestedFees:()=>q0,hopHealth:()=>Gx,hopQuote:()=>O0,relayHealth:()=>Jx,relayPrepare:()=>Hx,relayQuote:()=>kl});async function Yx(e={}){try{return{ok:!0,estimatedFillTimeSec:(await q0({token:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",destinationToken:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",originChainId:1,destinationChainId:42161,amount:"1000000000000000"},e)).estimatedFillTimeSec}}catch(A){return{ok:!1,error:String(A.message||A).slice(0,160)}}}async function q0(e={},A={}){let{token:t,destinationToken:r=t,originChainId:n,destinationChainId:s,amount:o}=e;if(!t||n==null||s==null||!o)throw new Error("acrossSuggestedFees requires token, originChainId, destinationChainId, amount");let i=new URLSearchParams({token:t,destinationToken:r,originChainId:String(n),destinationChainId:String(s),amount:String(o)}),a=(A.baseUrl||process.env.ACROSS_API_URL||J0).replace(/\/$/,"");return Z(`${a}/suggested-fees?${i}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3})}async function Gx(e={}){try{let A=await O0({amount:"1000000000000000",token:"ETH",fromChain:"ethereum",toChain:"arbitrum",slippage:.5},e);return{ok:!0,estimatedRecieved:A.estimatedRecieved||A.estimatedReceived}}catch(A){return{ok:!1,error:String(A.message||A).slice(0,160)}}}async function O0(e={},A={}){let{amount:t,token:r="ETH",fromChain:n="ethereum",toChain:s="arbitrum"}=e;if(!t)throw new Error("hopQuote requires amount");let o=e.slippage==null?void 0:Math.round(Number(e.slippage)*100),i=GA({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:n!==s,requestedCapBps:e.maxSlippageBps??e.slippageBps??o});if(!i.executable)throw new Error(`hop: route requires ${i.requiredBps} bps above cap ${i.capBps}`);let a=new URLSearchParams({amount:String(t),token:r,fromChain:n,toChain:s,slippage:String(i.selectedBps/100)}),c=(A.baseUrl||process.env.HOP_API_URL||H0).replace(/\/$/,""),g=await Z(`${c}/quote?${a}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3}),u=g?.estimatedRecieved||g?.estimatedReceived;return u?Ie(g,{chainId:Number(e.originChainId||e.chainId||vx[n]||0),venue:g?.tx?.to||"hop",amountOut:u,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:n!==s,requestedCapBps:e.maxSlippageBps??e.slippageBps??o}):{...g,autoSlippagePolicy:i}}async function Jx(e={}){try{let A=await kl({user:st,originChainId:1,destinationChainId:8453,originCurrency:"0x0000000000000000000000000000000000000000",destinationCurrency:"0x0000000000000000000000000000000000000000",amount:"1000000000000000",tradeType:"EXACT_INPUT"},e);return{ok:!0,hasSteps:Array.isArray(A.steps),stepCount:A.steps?.length||0}}catch(A){return{ok:!1,error:String(A.message||A).slice(0,160)}}}async function kl(e={},A={}){let{user:t=st,originChainId:r,destinationChainId:n,originCurrency:s="0x0000000000000000000000000000000000000000",destinationCurrency:o="0x0000000000000000000000000000000000000000",amount:i,tradeType:a="EXACT_INPUT"}=e;if(r==null||n==null||!i)throw new Error("relayQuote requires originChainId, destinationChainId, amount");let c=GA({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(r)!==Number(n),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!c.executable)throw new Error(`relay: route requires ${c.requiredBps} bps above cap ${c.capBps}`);let g=(A.baseUrl||process.env.RELAY_API_URL||V0).replace(/\/$/,""),u=await Z(`${g}/quote`,{method:"POST",body:{user:t,originChainId:Number(r),destinationChainId:Number(n),originCurrency:s,destinationCurrency:o,amount:String(i),tradeType:a,slippageTolerance:String(c.selectedBps)},fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??2e4}),l=u?.details?.currencyOut?.amount;return!l||!/^\d+$/.test(String(l))?{...u,autoSlippagePolicy:c}:Ie(u,{chainId:Number(r),venue:u?.steps?.[0]?.items?.[0]?.data?.to||"relay",amountOut:l,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(r)!==Number(n),requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Hx(e={},A={}){let t=await kl(e,A),r=Number(e.originChainId),n=(t.steps||[]).flatMap(i=>(i.items||[]).filter(a=>a?.data?.to&&a?.data?.data).map(a=>({stepId:i.id,...a.data})));if(!n.length)throw new Error("relay: quote returned no executable transaction items");let s=String(t?.autoSlippage?.venue||"").toLowerCase();if(n.some(i=>String(i.to).toLowerCase()!==s))throw new Error("relay: route includes a separate approval/transaction that is not yet safely bound");let o=n.map(i=>({chainId:r,from:i.from||e.user,to:i.to,data:i.data,value:i.value??"0x0",...i.gasLimit!=null||i.gas!=null?{gasLimit:i.gasLimit??i.gas}:{},slippageGuard:iA(t.autoSlippage,{chainId:r,venue:i.to,data:i.data})}));return ge({provider:"relay",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,quote:t,autoSlippage:t.autoSlippage,transactions:o},{provider:"relay",kind:"relay-tx"})}var J0,H0,V0,vx,mi=se(()=>{wA();JA();ri();aA();J0="https://across.to/api",H0="https://api.hop.exchange/v1",V0="https://api.relay.link",vx={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453}});import{realpathSync as sp}from"node:fs";import{fileURLToPath as o2}from"node:url";var As=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),H=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),v=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),fp=/^0x[0-9a-fA-F]{40}$/;function pp(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}fp.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))As.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 wp(e){let{ok:A,errors:t,warnings:r}=pp(e);if(!A)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
48
48
  - ${t.join(`
49
- - `)}`);let n=e.capabilities||{},s=As.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:As.filter(i=>!s.includes(i))}},supports(i){return s.includes(i)}};for(let i of As)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 Ni=new Map;function Yl(e){let A=wp(e);return Ni.set(A.chainId,A),A}function ts(e){return Ni.get(Number(e))||null}function Hr(){return[...Ni.values()]}var lA=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"}),Jl={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"},Vr=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}};function Gl(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:g=!1,meta:u={}}=e||{};if(c||t==null)return{source:A,quality:lA.FAILED,amountOut:null,error:c||"no amountOut returned"};let l=Vr(t);if(l==null||l<=0n)return{source:A,quality:lA.FAILED,amountOut:null,error:"non-positive amountOut"};let E=Number(o);return{source:A,quality:n==null?lA.NO_GAS:lA.FULL,amountOut:l.toString(),minOut:Vr(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:g,meta:u}}async function Hl(e,A,{divisor:t=1000n}={}){let r=Vr(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=Vr(s),a=Vr(o);if(i==null||a==null||i<=0n)return null;let c=Number(i)/Number(n),g=Number(a)/Number(r);return!Number.isFinite(c)||!Number.isFinite(g)||c<=0?null:{impactPct:(1-g/c)*100,probeAmountIn:n.toString(),probeAmountOut:i.toString(),fullAmountOut:a.toString()}}function Vl(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 Ui(e,{destPriceUsd:A=null,destDecimals:t=null,liquidityFirst:r=!0,liquidityBandBps:n=50,gasPriceWei:s=null,nativePriceUsd:o=null}={}){let i=e.filter(U=>U.quality!==lA.FAILED),a=e.filter(U=>U.quality===lA.FAILED),c=A!=null&&A>0&&t!=null&&t>=0,g=Number(s),u=Number(o),l=Number.isFinite(g)&&g>0&&Number.isFinite(u)&&u>0,E=i.map(U=>{let P=BigInt(U.amountOut),Ue=0n,pe=!1,ae=!1,qe=BigInt(U.oracleFeeBps??0),yA=qe>0n?P*qe/10000n:0n;if(c){let es=U.gasUsd,Si=Number(U.meta?.gasUnits??U.estimatedGas);if(es==null&&l&&Number.isFinite(Si)&&Si>0){let ct=Si*g/1e18*u;Number.isFinite(ct)&&ct>=0&&(es=ct,ae=!0)}let vl=(es??0)+(U.feeUsd??0);if(vl>0){let ct=vl/A*10**t;Number.isFinite(ct)&&ct>=0&&(Ue=BigInt(Math.floor(ct)),pe=!0)}else es===0&&(pe=!0)}let Jt=Ue+yA,Ht=P>Jt?P-Jt:0n;return{...U,grossOut:P.toString(),netOut:Ht.toString(),costInDest:Ue.toString(),oracleFeeInDest:yA.toString(),costAccounted:pe,gasEstimated:ae}}),Q=Number(n)>0?Number(n):0,h=E.reduce((U,P)=>BigInt(P.netOut)>U?BigInt(P.netOut):U,0n),B=U=>h>0n?Number((h-BigInt(U))*10000n/h):0,I=[],C=E.slice().sort((U,P)=>BigInt(P.netOut)>BigInt(U.netOut)?1:-1)[0]??null;E.sort((U,P)=>{let Ue=B(U.netOut)<=Q?0:1,pe=B(P.netOut)<=Q?0:1;if(r&&Q>0&&Ue!==pe)return Ue-pe;if(r&&Q>0){let ae=U.liquidityUsd??-1,qe=P.liquidityUsd??-1;if(ae!==qe)return qe-ae}return BigInt(P.netOut)>BigInt(U.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 p=E.filter(U=>!U.costAccounted).map(U=>U.source);c?p.length&&I.push(`gas not reported by: ${p.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 w=E[0];if(c&&w&&w.costAccounted===!1){let U=E.find(P=>P.costAccounted&&B(P.netOut)<=Q);U&&I.push(`winner ${w.source} has UNMEASURED gas; gas-measured ${U.source} is within ${Q} bps and may net more once ${w.source}'s real gas is paid \u2014 prefer it if unsure.`)}let R=E.filter(U=>U.gasEstimated).map(U=>U.source);R.length&&I.push(`gas ESTIMATED (from gas units x current gas price, not measured) for: ${R.join(", ")}. Net includes this estimate so the ranking is gas-inclusive, but the on-chain gas may differ.`);let x=null,O=null;if(E.length>=2&&E[0].costAccounted&&E[1].costAccounted){let U=BigInt(E[0].netOut),P=BigInt(E[1].netOut);P>0n&&(x=Number((U-P)*10000n/P),O=`${E[0].source} vs ${E[1].source}`)}return{best:E[0]??null,routes:E,failed:a,improvementBps:x,spreadBasis:O,rankedOn:c?"net-of-cost":"gross",warnings:I}}async function rs(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"?Gl({source:o,error:String(n.reason?.message||n.reason)}):Gl({source:o,...n.value})})}oi();Bl();hl();wA();JA();Il();aA();var YT="https://api.1inch.dev/swap/v6.0";function e0(e={}){return ai({provider:"oneinch",defaultUrl:YT,hosts:["api.1inch.dev"],url:e.baseUrl||process.env.ONEINCH_API_URL})}function GT(e={}){return e0(e).baseUrl}function A0(e={}){return e.apiKey||process.env.ONEINCH_API_KEY||process.env.ONE_INCH_API_KEY||""}function JT(e={}){let A=A0(e);return ci({accept:"application/json"},{Authorization:A?`Bearer ${A}`:""},e0(e).trusted)}async function t0(e={},A={}){if(!A0(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 Z(`${GT(A)}/${t}/quote?${o}`,{headers:JT(A),fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3});return i?.dstAmount?Ie(i,{chainId:t,venue:"1inch-quote",amountOut:i.dstAmount,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):i}pl();Ci();Dl();wA();var Mx="https://coins.llama.fi",Lx="https://api.llama.fi";function Tx(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Mx).replace(/\/$/,"")}function xx(e={}){return(e.baseUrl||process.env.DEFILLAMA_API_URL||Lx).replace(/\/$/,"")}async function pi(e,A={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let t=e.map(encodeURIComponent).join(",");return Z(`${Tx(A)}/prices/current/${t}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs})}async function G0(e={}){return Z(`${xx(e)}/protocols`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??2e4})}var mA=e=>{let A=Number(e);return Number.isFinite(A)?A:null};function yi(e){if(!Array.isArray(e))return null;let A=0,t=!1;for(let r of e){let n=mA(r?.amountUSD);n!=null&&(A+=n,t=!0)}return t?A:null}async function P0(e,A={}){let t=Jl[Number(e)];if(!t)return null;try{let r=await pi([t],A);return mA(r?.coins?.[t]?.price)}catch{return null}}var it=e=>String(e??"").toLowerCase().replace(/[^a-z0-9]/g,""),W0=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"]});async function Vx(e={}){try{let A=await G0({...e,baseUrl:e.defillamaApiBaseUrl,timeoutMs:e.defillamaTimeoutMs??Math.min(Number(e.timeoutMs??5e3),5e3)});return Array.isArray(A)?A:[]}catch{return[]}}function qx(e,A={}){let t=it(A.tool||A.provider||A.bridge||A.protocol),r=[];return e==="lifi"&&t&&t!=="lifi"&&r.push(...W0[t]||[t]),r.push(...W0[it(e)]||[e]),r}function Ox(e,A,t={}){let r=Array.isArray(e)?e:[],n=qx(A,t).map(it).filter(Boolean);for(let s of n){let o=r.find(a=>it(a?.slug)===s||it(a?.name)===s),i=mA(o?.tvl);if(i!=null)return{liquidityUsd:i,protocol:o?.name??o?.slug??s}}for(let s of n){let o=r.find(a=>{let c=it(a?.category);return!c.includes("bridge")&&!c.includes("crosschain")?!1:it(a?.slug).includes(s)||it(a?.name).includes(s)}),i=mA(o?.tvl);if(i!=null)return{liquidityUsd:i,protocol:o?.name??o?.slug??s}}return null}function Rl({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n,slippageBps:s,decimalsIn:o,decimalsOut:i,nativePriceUsd:a=null,destDecimalsPromise:c=null,opts:g={}}){let u=[];return u.push({source:"lifi",run:async()=>{let l=await On({fromChain:e,toChain:e,fromToken:A,toToken:t,fromAmount:r},g),E=l?.estimate??l?.[0]?.estimate;return{amountOut:E?.toAmount,minOut:E?.toAmountMin,gasUsd:yi(E?.gasCosts),feeUsd:yi(E?.feeCosts),oracleFeeBps:l?.oracleFee?.applies?l.oracleFee.bps:0,meta:{tool:l?.tool??l?.toolDetails?.name,oracleFee:l?.oracleFee??null}}}}),o!=null&&u.push({source:"paraswap",run:async()=>{let l=i??(await Promise.resolve(c))?.decimals;if(l==null)throw new Error("paraswap needs destination decimals; none supplied or resolvable");let E=await ii({chainId:e,srcToken:A,destToken:t,amount:r,srcDecimals:o,destDecimals:l},g),Q=E?.priceRoute;return{amountOut:Q?.destAmount,gasUsd:mA(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 l=await li({chainId:e,sellToken:A,buyToken:t,sellAmount:r,taker:n},g),E=null,Q=l?.totalNetworkFee,h=await Promise.resolve(a);return Q!=null&&h&&(E=Number(Q)/1e18*h),{amountOut:l?.buyAmount,minOut:l?.minBuyAmount,gasUsd:E,meta:{source:l?.route?.fills?.[0]?.source}}}}),process.env.ONEINCH_API_KEY&&u.push({source:"1inch",run:async()=>{let l=await t0({chainId:e,src:A,dst:t,amount:r},g),E=null;return l?.gas!=null&&a&&(E=null),{amountOut:l?.dstAmount,gasUsd:E,meta:{gasUnits:l?.gas}}}}),u.push({source:"cow",run:async()=>{let l=await Pn({chainId:e,sellToken:A,buyToken:t,sellAmountBeforeFee:String(r),from:n},g),E=l?.quote??l,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 l=await Kn({chainId:e,tokenIn:A,tokenOut:t,amountIn:r},g);return{amountOut:l?.amountOut,minOut:l?.minOut??l?.amountOutMinimum??null,gasUsd:null,liquidityUsd:l?.liquidityUsd??null,meta:{onchain:!0,fee:l?.fee,gasUnits:l?.gasEstimate,quoter:l?.quoter}}}}),HA[Number(e)]&&u.push({source:"uniswap-v4",run:async()=>{let l=await fi({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,recipient:n,slippageBps:s},g);return{amountOut:l?.amountOut,minOut:l?.minOut??l?.amountOutMinimum??null,gasUsd:null,liquidityUsd:l?.liquidityUsd??null,meta:{onchain:!0,venue:"uniswap-v4",fee:l?.fee,tickSpacing:l?.tickSpacing,poolId:l?.poolId,hooks:l?.hooks,gasUnits:l?.gasEstimate,quoter:l?.quoter,poolManager:l?.poolManager,prepareReady:l?.prepareReady===!0,executionReady:!1}}}}),u}function _0({fromChainId:e,toChainId:A,tokenIn:t,tokenOut:r,amountIn:n,taker:s,opts:o={}}){let i=[],a=null,c=async(g,u={})=>(a||=Vx(o),Ox(await a,g,u));return i.push({source:"lifi",run:async()=>{let g=await On({fromChain:e,toChain:A,fromToken:t,toToken:r,fromAmount:n},o),u=g?.estimate??g?.[0]?.estimate,l={tool:g?.tool??g?.toolDetails?.name,durationSeconds:mA(u?.executionDuration)},E=await c("lifi",l);return{amountOut:u?.toAmount,minOut:u?.toAmountMin,gasUsd:yi(u?.gasCosts),feeUsd:yi(u?.feeCosts),oracleFeeBps:g?.oracleFee?.applies?g.oracleFee.bps:0,liquidityUsd:E?.liquidityUsd??null,meta:{...l,liquidityProtocol:E?.protocol,oracleFee:g?.oracleFee??null}}}}),i.push({source:"relay",run:async()=>{let{relayQuote:g}=await Promise.resolve().then(()=>(mi(),wi)),l=(await g({user:s,originChainId:e,destinationChainId:A,originCurrency:t,destinationCurrency:r,amount:String(n)},o))?.details,E={durationSeconds:mA(l?.timeEstimate),rate:l?.rate},Q=await c("relay",E);return{amountOut:l?.currencyOut?.amount,minOut:l?.currencyOut?.minimumAmount,gasUsd:mA(l?.totalImpact?.usd)!=null?Math.abs(mA(l.totalImpact.usd)):null,liquidityUsd:Q?.liquidityUsd??null,meta:{...E,liquidityProtocol:Q?.protocol}}}}),i.push({source:"across",run:async()=>{let{acrossSuggestedFees:g}=await Promise.resolve().then(()=>(mi(),wi)),u=await g({token:t,destinationToken:r,originChainId:e,destinationChainId:A,amount:String(n)},o),l=u?.totalRelayFee?.total,E=null;if(l!=null)try{let h=BigInt(String(n))-BigInt(String(l));h>0n&&(E=h.toString())}catch{}let Q=await c("across");return{amountOut:E,gasUsd:null,liquidityUsd:Q?.liquidityUsd??null,meta:{derivedFromFees:!0,durationSeconds:mA(u?.estimatedFillTimeSec),limits:u?.limits?{min:u.limits.minDeposit,max:u.limits.maxDeposit}:void 0,liquidityProtocol:Q?.protocol}}}}),i}si();vt();var Wx={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"};async function K0(e,A,t){let r=Wx[Number(e)];if(!r)return{priceUsd:null,decimals:null};let n=`${r}:${A}`;try{let o=(await pi([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 bi(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=P0(t,A),i=K0(t,n,A),a=p0(t,A).catch(()=>null),c=Rl({...e,nativePriceUsd:o,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:A}),[g,u,l]=await Promise.all([rs(c,{timeoutMs:A.timeoutMs??12e3}),i,a]);o.catch(()=>{});let E=await o.then(B=>B,()=>null),Q=Ui(g,{destPriceUsd:u.priceUsd,destDecimals:e.decimalsOut??u.decimals,liquidityBandBps:A.liquidityBandBps??50,gasPriceWei:l,nativePriceUsd:E}),h=A.maxImpactPct===void 0?25:A.maxImpactPct;if(h!=null&&Q.best){let B=Q.best.source,C=await Hl(async p=>{let w=Rl({...e,amountIn:p.toString(),nativePriceUsd:o,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:A}).filter(x=>x.source===B);return w.length?(await rs(w,{timeoutMs:A.timeoutMs??12e3}))?.[0]?.amountOut??null:null},s);if(C){let p=Vl(Q,{[B]:C},{maxImpactPct:h});return{kind:"swap",chainId:t,tokenIn:r,tokenOut:n,amountIn:String(s),...p,sourcesTried:c.length,sourcesAnswered:g.filter(w=>w.quality!==lA.FAILED).length,note:Sl(p,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:g.filter(B=>B.quality!==lA.FAILED).length,note:Sl(Q,c.length)}}async function Di(e,A={}){let{fromChainId:t,toChainId:r,tokenIn:n,tokenOut:s,amountIn:o}=e;if(t==null||r==null||!n||!s||o==null)throw new Error("bestBridgeRoute requires fromChainId, toChainId, tokenIn, tokenOut, amountIn");if(Number(t)===Number(r))throw new Error("bestBridgeRoute is for cross-chain; use bestSwapRoute for same-chain");let i=K0(r,s,A),a=_0({...e,opts:A}),[c,g]=await Promise.all([rs(a,{timeoutMs:A.timeoutMs??15e3}),i]),u=Ui(c,{destPriceUsd:g.priceUsd,destDecimals:e.decimalsOut??g.decimals,liquidityBandBps:A.liquidityBandBps??50}),l=u.routes.map(E=>({source:E.source,seconds:E.meta?.durationSeconds??null})).filter(E=>E.seconds!=null);return{kind:"bridge",fromChainId:t,toChainId:r,tokenIn:n,tokenOut:s,amountIn:String(o),...u,durations:l,sourcesTried:a.length,sourcesAnswered:c.filter(E=>E.quality!==lA.FAILED).length,note:Sl(u,a.length)}}function Px(e){let A=e?.meta?.oracleFee;return A?.applies?` \xB7 ${Yf(A)}`:""}function Sl(e,A){if(!e.best)return"no source returned a usable route";let t=e.routes.length,r=Px(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}aA();var at=Object.freeze({TRANSACTION:"unsigned-transaction",TYPED_DATA_ORDER:"typed-data-order"}),_x=100,Fl={"uniswap-v3":async({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n},s)=>{let{uniV3PrepareExactIn:o}=await Promise.resolve().then(()=>(Ci(),N0)),i=await o({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,recipient:n},s);return{artifactKind:at.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:g}=await Promise.resolve().then(()=>(Dl(),Y0)),u=await g({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,recipient:n,slippageBps:s,fee:o,tickSpacing:i,hooks:a},c);return{artifactKind:at.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(()=>(oi(),El)),i=await o({fromChain:e,toChain:e,fromToken:A,toToken:t,fromAmount:r,fromAddress:n},s);return{artifactKind:at.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(()=>(Bl(),Wf)),c=await a({chainId:e,srcToken:A,destToken:t,amount:r,srcDecimals:s,destDecimals:o,userAddress:n,side:"SELL"},i);return{artifactKind:at.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(()=>(hl(),jf)),i=await o({chainId:e,sellToken:A,buyToken:t,sellAmount:r,taker:n},s);return{artifactKind:at.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(()=>(pl(),E0)),i=await o({chainId:e,sellToken:A,buyToken:t,sellAmountBeforeFee:String(r),from:n},s);return{artifactKind:at.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 Kx=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),Zx=/^0x[0-9a-fA-F]{40}$/;async function Z0(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(!Zx.test(t))throw new Error(`taker must be a valid 20-byte address, got "${t}"`);if(Kx.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 bi(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=Fl[n];if(!o){let B=r.routes.find(I=>Fl[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(" :: "),p=/allowance/i.test(C),w=!p&&/not enough|insufficient|balance/i.test(C),R,x;p?(x="approval-required-first",R=`${n} will not build swap calldata until the token approval exists on-chain. Approve the spender first, then prepare again. Underlying: ${C}`):w?(x="taker-not-funded",R=`${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.`):(x="provider-error",R=`${n} prepare failed: ${C}`);let O=r.routes.find(U=>Fl[U.source]&&U.source!==n);return{ok:!1,reason:R,failureKind:x,...O?{alternative:O.source}:{},comparison:r}}let a=e.driftToleranceBps??_x,c=null,g=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&&(g=`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 ge({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===at.TRANSACTION?i.transaction?.to??null:i.settlement??null,driftBps:c,warnings:[...g?[g]:[],...r.warnings||[],...i.artifactKind===at.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"})}aA();var zx=/^0x[0-9a-fA-F]{40}$/,Xx=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),$x=100,Nl={relay:async({fromChainId:e,toChainId:A,tokenIn:t,tokenOut:r,amountIn:n,taker:s},o)=>{let{relayPrepare:i}=await Promise.resolve().then(()=>(mi(),wi)),a=await i({user:s,originChainId:e,destinationChainId:A,originCurrency:t,destinationCurrency:r,amount:String(n)},o);return{transactions:a.transactions||[],amountOut:a.quote?.details?.currencyOut?.amount??null,minOut:a.quote?.details?.currencyOut?.minimumAmount??null,durationSeconds:a.quote?.details?.timeEstimate??null}},lifi:async({fromChainId:e,toChainId:A,tokenIn:t,tokenOut:r,amountIn:n,taker:s,isHolder:o},i)=>{let{lifiPrepare:a}=await Promise.resolve().then(()=>(oi(),El)),c=await a({fromChain:e,toChain:A,fromToken:t,toToken:r,fromAmount:n,fromAddress:s,isHolder:o,feeAction:"bridge"},i);return{transactions:c.transaction?[c.transaction]:[],requiresApproval:c.requiresApproval??null,amountOut:c.quote?.estimate?.toAmount??null,minOut:c.quote?.estimate?.toAmountMin??null,durationSeconds:c.quote?.estimate?.executionDuration??null}}};async function z0(e,A={}){let{taker:t,fromChainId:r,toChainId:n}=e;if(!t)throw new Error("prepareBestBridgeRoute requires taker: bridge transactions are built FOR an address, and the quote-only placeholder must never end up in one");if(!zx.test(t))throw new Error(`taker must be a valid 20-byte address, got "${t}"`);if(Xx.has(t.toLowerCase()))throw new Error(`taker "${t}" is a placeholder/burn address. Bridging to it would send funds to an address nobody controls, on a chain where you cannot undo it.`);let s=await Di(e,A);if(!s.best)return{ok:!1,reason:"no source returned a usable bridge route",comparison:s};let o=e.source||s.best.source,i=s.routes.find(B=>B.source===o);if(!i)return{ok:!1,reason:`source "${o}" returned no usable route`,comparison:s};let a=Nl[o];if(!a){let B=s.routes.find(I=>Nl[I.source]&&I.source!==o);return{ok:!1,reason:`${o} won the comparison but has no bridge prepare path in this build. `+(B?`Next preparable route is ${B.source}; pass source:"${B.source}".`:"No route in this comparison can be prepared."),failureKind:"no-prepare-path",...B?{alternative:B.source}:{},winner:o,comparison:s}}let c;try{c=await a(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(" :: "),p=/allowance/i.test(C),w=!p&&/not enough|insufficient|balance/i.test(C),R=s.routes.find(x=>Nl[x.source]&&x.source!==o);return{ok:!1,reason:p?`${o} will not build calldata until the token approval exists on-chain. Approve first, then prepare again. Underlying: ${C}`:w?`${o} refused to build: ${C}. Quoting works for any address; preparing needs the real funded wallet on chain ${r}.`:`${o} bridge prepare failed: ${C}`,failureKind:p?"approval-required-first":w?"taker-not-funded":"provider-error",...R?{alternative:R.source}:{},comparison:s}}let g=c.transactions||[];if(!g.length)return{ok:!1,reason:`${o} returned no executable transaction for this route`,failureKind:"provider-error",comparison:s};let u=g.filter(B=>B.chainId!=null&&Number(B.chainId)!==Number(r));if(u.length)return{ok:!1,reason:`${o} returned a transaction for chain ${u[0].chainId} but the origin chain is ${r}. Refusing to hand over a mismatched artifact.`,failureKind:"chain-mismatch",comparison:s};let l=e.driftToleranceBps??$x,E=null,Q=null;if(c.amountOut!=null&&i.grossOut!=null)try{let B=BigInt(i.grossOut),I=BigInt(c.amountOut);B>0n&&(E=Number((I-B)*10000n/B),E<-l&&(Q=`route moved ${(E/100).toFixed(2)}% against you since the comparison (tolerance ${(l/100).toFixed(2)}%). Re-compare before signing.`))}catch{}let h=[...Q?[Q]:[],...s.warnings||[],`Bridging is NOT atomic: the origin transaction succeeding does not mean funds arrived on chain ${n}. Expect ~${c.durationSeconds!=null?`${c.durationSeconds}s`:"minutes"} before the destination credits, and do not re-send if it is pending.`];return g.length>1&&h.push(`This route needs ${g.length} transactions signed IN ORDER. Signing only the first leaves funds approved but not bridged.`),ge({ok:!0,chosen:{source:o,wasWinner:o===s.best.source,netOut:i.netOut,grossOut:i.grossOut,gasUsd:i.gasUsd},artifactKind:"unsigned-transaction-sequence",fromChainId:Number(r),toChainId:Number(n),transactionCount:g.length,transactions:g,requiresApproval:c.requiresApproval??null,minOut:c.minOut??null,durationSeconds:c.durationSeconds??null,destination:g[0]?.to??null,unsigned:!0,signedBy:"user-wallet",driftBps:E,warnings:h,runnersUp:s.routes.filter(B=>B.source!==o).map(B=>({source:B.source,netOut:B.netOut,gasUsd:B.gasUsd})),comparison:{rankedOn:s.rankedOn,sourcesAnswered:s.sourcesAnswered,sourcesTried:s.sourcesTried,improvementBps:s.improvementBps},note:`UNSIGNED. ${g.length} transaction(s) on chain ${r}, crediting chain ${n}. Verify every destination address before signing.`},{provider:"router",kind:"best-bridge"})}vt();Bi();vt();var Ml={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},ze=e=>BigInt(e).toString(16).padStart(64,"0"),zn=e=>e.slice(2).toLowerCase().padStart(64,"0");function jx(e,A){return`0x${Ml.getAmountsOut}`+ze(e)+ze(64)+ze(A.length)+A.map(zn).join("")}function e2(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 Ul(e,A="router"){return(e?.venues||[]).find(r=>r.kind===A)?.address??null}var Ll=100;function A2(e,A){let t=Number(A);if(!Number.isFinite(t)||t<0)throw new Error("slippageBps must be a non-negative number");if(t>Ll)throw new Error(`slippageBps ${t} exceeds the ${Ll} 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 X0(e){let{chainId:A,wrappedNative:t}=e;async function r(n,s,o,i){let a=await Ce(A,"eth_call",[{to:n,data:jx(s,o)},"latest"],i);return e2(a?.result??a)}return{async quote({tokenIn:n,tokenOut:s,amountIn:o,path:i},a={}){let c=Ul(a.scanner);if(!c)return{chainId:A,evidence:H.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let g=i||[n,s];if(g.some(l=>!/^0x[0-9a-fA-F]{40}$/.test(l||"")))throw new Error("quote requires valid 20-byte addresses");let u=await r(c,o,g,a);return u?{chainId:A,router:c,path:g,amountIn:String(o),amountOut:u[u.length-1].toString(),hops:g.length-1,evidence:H.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:A,router:c,path:g,evidence:H.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=Ul(i.scanner),c=o||t;if(c&&String(n).toLowerCase()===String(c).toLowerCase())return{chainId:A,token:n,verdict:v.UNKNOWN,evidence:H.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:v.UNKNOWN,evidence:H.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 g=await r(a,s,[c,n],i);if(!g)return{chainId:A,token:n,verdict:v.FAIL,evidence:H.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let u=g[g.length-1];if(u===0n)return{chainId:A,token:n,verdict:v.FAIL,evidence:H.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let l=await r(a,u,[n,c],i);if(!l)return{chainId:A,token:n,verdict:v.FAIL,evidence:H.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=l[l.length-1],Q=Number(E*10000n/BigInt(s)),h=v.PASS,B="round trip completes with expected fee/impact loss";return Q<5e3?(h=v.FAIL,B=`round trip returns only ${(Q/100).toFixed(2)}% -- punitive tax or no real liquidity`):Q<9e3&&(h=v.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:H.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:g},u={}){let l=u.scanner,E=Ul(l);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=g||[n,s],h=await this.quote({tokenIn:n,tokenOut:s,amountIn:o,path:Q},u);if(h.evidence!==H.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let B=A2(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,p=C?`0x${Ml.swapExactETHForTokens}`+ze(B)+ze(128)+zn(i)+ze(I)+ze(Q.length)+Q.map(zn).join(""):`0x${Ml.swapExactTokensForTokens}`+ze(o)+ze(B)+ze(160)+zn(i)+ze(I)+ze(Q.length)+Q.map(zn).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:A,tx:{to:E,data:p,value:C?`0x${BigInt(o).toString(16)}`:"0x0"},guard:{quotedOut:h.amountOut,minOut:B.toString(),slippageBps:a,maxSlippageBps:Ll,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."}}}}vt();var t2=[100,500,3e3,1e4],$0={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},Gt=e=>BigInt(e).toString(16).padStart(64,"0"),Xn=e=>e.slice(2).toLowerCase().padStart(64,"0"),j0=/^0x[0-9a-fA-F]{40}$/,xl=100;function r2(e,A){let t=Number(A);if(!Number.isFinite(t)||t<0)throw new Error("slippageBps must be a non-negative number");if(t>xl)throw new Error(`slippageBps ${t} exceeds the ${xl} 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 Tl(e,A){return(e?.venues||[]).find(t=>t.kind===A)?.address??null}function ep(e){let{chainId:A,wrappedNative:t}=e;async function r({quoter:s,tokenIn:o,tokenOut:i,amountIn:a,fee:c},g){let u=`0x${$0.quoteExactInputSingle}`+Xn(o)+Xn(i)+Gt(a)+Gt(c)+Gt(0),l=await Ce(A,"eth_call",[{to:s,data:u},"latest"],g).catch(()=>null),E=l?.result??l;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 g=[],u=null;for(let l of t2){let E=await r({quoter:s,tokenIn:o,tokenOut:i,amountIn:a,fee:l},c);g.push({fee:l,amountOut:E?E.toString():null}),E&&(!u||E>u.amountOut)&&(u={fee:l,amountOut:E})}return{best:u,tried:g}}return{async quote({tokenIn:s,tokenOut:o,amountIn:i},a={}){let c=Tl(a.scanner,"quoter");if(!c)return{chainId:A,evidence:H.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let l of[s,o])if(!j0.test(l||""))throw new Error("quote requires valid 20-byte addresses");let{best:g,tried:u}=await n({quoter:c,tokenIn:s,tokenOut:o,amountIn:i},a);return g?{chainId:A,venue:"uniswap-v3",quoter:c,tokenIn:s,tokenOut:o,amountIn:String(i),amountOut:g.amountOut.toString(),fee:g.fee,triedFeeTiers:u,evidence:H.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:H.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=Tl(a.scanner,"quoter"),g=i||t;if(g&&String(s).toLowerCase()===String(g).toLowerCase())return{chainId:A,token:s,verdict:v.UNKNOWN,evidence:H.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||!g)return{chainId:A,token:s,verdict:v.UNKNOWN,evidence:H.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:g,tokenOut:s,amountIn:o},a);if(!u.best)return{chainId:A,token:s,verdict:v.FAIL,evidence:H.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier"};let l=await n({quoter:c,tokenIn:s,tokenOut:g,amountIn:u.best.amountOut},a);if(!l.best)return{chainId:A,token:s,verdict:v.FAIL,evidence:H.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=l.best.amountOut,Q=Number(E*10000n/BigInt(o)),h=v.PASS,B="round trip completes with expected fee/impact loss";return Q<5e3?(h=v.FAIL,B=`round trip returns only ${(Q/100).toFixed(2)}% -- punitive tax or no real liquidity`):Q<9e3&&(h=v.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:g,verdict:h,reason:B,amountIn:String(o),bought:u.best.amountOut.toString(),returned:E.toString(),retentionBps:Q,buyFee:u.best.fee,sellFee:l.best.fee,evidence:H.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:g},u={}){let l=Tl(u.scanner,"router");if(!l)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(!j0.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!==H.LIVE)throw new Error(`cannot prepare without a live quote (${E.evidence}: ${E.reason??"no reason given"})`);let Q=g??E.fee,h=r2(E.amountOut,c);if(h<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let B=`0x${$0.exactInputSingle}`+Xn(s)+Xn(o)+Gt(Q)+Xn(a)+Gt(i)+Gt(h)+Gt(0);return{unsigned:!0,signedBy:"user-wallet",chainId:A,venue:"uniswap-v3",tx:{to:l,data:B,value:"0x0"},guard:{quotedOut:E.amountOut,minOut:h.toString(),slippageBps:c,maxSlippageBps:xl,fee:Q},requires:[{step:"approve",token:s,spender:l,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 ki={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function Ap(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function tp(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 n2(e){let{chainId:A}=e;async function t(r,n,s){return Ce(A,"eth_call",[{to:r,data:n},"latest"],s)}return{async blockNumber(r={}){let n=await f0(A,r);return{chainId:A,blockNumber:n?.blockNumber??n,evidence:H.LIVE}},async nativeBalance(r,n={}){let s=await w0(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:H.LIVE}},async tokenBalance({token:r,owner:n},s={}){let o=await m0({chainId:A,token:r,owner:n},s);return{chainId:A,token:r,owner:n,raw:o?.balance??o,evidence:H.LIVE}},async resolveToken(r,n={}){if(!/^0x[0-9a-fA-F]{40}$/.test(r||""))return{chainId:A,token:r,evidence:H.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,ki.decimals,n).catch(()=>null),t(r,ki.symbol,n).catch(()=>null),t(r,ki.name,n).catch(()=>null),t(r,ki.totalSupply,n).catch(()=>null)]),c=Ap(s?.result??s),g=c!==null||o?.result||i?.result;return{chainId:A,address:r,decimals:c===null?null:Number(c),symbol:tp(o?.result??o),name:tp(i?.result??i),totalSupply:(Ap(a?.result??a)??null)?.toString()??null,evidence:g?H.LIVE:H.UNKNOWN,warning:g?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:H.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let o=await wl(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,g)=>(g.liquidityUsd??0)-(c.liquidityUsd??0));return{chainId:A,token:r,pools:a,evidence:a.length?H.LIVE:H.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=[],g=[];for(let u=r;u<=n;u+=i){let l=Math.min(u+i-1,n);g.push([u,l])}for(let[u,l]of g){let E={fromBlock:`0x${u.toString(16)}`,toBlock:`0x${l.toString(16)}`};s&&(E.address=s),o&&(E.topics=o);let Q=await Ce(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,l],error:Q.error,evidence:H.UNKNOWN};for(let h of Q?.result??Q??[])c.push(h)}return{chainId:A,fromBlock:r,toBlock:n,logs:c,complete:!0,chunks:g.length,evidence:H.LIVE}},async scoreRisk(r,n={}){let s=[],o=v.PASS,i=g=>{let u={[v.PASS]:0,[v.CAUTION]:1,[v.UNKNOWN]:2,[v.FAIL]:3};u[g]>u[o]&&(o=g)},a=await this.resolveToken(r,n);a.evidence!==H.LIVE?(s.push({check:"erc20-metadata",result:v.UNKNOWN,detail:a.warning}),i(v.UNKNOWN)):s.push({check:"erc20-metadata",result:v.PASS,detail:`${a.symbol} / ${a.decimals}d`});let c=await this.resolvePools(r,n);if(c.evidence===H.UNAVAILABLE)s.push({check:"liquidity",result:v.UNKNOWN,detail:c.reason}),i(v.UNKNOWN);else if(!c.pools.length)s.push({check:"liquidity",result:v.FAIL,detail:"no pool with liquidity found"}),i(v.FAIL);else{let g=c.pools[0],u=g.liquidityUsd??0;u<5e3?(s.push({check:"liquidity",result:v.CAUTION,detail:`top pool only $${u}`}),i(v.CAUTION)):s.push({check:"liquidity",result:v.PASS,detail:`$${u} on ${g.dex}`}),g.createdAt&&Date.now()-g.createdAt<24*3600*1e3&&(s.push({check:"age",result:v.CAUTION,detail:"pool under 24h old"}),i(v.CAUTION))}if(typeof this.sellSimulation=="function"){let g=await this.sellSimulation({token:r,amountIn:(10n**16n).toString()},n).catch(u=>({verdict:v.UNKNOWN,reason:String(u?.message||u)}));s.push({check:"sellability",result:g.verdict,detail:g.retentionBps!=null?`round trip returns ${(g.retentionBps/100).toFixed(2)}% -- ${g.reason}`:g.reason}),i(g.verdict)}else s.push({check:"sellability",result:v.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(v.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 rp(e){let t={...n2(e)},r=new Set((e.venues||[]).map(s=>s.kind));e.venueKind==="uniswap-v3"&&r.has("quoter")&&r.has("router")?Object.assign(t,ep({chainId:e.chainId,wrappedNative:e.wrappedNative})):e.venueKind==="uniswap-v2"&&r.has("router")&&Object.assign(t,X0({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 s2=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 np(){return s2.map(e=>Yl(rp(e)))}Ci();var op="0x0000000000000000000000000000000000000000",ip=/^0x[0-9a-fA-F]{40}$/,ap=!1;function Ri(){ap||(np(),ap=!0)}var Ee=class extends Error{constructor(A){super(A),this.name="SwapArgsError"}};function gp(e){if(Ri(),!e)throw new Ee("missing <chain>");let A=Number(e);if(Number.isFinite(A)&&ts(A))return A;let t=Hr().find(r=>r.key===String(e).toLowerCase());if(t)return t.chainId;throw new Ee(`unknown chain "${e}". Known: ${Hr().map(r=>r.key).join(", ")}`)}function $n(e){try{return gp(e)}catch(A){jn(A.message)}}function i2(e){return Ri(),Hr().find(A=>A.chainId===Number(e))?.key??String(e)}function jn(e){console.error(`error: ${e}`),process.exit(1)}function cp(e,A){return(Number(e)/10**A).toLocaleString(void 0,{maximumFractionDigits:6})}function up(e,A){if(console.log(`sources: ${e.sourcesAnswered}/${e.sourcesTried} answered`),console.log(`ranked on: ${e.rankedOn}
49
+ - `)}`);let n=e.capabilities||{},s=As.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:As.filter(i=>!s.includes(i))}},supports(i){return s.includes(i)}};for(let i of As)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 Ni=new Map;function Yl(e){let A=wp(e);return Ni.set(A.chainId,A),A}function ts(e){return Ni.get(Number(e))||null}function Hr(){return[...Ni.values()]}var lA=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"}),Jl={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"},Vr=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}};function Gl(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:g=!1,meta:u={}}=e||{};if(c||t==null)return{source:A,quality:lA.FAILED,amountOut:null,error:c||"no amountOut returned"};let l=Vr(t);if(l==null||l<=0n)return{source:A,quality:lA.FAILED,amountOut:null,error:"non-positive amountOut"};let E=Number(o);return{source:A,quality:n==null?lA.NO_GAS:lA.FULL,amountOut:l.toString(),minOut:Vr(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:g,meta:u}}async function Hl(e,A,{divisor:t=1000n}={}){let r=Vr(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=Vr(s),a=Vr(o);if(i==null||a==null||i<=0n)return null;let c=Number(i)/Number(n),g=Number(a)/Number(r);return!Number.isFinite(c)||!Number.isFinite(g)||c<=0?null:{impactPct:(1-g/c)*100,probeAmountIn:n.toString(),probeAmountOut:i.toString(),fullAmountOut:a.toString()}}function Vl(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 Ui(e,{destPriceUsd:A=null,destDecimals:t=null,liquidityFirst:r=!0,liquidityBandBps:n=50,gasPriceWei:s=null,nativePriceUsd:o=null}={}){let i=e.filter(U=>U.quality!==lA.FAILED),a=e.filter(U=>U.quality===lA.FAILED),c=A!=null&&A>0&&t!=null&&t>=0,g=Number(s),u=Number(o),l=Number.isFinite(g)&&g>0&&Number.isFinite(u)&&u>0,E=i.map(U=>{let P=BigInt(U.amountOut),Ue=0n,pe=!1,ae=!1,qe=BigInt(U.oracleFeeBps??0),yA=qe>0n?P*qe/10000n:0n;if(c){let es=U.gasUsd,Si=Number(U.meta?.gasUnits??U.estimatedGas);if(es==null&&l&&Number.isFinite(Si)&&Si>0){let ct=Si*g/1e18*u;Number.isFinite(ct)&&ct>=0&&(es=ct,ae=!0)}let vl=(es??0)+(U.feeUsd??0);if(vl>0){let ct=vl/A*10**t;Number.isFinite(ct)&&ct>=0&&(Ue=BigInt(Math.floor(ct)),pe=!0)}else es===0&&(pe=!0)}let Jt=Ue+yA,Ht=P>Jt?P-Jt:0n;return{...U,grossOut:P.toString(),netOut:Ht.toString(),costInDest:Ue.toString(),oracleFeeInDest:yA.toString(),costAccounted:pe,gasEstimated:ae}}),Q=Number(n)>0?Number(n):0,h=E.reduce((U,P)=>BigInt(P.netOut)>U?BigInt(P.netOut):U,0n),B=U=>h>0n?Number((h-BigInt(U))*10000n/h):0,I=[],C=E.slice().sort((U,P)=>BigInt(P.netOut)>BigInt(U.netOut)?1:-1)[0]??null;E.sort((U,P)=>{let Ue=B(U.netOut)<=Q?0:1,pe=B(P.netOut)<=Q?0:1;if(r&&Q>0&&Ue!==pe)return Ue-pe;if(r&&Q>0){let ae=U.liquidityUsd??-1,qe=P.liquidityUsd??-1;if(ae!==qe)return qe-ae}return BigInt(P.netOut)>BigInt(U.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 p=E.filter(U=>!U.costAccounted).map(U=>U.source);c?p.length&&I.push(`gas not reported by: ${p.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 w=E[0];if(c&&w&&w.costAccounted===!1){let U=E.find(P=>P.costAccounted&&B(P.netOut)<=Q);U&&I.push(`winner ${w.source} has UNMEASURED gas; gas-measured ${U.source} is within ${Q} bps and may net more once ${w.source}'s real gas is paid \u2014 prefer it if unsure.`)}let R=E.filter(U=>U.gasEstimated).map(U=>U.source);R.length&&I.push(`gas ESTIMATED (from gas units x current gas price, not measured) for: ${R.join(", ")}. Net includes this estimate so the ranking is gas-inclusive, but the on-chain gas may differ.`);let x=null,O=null;if(E.length>=2&&E[0].costAccounted&&E[1].costAccounted){let U=BigInt(E[0].netOut),P=BigInt(E[1].netOut);P>0n&&(x=Number((U-P)*10000n/P),O=`${E[0].source} vs ${E[1].source}`)}return{best:E[0]??null,routes:E,failed:a,improvementBps:x,spreadBasis:O,rankedOn:c?"net-of-cost":"gross",warnings:I}}async function rs(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"?Gl({source:o,error:String(n.reason?.message||n.reason)}):Gl({source:o,...n.value})})}oi();Bl();hl();wA();JA();Il();aA();var YT="https://api.1inch.dev/swap/v6.0";function e0(e={}){return ai({provider:"oneinch",defaultUrl:YT,hosts:["api.1inch.dev"],url:e.baseUrl||process.env.ONEINCH_API_URL})}function GT(e={}){return e0(e).baseUrl}function A0(e={}){return e.apiKey||process.env.ONEINCH_API_KEY||process.env.ONE_INCH_API_KEY||""}function JT(e={}){let A=A0(e);return ci({accept:"application/json"},{Authorization:A?`Bearer ${A}`:""},e0(e).trusted)}async function t0(e={},A={}){if(!A0(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 Z(`${GT(A)}/${t}/quote?${o}`,{headers:JT(A),fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs??15e3});return i?.dstAmount?Ie(i,{chainId:t,venue:"1inch-quote",amountOut:i.dstAmount,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):i}pl();Ci();Dl();wA();var Mx="https://coins.llama.fi",Lx="https://api.llama.fi";function Tx(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Mx).replace(/\/$/,"")}function xx(e={}){return(e.baseUrl||process.env.DEFILLAMA_API_URL||Lx).replace(/\/$/,"")}async function pi(e,A={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let t=e.map(encodeURIComponent).join(",");return Z(`${Tx(A)}/prices/current/${t}`,{fetchImpl:A.fetchImpl,timeoutMs:A.timeoutMs})}async function G0(e={}){return Z(`${xx(e)}/protocols`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??2e4})}var mA=e=>{let A=Number(e);return Number.isFinite(A)?A:null};function yi(e){if(!Array.isArray(e))return null;let A=0,t=!1;for(let r of e){let n=mA(r?.amountUSD);n!=null&&(A+=n,t=!0)}return t?A:null}async function P0(e,A={}){let t=Jl[Number(e)];if(!t)return null;try{let r=await pi([t],A);return mA(r?.coins?.[t]?.price)}catch{return null}}var it=e=>String(e??"").toLowerCase().replace(/[^a-z0-9]/g,""),W0=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"]});async function Vx(e={}){try{let A=await G0({...e,baseUrl:e.defillamaApiBaseUrl,timeoutMs:e.defillamaTimeoutMs??Math.min(Number(e.timeoutMs??5e3),5e3)});return Array.isArray(A)?A:[]}catch{return[]}}function qx(e,A={}){let t=it(A.tool||A.provider||A.bridge||A.protocol),r=[];return e==="lifi"&&t&&t!=="lifi"&&r.push(...W0[t]||[t]),r.push(...W0[it(e)]||[e]),r}function Ox(e,A,t={}){let r=Array.isArray(e)?e:[],n=qx(A,t).map(it).filter(Boolean);for(let s of n){let o=r.find(a=>it(a?.slug)===s||it(a?.name)===s),i=mA(o?.tvl);if(i!=null)return{liquidityUsd:i,protocol:o?.name??o?.slug??s}}for(let s of n){let o=r.find(a=>{let c=it(a?.category);return!c.includes("bridge")&&!c.includes("crosschain")?!1:it(a?.slug).includes(s)||it(a?.name).includes(s)}),i=mA(o?.tvl);if(i!=null)return{liquidityUsd:i,protocol:o?.name??o?.slug??s}}return null}function Rl({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n,slippageBps:s,decimalsIn:o,decimalsOut:i,nativePriceUsd:a=null,destDecimalsPromise:c=null,opts:g={}}){let u=[];return u.push({source:"lifi",run:async()=>{let l=await On({fromChain:e,toChain:e,fromToken:A,toToken:t,fromAmount:r},g),E=l?.estimate??l?.[0]?.estimate;return{amountOut:E?.toAmount,minOut:E?.toAmountMin,gasUsd:yi(E?.gasCosts),feeUsd:yi(E?.feeCosts),oracleFeeBps:l?.oracleFee?.applies?l.oracleFee.bps:0,meta:{tool:l?.tool??l?.toolDetails?.name,oracleFee:l?.oracleFee??null}}}}),o!=null&&u.push({source:"paraswap",run:async()=>{let l=i??(await Promise.resolve(c))?.decimals;if(l==null)throw new Error("paraswap needs destination decimals; none supplied or resolvable");let E=await ii({chainId:e,srcToken:A,destToken:t,amount:r,srcDecimals:o,destDecimals:l},g),Q=E?.priceRoute;return{amountOut:Q?.destAmount,gasUsd:mA(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 l=await li({chainId:e,sellToken:A,buyToken:t,sellAmount:r,taker:n},g),E=null,Q=l?.totalNetworkFee,h=await Promise.resolve(a);return Q!=null&&h&&(E=Number(Q)/1e18*h),{amountOut:l?.buyAmount,minOut:l?.minBuyAmount,gasUsd:E,meta:{source:l?.route?.fills?.[0]?.source}}}}),process.env.ONEINCH_API_KEY&&u.push({source:"1inch",run:async()=>{let l=await t0({chainId:e,src:A,dst:t,amount:r},g),E=null;return l?.gas!=null&&a&&(E=null),{amountOut:l?.dstAmount,gasUsd:E,meta:{gasUnits:l?.gas}}}}),u.push({source:"cow",run:async()=>{let l=await Pn({chainId:e,sellToken:A,buyToken:t,sellAmountBeforeFee:String(r),from:n},g),E=l?.quote??l,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 l=await Kn({chainId:e,tokenIn:A,tokenOut:t,amountIn:r},g);return{amountOut:l?.amountOut,minOut:l?.minOut??l?.amountOutMinimum??null,gasUsd:null,liquidityUsd:l?.liquidityUsd??null,meta:{onchain:!0,fee:l?.fee,gasUnits:l?.gasEstimate,quoter:l?.quoter}}}}),HA[Number(e)]&&u.push({source:"uniswap-v4",run:async()=>{let l=await fi({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,recipient:n,slippageBps:s},g);return{amountOut:l?.amountOut,minOut:l?.minOut??l?.amountOutMinimum??null,gasUsd:null,liquidityUsd:l?.liquidityUsd??null,meta:{onchain:!0,venue:"uniswap-v4",fee:l?.fee,tickSpacing:l?.tickSpacing,poolId:l?.poolId,hooks:l?.hooks,gasUnits:l?.gasEstimate,quoter:l?.quoter,poolManager:l?.poolManager,prepareReady:l?.prepareReady===!0,executionReady:!1}}}}),u}function _0({fromChainId:e,toChainId:A,tokenIn:t,tokenOut:r,amountIn:n,taker:s,opts:o={}}){let i=[],a=null,c=async(g,u={})=>(a||=Vx(o),Ox(await a,g,u));return i.push({source:"lifi",run:async()=>{let g=await On({fromChain:e,toChain:A,fromToken:t,toToken:r,fromAmount:n},o),u=g?.estimate??g?.[0]?.estimate,l={tool:g?.tool??g?.toolDetails?.name,durationSeconds:mA(u?.executionDuration)},E=await c("lifi",l);return{amountOut:u?.toAmount,minOut:u?.toAmountMin,gasUsd:yi(u?.gasCosts),feeUsd:yi(u?.feeCosts),oracleFeeBps:g?.oracleFee?.applies?g.oracleFee.bps:0,liquidityUsd:E?.liquidityUsd??null,meta:{...l,liquidityProtocol:E?.protocol,oracleFee:g?.oracleFee??null}}}}),i.push({source:"relay",run:async()=>{let{relayQuote:g}=await Promise.resolve().then(()=>(mi(),wi)),l=(await g({user:s,originChainId:e,destinationChainId:A,originCurrency:t,destinationCurrency:r,amount:String(n)},o))?.details,E={durationSeconds:mA(l?.timeEstimate),rate:l?.rate},Q=await c("relay",E);return{amountOut:l?.currencyOut?.amount,minOut:l?.currencyOut?.minimumAmount,gasUsd:mA(l?.totalImpact?.usd)!=null?Math.abs(mA(l.totalImpact.usd)):null,liquidityUsd:Q?.liquidityUsd??null,meta:{...E,liquidityProtocol:Q?.protocol}}}}),i.push({source:"across",run:async()=>{let{acrossSuggestedFees:g}=await Promise.resolve().then(()=>(mi(),wi)),u=await g({token:t,destinationToken:r,originChainId:e,destinationChainId:A,amount:String(n)},o),l=u?.totalRelayFee?.total,E=null;if(l!=null)try{let h=BigInt(String(n))-BigInt(String(l));h>0n&&(E=h.toString())}catch{}let Q=await c("across");return{amountOut:E,gasUsd:null,liquidityUsd:Q?.liquidityUsd??null,meta:{derivedFromFees:!0,durationSeconds:mA(u?.estimatedFillTimeSec),limits:u?.limits?{min:u.limits.minDeposit,max:u.limits.maxDeposit}:void 0,liquidityProtocol:Q?.protocol}}}}),i}si();vt();var Wx={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"};async function K0(e,A,t){let r=Wx[Number(e)];if(!r)return{priceUsd:null,decimals:null};let n=`${r}:${A}`;try{let o=(await pi([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 bi(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=P0(t,A),i=K0(t,n,A),a=p0(t,A).catch(()=>null),c=Rl({...e,nativePriceUsd:o,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:A}),[g,u,l]=await Promise.all([rs(c,{timeoutMs:A.timeoutMs??12e3}),i,a]);o.catch(()=>{});let E=await o.then(B=>B,()=>null),Q=Ui(g,{destPriceUsd:u.priceUsd,destDecimals:e.decimalsOut??u.decimals,liquidityBandBps:A.liquidityBandBps??50,gasPriceWei:l,nativePriceUsd:E}),h=A.maxImpactPct===void 0?25:A.maxImpactPct;if(h!=null&&Q.best){let B=Q.best.source,C=await Hl(async p=>{let w=Rl({...e,amountIn:p.toString(),nativePriceUsd:o,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:A}).filter(x=>x.source===B);return w.length?(await rs(w,{timeoutMs:A.timeoutMs??12e3}))?.[0]?.amountOut??null:null},s);if(C){let p=Vl(Q,{[B]:C},{maxImpactPct:h});return{kind:"swap",chainId:t,tokenIn:r,tokenOut:n,amountIn:String(s),...p,sourcesTried:c.length,sourcesAnswered:g.filter(w=>w.quality!==lA.FAILED).length,note:Sl(p,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:g.filter(B=>B.quality!==lA.FAILED).length,note:Sl(Q,c.length)}}async function Di(e,A={}){let{fromChainId:t,toChainId:r,tokenIn:n,tokenOut:s,amountIn:o}=e;if(t==null||r==null||!n||!s||o==null)throw new Error("bestBridgeRoute requires fromChainId, toChainId, tokenIn, tokenOut, amountIn");if(Number(t)===Number(r))throw new Error("bestBridgeRoute is for cross-chain; use bestSwapRoute for same-chain");let i=K0(r,s,A),a=_0({...e,opts:A}),[c,g]=await Promise.all([rs(a,{timeoutMs:A.timeoutMs??15e3}),i]),u=Ui(c,{destPriceUsd:g.priceUsd,destDecimals:e.decimalsOut??g.decimals,liquidityBandBps:A.liquidityBandBps??50}),l=u.routes.map(E=>({source:E.source,seconds:E.meta?.durationSeconds??null})).filter(E=>E.seconds!=null);return{kind:"bridge",fromChainId:t,toChainId:r,tokenIn:n,tokenOut:s,amountIn:String(o),...u,durations:l,sourcesTried:a.length,sourcesAnswered:c.filter(E=>E.quality!==lA.FAILED).length,note:Sl(u,a.length)}}function Px(e){let A=e?.meta?.oracleFee;return A?.applies?` \xB7 ${Yf(A)}`:""}function Sl(e,A){if(!e.best)return"no source returned a usable route";let t=e.routes.length,r=Px(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}aA();var at=Object.freeze({TRANSACTION:"unsigned-transaction",TYPED_DATA_ORDER:"typed-data-order"}),_x=100,Fl={"uniswap-v3":async({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,taker:n},s)=>{let{uniV3PrepareExactIn:o}=await Promise.resolve().then(()=>(Ci(),N0)),i=await o({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,recipient:n},s);return{artifactKind:at.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:g}=await Promise.resolve().then(()=>(Dl(),Y0)),u=await g({chainId:e,tokenIn:A,tokenOut:t,amountIn:r,recipient:n,slippageBps:s,fee:o,tickSpacing:i,hooks:a},c);return{artifactKind:at.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(()=>(oi(),El)),i=await o({fromChain:e,toChain:e,fromToken:A,toToken:t,fromAmount:r,fromAddress:n},s);return{artifactKind:at.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(()=>(Bl(),Wf)),c=await a({chainId:e,srcToken:A,destToken:t,amount:r,srcDecimals:s,destDecimals:o,userAddress:n,side:"SELL"},i);return{artifactKind:at.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(()=>(hl(),jf)),i=await o({chainId:e,sellToken:A,buyToken:t,sellAmount:r,taker:n},s);return{artifactKind:at.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(()=>(pl(),E0)),i=await o({chainId:e,sellToken:A,buyToken:t,sellAmountBeforeFee:String(r),from:n},s);return{artifactKind:at.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 Kx=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),Zx=/^0x[0-9a-fA-F]{40}$/;async function Z0(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(!Zx.test(t))throw new Error(`taker must be a valid 20-byte address, got "${t}"`);if(Kx.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 bi(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=Fl[n];if(!o){let B=r.routes.find(I=>Fl[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(" :: "),p=/allowance/i.test(C),w=!p&&/not enough|insufficient|balance/i.test(C),R,x;p?(x="approval-required-first",R=`${n} will not build swap calldata until the token approval exists on-chain. Approve the spender first, then prepare again. Underlying: ${C}`):w?(x="taker-not-funded",R=`${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.`):(x="provider-error",R=`${n} prepare failed: ${C}`);let O=r.routes.find(U=>Fl[U.source]&&U.source!==n);return{ok:!1,reason:R,failureKind:x,...O?{alternative:O.source}:{},comparison:r}}let a=e.driftToleranceBps??_x,c=null,g=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&&(g=`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 ge({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===at.TRANSACTION?i.transaction?.to??null:i.settlement??null,driftBps:c,warnings:[...g?[g]:[],...r.warnings||[],...i.artifactKind===at.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"})}aA();var zx=/^0x[0-9a-fA-F]{40}$/,Xx=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),$x=100,Nl={relay:async({fromChainId:e,toChainId:A,tokenIn:t,tokenOut:r,amountIn:n,taker:s},o)=>{let{relayPrepare:i}=await Promise.resolve().then(()=>(mi(),wi)),a=await i({user:s,originChainId:e,destinationChainId:A,originCurrency:t,destinationCurrency:r,amount:String(n)},o);return{transactions:a.transactions||[],amountOut:a.quote?.details?.currencyOut?.amount??null,minOut:a.quote?.details?.currencyOut?.minimumAmount??null,durationSeconds:a.quote?.details?.timeEstimate??null}},lifi:async({fromChainId:e,toChainId:A,tokenIn:t,tokenOut:r,amountIn:n,taker:s,isHolder:o},i)=>{let{lifiPrepare:a}=await Promise.resolve().then(()=>(oi(),El)),c=await a({fromChain:e,toChain:A,fromToken:t,toToken:r,fromAmount:n,fromAddress:s,isHolder:o,feeAction:"bridge"},i);return{transactions:c.transaction?[c.transaction]:[],requiresApproval:c.requiresApproval??null,amountOut:c.quote?.estimate?.toAmount??null,minOut:c.quote?.estimate?.toAmountMin??null,durationSeconds:c.quote?.estimate?.executionDuration??null}}};async function z0(e,A={}){let{taker:t,fromChainId:r,toChainId:n}=e;if(!t)throw new Error("prepareBestBridgeRoute requires taker: bridge transactions are built FOR an address, and the quote-only placeholder must never end up in one");if(!zx.test(t))throw new Error(`taker must be a valid 20-byte address, got "${t}"`);if(Xx.has(t.toLowerCase()))throw new Error(`taker "${t}" is a placeholder/burn address. Bridging to it would send funds to an address nobody controls, on a chain where you cannot undo it.`);let s=await Di(e,A);if(!s.best)return{ok:!1,reason:"no source returned a usable bridge route",comparison:s};let o=e.source||s.best.source,i=s.routes.find(B=>B.source===o);if(!i)return{ok:!1,reason:`source "${o}" returned no usable route`,comparison:s};let a=Nl[o];if(!a){let B=s.routes.find(I=>Nl[I.source]&&I.source!==o);return{ok:!1,reason:`${o} won the comparison but has no bridge prepare path in this build. `+(B?`Next preparable route is ${B.source}; pass source:"${B.source}".`:"No route in this comparison can be prepared."),failureKind:"no-prepare-path",...B?{alternative:B.source}:{},winner:o,comparison:s}}let c;try{c=await a(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(" :: "),p=/allowance/i.test(C),w=!p&&/not enough|insufficient|balance/i.test(C),R=s.routes.find(x=>Nl[x.source]&&x.source!==o);return{ok:!1,reason:p?`${o} will not build calldata until the token approval exists on-chain. Approve first, then prepare again. Underlying: ${C}`:w?`${o} refused to build: ${C}. Quoting works for any address; preparing needs the real funded wallet on chain ${r}.`:`${o} bridge prepare failed: ${C}`,failureKind:p?"approval-required-first":w?"taker-not-funded":"provider-error",...R?{alternative:R.source}:{},comparison:s}}let g=c.transactions||[];if(!g.length)return{ok:!1,reason:`${o} returned no executable transaction for this route`,failureKind:"provider-error",comparison:s};let u=g.filter(B=>B.chainId!=null&&Number(B.chainId)!==Number(r));if(u.length)return{ok:!1,reason:`${o} returned a transaction for chain ${u[0].chainId} but the origin chain is ${r}. Refusing to hand over a mismatched artifact.`,failureKind:"chain-mismatch",comparison:s};let l=e.driftToleranceBps??$x,E=null,Q=null;if(c.amountOut!=null&&i.grossOut!=null)try{let B=BigInt(i.grossOut),I=BigInt(c.amountOut);B>0n&&(E=Number((I-B)*10000n/B),E<-l&&(Q=`route moved ${(E/100).toFixed(2)}% against you since the comparison (tolerance ${(l/100).toFixed(2)}%). Re-compare before signing.`))}catch{}let h=[...Q?[Q]:[],...s.warnings||[],`Bridging is NOT atomic: the origin transaction succeeding does not mean funds arrived on chain ${n}. Expect ~${c.durationSeconds!=null?`${c.durationSeconds}s`:"minutes"} before the destination credits, and do not re-send if it is pending.`];return g.length>1&&h.push(`This route needs ${g.length} transactions signed IN ORDER. Signing only the first leaves funds approved but not bridged.`),ge({ok:!0,chosen:{source:o,wasWinner:o===s.best.source,netOut:i.netOut,grossOut:i.grossOut,gasUsd:i.gasUsd},artifactKind:"unsigned-transaction-sequence",fromChainId:Number(r),toChainId:Number(n),transactionCount:g.length,transactions:g,requiresApproval:c.requiresApproval??null,minOut:c.minOut??null,durationSeconds:c.durationSeconds??null,destination:g[0]?.to??null,unsigned:!0,signedBy:"user-wallet",driftBps:E,warnings:h,runnersUp:s.routes.filter(B=>B.source!==o).map(B=>({source:B.source,netOut:B.netOut,gasUsd:B.gasUsd})),comparison:{rankedOn:s.rankedOn,sourcesAnswered:s.sourcesAnswered,sourcesTried:s.sourcesTried,improvementBps:s.improvementBps},note:`UNSIGNED. ${g.length} transaction(s) on chain ${r}, crediting chain ${n}. Verify every destination address before signing.`},{provider:"router",kind:"best-bridge"})}vt();Bi();vt();var Ml={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},ze=e=>BigInt(e).toString(16).padStart(64,"0"),zn=e=>e.slice(2).toLowerCase().padStart(64,"0");function jx(e,A){return`0x${Ml.getAmountsOut}`+ze(e)+ze(64)+ze(A.length)+A.map(zn).join("")}function e2(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 Ul(e,A="router"){return(e?.venues||[]).find(r=>r.kind===A)?.address??null}var Ll=100;function A2(e,A){let t=Number(A);if(!Number.isFinite(t)||t<0)throw new Error("slippageBps must be a non-negative number");if(t>Ll)throw new Error(`slippageBps ${t} exceeds the ${Ll} 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 X0(e){let{chainId:A,wrappedNative:t}=e;async function r(n,s,o,i){let a=await Ce(A,"eth_call",[{to:n,data:jx(s,o)},"latest"],i);return e2(a?.result??a)}return{async quote({tokenIn:n,tokenOut:s,amountIn:o,path:i},a={}){let c=Ul(a.scanner);if(!c)return{chainId:A,evidence:H.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let g=i||[n,s];if(g.some(l=>!/^0x[0-9a-fA-F]{40}$/.test(l||"")))throw new Error("quote requires valid 20-byte addresses");let u=await r(c,o,g,a);return u?{chainId:A,router:c,path:g,amountIn:String(o),amountOut:u[u.length-1].toString(),hops:g.length-1,evidence:H.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:A,router:c,path:g,evidence:H.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=Ul(i.scanner),c=o||t;if(c&&String(n).toLowerCase()===String(c).toLowerCase())return{chainId:A,token:n,verdict:v.UNKNOWN,evidence:H.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:v.UNKNOWN,evidence:H.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 g=await r(a,s,[c,n],i);if(!g)return{chainId:A,token:n,verdict:v.FAIL,evidence:H.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let u=g[g.length-1];if(u===0n)return{chainId:A,token:n,verdict:v.FAIL,evidence:H.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let l=await r(a,u,[n,c],i);if(!l)return{chainId:A,token:n,verdict:v.FAIL,evidence:H.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=l[l.length-1],Q=Number(E*10000n/BigInt(s)),h=v.PASS,B="round trip completes with expected fee/impact loss";return Q<5e3?(h=v.FAIL,B=`round trip returns only ${(Q/100).toFixed(2)}% -- punitive tax or no real liquidity`):Q<9e3&&(h=v.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:H.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:g},u={}){let l=u.scanner,E=Ul(l);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=g||[n,s],h=await this.quote({tokenIn:n,tokenOut:s,amountIn:o,path:Q},u);if(h.evidence!==H.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let B=A2(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,p=C?`0x${Ml.swapExactETHForTokens}`+ze(B)+ze(128)+zn(i)+ze(I)+ze(Q.length)+Q.map(zn).join(""):`0x${Ml.swapExactTokensForTokens}`+ze(o)+ze(B)+ze(160)+zn(i)+ze(I)+ze(Q.length)+Q.map(zn).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:A,tx:{to:E,data:p,value:C?`0x${BigInt(o).toString(16)}`:"0x0"},guard:{quotedOut:h.amountOut,minOut:B.toString(),slippageBps:a,maxSlippageBps:Ll,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."}}}}vt();var t2=[100,500,3e3,1e4],$0={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},Gt=e=>BigInt(e).toString(16).padStart(64,"0"),Xn=e=>e.slice(2).toLowerCase().padStart(64,"0"),j0=/^0x[0-9a-fA-F]{40}$/,xl=100;function r2(e,A){let t=Number(A);if(!Number.isFinite(t)||t<0)throw new Error("slippageBps must be a non-negative number");if(t>xl)throw new Error(`slippageBps ${t} exceeds the ${xl} 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 Tl(e,A){return(e?.venues||[]).find(t=>t.kind===A)?.address??null}function ep(e){let{chainId:A,wrappedNative:t}=e;async function r({quoter:s,tokenIn:o,tokenOut:i,amountIn:a,fee:c},g){let u=`0x${$0.quoteExactInputSingle}`+Xn(o)+Xn(i)+Gt(a)+Gt(c)+Gt(0),l=await Ce(A,"eth_call",[{to:s,data:u},"latest"],g).catch(()=>null),E=l?.result??l;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 g=[],u=null;for(let l of t2){let E=await r({quoter:s,tokenIn:o,tokenOut:i,amountIn:a,fee:l},c);g.push({fee:l,amountOut:E?E.toString():null}),E&&(!u||E>u.amountOut)&&(u={fee:l,amountOut:E})}return{best:u,tried:g}}return{async quote({tokenIn:s,tokenOut:o,amountIn:i},a={}){let c=Tl(a.scanner,"quoter");if(!c)return{chainId:A,evidence:H.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let l of[s,o])if(!j0.test(l||""))throw new Error("quote requires valid 20-byte addresses");let{best:g,tried:u}=await n({quoter:c,tokenIn:s,tokenOut:o,amountIn:i},a);return g?{chainId:A,venue:"uniswap-v3",quoter:c,tokenIn:s,tokenOut:o,amountIn:String(i),amountOut:g.amountOut.toString(),fee:g.fee,useNative:!!t&&String(s).toLowerCase()===String(t).toLowerCase(),triedFeeTiers:u,evidence:H.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:H.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=Tl(a.scanner,"quoter"),g=i||t;if(g&&String(s).toLowerCase()===String(g).toLowerCase())return{chainId:A,token:s,verdict:v.UNKNOWN,evidence:H.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||!g)return{chainId:A,token:s,verdict:v.UNKNOWN,evidence:H.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:g,tokenOut:s,amountIn:o},a);if(!u.best)return{chainId:A,token:s,verdict:v.FAIL,evidence:H.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier"};let l=await n({quoter:c,tokenIn:s,tokenOut:g,amountIn:u.best.amountOut},a);if(!l.best)return{chainId:A,token:s,verdict:v.FAIL,evidence:H.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=l.best.amountOut,Q=Number(E*10000n/BigInt(o)),h=v.PASS,B="round trip completes with expected fee/impact loss";return Q<5e3?(h=v.FAIL,B=`round trip returns only ${(Q/100).toFixed(2)}% -- punitive tax or no real liquidity`):Q<9e3&&(h=v.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:g,verdict:h,reason:B,amountIn:String(o),bought:u.best.amountOut.toString(),returned:E.toString(),retentionBps:Q,buyFee:u.best.fee,sellFee:l.best.fee,evidence:H.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:g},u={}){let l=Tl(u.scanner,"router");if(!l)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(!j0.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!==H.LIVE)throw new Error(`cannot prepare without a live quote (${E.evidence}: ${E.reason??"no reason given"})`);let Q=g??E.fee,h=r2(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${$0.exactInputSingle}`+Xn(s)+Xn(o)+Gt(Q)+Xn(a)+Gt(i)+Gt(h)+Gt(0);return{unsigned:!0,signedBy:"user-wallet",chainId:A,venue:"uniswap-v3",tx:{to:l,data:I,value:B?String(i):"0x0"},guard:{quotedOut:E.amountOut,minOut:h.toString(),slippageBps:c,maxSlippageBps:xl,fee:Q},requires:B?[]:[{step:"approve",token:s,spender:l,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 ki={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function Ap(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function tp(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 n2(e){let{chainId:A}=e;async function t(r,n,s){return Ce(A,"eth_call",[{to:r,data:n},"latest"],s)}return{async blockNumber(r={}){let n=await f0(A,r);return{chainId:A,blockNumber:n?.blockNumber??n,evidence:H.LIVE}},async nativeBalance(r,n={}){let s=await w0(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:H.LIVE}},async tokenBalance({token:r,owner:n},s={}){let o=await m0({chainId:A,token:r,owner:n},s);return{chainId:A,token:r,owner:n,raw:o?.balance??o,evidence:H.LIVE}},async resolveToken(r,n={}){if(!/^0x[0-9a-fA-F]{40}$/.test(r||""))return{chainId:A,token:r,evidence:H.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,ki.decimals,n).catch(()=>null),t(r,ki.symbol,n).catch(()=>null),t(r,ki.name,n).catch(()=>null),t(r,ki.totalSupply,n).catch(()=>null)]),c=Ap(s?.result??s),g=c!==null||o?.result||i?.result;return{chainId:A,address:r,decimals:c===null?null:Number(c),symbol:tp(o?.result??o),name:tp(i?.result??i),totalSupply:(Ap(a?.result??a)??null)?.toString()??null,evidence:g?H.LIVE:H.UNKNOWN,warning:g?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:H.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let o=await wl(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,g)=>(g.liquidityUsd??0)-(c.liquidityUsd??0));return{chainId:A,token:r,pools:a,evidence:a.length?H.LIVE:H.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=[],g=[];for(let u=r;u<=n;u+=i){let l=Math.min(u+i-1,n);g.push([u,l])}for(let[u,l]of g){let E={fromBlock:`0x${u.toString(16)}`,toBlock:`0x${l.toString(16)}`};s&&(E.address=s),o&&(E.topics=o);let Q=await Ce(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,l],error:Q.error,evidence:H.UNKNOWN};for(let h of Q?.result??Q??[])c.push(h)}return{chainId:A,fromBlock:r,toBlock:n,logs:c,complete:!0,chunks:g.length,evidence:H.LIVE}},async scoreRisk(r,n={}){let s=[],o=v.PASS,i=g=>{let u={[v.PASS]:0,[v.CAUTION]:1,[v.UNKNOWN]:2,[v.FAIL]:3};u[g]>u[o]&&(o=g)},a=await this.resolveToken(r,n);a.evidence!==H.LIVE?(s.push({check:"erc20-metadata",result:v.UNKNOWN,detail:a.warning}),i(v.UNKNOWN)):s.push({check:"erc20-metadata",result:v.PASS,detail:`${a.symbol} / ${a.decimals}d`});let c=await this.resolvePools(r,n);if(c.evidence===H.UNAVAILABLE)s.push({check:"liquidity",result:v.UNKNOWN,detail:c.reason}),i(v.UNKNOWN);else if(!c.pools.length)s.push({check:"liquidity",result:v.FAIL,detail:"no pool with liquidity found"}),i(v.FAIL);else{let g=c.pools[0],u=g.liquidityUsd??0;u<5e3?(s.push({check:"liquidity",result:v.CAUTION,detail:`top pool only $${u}`}),i(v.CAUTION)):s.push({check:"liquidity",result:v.PASS,detail:`$${u} on ${g.dex}`}),g.createdAt&&Date.now()-g.createdAt<24*3600*1e3&&(s.push({check:"age",result:v.CAUTION,detail:"pool under 24h old"}),i(v.CAUTION))}if(typeof this.sellSimulation=="function"){let g=await this.sellSimulation({token:r,amountIn:(10n**16n).toString()},n).catch(u=>({verdict:v.UNKNOWN,reason:String(u?.message||u)}));s.push({check:"sellability",result:g.verdict,detail:g.retentionBps!=null?`round trip returns ${(g.retentionBps/100).toFixed(2)}% -- ${g.reason}`:g.reason}),i(g.verdict)}else s.push({check:"sellability",result:v.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(v.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 rp(e){let t={...n2(e)},r=new Set((e.venues||[]).map(s=>s.kind));e.venueKind==="uniswap-v3"&&r.has("quoter")&&r.has("router")?Object.assign(t,ep({chainId:e.chainId,wrappedNative:e.wrappedNative})):e.venueKind==="uniswap-v2"&&r.has("router")&&Object.assign(t,X0({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 s2=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 np(){return s2.map(e=>Yl(rp(e)))}Ci();var op="0x0000000000000000000000000000000000000000",ip=/^0x[0-9a-fA-F]{40}$/,ap=!1;function Ri(){ap||(np(),ap=!0)}var Ee=class extends Error{constructor(A){super(A),this.name="SwapArgsError"}};function gp(e){if(Ri(),!e)throw new Ee("missing <chain>");let A=Number(e);if(Number.isFinite(A)&&ts(A))return A;let t=Hr().find(r=>r.key===String(e).toLowerCase());if(t)return t.chainId;throw new Ee(`unknown chain "${e}". Known: ${Hr().map(r=>r.key).join(", ")}`)}function $n(e){try{return gp(e)}catch(A){jn(A.message)}}function i2(e){return Ri(),Hr().find(A=>A.chainId===Number(e))?.key??String(e)}function jn(e){console.error(`error: ${e}`),process.exit(1)}function cp(e,A){return(Number(e)/10**A).toLocaleString(void 0,{maximumFractionDigits:6})}function up(e,A){if(console.log(`sources: ${e.sourcesAnswered}/${e.sourcesTried} answered`),console.log(`ranked on: ${e.rankedOn}
50
50
  `),!e.routes.length){console.log("no source returned a usable route.");for(let r of e.failed)console.log(` ${r.source}: ${r.error}`);return}let t=Math.max(...e.routes.map(r=>r.source.length),6);console.log(` ${"source".padEnd(t)} ${"net out".padStart(14)} ${"gross".padStart(14)} cost`);for(let[r,n]of e.routes.entries()){let s=r===0?"*":" ",o=n.gasUsd==null?"gas unknown":n.gasUsd===0?"gasless (solver)":`$${Number(n.gasUsd+(n.feeUsd??0)).toFixed(2)}`,i=n.meta?.durationSeconds!=null?` ~${n.meta.durationSeconds}s`:"";console.log(`${s} ${n.source.padEnd(t)} ${cp(n.netOut,A).padStart(14)} ${cp(n.grossOut,A).padStart(14)} ${o}${i}`)}for(let r of e.failed)console.log(` ${r.source.padEnd(t)} FAILED: ${String(r.error).slice(0,60)}`);console.log(`
51
51
  ${e.note}`);for(let r of e.warnings)console.log(`
52
52
  WARNING: ${r}`)}function lp(e,A,t){let r=String(e).trim();if(!/^\d+(\.\d+)?$/.test(r))throw new Ee(`${t} "${e}" is not a positive decimal number`);if(A==null)throw new Ee(`cannot scale ${t} "${e}": the token's decimals could not be read from chain. Pass exact base units instead (--base-units <integer>).`);let n=Number(A),[s,o=""]=r.split(".");if(o.length>n)throw new Ee(`${t} "${e}" has more precision than the token's ${n} decimals`);let i=(BigInt(s)*10n**BigInt(n)+BigInt(o.padEnd(n,"0")||"0")).toString();if(i==="0")throw new Ee(`${t} "${e}" rounds to zero at ${n} decimals`);return i}function a2(e,A){let t=String(e).trim();if(!/^\d+$/.test(t))throw new Ee(`${A} "${e}" must be a positive integer of base units`);if(BigInt(t)===0n)throw new Ee(`${A} must be greater than zero`);return t}function c2({raw:e,symbol:A,address:t,decimals:r,chainRef:n}){let s=A?`${A} (${t})`:t,o=10n**BigInt(r)*BigInt(e),i=`0.${String(e).padStart(r,"0")}`.replace(/(\.\d*?[1-9])0+$/,"$1");return new Ee([`ambiguous amount "${e}" for ${s}.`,`Bare numbers are BASE UNITS, so "${e}" means ${i} ${A||"token"} -- dust that no source will quote.`,`If you meant ${e} whole tokens, that is ${o} base units. Say which you meant:`,"",` human amount: oracle route swap ${n} <tokenIn> <tokenOut> --amount ${e}`,` explicit base units: oracle route swap ${n} <tokenIn> <tokenOut> ${o}`,` exact, no scaling: oracle route swap ${n} <tokenIn> <tokenOut> --base-units ${e}`,` fully explicit: oracle route swap ${n} ${t} <tokenOutAddress> ${o}`].join(`