@oracle-agent/oracle 0.35.51 → 0.35.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/agent-sessions.mjs +21 -21
  2. package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
  3. package/dist/bin/desk-server.mjs +28 -28
  4. package/dist/bin/oracle-data-mcp.mjs +13 -13
  5. package/dist/bin/oracle-public-server.mjs +4 -4
  6. package/dist/bin/oracle-route.mjs +12 -12
  7. package/dist/cli/commands/agent-session.mjs +19 -19
  8. package/dist/cli/commands/chat.mjs +262 -230
  9. package/dist/cli/commands/data.mjs +31 -31
  10. package/dist/cli/commands/doctor.mjs +1 -1
  11. package/dist/cli/commands/eval.mjs +199 -167
  12. package/dist/cli/commands/extension-policy.mjs +1 -1
  13. package/dist/cli/commands/model.mjs +266 -234
  14. package/dist/cli/commands/swap.mjs +6 -6
  15. package/dist/data/desk-data.mjs +26 -26
  16. package/dist/data/providers/lp-destination-discovery.mjs +2 -2
  17. package/dist/index.mjs +42 -42
  18. package/dist/router/index.mjs +2 -2
  19. package/dist/router/prepare-bridge.mjs +1 -1
  20. package/dist/router/prepare-route.mjs +2 -2
  21. package/dist/tui/permission-modes.mjs +4 -0
  22. package/dist/tui/standalone-client.mjs +132 -100
  23. package/package.json +2 -1
  24. package/public/oracle-splash/docs/browser-and-web/index.html +2 -2
  25. package/public/oracle-splash/docs/connectors/index.html +2 -2
  26. package/public/oracle-splash/docs/getting-started/index.html +2 -2
  27. package/public/oracle-splash/docs/index.html +3 -3
  28. package/public/oracle-splash/docs/reference/index.html +2 -2
  29. package/public/oracle-splash/docs/security/index.html +2 -2
  30. package/public/oracle-splash/docs/using-oracle/index.html +2 -2
  31. package/server.json +2 -2
@@ -1,2 +1,2 @@
1
1
  var jr=Object.defineProperty;var V=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var je=(e,t)=>{for(var r in t)jr(e,r,{get:t[r],enumerable:!0})};import{AsyncLocalStorage as Vr}from"node:async_hooks";function Te(e){let t=zr.getStore();if(!t||t.closed||!Kr.includes(e))return null;if(t.spans.length>=Gr)return t.droppedSpans++,null;let r={stage:e,startMs:t.now()-t.start,durationMs:null,outcome:"pending",status:null};return t.spans.push(r),(n,a=null)=>{t.closed||r.durationMs!==null||(r.durationMs=Math.max(0,t.now()-t.start-r.startMs),r.outcome=n==="succeeded"?"succeeded":"failed",r.status=Number.isInteger(a)&&a>=100&&a<=599?a:null)}}var zr,Kr,Gr,Ot=V(()=>{zr=new Vr,Kr=["http","retry","shared"],Gr=512});import ue from"node:net";import Wr from"node:dns";function Ne(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=c=>{if(!c)return[];let d=c.split(":"),h=d.at(-1);if(h?.includes(".")){let p=h.split(".").map(Number);if(p.length!==4||p.some(m=>!Number.isInteger(m)||m<0||m>255))return null;d.splice(d.length-1,1,(p[0]<<8|p[1]).toString(16),(p[2]<<8|p[3]).toString(16))}return d.some(p=>!/^[0-9a-f]{1,4}$/.test(p))?null:d.map(p=>Number.parseInt(p,16))},[n,a]=t.split("::"),s=r(n),o=r(a);if(!s||!o)return null;let u=t.includes("::"),l=8-s.length-o.length;if(!u&&l!==0||u&&l<1)return null;let i=[...s,...Array(Math.max(0,l)).fill(0),...o];return i.length!==8?null:Uint8Array.from(i.flatMap(c=>[c>>8,c&255]))}function Ke(e,t,r){let n=Math.floor(r/8),a=r%8;for(let o=0;o<n;o+=1)if(e[o]!==t[o])return!1;if(!a)return!0;let s=255<<8-a;return(e[n]&s)===(t[n]&s)}function Ge(e){if(ue.isIPv4(e)){let t=e.split(".").map(Number);return!(t[0]===0||t[0]===10||t[0]===127||t[0]>=224||t[0]===100&&t[1]>=64&&t[1]<=127||t[0]===169&&t[1]===254||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&(t[1]===0||t[1]===2||t[1]===168)||t[0]===192&&t[1]===88&&t[2]===99||t[0]===198&&(t[1]===18||t[1]===19||t[1]===51)||t[0]===203&&t[1]===0&&t[2]===113)}if(ue.isIPv6(e)){let t=Ne(e);if(!t)return!1;let r=Ne("::ffff:0:0");return Ke(t,r,96)?Ge([...t.slice(12)].join(".")):Ke(t,Ne("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([a,s])=>Ke(t,Ne(a),s)):!1}return!1}function Yr(e){let t;try{t=new URL(String(e))}catch{return{ok:!1,error:`not a valid URL: ${String(e).slice(0,120)}`}}if(t.protocol!=="http:"&&t.protocol!=="https:")return{ok:!1,error:`refused protocol ${t.protocol} (only http/https)`};let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(Qr.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=ue.isIP(r);return n!==0&&!Ge(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function We(e,{lookupFn:t=Wr.promises.lookup}={}){let r=Yr(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:ue.isIPv6(r.host)?6:4}]};let n;if(process.env.ORACLE_HOSTED_EGRESS_PROXY)return{ok:!0,url:r.url,addresses:[]};try{n=await t(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(a=>!Ge(a.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}function Xr(e=process.env){let t=e.ORACLE_HOSTED_EGRESS_PROXY||"";if(!t)return null;let r;try{r=new URL(t)}catch{throw new Error("egress-guard: ORACLE_HOSTED_EGRESS_PROXY is not a URL")}if(r.protocol!=="http:"||!["127.0.0.1","::1","localhost","[::1]"].includes(r.hostname)||!r.port||r.username||r.password)throw new Error("egress-guard: egress proxy must be an exact loopback http origin");let n=e.ORACLE_HOSTED_EGRESS_TOKEN||"";if(!/^[A-Za-z0-9_-]{43}$/.test(n))throw new Error("egress-guard: egress proxy token is missing");return{uri:r.origin,token:n}}async function Qe({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n,a;try{a=await t(),r=a.Agent,n=a.fetch}catch(p){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${p?.message||p}`);return null}if(typeof r!="function"||typeof n!="function"){if(e)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let s=p=>String(p).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),o=new Map,u=p=>(Array.isArray(p)?p:[p]).map(m=>typeof m=="string"?{address:m}:m).filter(m=>m&&m.address).map(m=>({address:m.address,family:m.family||(ue.isIPv6(m.address)?6:4)})),l=(p,m,w)=>{o.set(s(p),u(typeof m=="string"?[{address:m,family:w}]:m))},i=p=>{let m=s(p);if(ue.isIP(m))return[{address:m,family:ue.isIPv6(m)?6:4}];let w=o.get(m);if(!w||!w.length)throw new Error(`refused: unpinned host ${p} during pinned fetch`);return w},c=Xr(),d=c&&typeof a.ProxyAgent=="function"?new a.ProxyAgent({uri:c.uri,token:`Bearer ${c.token}`,connectTimeout:1e4}):new r({connect:{lookup(p,m,w){let b;try{b=i(p)}catch(A){return w(A)}return m?.all?w(null,b):w(null,b[0].address,b[0].family)}}}),h=Jr((p,m={})=>n(p,{...m,dispatcher:d}),l);return{dispatcher:d,fetch:h,pin:l,resolve:i,async close(){try{await d.destroy()}catch{}}}}function Jr(e,t){if(typeof e!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof t!="function")throw new Error("markPinCapableFetch: pin must be a function");return e[Ye]=Object.freeze({pin:t}),e}function Xe(e){return typeof e=="function"&&typeof e[Ye]?.pin=="function"}function Tt(e,t,r){if(!Xe(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[Ye].pin(t,r)}var Qr,Ye,Nt=V(()=>{Qr=new Set(["localhost","metadata.google.internal","metadata.goog"]);Ye=Symbol.for("oracle.egressGuard.pinCapableFetch")});import{createHash as Zr}from"node:crypto";import{types as te}from"node:util";function L(e){return oe(`HTTP JSON body refused: ${e}`)}function un(e){return["isArgumentsObject","isArrayBuffer","isAnyArrayBuffer","isArrayBufferView","isBoxedPrimitive","isDataView","isDate","isExternal","isGeneratorObject","isKeyObject","isCryptoKey","isMap","isMapIterator","isModuleNamespaceObject","isNativeError","isPromise","isRegExp","isSet","isSetIterator","isTypedArray","isWeakMap","isWeakSet"].some(t=>typeof te[t]=="function"&&te[t](e))}function ln(e){let t=[],r=0,n=0,a=0,s=0,o=new WeakSet,u=c=>{if(r+=Buffer.byteLength(c,"utf8"),r>ee.bytes)throw L("serialized byte limit exceeded");t.push(c)},l=c=>{if(Buffer.byteLength(c,"utf8")>ee.bytes)throw L("serialized byte limit exceeded");return JSON.stringify(c)},i=(c,d)=>{if(n+=1,n>ee.nodes)throw L("node limit exceeded");if(d>ee.depth)throw L("depth limit exceeded");if(c===null){u("null");return}if(typeof c=="string"){u(l(c));return}if(typeof c=="boolean"){u(c?"true":"false");return}if(typeof c=="number"){if(!Number.isFinite(c))throw L("non-finite number");u(Object.is(c,-0)?"0":String(c));return}if(typeof c!="object")throw L("unsupported non-JSON value");if(te.isProxy(c))throw L("proxy value");if(un(c))throw L("unsupported exotic object");if(o.has(c))throw L("cyclic value");o.add(c);try{if(Object.getOwnPropertySymbols(c).length>0)throw L("symbol-keyed fields are unsupported");if(Array.isArray(c)){let m=Object.getPrototypeOf(c),w=0;for(;m!==null;){if(te.isProxy(m))throw L("proxy array prototype");if(w+=1,w>ee.depth)throw L("array prototype depth limit exceeded");m=Object.getPrototypeOf(m)}if(c.length>ee.arrayLength)throw L("array length limit exceeded");for(let A=0;A<c.length;A+=1){let g=Object.getOwnPropertyDescriptor(c,String(A));if(!g||!Object.hasOwn(g,"value")||g.enumerable!==!0)throw L("array entries must be dense enumerable own data")}let b=0;for(let A in c){if(s+=1,s>ee.fields)throw L("enumeration limit exceeded");if(Object.hasOwn(c,A)&&(b+=1,b>c.length))throw L("named array fields are unsupported")}if(b!==c.length)throw L("array entries must be dense enumerable own data");u("[");for(let A=0;A<c.length;A+=1)A&&u(","),i(Object.getOwnPropertyDescriptor(c,String(A)).value,d+1);u("]");return}let h=Object.getPrototypeOf(c);if(h!==Object.prototype&&h!==null)throw L("non-plain object");let p=[];for(let m in c){if(s+=1,s>ee.fields)throw L("enumeration limit exceeded");if(!Object.hasOwn(c,m))continue;if(a+=1,a>ee.fields)throw L("field limit exceeded");let w=Object.getOwnPropertyDescriptor(c,m);if(!w||!Object.hasOwn(w,"value")||w.enumerable!==!0)throw L("object fields must be enumerable own data");p.push([m,w.value])}u("{");for(let m=0;m<p.length;m+=1)m&&u(","),u(l(p[m][0])),u(":"),i(p[m][1],d+1);u("}")}finally{o.delete(c)}};return i(e,0),t.join("")}function dn(e){let t=Object.create(null);if(e==null)return t;if(typeof e!="object"&&typeof e!="function")throw new TypeError("HTTP headers must be an object");if(te.isProxy(e))throw new TypeError("HTTP headers must not be a proxy");if(Object.getOwnPropertySymbols(e).length>0)throw new TypeError("HTTP headers must not contain symbol fields");let r=new Set;for(let n of Object.keys(e)){if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(n))throw new TypeError("HTTP header names must be valid tokens");let a=n.toLowerCase();if(r.has(a))throw new TypeError("HTTP headers contain a duplicate canonical name");r.add(a);let s=Object.getOwnPropertyDescriptor(e,n);if(!s||!Object.hasOwn(s,"value"))throw new TypeError("HTTP headers must contain own data properties");let o=s.value;if(o==null||["object","function","symbol"].includes(typeof o))throw new TypeError("HTTP header values must be scalar");t[n]=String(o)}return t}function pn(){return Object.assign(Object.create(null),{Accept:"application/json"})}function fn(e,t){if(!e)throw new Error(`HTTP redirect from ${t} missing Location`);let r=new URL(String(e),String(t));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${t} used unsupported protocol ${r.protocol}`);return r.toString()}function mn(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function Re(e){if((typeof e!="object"||e===null)&&typeof e!="function")return`${typeof e}:${String(e)}`;let t=Pt.get(e);return t||(t=Lt,Lt+=1,Pt.set(e,t)),`reference:${t}`}function $t(e){if(!e||typeof e!="object"||Array.isArray(e)||!Object.hasOwn(e,"jsonrpc")||!Object.hasOwn(e,"method")||e.jsonrpc!=="2.0")return!1;let t=typeof e.method=="string"?e.method:"";return t?hn.has(t)||/^get[A-Z0-9_]/u.test(t)||/^is[A-Z0-9_]/u.test(t)||/^eth_get[A-Z0-9_]/u.test(t):!1}function Dt(e,t){if(e==="GET"&&t==null)return!0;if(e!=="POST"||t==null)return!1;let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch{return!1}if(Array.isArray(r))return r.length>0&&r.every($t);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return $t(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&gn.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function bn(e,t,r,n={},a=null){let s=Zr("sha256"),o=(l,i)=>{let c=String(i);s.update(String(Buffer.byteLength(l,"utf8"))).update(":").update(l),s.update("=").update(String(Buffer.byteLength(c,"utf8"))).update(":").update(c).update(`
2
- `)};o("method",e),o("url",t),Object.keys(r||{}).map((l,i)=>({name:l.toLowerCase(),order:i,value:String(r[l])})).sort((l,i)=>l.name.localeCompare(i.name)||l.order-i.order).forEach((l,i)=>{o(`header-name-${i}`,l.name),o(`header-value-${i}`,l.value)}),o("body",a??"-");for(let l of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])o(`context-${l}`,n[l]??"-");return s.digest("hex")}function wn(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Bt):Math.min(250*2**e,Bt)+Math.floor(Math.random()*100)}function oe(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function Ze(e,t,r){return oe(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function le(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function Sn(e){return e?e.byteLength??e.length??0:0}async function En(e,t,{url:r,truncate:n=!1,onOversize:a}={}){if(t==null)return await e.text();let s=Number(e.headers?.get?.("content-length"));if(Number.isFinite(s)&&s>t&&(le(e),!n))throw Ze(r,`content-length ${s}`,t);let o=e.body?.getReader?.();if(!o){let d=await e.text(),h=Buffer.byteLength(d,"utf8");if(h>t){if(!n)throw Ze(r,`body ${h} bytes`,t);return Buffer.from(d,"utf8").subarray(0,t).toString("utf8")}return d}let u=[],l=0,i=!1;try{for(;;){let{value:d,done:h}=await o.read();if(h)break;if(d&&(u.push(Buffer.from(d)),l+=Sn(d),l>t)){i=!0;break}}}finally{if(i)try{await o.cancel()}catch{}try{o.releaseLock?.()}catch{}}if(i&&(typeof a=="function"&&a(),!n))throw Ze(r,`streamed ${l} bytes`,t);let c=Buffer.concat(u);return(i?c.subarray(0,t):c).toString("utf8")}function An(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function xn(e,{fetchImpl:t,method:r,headers:n,body:a,timeoutMs:s,lookupFn:o,realFetch:u,untrustedUrl:l=!1,maxResponseBytes:i=null,sameOriginRedirectsOnly:c=!1,importUndici:d,validateResponse:h,signal:p,redirectPolicy:m="follow",maxRedirects:w=Be}){let b=null,A=t,g=o?{lookupFn:o}:{};if(l&&!u&&!Xe(A))throw oe(`HTTP refused ${e}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let C=new AbortController,U=setTimeout(()=>C.abort(),s),I=p?Ut?Ut([p,C.signal]):p:C.signal,P=async(x,{status:_=null}={})=>{let y=await We(x,g);if(!y.ok)throw oe(_==null?`HTTP refused ${x}: ${y.error}`:`HTTP redirect to ${x} ${y.error}`,_==null?{}:{status:_});let k=new URL(x).hostname;if(u){if(b&&(await b.close(),b=null),!b)try{b=await Qe({requireUndici:!0,...d?{importUndici:d}:{}})}catch(E){throw oe(_==null?`HTTP refused ${x}: ${E?.message||E}`:`HTTP redirect to ${x} refused: ${E?.message||E}`,_==null?{}:{status:_})}b.pin(k,y.addresses),A=b.fetch}else Tt(A,k,y.addresses);return y};try{let x=String(e),_=Object.assign(Object.create(null),n||{});l&&await P(x);for(let y=0;y<=w;y+=1){let k=Object.assign(Object.create(null),{method:r,headers:_,body:a,signal:I,redirect:"manual",dispatcher:void 0}),E=await A(x,k);if((m==="error"||w===0)&&E.status>=300&&E.status<400)throw le(E),oe(`HTTP ${E.status} ${r} redirect refused`,{status:E.status,redirectRefused:!0});if(cn.has(E.status)){let B=c===!0&&r==="POST"&&[307,308].includes(E.status)&&Dt(r,a);if(r!=="GET"&&r!=="HEAD"&&!B){le(E);let O=new Error(`HTTP ${E.status} ${r} ${x} redirected non-idempotent request`);throw O.status=E.status,O}if(y===w)throw le(E),oe(`HTTP ${E.status} ${r} redirect budget exhausted`,{status:E.status,redirectRefused:!0});let q=E.headers?.get?.("location"),F;try{F=fn(q,x)}catch(O){throw le(E),O}let D=!mn(F,x);if(le(E),D&&r==="POST"){let O=new Error(`HTTP ${E.status} ${r} cross-origin redirect refused`);throw O.status=E.status,O}if(D&&c){let O=new Error(`HTTP ${E.status} ${r} cross-origin redirect refused`);throw O.status=E.status,O.retryable=!1,O}if(D&&(_=pn(_)),l)await P(F,{status:E.status});else if(D){let O=await We(F,g);if(!O.ok){let T=new Error(`HTTP redirect from ${x} ${O.error}`);throw T.status=E.status,T.retryable=!1,T}u&&O.addresses?.length&&(b||(b=await Qe(d?{importUndici:d}:{})),b&&(b.pin(new URL(F).hostname,O.addresses),A=b.fetch))}x=F;continue}if(typeof h=="function")try{await h(E,{url:x})}catch(B){throw le(E),oe(B?.message||String(B))}let R=await En(E,i,{url:x,onOversize:()=>C.abort()}),S=An(R);if(!E.ok){let B=new Error(`HTTP ${E.status} ${r} ${x}`);throw B.status=E.status,B.retryAfter=E.headers?.get?.("retry-after")??null,B.body=S??R.slice(0,300),B}return S??R}throw new Error(`HTTP redirect loop for ${e}`)}catch(x){if(C.signal.aborted&&!ye(p)){let _=x&&(typeof x=="object"||typeof x=="function")&&!te.isProxy(x)?x:null,y=_?Object.getOwnPropertyDescriptor(_,"oversize"):null;if(!(y&&Object.hasOwn(y,"value")&&y.value===!0))try{if(!_)throw new TypeError("unsafe rejection");Object.defineProperties(_,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let E=new Error("HTTP request timed out");throw Object.defineProperties(E,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),E}}throw x}finally{clearTimeout(U),b&&await b.close()}}async function v(e,t={}){if(t!=null&&typeof t!="object"&&typeof t!="function")throw new TypeError("HTTP options must be an object");if(t!=null&&te.isProxy(t))throw new TypeError("HTTP options must not be a proxy");let r=new Set(["body","dedupe","fetchImpl","headers","importUndici","lookupFn","maxRedirects","maxResponseBytes","method","redirectPolicy","retries","sameOriginRedirectsOnly","signal","timeoutMs","untrustedUrl","validateResponse"]);if(t!=null){if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("HTTP options contain unknown fields");for(let T of Object.getOwnPropertyNames(t)){let N=Object.getOwnPropertyDescriptor(t,T);if(!(T==="toJSON"&&N&&Object.hasOwn(N,"value")&&N.value===void 0)){if(!r.has(T))throw new TypeError("HTTP options contain unknown fields");if(!N||!N.enumerable||!Object.hasOwn(N,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=T=>{if(t==null||!Object.hasOwn(t,T))return;let N=Object.getOwnPropertyDescriptor(t,T);if(!N||!Object.hasOwn(N,"value"))throw new TypeError("HTTP options must contain own data properties");return N.value};if(typeof e!="string"||e.length===0||e.length>8192)throw new TypeError("HTTP URL must be a bounded string");let a=n("method");if(a!==void 0&&(typeof a!="string"||!/^[A-Za-z]+$/u.test(a)))throw new TypeError("HTTP method must be a string token");let s=n("timeoutMs");if(s!==void 0&&(!Number.isInteger(s)||s<1||s>12e4))throw new TypeError("HTTP timeoutMs must be a bounded integer");let o=n("retries");if(o!==void 0&&(!Number.isInteger(o)||o<0||o>10))throw new TypeError("HTTP retries must be a bounded integer");let u=n("redirectPolicy");if(u!==void 0&&u!=="follow"&&u!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let l=n("maxRedirects");if(l!==void 0&&(!Number.isInteger(l)||l<0||l>Be))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${Be}`);if(u==="error"&&l!==void 0&&l!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let i=u??"follow",c=i==="error"?0:l??Be;for(let T of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let N=n(T);if(N!==void 0&&typeof N!="boolean")throw new TypeError(`HTTP ${T} must be boolean`)}let d=n("maxResponseBytes");if(d!==void 0&&(!Number.isInteger(d)||d<1||d>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let h=n("signal");if(h!==void 0){if(te.isProxy(h)||!(h instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{ye(h)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let T of["importUndici","lookupFn","validateResponse"]){let N=n(T);if(N!==void 0&&typeof N!="function")throw new TypeError(`HTTP ${T} must be a function`)}let p=n("fetchImpl"),m=p||globalThis.fetch;if(typeof m!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let w=s??12e3,b=(a||"GET").toUpperCase(),A=n("headers"),g=dn(A),C=Object.assign(Object.create(null),g);Object.keys(C).some(T=>T.toLowerCase()==="accept")||(C.Accept="application/json");let U=n("body");U!=null&&typeof U!="string"&&(Object.keys(C).find(N=>N.toLowerCase()==="content-type")||(C["Content-Type"]="application/json"),U=ln(U));let I=o??tn,P=n("lookupFn"),x=!p,_=n("untrustedUrl")===!0,y=n("sameOriginRedirectsOnly")===!0,k=n("importUndici"),E=n("validateResponse"),R=h,S=d??null,B=async()=>{let T;for(let N=0;N<=I;N++){R&&on.call(R);let j=Te("http");try{let z=await xn(e,{fetchImpl:m,method:b,headers:C,body:U,timeoutMs:w,lookupFn:P,realFetch:x,untrustedUrl:_,maxResponseBytes:S,sameOriginRedirectsOnly:y,importUndici:k,validateResponse:E,signal:R,redirectPolicy:i,maxRedirects:c});return j?.("succeeded"),z}catch(z){T=z;let J=de=>{if(!z||typeof z!="object"&&typeof z!="function"||te.isProxy(z))return;let ne=Object.getOwnPropertyDescriptor(z,de);return ne&&Object.hasOwn(ne,"value")?ne.value:void 0},ce=J("status");j?.("failed",ce);let Ie=J("oracleTimeout")===!0||J("name")==="AbortError"||J("name")==="TimeoutError"||ye(R),ke=new Set([408,425,429]),f=J("retryable")===!1?!1:ce!=null?ke.has(ce)||en.has(ce)&&Rt.has(b):!Ie&&Rt.has(b);if(N===I||!f)throw z;let M=wn(N,J("retryAfter")),W=Te("retry"),K=!1;try{R?await new Promise((de,ne)=>{let Oe,we=()=>{clearTimeout(Oe),_t.call(R,"abort",we),ne(sn(R)||new DOMException("Aborted","AbortError"))};if(ye(R)){we();return}Oe=setTimeout(()=>{_t.call(R,"abort",we),de()},M),an.call(R,"abort",we,{once:!0}),ye(R)&&we()}):await yn(M),K=!0}finally{W?.(K?"succeeded":"failed")}}}throw T};if(!(n("dedupe")!==!1&&!R&&Dt(b,U)))return B();let F=bn(b,e,C,{untrustedUrl:_,maxResponseBytes:S,sameOriginRedirectsOnly:y,redirectPolicy:i,maxRedirects:c,timeoutMs:w,retries:I,fetchImpl:Re(m),realFetch:x,lookupFn:Re(P),importUndici:Re(k),validateResponse:Re(E)},U),D=Je.get(F);if(D){let T=Te("shared");try{let N=await D;return T?.("succeeded"),N}catch(N){throw T?.("failed"),N}}let O=B().finally(()=>Je.delete(F));return Je.set(F,O),O}var en,Rt,tn,Bt,rn,nn,on,an,_t,Ut,ye,sn,cn,Be,Oa,ee,Je,Pt,Lt,hn,gn,yn,$=V(()=>{Ot();Nt();en=new Set([408,425,429,500,502,503,504]),Rt=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),tn=2,Bt=4e3,rn=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,nn=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,on=AbortSignal.prototype.throwIfAborted,an=EventTarget.prototype.addEventListener,_t=EventTarget.prototype.removeEventListener,Ut=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,ye=e=>e?rn.call(e):!1,sn=e=>e?nn.call(e):void 0,cn=new Set([301,302,303,307,308]),Be=3,Oa=64*1024,ee=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});Je=new Map,Pt=new WeakMap,Lt=1;hn=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),gn=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);yn=e=>new Promise(t=>setTimeout(t,e))});import{readFileSync as vn}from"node:fs";import{homedir as Cn}from"node:os";import{join as _e}from"node:path";function In(){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){let r=(process.env.ORACLE_EXEC_ENV_FILE||"").trim();return r?[r]:[]}let e=(process.env.ORACLE_EXEC_ENV_FILE||process.env.MAD_EXEC_ENV_FILE||"").trim(),t=Cn();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||_e(t,".config","oracle")).trim();return[e,_e(r,"exec.env")].filter(Boolean)}return[e,_e(t,".config","oracle","exec.env"),_e(t,".config","mad-desk","exec.env")].filter(Boolean)}function Ft(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let a of In())try{let s=vn(a,"utf8"),o=s.match(new RegExp(`^${t}=(.*)$`,"m"))||s.match(new RegExp(`^${r}=(.*)$`,"m"));if(o&&(n=o[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}var qt=V(()=>{});var Mt=V(()=>{});import{createHash as kn,createHmac as jt,timingSafeEqual as On}from"node:crypto";function Pe(e){return Array.isArray(e)?`[${e.map(Pe).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Pe(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Vt(e,{required:t=!1}={}){try{return Ft(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function tt(e){let{signature:t,...r}=e;return r}function zt(e,{secret:t}={}){let r=Vt(t);return r?{...e,signature:jt("sha256",r).update(Pe(tt(e))).digest("hex")}:e}function Tn(e){let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(t)||t.length<10||t.length%2!==0)throw new Error("auto-slippage calldata must be even-length hex with a selector");return kn("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function ae(e,{chainId:t,venue:r,data:n,secret:a}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");if(Number(e.chainId)!==Number(t))throw new Error("auto-slippage guard chain mismatch");if(String(e.venue).toLowerCase()!==String(r||"").toLowerCase())throw new Error("auto-slippage guard venue mismatch");let s=Vt(a);if(s){let p=jt("sha256",s).update(Pe(tt(e))).digest("hex");if(!Nn(e.signature,p))throw new Error("auto-slippage guard signature mismatch \u2014 refusing to bind a guard this Oracle did not issue")}let o=Number(e.selectedBps),u=Number(e.capBps);if(!Number.isInteger(o)||o<0||o>Ue||!Number.isInteger(u)||u<0||u>Ue||o>u)throw new Error("auto-slippage guard bounds are invalid");let l=BigInt(e.quoteAmountOut??0),i=BigInt(e.minAmountOut??0);if(l<=0n||i<=0n)throw new Error("auto-slippage guard amounts must be positive");let c=l*BigInt(1e4-o),d=c/10000n;if(c%10000n!==0n&&(d+=1n),i<d)throw new Error("auto-slippage guard is under-protected relative to its quote");let h=_n(n);if(h!=null&&h!==i)throw new Error(`auto-slippage: calldata encodes floor ${h}, not the guard floor ${i} \u2014 refusing to bind`);return zt({...tt(e),calldataHash:Tn(n)},{secret:a})}function Nn(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:On(r,n)}function et(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function Rn(e){let t=e==null?Ue:Number(e);if(!Number.isInteger(t)||t<0)throw new Error("auto-slippage cap must be a non-negative integer bps value");return Math.min(t,Ue)}function se({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:a}={}){let s=et(e,0),o=s>0?s>=25e4?5:s>=1e5?10:s>=5e4?20:s>=1e4?40:70:n?30:10,u=Math.min(60,Math.abs(et(t,0))*2),l=Math.min(40,Math.floor(Math.max(0,et(r,0))/5e3)*5),i=Math.max(25,Math.ceil(20+o+u+l)),c=Rn(a);return{mode:"auto",requiredBps:i,selectedBps:Math.min(i,c),capBps:c,executable:i<=c}}function Bn({chainId:e,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:a=0,quoteAgeMs:s=0,crossChain:o=!1,requestedCapBps:u,quotedAtMs:l=Date.now(),ttlMs:i=Ht,secret:c}={}){let d=BigInt(r??0);if(d<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let h=se({liquidityUsd:n,priceChange5m:a,quoteAgeMs:s,crossChain:o,requestedCapBps:u});if(!h.executable)throw new Error(`auto-slippage requires ${h.requiredBps} bps above hard/requested cap ${h.capBps}; route blocked`);let p=Number(l);if(!Number.isFinite(p))throw new Error("auto-slippage: quotedAtMs must be a finite number");let m=Math.min(3e4,Math.max(1e3,Number(i)||Ht)),w=d*BigInt(1e4-h.selectedBps),b=w/10000n;if(w%10000n!==0n&&(b+=1n),b>d&&(b=d),d>0n&&b<=0n)throw new Error(`auto-slippage: quote ${d} is too small to express a ${h.selectedBps} bps floor without rounding to zero`);let A=Number((d-b)*10000n/(d===0n?1n:d));if(A>h.capBps)throw new Error(`auto-slippage: realised floor implies ${A} bps, above cap ${h.capBps} \u2014 refusing to issue a guard weaker than advertised`);return zt({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:d.toString(),minAmountOut:b.toString(),requiredBps:h.requiredBps,selectedBps:h.selectedBps,capBps:h.capBps,quotedAtMs:p,expiresAtMs:p+m},{secret:c})}function _n(e){let t=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(t)||t.length<10||t.length%2!==0)return null;let r=t.slice(0,10).toLowerCase(),n=[];for(let s=10;s+64<=t.length;s+=64)n.push(t.slice(s,s+64));let a=s=>n[s]==null?null:BigInt("0x"+n[s]);switch(r){case"0x414bf389":return a(6);case"0x04e45aaf":return a(5);case"0xc04b8d59":{let s=a(0);if(s==null)return null;let o=Number(s)/32;return!Number.isInteger(o)||o<0?null:a(o+4)}case"0xb858183f":{let s=a(0);if(s==null)return null;let o=Number(s)/32;return!Number.isInteger(o)||o<0?null:a(o+3)}case"0xa026383e":return a(6);case"0x38ed1739":case"0x5c11d795":return a(1);case"0x7ff36ab5":case"0xb6f9de95":return a(0);case"0x18cbafe5":case"0x791ac947":return a(1);default:return null}}function Q(e,{chainId:t,venue:r,amountOut:n,liquidityUsd:a,priceChange5m:s,crossChain:o,requestedCapBps:u,quotedAtMs:l=Date.now(),ttlMs:i}={}){let c=Bn({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:a,priceChange5m:s,crossChain:o,requestedCapBps:u,quotedAtMs:l,ttlMs:i});return{...e,autoSlippage:c,amountOutMinimum:c.minAmountOut}}var Ue,Ht,re=V(()=>{qt();Mt();Ue=100,Ht=2e4});var pe,Le=V(()=>{pe="0x000000000000000000000000000000000000dEaD"});import{createHash as Un,createHmac as Pn,timingSafeEqual as Ha}from"node:crypto";function rt(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(rt).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${rt(e[r])}`).join(",")}}`}function Kt(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Gt(e=process.env){return Kt(process.env)||Kt(e)}function Fn(e){let{prepareHash:t,prepareMac:r,note:n,...a}=e||{};return a}function qn(e){let t=Fn(e);return Un("sha256").update(rt(t)).digest("hex")}function Mn(e,t=Gt()){return t?Pn("sha256",t).update(String(e)).digest("hex"):""}function H(e,{provider:t,kind:r,env:n=process.env,nowMs:a=Date.now(),expiresAtMs:s}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let o=Object.prototype.hasOwnProperty.call(e,"oraclePrepared");if(o&&typeof e.oraclePrepared!="boolean")throw new Error("stampPrepared: oraclePrepared must be boolean");let u={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1,oraclePrepared:o?e.oraclePrepared:!0};if(!u.provider)throw new Error("stampPrepared: provider required");if(!u.kind)throw new Error("stampPrepared: kind required");let l=Number(a),i=s==null?l+$n:Number(s),c=i-l;if(!Number.isSafeInteger(l)||!Number.isSafeInteger(i)||c<=0||c>Dn)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let h={...u,preparedAt:l,expiresAt:i,prepareVersion:Ln},p=qn(h),m=Gt(n),w=m?Mn(p,m):void 0,b={...h,prepareHash:p};return w&&(b.prepareMac=w),b}var Ln,$n,Dn,Y=V(()=>{Ln=2,$n=300*1e3,Dn=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Contract as Hn,JsonRpcProvider as jn}from"ethers";function Qn(e){return Wn.test(String(e||""))}async function Wt(e,{contract:t=Vn,rpc:r=Kn,chainId:n=zn,balanceOf:a}={}){if(!Qn(e))throw new Error("invalid-address");if(a)return BigInt(await a(e));let s=new jn(r,n,{staticNetwork:!0}),o=new Hn(t,Gn,s);return BigInt(await o.balanceOf(e))}var Vn,zn,Kn,Gn,Wn,Qt=V(()=>{Vn="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",zn=999,Kn="https://rpc.hyperliquid.xyz/evm",Gn=["function balanceOf(address owner) view returns (uint256)"],Wn=/^0x[a-fA-F0-9]{40}$/});import{existsSync as Yn,readFileSync as Xn,lstatSync as Jn}from"node:fs";import{homedir as Yt}from"node:os";import{join as nt}from"node:path";function to(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(Xt,t)?Xt[t]:eo}function so(e=process.env){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){if(e[Jt])return String(e[Jt]);let t=e.ORACLE_CONFIG_DIR||nt(Yt(),".config","oracle");return nt(t,"fee-recipient")}return nt(Yt(),".config","oracle","fee-recipient")}function io(e=process.env){try{let t=so(e);if(!Yn(t)||Jn(t).isSymbolicLink())return"";let r=Xn(t,"utf8").trim().toLowerCase();return/^0x[a-f0-9]{40}$/.test(r)?r:""}catch{return""}}function co(e,{fallback:t=0}={}){if(e==null)return t;if(String(e).trim()==="")return 0;let r=Number(e);return!Number.isFinite(r)||r<=0?0:Math.min(Math.floor(r),Zn)}function uo({env:e=process.env,action:t="swap",admin:r=!1}={}){let n=String(e[no]||"").trim(),a=String(e[oo]||ao).trim();if(r===!0)return{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"admin-oracle"};let s=to(t),o=co(e[ro],{fallback:n?s:0}),u=Math.min(o,s);if(!u)return{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"not-configured"};if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"no-recipient"};let l=io(e);return!l||l!==n.toLowerCase()?{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"recipient-not-pinned"}:{bps:u,recipient:n,integrator:a,action:t,applies:!0,reason:"configured"}}async function ot({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={},admin:a=!1}={}){let s=uo({env:t,action:r,admin:a});if(a===!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 Wt(o,n))>0n?{...s,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...s,holderVerificationStatus:"non-holder"}}catch{return{...s,holderVerificationStatus:"unavailable"}}}function Zt(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 er(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}var Zn,eo,Xt,ro,no,oo,Jt,ao,$e=V(()=>{Qt();Zn=100,eo=5,Xt=Object.freeze({swap:5,bridge:5,perps:0,nft:0});ro="ORACLE_INTEGRATOR_FEE_BPS",no="ORACLE_INTEGRATOR_FEE_RECIPIENT",oo="ORACLE_INTEGRATOR_ID",Jt="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",ao="oracle"});var rr={};je(rr,{LIFI_API:()=>tr,lifiChains:()=>mo,lifiHealth:()=>it,lifiPrepare:()=>fo,lifiQuote:()=>me});function st(e={}){return(e.baseUrl||process.env.LIFI_API_URL||tr).replace(/\/$/,"")}function po(e){let t=String(e||at).toLowerCase();return t===at.toLowerCase()||t===lo}function fe(e,t){let r=String(e||"").trim();if(!/^0x[0-9a-fA-F]{40}$/.test(r))throw new Error(`lifi: ${t} must be a 20-byte address`);return r.toLowerCase()}async function it(e={}){let t=await v(`${st(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3}),r=Array.isArray(t)?t.length:t?.chains?.length||0;return{ok:r>0,chainCount:r}}async function me(e={},t={}){let{fromChain:r,toChain:n=r,fromToken:a=at,toToken:s,fromAmount:o,fromAddress:u=pe}=e;if(r==null||!s||!o)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let l=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:a,toToken:s,fromAmount:String(o),fromAddress:u}),i=se({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!i.executable)throw new Error(`lifi: route requires ${i.requiredBps} bps above cap ${i.capBps}`);l.set("slippage",String(i.selectedBps/1e4));let c=await ot({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[b,A]of Object.entries(er(c)))l.set(b,A);let d=await v(`${st(t)}/quote?${l}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),h=d?.estimate?.toAmount||d?.toAmount;if(!h)return{...d,autoSlippagePolicy:i,oracleFee:c};let p=d?.transactionRequest?.to||d?.estimate?.approvalAddress||"lifi",m=Q(d,{chainId:Number(r),venue:p,amountOut:h,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),w=d?.estimate?.toAmountMin||d?.toAmountMin;if(w!=null&&BigInt(w)<BigInt(m.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...m,oracleFee:c}}async function fo(e={},t={}){let r=await me(e,t),n=r?.transactionRequest;if(!n?.to||!n?.data)throw new Error("lifi: quote did not return an executable transactionRequest");if(["nonce","authorizationList","maxFeePerBlobGas","blobVersionedHashes","blobs","kzg","signature","rawTransaction","signedTransaction","r","s","v"].find(d=>n[d]!=null))throw new Error("lifi: unsupported transaction authority");if(n.type!=null){let d=String(n.type).trim().toLowerCase();if(!/^(?:0x[0-9a-f]+|\d+)$/.test(d)||BigInt(d)>2n)throw new Error("lifi: unsupported transaction authority")}let s=Number(e.fromChain);if(n.chainId==null)throw new Error("lifi: transaction missing chain authority");if(Number(n.chainId)!==s)throw new Error("lifi: transaction chain mismatch");let o=e.fromAddress?fe(e.fromAddress,"transaction sender"):n.from?fe(n.from,"transaction sender"):null;if(!o)throw new Error("lifi: transaction missing sender authority");if(n.from&&fe(n.from,"transaction sender")!==o)throw new Error("lifi: transaction sender mismatch");let u=fe(n.to,"transaction target"),l=String(n.data);if(!/^0x(?:[0-9a-fA-F]{2})+$/.test(l))throw new Error("lifi: transaction calldata must be non-empty hex bytes");let i=String(n.value??"0x0");if(!/^(?:0x[0-9a-fA-F]+|\d+)$/.test(i))throw new Error("lifi: transaction value must be an unsigned integer string");let c=null;if(!po(e.fromToken)){let d=r?.estimate?.approvalAddress||r?.approvalAddress;if(!d)throw new Error("lifi: ERC20 route missing approvalAddress");let h=r?.action?.fromToken?.address||r?.estimate?.fromToken?.address||e.fromToken;c={token:fe(h,"approval token"),spender:fe(d,"approval spender"),amount:String(e.fromAmount)}}return H({provider:"lifi",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:s,quote:r,autoSlippage:r.autoSlippage,requiresApproval:c,transaction:{chainId:s,from:o,to:u,data:l,value:i,...n.gasLimit!=null?{gasLimit:n.gasLimit}:{},slippageGuard:ae(r.autoSlippage,{chainId:s,venue:u,data:l})}},{provider:"lifi",kind:"lifi-tx",env:t.env,nowMs:t.nowMs,expiresAtMs:t.expiresAtMs})}async function mo(e={}){return v(`${st(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var tr,at,lo,De=V(()=>{$();re();Le();Y();$e();tr="https://li.quest/v1";at="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",lo="0x0000000000000000000000000000000000000000"});var He={};je(He,{ACROSS_API:()=>sr,HOP_API:()=>ir,RANGO_API:()=>ur,RELAY_API:()=>cr,acrossHealth:()=>dt,acrossSuggestedFees:()=>qe,hopHealth:()=>pt,hopQuote:()=>Me,rangoQuote:()=>ht,relayHealth:()=>mt,relayPrepare:()=>To,relayQuote:()=>Ae});async function dt(e={}){try{return{ok:!0,estimatedFillTimeSec:(await qe({token:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",destinationToken:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",originChainId:1,destinationChainId:42161,amount:"1000000000000000"},e)).estimatedFillTimeSec}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function qe(e={},t={}){let{token:r,destinationToken:n=r,originChainId:a,destinationChainId:s,amount:o}=e;if(!r||a==null||s==null||!o)throw new Error("acrossSuggestedFees requires token, originChainId, destinationChainId, amount");let u=new URLSearchParams({token:r,destinationToken:n,originChainId:String(a),destinationChainId:String(s),amount:String(o)}),l=(t.baseUrl||process.env.ACROSS_API_URL||sr).replace(/\/$/,"");return v(`${l}/suggested-fees?${u}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function pt(e={}){try{let t=await Me({amount:"1000000000000000",token:"ETH",fromChain:"ethereum",toChain:"arbitrum",slippage:.5},e);return{ok:!0,estimatedRecieved:t.estimatedRecieved||t.estimatedReceived}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function Me(e={},t={}){let{amount:r,token:n="ETH",fromChain:a="ethereum",toChain:s="arbitrum"}=e;if(!r)throw new Error("hopQuote requires amount");let o=e.slippage==null?void 0:Math.round(Number(e.slippage)*100),u=se({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:a!==s,requestedCapBps:e.maxSlippageBps??e.slippageBps??o});if(!u.executable)throw new Error(`hop: route requires ${u.requiredBps} bps above cap ${u.capBps}`);let l=new URLSearchParams({amount:String(r),token:n,fromChain:a,toChain:s,slippage:String(u.selectedBps/100)}),i=(t.baseUrl||process.env.HOP_API_URL||ir).replace(/\/$/,""),c=await v(`${i}/quote?${l}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),d=c?.estimatedRecieved||c?.estimatedReceived;return d?Q(c,{chainId:Number(e.originChainId||e.chainId||Co[a]||0),venue:c?.tx?.to||"hop",amountOut:d,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:a!==s,requestedCapBps:e.maxSlippageBps??e.slippageBps??o}):{...c,autoSlippagePolicy:u}}function lr(e){return(e?.steps||[]).flatMap(t=>(t?.items||[]).filter(r=>r?.data?.to&&r?.data?.data).map(r=>({stepId:t.id,...r.data})))}function ko(e){let t=String(e?.data??"").toLowerCase();if(!t.startsWith(ft))return null;if(!/^0x[0-9a-f]{136}$/.test(t))throw new Error("relay: malformed ERC20 approval calldata");return{spender:`0x${t.slice(34,74)}`,amount:BigInt(`0x${t.slice(74,138)}`).toString()}}function Oo(e){return lr(e).find(t=>!String(t.data).toLowerCase().startsWith(ft))??null}async function mt(e={}){try{let t=await Ae({user:pe,originChainId:1,destinationChainId:8453,originCurrency:"0x0000000000000000000000000000000000000000",destinationCurrency:"0x0000000000000000000000000000000000000000",amount:"1000000000000000",tradeType:"EXACT_INPUT"},e);return{ok:!0,hasSteps:Array.isArray(t.steps),stepCount:t.steps?.length||0}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function Ae(e={},t={}){let{user:r=pe,originChainId:n,destinationChainId:a,originCurrency:s="0x0000000000000000000000000000000000000000",destinationCurrency:o="0x0000000000000000000000000000000000000000",amount:u,tradeType:l="EXACT_INPUT"}=e;if(n==null||a==null||!u)throw new Error("relayQuote requires originChainId, destinationChainId, amount");let i=se({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(a),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!i.executable)throw new Error(`relay: route requires ${i.requiredBps} bps above cap ${i.capBps}`);let c=(t.baseUrl||process.env.RELAY_API_URL||cr).replace(/\/$/,""),d=await v(`${c}/quote`,{method:"POST",body:{user:r,originChainId:Number(n),destinationChainId:Number(a),originCurrency:s,destinationCurrency:o,amount:String(u),tradeType:l,slippageTolerance:String(i.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),h=d?.details?.currencyOut?.amount;if(!h||!/^\d+$/.test(String(h)))return{...d,autoSlippagePolicy:i};let p=Oo(d);return Q(d,{chainId:Number(n),venue:p?.to||"relay",amountOut:h,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(a),requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function To(e={},t={}){let r=await Ae(e,t),n=Number(e.originChainId),a=lr(r);if(!a.length)throw new Error("relay: quote returned no executable transaction items");let s=String(r?.autoSlippage?.venue||"").toLowerCase(),o=[],u=[];for(let c of a){if(c.chainId!=null&&Number(c.chainId)!==n)throw new Error("relay: transaction chain mismatch");if(e.user&&c.from&&String(c.from).toLowerCase()!==String(e.user).toLowerCase())throw new Error("relay: transaction sender mismatch");let d=ko(c);d?o.push({tx:c,approval:d}):u.push(c)}if(!u.length)throw new Error("relay: quote returned no bridge deposit transaction");if(u.some(c=>String(c.to).toLowerCase()!==s))throw new Error("relay: route execution target is not safely bound");if(o.length>1)throw new Error("relay: multiple token approvals are not supported");let l=null;if(o.length===1){let{tx:c,approval:d}=o[0],h=String(e.originCurrency||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(h)||h===Io)throw new Error("relay: native route returned an ERC20 approval");if(String(c.to).toLowerCase()!==h)throw new Error("relay: approval token mismatch");if(d.amount!==String(e.amount))throw new Error("relay: approval amount must equal the exact input amount");if(!u.some(p=>String(p.to).toLowerCase()===d.spender))throw new Error("relay: approval spender does not match the bridge target");l={token:h,spender:d.spender,amount:String(e.amount)}}let i=a.map(c=>({chainId:n,from:c.from||e.user,to:c.to,data:c.data,value:c.value??"0x0",...c.gasLimit!=null||c.gas!=null?{gasLimit:c.gasLimit??c.gas}:{},...String(c.data).toLowerCase().startsWith(ft)?{}:{slippageGuard:ae(r.autoSlippage,{chainId:n,venue:c.to,data:c.data})}}));return H({provider:"relay",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:r,autoSlippage:r.autoSlippage,requiresApproval:l,destination:s,transactions:i},{provider:"relay",kind:"relay-tx",env:t.env,nowMs:t.nowMs,expiresAtMs:t.expiresAtMs})}async function ht({from:e,to:t,amount:r,slippage:n=1,enableCentralizedSwappers:a=!1}={},s={}){if(!e||!t||!r)throw new Error("rangoQuote requires from, to, amount");let o=s.env??process.env,u=s.rangoApiKey||o.RANGO_API_KEY;if(!u)throw new Error("rango: RANGO_API_KEY is required");let l=new URLSearchParams({from:e,to:t,amount:String(r),slippage:String(n),enableCentralizedSwappers:a?"true":"false",apiKey:u}),i=(s.rangoBaseUrl||process.env.RANGO_API_URL||ur).replace(/\/$/,""),c;try{c=await v(`${i}/basic/quote?${l}`,{fetchImpl:s.fetchImpl,timeoutMs:s.timeoutMs??2e4,retries:s.retries})}catch(d){let h=Number.isInteger(d?.status)?` (HTTP ${d.status})`:"";throw new Error(`rango: request failed${h}`)}if(c?.error||c?.resultType&&c.resultType!=="OK"){let d=String(c?.error||c.resultType).split(u).join("[redacted]").split(encodeURIComponent(u)).join("[redacted]").slice(0,160);throw new Error(`rango: ${d}`)}return{amountOut:c?.route?.outputAmount,feeUsd:c?.route?.feeUsd??null,estimatedTime:c?.route?.estimatedTimeInSeconds}}var sr,ir,cr,ur,Co,ft,Io,xe=V(()=>{$();re();Le();Y();sr="https://across.to/api",ir="https://api.hop.exchange/v1",cr="https://api.relay.link",ur="https://api.rango.exchange",Co={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453};ft="0x095ea7b3",Io="0x0000000000000000000000000000000000000000"});var yr={};je(yr,{DEBRIDGE_API:()=>br,debridgeHealth:()=>wt,debridgePrepare:()=>Mo,debridgeQuote:()=>bt});function wr(e={}){return(e.baseUrl||process.env.DEBRIDGE_API_URL||br).replace(/\/$/,"")}function gt(e,t=200){return String(e?.message||e||"unknown error").slice(0,t)}function qo(e){return typeof e?.to=="string"&&e.to.length>0&&/^0x(?:[0-9a-fA-F]{2})+$/.test(String(e.data||""))}async function bt({srcChainId:e,srcChainTokenIn:t,srcChainTokenInAmount:r,dstChainId:n,dstChainTokenOut:a,taker:s,slippage:o=100,affiliateFeePercent:u="0"}={},l={}){if(!e||!n||!t||!a||!r)return{error:"debridge quote requires srcChainId, dstChainId, srcChainTokenIn, dstChainTokenOut, srcChainTokenInAmount"};try{let i=new URLSearchParams({srcChainId:String(e),srcChainTokenIn:t,srcChainTokenInAmount:String(r),dstChainId:String(n),dstChainTokenOut:a,dstChainTokenOutAmount:"auto",slippage:String(o),affiliateFeePercent:String(u)});s&&(i.set("dstChainTokenOutRecipient",s),i.set("srcChainOrderAuthorityAddress",s),i.set("dstChainOrderAuthorityAddress",s));let c=await v(`${wr(l)}/dln/order/create-tx?${i}`,{fetchImpl:l.fetchImpl,timeoutMs:l.timeoutMs??2e4,retries:l.retries,headers:l.headers});return c?.error?{error:gt(c.error)}:{estimation:c?.estimation??{},order:c?.order??{},fixFee:c?.fixFee??c?.estimation?.fixFee??"0",tx:c?.tx??null,walletBinding:s?{dstChainTokenOutRecipient:s,srcChainOrderAuthorityAddress:s,dstChainOrderAuthorityAddress:s}:null}}catch(i){return{error:gt(i)}}}async function wt(e={}){try{let t=await v(`${wr(e)}/supported-chains-info`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??15e3,retries:e.retries}),r=Array.isArray(t)?t:t?.chains,n=Array.isArray(r)?r.length:0;return{ok:n>0,chainCount:n}}catch(t){return{ok:!1,error:gt(t,160)}}}async function Mo(e,{taker:t}={}){if(!t)throw new Error("debridge prepare requires taker address");if(!qo(e?.tx))throw new Error("debridge prepare requires paired unsigned transaction bytes");let r=e?.walletBinding,n=String(t).toLowerCase();if(!r||[r.dstChainTokenOutRecipient,r.srcChainOrderAuthorityAddress,r.dstChainOrderAuthorityAddress].some(a=>String(a||"").toLowerCase()!==n))throw new Error("debridge prepare wallet binding does not match taker");if(e.tx.from&&String(e.tx.from).toLowerCase()!==n)throw new Error("debridge prepare transaction sender does not match taker");return H({provider:"debridge",kind:"debridge-tx",calldataReady:!0,requiresUserSignature:!0,transaction:e.tx,quote:e},{provider:"debridge",kind:"debridge-tx"})}var br,yt=V(()=>{$();Y();br="https://dln.debridge.finance/v1.0"});var ma=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),Ve=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),ze=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"});var Z=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"});var vt=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}};function Ct(e){let{source:t,amountOut:r,minOut:n=null,gasUsd:a=null,feeUsd:s=null,feeIncludedInAmountOut:o=!1,oracleFeeBps:u=0,estimatedGas:l=null,liquidityUsd:i=null,error:c=null,executionReady:d=!1,meta:h={}}=e||{};if(c||r==null)return{source:t,quality:Z.FAILED,amountOut:null,error:c||"no amountOut returned"};let p=vt(r);if(p==null||p<=0n)return{source:t,quality:Z.FAILED,amountOut:null,error:"non-positive amountOut"};let m=Number(u);return{source:t,quality:a==null?Z.NO_GAS:Z.FULL,amountOut:p.toString(),minOut:vt(n)?.toString()??null,gasUsd:a,feeUsd:s,feeIncludedInAmountOut:o===!0,oracleFeeBps:Number.isFinite(m)&&m>0?Math.floor(m):0,estimatedGas:l==null?null:String(l),liquidityUsd:i==null?null:Number(i),executionReady:d,meta:h}}function It(e,{destPriceUsd:t=null,destDecimals:r=null,liquidityFirst:n=!0,liquidityBandBps:a=50,gasPriceWei:s=null,nativePriceUsd:o=null}={}){let u=e.filter(y=>y.quality!==Z.FAILED),l=e.filter(y=>y.quality===Z.FAILED),i=t!=null&&t>0&&r!=null&&r>=0,c=Number(s),d=Number(o),h=Number.isFinite(c)&&c>0&&Number.isFinite(d)&&d>0,p=u.map(y=>{let k=BigInt(y.amountOut),E=0n,R=!1,S=!1,B=BigInt(y.oracleFeeBps??0),q=B>0n?k*B/10000n:0n;if(i){let O=y.gasUsd,T=Number(y.meta?.gasUnits??y.estimatedGas);if(O==null&&h&&Number.isFinite(T)&&T>0){let j=T*c/1e18*d;Number.isFinite(j)&&j>=0&&(O=j,S=!0)}let N=(O??0)+(y.feeIncludedInAmountOut?0:y.feeUsd??0);if(N>0){let j=N/t*10**r;Number.isFinite(j)&&j>=0&&(E=BigInt(Math.floor(j)),R=!0)}else O===0&&(R=!0)}let F=E+q,D=k>F?k-F:0n;return{...y,grossOut:k.toString(),netOut:D.toString(),costInDest:E.toString(),oracleFeeInDest:q.toString(),costAccounted:R,gasEstimated:S}}),m=Number(a)>0?Number(a):0,w=p.reduce((y,k)=>BigInt(k.netOut)>y?BigInt(k.netOut):y,0n),b=y=>w>0n?Number((w-BigInt(y))*10000n/w):0,A=[],g=(y,k)=>{let E=BigInt(y.netOut),R=BigInt(k.netOut);return E!==R?R>E?1:-1:String(y.source).localeCompare(String(k.source))},C=p.slice().sort(g)[0]??null;p.sort((y,k)=>{let E=b(y.netOut)<=m?0:1,R=b(k.netOut)<=m?0:1;if(n&&m>0&&E!==R)return E-R;if(n&&m>0){let S=y.liquidityUsd??-1,B=k.liquidityUsd??-1;if(S!==B)return B-S}return g(y,k)}),n&&m>0&&C&&p[0]&&p[0].source!==C.source&&A.push(`liquidity-first: chose ${p[0].source} (liquidity $${p[0].liquidityUsd??"unknown"}) over best-price ${C.source} within ${m} bps`);let U=p.filter(y=>!y.costAccounted).map(y=>y.source);i?U.length&&A.push(`gas not reported by: ${U.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):A.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let I=p[0];if(i&&I&&I.costAccounted===!1){let y=p.find(k=>k.costAccounted&&b(k.netOut)<=m);y&&A.push(`winner ${I.source} has UNMEASURED gas; gas-measured ${y.source} is within ${m} bps and may net more once ${I.source}'s real gas is paid \u2014 prefer it if unsure.`)}let P=p.filter(y=>y.gasEstimated).map(y=>y.source);P.length&&A.push(`gas ESTIMATED (from gas units x current gas price, not measured) for: ${P.join(", ")}. Net includes this estimate so the ranking is gas-inclusive, but the on-chain gas may differ.`);let x=null,_=null;if(p.length>=2&&p[0].costAccounted&&p[1].costAccounted){let y=BigInt(p[0].netOut),k=BigInt(p[1].netOut);k>0n&&(x=Number((y-k)*10000n/k),_=`${p[0].source} vs ${p[1].source}`)}return{best:p[0]??null,routes:p,failed:l,improvementBps:x,spreadBasis:_,rankedOn:i?"net-of-cost":"gross",warnings:A}}async function kt(e,{timeoutMs:t=12e3}={}){let r=(a,s)=>{let o;return Promise.race([a,new Promise((u,l)=>{o=setTimeout(()=>l(new Error(`${s}: timeout`)),t)})]).finally(()=>clearTimeout(o))};return(await Promise.allSettled(e.map(a=>r(Promise.resolve().then(a.run),a.source)))).map((a,s)=>{let o=e[s].source;return a.status==="rejected"?Ct({source:o,error:String(a.reason?.message||a.reason)}):Ct({source:o,...a.value})})}De();$();re();Y();$e();$();re();Y();$();re();Y();$();re();import{TypedDataEncoder as vs,getAddress as Cs,isAddress as Is}from"ethers";var ys=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});Le();Y();var _s=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),Us=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"});var Ps=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"}]}),Ls=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]});import{Interface as or,getAddress as ti,isAddress as ri}from"ethers";$();var ct={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0},elysium:{chainId:1339,name:"Elysium",rpcEnv:["ELYSIUM_RPC_URL"],evm:!0,readOnly:!0}};var nr=new Map(Object.values(ct).map(e=>[e.chainId,e]));function Se(e){return nr.get(Number(e))||null}function Fe(e){return nr.get(Number(e))?.readOnly===!0}import{Interface as bo,getAddress as Ks}from"ethers";var Gs=new bo(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);$();var Js=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});re();Y();var ii=new or(["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)"]),ci=new or(["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)"]);import{AbiCoder as So,Interface as ut,getAddress as pi,isAddress as fi,keccak256 as mi}from"ethers";re();Y();var yi=So.defaultAbiCoder();var Si=new ut(["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)","function quoteExactOutputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountIn, uint256 gasEstimate)"]),Ei=new ut(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),Ai=new ut(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96,int24 tick,uint24 protocolFee,uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),xi=Object.freeze([[13,"beforeInitialize"],[12,"afterInitialize"],[11,"beforeAddLiquidity"],[10,"afterAddLiquidity"],[9,"beforeRemoveLiquidity"],[8,"afterRemoveLiquidity"],[7,"beforeSwap"],[6,"afterSwap"],[5,"beforeDonate"],[4,"afterDonate"],[3,"beforeSwapReturnsDelta"],[2,"afterSwapReturnsDelta"],[1,"afterAddLiquidityReturnsDelta"],[0,"afterRemoveLiquidityReturnsDelta"]]),vi=(1n<<14n)-1n;$();var Eo="https://coins.llama.fi",Ao="https://api.llama.fi";function xo(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Eo).replace(/\/$/,"")}function vo(e={}){return(e.baseUrl||process.env.DEFILLAMA_API_URL||Ao).replace(/\/$/,"")}async function lt(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return v(`${xo(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function ar(e={}){return v(`${vo(e)}/protocols`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??2e4})}var G=e=>{let t=Number(e);return Number.isFinite(t)?t:null};function dr(e){if(!Array.isArray(e))return null;let t=0,r=!1;for(let n of e){let a=G(n?.amountUSD);a!=null&&(t+=a,r=!0)}return r?t:null}function pr(e){return Array.isArray(e)?e.flatMap((t,r)=>{let n=String(t?.amountUSD??"").trim();return/^\d+(?:\.\d+)?$/.test(n)?[{name:String(t?.name??t?.type??`cost-${r+1}`),amountUsd:n}]:[]}):[]}var ie=e=>String(e??"").toLowerCase().replace(/[^a-z0-9]/g,""),fr=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 No(e={}){try{let t=await ar({...e,baseUrl:e.defillamaApiBaseUrl,timeoutMs:e.defillamaTimeoutMs??Math.min(Number(e.timeoutMs??5e3),5e3)});return Array.isArray(t)?t:[]}catch{return[]}}function Ro(e,t={}){let r=ie(t.tool||t.provider||t.bridge||t.protocol),n=[];return e==="lifi"&&r&&r!=="lifi"&&n.push(...fr[r]||[r]),n.push(...fr[ie(e)]||[e]),n}function Bo(e,t,r={}){let n=Array.isArray(e)?e:[],a=Ro(t,r).map(ie).filter(Boolean);for(let s of a){let o=n.find(l=>ie(l?.slug)===s||ie(l?.name)===s),u=G(o?.tvl);if(u!=null)return{liquidityUsd:u,protocol:o?.name??o?.slug??s}}for(let s of a){let o=n.find(l=>{let i=ie(l?.category);return!i.includes("bridge")&&!i.includes("crosschain")?!1:ie(l?.slug).includes(s)||ie(l?.name).includes(s)}),u=G(o?.tvl);if(u!=null)return{liquidityUsd:u,protocol:o?.name??o?.slug??s}}return null}function mr({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:a,taker:s,slippageBps:o,allowedSources:u,opts:l={}}){let i=[],c=null,d=async(p,m={})=>(c||=No(l),Bo(await c,p,m));if(i.push({source:"lifi",run:async()=>{let p=await me({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:a,fromAddress:s,slippageBps:o},l),m=p?.estimate??p?.[0]?.estimate,w=(p?.includedSteps??p?.steps??[]).map((g,C)=>({id:String(g?.id??`step-${C+1}`),type:String(g?.type??"route"),tool:String(g?.tool??g?.toolDetails?.name??"LI.FI"),fromChainId:Number(g?.action?.fromChainId??e),toChainId:Number(g?.action?.toChainId??t)})),b={tool:p?.tool??p?.toolDetails?.name,durationSeconds:G(m?.executionDuration),destinationDecimals:G(p?.action?.toToken?.decimals),routeSteps:w,feeCosts:pr(m?.feeCosts),gasCosts:pr(m?.gasCosts)},A=await d("lifi",b);return{amountOut:m?.toAmount,minOut:m?.toAmountMin,gasUsd:dr(m?.gasCosts),feeUsd:dr(m?.feeCosts),feeIncludedInAmountOut:!0,oracleFeeBps:p?.oracleFee?.applies?p.oracleFee.bps:0,liquidityUsd:A?.liquidityUsd??null,meta:{...b,liquidityProtocol:A?.protocol,oracleFee:p?.oracleFee??null}}}}),i.push({source:"relay",run:async()=>{let{relayQuote:p}=await Promise.resolve().then(()=>(xe(),He)),m=await p({user:s,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(a),slippageBps:o},l),w=m?.details,b=(m?.steps??[]).map((P,x)=>({id:String(P?.id??`step-${x+1}`),type:String(P?.kind??"transaction"),tool:"Relay",label:String(P?.description??P?.action??P?.id??`Step ${x+1}`),fromChainId:Number(e),toChainId:Number(t)})),A=String(m?.fees?.relayer?.amountUsd??"").trim(),g=String(m?.fees?.gas?.amountUsd??"").trim(),C=String(w?.totalImpact?.usd??"").trim(),U={durationSeconds:G(w?.timeEstimate),rate:w?.rate,destinationDecimals:G(w?.currencyOut?.currency?.decimals),routeSteps:b,feeCosts:[.../^\d+(?:\.\d+)?$/.test(A)?[{name:"relayer",amountUsd:A}]:[],.../^-?\d+(?:\.\d+)?$/.test(C)?[{name:"total-impact",amountUsd:C}]:[]],gasCosts:/^\d+(?:\.\d+)?$/.test(g)?[{name:"origin-gas",amountUsd:g}]:[]},I=await d("relay",U);return{amountOut:w?.currencyOut?.amount,minOut:w?.currencyOut?.minimumAmount,gasUsd:G(m?.fees?.gas?.amountUsd),feeUsd:G(m?.fees?.relayer?.amountUsd)??(G(w?.totalImpact?.usd)!=null?Math.abs(G(w.totalImpact.usd)):null),feeIncludedInAmountOut:!0,liquidityUsd:I?.liquidityUsd??null,meta:{...U,liquidityProtocol:I?.protocol}}}}),i.push({source:"across",run:async()=>{let{acrossSuggestedFees:p}=await Promise.resolve().then(()=>(xe(),He)),m=await p({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(a)},l),w=m?.totalRelayFee?.total,b=null;if(w!=null)try{let g=BigInt(String(a))-BigInt(String(w));g>0n&&(b=g.toString())}catch{}let A=await d("across");return{amountOut:b,gasUsd:null,liquidityUsd:A?.liquidityUsd??null,meta:{derivedFromFees:!0,durationSeconds:G(m?.estimatedFillTimeSec),limits:m?.limits?{min:m.limits.minDeposit,max:m.limits.maxDeposit}:void 0,liquidityProtocol:A?.protocol}}}}),!Array.isArray(u))return i;let h=new Set(u.map(p=>String(p).toLowerCase()));return i.filter(p=>h.has(p.source))}$e();function _o(e,t,r){let n=t.find(s=>Fe(s));if(n==null)return null;let a=Se(n)?.name||`chain ${n}`;return{kind:e,...r,best:null,routes:[],failed:[],improvementBps:null,spreadBasis:null,rankedOn:null,warnings:[],unsupported:!0,readOnlyChain:Number(n),sourcesTried:0,sourcesAnswered:0,note:`${a} (${n}) is registered read-only: no swap venue or route source covers it. This is UNSUPPORTED, not a failed quote. Oracle reads balances and calls there; it does not quote or prepare.`}}var Uo={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"},hr=Object.freeze(["lifi","relay"]);function Po(e){let t=e==null?50:Number(e);if(!Number.isInteger(t)||t<1||t>100)throw new Error("slippageBps must be an integer from 1 through 100");return t}function Lo(e,t=hr){let r=new Set((Array.isArray(t)?t:hr).map(o=>String(o).toLowerCase())),n=(e?.routes??[]).filter(o=>r.has(o.source)),a=new Set(n.map(o=>o.source)),s=(e?.failed??[]).filter(o=>r.has(o.source)&&!a.has(o.source));return[...n,...s].map(o=>({provider:o.source,status:o.quality===Z.FAILED?"unavailable":"quoted",amountOut:o.amountOut??null,minAmountOut:o.minOut??null,netAmountOut:o.netOut??null,feeUsd:o.feeUsd??null,gasUsd:o.gasUsd??null,etaSeconds:o.meta?.durationSeconds??null,decimalsOut:o.meta?.destinationDecimals??null,routeSteps:Array.isArray(o.meta?.routeSteps)?o.meta.routeSteps:[],feeCosts:Array.isArray(o.meta?.feeCosts)?o.meta.feeCosts:[],gasCosts:Array.isArray(o.meta?.gasCosts)?o.meta.gasCosts:[],selected:o.source===e?.best?.source,error:o.error??null}))}async function $o(e,t,r){let n=Uo[Number(e)];if(!n)return{priceUsd:null,decimals:null};let a=`${n}:${t}`;try{let o=(await lt([a],r))?.coins?.[a],u=Number(o?.price),l=Number(o?.decimals);return{priceUsd:Number.isFinite(u)?u:null,decimals:Number.isFinite(l)?l:null}}catch{return{priceUsd:null,decimals:null}}}async function gr(e,t={}){let{fromChainId:r,toChainId:n,tokenIn:a,tokenOut:s,amountIn:o}=e;if(r==null||n==null||!a||!s||o==null)throw new Error("bestBridgeRoute requires fromChainId, toChainId, tokenIn, tokenOut, amountIn");if(Number(r)===Number(n))throw new Error("bestBridgeRoute is for cross-chain; use bestSwapRoute for same-chain");let u=_o("bridge",[r,n],{fromChainId:r,toChainId:n,tokenIn:a,tokenOut:s,amountIn:String(o)});if(u)return u;let l=Po(e.slippageBps),i={...e,slippageBps:l},c=$o(n,s,t),d=mr({...i,opts:t}),[h,p]=await Promise.all([kt(d,{timeoutMs:t.timeoutMs??15e3}),c]),m=It(h,{destPriceUsd:p.priceUsd,destDecimals:e.decimalsOut??p.decimals,liquidityFirst:!1,liquidityBandBps:0}),w=m.routes.map(b=>({source:b.source,seconds:b.meta?.durationSeconds??null})).filter(b=>b.seconds!=null);return{kind:"bridge",fromChainId:r,toChainId:n,tokenIn:a,tokenOut:s,amountIn:String(o),slippageBps:l,...m,routeOptions:Lo(m,e.allowedSources),durations:w,sourcesTried:d.length,sourcesAnswered:h.filter(b=>b.quality!==Z.FAILED).length,note:Fo(m,d.length)}}function Do(e){let t=e?.meta?.oracleFee;return t?.applies?` \xB7 ${Zt(t)}`:""}function Fo(e,t){if(!e.best)return"no source returned a usable route";let r=e.routes.length,n=Do(e.best);if(r===1)return`only 1 of ${t} sources answered, so this is the ONLY route, not a proven best one. Treat it as unbenchmarked.`+n;if(e.improvementBps!=null){let a=e.improvementBps,s=a/100;if(a<.01)return`best of ${r} routes, ranked on ${e.rankedOn}: effectively tied with the runner-up (${e.spreadBasis}), inside quote noise. Re-quote before you size up.`+n;let o=s>=.01?`${s.toFixed(2)}%`:`${a.toFixed(2)}bps`;return`best of ${r} routes, ranked on ${e.rankedOn}: ${o} better than the runner-up (${e.spreadBasis})`+n}return`best of ${r} routes, ranked on ${e.rankedOn}. No spread quoted: the top routes report cost differently, so the margin is not comparable.`+n}Y();De();yt();$();var St="https://api.changenow.io/v2",he=new Map,Sr=0,Ho=6e5;async function jo({active:e=!0}={},t={}){let r=Date.now();if(he.size&&r-Sr<Ho)return[...he.values()];try{let n=await v(`${St}/exchange/currencies?active=${e?"true":"false"}`,t);he.clear();for(let a of n??[])he.set(String(a.ticker).toLowerCase(),a);return Sr=r,n??[]}catch(n){return he.size?[...he.values()]:{error:String(n.message||n).slice(0,200)}}}async function Vo(e,t,r={}){if(!e||!t)return{error:"changenow minAmount requires fromTicker and toTicker"};try{return{minAmount:(await v(`${St}/exchange/min-amount/${encodeURIComponent(e)}_${encodeURIComponent(t)}`,r))?.minAmount??"0"}}catch(n){return{error:String(n.message||n).slice(0,200)}}}async function zo(e,t,r,{flow:n="standard"}={},a={}){if(!e||!t||!r)return{error:"changenow estimate requires fromTicker, toTicker, fromAmount"};try{let s=new URLSearchParams({fromCurrency:String(e).toLowerCase(),toCurrency:String(t).toLowerCase(),fromAmount:String(r),flow:n}),o=await v(`${St}/exchange/estimated-amount?${s}`,a);return{fromAmount:o?.fromAmount,toAmount:o?.toAmount,rate:o?.rate,flow:o?.flow??n}}catch(s){return{error:String(s.message||s).slice(0,200)}}}async function Er({fromTicker:e,toTicker:t,fromAmount:r,flow:n}={},a={}){if(!e||!t)return{error:"changenow quote requires fromTicker and toTicker"};let s=await Vo(e,t,a);if(s.error)return s;let o=r??s.minAmount,u=await zo(e,t,o,{flow:n},a);if(u.error)return u;let l=await jo({},a),i=l.find(d=>String(d?.ticker).toLowerCase()===String(e).toLowerCase()),c=l.find(d=>String(d?.ticker).toLowerCase()===String(t).toLowerCase());return{provider:"changenow",fromTicker:e,toTicker:t,fromAmount:o,toAmount:u.toAmount,estimatedRate:u.rate,minAmount:s.minAmount,flow:u.flow,networkFee:i?.networkFee??null,kycRequired:i?.kycRequired??c?.kycRequired??!1,riskDisclosure:"ChangeNOW is a centralized swap service. Funds are sent to a ChangeNOW deposit address. Not self-custodial during the swap window."}}$();var Ko="https://api.squidrouter.com/v1";async function Ar({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:a,fromAddress:s,slippage:o=1}={},u={}){if(!e||!t||!r||!n||!a||!s)return{error:"squid quote requires fromChain, toChain, fromToken, toToken, fromAmount, fromAddress"};try{let l={fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:String(a),fromAddress:s,slippage:o},i=await v(`${Ko}/route`,{...u,method:"POST",body:JSON.stringify(l),headers:{"content-type":"application/json",...u.headers||{}}});return{route:i?.route??{},toAmount:i?.route?.estimate?.toAmount,fee:i?.route?.estimate?.feeCosts}}catch(l){return{error:String(l.message||l).slice(0,200)}}}$();var Go="https://api.stargate.finance";async function xr({srcChainId:e,dstChainId:t,token:r,amount:n,dstGasForCall:a=0,minAmountOut:s="0"}={},o={}){if(!e||!t||!r||!n)return{error:"stargate quote requires srcChainId, dstChainId, token, amount"};try{let u=new URLSearchParams({srcChainId:String(e),dstChainId:String(t),token:r,amount:String(n),dstGasForCall:String(a),minAmountOut:String(s)}),l=await v(`${Go}/quote?${u}`,o);return{amountOut:l?.amountOut,fee:l?.fee,estimatedTime:l?.estimatedTime}}catch(u){return{error:String(u.message||u).slice(0,200)}}}$();var vr="https://midgard.ninerealms.com/v2";async function Cr({fromAsset:e,toAsset:t,amount:r,destination:n}={},a={}){if(!e||!t||!r)return{error:"thorchain quote requires fromAsset, toAsset, amount"};try{let s=new URLSearchParams({from_asset:e,to_asset:t,amount:String(r),destination:n||""}),o=await v(`${vr}/quote/swap?${s}`,a);return{expectedAmountOut:o?.expected_amount_out,fees:o?.fees,slippageBps:o?.slippage_bps,inboundAddress:o?.inbound_address,memo:o?.memo,estimatedTime:o?.total_swap_seconds?`${Math.round(o.total_swap_seconds/60)} min`:"unknown"}}catch(s){return{error:String(s.message||s).slice(0,200)}}}async function Ir(){try{return{ok:(await v(`${vr}/health`))?.scannerHeight>0}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}$();var Wo="https://api.socket.tech/v2";async function kr({fromChainId:e,toChainId:t,fromToken:r,toToken:n,fromAmount:a,userAddress:s}={},o={}){if(!e||!t||!r||!n||!a||!s)return{error:"bungee quote requires fromChainId, toChainId, fromToken, toToken, fromAmount, userAddress"};try{let u=new URLSearchParams({fromChainId:String(e),toChainId:String(t),fromTokenAddress:r,toTokenAddress:n,fromAmount:String(a),userAddress:s,sort:"output",singleTxOnly:"false"}),l=await v(`${Wo}/quote?${u}`,o);return{amountOut:l?.result?.toAmount,feeUsd:l?.result?.totalGasFeesInUsd,route:l?.result?.route,estimatedTime:l?.result?.serviceTime?`${l.result.serviceTime}s`:"unknown"}}catch(u){return{error:String(u.message||u).slice(0,200)}}}$();var Qo="https://api.connext.network";async function Or({originDomain:e,destinationDomain:t,originToken:r,destinationToken:n,amount:a}={},s={}){if(!e||!t||!r||!n||!a)return{error:"connext quote requires originDomain, destinationDomain, originToken, destinationToken, amount"};try{let o={originDomain:String(e),destinationDomain:String(t),originToken:r,destinationToken:n,amount:String(a)},u=await v(`${Qo}/estimate`,{...s,method:"POST",body:JSON.stringify(o),headers:{"content-type":"application/json",...s.headers||{}}});return{amountOut:u?.amountOut,fee:u?.fee,estimatedTime:u?.estimatedTransferTime}}catch(o){return{error:String(o.message||o).slice(0,200)}}}$();var Yo="https://api.portalbridge.com/v1";async function Tr({fromChain:e,toChain:t,token:r,amount:n}={},a={}){if(!e||!t||!r||!n)return{error:"wormhole quote requires fromChain, toChain, token, amount"};try{let s=new URLSearchParams({fromChain:String(e),toChain:String(t),token:r,amount:String(n)}),o=await v(`${Yo}/quote?${s}`,a);return{amountOut:o?.amountOut,fee:o?.fee,estimatedTime:o?.estimatedTime}}catch(s){return{error:String(s.message||s).slice(0,200)}}}xe();import{Interface as Rr,getAddress as tu,id as Br}from"ethers";$();var Nr=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",stableQuoteAssets:["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48","0xdAC17F958D2ee523a2206206994597C13D831ec7"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85","0x94b008aA00579c1307B0EF2c499aD98a8ce58e58"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",stableQuoteAssets:["0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d","0x55d398326f99059fF775485246999027B3197955"],venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",stableQuoteAssets:["0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359","0xc2132D05D31c914a87C6611C10748AEb04B58e8F"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",stableQuoteAssets:["0x5fc5360d0400a0fd4f2af552add042d716f1d168"],venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",stableQuoteAssets:["0xaf88d065e77c8cC2239327C5EDb3A432268e5831","0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",stableQuoteAssets:["0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"],venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);$();var au=new Rr(["function decimals() view returns (uint8)","function symbol() view returns (string)"]),su=new Rr(["function isApprovedForAll(address owner, address operator) view returns (bool)","function name() view returns (string)"]),iu=Br("Approval(address,address,uint256)"),cu=Br("ApprovalForAll(address,address,bool)");var uu=Object.freeze({"0x1111111254eeb25477b68fb85ed929f73a960582":"1inch v5 Router","0x111111125421ca6dc452d289314280a0f8842a65":"1inch v6 Router","0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45":"Uniswap Universal Router","0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad":"Uniswap Universal Router","0x000000000022d473030f116ddee9f6b43ac78ba3":"Permit2","0xe592427a0aece92de3edee1f18e0157c05861564":"Uniswap v3 Router","0x7a250d5630b4cf539739df2c5dacb4c659f2488d":"Uniswap v2 Router","0xdef1c0ded9bec7f1a1670819833240f027b25eff":"0x Exchange Proxy","0x2626664c2603336e57b271c5c0b26f421741e481":"Uniswap SwapRouter02 (Base)","0x6131b5fae19ea4f9d964eac0408e4408b66337b5":"KyberSwap Meta Aggregator","0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48":"USDC (token contract)"}),lu=Object.freeze([{address:"0x000000000022d473030f116ddee9f6b43ac78ba3",label:"Permit2"},{address:"0x1111111254eeb25477b68fb85ed929f73a960582",label:"1inch v5 Router"},{address:"0x111111125421ca6dc452d289314280a0f8842a65",label:"1inch v6 Router"},{address:"0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45",label:"Uniswap Universal Router"},{address:"0xe592427a0aece92de3edee1f18e0157c05861564",label:"Uniswap v3 Router"},{address:"0x7a250d5630b4cf539739df2c5dacb4c659f2488d",label:"Uniswap v2 Router"},{address:"0xdef1c0ded9bec7f1a1670819833240f027b25eff",label:"0x Exchange Proxy"},{address:"0x2626664c2603336e57b271c5c0b26f421741e481",label:"Uniswap SwapRouter02"}]),du=Object.freeze([{address:"0x1e0049783f008a0085193e00003d00cd54003c71",label:"OpenSea Seaport Conduit"},{address:"0x00000000000000adc04c56bf30ac9d3c0aaf14dc",label:"Seaport 1.5"},{address:"0x0000000000000068f116a894984e2db1123eb395",label:"Seaport 1.6"},{address:"0x00000000000001ad428e4906ae43d8f9852d0dd6",label:"Seaport 1.4"},{address:"0x000000000000ad05ccc4f10045630fb830b95127",label:"Blur Marketplace"},{address:"0x00000000000000000000000000000000000000a5",label:"Blur Execution Delegate"},{address:"0xf42aa99f011a1fa7cda90e5e98b277e306bca83e",label:"Rarible Transfer Proxy"},{address:"0x000000000022d473030f116ddee9f6b43ac78ba3",label:"Permit2"}]),pu=Object.freeze({1:[{address:"0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d",name:"Bored Ape Yacht Club"},{address:"0x60e4d786628fea6478f785a6d7e704777c86a7c6",name:"Mutant Ape Yacht Club"},{address:"0xed5af388653567af2f388e6224dc7c4b3241c544",name:"Azuki"},{address:"0x8a90cab2b38dba80c64b7734e58ee1db38b8992e",name:"Doodles"},{address:"0x49cf6f5d44e70224e2e23fdcdd2c053f30ada28b",name:"CloneX"},{address:"0x23581767a106ae21c074b2276d25e5c3e136a68b",name:"Moonbirds"}]}),fu=Object.freeze({1:[{address:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",symbol:"USDC",decimals:6},{address:"0xdac17f958d2ee523a2206206994597c13d831ec7",symbol:"USDT",decimals:6},{address:"0x6b175474e89094c44da98b954eedeac495271d0f",symbol:"DAI",decimals:18},{address:"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",symbol:"WETH",decimals:18},{address:"0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",symbol:"WBTC",decimals:8}],8453:[{address:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",symbol:"USDC",decimals:6},{address:"0x4200000000000000000000000000000000000006",symbol:"WETH",decimals:18}],42161:[{address:"0xaf88d065e77c8cc2239327c5edb3a432268e5831",symbol:"USDC",decimals:6},{address:"0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9",symbol:"USDT",decimals:6},{address:"0x82af49447d8a07e3bd95bd0d56f35241523fbab1",symbol:"WETH",decimals:18}],10:[{address:"0x0b2c639c533813f4aa9d7837caf62653d097ff85",symbol:"USDC",decimals:6},{address:"0x4200000000000000000000000000000000000006",symbol:"WETH",decimals:18}],137:[{address:"0x3c499c542cef5e3811e1192ce70d8cc03d5c3359",symbol:"USDC",decimals:6},{address:"0xc2132d05d31c914a87c6611c10748aeb04b58e8f",symbol:"USDT",decimals:6}]}),Zo=(1n<<256n)-1n,mu=Zo/2n,hu=4320*60*60*1e3,gu=360*60*1e3,bu=600*1e3,wu=45*1e3;var ve=Object.freeze(["debridge","lifi","relay","squid","stargate","thorchain","bungee","connext","wormhole","across","hop","changenow","rango"]),_r=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche"}),ea=Object.freeze({1:"ETHEREUM",10:"OPTIMISM",56:"BSC",137:"POLYGON",324:"ZKSYNC",1101:"POLYGONZK",5e3:"MANTLE",8453:"BASE",42161:"ARBITRUM",43114:"AVAX_CCHAIN",59144:"LINEA",81457:"BLAST",534352:"SCROLL"}),ta=Object.freeze({1:"ETH",56:"BSC",8453:"BASE",42161:"ARB",43114:"AVAX"}),Dr=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]);function Et(e,t=180){return String(e?.message||e||"unknown error").replace(/\s+/g," ").slice(0,t)}function Ur(e){let t=String(e??"");if(!/^\d+$/.test(t))return null;try{return BigInt(t)>0n?t:null}catch{return null}}function ra(e,t){try{let r=BigInt(String(e))-BigInt(String(t));return r>0n?r.toString():null}catch{return null}}function ge(e){let t=Number(e);return Number.isInteger(t)&&t>=0&&t<=255?t:null}function na(e,t){let r=ge(t),n=String(e??"");if(r==null||!/^\d+$/.test(n))return null;if(r===0)return n;let a=n.padStart(r+1,"0"),s=a.slice(0,-r),o=a.slice(-r).replace(/0+$/,"");return o?`${s}.${o}`:s}function oa(e,t){let r=ge(t),n=/^(\d+)(?:\.(\d+))?$/.exec(String(e??""));if(r==null||!n)return null;let a=n[2]||"";if(a.length>r&&/[1-9]/.test(a.slice(r)))return null;let s=a.slice(0,r).padEnd(r,"0");try{return(BigInt(n[1])*10n**BigInt(r)+BigInt(s||"0")).toString()}catch{return null}}function Pr(e,t,r){let n=ge(t),a=ge(r);if(n==null||a==null||!/^\d+$/.test(String(e??"")))return null;let s=BigInt(String(e));return a>=n?(s*10n**BigInt(a-n)).toString():(s/10n**BigInt(n-a)).toString()}function At(e){return typeof e?.to=="string"&&e.to.length>0&&/^0x(?:[0-9a-fA-F]{2})+$/.test(String(e.data||""))}function aa(e){return(e?.steps||[]).some(t=>(t?.items||[]).some(r=>At(r?.data)))}function Lr(e,t,r){let n=ea[Number(e)];return n?Dr.has(String(t||"").toLowerCase())?r&&r!=="?"?`${n}.${r}`:null:t?`${n}--${t}`:null:null}function $r(e,t,r){if(!r||r==="?")return null;if(r.includes("."))return r;let n=ta[Number(e)];return n?Dr.has(String(t||"").toLowerCase())?`${n}.${r}`:`${n}.${r}-${t}`:null}async function Fr(e={},t={}){let{fromChainId:r,toChainId:n,tokenIn:a,tokenOut:s,amount:o,taker:u,fromSymbol:l="?",toSymbol:i="?",fromDecimals:c,toDecimals:d,slippageBps:h}=e,p=t.includeCentralized===!0||e.includeCentralized===!0,m=ge(c),w=ge(d),b=new Map(ve.map(f=>[f,{provider:f,status:"pending"}])),A=[],g={fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs,retries:t.retries,headers:t.headers},C=(f,M,W=!1)=>{b.set(f,{provider:f,status:"unavailable",reason:Et(M),optional:W})},U=(f,M)=>{b.set(f,{provider:f,status:"skipped",reason:Et(M)})},I=(f,M,W)=>{b.set(f,{provider:f,status:"attempted"}),A.push(Promise.resolve().then(M).then(K=>{if(K?.error)throw new Error(K.error);let de=W(K),ne=Ur(de?.amountOut);if(!ne)throw new Error("no usable integer base-unit amountOut");let Oe={...de,provider:f,amountOut:ne,raw:K};return b.set(f,{provider:f,status:"successful"}),Oe}).catch(K=>(b.set(f,{provider:f,status:"failed",reason:Et(K)}),null)))};I("debridge",()=>bt({srcChainId:r,srcChainTokenIn:a,srcChainTokenInAmount:o,dstChainId:n,dstChainTokenOut:s,taker:u,slippage:h},g),f=>({amountOut:f.estimation?.dstChainTokenOut?.amount??f.estimation?.toAmount,feeUsd:f.estimation?.fixFee??f.fixFee,estimatedTime:f.estimation?.execution?.estimatedTransferTime?`${f.estimation.execution.estimatedTransferTime}s`:"unknown",preparable:At(f.tx)})),I("lifi",()=>me({fromChain:r,toChain:n,fromToken:a,toToken:s,fromAmount:o,fromAddress:u},g),f=>({amountOut:f.estimate?.toAmount??f.toAmount,feeUsd:f.estimate?.feeCosts??null,estimatedTime:f.estimate?.executionDuration??"unknown",preparable:At(f.transactionRequest)})),I("relay",()=>Ae({user:u,originChainId:r,destinationChainId:n,originCurrency:a,destinationCurrency:s,amount:String(o)},g),f=>({amountOut:f.details?.currencyOut?.amount,feeUsd:f.details?.totalImpact?.usd??null,estimatedTime:f.details?.timeEstimate??"unknown",preparable:aa(f)})),I("squid",()=>Ar({fromChain:r,toChain:n,fromToken:a,toToken:s,fromAmount:o,fromAddress:u},g),f=>({amountOut:f.toAmount,feeUsd:f.fee??null,estimatedTime:"30s - 3min",preparable:!1})),I("stargate",()=>xr({srcChainId:r,dstChainId:n,token:a,amount:o},g),f=>({amountOut:f.amountOut,feeUsd:f.fee,estimatedTime:f.estimatedTime||"1-5 min",preparable:!1}));let P=Pr(o,m,8),x=$r(r,a,l),_=$r(n,s,i);m==null||w==null?C("thorchain","fromDecimals and toDecimals are required for unit conversion"):!x||!_?C("thorchain","supported chain mapping plus qualified asset symbols are required"):Ur(P)?I("thorchain",()=>Cr({fromAsset:x,toAsset:_,amount:P,destination:u},g),f=>({amountOut:Pr(f.expectedAmountOut,8,w),feeUsd:f.fees?.total,estimatedTime:f.estimatedTime||"10-30 min",preparable:!1})):C("thorchain","amount is below THORChain's 8-decimal quote precision"),I("bungee",()=>kr({fromChainId:r,toChainId:n,fromToken:a,toToken:s,fromAmount:o,userAddress:u},g),f=>({amountOut:f.amountOut,feeUsd:f.feeUsd,estimatedTime:f.estimatedTime,preparable:!1})),I("connext",()=>Or({originDomain:r,destinationDomain:n,originToken:a,destinationToken:s,amount:o},g),f=>({amountOut:f.amountOut,feeUsd:f.fee,estimatedTime:f.estimatedTime||"5-20 min",preparable:!1})),I("wormhole",()=>Tr({fromChain:r,toChain:n,token:a,amount:o},g),f=>({amountOut:f.amountOut,feeUsd:f.fee,estimatedTime:f.estimatedTime||"5-15 min",preparable:!1})),I("across",()=>qe({token:a,destinationToken:s,originChainId:r,destinationChainId:n,amount:String(o)},g),f=>{let M=f.outputAmount??f.expectedOutputAmount,W=f.totalRelayFee?.total??f.relayFeeTotal;return{amountOut:M??(W!=null?ra(o,W):null),feeUsd:f.relayFeeTotalUsd??null,estimatedTime:f.estimatedFillTimeSec!=null?`${f.estimatedFillTimeSec}s`:"unknown",preparable:!1}});let y=_r[Number(r)],k=_r[Number(n)];!y||!k||!l||l==="?"?C("hop","supported chain mapping and fromSymbol are required"):I("hop",()=>Me({amount:String(o),token:l,fromChain:y,toChain:k},g),f=>({amountOut:f.estimatedRecieved??f.estimatedReceived,feeUsd:f.feeUsd??null,estimatedTime:f.estimatedTime??"unknown",preparable:!1}));let E=na(o,m);p?m==null||w==null?C("changenow","fromDecimals and toDecimals are required for unit conversion"):!l||!i||l==="?"||i==="?"?C("changenow","fromSymbol and toSymbol are required"):E==null?C("changenow","valid integer amount is required"):I("changenow",()=>Er({fromTicker:l,toTicker:i,fromAmount:E},g),f=>({amountOut:oa(f.toAmount,w),feeUsd:f.networkFee,estimatedTime:f.flow==="standard"?"5-30 min":"instant",preparable:!1,centralized:!0,kycRequired:!!f.kycRequired,kycRisk:!0,riskDisclosure:f.riskDisclosure||"ChangeNOW is centralized and may require KYC."})):U("changenow","centralized/KYC-risk routes require includeCentralized=true");let R=t.env??process.env,S=t.rangoApiKey||R.RANGO_API_KEY,B=Lr(r,a,l),q=Lr(n,s,i);S?!B||!q?C("rango","supported Rango chain/token identifiers are required",!0):I("rango",()=>ht({from:B,to:q,amount:String(o),enableCentralizedSwappers:!1},{...t,rangoApiKey:S}),f=>({amountOut:f.amountOut,feeUsd:f.feeUsd,estimatedTime:f.estimatedTime!=null?`${f.estimatedTime}s`:"unknown",preparable:!1})):C("rango","RANGO_API_KEY is not configured",!0);let D=(await Promise.all(A)).filter(Boolean);D.sort((f,M)=>{let W=BigInt(f.amountOut),K=BigInt(M.amountOut);return W!==K?W>K?-1:1:f.preparable!==M.preparable?f.preparable?-1:1:ve.indexOf(f.provider)-ve.indexOf(M.provider)});let O=ve.map(f=>b.get(f)),T=O.filter(f=>["successful","failed"].includes(f.status)).map(f=>f.provider),N=O.filter(f=>f.status==="successful").map(f=>f.provider),j=O.filter(f=>f.status==="failed").map(f=>f.provider),z=O.filter(f=>f.status==="unavailable").map(f=>f.provider),J=O.filter(f=>f.status==="skipped").map(f=>f.provider),ce=O.filter(f=>f.status==="failed").map(f=>`${f.provider}: ${f.reason}`),Ie=D.length>0,ke=Ie&&O.every(f=>f.status==="successful"||f.status==="skipped"||f.status==="unavailable"&&f.optional);return{ok:Ie,providers:D.map(f=>f.provider),bestRoute:D[0]?.provider??"none",winner:D[0]??null,runnersUp:D.slice(1),errors:ce.length?ce:null,attemptedProviders:T,successfulProviders:N,failedProviders:j,unavailableProviders:z,skippedProviders:J,comparisonComplete:ke,coverage:{roster:[...ve],attemptedProviders:T,successfulProviders:N,failedProviders:j,unavailableProviders:z,skippedProviders:J,complete:ke,details:O}}}var Bu=Object.freeze({debridge:e=>wt(e),lifi:e=>it(e),relay:e=>mt(e),thorchain:e=>Ir(e),across:e=>dt(e),hop:e=>pt(e)}),_u=Object.freeze({squid:"existing health helper does not validate its response or accept injected request options",stargate:"adapter exposes only static metadata, not a network-backed health check",bungee:"existing health helper does not validate its response or accept injected request options",connext:"adapter exposes only static metadata, not a network-backed health check",wormhole:"adapter exposes only static metadata, not a network-backed health check",changenow:"existing health helper is cache-backed and cannot prove current availability",rango:"Rango has no standalone health check; quote health requires a configured route and RANGO_API_KEY"});var X=/^0x[0-9a-fA-F]{40}$/,qr=/^0x(?:[0-9a-fA-F]{2})+$/;function xt(e){return Array.isArray(e)?e.map(xt):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([t])=>t!=="signature"&&t!=="rawTransaction"&&t!=="signedTransaction").map(([t,r])=>[t,xt(r)]))}var sa=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),ia=100;function ca(e){let t=e==null?50:Number(e);if(!Number.isInteger(t)||t<1||t>100)throw new Error("slippageBps must be an integer from 1 through 100");return t}function Mr(e){return Array.isArray(e)?e.flatMap((t,r)=>{let n=String(t?.amountUSD??t?.amountUsd??"").trim();return/^-?\d+(?:\.\d+)?$/.test(n)?[{name:String(t?.name??t?.type??`fee-${r+1}`),amountUsd:n}]:[]}):[]}function ua(e){if(Array.isArray(e)){let r=Mr(e);if(!r.length)return null;let n=r.reduce((a,s)=>a+Number(s.amountUsd),0);return Number.isFinite(n)?n:null}let t=Number(e);return e!=null&&e!==""&&Number.isFinite(t)?t:null}function la(e){let t=Number(e);if(e!=null&&e!==""&&Number.isFinite(t)&&t>=0)return t;let r=/^\s*(\d+)s\s*$/i.exec(String(e??""));return r?Number(r[1]):null}function Hr(e,t){let r=e?.raw?.tx;if(!r||typeof r!="object"||Array.isArray(r))return{ok:!1,reason:"deBridge returned no paired transaction"};if(!X.test(String(r.to??"")))return{ok:!1,reason:"deBridge paired transaction target is not a valid destination"};if(!qr.test(String(r.data??"")))return{ok:!1,reason:"deBridge paired transaction calldata is not complete unsigned bytes"};if(r.chainId!=null&&Number(r.chainId)!==Number(t.fromChainId))return{ok:!1,reason:"deBridge paired transaction origin chain is mismatched"};if(!X.test(String(r.from??""))||String(r.from).toLowerCase()!==String(t.taker).toLowerCase())return{ok:!1,reason:"deBridge paired transaction sender is not the exact taker"};let n=e?.raw?.walletBinding;return!n||[n.dstChainTokenOutRecipient,n.srcChainOrderAuthorityAddress,n.dstChainOrderAuthorityAddress].some(a=>String(a??"").toLowerCase()!==String(t.taker).toLowerCase())?{ok:!1,reason:"deBridge destination recipient and order authorities are not bound to taker"}:{ok:!0,reason:null}}function da(e,t){return be[e?.provider]?e.provider==="debridge"?Hr(e,t):e?.preparable!==!0?{ok:!1,reason:"provider returned no verified unsigned transaction bytes"}:{ok:!0,reason:null}:{ok:!1,reason:"quote-only provider: no reviewed strict preparer"}}function Ce(e){return e?{source:e.source,amountOut:e.amountOut,grossOut:e.grossOut,netOut:e.netOut,feeUsd:e.feeUsd,gasUsd:e.gasUsd,etaSeconds:e.meta?.durationSeconds??null,estimatedTime:e.meta?.estimatedTime??null,preparable:e.preparable===!0}:null}async function pa(e,t){let{fromChainId:r,toChainId:n,tokenIn:a,tokenOut:s,amountIn:o,taker:u}=e;if(r==null||n==null||!a||!s||o==null)throw new Error("prepareBestBridgeRoute requires fromChainId, toChainId, tokenIn, tokenOut, amountIn");if(Number(r)===Number(n))throw new Error("prepareBestBridgeRoute is for cross-chain routes only");let l=ca(e.slippageBps),i=await Fr({fromChainId:r,toChainId:n,tokenIn:a,tokenOut:s,amount:String(o),taker:u,fromSymbol:e.fromSymbol,toSymbol:e.toSymbol,fromDecimals:e.fromDecimals??e.decimalsIn,toDecimals:e.toDecimals??e.decimalsOut,slippageBps:l,includeCentralized:e.includeCentralized===!0},t),d=[i.winner,...i.runnersUp||[]].filter(Boolean).map(g=>{let C=Mr(g.feeUsd),U=da(g,e),I={source:g.provider,quality:"NO_GAS",amountOut:String(g.amountOut),grossOut:String(g.amountOut),netOut:String(g.amountOut),gasUsd:null,feeUsd:ua(g.feeUsd),preparable:U.ok,prepareReason:U.reason,centralized:g.centralized===!0,kycRequired:g.kycRequired===!0,kycRisk:g.kycRisk===!0,riskDisclosure:g.riskDisclosure??null,meta:{durationSeconds:la(g.estimatedTime),estimatedTime:g.estimatedTime??null,destinationDecimals:Number.isInteger(e.toDecimals??e.decimalsOut)?Number(e.toDecimals??e.decimalsOut):null,routeSteps:[],feeCosts:C,gasCosts:[]}};return Object.defineProperty(I,"raw",{value:g.raw,enumerable:!1}),I}),h=d[0]??null,p=d.map((g,C)=>({provider:g.source,status:"quoted",rank:C+1,amountOut:g.amountOut,minAmountOut:null,netAmountOut:g.netOut,feeUsd:g.feeUsd,gasUsd:g.gasUsd,etaSeconds:g.meta.durationSeconds,estimatedTime:g.meta.estimatedTime,decimalsOut:g.meta.destinationDecimals,routeSteps:[],feeCosts:g.meta.feeCosts,gasCosts:[],selected:!1,quoteWinner:g.source===h?.source,preparable:g.preparable,quoteOnly:g.preparable!==!0,prepareReason:g.prepareReason,centralized:g.centralized,kycRequired:g.kycRequired,kycRisk:g.kycRisk,riskDisclosure:g.riskDisclosure,error:null})),m=new Set(d.map(g=>g.source)),w=(i.coverage?.details||[]).filter(g=>!m.has(g.provider)).map(g=>({provider:g.provider,status:g.status==="skipped"?"skipped":"unavailable",rank:null,amountOut:null,minAmountOut:null,netAmountOut:null,feeUsd:null,gasUsd:null,etaSeconds:null,estimatedTime:null,decimalsOut:Number.isInteger(e.toDecimals??e.decimalsOut)?Number(e.toDecimals??e.decimalsOut):null,routeSteps:[],feeCosts:[],gasCosts:[],selected:!1,quoteWinner:!1,preparable:!1,quoteOnly:!0,prepareReason:g.reason??"provider returned no usable quote",centralized:g.provider==="changenow",error:g.reason??null})),b=null;if(d.length>=2&&BigInt(d[1].netOut)>0n){let g=(BigInt(d[0].netOut)-BigInt(d[1].netOut))*10000n/BigInt(d[1].netOut);g<=BigInt(Number.MAX_SAFE_INTEGER)&&(b=Number(g))}let A=[];return i.comparisonComplete!==!0&&A.push("bridge comparison coverage is incomplete; unavailable and failed providers remain explicit in routeOptions"),h&&h.preparable!==!0&&A.push(`${h.source} is the overall quote winner but is quote-only and cannot become a prepared wallet action`),{kind:"bridge",fromChainId:r,toChainId:n,tokenIn:a,tokenOut:s,amountIn:String(o),slippageBps:l,best:h,routes:d,failed:w.filter(g=>g.status==="unavailable"),routeOptions:[...p,...w],winner:Ce(h),runnersUp:d.slice(1).map(Ce),coverage:i.coverage,comparisonComplete:i.comparisonComplete===!0,complete:i.comparisonComplete===!0,sourcesTried:i.coverage?.roster?.length??0,sourcesAnswered:d.length,improvementBps:b,spreadBasis:d.length>=2?`${d[0].source} vs ${d[1].source}`:null,rankedOn:"exact-base-unit-output",durations:d.filter(g=>g.meta.durationSeconds!=null).map(g=>({source:g.source,seconds:g.meta.durationSeconds})),warnings:A,note:d.length?`${d.length} of ${i.coverage?.roster?.length??0} canonical bridge providers returned exact base-unit output`:"no canonical bridge provider returned a usable route"}}var be={debridge:async({fromChainId:e,taker:t},r,n)=>{let a=Hr({provider:"debridge",preparable:!0,raw:n?.raw},{fromChainId:e,taker:t});if(!a.ok)throw new Error(a.reason);let{debridgePrepare:s}=await Promise.resolve().then(()=>(yt(),yr)),u=(await s(n.raw,{taker:t})).transaction,l=u.value??"0";if(!/^(?:0x[0-9a-fA-F]+|\d+)$/.test(String(l)))throw new Error("deBridge paired transaction value is not a canonical unsigned amount");return{transactions:[{chainId:Number(e),from:String(u.from),to:String(u.to),data:String(u.data),value:String(l),...u.gasLimit!=null||u.gas!=null?{gasLimit:u.gasLimit??u.gas}:{}}],destination:String(u.to),requiresApproval:null,amountOut:n.amountOut,minOut:null,durationSeconds:n.meta?.durationSeconds??null}},relay:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:a,taker:s,slippageBps:o},u)=>{let{relayPrepare:l}=await Promise.resolve().then(()=>(xe(),He)),i=await l({user:s,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(a),slippageBps:o},u);return{transactions:i.transactions||[],destination:i.destination??null,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.details?.currencyOut?.amount??null,minOut:i.quote?.details?.currencyOut?.minimumAmount??null,durationSeconds:i.quote?.details?.timeEstimate??null}},lifi:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:a,taker:s,isHolder:o,slippageBps:u},l)=>{let{lifiPrepare:i}=await Promise.resolve().then(()=>(De(),rr)),c=await i({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:a,fromAddress:s,isHolder:o,feeAction:"bridge",slippageBps:u},l);return{transactions:c.transaction?[c.transaction]:[],destination:c.transaction?.to??null,requiresApproval:c.requiresApproval??null,amountOut:c.quote?.estimate?.toAmount??null,minOut:c.quote?.estimate?.toAmountMin??null,durationSeconds:c.quote?.estimate?.executionDuration??null}}};function Fu(){return Object.keys(be)}async function qu(e,t={}){let{taker:r,fromChainId:n,toChainId:a,tokenIn:s,tokenOut:o}=e;if(!r)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(!X.test(r))throw new Error(`taker must be a valid 20-byte address, got "${r}"`);if(sa.has(r.toLowerCase()))throw new Error(`taker "${r}" is a placeholder/burn address. Bridging to it would send funds to an address nobody controls, on a chain where you cannot undo it.`);if(e.walletReviewOnly===!0&&(!X.test(String(s))||!X.test(String(o))))throw new Error("wallet-review bridge preparation requires exact origin and destination token addresses");let u=[n,a].find(S=>Fe(S));if(u!=null)return{ok:!1,unsupported:!0,reason:`${Se(u)?.name||`chain ${u}`} (${u}) is registered read-only: no bridge route source covers it. UNSUPPORTED, not a failed quote.`,comparison:null};let l=!Array.isArray(e.allowedSources),i=l?await pa(e,t):await gr(e,t);if(!i.best)return{ok:!1,reason:"no source returned a usable bridge route",comparison:i};let c=i.best.source,d=l?i.routes.find(S=>S.preparable===!0&&be[S.source]):i.best,h=e.source||d?.source;if(!h)return{ok:!1,reason:`${c} won the quote comparison, but no route has verified real unsigned transaction bytes, a bound destination, and an existing strict preparer.`,failureKind:"no-prepare-path",winner:c,comparison:i};let p=i.routes.find(S=>S.source===h);if(!p)return{ok:!1,reason:`source "${h}" returned no usable route`,comparison:i};let m=be[h];if(!m||l&&p.preparable!==!0){let S=i.routes.find(B=>be[B.source]&&(!l||B.preparable===!0)&&B.source!==h);return{ok:!1,reason:`${h} is quote-only for this response and cannot become a prepared wallet action. `+(S?`Next preparable route is ${S.source}; pass source:"${S.source}".`:"No route in this comparison has verified unsigned bytes and a strict preparer."),failureKind:"no-prepare-path",...S?{alternative:S.source}:{},winner:c,comparison:i}}i={...i,routeOptions:(i.routeOptions||[]).map(S=>({...S,selected:S.provider===h,quoteWinner:S.provider===c}))};let w;try{w=await m(e,t,p)}catch(S){let B=typeof S?.body=="string"?S.body:S?.body?JSON.stringify(S.body):"",q=[String(S?.message||S),B].filter(Boolean).join(" :: "),F=/allowance/i.test(q),D=!F&&/not enough|insufficient|balance/i.test(q),O=i.routes.find(T=>be[T.source]&&(!l||T.preparable===!0)&&T.source!==h);return{ok:!1,reason:F?`${h} will not build calldata until the token approval exists on-chain. Approve first, then prepare again. Underlying: ${q}`:D?`${h} refused to build: ${q}. Quoting works for any address; preparing needs the real funded wallet on chain ${n}.`:`${h} bridge prepare failed: ${q}`,failureKind:F?"approval-required-first":D?"taker-not-funded":"provider-error",...O?{alternative:O.source}:{},comparison:i}}let b=w.transactions||[];if(!b.length)return{ok:!1,reason:`${h} returned no executable transaction for this route`,failureKind:"provider-error",comparison:i};let A=b.filter(S=>S.chainId==null||Number(S.chainId)!==Number(n));if(A.length)return{ok:!1,reason:`${h} returned a transaction for chain ${A[0].chainId??"missing"} but the origin chain is ${n}. Refusing to hand over a mismatched artifact.`,failureKind:"chain-mismatch",comparison:i};if(b.find(S=>!X.test(String(S.from??""))||String(S.from).toLowerCase()!==r.toLowerCase()))return{ok:!1,reason:`${h} returned a transaction whose sender is not the exact wallet under review`,failureKind:"sender-mismatch",comparison:i};if(b.find(S=>!X.test(String(S.to??""))))return{ok:!1,reason:`${h} returned an invalid transaction target`,failureKind:"destination-not-bound",comparison:i};if(b.find(S=>!qr.test(String(S.data??""))))return{ok:!1,reason:`${h} returned incomplete unsigned calldata bytes`,failureKind:"provider-error",comparison:i};let I=w.requiresApproval??null,P=String(w.destination??"");if(!X.test(P)||!b.some(S=>String(S.to).toLowerCase()===P.toLowerCase()))return{ok:!1,reason:`${h} returned no safely bound bridge deposit destination`,failureKind:"destination-not-bound",comparison:i};if(I){if(String(I.amount)!==String(e.amountIn))return{ok:!1,reason:`${h} approval amount does not equal the exact input amount`,failureKind:"approval-not-exact",comparison:i};if(!X.test(String(I.token))||!X.test(String(I.spender)))return{ok:!1,reason:`${h} returned an incomplete approval bound`,failureKind:"approval-not-exact",comparison:i}}let x=e.driftToleranceBps??ia,_=null,y=null;if(w.amountOut!=null&&p.grossOut!=null)try{let S=BigInt(p.grossOut),B=BigInt(w.amountOut);S>0n&&(_=Number((B-S)*10000n/S),_<-x&&(y=`route moved ${(_/100).toFixed(2)}% against you since the comparison (tolerance ${(x/100).toFixed(2)}%). Re-compare before signing.`))}catch{}let k=[...y?[y]:[],...i.warnings||[],`Bridging is NOT atomic: the origin transaction succeeding does not mean funds arrived on chain ${a}. Expect ~${w.durationSeconds!=null?`${w.durationSeconds}s`:"minutes"} before the destination credits, and do not re-send if it is pending.`];b.length>1&&k.push(`This route needs ${b.length} transactions signed IN ORDER. Signing only the first leaves funds approved but not bridged.`);let E=e.walletReviewOnly===!0?xt(b):b,R=H({ok:!0,chosen:{source:h,wasWinner:h===c,netOut:p.netOut,grossOut:p.grossOut,gasUsd:p.gasUsd,feeUsd:p.feeUsd,feeCosts:Array.isArray(p.meta?.feeCosts)?p.meta.feeCosts:[],gasCosts:Array.isArray(p.meta?.gasCosts)?p.meta.gasCosts:[]},artifactKind:"unsigned-transaction-sequence",sender:r.toLowerCase(),fromChainId:Number(n),toChainId:Number(a),tokenIn:String(s),tokenOut:String(o),amountIn:String(e.amountIn),decimalsIn:Number.isInteger(e.decimalsIn)?Number(e.decimalsIn):null,decimalsOut:Number.isInteger(e.decimalsOut)?Number(e.decimalsOut):null,transactionCount:b.length,transactions:E,requiresApproval:I,amountOut:w.amountOut??null,minOut:w.minOut??null,durationSeconds:w.durationSeconds??null,slippageBps:i.slippageBps,routeOptions:i.routeOptions??[],winner:Ce(i.best),quoteWinner:Ce(i.best),coverage:i.coverage??null,comparisonComplete:i.comparisonComplete??null,complete:i.complete??null,destination:P,unsigned:!0,signedBy:"user-wallet",driftBps:_,warnings:k,runnersUp:i.routes.slice(1).map(Ce),comparison:{rankedOn:i.rankedOn,sourcesAnswered:i.sourcesAnswered,sourcesTried:i.sourcesTried,improvementBps:i.improvementBps,winner:c,selectedForPreparation:h,complete:i.comparisonComplete??null},note:`UNSIGNED. ${b.length} transaction(s) on chain ${n}, crediting chain ${a}. Verify every destination address before signing.`},{provider:"router",kind:"best-bridge",env:t.env,nowMs:t.nowMs,expiresAtMs:t.expiresAtMs});if(e.walletReviewOnly===!0&&R.prepareMac){let{prepareMac:S,...B}=R;return B}return R}export{qu as prepareBestBridgeRoute,Fu as supportedBridgePreparers};
2
+ `)};o("method",e),o("url",t),Object.keys(r||{}).map((l,i)=>({name:l.toLowerCase(),order:i,value:String(r[l])})).sort((l,i)=>l.name.localeCompare(i.name)||l.order-i.order).forEach((l,i)=>{o(`header-name-${i}`,l.name),o(`header-value-${i}`,l.value)}),o("body",a??"-");for(let l of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])o(`context-${l}`,n[l]??"-");return s.digest("hex")}function wn(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Bt):Math.min(250*2**e,Bt)+Math.floor(Math.random()*100)}function oe(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function Ze(e,t,r){return oe(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function le(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function Sn(e){return e?e.byteLength??e.length??0:0}async function En(e,t,{url:r,truncate:n=!1,onOversize:a}={}){if(t==null)return await e.text();let s=Number(e.headers?.get?.("content-length"));if(Number.isFinite(s)&&s>t&&(le(e),!n))throw Ze(r,`content-length ${s}`,t);let o=e.body?.getReader?.();if(!o){let d=await e.text(),h=Buffer.byteLength(d,"utf8");if(h>t){if(!n)throw Ze(r,`body ${h} bytes`,t);return Buffer.from(d,"utf8").subarray(0,t).toString("utf8")}return d}let u=[],l=0,i=!1;try{for(;;){let{value:d,done:h}=await o.read();if(h)break;if(d&&(u.push(Buffer.from(d)),l+=Sn(d),l>t)){i=!0;break}}}finally{if(i)try{await o.cancel()}catch{}try{o.releaseLock?.()}catch{}}if(i&&(typeof a=="function"&&a(),!n))throw Ze(r,`streamed ${l} bytes`,t);let c=Buffer.concat(u);return(i?c.subarray(0,t):c).toString("utf8")}function An(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function xn(e,{fetchImpl:t,method:r,headers:n,body:a,timeoutMs:s,lookupFn:o,realFetch:u,untrustedUrl:l=!1,maxResponseBytes:i=null,sameOriginRedirectsOnly:c=!1,importUndici:d,validateResponse:h,signal:p,redirectPolicy:m="follow",maxRedirects:w=Be}){let b=null,A=t,g=o?{lookupFn:o}:{};if(l&&!u&&!Xe(A))throw oe(`HTTP refused ${e}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let C=new AbortController,U=setTimeout(()=>C.abort(),s),I=p?Ut?Ut([p,C.signal]):p:C.signal,P=async(x,{status:_=null}={})=>{let y=await We(x,g);if(!y.ok)throw oe(_==null?`HTTP refused ${x}: ${y.error}`:`HTTP redirect to ${x} ${y.error}`,_==null?{}:{status:_});let k=new URL(x).hostname;if(u){if(b&&(await b.close(),b=null),!b)try{b=await Qe({requireUndici:!0,...d?{importUndici:d}:{}})}catch(E){throw oe(_==null?`HTTP refused ${x}: ${E?.message||E}`:`HTTP redirect to ${x} refused: ${E?.message||E}`,_==null?{}:{status:_})}b.pin(k,y.addresses),A=b.fetch}else Tt(A,k,y.addresses);return y};try{let x=String(e),_=Object.assign(Object.create(null),n||{});l&&await P(x);for(let y=0;y<=w;y+=1){let k=Object.assign(Object.create(null),{method:r,headers:_,body:a,signal:I,redirect:"manual",dispatcher:void 0}),E=await A(x,k);if((m==="error"||w===0)&&E.status>=300&&E.status<400)throw le(E),oe(`HTTP ${E.status} ${r} redirect refused`,{status:E.status,redirectRefused:!0});if(cn.has(E.status)){let B=c===!0&&r==="POST"&&[307,308].includes(E.status)&&Dt(r,a);if(r!=="GET"&&r!=="HEAD"&&!B){le(E);let O=new Error(`HTTP ${E.status} ${r} ${x} redirected non-idempotent request`);throw O.status=E.status,O}if(y===w)throw le(E),oe(`HTTP ${E.status} ${r} redirect budget exhausted`,{status:E.status,redirectRefused:!0});let q=E.headers?.get?.("location"),F;try{F=fn(q,x)}catch(O){throw le(E),O}let D=!mn(F,x);if(le(E),D&&r==="POST"){let O=new Error(`HTTP ${E.status} ${r} cross-origin redirect refused`);throw O.status=E.status,O}if(D&&c){let O=new Error(`HTTP ${E.status} ${r} cross-origin redirect refused`);throw O.status=E.status,O.retryable=!1,O}if(D&&(_=pn(_)),l)await P(F,{status:E.status});else if(D){let O=await We(F,g);if(!O.ok){let T=new Error(`HTTP redirect from ${x} ${O.error}`);throw T.status=E.status,T.retryable=!1,T}u&&O.addresses?.length&&(b||(b=await Qe(d?{importUndici:d}:{})),b&&(b.pin(new URL(F).hostname,O.addresses),A=b.fetch))}x=F;continue}if(typeof h=="function")try{await h(E,{url:x})}catch(B){throw le(E),oe(B?.message||String(B))}let R=await En(E,i,{url:x,onOversize:()=>C.abort()}),S=An(R);if(!E.ok){let B=new Error(`HTTP ${E.status} ${r} ${x}`);throw B.status=E.status,B.retryAfter=E.headers?.get?.("retry-after")??null,B.body=S??R.slice(0,300),B}return S??R}throw new Error(`HTTP redirect loop for ${e}`)}catch(x){if(C.signal.aborted&&!ye(p)){let _=x&&(typeof x=="object"||typeof x=="function")&&!te.isProxy(x)?x:null,y=_?Object.getOwnPropertyDescriptor(_,"oversize"):null;if(!(y&&Object.hasOwn(y,"value")&&y.value===!0))try{if(!_)throw new TypeError("unsafe rejection");Object.defineProperties(_,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let E=new Error("HTTP request timed out");throw Object.defineProperties(E,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),E}}throw x}finally{clearTimeout(U),b&&await b.close()}}async function v(e,t={}){if(t!=null&&typeof t!="object"&&typeof t!="function")throw new TypeError("HTTP options must be an object");if(t!=null&&te.isProxy(t))throw new TypeError("HTTP options must not be a proxy");let r=new Set(["body","dedupe","fetchImpl","headers","importUndici","lookupFn","maxRedirects","maxResponseBytes","method","redirectPolicy","retries","sameOriginRedirectsOnly","signal","timeoutMs","untrustedUrl","validateResponse"]);if(t!=null){if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("HTTP options contain unknown fields");for(let T of Object.getOwnPropertyNames(t)){let N=Object.getOwnPropertyDescriptor(t,T);if(!(T==="toJSON"&&N&&Object.hasOwn(N,"value")&&N.value===void 0)){if(!r.has(T))throw new TypeError("HTTP options contain unknown fields");if(!N||!N.enumerable||!Object.hasOwn(N,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=T=>{if(t==null||!Object.hasOwn(t,T))return;let N=Object.getOwnPropertyDescriptor(t,T);if(!N||!Object.hasOwn(N,"value"))throw new TypeError("HTTP options must contain own data properties");return N.value};if(typeof e!="string"||e.length===0||e.length>8192)throw new TypeError("HTTP URL must be a bounded string");let a=n("method");if(a!==void 0&&(typeof a!="string"||!/^[A-Za-z]+$/u.test(a)))throw new TypeError("HTTP method must be a string token");let s=n("timeoutMs");if(s!==void 0&&(!Number.isInteger(s)||s<1||s>12e4))throw new TypeError("HTTP timeoutMs must be a bounded integer");let o=n("retries");if(o!==void 0&&(!Number.isInteger(o)||o<0||o>10))throw new TypeError("HTTP retries must be a bounded integer");let u=n("redirectPolicy");if(u!==void 0&&u!=="follow"&&u!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let l=n("maxRedirects");if(l!==void 0&&(!Number.isInteger(l)||l<0||l>Be))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${Be}`);if(u==="error"&&l!==void 0&&l!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let i=u??"follow",c=i==="error"?0:l??Be;for(let T of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let N=n(T);if(N!==void 0&&typeof N!="boolean")throw new TypeError(`HTTP ${T} must be boolean`)}let d=n("maxResponseBytes");if(d!==void 0&&(!Number.isInteger(d)||d<1||d>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let h=n("signal");if(h!==void 0){if(te.isProxy(h)||!(h instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{ye(h)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let T of["importUndici","lookupFn","validateResponse"]){let N=n(T);if(N!==void 0&&typeof N!="function")throw new TypeError(`HTTP ${T} must be a function`)}let p=n("fetchImpl"),m=p||globalThis.fetch;if(typeof m!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let w=s??12e3,b=(a||"GET").toUpperCase(),A=n("headers"),g=dn(A),C=Object.assign(Object.create(null),g);Object.keys(C).some(T=>T.toLowerCase()==="accept")||(C.Accept="application/json");let U=n("body");U!=null&&typeof U!="string"&&(Object.keys(C).find(N=>N.toLowerCase()==="content-type")||(C["Content-Type"]="application/json"),U=ln(U));let I=o??tn,P=n("lookupFn"),x=!p,_=n("untrustedUrl")===!0,y=n("sameOriginRedirectsOnly")===!0,k=n("importUndici"),E=n("validateResponse"),R=h,S=d??null,B=async()=>{let T;for(let N=0;N<=I;N++){R&&on.call(R);let j=Te("http");try{let z=await xn(e,{fetchImpl:m,method:b,headers:C,body:U,timeoutMs:w,lookupFn:P,realFetch:x,untrustedUrl:_,maxResponseBytes:S,sameOriginRedirectsOnly:y,importUndici:k,validateResponse:E,signal:R,redirectPolicy:i,maxRedirects:c});return j?.("succeeded"),z}catch(z){T=z;let J=de=>{if(!z||typeof z!="object"&&typeof z!="function"||te.isProxy(z))return;let ne=Object.getOwnPropertyDescriptor(z,de);return ne&&Object.hasOwn(ne,"value")?ne.value:void 0},ce=J("status");j?.("failed",ce);let Ie=J("oracleTimeout")===!0||J("name")==="AbortError"||J("name")==="TimeoutError"||ye(R),ke=new Set([408,425,429]),f=J("retryable")===!1?!1:ce!=null?ke.has(ce)||en.has(ce)&&Rt.has(b):!Ie&&Rt.has(b);if(N===I||!f)throw z;let M=wn(N,J("retryAfter")),W=Te("retry"),K=!1;try{R?await new Promise((de,ne)=>{let Oe,we=()=>{clearTimeout(Oe),_t.call(R,"abort",we),ne(sn(R)||new DOMException("Aborted","AbortError"))};if(ye(R)){we();return}Oe=setTimeout(()=>{_t.call(R,"abort",we),de()},M),an.call(R,"abort",we,{once:!0}),ye(R)&&we()}):await yn(M),K=!0}finally{W?.(K?"succeeded":"failed")}}}throw T};if(!(n("dedupe")!==!1&&!R&&Dt(b,U)))return B();let F=bn(b,e,C,{untrustedUrl:_,maxResponseBytes:S,sameOriginRedirectsOnly:y,redirectPolicy:i,maxRedirects:c,timeoutMs:w,retries:I,fetchImpl:Re(m),realFetch:x,lookupFn:Re(P),importUndici:Re(k),validateResponse:Re(E)},U),D=Je.get(F);if(D){let T=Te("shared");try{let N=await D;return T?.("succeeded"),N}catch(N){throw T?.("failed"),N}}let O=B().finally(()=>Je.delete(F));return Je.set(F,O),O}var en,Rt,tn,Bt,rn,nn,on,an,_t,Ut,ye,sn,cn,Be,Ta,ee,Je,Pt,Lt,hn,gn,yn,$=V(()=>{Ot();Nt();en=new Set([408,425,429,500,502,503,504]),Rt=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),tn=2,Bt=4e3,rn=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,nn=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,on=AbortSignal.prototype.throwIfAborted,an=EventTarget.prototype.addEventListener,_t=EventTarget.prototype.removeEventListener,Ut=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,ye=e=>e?rn.call(e):!1,sn=e=>e?nn.call(e):void 0,cn=new Set([301,302,303,307,308]),Be=3,Ta=64*1024,ee=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});Je=new Map,Pt=new WeakMap,Lt=1;hn=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),gn=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);yn=e=>new Promise(t=>setTimeout(t,e))});import{readFileSync as vn}from"node:fs";import{homedir as Cn}from"node:os";import{join as _e}from"node:path";function In(){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){let r=(process.env.ORACLE_EXEC_ENV_FILE||"").trim();return r?[r]:[]}let e=(process.env.ORACLE_EXEC_ENV_FILE||process.env.MAD_EXEC_ENV_FILE||"").trim(),t=Cn();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||_e(t,".config","oracle")).trim();return[e,_e(r,"exec.env")].filter(Boolean)}return[e,_e(t,".config","oracle","exec.env"),_e(t,".config","mad-desk","exec.env")].filter(Boolean)}function Ft(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let a of In())try{let s=vn(a,"utf8"),o=s.match(new RegExp(`^${t}=(.*)$`,"m"))||s.match(new RegExp(`^${r}=(.*)$`,"m"));if(o&&(n=o[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}var qt=V(()=>{});var Mt=V(()=>{});import{createHash as kn,createHmac as jt,timingSafeEqual as On}from"node:crypto";function Pe(e){return Array.isArray(e)?`[${e.map(Pe).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Pe(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Vt(e,{required:t=!1}={}){try{return Ft(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function tt(e){let{signature:t,...r}=e;return r}function zt(e,{secret:t}={}){let r=Vt(t);return r?{...e,signature:jt("sha256",r).update(Pe(tt(e))).digest("hex")}:e}function Tn(e){let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(t)||t.length<10||t.length%2!==0)throw new Error("auto-slippage calldata must be even-length hex with a selector");return kn("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function ae(e,{chainId:t,venue:r,data:n,secret:a}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");if(Number(e.chainId)!==Number(t))throw new Error("auto-slippage guard chain mismatch");if(String(e.venue).toLowerCase()!==String(r||"").toLowerCase())throw new Error("auto-slippage guard venue mismatch");let s=Vt(a);if(s){let p=jt("sha256",s).update(Pe(tt(e))).digest("hex");if(!Nn(e.signature,p))throw new Error("auto-slippage guard signature mismatch \u2014 refusing to bind a guard this Oracle did not issue")}let o=Number(e.selectedBps),u=Number(e.capBps);if(!Number.isInteger(o)||o<0||o>Ue||!Number.isInteger(u)||u<0||u>Ue||o>u)throw new Error("auto-slippage guard bounds are invalid");let l=BigInt(e.quoteAmountOut??0),i=BigInt(e.minAmountOut??0);if(l<=0n||i<=0n)throw new Error("auto-slippage guard amounts must be positive");let c=l*BigInt(1e4-o),d=c/10000n;if(c%10000n!==0n&&(d+=1n),i<d)throw new Error("auto-slippage guard is under-protected relative to its quote");let h=_n(n);if(h!=null&&h!==i)throw new Error(`auto-slippage: calldata encodes floor ${h}, not the guard floor ${i} \u2014 refusing to bind`);return zt({...tt(e),calldataHash:Tn(n)},{secret:a})}function Nn(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:On(r,n)}function et(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function Rn(e){let t=e==null?Ue:Number(e);if(!Number.isInteger(t)||t<0)throw new Error("auto-slippage cap must be a non-negative integer bps value");return Math.min(t,Ue)}function se({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:a}={}){let s=et(e,0),o=s>0?s>=25e4?5:s>=1e5?10:s>=5e4?20:s>=1e4?40:70:n?30:10,u=Math.min(60,Math.abs(et(t,0))*2),l=Math.min(40,Math.floor(Math.max(0,et(r,0))/5e3)*5),i=Math.max(25,Math.ceil(20+o+u+l)),c=Rn(a);return{mode:"auto",requiredBps:i,selectedBps:Math.min(i,c),capBps:c,executable:i<=c}}function Bn({chainId:e,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:a=0,quoteAgeMs:s=0,crossChain:o=!1,requestedCapBps:u,quotedAtMs:l=Date.now(),ttlMs:i=Ht,secret:c}={}){let d=BigInt(r??0);if(d<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let h=se({liquidityUsd:n,priceChange5m:a,quoteAgeMs:s,crossChain:o,requestedCapBps:u});if(!h.executable)throw new Error(`auto-slippage requires ${h.requiredBps} bps above hard/requested cap ${h.capBps}; route blocked`);let p=Number(l);if(!Number.isFinite(p))throw new Error("auto-slippage: quotedAtMs must be a finite number");let m=Math.min(3e4,Math.max(1e3,Number(i)||Ht)),w=d*BigInt(1e4-h.selectedBps),b=w/10000n;if(w%10000n!==0n&&(b+=1n),b>d&&(b=d),d>0n&&b<=0n)throw new Error(`auto-slippage: quote ${d} is too small to express a ${h.selectedBps} bps floor without rounding to zero`);let A=Number((d-b)*10000n/(d===0n?1n:d));if(A>h.capBps)throw new Error(`auto-slippage: realised floor implies ${A} bps, above cap ${h.capBps} \u2014 refusing to issue a guard weaker than advertised`);return zt({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:d.toString(),minAmountOut:b.toString(),requiredBps:h.requiredBps,selectedBps:h.selectedBps,capBps:h.capBps,quotedAtMs:p,expiresAtMs:p+m},{secret:c})}function _n(e){let t=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(t)||t.length<10||t.length%2!==0)return null;let r=t.slice(0,10).toLowerCase(),n=[];for(let s=10;s+64<=t.length;s+=64)n.push(t.slice(s,s+64));let a=s=>n[s]==null?null:BigInt("0x"+n[s]);switch(r){case"0x414bf389":return a(6);case"0x04e45aaf":return a(5);case"0xc04b8d59":{let s=a(0);if(s==null)return null;let o=Number(s)/32;return!Number.isInteger(o)||o<0?null:a(o+4)}case"0xb858183f":{let s=a(0);if(s==null)return null;let o=Number(s)/32;return!Number.isInteger(o)||o<0?null:a(o+3)}case"0xa026383e":return a(6);case"0x38ed1739":case"0x5c11d795":return a(1);case"0x7ff36ab5":case"0xb6f9de95":return a(0);case"0x18cbafe5":case"0x791ac947":return a(1);default:return null}}function Q(e,{chainId:t,venue:r,amountOut:n,liquidityUsd:a,priceChange5m:s,crossChain:o,requestedCapBps:u,quotedAtMs:l=Date.now(),ttlMs:i}={}){let c=Bn({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:a,priceChange5m:s,crossChain:o,requestedCapBps:u,quotedAtMs:l,ttlMs:i});return{...e,autoSlippage:c,amountOutMinimum:c.minAmountOut}}var Ue,Ht,re=V(()=>{qt();Mt();Ue=100,Ht=2e4});var pe,Le=V(()=>{pe="0x000000000000000000000000000000000000dEaD"});import{createHash as Un,createHmac as Pn,timingSafeEqual as ja}from"node:crypto";function rt(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(rt).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${rt(e[r])}`).join(",")}}`}function Kt(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Gt(e=process.env){return Kt(process.env)||Kt(e)}function Fn(e){let{prepareHash:t,prepareMac:r,note:n,...a}=e||{};return a}function qn(e){let t=Fn(e);return Un("sha256").update(rt(t)).digest("hex")}function Mn(e,t=Gt()){return t?Pn("sha256",t).update(String(e)).digest("hex"):""}function H(e,{provider:t,kind:r,env:n=process.env,nowMs:a=Date.now(),expiresAtMs:s}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let o=Object.prototype.hasOwnProperty.call(e,"oraclePrepared");if(o&&typeof e.oraclePrepared!="boolean")throw new Error("stampPrepared: oraclePrepared must be boolean");let u={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1,oraclePrepared:o?e.oraclePrepared:!0};if(!u.provider)throw new Error("stampPrepared: provider required");if(!u.kind)throw new Error("stampPrepared: kind required");let l=Number(a),i=s==null?l+$n:Number(s),c=i-l;if(!Number.isSafeInteger(l)||!Number.isSafeInteger(i)||c<=0||c>Dn)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let h={...u,preparedAt:l,expiresAt:i,prepareVersion:Ln},p=qn(h),m=Gt(n),w=m?Mn(p,m):void 0,b={...h,prepareHash:p};return w&&(b.prepareMac=w),b}var Ln,$n,Dn,Y=V(()=>{Ln=2,$n=300*1e3,Dn=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Contract as Hn,JsonRpcProvider as jn}from"ethers";function Qn(e){return Wn.test(String(e||""))}async function Wt(e,{contract:t=Vn,rpc:r=Kn,chainId:n=zn,balanceOf:a}={}){if(!Qn(e))throw new Error("invalid-address");if(a)return BigInt(await a(e));let s=new jn(r,n,{staticNetwork:!0}),o=new Hn(t,Gn,s);return BigInt(await o.balanceOf(e))}var Vn,zn,Kn,Gn,Wn,Qt=V(()=>{Vn="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",zn=999,Kn="https://rpc.hyperliquid.xyz/evm",Gn=["function balanceOf(address owner) view returns (uint256)"],Wn=/^0x[a-fA-F0-9]{40}$/});import{existsSync as Yn,readFileSync as Xn,lstatSync as Jn}from"node:fs";import{homedir as Yt}from"node:os";import{join as nt}from"node:path";function to(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(Xt,t)?Xt[t]:eo}function so(e=process.env){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){if(e[Jt])return String(e[Jt]);let t=e.ORACLE_CONFIG_DIR||nt(Yt(),".config","oracle");return nt(t,"fee-recipient")}return nt(Yt(),".config","oracle","fee-recipient")}function io(e=process.env){try{let t=so(e);if(!Yn(t)||Jn(t).isSymbolicLink())return"";let r=Xn(t,"utf8").trim().toLowerCase();return/^0x[a-f0-9]{40}$/.test(r)?r:""}catch{return""}}function co(e,{fallback:t=0}={}){if(e==null)return t;if(String(e).trim()==="")return 0;let r=Number(e);return!Number.isFinite(r)||r<=0?0:Math.min(Math.floor(r),Zn)}function uo({env:e=process.env,action:t="swap",admin:r=!1}={}){let n=String(e[no]||"").trim(),a=String(e[oo]||ao).trim();if(r===!0)return{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"admin-oracle"};let s=to(t),o=co(e[ro],{fallback:n?s:0}),u=Math.min(o,s);if(!u)return{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"not-configured"};if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"no-recipient"};let l=io(e);return!l||l!==n.toLowerCase()?{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"recipient-not-pinned"}:{bps:u,recipient:n,integrator:a,action:t,applies:!0,reason:"configured"}}async function ot({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={},admin:a=!1}={}){let s=uo({env:t,action:r,admin:a});if(a===!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 Wt(o,n))>0n?{...s,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...s,holderVerificationStatus:"non-holder"}}catch{return{...s,holderVerificationStatus:"unavailable"}}}function Zt(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 er(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}var Zn,eo,Xt,ro,no,oo,Jt,ao,$e=V(()=>{Qt();Zn=100,eo=5,Xt=Object.freeze({swap:5,bridge:5,perps:0,nft:0});ro="ORACLE_INTEGRATOR_FEE_BPS",no="ORACLE_INTEGRATOR_FEE_RECIPIENT",oo="ORACLE_INTEGRATOR_ID",Jt="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",ao="oracle"});var rr={};je(rr,{LIFI_API:()=>tr,lifiChains:()=>mo,lifiHealth:()=>it,lifiPrepare:()=>fo,lifiQuote:()=>me});function st(e={}){return(e.baseUrl||process.env.LIFI_API_URL||tr).replace(/\/$/,"")}function po(e){let t=String(e||at).toLowerCase();return t===at.toLowerCase()||t===lo}function fe(e,t){let r=String(e||"").trim();if(!/^0x[0-9a-fA-F]{40}$/.test(r))throw new Error(`lifi: ${t} must be a 20-byte address`);return r.toLowerCase()}async function it(e={}){let t=await v(`${st(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3}),r=Array.isArray(t)?t.length:t?.chains?.length||0;return{ok:r>0,chainCount:r}}async function me(e={},t={}){let{fromChain:r,toChain:n=r,fromToken:a=at,toToken:s,fromAmount:o,fromAddress:u=pe}=e;if(r==null||!s||!o)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let l=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:a,toToken:s,fromAmount:String(o),fromAddress:u}),i=se({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!i.executable)throw new Error(`lifi: route requires ${i.requiredBps} bps above cap ${i.capBps}`);l.set("slippage",String(i.selectedBps/1e4));let c=await ot({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[b,A]of Object.entries(er(c)))l.set(b,A);let d=await v(`${st(t)}/quote?${l}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),h=d?.estimate?.toAmount||d?.toAmount;if(!h)return{...d,autoSlippagePolicy:i,oracleFee:c};let p=d?.transactionRequest?.to||d?.estimate?.approvalAddress||"lifi",m=Q(d,{chainId:Number(r),venue:p,amountOut:h,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),w=d?.estimate?.toAmountMin||d?.toAmountMin;if(w!=null&&BigInt(w)<BigInt(m.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...m,oracleFee:c}}async function fo(e={},t={}){let r=await me(e,t),n=r?.transactionRequest;if(!n?.to||!n?.data)throw new Error("lifi: quote did not return an executable transactionRequest");if(["nonce","authorizationList","maxFeePerBlobGas","blobVersionedHashes","blobs","kzg","signature","rawTransaction","signedTransaction","r","s","v"].find(d=>n[d]!=null))throw new Error("lifi: unsupported transaction authority");if(n.type!=null){let d=String(n.type).trim().toLowerCase();if(!/^(?:0x[0-9a-f]+|\d+)$/.test(d)||BigInt(d)>2n)throw new Error("lifi: unsupported transaction authority")}let s=Number(e.fromChain);if(n.chainId==null)throw new Error("lifi: transaction missing chain authority");if(Number(n.chainId)!==s)throw new Error("lifi: transaction chain mismatch");let o=e.fromAddress?fe(e.fromAddress,"transaction sender"):n.from?fe(n.from,"transaction sender"):null;if(!o)throw new Error("lifi: transaction missing sender authority");if(n.from&&fe(n.from,"transaction sender")!==o)throw new Error("lifi: transaction sender mismatch");let u=fe(n.to,"transaction target"),l=String(n.data);if(!/^0x(?:[0-9a-fA-F]{2})+$/.test(l))throw new Error("lifi: transaction calldata must be non-empty hex bytes");let i=String(n.value??"0x0");if(!/^(?:0x[0-9a-fA-F]+|\d+)$/.test(i))throw new Error("lifi: transaction value must be an unsigned integer string");let c=null;if(!po(e.fromToken)){let d=r?.estimate?.approvalAddress||r?.approvalAddress;if(!d)throw new Error("lifi: ERC20 route missing approvalAddress");let h=r?.action?.fromToken?.address||r?.estimate?.fromToken?.address||e.fromToken;c={token:fe(h,"approval token"),spender:fe(d,"approval spender"),amount:String(e.fromAmount)}}return H({provider:"lifi",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:s,quote:r,autoSlippage:r.autoSlippage,requiresApproval:c,transaction:{chainId:s,from:o,to:u,data:l,value:i,...n.gasLimit!=null?{gasLimit:n.gasLimit}:{},slippageGuard:ae(r.autoSlippage,{chainId:s,venue:u,data:l})}},{provider:"lifi",kind:"lifi-tx",env:t.env,nowMs:t.nowMs,expiresAtMs:t.expiresAtMs})}async function mo(e={}){return v(`${st(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var tr,at,lo,De=V(()=>{$();re();Le();Y();$e();tr="https://li.quest/v1";at="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",lo="0x0000000000000000000000000000000000000000"});var He={};je(He,{ACROSS_API:()=>sr,HOP_API:()=>ir,RANGO_API:()=>ur,RELAY_API:()=>cr,acrossHealth:()=>dt,acrossSuggestedFees:()=>qe,hopHealth:()=>pt,hopQuote:()=>Me,rangoQuote:()=>ht,relayHealth:()=>mt,relayPrepare:()=>No,relayQuote:()=>Ae});async function dt(e={}){try{return{ok:!0,estimatedFillTimeSec:(await qe({token:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",destinationToken:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",originChainId:1,destinationChainId:42161,amount:"1000000000000000"},e)).estimatedFillTimeSec}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function qe(e={},t={}){let{token:r,destinationToken:n=r,originChainId:a,destinationChainId:s,amount:o}=e;if(!r||a==null||s==null||!o)throw new Error("acrossSuggestedFees requires token, originChainId, destinationChainId, amount");let u=new URLSearchParams({token:r,destinationToken:n,originChainId:String(a),destinationChainId:String(s),amount:String(o)}),l=(t.baseUrl||process.env.ACROSS_API_URL||sr).replace(/\/$/,"");return v(`${l}/suggested-fees?${u}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function pt(e={}){try{let t=await Me({amount:"1000000000000000",token:"ETH",fromChain:"ethereum",toChain:"arbitrum",slippage:.5},e);return{ok:!0,estimatedRecieved:t.estimatedRecieved||t.estimatedReceived}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function Me(e={},t={}){let{amount:r,token:n="ETH",fromChain:a="ethereum",toChain:s="arbitrum"}=e;if(!r)throw new Error("hopQuote requires amount");let o=e.slippage==null?void 0:Math.round(Number(e.slippage)*100),u=se({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:a!==s,requestedCapBps:e.maxSlippageBps??e.slippageBps??o});if(!u.executable)throw new Error(`hop: route requires ${u.requiredBps} bps above cap ${u.capBps}`);let l=new URLSearchParams({amount:String(r),token:n,fromChain:a,toChain:s,slippage:String(u.selectedBps/100)}),i=(t.baseUrl||process.env.HOP_API_URL||ir).replace(/\/$/,""),c=await v(`${i}/quote?${l}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),d=c?.estimatedRecieved||c?.estimatedReceived;return d?Q(c,{chainId:Number(e.originChainId||e.chainId||Io[a]||0),venue:c?.tx?.to||"hop",amountOut:d,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:a!==s,requestedCapBps:e.maxSlippageBps??e.slippageBps??o}):{...c,autoSlippagePolicy:u}}function lr(e){return(e?.steps||[]).flatMap(t=>(t?.items||[]).filter(r=>r?.data?.to&&r?.data?.data).map(r=>({stepId:t.id,...r.data})))}function Oo(e){let t=String(e?.data??"").toLowerCase();if(!t.startsWith(ft))return null;if(!/^0x[0-9a-f]{136}$/.test(t))throw new Error("relay: malformed ERC20 approval calldata");return{spender:`0x${t.slice(34,74)}`,amount:BigInt(`0x${t.slice(74,138)}`).toString()}}function To(e){return lr(e).find(t=>!String(t.data).toLowerCase().startsWith(ft))??null}async function mt(e={}){try{let t=await Ae({user:pe,originChainId:1,destinationChainId:8453,originCurrency:"0x0000000000000000000000000000000000000000",destinationCurrency:"0x0000000000000000000000000000000000000000",amount:"1000000000000000",tradeType:"EXACT_INPUT"},e);return{ok:!0,hasSteps:Array.isArray(t.steps),stepCount:t.steps?.length||0}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function Ae(e={},t={}){let{user:r=pe,originChainId:n,destinationChainId:a,originCurrency:s="0x0000000000000000000000000000000000000000",destinationCurrency:o="0x0000000000000000000000000000000000000000",amount:u,tradeType:l="EXACT_INPUT"}=e;if(n==null||a==null||!u)throw new Error("relayQuote requires originChainId, destinationChainId, amount");let i=se({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(a),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!i.executable)throw new Error(`relay: route requires ${i.requiredBps} bps above cap ${i.capBps}`);let c=(t.baseUrl||process.env.RELAY_API_URL||cr).replace(/\/$/,""),d=await v(`${c}/quote`,{method:"POST",body:{user:r,originChainId:Number(n),destinationChainId:Number(a),originCurrency:s,destinationCurrency:o,amount:String(u),tradeType:l,slippageTolerance:String(i.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),h=d?.details?.currencyOut?.amount;if(!h||!/^\d+$/.test(String(h)))return{...d,autoSlippagePolicy:i};let p=To(d);return Q(d,{chainId:Number(n),venue:p?.to||"relay",amountOut:h,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(a),requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function No(e={},t={}){let r=await Ae(e,t),n=Number(e.originChainId),a=lr(r);if(!a.length)throw new Error("relay: quote returned no executable transaction items");let s=String(r?.autoSlippage?.venue||"").toLowerCase(),o=[],u=[];for(let c of a){if(c.chainId!=null&&Number(c.chainId)!==n)throw new Error("relay: transaction chain mismatch");if(e.user&&c.from&&String(c.from).toLowerCase()!==String(e.user).toLowerCase())throw new Error("relay: transaction sender mismatch");let d=Oo(c);d?o.push({tx:c,approval:d}):u.push(c)}if(!u.length)throw new Error("relay: quote returned no bridge deposit transaction");if(u.some(c=>String(c.to).toLowerCase()!==s))throw new Error("relay: route execution target is not safely bound");if(o.length>1)throw new Error("relay: multiple token approvals are not supported");let l=null;if(o.length===1){let{tx:c,approval:d}=o[0],h=String(e.originCurrency||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(h)||h===ko)throw new Error("relay: native route returned an ERC20 approval");if(String(c.to).toLowerCase()!==h)throw new Error("relay: approval token mismatch");if(d.amount!==String(e.amount))throw new Error("relay: approval amount must equal the exact input amount");if(!u.some(p=>String(p.to).toLowerCase()===d.spender))throw new Error("relay: approval spender does not match the bridge target");l={token:h,spender:d.spender,amount:String(e.amount)}}let i=a.map(c=>({chainId:n,from:c.from||e.user,to:c.to,data:c.data,value:c.value??"0x0",...c.gasLimit!=null||c.gas!=null?{gasLimit:c.gasLimit??c.gas}:{},...String(c.data).toLowerCase().startsWith(ft)?{}:{slippageGuard:ae(r.autoSlippage,{chainId:n,venue:c.to,data:c.data})}}));return H({provider:"relay",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:r,autoSlippage:r.autoSlippage,requiresApproval:l,destination:s,transactions:i},{provider:"relay",kind:"relay-tx",env:t.env,nowMs:t.nowMs,expiresAtMs:t.expiresAtMs})}async function ht({from:e,to:t,amount:r,slippage:n=1,enableCentralizedSwappers:a=!1}={},s={}){if(!e||!t||!r)throw new Error("rangoQuote requires from, to, amount");let o=s.env??process.env,u=s.rangoApiKey||o.RANGO_API_KEY;if(!u)throw new Error("rango: RANGO_API_KEY is required");let l=new URLSearchParams({from:e,to:t,amount:String(r),slippage:String(n),enableCentralizedSwappers:a?"true":"false",apiKey:u}),i=(s.rangoBaseUrl||process.env.RANGO_API_URL||ur).replace(/\/$/,""),c;try{c=await v(`${i}/basic/quote?${l}`,{fetchImpl:s.fetchImpl,timeoutMs:s.timeoutMs??2e4,retries:s.retries})}catch(d){let h=Number.isInteger(d?.status)?` (HTTP ${d.status})`:"";throw new Error(`rango: request failed${h}`)}if(c?.error||c?.resultType&&c.resultType!=="OK"){let d=String(c?.error||c.resultType).split(u).join("[redacted]").split(encodeURIComponent(u)).join("[redacted]").slice(0,160);throw new Error(`rango: ${d}`)}return{amountOut:c?.route?.outputAmount,feeUsd:c?.route?.feeUsd??null,estimatedTime:c?.route?.estimatedTimeInSeconds}}var sr,ir,cr,ur,Io,ft,ko,xe=V(()=>{$();re();Le();Y();sr="https://across.to/api",ir="https://api.hop.exchange/v1",cr="https://api.relay.link",ur="https://api.rango.exchange",Io={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453};ft="0x095ea7b3",ko="0x0000000000000000000000000000000000000000"});var yr={};je(yr,{DEBRIDGE_API:()=>br,debridgeHealth:()=>wt,debridgePrepare:()=>Ho,debridgeQuote:()=>bt});function wr(e={}){return(e.baseUrl||process.env.DEBRIDGE_API_URL||br).replace(/\/$/,"")}function gt(e,t=200){return String(e?.message||e||"unknown error").slice(0,t)}function Mo(e){return typeof e?.to=="string"&&e.to.length>0&&/^0x(?:[0-9a-fA-F]{2})+$/.test(String(e.data||""))}async function bt({srcChainId:e,srcChainTokenIn:t,srcChainTokenInAmount:r,dstChainId:n,dstChainTokenOut:a,taker:s,slippage:o=100,affiliateFeePercent:u="0"}={},l={}){if(!e||!n||!t||!a||!r)return{error:"debridge quote requires srcChainId, dstChainId, srcChainTokenIn, dstChainTokenOut, srcChainTokenInAmount"};try{let i=new URLSearchParams({srcChainId:String(e),srcChainTokenIn:t,srcChainTokenInAmount:String(r),dstChainId:String(n),dstChainTokenOut:a,dstChainTokenOutAmount:"auto",slippage:String(o),affiliateFeePercent:String(u)});s&&(i.set("dstChainTokenOutRecipient",s),i.set("srcChainOrderAuthorityAddress",s),i.set("dstChainOrderAuthorityAddress",s));let c=await v(`${wr(l)}/dln/order/create-tx?${i}`,{fetchImpl:l.fetchImpl,timeoutMs:l.timeoutMs??2e4,retries:l.retries,headers:l.headers});return c?.error?{error:gt(c.error)}:{estimation:c?.estimation??{},order:c?.order??{},fixFee:c?.fixFee??c?.estimation?.fixFee??"0",tx:c?.tx??null,walletBinding:s?{dstChainTokenOutRecipient:s,srcChainOrderAuthorityAddress:s,dstChainOrderAuthorityAddress:s}:null}}catch(i){return{error:gt(i)}}}async function wt(e={}){try{let t=await v(`${wr(e)}/supported-chains-info`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??15e3,retries:e.retries}),r=Array.isArray(t)?t:t?.chains,n=Array.isArray(r)?r.length:0;return{ok:n>0,chainCount:n}}catch(t){return{ok:!1,error:gt(t,160)}}}async function Ho(e,{taker:t}={}){if(!t)throw new Error("debridge prepare requires taker address");if(!Mo(e?.tx))throw new Error("debridge prepare requires paired unsigned transaction bytes");let r=e?.walletBinding,n=String(t).toLowerCase();if(!r||[r.dstChainTokenOutRecipient,r.srcChainOrderAuthorityAddress,r.dstChainOrderAuthorityAddress].some(a=>String(a||"").toLowerCase()!==n))throw new Error("debridge prepare wallet binding does not match taker");if(e.tx.from&&String(e.tx.from).toLowerCase()!==n)throw new Error("debridge prepare transaction sender does not match taker");return H({provider:"debridge",kind:"debridge-tx",calldataReady:!0,requiresUserSignature:!0,transaction:e.tx,quote:e},{provider:"debridge",kind:"debridge-tx"})}var br,yt=V(()=>{$();Y();br="https://dln.debridge.finance/v1.0"});var ha=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),Ve=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),ze=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"});var Z=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"});var vt=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}};function Ct(e){let{source:t,amountOut:r,minOut:n=null,gasUsd:a=null,feeUsd:s=null,feeIncludedInAmountOut:o=!1,oracleFeeBps:u=0,estimatedGas:l=null,liquidityUsd:i=null,error:c=null,executionReady:d=!1,meta:h={}}=e||{};if(c||r==null)return{source:t,quality:Z.FAILED,amountOut:null,error:c||"no amountOut returned"};let p=vt(r);if(p==null||p<=0n)return{source:t,quality:Z.FAILED,amountOut:null,error:"non-positive amountOut"};let m=Number(u);return{source:t,quality:a==null?Z.NO_GAS:Z.FULL,amountOut:p.toString(),minOut:vt(n)?.toString()??null,gasUsd:a,feeUsd:s,feeIncludedInAmountOut:o===!0,oracleFeeBps:Number.isFinite(m)&&m>0?Math.floor(m):0,estimatedGas:l==null?null:String(l),liquidityUsd:i==null?null:Number(i),executionReady:d,meta:h}}function It(e,{destPriceUsd:t=null,destDecimals:r=null,liquidityFirst:n=!0,liquidityBandBps:a=50,gasPriceWei:s=null,nativePriceUsd:o=null}={}){let u=e.filter(y=>y.quality!==Z.FAILED),l=e.filter(y=>y.quality===Z.FAILED),i=t!=null&&t>0&&r!=null&&r>=0,c=Number(s),d=Number(o),h=Number.isFinite(c)&&c>0&&Number.isFinite(d)&&d>0,p=u.map(y=>{let k=BigInt(y.amountOut),E=0n,R=!1,S=!1,B=BigInt(y.oracleFeeBps??0),q=B>0n?k*B/10000n:0n;if(i){let O=y.gasUsd,T=Number(y.meta?.gasUnits??y.estimatedGas);if(O==null&&h&&Number.isFinite(T)&&T>0){let j=T*c/1e18*d;Number.isFinite(j)&&j>=0&&(O=j,S=!0)}let N=(O??0)+(y.feeIncludedInAmountOut?0:y.feeUsd??0);if(N>0){let j=N/t*10**r;Number.isFinite(j)&&j>=0&&(E=BigInt(Math.floor(j)),R=!0)}else O===0&&(R=!0)}let F=E+q,D=k>F?k-F:0n;return{...y,grossOut:k.toString(),netOut:D.toString(),costInDest:E.toString(),oracleFeeInDest:q.toString(),costAccounted:R,gasEstimated:S}}),m=Number(a)>0?Number(a):0,w=p.reduce((y,k)=>BigInt(k.netOut)>y?BigInt(k.netOut):y,0n),b=y=>w>0n?Number((w-BigInt(y))*10000n/w):0,A=[],g=(y,k)=>{let E=BigInt(y.netOut),R=BigInt(k.netOut);return E!==R?R>E?1:-1:String(y.source).localeCompare(String(k.source))},C=p.slice().sort(g)[0]??null;p.sort((y,k)=>{let E=b(y.netOut)<=m?0:1,R=b(k.netOut)<=m?0:1;if(n&&m>0&&E!==R)return E-R;if(n&&m>0){let S=y.liquidityUsd??-1,B=k.liquidityUsd??-1;if(S!==B)return B-S}return g(y,k)}),n&&m>0&&C&&p[0]&&p[0].source!==C.source&&A.push(`liquidity-first: chose ${p[0].source} (liquidity $${p[0].liquidityUsd??"unknown"}) over best-price ${C.source} within ${m} bps`);let U=p.filter(y=>!y.costAccounted).map(y=>y.source);i?U.length&&A.push(`gas not reported by: ${U.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):A.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let I=p[0];if(i&&I&&I.costAccounted===!1){let y=p.find(k=>k.costAccounted&&b(k.netOut)<=m);y&&A.push(`winner ${I.source} has UNMEASURED gas; gas-measured ${y.source} is within ${m} bps and may net more once ${I.source}'s real gas is paid \u2014 prefer it if unsure.`)}let P=p.filter(y=>y.gasEstimated).map(y=>y.source);P.length&&A.push(`gas ESTIMATED (from gas units x current gas price, not measured) for: ${P.join(", ")}. Net includes this estimate so the ranking is gas-inclusive, but the on-chain gas may differ.`);let x=null,_=null;if(p.length>=2&&p[0].costAccounted&&p[1].costAccounted){let y=BigInt(p[0].netOut),k=BigInt(p[1].netOut);k>0n&&(x=Number((y-k)*10000n/k),_=`${p[0].source} vs ${p[1].source}`)}return{best:p[0]??null,routes:p,failed:l,improvementBps:x,spreadBasis:_,rankedOn:i?"net-of-cost":"gross",warnings:A}}async function kt(e,{timeoutMs:t=12e3}={}){let r=(a,s)=>{let o;return Promise.race([a,new Promise((u,l)=>{o=setTimeout(()=>l(new Error(`${s}: timeout`)),t)})]).finally(()=>clearTimeout(o))};return(await Promise.allSettled(e.map(a=>r(Promise.resolve().then(a.run),a.source)))).map((a,s)=>{let o=e[s].source;return a.status==="rejected"?Ct({source:o,error:String(a.reason?.message||a.reason)}):Ct({source:o,...a.value})})}De();$();re();Y();$e();$();re();Y();$();re();Y();$();re();import{TypedDataEncoder as Cs,getAddress as Is,isAddress as ks}from"ethers";var Ss=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});Le();Y();var Us=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),Ps=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"});var Ls=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"}]}),$s=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]});import{Interface as or,getAddress as ri,isAddress as ni}from"ethers";$();var ct={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0},elysium:{chainId:1339,name:"Elysium",rpcEnv:["ELYSIUM_RPC_URL"],evm:!0,readOnly:!0}};var nr=new Map(Object.values(ct).map(e=>[e.chainId,e]));function Se(e){return nr.get(Number(e))||null}function Fe(e){return nr.get(Number(e))?.readOnly===!0}import{Interface as bo,getAddress as Gs}from"ethers";var Ws=new bo(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);$();var Zs=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});re();Y();var ci=new or(["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)"]),ui=new or(["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)"]);import{AbiCoder as So,Interface as ut,getAddress as fi,isAddress as mi,keccak256 as hi}from"ethers";re();Y();var Si=So.defaultAbiCoder();var Ei=new ut(["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)","function quoteExactOutputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountIn, uint256 gasEstimate)"]),Ai=new ut(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),xi=new ut(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96,int24 tick,uint24 protocolFee,uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),vi=Object.freeze([[13,"beforeInitialize"],[12,"afterInitialize"],[11,"beforeAddLiquidity"],[10,"afterAddLiquidity"],[9,"beforeRemoveLiquidity"],[8,"afterRemoveLiquidity"],[7,"beforeSwap"],[6,"afterSwap"],[5,"beforeDonate"],[4,"afterDonate"],[3,"beforeSwapReturnsDelta"],[2,"afterSwapReturnsDelta"],[1,"afterAddLiquidityReturnsDelta"],[0,"afterRemoveLiquidityReturnsDelta"]]),Ci=(1n<<14n)-1n;$();var Eo="https://coins.llama.fi",Ao="https://api.llama.fi";function xo(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Eo).replace(/\/$/,"")}function vo(e={}){return(e.baseUrl||process.env.DEFILLAMA_API_URL||Ao).replace(/\/$/,"")}function Co(e){let t=Array.isArray(e)?e:typeof e=="string"?e.split(","):[];return[...new Set(t.map(r=>String(r??"").trim()).filter(Boolean))].slice(0,100)}async function lt(e,t={}){let r=Co(e);if(!r.length)throw new Error("llamaPrices requires coins[]");let n=r.map(encodeURIComponent).join(",");return v(`${xo(t)}/prices/current/${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function ar(e={}){return v(`${vo(e)}/protocols`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??2e4})}var G=e=>{let t=Number(e);return Number.isFinite(t)?t:null};function dr(e){if(!Array.isArray(e))return null;let t=0,r=!1;for(let n of e){let a=G(n?.amountUSD);a!=null&&(t+=a,r=!0)}return r?t:null}function pr(e){return Array.isArray(e)?e.flatMap((t,r)=>{let n=String(t?.amountUSD??"").trim();return/^\d+(?:\.\d+)?$/.test(n)?[{name:String(t?.name??t?.type??`cost-${r+1}`),amountUsd:n}]:[]}):[]}var ie=e=>String(e??"").toLowerCase().replace(/[^a-z0-9]/g,""),fr=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 Ro(e={}){try{let t=await ar({...e,baseUrl:e.defillamaApiBaseUrl,timeoutMs:e.defillamaTimeoutMs??Math.min(Number(e.timeoutMs??5e3),5e3)});return Array.isArray(t)?t:[]}catch{return[]}}function Bo(e,t={}){let r=ie(t.tool||t.provider||t.bridge||t.protocol),n=[];return e==="lifi"&&r&&r!=="lifi"&&n.push(...fr[r]||[r]),n.push(...fr[ie(e)]||[e]),n}function _o(e,t,r={}){let n=Array.isArray(e)?e:[],a=Bo(t,r).map(ie).filter(Boolean);for(let s of a){let o=n.find(l=>ie(l?.slug)===s||ie(l?.name)===s),u=G(o?.tvl);if(u!=null)return{liquidityUsd:u,protocol:o?.name??o?.slug??s}}for(let s of a){let o=n.find(l=>{let i=ie(l?.category);return!i.includes("bridge")&&!i.includes("crosschain")?!1:ie(l?.slug).includes(s)||ie(l?.name).includes(s)}),u=G(o?.tvl);if(u!=null)return{liquidityUsd:u,protocol:o?.name??o?.slug??s}}return null}function mr({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:a,taker:s,slippageBps:o,allowedSources:u,opts:l={}}){let i=[],c=null,d=async(p,m={})=>(c||=Ro(l),_o(await c,p,m));if(i.push({source:"lifi",run:async()=>{let p=await me({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:a,fromAddress:s,slippageBps:o},l),m=p?.estimate??p?.[0]?.estimate,w=(p?.includedSteps??p?.steps??[]).map((g,C)=>({id:String(g?.id??`step-${C+1}`),type:String(g?.type??"route"),tool:String(g?.tool??g?.toolDetails?.name??"LI.FI"),fromChainId:Number(g?.action?.fromChainId??e),toChainId:Number(g?.action?.toChainId??t)})),b={tool:p?.tool??p?.toolDetails?.name,durationSeconds:G(m?.executionDuration),destinationDecimals:G(p?.action?.toToken?.decimals),routeSteps:w,feeCosts:pr(m?.feeCosts),gasCosts:pr(m?.gasCosts)},A=await d("lifi",b);return{amountOut:m?.toAmount,minOut:m?.toAmountMin,gasUsd:dr(m?.gasCosts),feeUsd:dr(m?.feeCosts),feeIncludedInAmountOut:!0,oracleFeeBps:p?.oracleFee?.applies?p.oracleFee.bps:0,liquidityUsd:A?.liquidityUsd??null,meta:{...b,liquidityProtocol:A?.protocol,oracleFee:p?.oracleFee??null}}}}),i.push({source:"relay",run:async()=>{let{relayQuote:p}=await Promise.resolve().then(()=>(xe(),He)),m=await p({user:s,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(a),slippageBps:o},l),w=m?.details,b=(m?.steps??[]).map((P,x)=>({id:String(P?.id??`step-${x+1}`),type:String(P?.kind??"transaction"),tool:"Relay",label:String(P?.description??P?.action??P?.id??`Step ${x+1}`),fromChainId:Number(e),toChainId:Number(t)})),A=String(m?.fees?.relayer?.amountUsd??"").trim(),g=String(m?.fees?.gas?.amountUsd??"").trim(),C=String(w?.totalImpact?.usd??"").trim(),U={durationSeconds:G(w?.timeEstimate),rate:w?.rate,destinationDecimals:G(w?.currencyOut?.currency?.decimals),routeSteps:b,feeCosts:[.../^\d+(?:\.\d+)?$/.test(A)?[{name:"relayer",amountUsd:A}]:[],.../^-?\d+(?:\.\d+)?$/.test(C)?[{name:"total-impact",amountUsd:C}]:[]],gasCosts:/^\d+(?:\.\d+)?$/.test(g)?[{name:"origin-gas",amountUsd:g}]:[]},I=await d("relay",U);return{amountOut:w?.currencyOut?.amount,minOut:w?.currencyOut?.minimumAmount,gasUsd:G(m?.fees?.gas?.amountUsd),feeUsd:G(m?.fees?.relayer?.amountUsd)??(G(w?.totalImpact?.usd)!=null?Math.abs(G(w.totalImpact.usd)):null),feeIncludedInAmountOut:!0,liquidityUsd:I?.liquidityUsd??null,meta:{...U,liquidityProtocol:I?.protocol}}}}),i.push({source:"across",run:async()=>{let{acrossSuggestedFees:p}=await Promise.resolve().then(()=>(xe(),He)),m=await p({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(a)},l),w=m?.totalRelayFee?.total,b=null;if(w!=null)try{let g=BigInt(String(a))-BigInt(String(w));g>0n&&(b=g.toString())}catch{}let A=await d("across");return{amountOut:b,gasUsd:null,liquidityUsd:A?.liquidityUsd??null,meta:{derivedFromFees:!0,durationSeconds:G(m?.estimatedFillTimeSec),limits:m?.limits?{min:m.limits.minDeposit,max:m.limits.maxDeposit}:void 0,liquidityProtocol:A?.protocol}}}}),!Array.isArray(u))return i;let h=new Set(u.map(p=>String(p).toLowerCase()));return i.filter(p=>h.has(p.source))}$e();function Uo(e,t,r){let n=t.find(s=>Fe(s));if(n==null)return null;let a=Se(n)?.name||`chain ${n}`;return{kind:e,...r,best:null,routes:[],failed:[],improvementBps:null,spreadBasis:null,rankedOn:null,warnings:[],unsupported:!0,readOnlyChain:Number(n),sourcesTried:0,sourcesAnswered:0,note:`${a} (${n}) is registered read-only: no swap venue or route source covers it. This is UNSUPPORTED, not a failed quote. Oracle reads balances and calls there; it does not quote or prepare.`}}var Po={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"},hr=Object.freeze(["lifi","relay"]);function Lo(e){let t=e==null?50:Number(e);if(!Number.isInteger(t)||t<1||t>100)throw new Error("slippageBps must be an integer from 1 through 100");return t}function $o(e,t=hr){let r=new Set((Array.isArray(t)?t:hr).map(o=>String(o).toLowerCase())),n=(e?.routes??[]).filter(o=>r.has(o.source)),a=new Set(n.map(o=>o.source)),s=(e?.failed??[]).filter(o=>r.has(o.source)&&!a.has(o.source));return[...n,...s].map(o=>({provider:o.source,status:o.quality===Z.FAILED?"unavailable":"quoted",amountOut:o.amountOut??null,minAmountOut:o.minOut??null,netAmountOut:o.netOut??null,feeUsd:o.feeUsd??null,gasUsd:o.gasUsd??null,etaSeconds:o.meta?.durationSeconds??null,decimalsOut:o.meta?.destinationDecimals??null,routeSteps:Array.isArray(o.meta?.routeSteps)?o.meta.routeSteps:[],feeCosts:Array.isArray(o.meta?.feeCosts)?o.meta.feeCosts:[],gasCosts:Array.isArray(o.meta?.gasCosts)?o.meta.gasCosts:[],selected:o.source===e?.best?.source,error:o.error??null}))}async function Do(e,t,r){let n=Po[Number(e)];if(!n)return{priceUsd:null,decimals:null};let a=`${n}:${t}`;try{let o=(await lt([a],r))?.coins?.[a],u=Number(o?.price),l=Number(o?.decimals);return{priceUsd:Number.isFinite(u)?u:null,decimals:Number.isFinite(l)?l:null}}catch{return{priceUsd:null,decimals:null}}}async function gr(e,t={}){let{fromChainId:r,toChainId:n,tokenIn:a,tokenOut:s,amountIn:o}=e;if(r==null||n==null||!a||!s||o==null)throw new Error("bestBridgeRoute requires fromChainId, toChainId, tokenIn, tokenOut, amountIn");if(Number(r)===Number(n))throw new Error("bestBridgeRoute is for cross-chain; use bestSwapRoute for same-chain");let u=Uo("bridge",[r,n],{fromChainId:r,toChainId:n,tokenIn:a,tokenOut:s,amountIn:String(o)});if(u)return u;let l=Lo(e.slippageBps),i={...e,slippageBps:l},c=Do(n,s,t),d=mr({...i,opts:t}),[h,p]=await Promise.all([kt(d,{timeoutMs:t.timeoutMs??15e3}),c]),m=It(h,{destPriceUsd:p.priceUsd,destDecimals:e.decimalsOut??p.decimals,liquidityFirst:!1,liquidityBandBps:0}),w=m.routes.map(b=>({source:b.source,seconds:b.meta?.durationSeconds??null})).filter(b=>b.seconds!=null);return{kind:"bridge",fromChainId:r,toChainId:n,tokenIn:a,tokenOut:s,amountIn:String(o),slippageBps:l,...m,routeOptions:$o(m,e.allowedSources),durations:w,sourcesTried:d.length,sourcesAnswered:h.filter(b=>b.quality!==Z.FAILED).length,note:qo(m,d.length)}}function Fo(e){let t=e?.meta?.oracleFee;return t?.applies?` \xB7 ${Zt(t)}`:""}function qo(e,t){if(!e.best)return"no source returned a usable route";let r=e.routes.length,n=Fo(e.best);if(r===1)return`only 1 of ${t} sources answered, so this is the ONLY route, not a proven best one. Treat it as unbenchmarked.`+n;if(e.improvementBps!=null){let a=e.improvementBps,s=a/100;if(a<.01)return`best of ${r} routes, ranked on ${e.rankedOn}: effectively tied with the runner-up (${e.spreadBasis}), inside quote noise. Re-quote before you size up.`+n;let o=s>=.01?`${s.toFixed(2)}%`:`${a.toFixed(2)}bps`;return`best of ${r} routes, ranked on ${e.rankedOn}: ${o} better than the runner-up (${e.spreadBasis})`+n}return`best of ${r} routes, ranked on ${e.rankedOn}. No spread quoted: the top routes report cost differently, so the margin is not comparable.`+n}Y();De();yt();$();var St="https://api.changenow.io/v2",he=new Map,Sr=0,jo=6e5;async function Vo({active:e=!0}={},t={}){let r=Date.now();if(he.size&&r-Sr<jo)return[...he.values()];try{let n=await v(`${St}/exchange/currencies?active=${e?"true":"false"}`,t);he.clear();for(let a of n??[])he.set(String(a.ticker).toLowerCase(),a);return Sr=r,n??[]}catch(n){return he.size?[...he.values()]:{error:String(n.message||n).slice(0,200)}}}async function zo(e,t,r={}){if(!e||!t)return{error:"changenow minAmount requires fromTicker and toTicker"};try{return{minAmount:(await v(`${St}/exchange/min-amount/${encodeURIComponent(e)}_${encodeURIComponent(t)}`,r))?.minAmount??"0"}}catch(n){return{error:String(n.message||n).slice(0,200)}}}async function Ko(e,t,r,{flow:n="standard"}={},a={}){if(!e||!t||!r)return{error:"changenow estimate requires fromTicker, toTicker, fromAmount"};try{let s=new URLSearchParams({fromCurrency:String(e).toLowerCase(),toCurrency:String(t).toLowerCase(),fromAmount:String(r),flow:n}),o=await v(`${St}/exchange/estimated-amount?${s}`,a);return{fromAmount:o?.fromAmount,toAmount:o?.toAmount,rate:o?.rate,flow:o?.flow??n}}catch(s){return{error:String(s.message||s).slice(0,200)}}}async function Er({fromTicker:e,toTicker:t,fromAmount:r,flow:n}={},a={}){if(!e||!t)return{error:"changenow quote requires fromTicker and toTicker"};let s=await zo(e,t,a);if(s.error)return s;let o=r??s.minAmount,u=await Ko(e,t,o,{flow:n},a);if(u.error)return u;let l=await Vo({},a),i=l.find(d=>String(d?.ticker).toLowerCase()===String(e).toLowerCase()),c=l.find(d=>String(d?.ticker).toLowerCase()===String(t).toLowerCase());return{provider:"changenow",fromTicker:e,toTicker:t,fromAmount:o,toAmount:u.toAmount,estimatedRate:u.rate,minAmount:s.minAmount,flow:u.flow,networkFee:i?.networkFee??null,kycRequired:i?.kycRequired??c?.kycRequired??!1,riskDisclosure:"ChangeNOW is a centralized swap service. Funds are sent to a ChangeNOW deposit address. Not self-custodial during the swap window."}}$();var Go="https://api.squidrouter.com/v1";async function Ar({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:a,fromAddress:s,slippage:o=1}={},u={}){if(!e||!t||!r||!n||!a||!s)return{error:"squid quote requires fromChain, toChain, fromToken, toToken, fromAmount, fromAddress"};try{let l={fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:String(a),fromAddress:s,slippage:o},i=await v(`${Go}/route`,{...u,method:"POST",body:JSON.stringify(l),headers:{"content-type":"application/json",...u.headers||{}}});return{route:i?.route??{},toAmount:i?.route?.estimate?.toAmount,fee:i?.route?.estimate?.feeCosts}}catch(l){return{error:String(l.message||l).slice(0,200)}}}$();var Wo="https://api.stargate.finance";async function xr({srcChainId:e,dstChainId:t,token:r,amount:n,dstGasForCall:a=0,minAmountOut:s="0"}={},o={}){if(!e||!t||!r||!n)return{error:"stargate quote requires srcChainId, dstChainId, token, amount"};try{let u=new URLSearchParams({srcChainId:String(e),dstChainId:String(t),token:r,amount:String(n),dstGasForCall:String(a),minAmountOut:String(s)}),l=await v(`${Wo}/quote?${u}`,o);return{amountOut:l?.amountOut,fee:l?.fee,estimatedTime:l?.estimatedTime}}catch(u){return{error:String(u.message||u).slice(0,200)}}}$();var vr="https://midgard.ninerealms.com/v2";async function Cr({fromAsset:e,toAsset:t,amount:r,destination:n}={},a={}){if(!e||!t||!r)return{error:"thorchain quote requires fromAsset, toAsset, amount"};try{let s=new URLSearchParams({from_asset:e,to_asset:t,amount:String(r),destination:n||""}),o=await v(`${vr}/quote/swap?${s}`,a);return{expectedAmountOut:o?.expected_amount_out,fees:o?.fees,slippageBps:o?.slippage_bps,inboundAddress:o?.inbound_address,memo:o?.memo,estimatedTime:o?.total_swap_seconds?`${Math.round(o.total_swap_seconds/60)} min`:"unknown"}}catch(s){return{error:String(s.message||s).slice(0,200)}}}async function Ir(){try{return{ok:(await v(`${vr}/health`))?.scannerHeight>0}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}$();var Qo="https://api.socket.tech/v2";async function kr({fromChainId:e,toChainId:t,fromToken:r,toToken:n,fromAmount:a,userAddress:s}={},o={}){if(!e||!t||!r||!n||!a||!s)return{error:"bungee quote requires fromChainId, toChainId, fromToken, toToken, fromAmount, userAddress"};try{let u=new URLSearchParams({fromChainId:String(e),toChainId:String(t),fromTokenAddress:r,toTokenAddress:n,fromAmount:String(a),userAddress:s,sort:"output",singleTxOnly:"false"}),l=await v(`${Qo}/quote?${u}`,o);return{amountOut:l?.result?.toAmount,feeUsd:l?.result?.totalGasFeesInUsd,route:l?.result?.route,estimatedTime:l?.result?.serviceTime?`${l.result.serviceTime}s`:"unknown"}}catch(u){return{error:String(u.message||u).slice(0,200)}}}$();var Yo="https://api.connext.network";async function Or({originDomain:e,destinationDomain:t,originToken:r,destinationToken:n,amount:a}={},s={}){if(!e||!t||!r||!n||!a)return{error:"connext quote requires originDomain, destinationDomain, originToken, destinationToken, amount"};try{let o={originDomain:String(e),destinationDomain:String(t),originToken:r,destinationToken:n,amount:String(a)},u=await v(`${Yo}/estimate`,{...s,method:"POST",body:JSON.stringify(o),headers:{"content-type":"application/json",...s.headers||{}}});return{amountOut:u?.amountOut,fee:u?.fee,estimatedTime:u?.estimatedTransferTime}}catch(o){return{error:String(o.message||o).slice(0,200)}}}$();var Xo="https://api.portalbridge.com/v1";async function Tr({fromChain:e,toChain:t,token:r,amount:n}={},a={}){if(!e||!t||!r||!n)return{error:"wormhole quote requires fromChain, toChain, token, amount"};try{let s=new URLSearchParams({fromChain:String(e),toChain:String(t),token:r,amount:String(n)}),o=await v(`${Xo}/quote?${s}`,a);return{amountOut:o?.amountOut,fee:o?.fee,estimatedTime:o?.estimatedTime}}catch(s){return{error:String(s.message||s).slice(0,200)}}}xe();import{Interface as Rr,getAddress as ru,id as Br}from"ethers";$();var Nr=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",stableQuoteAssets:["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48","0xdAC17F958D2ee523a2206206994597C13D831ec7"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85","0x94b008aA00579c1307B0EF2c499aD98a8ce58e58"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",stableQuoteAssets:["0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d","0x55d398326f99059fF775485246999027B3197955"],venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",stableQuoteAssets:["0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359","0xc2132D05D31c914a87C6611C10748AEb04B58e8F"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",stableQuoteAssets:["0x5fc5360d0400a0fd4f2af552add042d716f1d168"],venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",stableQuoteAssets:["0xaf88d065e77c8cC2239327C5EDb3A432268e5831","0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",stableQuoteAssets:["0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"],venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);$();var su=new Rr(["function decimals() view returns (uint8)","function symbol() view returns (string)"]),iu=new Rr(["function isApprovedForAll(address owner, address operator) view returns (bool)","function name() view returns (string)"]),cu=Br("Approval(address,address,uint256)"),uu=Br("ApprovalForAll(address,address,bool)");var lu=Object.freeze({"0x1111111254eeb25477b68fb85ed929f73a960582":"1inch v5 Router","0x111111125421ca6dc452d289314280a0f8842a65":"1inch v6 Router","0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45":"Uniswap Universal Router","0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad":"Uniswap Universal Router","0x000000000022d473030f116ddee9f6b43ac78ba3":"Permit2","0xe592427a0aece92de3edee1f18e0157c05861564":"Uniswap v3 Router","0x7a250d5630b4cf539739df2c5dacb4c659f2488d":"Uniswap v2 Router","0xdef1c0ded9bec7f1a1670819833240f027b25eff":"0x Exchange Proxy","0x2626664c2603336e57b271c5c0b26f421741e481":"Uniswap SwapRouter02 (Base)","0x6131b5fae19ea4f9d964eac0408e4408b66337b5":"KyberSwap Meta Aggregator","0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48":"USDC (token contract)"}),du=Object.freeze([{address:"0x000000000022d473030f116ddee9f6b43ac78ba3",label:"Permit2"},{address:"0x1111111254eeb25477b68fb85ed929f73a960582",label:"1inch v5 Router"},{address:"0x111111125421ca6dc452d289314280a0f8842a65",label:"1inch v6 Router"},{address:"0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45",label:"Uniswap Universal Router"},{address:"0xe592427a0aece92de3edee1f18e0157c05861564",label:"Uniswap v3 Router"},{address:"0x7a250d5630b4cf539739df2c5dacb4c659f2488d",label:"Uniswap v2 Router"},{address:"0xdef1c0ded9bec7f1a1670819833240f027b25eff",label:"0x Exchange Proxy"},{address:"0x2626664c2603336e57b271c5c0b26f421741e481",label:"Uniswap SwapRouter02"}]),pu=Object.freeze([{address:"0x1e0049783f008a0085193e00003d00cd54003c71",label:"OpenSea Seaport Conduit"},{address:"0x00000000000000adc04c56bf30ac9d3c0aaf14dc",label:"Seaport 1.5"},{address:"0x0000000000000068f116a894984e2db1123eb395",label:"Seaport 1.6"},{address:"0x00000000000001ad428e4906ae43d8f9852d0dd6",label:"Seaport 1.4"},{address:"0x000000000000ad05ccc4f10045630fb830b95127",label:"Blur Marketplace"},{address:"0x00000000000000000000000000000000000000a5",label:"Blur Execution Delegate"},{address:"0xf42aa99f011a1fa7cda90e5e98b277e306bca83e",label:"Rarible Transfer Proxy"},{address:"0x000000000022d473030f116ddee9f6b43ac78ba3",label:"Permit2"}]),fu=Object.freeze({1:[{address:"0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d",name:"Bored Ape Yacht Club"},{address:"0x60e4d786628fea6478f785a6d7e704777c86a7c6",name:"Mutant Ape Yacht Club"},{address:"0xed5af388653567af2f388e6224dc7c4b3241c544",name:"Azuki"},{address:"0x8a90cab2b38dba80c64b7734e58ee1db38b8992e",name:"Doodles"},{address:"0x49cf6f5d44e70224e2e23fdcdd2c053f30ada28b",name:"CloneX"},{address:"0x23581767a106ae21c074b2276d25e5c3e136a68b",name:"Moonbirds"}]}),mu=Object.freeze({1:[{address:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",symbol:"USDC",decimals:6},{address:"0xdac17f958d2ee523a2206206994597c13d831ec7",symbol:"USDT",decimals:6},{address:"0x6b175474e89094c44da98b954eedeac495271d0f",symbol:"DAI",decimals:18},{address:"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",symbol:"WETH",decimals:18},{address:"0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",symbol:"WBTC",decimals:8}],8453:[{address:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",symbol:"USDC",decimals:6},{address:"0x4200000000000000000000000000000000000006",symbol:"WETH",decimals:18}],42161:[{address:"0xaf88d065e77c8cc2239327c5edb3a432268e5831",symbol:"USDC",decimals:6},{address:"0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9",symbol:"USDT",decimals:6},{address:"0x82af49447d8a07e3bd95bd0d56f35241523fbab1",symbol:"WETH",decimals:18}],10:[{address:"0x0b2c639c533813f4aa9d7837caf62653d097ff85",symbol:"USDC",decimals:6},{address:"0x4200000000000000000000000000000000000006",symbol:"WETH",decimals:18}],137:[{address:"0x3c499c542cef5e3811e1192ce70d8cc03d5c3359",symbol:"USDC",decimals:6},{address:"0xc2132d05d31c914a87c6611c10748aeb04b58e8f",symbol:"USDT",decimals:6}]}),ea=(1n<<256n)-1n,hu=ea/2n,gu=4320*60*60*1e3,bu=360*60*1e3,wu=600*1e3,yu=45*1e3;var ve=Object.freeze(["debridge","lifi","relay","squid","stargate","thorchain","bungee","connext","wormhole","across","hop","changenow","rango"]),_r=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche"}),ta=Object.freeze({1:"ETHEREUM",10:"OPTIMISM",56:"BSC",137:"POLYGON",324:"ZKSYNC",1101:"POLYGONZK",5e3:"MANTLE",8453:"BASE",42161:"ARBITRUM",43114:"AVAX_CCHAIN",59144:"LINEA",81457:"BLAST",534352:"SCROLL"}),ra=Object.freeze({1:"ETH",56:"BSC",8453:"BASE",42161:"ARB",43114:"AVAX"}),Dr=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]);function Et(e,t=180){return String(e?.message||e||"unknown error").replace(/\s+/g," ").slice(0,t)}function Ur(e){let t=String(e??"");if(!/^\d+$/.test(t))return null;try{return BigInt(t)>0n?t:null}catch{return null}}function na(e,t){try{let r=BigInt(String(e))-BigInt(String(t));return r>0n?r.toString():null}catch{return null}}function ge(e){let t=Number(e);return Number.isInteger(t)&&t>=0&&t<=255?t:null}function oa(e,t){let r=ge(t),n=String(e??"");if(r==null||!/^\d+$/.test(n))return null;if(r===0)return n;let a=n.padStart(r+1,"0"),s=a.slice(0,-r),o=a.slice(-r).replace(/0+$/,"");return o?`${s}.${o}`:s}function aa(e,t){let r=ge(t),n=/^(\d+)(?:\.(\d+))?$/.exec(String(e??""));if(r==null||!n)return null;let a=n[2]||"";if(a.length>r&&/[1-9]/.test(a.slice(r)))return null;let s=a.slice(0,r).padEnd(r,"0");try{return(BigInt(n[1])*10n**BigInt(r)+BigInt(s||"0")).toString()}catch{return null}}function Pr(e,t,r){let n=ge(t),a=ge(r);if(n==null||a==null||!/^\d+$/.test(String(e??"")))return null;let s=BigInt(String(e));return a>=n?(s*10n**BigInt(a-n)).toString():(s/10n**BigInt(n-a)).toString()}function At(e){return typeof e?.to=="string"&&e.to.length>0&&/^0x(?:[0-9a-fA-F]{2})+$/.test(String(e.data||""))}function sa(e){return(e?.steps||[]).some(t=>(t?.items||[]).some(r=>At(r?.data)))}function Lr(e,t,r){let n=ta[Number(e)];return n?Dr.has(String(t||"").toLowerCase())?r&&r!=="?"?`${n}.${r}`:null:t?`${n}--${t}`:null:null}function $r(e,t,r){if(!r||r==="?")return null;if(r.includes("."))return r;let n=ra[Number(e)];return n?Dr.has(String(t||"").toLowerCase())?`${n}.${r}`:`${n}.${r}-${t}`:null}async function Fr(e={},t={}){let{fromChainId:r,toChainId:n,tokenIn:a,tokenOut:s,amount:o,taker:u,fromSymbol:l="?",toSymbol:i="?",fromDecimals:c,toDecimals:d,slippageBps:h}=e,p=t.includeCentralized===!0||e.includeCentralized===!0,m=ge(c),w=ge(d),b=new Map(ve.map(f=>[f,{provider:f,status:"pending"}])),A=[],g={fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs,retries:t.retries,headers:t.headers},C=(f,M,W=!1)=>{b.set(f,{provider:f,status:"unavailable",reason:Et(M),optional:W})},U=(f,M)=>{b.set(f,{provider:f,status:"skipped",reason:Et(M)})},I=(f,M,W)=>{b.set(f,{provider:f,status:"attempted"}),A.push(Promise.resolve().then(M).then(K=>{if(K?.error)throw new Error(K.error);let de=W(K),ne=Ur(de?.amountOut);if(!ne)throw new Error("no usable integer base-unit amountOut");let Oe={...de,provider:f,amountOut:ne,raw:K};return b.set(f,{provider:f,status:"successful"}),Oe}).catch(K=>(b.set(f,{provider:f,status:"failed",reason:Et(K)}),null)))};I("debridge",()=>bt({srcChainId:r,srcChainTokenIn:a,srcChainTokenInAmount:o,dstChainId:n,dstChainTokenOut:s,taker:u,slippage:h},g),f=>({amountOut:f.estimation?.dstChainTokenOut?.amount??f.estimation?.toAmount,feeUsd:f.estimation?.fixFee??f.fixFee,estimatedTime:f.estimation?.execution?.estimatedTransferTime?`${f.estimation.execution.estimatedTransferTime}s`:"unknown",preparable:At(f.tx)})),I("lifi",()=>me({fromChain:r,toChain:n,fromToken:a,toToken:s,fromAmount:o,fromAddress:u},g),f=>({amountOut:f.estimate?.toAmount??f.toAmount,feeUsd:f.estimate?.feeCosts??null,estimatedTime:f.estimate?.executionDuration??"unknown",preparable:At(f.transactionRequest)})),I("relay",()=>Ae({user:u,originChainId:r,destinationChainId:n,originCurrency:a,destinationCurrency:s,amount:String(o)},g),f=>({amountOut:f.details?.currencyOut?.amount,feeUsd:f.details?.totalImpact?.usd??null,estimatedTime:f.details?.timeEstimate??"unknown",preparable:sa(f)})),I("squid",()=>Ar({fromChain:r,toChain:n,fromToken:a,toToken:s,fromAmount:o,fromAddress:u},g),f=>({amountOut:f.toAmount,feeUsd:f.fee??null,estimatedTime:"30s - 3min",preparable:!1})),I("stargate",()=>xr({srcChainId:r,dstChainId:n,token:a,amount:o},g),f=>({amountOut:f.amountOut,feeUsd:f.fee,estimatedTime:f.estimatedTime||"1-5 min",preparable:!1}));let P=Pr(o,m,8),x=$r(r,a,l),_=$r(n,s,i);m==null||w==null?C("thorchain","fromDecimals and toDecimals are required for unit conversion"):!x||!_?C("thorchain","supported chain mapping plus qualified asset symbols are required"):Ur(P)?I("thorchain",()=>Cr({fromAsset:x,toAsset:_,amount:P,destination:u},g),f=>({amountOut:Pr(f.expectedAmountOut,8,w),feeUsd:f.fees?.total,estimatedTime:f.estimatedTime||"10-30 min",preparable:!1})):C("thorchain","amount is below THORChain's 8-decimal quote precision"),I("bungee",()=>kr({fromChainId:r,toChainId:n,fromToken:a,toToken:s,fromAmount:o,userAddress:u},g),f=>({amountOut:f.amountOut,feeUsd:f.feeUsd,estimatedTime:f.estimatedTime,preparable:!1})),I("connext",()=>Or({originDomain:r,destinationDomain:n,originToken:a,destinationToken:s,amount:o},g),f=>({amountOut:f.amountOut,feeUsd:f.fee,estimatedTime:f.estimatedTime||"5-20 min",preparable:!1})),I("wormhole",()=>Tr({fromChain:r,toChain:n,token:a,amount:o},g),f=>({amountOut:f.amountOut,feeUsd:f.fee,estimatedTime:f.estimatedTime||"5-15 min",preparable:!1})),I("across",()=>qe({token:a,destinationToken:s,originChainId:r,destinationChainId:n,amount:String(o)},g),f=>{let M=f.outputAmount??f.expectedOutputAmount,W=f.totalRelayFee?.total??f.relayFeeTotal;return{amountOut:M??(W!=null?na(o,W):null),feeUsd:f.relayFeeTotalUsd??null,estimatedTime:f.estimatedFillTimeSec!=null?`${f.estimatedFillTimeSec}s`:"unknown",preparable:!1}});let y=_r[Number(r)],k=_r[Number(n)];!y||!k||!l||l==="?"?C("hop","supported chain mapping and fromSymbol are required"):I("hop",()=>Me({amount:String(o),token:l,fromChain:y,toChain:k},g),f=>({amountOut:f.estimatedRecieved??f.estimatedReceived,feeUsd:f.feeUsd??null,estimatedTime:f.estimatedTime??"unknown",preparable:!1}));let E=oa(o,m);p?m==null||w==null?C("changenow","fromDecimals and toDecimals are required for unit conversion"):!l||!i||l==="?"||i==="?"?C("changenow","fromSymbol and toSymbol are required"):E==null?C("changenow","valid integer amount is required"):I("changenow",()=>Er({fromTicker:l,toTicker:i,fromAmount:E},g),f=>({amountOut:aa(f.toAmount,w),feeUsd:f.networkFee,estimatedTime:f.flow==="standard"?"5-30 min":"instant",preparable:!1,centralized:!0,kycRequired:!!f.kycRequired,kycRisk:!0,riskDisclosure:f.riskDisclosure||"ChangeNOW is centralized and may require KYC."})):U("changenow","centralized/KYC-risk routes require includeCentralized=true");let R=t.env??process.env,S=t.rangoApiKey||R.RANGO_API_KEY,B=Lr(r,a,l),q=Lr(n,s,i);S?!B||!q?C("rango","supported Rango chain/token identifiers are required",!0):I("rango",()=>ht({from:B,to:q,amount:String(o),enableCentralizedSwappers:!1},{...t,rangoApiKey:S}),f=>({amountOut:f.amountOut,feeUsd:f.feeUsd,estimatedTime:f.estimatedTime!=null?`${f.estimatedTime}s`:"unknown",preparable:!1})):C("rango","RANGO_API_KEY is not configured",!0);let D=(await Promise.all(A)).filter(Boolean);D.sort((f,M)=>{let W=BigInt(f.amountOut),K=BigInt(M.amountOut);return W!==K?W>K?-1:1:f.preparable!==M.preparable?f.preparable?-1:1:ve.indexOf(f.provider)-ve.indexOf(M.provider)});let O=ve.map(f=>b.get(f)),T=O.filter(f=>["successful","failed"].includes(f.status)).map(f=>f.provider),N=O.filter(f=>f.status==="successful").map(f=>f.provider),j=O.filter(f=>f.status==="failed").map(f=>f.provider),z=O.filter(f=>f.status==="unavailable").map(f=>f.provider),J=O.filter(f=>f.status==="skipped").map(f=>f.provider),ce=O.filter(f=>f.status==="failed").map(f=>`${f.provider}: ${f.reason}`),Ie=D.length>0,ke=Ie&&O.every(f=>f.status==="successful"||f.status==="skipped"||f.status==="unavailable"&&f.optional);return{ok:Ie,providers:D.map(f=>f.provider),bestRoute:D[0]?.provider??"none",winner:D[0]??null,runnersUp:D.slice(1),errors:ce.length?ce:null,attemptedProviders:T,successfulProviders:N,failedProviders:j,unavailableProviders:z,skippedProviders:J,comparisonComplete:ke,coverage:{roster:[...ve],attemptedProviders:T,successfulProviders:N,failedProviders:j,unavailableProviders:z,skippedProviders:J,complete:ke,details:O}}}var _u=Object.freeze({debridge:e=>wt(e),lifi:e=>it(e),relay:e=>mt(e),thorchain:e=>Ir(e),across:e=>dt(e),hop:e=>pt(e)}),Uu=Object.freeze({squid:"existing health helper does not validate its response or accept injected request options",stargate:"adapter exposes only static metadata, not a network-backed health check",bungee:"existing health helper does not validate its response or accept injected request options",connext:"adapter exposes only static metadata, not a network-backed health check",wormhole:"adapter exposes only static metadata, not a network-backed health check",changenow:"existing health helper is cache-backed and cannot prove current availability",rango:"Rango has no standalone health check; quote health requires a configured route and RANGO_API_KEY"});var X=/^0x[0-9a-fA-F]{40}$/,qr=/^0x(?:[0-9a-fA-F]{2})+$/;function xt(e){return Array.isArray(e)?e.map(xt):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([t])=>t!=="signature"&&t!=="rawTransaction"&&t!=="signedTransaction").map(([t,r])=>[t,xt(r)]))}var ia=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),ca=100;function ua(e){let t=e==null?50:Number(e);if(!Number.isInteger(t)||t<1||t>100)throw new Error("slippageBps must be an integer from 1 through 100");return t}function Mr(e){return Array.isArray(e)?e.flatMap((t,r)=>{let n=String(t?.amountUSD??t?.amountUsd??"").trim();return/^-?\d+(?:\.\d+)?$/.test(n)?[{name:String(t?.name??t?.type??`fee-${r+1}`),amountUsd:n}]:[]}):[]}function la(e){if(Array.isArray(e)){let r=Mr(e);if(!r.length)return null;let n=r.reduce((a,s)=>a+Number(s.amountUsd),0);return Number.isFinite(n)?n:null}let t=Number(e);return e!=null&&e!==""&&Number.isFinite(t)?t:null}function da(e){let t=Number(e);if(e!=null&&e!==""&&Number.isFinite(t)&&t>=0)return t;let r=/^\s*(\d+)s\s*$/i.exec(String(e??""));return r?Number(r[1]):null}function Hr(e,t){let r=e?.raw?.tx;if(!r||typeof r!="object"||Array.isArray(r))return{ok:!1,reason:"deBridge returned no paired transaction"};if(!X.test(String(r.to??"")))return{ok:!1,reason:"deBridge paired transaction target is not a valid destination"};if(!qr.test(String(r.data??"")))return{ok:!1,reason:"deBridge paired transaction calldata is not complete unsigned bytes"};if(r.chainId!=null&&Number(r.chainId)!==Number(t.fromChainId))return{ok:!1,reason:"deBridge paired transaction origin chain is mismatched"};if(!X.test(String(r.from??""))||String(r.from).toLowerCase()!==String(t.taker).toLowerCase())return{ok:!1,reason:"deBridge paired transaction sender is not the exact taker"};let n=e?.raw?.walletBinding;return!n||[n.dstChainTokenOutRecipient,n.srcChainOrderAuthorityAddress,n.dstChainOrderAuthorityAddress].some(a=>String(a??"").toLowerCase()!==String(t.taker).toLowerCase())?{ok:!1,reason:"deBridge destination recipient and order authorities are not bound to taker"}:{ok:!0,reason:null}}function pa(e,t){return be[e?.provider]?e.provider==="debridge"?Hr(e,t):e?.preparable!==!0?{ok:!1,reason:"provider returned no verified unsigned transaction bytes"}:{ok:!0,reason:null}:{ok:!1,reason:"quote-only provider: no reviewed strict preparer"}}function Ce(e){return e?{source:e.source,amountOut:e.amountOut,grossOut:e.grossOut,netOut:e.netOut,feeUsd:e.feeUsd,gasUsd:e.gasUsd,etaSeconds:e.meta?.durationSeconds??null,estimatedTime:e.meta?.estimatedTime??null,preparable:e.preparable===!0}:null}async function fa(e,t){let{fromChainId:r,toChainId:n,tokenIn:a,tokenOut:s,amountIn:o,taker:u}=e;if(r==null||n==null||!a||!s||o==null)throw new Error("prepareBestBridgeRoute requires fromChainId, toChainId, tokenIn, tokenOut, amountIn");if(Number(r)===Number(n))throw new Error("prepareBestBridgeRoute is for cross-chain routes only");let l=ua(e.slippageBps),i=await Fr({fromChainId:r,toChainId:n,tokenIn:a,tokenOut:s,amount:String(o),taker:u,fromSymbol:e.fromSymbol,toSymbol:e.toSymbol,fromDecimals:e.fromDecimals??e.decimalsIn,toDecimals:e.toDecimals??e.decimalsOut,slippageBps:l,includeCentralized:e.includeCentralized===!0},t),d=[i.winner,...i.runnersUp||[]].filter(Boolean).map(g=>{let C=Mr(g.feeUsd),U=pa(g,e),I={source:g.provider,quality:"NO_GAS",amountOut:String(g.amountOut),grossOut:String(g.amountOut),netOut:String(g.amountOut),gasUsd:null,feeUsd:la(g.feeUsd),preparable:U.ok,prepareReason:U.reason,centralized:g.centralized===!0,kycRequired:g.kycRequired===!0,kycRisk:g.kycRisk===!0,riskDisclosure:g.riskDisclosure??null,meta:{durationSeconds:da(g.estimatedTime),estimatedTime:g.estimatedTime??null,destinationDecimals:Number.isInteger(e.toDecimals??e.decimalsOut)?Number(e.toDecimals??e.decimalsOut):null,routeSteps:[],feeCosts:C,gasCosts:[]}};return Object.defineProperty(I,"raw",{value:g.raw,enumerable:!1}),I}),h=d[0]??null,p=d.map((g,C)=>({provider:g.source,status:"quoted",rank:C+1,amountOut:g.amountOut,minAmountOut:null,netAmountOut:g.netOut,feeUsd:g.feeUsd,gasUsd:g.gasUsd,etaSeconds:g.meta.durationSeconds,estimatedTime:g.meta.estimatedTime,decimalsOut:g.meta.destinationDecimals,routeSteps:[],feeCosts:g.meta.feeCosts,gasCosts:[],selected:!1,quoteWinner:g.source===h?.source,preparable:g.preparable,quoteOnly:g.preparable!==!0,prepareReason:g.prepareReason,centralized:g.centralized,kycRequired:g.kycRequired,kycRisk:g.kycRisk,riskDisclosure:g.riskDisclosure,error:null})),m=new Set(d.map(g=>g.source)),w=(i.coverage?.details||[]).filter(g=>!m.has(g.provider)).map(g=>({provider:g.provider,status:g.status==="skipped"?"skipped":"unavailable",rank:null,amountOut:null,minAmountOut:null,netAmountOut:null,feeUsd:null,gasUsd:null,etaSeconds:null,estimatedTime:null,decimalsOut:Number.isInteger(e.toDecimals??e.decimalsOut)?Number(e.toDecimals??e.decimalsOut):null,routeSteps:[],feeCosts:[],gasCosts:[],selected:!1,quoteWinner:!1,preparable:!1,quoteOnly:!0,prepareReason:g.reason??"provider returned no usable quote",centralized:g.provider==="changenow",error:g.reason??null})),b=null;if(d.length>=2&&BigInt(d[1].netOut)>0n){let g=(BigInt(d[0].netOut)-BigInt(d[1].netOut))*10000n/BigInt(d[1].netOut);g<=BigInt(Number.MAX_SAFE_INTEGER)&&(b=Number(g))}let A=[];return i.comparisonComplete!==!0&&A.push("bridge comparison coverage is incomplete; unavailable and failed providers remain explicit in routeOptions"),h&&h.preparable!==!0&&A.push(`${h.source} is the overall quote winner but is quote-only and cannot become a prepared wallet action`),{kind:"bridge",fromChainId:r,toChainId:n,tokenIn:a,tokenOut:s,amountIn:String(o),slippageBps:l,best:h,routes:d,failed:w.filter(g=>g.status==="unavailable"),routeOptions:[...p,...w],winner:Ce(h),runnersUp:d.slice(1).map(Ce),coverage:i.coverage,comparisonComplete:i.comparisonComplete===!0,complete:i.comparisonComplete===!0,sourcesTried:i.coverage?.roster?.length??0,sourcesAnswered:d.length,improvementBps:b,spreadBasis:d.length>=2?`${d[0].source} vs ${d[1].source}`:null,rankedOn:"exact-base-unit-output",durations:d.filter(g=>g.meta.durationSeconds!=null).map(g=>({source:g.source,seconds:g.meta.durationSeconds})),warnings:A,note:d.length?`${d.length} of ${i.coverage?.roster?.length??0} canonical bridge providers returned exact base-unit output`:"no canonical bridge provider returned a usable route"}}var be={debridge:async({fromChainId:e,taker:t},r,n)=>{let a=Hr({provider:"debridge",preparable:!0,raw:n?.raw},{fromChainId:e,taker:t});if(!a.ok)throw new Error(a.reason);let{debridgePrepare:s}=await Promise.resolve().then(()=>(yt(),yr)),u=(await s(n.raw,{taker:t})).transaction,l=u.value??"0";if(!/^(?:0x[0-9a-fA-F]+|\d+)$/.test(String(l)))throw new Error("deBridge paired transaction value is not a canonical unsigned amount");return{transactions:[{chainId:Number(e),from:String(u.from),to:String(u.to),data:String(u.data),value:String(l),...u.gasLimit!=null||u.gas!=null?{gasLimit:u.gasLimit??u.gas}:{}}],destination:String(u.to),requiresApproval:null,amountOut:n.amountOut,minOut:null,durationSeconds:n.meta?.durationSeconds??null}},relay:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:a,taker:s,slippageBps:o},u)=>{let{relayPrepare:l}=await Promise.resolve().then(()=>(xe(),He)),i=await l({user:s,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(a),slippageBps:o},u);return{transactions:i.transactions||[],destination:i.destination??null,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.details?.currencyOut?.amount??null,minOut:i.quote?.details?.currencyOut?.minimumAmount??null,durationSeconds:i.quote?.details?.timeEstimate??null}},lifi:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:a,taker:s,isHolder:o,slippageBps:u},l)=>{let{lifiPrepare:i}=await Promise.resolve().then(()=>(De(),rr)),c=await i({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:a,fromAddress:s,isHolder:o,feeAction:"bridge",slippageBps:u},l);return{transactions:c.transaction?[c.transaction]:[],destination:c.transaction?.to??null,requiresApproval:c.requiresApproval??null,amountOut:c.quote?.estimate?.toAmount??null,minOut:c.quote?.estimate?.toAmountMin??null,durationSeconds:c.quote?.estimate?.executionDuration??null}}};function qu(){return Object.keys(be)}async function Mu(e,t={}){let{taker:r,fromChainId:n,toChainId:a,tokenIn:s,tokenOut:o}=e;if(!r)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(!X.test(r))throw new Error(`taker must be a valid 20-byte address, got "${r}"`);if(ia.has(r.toLowerCase()))throw new Error(`taker "${r}" is a placeholder/burn address. Bridging to it would send funds to an address nobody controls, on a chain where you cannot undo it.`);if(e.walletReviewOnly===!0&&(!X.test(String(s))||!X.test(String(o))))throw new Error("wallet-review bridge preparation requires exact origin and destination token addresses");let u=[n,a].find(S=>Fe(S));if(u!=null)return{ok:!1,unsupported:!0,reason:`${Se(u)?.name||`chain ${u}`} (${u}) is registered read-only: no bridge route source covers it. UNSUPPORTED, not a failed quote.`,comparison:null};let l=!Array.isArray(e.allowedSources),i=l?await fa(e,t):await gr(e,t);if(!i.best)return{ok:!1,reason:"no source returned a usable bridge route",comparison:i};let c=i.best.source,d=l?i.routes.find(S=>S.preparable===!0&&be[S.source]):i.best,h=e.source||d?.source;if(!h)return{ok:!1,reason:`${c} won the quote comparison, but no route has verified real unsigned transaction bytes, a bound destination, and an existing strict preparer.`,failureKind:"no-prepare-path",winner:c,comparison:i};let p=i.routes.find(S=>S.source===h);if(!p)return{ok:!1,reason:`source "${h}" returned no usable route`,comparison:i};let m=be[h];if(!m||l&&p.preparable!==!0){let S=i.routes.find(B=>be[B.source]&&(!l||B.preparable===!0)&&B.source!==h);return{ok:!1,reason:`${h} is quote-only for this response and cannot become a prepared wallet action. `+(S?`Next preparable route is ${S.source}; pass source:"${S.source}".`:"No route in this comparison has verified unsigned bytes and a strict preparer."),failureKind:"no-prepare-path",...S?{alternative:S.source}:{},winner:c,comparison:i}}i={...i,routeOptions:(i.routeOptions||[]).map(S=>({...S,selected:S.provider===h,quoteWinner:S.provider===c}))};let w;try{w=await m(e,t,p)}catch(S){let B=typeof S?.body=="string"?S.body:S?.body?JSON.stringify(S.body):"",q=[String(S?.message||S),B].filter(Boolean).join(" :: "),F=/allowance/i.test(q),D=!F&&/not enough|insufficient|balance/i.test(q),O=i.routes.find(T=>be[T.source]&&(!l||T.preparable===!0)&&T.source!==h);return{ok:!1,reason:F?`${h} will not build calldata until the token approval exists on-chain. Approve first, then prepare again. Underlying: ${q}`:D?`${h} refused to build: ${q}. Quoting works for any address; preparing needs the real funded wallet on chain ${n}.`:`${h} bridge prepare failed: ${q}`,failureKind:F?"approval-required-first":D?"taker-not-funded":"provider-error",...O?{alternative:O.source}:{},comparison:i}}let b=w.transactions||[];if(!b.length)return{ok:!1,reason:`${h} returned no executable transaction for this route`,failureKind:"provider-error",comparison:i};let A=b.filter(S=>S.chainId==null||Number(S.chainId)!==Number(n));if(A.length)return{ok:!1,reason:`${h} returned a transaction for chain ${A[0].chainId??"missing"} but the origin chain is ${n}. Refusing to hand over a mismatched artifact.`,failureKind:"chain-mismatch",comparison:i};if(b.find(S=>!X.test(String(S.from??""))||String(S.from).toLowerCase()!==r.toLowerCase()))return{ok:!1,reason:`${h} returned a transaction whose sender is not the exact wallet under review`,failureKind:"sender-mismatch",comparison:i};if(b.find(S=>!X.test(String(S.to??""))))return{ok:!1,reason:`${h} returned an invalid transaction target`,failureKind:"destination-not-bound",comparison:i};if(b.find(S=>!qr.test(String(S.data??""))))return{ok:!1,reason:`${h} returned incomplete unsigned calldata bytes`,failureKind:"provider-error",comparison:i};let I=w.requiresApproval??null,P=String(w.destination??"");if(!X.test(P)||!b.some(S=>String(S.to).toLowerCase()===P.toLowerCase()))return{ok:!1,reason:`${h} returned no safely bound bridge deposit destination`,failureKind:"destination-not-bound",comparison:i};if(I){if(String(I.amount)!==String(e.amountIn))return{ok:!1,reason:`${h} approval amount does not equal the exact input amount`,failureKind:"approval-not-exact",comparison:i};if(!X.test(String(I.token))||!X.test(String(I.spender)))return{ok:!1,reason:`${h} returned an incomplete approval bound`,failureKind:"approval-not-exact",comparison:i}}let x=e.driftToleranceBps??ca,_=null,y=null;if(w.amountOut!=null&&p.grossOut!=null)try{let S=BigInt(p.grossOut),B=BigInt(w.amountOut);S>0n&&(_=Number((B-S)*10000n/S),_<-x&&(y=`route moved ${(_/100).toFixed(2)}% against you since the comparison (tolerance ${(x/100).toFixed(2)}%). Re-compare before signing.`))}catch{}let k=[...y?[y]:[],...i.warnings||[],`Bridging is NOT atomic: the origin transaction succeeding does not mean funds arrived on chain ${a}. Expect ~${w.durationSeconds!=null?`${w.durationSeconds}s`:"minutes"} before the destination credits, and do not re-send if it is pending.`];b.length>1&&k.push(`This route needs ${b.length} transactions signed IN ORDER. Signing only the first leaves funds approved but not bridged.`);let E=e.walletReviewOnly===!0?xt(b):b,R=H({ok:!0,chosen:{source:h,wasWinner:h===c,netOut:p.netOut,grossOut:p.grossOut,gasUsd:p.gasUsd,feeUsd:p.feeUsd,feeCosts:Array.isArray(p.meta?.feeCosts)?p.meta.feeCosts:[],gasCosts:Array.isArray(p.meta?.gasCosts)?p.meta.gasCosts:[]},artifactKind:"unsigned-transaction-sequence",sender:r.toLowerCase(),fromChainId:Number(n),toChainId:Number(a),tokenIn:String(s),tokenOut:String(o),amountIn:String(e.amountIn),decimalsIn:Number.isInteger(e.decimalsIn)?Number(e.decimalsIn):null,decimalsOut:Number.isInteger(e.decimalsOut)?Number(e.decimalsOut):null,transactionCount:b.length,transactions:E,requiresApproval:I,amountOut:w.amountOut??null,minOut:w.minOut??null,durationSeconds:w.durationSeconds??null,slippageBps:i.slippageBps,routeOptions:i.routeOptions??[],winner:Ce(i.best),quoteWinner:Ce(i.best),coverage:i.coverage??null,comparisonComplete:i.comparisonComplete??null,complete:i.complete??null,destination:P,unsigned:!0,signedBy:"user-wallet",driftBps:_,warnings:k,runnersUp:i.routes.slice(1).map(Ce),comparison:{rankedOn:i.rankedOn,sourcesAnswered:i.sourcesAnswered,sourcesTried:i.sourcesTried,improvementBps:i.improvementBps,winner:c,selectedForPreparation:h,complete:i.comparisonComplete??null},note:`UNSIGNED. ${b.length} transaction(s) on chain ${n}, crediting chain ${a}. Verify every destination address before signing.`},{provider:"router",kind:"best-bridge",env:t.env,nowMs:t.nowMs,expiresAtMs:t.expiresAtMs});if(e.walletReviewOnly===!0&&R.prepareMac){let{prepareMac:S,...B}=R;return B}return R}export{Mu as prepareBestBridgeRoute,qu as supportedBridgePreparers};