@oracle-agent/oracle 0.35.43 → 0.35.44

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 (63) hide show
  1. package/dist/agent-sessions.mjs +19 -19
  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 +19 -19
  5. package/dist/bin/oracle-gateway.mjs +42 -42
  6. package/dist/bin/oracle-investigate.mjs +5 -5
  7. package/dist/bin/oracle-launch-radar-shadow.mjs +6 -6
  8. package/dist/bin/oracle-mev-arb-shadow.mjs +6 -6
  9. package/dist/bin/oracle-mev-shadow.mjs +6 -6
  10. package/dist/bin/oracle-public-server.mjs +5 -5
  11. package/dist/bin/oracle-route.mjs +18 -18
  12. package/dist/bin/oracle-scan.mjs +11 -11
  13. package/dist/bin/oracle.mjs +12 -12
  14. package/dist/cli/commands/agent-session.mjs +21 -21
  15. package/dist/cli/commands/airdrop.mjs +10 -10
  16. package/dist/cli/commands/chat.mjs +218 -217
  17. package/dist/cli/commands/data.mjs +244 -8
  18. package/dist/cli/commands/doctor.mjs +5 -5
  19. package/dist/cli/commands/eval.mjs +157 -153
  20. package/dist/cli/commands/extension-policy.mjs +1 -1
  21. package/dist/cli/commands/farm.mjs +17 -17
  22. package/dist/cli/commands/fees.mjs +3 -3
  23. package/dist/cli/commands/follow.mjs +17 -17
  24. package/dist/cli/commands/mcp.mjs +6 -6
  25. package/dist/cli/commands/mint.mjs +10 -10
  26. package/dist/cli/commands/model.mjs +222 -221
  27. package/dist/cli/commands/quickstart.mjs +7 -7
  28. package/dist/cli/commands/receipt.mjs +8 -8
  29. package/dist/cli/commands/resolve.mjs +10 -10
  30. package/dist/cli/commands/sign.mjs +11 -11
  31. package/dist/cli/commands/signer.mjs +20 -20
  32. package/dist/cli/commands/snipe.mjs +11 -11
  33. package/dist/cli/commands/strategy.mjs +5 -5
  34. package/dist/cli/commands/swap.mjs +11 -11
  35. package/dist/cli/commands/venues.mjs +2 -2
  36. package/dist/data/desk-data.mjs +26 -26
  37. package/dist/data/names.mjs +3 -3
  38. package/dist/data/providers/farming.mjs +2 -2
  39. package/dist/data/providers/lp-destination-discovery.mjs +4 -4
  40. package/dist/index.mjs +44 -44
  41. package/dist/investigator/index.mjs +2 -2
  42. package/dist/launch-radar/index.mjs +5 -5
  43. package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
  44. package/dist/local-signer/index.mjs +3 -3
  45. package/dist/local-signer/runtime.mjs +16 -16
  46. package/dist/nft/universal-mint-router.mjs +4 -4
  47. package/dist/notifications/index.mjs +7 -7
  48. package/dist/router/index.mjs +3 -3
  49. package/dist/router/prepare-bridge.mjs +2 -2
  50. package/dist/router/prepare-route.mjs +3 -3
  51. package/dist/scanner/index.mjs +4 -4
  52. package/dist/strategy/index.mjs +3 -3
  53. package/dist/tui/standalone-client.mjs +90 -88
  54. package/package.json +1 -1
  55. package/public/eval-report.json +347 -13
  56. package/public/oracle-splash/docs/browser-and-web/index.html +2 -2
  57. package/public/oracle-splash/docs/connectors/index.html +2 -2
  58. package/public/oracle-splash/docs/getting-started/index.html +2 -2
  59. package/public/oracle-splash/docs/index.html +3 -3
  60. package/public/oracle-splash/docs/reference/index.html +2 -2
  61. package/public/oracle-splash/docs/security/index.html +2 -2
  62. package/public/oracle-splash/docs/using-oracle/index.html +2 -2
  63. package/server.json +2 -2
@@ -1,2 +1,2 @@
1
- var Lr=Object.defineProperty;var K=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var $e=(e,t)=>{for(var r in t)Lr(e,r,{get:t[r],enumerable:!0})};import ie from"node:net";import $r from"node:dns";function Ce(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=u=>{if(!u)return[];let c=u.split(":"),f=c.at(-1);if(f?.includes(".")){let m=f.split(".").map(Number);if(m.length!==4||m.some(h=>!Number.isInteger(h)||h<0||h>255))return null;c.splice(c.length-1,1,(m[0]<<8|m[1]).toString(16),(m[2]<<8|m[3]).toString(16))}return c.some(m=>!/^[0-9a-f]{1,4}$/.test(m))?null:c.map(m=>Number.parseInt(m,16))},[n,s]=t.split("::"),a=r(n),o=r(s);if(!a||!o)return null;let l=t.includes("::"),i=8-a.length-o.length;if(!l&&i!==0||l&&i<1)return null;let d=[...a,...Array(Math.max(0,i)).fill(0),...o];return d.length!==8?null:Uint8Array.from(d.flatMap(u=>[u>>8,u&255]))}function qe(e,t,r){let n=Math.floor(r/8),s=r%8;for(let o=0;o<n;o+=1)if(e[o]!==t[o])return!1;if(!s)return!0;let a=255<<8-s;return(e[n]&a)===(t[n]&a)}function Me(e){if(ie.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(ie.isIPv6(e)){let t=Ce(e);if(!t)return!1;let r=Ce("::ffff:0:0");return qe(t,r,96)?Me([...t.slice(12)].join(".")):qe(t,Ce("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([s,a])=>qe(t,Ce(s),a)):!1}return!1}function Fr(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(Dr.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=ie.isIP(r);return n!==0&&!Me(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function He(e,{lookupFn:t=$r.promises.lookup}={}){let r=Fr(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:ie.isIPv6(r.host)?6:4}]};let n;try{n=await t(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(s=>!Me(s.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function je({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n;try{let c=await t();r=c.Agent,n=c.fetch}catch(c){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${c?.message||c}`);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=c=>String(c).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),a=new Map,o=c=>(Array.isArray(c)?c:[c]).map(f=>typeof f=="string"?{address:f}:f).filter(f=>f&&f.address).map(f=>({address:f.address,family:f.family||(ie.isIPv6(f.address)?6:4)})),l=(c,f,m)=>{a.set(s(c),o(typeof f=="string"?[{address:f,family:m}]:f))},i=c=>{let f=s(c);if(ie.isIP(f))return[{address:f,family:ie.isIPv6(f)?6:4}];let m=a.get(f);if(!m||!m.length)throw new Error(`refused: unpinned host ${c} during pinned fetch`);return m},d=new r({connect:{lookup(c,f,m){let h;try{h=i(c)}catch(b){return m(b)}return f?.all?m(null,h):m(null,h[0].address,h[0].family)}}}),u=qr((c,f={})=>n(c,{...f,dispatcher:d}),l);return{dispatcher:d,fetch:u,pin:l,resolve:i,async close(){try{await d.destroy()}catch{}}}}function qr(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[Ve]=Object.freeze({pin:t}),e}function ze(e){return typeof e=="function"&&typeof e[Ve]?.pin=="function"}function St(e,t,r){if(!ze(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[Ve].pin(t,r)}var Dr,Ve,xt=K(()=>{Dr=new Set(["localhost","metadata.google.internal","metadata.goog"]);Ve=Symbol.for("oracle.egressGuard.pinCapableFetch")});import{createHash as Mr}from"node:crypto";import{types as ee}from"node:util";function P(e){return ne(`HTTP JSON body refused: ${e}`)}function Yr(e){return["isArgumentsObject","isArrayBuffer","isAnyArrayBuffer","isArrayBufferView","isBoxedPrimitive","isDataView","isDate","isExternal","isGeneratorObject","isKeyObject","isCryptoKey","isMap","isMapIterator","isModuleNamespaceObject","isNativeError","isPromise","isRegExp","isSet","isSetIterator","isTypedArray","isWeakMap","isWeakSet"].some(t=>typeof ee[t]=="function"&&ee[t](e))}function Xr(e){let t=[],r=0,n=0,s=0,a=0,o=new WeakSet,l=u=>{if(r+=Buffer.byteLength(u,"utf8"),r>Z.bytes)throw P("serialized byte limit exceeded");t.push(u)},i=u=>{if(Buffer.byteLength(u,"utf8")>Z.bytes)throw P("serialized byte limit exceeded");return JSON.stringify(u)},d=(u,c)=>{if(n+=1,n>Z.nodes)throw P("node limit exceeded");if(c>Z.depth)throw P("depth limit exceeded");if(u===null){l("null");return}if(typeof u=="string"){l(i(u));return}if(typeof u=="boolean"){l(u?"true":"false");return}if(typeof u=="number"){if(!Number.isFinite(u))throw P("non-finite number");l(Object.is(u,-0)?"0":String(u));return}if(typeof u!="object")throw P("unsupported non-JSON value");if(ee.isProxy(u))throw P("proxy value");if(Yr(u))throw P("unsupported exotic object");if(o.has(u))throw P("cyclic value");o.add(u);try{if(Object.getOwnPropertySymbols(u).length>0)throw P("symbol-keyed fields are unsupported");if(Array.isArray(u)){let h=Object.getPrototypeOf(u),b=0;for(;h!==null;){if(ee.isProxy(h))throw P("proxy array prototype");if(b+=1,b>Z.depth)throw P("array prototype depth limit exceeded");h=Object.getPrototypeOf(h)}if(u.length>Z.arrayLength)throw P("array length limit exceeded");for(let S=0;S<u.length;S+=1){let g=Object.getOwnPropertyDescriptor(u,String(S));if(!g||!Object.hasOwn(g,"value")||g.enumerable!==!0)throw P("array entries must be dense enumerable own data")}let y=0;for(let S in u){if(a+=1,a>Z.fields)throw P("enumeration limit exceeded");if(Object.hasOwn(u,S)&&(y+=1,y>u.length))throw P("named array fields are unsupported")}if(y!==u.length)throw P("array entries must be dense enumerable own data");l("[");for(let S=0;S<u.length;S+=1)S&&l(","),d(Object.getOwnPropertyDescriptor(u,String(S)).value,c+1);l("]");return}let f=Object.getPrototypeOf(u);if(f!==Object.prototype&&f!==null)throw P("non-plain object");let m=[];for(let h in u){if(a+=1,a>Z.fields)throw P("enumeration limit exceeded");if(!Object.hasOwn(u,h))continue;if(s+=1,s>Z.fields)throw P("field limit exceeded");let b=Object.getOwnPropertyDescriptor(u,h);if(!b||!Object.hasOwn(b,"value")||b.enumerable!==!0)throw P("object fields must be enumerable own data");m.push([h,b.value])}l("{");for(let h=0;h<m.length;h+=1)h&&l(","),l(i(m[h][0])),l(":"),d(m[h][1],c+1);l("}")}finally{o.delete(u)}};return d(e,0),t.join("")}function Jr(e){let t=Object.create(null);if(e==null)return t;if(typeof e!="object"&&typeof e!="function")throw new TypeError("HTTP headers must be an object");if(ee.isProxy(e))throw new TypeError("HTTP headers must not be a proxy");if(Object.getOwnPropertySymbols(e).length>0)throw new TypeError("HTTP headers must not contain symbol fields");let r=new Set;for(let n of Object.keys(e)){if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(n))throw new TypeError("HTTP header names must be valid tokens");let s=n.toLowerCase();if(r.has(s))throw new TypeError("HTTP headers contain a duplicate canonical name");r.add(s);let a=Object.getOwnPropertyDescriptor(e,n);if(!a||!Object.hasOwn(a,"value"))throw new TypeError("HTTP headers must contain own data properties");let o=a.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 Zr(){return Object.assign(Object.create(null),{Accept:"application/json"})}function en(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 tn(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function Ie(e){if((typeof e!="object"||e===null)&&typeof e!="function")return`${typeof e}:${String(e)}`;let t=Ot.get(e);return t||(t=Tt,Tt+=1,Ot.set(e,t)),`reference:${t}`}function Nt(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?rn.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 Bt(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(Nt);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return Nt(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&nn.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function on(e,t,r,n={},s=null){let a=Mr("sha256"),o=(i,d)=>{let u=String(d);a.update(String(Buffer.byteLength(i,"utf8"))).update(":").update(i),a.update("=").update(String(Buffer.byteLength(u,"utf8"))).update(":").update(u).update(`
2
- `)};o("method",e),o("url",t),Object.keys(r||{}).map((i,d)=>({name:i.toLowerCase(),order:d,value:String(r[i])})).sort((i,d)=>i.name.localeCompare(d.name)||i.order-d.order).forEach((i,d)=>{o(`header-name-${d}`,i.name),o(`header-value-${d}`,i.value)}),o("body",s??"-");for(let i of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])o(`context-${i}`,n[i]??"-");return a.digest("hex")}function an(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Ct):Math.min(250*2**e,Ct)+Math.floor(Math.random()*100)}function ne(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function Ge(e,t,r){return ne(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function ce(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function cn(e){return e?e.byteLength??e.length??0:0}async function un(e,t,{url:r,truncate:n=!1,onOversize:s}={}){if(t==null)return await e.text();let a=Number(e.headers?.get?.("content-length"));if(Number.isFinite(a)&&a>t&&(ce(e),!n))throw Ge(r,`content-length ${a}`,t);let o=e.body?.getReader?.();if(!o){let c=await e.text(),f=Buffer.byteLength(c,"utf8");if(f>t){if(!n)throw Ge(r,`body ${f} bytes`,t);return Buffer.from(c,"utf8").subarray(0,t).toString("utf8")}return c}let l=[],i=0,d=!1;try{for(;;){let{value:c,done:f}=await o.read();if(f)break;if(c&&(l.push(Buffer.from(c)),i+=cn(c),i>t)){d=!0;break}}}finally{if(d)try{await o.cancel()}catch{}try{o.releaseLock?.()}catch{}}if(d&&(typeof s=="function"&&s(),!n))throw Ge(r,`streamed ${i} bytes`,t);let u=Buffer.concat(l);return(d?u.subarray(0,t):u).toString("utf8")}function ln(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function dn(e,{fetchImpl:t,method:r,headers:n,body:s,timeoutMs:a,lookupFn:o,realFetch:l,untrustedUrl:i=!1,maxResponseBytes:d=null,sameOriginRedirectsOnly:u=!1,importUndici:c,validateResponse:f,signal:m,redirectPolicy:h="follow",maxRedirects:b=ke}){let y=null,S=t,g=o?{lookupFn:o}:{};if(i&&!l&&!ze(S))throw ne(`HTTP refused ${e}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let I=new AbortController,_=setTimeout(()=>I.abort(),a),O=m?kt?kt([m,I.signal]):m:I.signal,L=async(x,{status:B=null}={})=>{let A=await He(x,g);if(!A.ok)throw ne(B==null?`HTTP refused ${x}: ${A.error}`:`HTTP redirect to ${x} ${A.error}`,B==null?{}:{status:B});let k=new URL(x).hostname;if(l){if(y&&(await y.close(),y=null),!y)try{y=await je({requireUndici:!0,...c?{importUndici:c}:{}})}catch(E){throw ne(B==null?`HTTP refused ${x}: ${E?.message||E}`:`HTTP redirect to ${x} refused: ${E?.message||E}`,B==null?{}:{status:B})}y.pin(k,A.addresses),S=y.fetch}else St(S,k,A.addresses);return A};try{let x=String(e),B=Object.assign(Object.create(null),n||{});i&&await L(x);for(let A=0;A<=b;A+=1){let k=Object.assign(Object.create(null),{method:r,headers:B,body:s,signal:O,redirect:"manual",dispatcher:void 0}),E=await S(x,k);if((h==="error"||b===0)&&E.status>=300&&E.status<400)throw ce(E),ne(`HTTP ${E.status} ${r} redirect refused`,{status:E.status,redirectRefused:!0});if(Qr.has(E.status)){let R=u===!0&&r==="POST"&&[307,308].includes(E.status)&&Bt(r,s);if(r!=="GET"&&r!=="HEAD"&&!R){ce(E);let C=new Error(`HTTP ${E.status} ${r} ${x} redirected non-idempotent request`);throw C.status=E.status,C}if(A===b)throw ce(E),ne(`HTTP ${E.status} ${r} redirect budget exhausted`,{status:E.status,redirectRefused:!0});let V=E.headers?.get?.("location"),q;try{q=en(V,x)}catch(C){throw ce(E),C}let D=!tn(q,x);if(ce(E),D&&r==="POST"){let C=new Error(`HTTP ${E.status} ${r} cross-origin redirect refused`);throw C.status=E.status,C}if(D&&u){let C=new Error(`HTTP ${E.status} ${r} cross-origin redirect refused`);throw C.status=E.status,C.retryable=!1,C}if(D&&(B=Zr(B)),i)await L(q,{status:E.status});else if(D){let C=await He(q,g);if(!C.ok){let T=new Error(`HTTP redirect from ${x} ${C.error}`);throw T.status=E.status,T.retryable=!1,T}l&&C.addresses?.length&&(y||(y=await je(c?{importUndici:c}:{})),y&&(y.pin(new URL(q).hostname,C.addresses),S=y.fetch))}x=q;continue}if(typeof f=="function")try{await f(E,{url:x})}catch(R){throw ce(E),ne(R?.message||String(R))}let w=await un(E,d,{url:x,onOversize:()=>I.abort()}),U=ln(w);if(!E.ok){let R=new Error(`HTTP ${E.status} ${r} ${x}`);throw R.status=E.status,R.retryAfter=E.headers?.get?.("retry-after")??null,R.body=U??w.slice(0,300),R}return U??w}throw new Error(`HTTP redirect loop for ${e}`)}catch(x){if(I.signal.aborted&&!ge(m)){let B=x&&(typeof x=="object"||typeof x=="function")&&!ee.isProxy(x)?x:null,A=B?Object.getOwnPropertyDescriptor(B,"oversize"):null;if(!(A&&Object.hasOwn(A,"value")&&A.value===!0))try{if(!B)throw new TypeError("unsafe rejection");Object.defineProperties(B,{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(_),y&&await y.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&&ee.isProxy(t))throw new TypeError("HTTP options must not be a proxy");let r=new Set(["body","dedupe","fetchImpl","headers","importUndici","lookupFn","maxRedirects","maxResponseBytes","method","redirectPolicy","retries","sameOriginRedirectsOnly","signal","timeoutMs","untrustedUrl","validateResponse"]);if(t!=null){if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("HTTP options contain unknown fields");for(let 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 s=n("method");if(s!==void 0&&(typeof s!="string"||!/^[A-Za-z]+$/u.test(s)))throw new TypeError("HTTP method must be a string token");let a=n("timeoutMs");if(a!==void 0&&(!Number.isInteger(a)||a<1||a>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 l=n("redirectPolicy");if(l!==void 0&&l!=="follow"&&l!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let i=n("maxRedirects");if(i!==void 0&&(!Number.isInteger(i)||i<0||i>ke))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${ke}`);if(l==="error"&&i!==void 0&&i!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let d=l??"follow",u=d==="error"?0:i??ke;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 c=n("maxResponseBytes");if(c!==void 0&&(!Number.isInteger(c)||c<1||c>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let f=n("signal");if(f!==void 0){if(ee.isProxy(f)||!(f instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{ge(f)}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 m=n("fetchImpl"),h=m||globalThis.fetch;if(typeof h!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let b=a??12e3,y=(s||"GET").toUpperCase(),S=n("headers"),g=Jr(S),I=Object.assign(Object.create(null),g);Object.keys(I).some(T=>T.toLowerCase()==="accept")||(I.Accept="application/json");let _=n("body");_!=null&&typeof _!="string"&&(Object.keys(I).find(N=>N.toLowerCase()==="content-type")||(I["Content-Type"]="application/json"),_=Xr(_));let O=o??jr,L=n("lookupFn"),x=!m,B=n("untrustedUrl")===!0,A=n("sameOriginRedirectsOnly")===!0,k=n("importUndici"),E=n("validateResponse"),w=f,U=c??null,R=async()=>{let T;for(let N=0;N<=O;N++){w&&Kr.call(w);try{return await dn(e,{fetchImpl:h,method:y,headers:I,body:_,timeoutMs:b,lookupFn:L,realFetch:x,untrustedUrl:B,maxResponseBytes:U,sameOriginRedirectsOnly:A,importUndici:k,validateResponse:E,signal:w,redirectPolicy:d,maxRedirects:u})}catch(F){T=F;let X=M=>{if(!F||typeof F!="object"&&typeof F!="function"||ee.isProxy(F))return;let H=Object.getOwnPropertyDescriptor(F,M);return H&&Object.hasOwn(H,"value")?H.value:void 0},ue=X("status"),Se=X("oracleTimeout")===!0||X("name")==="AbortError"||X("name")==="TimeoutError"||ge(w),xe=new Set([408,425,429]),ve=X("retryable")===!1?!1:ue!=null?xe.has(ue)||Hr.has(ue)&&vt.has(y):!Se&&vt.has(y);if(N===O||!ve)throw F;let p=an(N,X("retryAfter"));w?await new Promise((M,H)=>{let z,re=()=>{clearTimeout(z),It.call(w,"abort",re),H(Wr(w)||new DOMException("Aborted","AbortError"))};if(ge(w)){re();return}z=setTimeout(()=>{It.call(w,"abort",re),M()},p),Gr.call(w,"abort",re,{once:!0}),ge(w)&&re()}):await sn(p)}}throw T};if(!(n("dedupe")!==!1&&!w&&Bt(y,_)))return R();let q=on(y,e,I,{untrustedUrl:B,maxResponseBytes:U,sameOriginRedirectsOnly:A,redirectPolicy:d,maxRedirects:u,timeoutMs:b,retries:O,fetchImpl:Ie(h),realFetch:x,lookupFn:Ie(L),importUndici:Ie(k),validateResponse:Ie(E)},_),D=Ke.get(q);if(D)return D;let C=R().finally(()=>Ke.delete(q));return Ke.set(q,C),C}var Hr,vt,jr,Ct,Vr,zr,Kr,Gr,It,kt,ge,Wr,Qr,ke,fa,Z,Ke,Ot,Tt,rn,nn,sn,$=K(()=>{xt();Hr=new Set([408,425,429,500,502,503,504]),vt=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),jr=2,Ct=4e3,Vr=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,zr=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Kr=AbortSignal.prototype.throwIfAborted,Gr=EventTarget.prototype.addEventListener,It=EventTarget.prototype.removeEventListener,kt=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,ge=e=>e?Vr.call(e):!1,Wr=e=>e?zr.call(e):void 0,Qr=new Set([301,302,303,307,308]),ke=3,fa=64*1024,Z=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});Ke=new Map,Ot=new WeakMap,Tt=1;rn=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),nn=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);sn=e=>new Promise(t=>setTimeout(t,e))});import{readFileSync as pn}from"node:fs";import{homedir as fn}from"node:os";import{join as Oe}from"node:path";function mn(){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=fn();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||Oe(t,".config","oracle")).trim();return[e,Oe(r,"exec.env")].filter(Boolean)}return[e,Oe(t,".config","oracle","exec.env"),Oe(t,".config","mad-desk","exec.env")].filter(Boolean)}function Rt(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let s of mn())try{let a=pn(s,"utf8"),o=a.match(new RegExp(`^${t}=(.*)$`,"m"))||a.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 _t=K(()=>{});var Ut=K(()=>{});import{createHash as hn,createHmac as Lt,timingSafeEqual as gn}from"node:crypto";function Ne(e){return Array.isArray(e)?`[${e.map(Ne).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Ne(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function $t(e,{required:t=!1}={}){try{return Rt(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function Qe(e){let{signature:t,...r}=e;return r}function Dt(e,{secret:t}={}){let r=$t(t);return r?{...e,signature:Lt("sha256",r).update(Ne(Qe(e))).digest("hex")}:e}function bn(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 hn("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function oe(e,{chainId:t,venue:r,data:n,secret:s}={}){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 a=$t(s);if(a){let m=Lt("sha256",a).update(Ne(Qe(e))).digest("hex");if(!wn(e.signature,m))throw new Error("auto-slippage guard signature mismatch \u2014 refusing to bind a guard this Oracle did not issue")}let o=Number(e.selectedBps),l=Number(e.capBps);if(!Number.isInteger(o)||o<0||o>Te||!Number.isInteger(l)||l<0||l>Te||o>l)throw new Error("auto-slippage guard bounds are invalid");let i=BigInt(e.quoteAmountOut??0),d=BigInt(e.minAmountOut??0);if(i<=0n||d<=0n)throw new Error("auto-slippage guard amounts must be positive");let u=i*BigInt(1e4-o),c=u/10000n;if(u%10000n!==0n&&(c+=1n),d<c)throw new Error("auto-slippage guard is under-protected relative to its quote");let f=En(n);if(f!=null&&f!==d)throw new Error(`auto-slippage: calldata encodes floor ${f}, not the guard floor ${d} \u2014 refusing to bind`);return Dt({...Qe(e),calldataHash:bn(n)},{secret:s})}function wn(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:gn(r,n)}function We(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function yn(e){let t=e==null?Te: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,Te)}function ae({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:s}={}){let a=We(e,0),o=a>0?a>=25e4?5:a>=1e5?10:a>=5e4?20:a>=1e4?40:70:n?30:10,l=Math.min(60,Math.abs(We(t,0))*2),i=Math.min(40,Math.floor(Math.max(0,We(r,0))/5e3)*5),d=Math.max(25,Math.ceil(20+o+l+i)),u=yn(s);return{mode:"auto",requiredBps:d,selectedBps:Math.min(d,u),capBps:u,executable:d<=u}}function An({chainId:e,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:s=0,quoteAgeMs:a=0,crossChain:o=!1,requestedCapBps:l,quotedAtMs:i=Date.now(),ttlMs:d=Pt,secret:u}={}){let c=BigInt(r??0);if(c<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let f=ae({liquidityUsd:n,priceChange5m:s,quoteAgeMs:a,crossChain:o,requestedCapBps:l});if(!f.executable)throw new Error(`auto-slippage requires ${f.requiredBps} bps above hard/requested cap ${f.capBps}; route blocked`);let m=Number(i);if(!Number.isFinite(m))throw new Error("auto-slippage: quotedAtMs must be a finite number");let h=Math.min(3e4,Math.max(1e3,Number(d)||Pt)),b=c*BigInt(1e4-f.selectedBps),y=b/10000n;if(b%10000n!==0n&&(y+=1n),y>c&&(y=c),c>0n&&y<=0n)throw new Error(`auto-slippage: quote ${c} is too small to express a ${f.selectedBps} bps floor without rounding to zero`);let S=Number((c-y)*10000n/(c===0n?1n:c));if(S>f.capBps)throw new Error(`auto-slippage: realised floor implies ${S} bps, above cap ${f.capBps} \u2014 refusing to issue a guard weaker than advertised`);return Dt({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:c.toString(),minAmountOut:y.toString(),requiredBps:f.requiredBps,selectedBps:f.selectedBps,capBps:f.capBps,quotedAtMs:m,expiresAtMs:m+h},{secret:u})}function En(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 a=10;a+64<=t.length;a+=64)n.push(t.slice(a,a+64));let s=a=>n[a]==null?null:BigInt("0x"+n[a]);switch(r){case"0x414bf389":return s(6);case"0x04e45aaf":return s(5);case"0xc04b8d59":{let a=s(0);if(a==null)return null;let o=Number(a)/32;return!Number.isInteger(o)||o<0?null:s(o+4)}case"0xb858183f":{let a=s(0);if(a==null)return null;let o=Number(a)/32;return!Number.isInteger(o)||o<0?null:s(o+3)}case"0xa026383e":return s(6);case"0x38ed1739":case"0x5c11d795":return s(1);case"0x7ff36ab5":case"0xb6f9de95":return s(0);case"0x18cbafe5":case"0x791ac947":return s(1);default:return null}}function W(e,{chainId:t,venue:r,amountOut:n,liquidityUsd:s,priceChange5m:a,crossChain:o,requestedCapBps:l,quotedAtMs:i=Date.now(),ttlMs:d}={}){let u=An({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:s,priceChange5m:a,crossChain:o,requestedCapBps:l,quotedAtMs:i,ttlMs:d});return{...e,autoSlippage:u,amountOutMinimum:u.minAmountOut}}var Te,Pt,te=K(()=>{_t();Ut();Te=100,Pt=2e4});var le,Be=K(()=>{le="0x000000000000000000000000000000000000dEaD"});import{createHash as Sn,createHmac as xn,timingSafeEqual as ka}from"node:crypto";function Ye(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Ye).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Ye(e[r])}`).join(",")}}`}function Ft(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function qt(e=process.env){return Ft(process.env)||Ft(e)}function kn(e){let{prepareHash:t,prepareMac:r,note:n,...s}=e||{};return s}function On(e){let t=kn(e);return Sn("sha256").update(Ye(t)).digest("hex")}function Tn(e,t=qt()){return t?xn("sha256",t).update(String(e)).digest("hex"):""}function j(e,{provider:t,kind:r,env:n=process.env,nowMs:s=Date.now(),expiresAtMs:a}={}){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 l={...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(!l.provider)throw new Error("stampPrepared: provider required");if(!l.kind)throw new Error("stampPrepared: kind required");let i=Number(s),d=a==null?i+Cn:Number(a),u=d-i;if(!Number.isSafeInteger(i)||!Number.isSafeInteger(d)||u<=0||u>In)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let f={...l,preparedAt:i,expiresAt:d,prepareVersion:vn},m=On(f),h=qt(n),b=h?Tn(m,h):void 0,y={...f,prepareHash:m};return b&&(y.prepareMac=b),y}var vn,Cn,In,Q=K(()=>{vn=2,Cn=300*1e3,In=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Contract as Nn,JsonRpcProvider as Bn}from"ethers";function $n(e){return Ln.test(String(e||""))}async function Mt(e,{contract:t=Rn,rpc:r=Un,chainId:n=_n,balanceOf:s}={}){if(!$n(e))throw new Error("invalid-address");if(s)return BigInt(await s(e));let a=new Bn(r,n,{staticNetwork:!0}),o=new Nn(t,Pn,a);return BigInt(await o.balanceOf(e))}var Rn,_n,Un,Pn,Ln,Ht=K(()=>{Rn="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",_n=999,Un="https://rpc.hyperliquid.xyz/evm",Pn=["function balanceOf(address owner) view returns (uint256)"],Ln=/^0x[a-fA-F0-9]{40}$/});import{existsSync as Dn,readFileSync as Fn,lstatSync as qn}from"node:fs";import{homedir as jt}from"node:os";import{join as Xe}from"node:path";function jn(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(Vt,t)?Vt[t]:Hn}function Wn(e=process.env){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){if(e[zt])return String(e[zt]);let t=e.ORACLE_CONFIG_DIR||Xe(jt(),".config","oracle");return Xe(t,"fee-recipient")}return Xe(jt(),".config","oracle","fee-recipient")}function Qn(e=process.env){try{let t=Wn(e);if(!Dn(t)||qn(t).isSymbolicLink())return"";let r=Fn(t,"utf8").trim().toLowerCase();return/^0x[a-f0-9]{40}$/.test(r)?r:""}catch{return""}}function Yn(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),Mn)}function Xn({env:e=process.env,action:t="swap",admin:r=!1}={}){let n=String(e[zn]||"").trim(),s=String(e[Kn]||Gn).trim();if(r===!0)return{bps:0,recipient:"",integrator:s,action:t,applies:!1,reason:"admin-oracle"};let a=jn(t),o=Yn(e[Vn],{fallback:n?a:0}),l=Math.min(o,a);if(!l)return{bps:0,recipient:"",integrator:s,action:t,applies:!1,reason:"not-configured"};if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{bps:0,recipient:"",integrator:s,action:t,applies:!1,reason:"no-recipient"};let i=Qn(e);return!i||i!==n.toLowerCase()?{bps:0,recipient:"",integrator:s,action:t,applies:!1,reason:"recipient-not-pinned"}:{bps:l,recipient:n,integrator:s,action:t,applies:!0,reason:"configured"}}async function Je({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={},admin:s=!1}={}){let a=Xn({env:t,action:r,admin:s});if(s===!0)return{...a,holderVerificationStatus:"admin-oracle"};let o=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(o))return{...a,holderVerificationStatus:"wallet-required"};try{return BigInt(await Mt(o,n))>0n?{...a,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...a,holderVerificationStatus:"non-holder"}}catch{return{...a,holderVerificationStatus:"unavailable"}}}function Kt(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 Gt(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}var Mn,Hn,Vt,Vn,zn,Kn,zt,Gn,Re=K(()=>{Ht();Mn=100,Hn=5,Vt=Object.freeze({swap:5,bridge:5,perps:0,nft:0});Vn="ORACLE_INTEGRATOR_FEE_BPS",zn="ORACLE_INTEGRATOR_FEE_RECIPIENT",Kn="ORACLE_INTEGRATOR_ID",zt="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",Gn="oracle"});var Qt={};$e(Qt,{LIFI_API:()=>Wt,lifiChains:()=>to,lifiHealth:()=>tt,lifiPrepare:()=>eo,lifiQuote:()=>pe});function et(e={}){return(e.baseUrl||process.env.LIFI_API_URL||Wt).replace(/\/$/,"")}function Zn(e){let t=String(e||Ze).toLowerCase();return t===Ze.toLowerCase()||t===Jn}function de(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 tt(e={}){let t=await v(`${et(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 pe(e={},t={}){let{fromChain:r,toChain:n=r,fromToken:s=Ze,toToken:a,fromAmount:o,fromAddress:l=le}=e;if(r==null||!a||!o)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let i=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:s,toToken:a,fromAmount:String(o),fromAddress:l}),d=ae({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!d.executable)throw new Error(`lifi: route requires ${d.requiredBps} bps above cap ${d.capBps}`);i.set("slippage",String(d.selectedBps/1e4));let u=await Je({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[y,S]of Object.entries(Gt(u)))i.set(y,S);let c=await v(`${et(t)}/quote?${i}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),f=c?.estimate?.toAmount||c?.toAmount;if(!f)return{...c,autoSlippagePolicy:d,oracleFee:u};let m=c?.transactionRequest?.to||c?.estimate?.approvalAddress||"lifi",h=W(c,{chainId:Number(r),venue:m,amountOut:f,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),b=c?.estimate?.toAmountMin||c?.toAmountMin;if(b!=null&&BigInt(b)<BigInt(h.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...h,oracleFee:u}}async function eo(e={},t={}){let r=await pe(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(c=>n[c]!=null))throw new Error("lifi: unsupported transaction authority");if(n.type!=null){let c=String(n.type).trim().toLowerCase();if(!/^(?:0x[0-9a-f]+|\d+)$/.test(c)||BigInt(c)>2n)throw new Error("lifi: unsupported transaction authority")}let a=Number(e.fromChain);if(n.chainId==null)throw new Error("lifi: transaction missing chain authority");if(Number(n.chainId)!==a)throw new Error("lifi: transaction chain mismatch");let o=e.fromAddress?de(e.fromAddress,"transaction sender"):n.from?de(n.from,"transaction sender"):null;if(!o)throw new Error("lifi: transaction missing sender authority");if(n.from&&de(n.from,"transaction sender")!==o)throw new Error("lifi: transaction sender mismatch");let l=de(n.to,"transaction target"),i=String(n.data);if(!/^0x(?:[0-9a-fA-F]{2})+$/.test(i))throw new Error("lifi: transaction calldata must be non-empty hex bytes");let d=String(n.value??"0x0");if(!/^(?:0x[0-9a-fA-F]+|\d+)$/.test(d))throw new Error("lifi: transaction value must be an unsigned integer string");let u=null;if(!Zn(e.fromToken)){let c=r?.estimate?.approvalAddress||r?.approvalAddress;if(!c)throw new Error("lifi: ERC20 route missing approvalAddress");let f=r?.action?.fromToken?.address||r?.estimate?.fromToken?.address||e.fromToken;u={token:de(f,"approval token"),spender:de(c,"approval spender"),amount:String(e.fromAmount)}}return j({provider:"lifi",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:a,quote:r,autoSlippage:r.autoSlippage,requiresApproval:u,transaction:{chainId:a,from:o,to:l,data:i,value:d,...n.gasLimit!=null?{gasLimit:n.gasLimit}:{},slippageGuard:oe(r.autoSlippage,{chainId:a,venue:l,data:i})}},{provider:"lifi",kind:"lifi-tx",env:t.env,nowMs:t.nowMs,expiresAtMs:t.expiresAtMs})}async function to(e={}){return v(`${et(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var Wt,Ze,Jn,_e=K(()=>{$();te();Be();Q();Re();Wt="https://li.quest/v1";Ze="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",Jn="0x0000000000000000000000000000000000000000"});var Le={};$e(Le,{ACROSS_API:()=>Zt,HOP_API:()=>er,RANGO_API:()=>rr,RELAY_API:()=>tr,acrossHealth:()=>ot,acrossSuggestedFees:()=>Ue,hopHealth:()=>at,hopQuote:()=>Pe,rangoQuote:()=>ct,relayHealth:()=>it,relayPrepare:()=>bo,relayQuote:()=>we});async function ot(e={}){try{return{ok:!0,estimatedFillTimeSec:(await Ue({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 Ue(e={},t={}){let{token:r,destinationToken:n=r,originChainId:s,destinationChainId:a,amount:o}=e;if(!r||s==null||a==null||!o)throw new Error("acrossSuggestedFees requires token, originChainId, destinationChainId, amount");let l=new URLSearchParams({token:r,destinationToken:n,originChainId:String(s),destinationChainId:String(a),amount:String(o)}),i=(t.baseUrl||process.env.ACROSS_API_URL||Zt).replace(/\/$/,"");return v(`${i}/suggested-fees?${l}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function at(e={}){try{let t=await Pe({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 Pe(e={},t={}){let{amount:r,token:n="ETH",fromChain:s="ethereum",toChain:a="arbitrum"}=e;if(!r)throw new Error("hopQuote requires amount");let o=e.slippage==null?void 0:Math.round(Number(e.slippage)*100),l=ae({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:s!==a,requestedCapBps:e.maxSlippageBps??e.slippageBps??o});if(!l.executable)throw new Error(`hop: route requires ${l.requiredBps} bps above cap ${l.capBps}`);let i=new URLSearchParams({amount:String(r),token:n,fromChain:s,toChain:a,slippage:String(l.selectedBps/100)}),d=(t.baseUrl||process.env.HOP_API_URL||er).replace(/\/$/,""),u=await v(`${d}/quote?${i}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),c=u?.estimatedRecieved||u?.estimatedReceived;return c?W(u,{chainId:Number(e.originChainId||e.chainId||fo[s]||0),venue:u?.tx?.to||"hop",amountOut:c,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:s!==a,requestedCapBps:e.maxSlippageBps??e.slippageBps??o}):{...u,autoSlippagePolicy:l}}function nr(e){return(e?.steps||[]).flatMap(t=>(t?.items||[]).filter(r=>r?.data?.to&&r?.data?.data).map(r=>({stepId:t.id,...r.data})))}function ho(e){let t=String(e?.data??"").toLowerCase();if(!t.startsWith(st))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 go(e){return nr(e).find(t=>!String(t.data).toLowerCase().startsWith(st))??null}async function it(e={}){try{let t=await we({user:le,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 we(e={},t={}){let{user:r=le,originChainId:n,destinationChainId:s,originCurrency:a="0x0000000000000000000000000000000000000000",destinationCurrency:o="0x0000000000000000000000000000000000000000",amount:l,tradeType:i="EXACT_INPUT"}=e;if(n==null||s==null||!l)throw new Error("relayQuote requires originChainId, destinationChainId, amount");let d=ae({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(s),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!d.executable)throw new Error(`relay: route requires ${d.requiredBps} bps above cap ${d.capBps}`);let u=(t.baseUrl||process.env.RELAY_API_URL||tr).replace(/\/$/,""),c=await v(`${u}/quote`,{method:"POST",body:{user:r,originChainId:Number(n),destinationChainId:Number(s),originCurrency:a,destinationCurrency:o,amount:String(l),tradeType:i,slippageTolerance:String(d.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),f=c?.details?.currencyOut?.amount;if(!f||!/^\d+$/.test(String(f)))return{...c,autoSlippagePolicy:d};let m=go(c);return W(c,{chainId:Number(n),venue:m?.to||"relay",amountOut:f,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(s),requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function bo(e={},t={}){let r=await we(e,t),n=Number(e.originChainId),s=nr(r);if(!s.length)throw new Error("relay: quote returned no executable transaction items");let a=String(r?.autoSlippage?.venue||"").toLowerCase(),o=[],l=[];for(let u of s){if(u.chainId!=null&&Number(u.chainId)!==n)throw new Error("relay: transaction chain mismatch");if(e.user&&u.from&&String(u.from).toLowerCase()!==String(e.user).toLowerCase())throw new Error("relay: transaction sender mismatch");let c=ho(u);c?o.push({tx:u,approval:c}):l.push(u)}if(!l.length)throw new Error("relay: quote returned no bridge deposit transaction");if(l.some(u=>String(u.to).toLowerCase()!==a))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 i=null;if(o.length===1){let{tx:u,approval:c}=o[0],f=String(e.originCurrency||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(f)||f===mo)throw new Error("relay: native route returned an ERC20 approval");if(String(u.to).toLowerCase()!==f)throw new Error("relay: approval token mismatch");if(c.amount!==String(e.amount))throw new Error("relay: approval amount must equal the exact input amount");if(!l.some(m=>String(m.to).toLowerCase()===c.spender))throw new Error("relay: approval spender does not match the bridge target");i={token:f,spender:c.spender,amount:String(e.amount)}}let d=s.map(u=>({chainId:n,from:u.from||e.user,to:u.to,data:u.data,value:u.value??"0x0",...u.gasLimit!=null||u.gas!=null?{gasLimit:u.gasLimit??u.gas}:{},...String(u.data).toLowerCase().startsWith(st)?{}:{slippageGuard:oe(r.autoSlippage,{chainId:n,venue:u.to,data:u.data})}}));return j({provider:"relay",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:r,autoSlippage:r.autoSlippage,requiresApproval:i,destination:a,transactions:d},{provider:"relay",kind:"relay-tx",env:t.env,nowMs:t.nowMs,expiresAtMs:t.expiresAtMs})}async function ct({from:e,to:t,amount:r,slippage:n=1,enableCentralizedSwappers:s=!1}={},a={}){if(!e||!t||!r)throw new Error("rangoQuote requires from, to, amount");let o=a.env??process.env,l=a.rangoApiKey||o.RANGO_API_KEY;if(!l)throw new Error("rango: RANGO_API_KEY is required");let i=new URLSearchParams({from:e,to:t,amount:String(r),slippage:String(n),enableCentralizedSwappers:s?"true":"false",apiKey:l}),d=(a.rangoBaseUrl||process.env.RANGO_API_URL||rr).replace(/\/$/,""),u;try{u=await v(`${d}/basic/quote?${i}`,{fetchImpl:a.fetchImpl,timeoutMs:a.timeoutMs??2e4,retries:a.retries})}catch(c){let f=Number.isInteger(c?.status)?` (HTTP ${c.status})`:"";throw new Error(`rango: request failed${f}`)}if(u?.error||u?.resultType&&u.resultType!=="OK"){let c=String(u?.error||u.resultType).split(l).join("[redacted]").split(encodeURIComponent(l)).join("[redacted]").slice(0,160);throw new Error(`rango: ${c}`)}return{amountOut:u?.route?.outputAmount,feeUsd:u?.route?.feeUsd??null,estimatedTime:u?.route?.estimatedTimeInSeconds}}var Zt,er,tr,rr,fo,st,mo,ye=K(()=>{$();te();Be();Q();Zt="https://across.to/api",er="https://api.hop.exchange/v1",tr="https://api.relay.link",rr="https://api.rango.exchange",fo={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453};st="0x095ea7b3",mo="0x0000000000000000000000000000000000000000"});var pr={};$e(pr,{DEBRIDGE_API:()=>lr,debridgeHealth:()=>dt,debridgePrepare:()=>Oo,debridgeQuote:()=>lt});function dr(e={}){return(e.baseUrl||process.env.DEBRIDGE_API_URL||lr).replace(/\/$/,"")}function ut(e,t=200){return String(e?.message||e||"unknown error").slice(0,t)}function ko(e){return typeof e?.to=="string"&&e.to.length>0&&/^0x(?:[0-9a-fA-F]{2})+$/.test(String(e.data||""))}async function lt({srcChainId:e,srcChainTokenIn:t,srcChainTokenInAmount:r,dstChainId:n,dstChainTokenOut:s,taker:a,slippage:o=100,affiliateFeePercent:l="0"}={},i={}){if(!e||!n||!t||!s||!r)return{error:"debridge quote requires srcChainId, dstChainId, srcChainTokenIn, dstChainTokenOut, srcChainTokenInAmount"};try{let d=new URLSearchParams({srcChainId:String(e),srcChainTokenIn:t,srcChainTokenInAmount:String(r),dstChainId:String(n),dstChainTokenOut:s,dstChainTokenOutAmount:"auto",slippage:String(o),affiliateFeePercent:String(l)});a&&(d.set("dstChainTokenOutRecipient",a),d.set("srcChainOrderAuthorityAddress",a),d.set("dstChainOrderAuthorityAddress",a));let u=await v(`${dr(i)}/dln/order/create-tx?${d}`,{fetchImpl:i.fetchImpl,timeoutMs:i.timeoutMs??2e4,retries:i.retries,headers:i.headers});return u?.error?{error:ut(u.error)}:{estimation:u?.estimation??{},order:u?.order??{},fixFee:u?.fixFee??u?.estimation?.fixFee??"0",tx:u?.tx??null,walletBinding:a?{dstChainTokenOutRecipient:a,srcChainOrderAuthorityAddress:a,dstChainOrderAuthorityAddress:a}:null}}catch(d){return{error:ut(d)}}}async function dt(e={}){try{let t=await v(`${dr(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:ut(t,160)}}}async function Oo(e,{taker:t}={}){if(!t)throw new Error("debridge prepare requires taker address");if(!ko(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(s=>String(s||"").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 j({provider:"debridge",kind:"debridge-tx",calldataReady:!0,requiresUserSignature:!0,transaction:e.tx,quote:e},{provider:"debridge",kind:"debridge-tx"})}var lr,pt=K(()=>{$();Q();lr="https://dln.debridge.finance/v1.0"});var ra=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),De=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),Fe=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"});var J=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"});var wt=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}};function yt(e){let{source:t,amountOut:r,minOut:n=null,gasUsd:s=null,feeUsd:a=null,feeIncludedInAmountOut:o=!1,oracleFeeBps:l=0,estimatedGas:i=null,liquidityUsd:d=null,error:u=null,executionReady:c=!1,meta:f={}}=e||{};if(u||r==null)return{source:t,quality:J.FAILED,amountOut:null,error:u||"no amountOut returned"};let m=wt(r);if(m==null||m<=0n)return{source:t,quality:J.FAILED,amountOut:null,error:"non-positive amountOut"};let h=Number(l);return{source:t,quality:s==null?J.NO_GAS:J.FULL,amountOut:m.toString(),minOut:wt(n)?.toString()??null,gasUsd:s,feeUsd:a,feeIncludedInAmountOut:o===!0,oracleFeeBps:Number.isFinite(h)&&h>0?Math.floor(h):0,estimatedGas:i==null?null:String(i),liquidityUsd:d==null?null:Number(d),executionReady:c,meta:f}}function At(e,{destPriceUsd:t=null,destDecimals:r=null,liquidityFirst:n=!0,liquidityBandBps:s=50,gasPriceWei:a=null,nativePriceUsd:o=null}={}){let l=e.filter(A=>A.quality!==J.FAILED),i=e.filter(A=>A.quality===J.FAILED),d=t!=null&&t>0&&r!=null&&r>=0,u=Number(a),c=Number(o),f=Number.isFinite(u)&&u>0&&Number.isFinite(c)&&c>0,m=l.map(A=>{let k=BigInt(A.amountOut),E=0n,w=!1,U=!1,R=BigInt(A.oracleFeeBps??0),V=R>0n?k*R/10000n:0n;if(d){let C=A.gasUsd,T=Number(A.meta?.gasUnits??A.estimatedGas);if(C==null&&f&&Number.isFinite(T)&&T>0){let F=T*u/1e18*c;Number.isFinite(F)&&F>=0&&(C=F,U=!0)}let N=(C??0)+(A.feeIncludedInAmountOut?0:A.feeUsd??0);if(N>0){let F=N/t*10**r;Number.isFinite(F)&&F>=0&&(E=BigInt(Math.floor(F)),w=!0)}else C===0&&(w=!0)}let q=E+V,D=k>q?k-q:0n;return{...A,grossOut:k.toString(),netOut:D.toString(),costInDest:E.toString(),oracleFeeInDest:V.toString(),costAccounted:w,gasEstimated:U}}),h=Number(s)>0?Number(s):0,b=m.reduce((A,k)=>BigInt(k.netOut)>A?BigInt(k.netOut):A,0n),y=A=>b>0n?Number((b-BigInt(A))*10000n/b):0,S=[],g=(A,k)=>{let E=BigInt(A.netOut),w=BigInt(k.netOut);return E!==w?w>E?1:-1:String(A.source).localeCompare(String(k.source))},I=m.slice().sort(g)[0]??null;m.sort((A,k)=>{let E=y(A.netOut)<=h?0:1,w=y(k.netOut)<=h?0:1;if(n&&h>0&&E!==w)return E-w;if(n&&h>0){let U=A.liquidityUsd??-1,R=k.liquidityUsd??-1;if(U!==R)return R-U}return g(A,k)}),n&&h>0&&I&&m[0]&&m[0].source!==I.source&&S.push(`liquidity-first: chose ${m[0].source} (liquidity $${m[0].liquidityUsd??"unknown"}) over best-price ${I.source} within ${h} bps`);let _=m.filter(A=>!A.costAccounted).map(A=>A.source);d?_.length&&S.push(`gas not reported by: ${_.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):S.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let O=m[0];if(d&&O&&O.costAccounted===!1){let A=m.find(k=>k.costAccounted&&y(k.netOut)<=h);A&&S.push(`winner ${O.source} has UNMEASURED gas; gas-measured ${A.source} is within ${h} bps and may net more once ${O.source}'s real gas is paid \u2014 prefer it if unsure.`)}let L=m.filter(A=>A.gasEstimated).map(A=>A.source);L.length&&S.push(`gas ESTIMATED (from gas units x current gas price, not measured) for: ${L.join(", ")}. Net includes this estimate so the ranking is gas-inclusive, but the on-chain gas may differ.`);let x=null,B=null;if(m.length>=2&&m[0].costAccounted&&m[1].costAccounted){let A=BigInt(m[0].netOut),k=BigInt(m[1].netOut);k>0n&&(x=Number((A-k)*10000n/k),B=`${m[0].source} vs ${m[1].source}`)}return{best:m[0]??null,routes:m,failed:i,improvementBps:x,spreadBasis:B,rankedOn:d?"net-of-cost":"gross",warnings:S}}async function Et(e,{timeoutMs:t=12e3}={}){let r=(s,a)=>{let o;return Promise.race([s,new Promise((l,i)=>{o=setTimeout(()=>i(new Error(`${a}: timeout`)),t)})]).finally(()=>clearTimeout(o))};return(await Promise.allSettled(e.map(s=>r(Promise.resolve().then(s.run),s.source)))).map((s,a)=>{let o=e[a].source;return s.status==="rejected"?yt({source:o,error:String(s.reason?.message||s.reason)}):yt({source:o,...s.value})})}_e();$();te();Q();Re();$();te();Q();$();te();Q();$();te();import{TypedDataEncoder as us,getAddress as ls,isAddress as ds}from"ethers";var os=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});Be();Q();var ws=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),ys=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"});var As=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"}]}),Es=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]});import{Interface as Xt,getAddress as qs,isAddress as Ms}from"ethers";$();var Yt={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}},xs=new Map(Object.values(Yt).map(e=>[e.chainId,e]));import{Interface as oo,getAddress as Bs}from"ethers";var Rs=new oo(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);$();var $s=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});te();Q();var Ks=new Xt(["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)"]),Gs=new Xt(["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 io,Interface as rt,getAddress as Xs,isAddress as Js,keccak256 as Zs}from"ethers";te();Q();var oi=io.defaultAbiCoder();var ai=new rt(["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)"]),si=new rt(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),ii=new rt(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96,int24 tick,uint24 protocolFee,uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),ci=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"]]),ui=(1n<<14n)-1n;$();var co="https://coins.llama.fi",uo="https://api.llama.fi";function lo(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||co).replace(/\/$/,"")}function po(e={}){return(e.baseUrl||process.env.DEFILLAMA_API_URL||uo).replace(/\/$/,"")}async function nt(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return v(`${lo(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function Jt(e={}){return v(`${po(e)}/protocols`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??2e4})}var G=e=>{let t=Number(e);return Number.isFinite(t)?t:null};function or(e){if(!Array.isArray(e))return null;let t=0,r=!1;for(let n of e){let s=G(n?.amountUSD);s!=null&&(t+=s,r=!0)}return r?t:null}function ar(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 se=e=>String(e??"").toLowerCase().replace(/[^a-z0-9]/g,""),sr=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 wo(e={}){try{let t=await Jt({...e,baseUrl:e.defillamaApiBaseUrl,timeoutMs:e.defillamaTimeoutMs??Math.min(Number(e.timeoutMs??5e3),5e3)});return Array.isArray(t)?t:[]}catch{return[]}}function yo(e,t={}){let r=se(t.tool||t.provider||t.bridge||t.protocol),n=[];return e==="lifi"&&r&&r!=="lifi"&&n.push(...sr[r]||[r]),n.push(...sr[se(e)]||[e]),n}function Ao(e,t,r={}){let n=Array.isArray(e)?e:[],s=yo(t,r).map(se).filter(Boolean);for(let a of s){let o=n.find(i=>se(i?.slug)===a||se(i?.name)===a),l=G(o?.tvl);if(l!=null)return{liquidityUsd:l,protocol:o?.name??o?.slug??a}}for(let a of s){let o=n.find(i=>{let d=se(i?.category);return!d.includes("bridge")&&!d.includes("crosschain")?!1:se(i?.slug).includes(a)||se(i?.name).includes(a)}),l=G(o?.tvl);if(l!=null)return{liquidityUsd:l,protocol:o?.name??o?.slug??a}}return null}function ir({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:s,taker:a,slippageBps:o,allowedSources:l,opts:i={}}){let d=[],u=null,c=async(m,h={})=>(u||=wo(i),Ao(await u,m,h));if(d.push({source:"lifi",run:async()=>{let m=await pe({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:s,fromAddress:a,slippageBps:o},i),h=m?.estimate??m?.[0]?.estimate,b=(m?.includedSteps??m?.steps??[]).map((g,I)=>({id:String(g?.id??`step-${I+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)})),y={tool:m?.tool??m?.toolDetails?.name,durationSeconds:G(h?.executionDuration),destinationDecimals:G(m?.action?.toToken?.decimals),routeSteps:b,feeCosts:ar(h?.feeCosts),gasCosts:ar(h?.gasCosts)},S=await c("lifi",y);return{amountOut:h?.toAmount,minOut:h?.toAmountMin,gasUsd:or(h?.gasCosts),feeUsd:or(h?.feeCosts),feeIncludedInAmountOut:!0,oracleFeeBps:m?.oracleFee?.applies?m.oracleFee.bps:0,liquidityUsd:S?.liquidityUsd??null,meta:{...y,liquidityProtocol:S?.protocol,oracleFee:m?.oracleFee??null}}}}),d.push({source:"relay",run:async()=>{let{relayQuote:m}=await Promise.resolve().then(()=>(ye(),Le)),h=await m({user:a,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(s),slippageBps:o},i),b=h?.details,y=(h?.steps??[]).map((L,x)=>({id:String(L?.id??`step-${x+1}`),type:String(L?.kind??"transaction"),tool:"Relay",label:String(L?.description??L?.action??L?.id??`Step ${x+1}`),fromChainId:Number(e),toChainId:Number(t)})),S=String(h?.fees?.relayer?.amountUsd??"").trim(),g=String(h?.fees?.gas?.amountUsd??"").trim(),I=String(b?.totalImpact?.usd??"").trim(),_={durationSeconds:G(b?.timeEstimate),rate:b?.rate,destinationDecimals:G(b?.currencyOut?.currency?.decimals),routeSteps:y,feeCosts:[.../^\d+(?:\.\d+)?$/.test(S)?[{name:"relayer",amountUsd:S}]:[],.../^-?\d+(?:\.\d+)?$/.test(I)?[{name:"total-impact",amountUsd:I}]:[]],gasCosts:/^\d+(?:\.\d+)?$/.test(g)?[{name:"origin-gas",amountUsd:g}]:[]},O=await c("relay",_);return{amountOut:b?.currencyOut?.amount,minOut:b?.currencyOut?.minimumAmount,gasUsd:G(h?.fees?.gas?.amountUsd),feeUsd:G(h?.fees?.relayer?.amountUsd)??(G(b?.totalImpact?.usd)!=null?Math.abs(G(b.totalImpact.usd)):null),feeIncludedInAmountOut:!0,liquidityUsd:O?.liquidityUsd??null,meta:{..._,liquidityProtocol:O?.protocol}}}}),d.push({source:"across",run:async()=>{let{acrossSuggestedFees:m}=await Promise.resolve().then(()=>(ye(),Le)),h=await m({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(s)},i),b=h?.totalRelayFee?.total,y=null;if(b!=null)try{let g=BigInt(String(s))-BigInt(String(b));g>0n&&(y=g.toString())}catch{}let S=await c("across");return{amountOut:y,gasUsd:null,liquidityUsd:S?.liquidityUsd??null,meta:{derivedFromFees:!0,durationSeconds:G(h?.estimatedFillTimeSec),limits:h?.limits?{min:h.limits.minDeposit,max:h.limits.maxDeposit}:void 0,liquidityProtocol:S?.protocol}}}}),!Array.isArray(l))return d;let f=new Set(l.map(m=>String(m).toLowerCase()));return d.filter(m=>f.has(m.source))}Re();var Eo={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"},cr=Object.freeze(["lifi","relay"]);function So(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 xo(e,t=cr){let r=new Set((Array.isArray(t)?t:cr).map(o=>String(o).toLowerCase())),n=(e?.routes??[]).filter(o=>r.has(o.source)),s=new Set(n.map(o=>o.source)),a=(e?.failed??[]).filter(o=>r.has(o.source)&&!s.has(o.source));return[...n,...a].map(o=>({provider:o.source,status:o.quality===J.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 vo(e,t,r){let n=Eo[Number(e)];if(!n)return{priceUsd:null,decimals:null};let s=`${n}:${t}`;try{let o=(await nt([s],r))?.coins?.[s],l=Number(o?.price),i=Number(o?.decimals);return{priceUsd:Number.isFinite(l)?l:null,decimals:Number.isFinite(i)?i:null}}catch{return{priceUsd:null,decimals:null}}}async function ur(e,t={}){let{fromChainId:r,toChainId:n,tokenIn:s,tokenOut:a,amountIn:o}=e;if(r==null||n==null||!s||!a||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 l=So(e.slippageBps),i={...e,slippageBps:l},d=vo(n,a,t),u=ir({...i,opts:t}),[c,f]=await Promise.all([Et(u,{timeoutMs:t.timeoutMs??15e3}),d]),m=At(c,{destPriceUsd:f.priceUsd,destDecimals:e.decimalsOut??f.decimals,liquidityFirst:!1,liquidityBandBps:0}),h=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:s,tokenOut:a,amountIn:String(o),slippageBps:l,...m,routeOptions:xo(m,e.allowedSources),durations:h,sourcesTried:u.length,sourcesAnswered:c.filter(b=>b.quality!==J.FAILED).length,note:Io(m,u.length)}}function Co(e){let t=e?.meta?.oracleFee;return t?.applies?` \xB7 ${Kt(t)}`:""}function Io(e,t){if(!e.best)return"no source returned a usable route";let r=e.routes.length,n=Co(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 s=e.improvementBps,a=s/100;if(s<.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=a>=.01?`${a.toFixed(2)}%`:`${s.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}Q();_e();pt();$();var ft="https://api.changenow.io/v2",fe=new Map,fr=0,To=6e5;async function No({active:e=!0}={},t={}){let r=Date.now();if(fe.size&&r-fr<To)return[...fe.values()];try{let n=await v(`${ft}/exchange/currencies?active=${e?"true":"false"}`,t);fe.clear();for(let s of n??[])fe.set(String(s.ticker).toLowerCase(),s);return fr=r,n??[]}catch(n){return fe.size?[...fe.values()]:{error:String(n.message||n).slice(0,200)}}}async function Bo(e,t,r={}){if(!e||!t)return{error:"changenow minAmount requires fromTicker and toTicker"};try{return{minAmount:(await v(`${ft}/exchange/min-amount/${encodeURIComponent(e)}_${encodeURIComponent(t)}`,r))?.minAmount??"0"}}catch(n){return{error:String(n.message||n).slice(0,200)}}}async function Ro(e,t,r,{flow:n="standard"}={},s={}){if(!e||!t||!r)return{error:"changenow estimate requires fromTicker, toTicker, fromAmount"};try{let a=new URLSearchParams({fromCurrency:String(e).toLowerCase(),toCurrency:String(t).toLowerCase(),fromAmount:String(r),flow:n}),o=await v(`${ft}/exchange/estimated-amount?${a}`,s);return{fromAmount:o?.fromAmount,toAmount:o?.toAmount,rate:o?.rate,flow:o?.flow??n}}catch(a){return{error:String(a.message||a).slice(0,200)}}}async function mr({fromTicker:e,toTicker:t,fromAmount:r,flow:n}={},s={}){if(!e||!t)return{error:"changenow quote requires fromTicker and toTicker"};let a=await Bo(e,t,s);if(a.error)return a;let o=r??a.minAmount,l=await Ro(e,t,o,{flow:n},s);if(l.error)return l;let i=await No({},s),d=i.find(c=>String(c?.ticker).toLowerCase()===String(e).toLowerCase()),u=i.find(c=>String(c?.ticker).toLowerCase()===String(t).toLowerCase());return{provider:"changenow",fromTicker:e,toTicker:t,fromAmount:o,toAmount:l.toAmount,estimatedRate:l.rate,minAmount:a.minAmount,flow:l.flow,networkFee:d?.networkFee??null,kycRequired:d?.kycRequired??u?.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 _o="https://api.squidrouter.com/v1";async function hr({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:s,fromAddress:a,slippage:o=1}={},l={}){if(!e||!t||!r||!n||!s||!a)return{error:"squid quote requires fromChain, toChain, fromToken, toToken, fromAmount, fromAddress"};try{let i={fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:String(s),fromAddress:a,slippage:o},d=await v(`${_o}/route`,{...l,method:"POST",body:JSON.stringify(i),headers:{"content-type":"application/json",...l.headers||{}}});return{route:d?.route??{},toAmount:d?.route?.estimate?.toAmount,fee:d?.route?.estimate?.feeCosts}}catch(i){return{error:String(i.message||i).slice(0,200)}}}$();var Uo="https://api.stargate.finance";async function gr({srcChainId:e,dstChainId:t,token:r,amount:n,dstGasForCall:s=0,minAmountOut:a="0"}={},o={}){if(!e||!t||!r||!n)return{error:"stargate quote requires srcChainId, dstChainId, token, amount"};try{let l=new URLSearchParams({srcChainId:String(e),dstChainId:String(t),token:r,amount:String(n),dstGasForCall:String(s),minAmountOut:String(a)}),i=await v(`${Uo}/quote?${l}`,o);return{amountOut:i?.amountOut,fee:i?.fee,estimatedTime:i?.estimatedTime}}catch(l){return{error:String(l.message||l).slice(0,200)}}}$();var br="https://midgard.ninerealms.com/v2";async function wr({fromAsset:e,toAsset:t,amount:r,destination:n}={},s={}){if(!e||!t||!r)return{error:"thorchain quote requires fromAsset, toAsset, amount"};try{let a=new URLSearchParams({from_asset:e,to_asset:t,amount:String(r),destination:n||""}),o=await v(`${br}/quote/swap?${a}`,s);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(a){return{error:String(a.message||a).slice(0,200)}}}async function yr(){try{return{ok:(await v(`${br}/health`))?.scannerHeight>0}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}$();var Po="https://api.socket.tech/v2";async function Ar({fromChainId:e,toChainId:t,fromToken:r,toToken:n,fromAmount:s,userAddress:a}={},o={}){if(!e||!t||!r||!n||!s||!a)return{error:"bungee quote requires fromChainId, toChainId, fromToken, toToken, fromAmount, userAddress"};try{let l=new URLSearchParams({fromChainId:String(e),toChainId:String(t),fromTokenAddress:r,toTokenAddress:n,fromAmount:String(s),userAddress:a,sort:"output",singleTxOnly:"false"}),i=await v(`${Po}/quote?${l}`,o);return{amountOut:i?.result?.toAmount,feeUsd:i?.result?.totalGasFeesInUsd,route:i?.result?.route,estimatedTime:i?.result?.serviceTime?`${i.result.serviceTime}s`:"unknown"}}catch(l){return{error:String(l.message||l).slice(0,200)}}}$();var Lo="https://api.connext.network";async function Er({originDomain:e,destinationDomain:t,originToken:r,destinationToken:n,amount:s}={},a={}){if(!e||!t||!r||!n||!s)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(s)},l=await v(`${Lo}/estimate`,{...a,method:"POST",body:JSON.stringify(o),headers:{"content-type":"application/json",...a.headers||{}}});return{amountOut:l?.amountOut,fee:l?.fee,estimatedTime:l?.estimatedTransferTime}}catch(o){return{error:String(o.message||o).slice(0,200)}}}$();var $o="https://api.portalbridge.com/v1";async function Sr({fromChain:e,toChain:t,token:r,amount:n}={},s={}){if(!e||!t||!r||!n)return{error:"wormhole quote requires fromChain, toChain, token, amount"};try{let a=new URLSearchParams({fromChain:String(e),toChain:String(t),token:r,amount:String(n)}),o=await v(`${$o}/quote?${a}`,s);return{amountOut:o?.amountOut,fee:o?.fee,estimatedTime:o?.estimatedTime}}catch(a){return{error:String(a.message||a).slice(0,200)}}}ye();import{Interface as xr,getAddress as $c,id as vr}from"ethers";$();var qo=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 Mc=new xr(["function decimals() view returns (uint8)","function symbol() view returns (string)"]),Hc=new xr(["function isApprovedForAll(address owner, address operator) view returns (bool)","function name() view returns (string)"]),jc=vr("Approval(address,address,uint256)"),Vc=vr("ApprovalForAll(address,address,bool)");var zc=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)"}),Kc=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"}]),Gc=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"}]),Wc=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"}]}),Qc=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}]}),Mo=(1n<<256n)-1n,Yc=Mo/2n,Xc=4320*60*60*1e3,Jc=360*60*1e3,Zc=600*1e3,eu=45*1e3;var Ae=Object.freeze(["debridge","lifi","relay","squid","stargate","thorchain","bungee","connext","wormhole","across","hop","changenow","rango"]),Cr=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche"}),Ho=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"}),jo=Object.freeze({1:"ETH",56:"BSC",8453:"BASE",42161:"ARB",43114:"AVAX"}),Nr=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]);function mt(e,t=180){return String(e?.message||e||"unknown error").replace(/\s+/g," ").slice(0,t)}function Ir(e){let t=String(e??"");if(!/^\d+$/.test(t))return null;try{return BigInt(t)>0n?t:null}catch{return null}}function Vo(e,t){try{let r=BigInt(String(e))-BigInt(String(t));return r>0n?r.toString():null}catch{return null}}function me(e){let t=Number(e);return Number.isInteger(t)&&t>=0&&t<=255?t:null}function zo(e,t){let r=me(t),n=String(e??"");if(r==null||!/^\d+$/.test(n))return null;if(r===0)return n;let s=n.padStart(r+1,"0"),a=s.slice(0,-r),o=s.slice(-r).replace(/0+$/,"");return o?`${a}.${o}`:a}function Ko(e,t){let r=me(t),n=/^(\d+)(?:\.(\d+))?$/.exec(String(e??""));if(r==null||!n)return null;let s=n[2]||"";if(s.length>r&&/[1-9]/.test(s.slice(r)))return null;let a=s.slice(0,r).padEnd(r,"0");try{return(BigInt(n[1])*10n**BigInt(r)+BigInt(a||"0")).toString()}catch{return null}}function kr(e,t,r){let n=me(t),s=me(r);if(n==null||s==null||!/^\d+$/.test(String(e??"")))return null;let a=BigInt(String(e));return s>=n?(a*10n**BigInt(s-n)).toString():(a/10n**BigInt(n-s)).toString()}function ht(e){return typeof e?.to=="string"&&e.to.length>0&&/^0x(?:[0-9a-fA-F]{2})+$/.test(String(e.data||""))}function Go(e){return(e?.steps||[]).some(t=>(t?.items||[]).some(r=>ht(r?.data)))}function Or(e,t,r){let n=Ho[Number(e)];return n?Nr.has(String(t||"").toLowerCase())?r&&r!=="?"?`${n}.${r}`:null:t?`${n}--${t}`:null:null}function Tr(e,t,r){if(!r||r==="?")return null;if(r.includes("."))return r;let n=jo[Number(e)];return n?Nr.has(String(t||"").toLowerCase())?`${n}.${r}`:`${n}.${r}-${t}`:null}async function Br(e={},t={}){let{fromChainId:r,toChainId:n,tokenIn:s,tokenOut:a,amount:o,taker:l,fromSymbol:i="?",toSymbol:d="?",fromDecimals:u,toDecimals:c,slippageBps:f}=e,m=t.includeCentralized===!0||e.includeCentralized===!0,h=me(u),b=me(c),y=new Map(Ae.map(p=>[p,{provider:p,status:"pending"}])),S=[],g={fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs,retries:t.retries,headers:t.headers},I=(p,M,H=!1)=>{y.set(p,{provider:p,status:"unavailable",reason:mt(M),optional:H})},_=(p,M)=>{y.set(p,{provider:p,status:"skipped",reason:mt(M)})},O=(p,M,H)=>{y.set(p,{provider:p,status:"attempted"}),S.push(Promise.resolve().then(M).then(z=>{if(z?.error)throw new Error(z.error);let re=H(z),bt=Ir(re?.amountOut);if(!bt)throw new Error("no usable integer base-unit amountOut");let Pr={...re,provider:p,amountOut:bt,raw:z};return y.set(p,{provider:p,status:"successful"}),Pr}).catch(z=>(y.set(p,{provider:p,status:"failed",reason:mt(z)}),null)))};O("debridge",()=>lt({srcChainId:r,srcChainTokenIn:s,srcChainTokenInAmount:o,dstChainId:n,dstChainTokenOut:a,taker:l,slippage:f},g),p=>({amountOut:p.estimation?.dstChainTokenOut?.amount??p.estimation?.toAmount,feeUsd:p.estimation?.fixFee??p.fixFee,estimatedTime:p.estimation?.execution?.estimatedTransferTime?`${p.estimation.execution.estimatedTransferTime}s`:"unknown",preparable:ht(p.tx)})),O("lifi",()=>pe({fromChain:r,toChain:n,fromToken:s,toToken:a,fromAmount:o,fromAddress:l},g),p=>({amountOut:p.estimate?.toAmount??p.toAmount,feeUsd:p.estimate?.feeCosts??null,estimatedTime:p.estimate?.executionDuration??"unknown",preparable:ht(p.transactionRequest)})),O("relay",()=>we({user:l,originChainId:r,destinationChainId:n,originCurrency:s,destinationCurrency:a,amount:String(o)},g),p=>({amountOut:p.details?.currencyOut?.amount,feeUsd:p.details?.totalImpact?.usd??null,estimatedTime:p.details?.timeEstimate??"unknown",preparable:Go(p)})),O("squid",()=>hr({fromChain:r,toChain:n,fromToken:s,toToken:a,fromAmount:o,fromAddress:l},g),p=>({amountOut:p.toAmount,feeUsd:p.fee??null,estimatedTime:"30s - 3min",preparable:!1})),O("stargate",()=>gr({srcChainId:r,dstChainId:n,token:s,amount:o},g),p=>({amountOut:p.amountOut,feeUsd:p.fee,estimatedTime:p.estimatedTime||"1-5 min",preparable:!1}));let L=kr(o,h,8),x=Tr(r,s,i),B=Tr(n,a,d);h==null||b==null?I("thorchain","fromDecimals and toDecimals are required for unit conversion"):!x||!B?I("thorchain","supported chain mapping plus qualified asset symbols are required"):Ir(L)?O("thorchain",()=>wr({fromAsset:x,toAsset:B,amount:L,destination:l},g),p=>({amountOut:kr(p.expectedAmountOut,8,b),feeUsd:p.fees?.total,estimatedTime:p.estimatedTime||"10-30 min",preparable:!1})):I("thorchain","amount is below THORChain's 8-decimal quote precision"),O("bungee",()=>Ar({fromChainId:r,toChainId:n,fromToken:s,toToken:a,fromAmount:o,userAddress:l},g),p=>({amountOut:p.amountOut,feeUsd:p.feeUsd,estimatedTime:p.estimatedTime,preparable:!1})),O("connext",()=>Er({originDomain:r,destinationDomain:n,originToken:s,destinationToken:a,amount:o},g),p=>({amountOut:p.amountOut,feeUsd:p.fee,estimatedTime:p.estimatedTime||"5-20 min",preparable:!1})),O("wormhole",()=>Sr({fromChain:r,toChain:n,token:s,amount:o},g),p=>({amountOut:p.amountOut,feeUsd:p.fee,estimatedTime:p.estimatedTime||"5-15 min",preparable:!1})),O("across",()=>Ue({token:s,destinationToken:a,originChainId:r,destinationChainId:n,amount:String(o)},g),p=>{let M=p.outputAmount??p.expectedOutputAmount,H=p.totalRelayFee?.total??p.relayFeeTotal;return{amountOut:M??(H!=null?Vo(o,H):null),feeUsd:p.relayFeeTotalUsd??null,estimatedTime:p.estimatedFillTimeSec!=null?`${p.estimatedFillTimeSec}s`:"unknown",preparable:!1}});let A=Cr[Number(r)],k=Cr[Number(n)];!A||!k||!i||i==="?"?I("hop","supported chain mapping and fromSymbol are required"):O("hop",()=>Pe({amount:String(o),token:i,fromChain:A,toChain:k},g),p=>({amountOut:p.estimatedRecieved??p.estimatedReceived,feeUsd:p.feeUsd??null,estimatedTime:p.estimatedTime??"unknown",preparable:!1}));let E=zo(o,h);m?h==null||b==null?I("changenow","fromDecimals and toDecimals are required for unit conversion"):!i||!d||i==="?"||d==="?"?I("changenow","fromSymbol and toSymbol are required"):E==null?I("changenow","valid integer amount is required"):O("changenow",()=>mr({fromTicker:i,toTicker:d,fromAmount:E},g),p=>({amountOut:Ko(p.toAmount,b),feeUsd:p.networkFee,estimatedTime:p.flow==="standard"?"5-30 min":"instant",preparable:!1,centralized:!0,kycRequired:!!p.kycRequired,kycRisk:!0,riskDisclosure:p.riskDisclosure||"ChangeNOW is centralized and may require KYC."})):_("changenow","centralized/KYC-risk routes require includeCentralized=true");let w=t.env??process.env,U=t.rangoApiKey||w.RANGO_API_KEY,R=Or(r,s,i),V=Or(n,a,d);U?!R||!V?I("rango","supported Rango chain/token identifiers are required",!0):O("rango",()=>ct({from:R,to:V,amount:String(o),enableCentralizedSwappers:!1},{...t,rangoApiKey:U}),p=>({amountOut:p.amountOut,feeUsd:p.feeUsd,estimatedTime:p.estimatedTime!=null?`${p.estimatedTime}s`:"unknown",preparable:!1})):I("rango","RANGO_API_KEY is not configured",!0);let D=(await Promise.all(S)).filter(Boolean);D.sort((p,M)=>{let H=BigInt(p.amountOut),z=BigInt(M.amountOut);return H!==z?H>z?-1:1:p.preparable!==M.preparable?p.preparable?-1:1:Ae.indexOf(p.provider)-Ae.indexOf(M.provider)});let C=Ae.map(p=>y.get(p)),T=C.filter(p=>["successful","failed"].includes(p.status)).map(p=>p.provider),N=C.filter(p=>p.status==="successful").map(p=>p.provider),F=C.filter(p=>p.status==="failed").map(p=>p.provider),X=C.filter(p=>p.status==="unavailable").map(p=>p.provider),ue=C.filter(p=>p.status==="skipped").map(p=>p.provider),Se=C.filter(p=>p.status==="failed").map(p=>`${p.provider}: ${p.reason}`),xe=D.length>0,ve=xe&&C.every(p=>p.status==="successful"||p.status==="skipped"||p.status==="unavailable"&&p.optional);return{ok:xe,providers:D.map(p=>p.provider),bestRoute:D[0]?.provider??"none",winner:D[0]??null,runnersUp:D.slice(1),errors:Se.length?Se:null,attemptedProviders:T,successfulProviders:N,failedProviders:F,unavailableProviders:X,skippedProviders:ue,comparisonComplete:ve,coverage:{roster:[...Ae],attemptedProviders:T,successfulProviders:N,failedProviders:F,unavailableProviders:X,skippedProviders:ue,complete:ve,details:C}}}var mu=Object.freeze({debridge:e=>dt(e),lifi:e=>tt(e),relay:e=>it(e),thorchain:e=>yr(e),across:e=>ot(e),hop:e=>at(e)}),hu=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 Y=/^0x[0-9a-fA-F]{40}$/,Rr=/^0x(?:[0-9a-fA-F]{2})+$/;function gt(e){return Array.isArray(e)?e.map(gt):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([t])=>t!=="signature"&&t!=="rawTransaction"&&t!=="signedTransaction").map(([t,r])=>[t,gt(r)]))}var Wo=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),Qo=100;function Yo(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 _r(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 Xo(e){if(Array.isArray(e)){let r=_r(e);if(!r.length)return null;let n=r.reduce((s,a)=>s+Number(a.amountUsd),0);return Number.isFinite(n)?n:null}let t=Number(e);return e!=null&&e!==""&&Number.isFinite(t)?t:null}function Jo(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 Ur(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(!Y.test(String(r.to??"")))return{ok:!1,reason:"deBridge paired transaction target is not a valid destination"};if(!Rr.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(!Y.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(s=>String(s??"").toLowerCase()!==String(t.taker).toLowerCase())?{ok:!1,reason:"deBridge destination recipient and order authorities are not bound to taker"}:{ok:!0,reason:null}}function Zo(e,t){return he[e?.provider]?e.provider==="debridge"?Ur(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 Ee(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 ea(e,t){let{fromChainId:r,toChainId:n,tokenIn:s,tokenOut:a,amountIn:o,taker:l}=e;if(r==null||n==null||!s||!a||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 i=Yo(e.slippageBps),d=await Br({fromChainId:r,toChainId:n,tokenIn:s,tokenOut:a,amount:String(o),taker:l,fromSymbol:e.fromSymbol,toSymbol:e.toSymbol,fromDecimals:e.fromDecimals??e.decimalsIn,toDecimals:e.toDecimals??e.decimalsOut,slippageBps:i,includeCentralized:e.includeCentralized===!0},t),c=[d.winner,...d.runnersUp||[]].filter(Boolean).map(g=>{let I=_r(g.feeUsd),_=Zo(g,e),O={source:g.provider,quality:"NO_GAS",amountOut:String(g.amountOut),grossOut:String(g.amountOut),netOut:String(g.amountOut),gasUsd:null,feeUsd:Xo(g.feeUsd),preparable:_.ok,prepareReason:_.reason,centralized:g.centralized===!0,kycRequired:g.kycRequired===!0,kycRisk:g.kycRisk===!0,riskDisclosure:g.riskDisclosure??null,meta:{durationSeconds:Jo(g.estimatedTime),estimatedTime:g.estimatedTime??null,destinationDecimals:Number.isInteger(e.toDecimals??e.decimalsOut)?Number(e.toDecimals??e.decimalsOut):null,routeSteps:[],feeCosts:I,gasCosts:[]}};return Object.defineProperty(O,"raw",{value:g.raw,enumerable:!1}),O}),f=c[0]??null,m=c.map((g,I)=>({provider:g.source,status:"quoted",rank:I+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===f?.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})),h=new Set(c.map(g=>g.source)),b=(d.coverage?.details||[]).filter(g=>!h.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})),y=null;if(c.length>=2&&BigInt(c[1].netOut)>0n){let g=(BigInt(c[0].netOut)-BigInt(c[1].netOut))*10000n/BigInt(c[1].netOut);g<=BigInt(Number.MAX_SAFE_INTEGER)&&(y=Number(g))}let S=[];return d.comparisonComplete!==!0&&S.push("bridge comparison coverage is incomplete; unavailable and failed providers remain explicit in routeOptions"),f&&f.preparable!==!0&&S.push(`${f.source} is the overall quote winner but is quote-only and cannot become a prepared wallet action`),{kind:"bridge",fromChainId:r,toChainId:n,tokenIn:s,tokenOut:a,amountIn:String(o),slippageBps:i,best:f,routes:c,failed:b.filter(g=>g.status==="unavailable"),routeOptions:[...m,...b],winner:Ee(f),runnersUp:c.slice(1).map(Ee),coverage:d.coverage,comparisonComplete:d.comparisonComplete===!0,complete:d.comparisonComplete===!0,sourcesTried:d.coverage?.roster?.length??0,sourcesAnswered:c.length,improvementBps:y,spreadBasis:c.length>=2?`${c[0].source} vs ${c[1].source}`:null,rankedOn:"exact-base-unit-output",durations:c.filter(g=>g.meta.durationSeconds!=null).map(g=>({source:g.source,seconds:g.meta.durationSeconds})),warnings:S,note:c.length?`${c.length} of ${d.coverage?.roster?.length??0} canonical bridge providers returned exact base-unit output`:"no canonical bridge provider returned a usable route"}}var he={debridge:async({fromChainId:e,taker:t},r,n)=>{let s=Ur({provider:"debridge",preparable:!0,raw:n?.raw},{fromChainId:e,taker:t});if(!s.ok)throw new Error(s.reason);let{debridgePrepare:a}=await Promise.resolve().then(()=>(pt(),pr)),l=(await a(n.raw,{taker:t})).transaction,i=l.value??"0";if(!/^(?:0x[0-9a-fA-F]+|\d+)$/.test(String(i)))throw new Error("deBridge paired transaction value is not a canonical unsigned amount");return{transactions:[{chainId:Number(e),from:String(l.from),to:String(l.to),data:String(l.data),value:String(i),...l.gasLimit!=null||l.gas!=null?{gasLimit:l.gasLimit??l.gas}:{}}],destination:String(l.to),requiresApproval:null,amountOut:n.amountOut,minOut:null,durationSeconds:n.meta?.durationSeconds??null}},relay:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:s,taker:a,slippageBps:o},l)=>{let{relayPrepare:i}=await Promise.resolve().then(()=>(ye(),Le)),d=await i({user:a,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(s),slippageBps:o},l);return{transactions:d.transactions||[],destination:d.destination??null,requiresApproval:d.requiresApproval??null,amountOut:d.quote?.details?.currencyOut?.amount??null,minOut:d.quote?.details?.currencyOut?.minimumAmount??null,durationSeconds:d.quote?.details?.timeEstimate??null}},lifi:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:s,taker:a,isHolder:o,slippageBps:l},i)=>{let{lifiPrepare:d}=await Promise.resolve().then(()=>(_e(),Qt)),u=await d({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:s,fromAddress:a,isHolder:o,feeAction:"bridge",slippageBps:l},i);return{transactions:u.transaction?[u.transaction]:[],destination:u.transaction?.to??null,requiresApproval:u.requiresApproval??null,amountOut:u.quote?.estimate?.toAmount??null,minOut:u.quote?.estimate?.toAmountMin??null,durationSeconds:u.quote?.estimate?.executionDuration??null}}};function Au(){return Object.keys(he)}async function Eu(e,t={}){let{taker:r,fromChainId:n,toChainId:s,tokenIn:a,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(!Y.test(r))throw new Error(`taker must be a valid 20-byte address, got "${r}"`);if(Wo.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&&(!Y.test(String(a))||!Y.test(String(o))))throw new Error("wallet-review bridge preparation requires exact origin and destination token addresses");let l=!Array.isArray(e.allowedSources),i=l?await ea(e,t):await ur(e,t);if(!i.best)return{ok:!1,reason:"no source returned a usable bridge route",comparison:i};let d=i.best.source,u=l?i.routes.find(w=>w.preparable===!0&&he[w.source]):i.best,c=e.source||u?.source;if(!c)return{ok:!1,reason:`${d} 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:d,comparison:i};let f=i.routes.find(w=>w.source===c);if(!f)return{ok:!1,reason:`source "${c}" returned no usable route`,comparison:i};let m=he[c];if(!m||l&&f.preparable!==!0){let w=i.routes.find(U=>he[U.source]&&(!l||U.preparable===!0)&&U.source!==c);return{ok:!1,reason:`${c} is quote-only for this response and cannot become a prepared wallet action. `+(w?`Next preparable route is ${w.source}; pass source:"${w.source}".`:"No route in this comparison has verified unsigned bytes and a strict preparer."),failureKind:"no-prepare-path",...w?{alternative:w.source}:{},winner:d,comparison:i}}i={...i,routeOptions:(i.routeOptions||[]).map(w=>({...w,selected:w.provider===c,quoteWinner:w.provider===d}))};let h;try{h=await m(e,t,f)}catch(w){let U=typeof w?.body=="string"?w.body:w?.body?JSON.stringify(w.body):"",R=[String(w?.message||w),U].filter(Boolean).join(" :: "),V=/allowance/i.test(R),q=!V&&/not enough|insufficient|balance/i.test(R),D=i.routes.find(C=>he[C.source]&&(!l||C.preparable===!0)&&C.source!==c);return{ok:!1,reason:V?`${c} will not build calldata until the token approval exists on-chain. Approve first, then prepare again. Underlying: ${R}`:q?`${c} refused to build: ${R}. Quoting works for any address; preparing needs the real funded wallet on chain ${n}.`:`${c} bridge prepare failed: ${R}`,failureKind:V?"approval-required-first":q?"taker-not-funded":"provider-error",...D?{alternative:D.source}:{},comparison:i}}let b=h.transactions||[];if(!b.length)return{ok:!1,reason:`${c} returned no executable transaction for this route`,failureKind:"provider-error",comparison:i};let y=b.filter(w=>w.chainId==null||Number(w.chainId)!==Number(n));if(y.length)return{ok:!1,reason:`${c} returned a transaction for chain ${y[0].chainId??"missing"} but the origin chain is ${n}. Refusing to hand over a mismatched artifact.`,failureKind:"chain-mismatch",comparison:i};if(b.find(w=>!Y.test(String(w.from??""))||String(w.from).toLowerCase()!==r.toLowerCase()))return{ok:!1,reason:`${c} returned a transaction whose sender is not the exact wallet under review`,failureKind:"sender-mismatch",comparison:i};if(b.find(w=>!Y.test(String(w.to??""))))return{ok:!1,reason:`${c} returned an invalid transaction target`,failureKind:"destination-not-bound",comparison:i};if(b.find(w=>!Rr.test(String(w.data??""))))return{ok:!1,reason:`${c} returned incomplete unsigned calldata bytes`,failureKind:"provider-error",comparison:i};let _=h.requiresApproval??null,O=String(h.destination??"");if(!Y.test(O)||!b.some(w=>String(w.to).toLowerCase()===O.toLowerCase()))return{ok:!1,reason:`${c} returned no safely bound bridge deposit destination`,failureKind:"destination-not-bound",comparison:i};if(_){if(String(_.amount)!==String(e.amountIn))return{ok:!1,reason:`${c} approval amount does not equal the exact input amount`,failureKind:"approval-not-exact",comparison:i};if(!Y.test(String(_.token))||!Y.test(String(_.spender)))return{ok:!1,reason:`${c} returned an incomplete approval bound`,failureKind:"approval-not-exact",comparison:i}}let L=e.driftToleranceBps??Qo,x=null,B=null;if(h.amountOut!=null&&f.grossOut!=null)try{let w=BigInt(f.grossOut),U=BigInt(h.amountOut);w>0n&&(x=Number((U-w)*10000n/w),x<-L&&(B=`route moved ${(x/100).toFixed(2)}% against you since the comparison (tolerance ${(L/100).toFixed(2)}%). Re-compare before signing.`))}catch{}let A=[...B?[B]:[],...i.warnings||[],`Bridging is NOT atomic: the origin transaction succeeding does not mean funds arrived on chain ${s}. Expect ~${h.durationSeconds!=null?`${h.durationSeconds}s`:"minutes"} before the destination credits, and do not re-send if it is pending.`];b.length>1&&A.push(`This route needs ${b.length} transactions signed IN ORDER. Signing only the first leaves funds approved but not bridged.`);let k=e.walletReviewOnly===!0?gt(b):b,E=j({ok:!0,chosen:{source:c,wasWinner:c===d,netOut:f.netOut,grossOut:f.grossOut,gasUsd:f.gasUsd,feeUsd:f.feeUsd,feeCosts:Array.isArray(f.meta?.feeCosts)?f.meta.feeCosts:[],gasCosts:Array.isArray(f.meta?.gasCosts)?f.meta.gasCosts:[]},artifactKind:"unsigned-transaction-sequence",sender:r.toLowerCase(),fromChainId:Number(n),toChainId:Number(s),tokenIn:String(a),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:k,requiresApproval:_,amountOut:h.amountOut??null,minOut:h.minOut??null,durationSeconds:h.durationSeconds??null,slippageBps:i.slippageBps,routeOptions:i.routeOptions??[],winner:Ee(i.best),quoteWinner:Ee(i.best),coverage:i.coverage??null,comparisonComplete:i.comparisonComplete??null,complete:i.complete??null,destination:O,unsigned:!0,signedBy:"user-wallet",driftBps:x,warnings:A,runnersUp:i.routes.slice(1).map(Ee),comparison:{rankedOn:i.rankedOn,sourcesAnswered:i.sourcesAnswered,sourcesTried:i.sourcesTried,improvementBps:i.improvementBps,winner:d,selectedForPreparation:c,complete:i.comparisonComplete??null},note:`UNSIGNED. ${b.length} transaction(s) on chain ${n}, crediting chain ${s}. Verify every destination address before signing.`},{provider:"router",kind:"best-bridge",env:t.env,nowMs:t.nowMs,expiresAtMs:t.expiresAtMs});if(e.walletReviewOnly===!0&&E.prepareMac){let{prepareMac:w,...U}=E;return U}return E}export{Eu as prepareBestBridgeRoute,Au as supportedBridgePreparers};
1
+ var Fr=Object.defineProperty;var j=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Me=(e,t)=>{for(var r in t)Fr(e,r,{get:t[r],enumerable:!0})};import{AsyncLocalStorage as qr}from"node:async_hooks";function Oe(e){let t=Mr.getStore();if(!t||t.closed||!Hr.includes(e))return null;if(t.spans.length>=jr)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,s=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(s)&&s>=100&&s<=599?s:null)}}var Mr,Hr,jr,Ct=j(()=>{Mr=new qr,Hr=["http","retry","shared"],jr=512});import ue from"node:net";import Vr from"node:dns";function Te(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=u=>{if(!u)return[];let c=u.split(":"),f=c.at(-1);if(f?.includes(".")){let m=f.split(".").map(Number);if(m.length!==4||m.some(h=>!Number.isInteger(h)||h<0||h>255))return null;c.splice(c.length-1,1,(m[0]<<8|m[1]).toString(16),(m[2]<<8|m[3]).toString(16))}return c.some(m=>!/^[0-9a-f]{1,4}$/.test(m))?null:c.map(m=>Number.parseInt(m,16))},[n,s]=t.split("::"),a=r(n),o=r(s);if(!a||!o)return null;let l=t.includes("::"),i=8-a.length-o.length;if(!l&&i!==0||l&&i<1)return null;let d=[...a,...Array(Math.max(0,i)).fill(0),...o];return d.length!==8?null:Uint8Array.from(d.flatMap(u=>[u>>8,u&255]))}function Ve(e,t,r){let n=Math.floor(r/8),s=r%8;for(let o=0;o<n;o+=1)if(e[o]!==t[o])return!1;if(!s)return!0;let a=255<<8-s;return(e[n]&a)===(t[n]&a)}function ze(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=Te(e);if(!t)return!1;let r=Te("::ffff:0:0");return Ve(t,r,96)?ze([...t.slice(12)].join(".")):Ve(t,Te("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([s,a])=>Ve(t,Te(s),a)):!1}return!1}function Kr(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(zr.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=ue.isIP(r);return n!==0&&!ze(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function Ke(e,{lookupFn:t=Vr.promises.lookup}={}){let r=Kr(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;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(s=>!ze(s.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function Ge({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n;try{let c=await t();r=c.Agent,n=c.fetch}catch(c){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${c?.message||c}`);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=c=>String(c).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),a=new Map,o=c=>(Array.isArray(c)?c:[c]).map(f=>typeof f=="string"?{address:f}:f).filter(f=>f&&f.address).map(f=>({address:f.address,family:f.family||(ue.isIPv6(f.address)?6:4)})),l=(c,f,m)=>{a.set(s(c),o(typeof f=="string"?[{address:f,family:m}]:f))},i=c=>{let f=s(c);if(ue.isIP(f))return[{address:f,family:ue.isIPv6(f)?6:4}];let m=a.get(f);if(!m||!m.length)throw new Error(`refused: unpinned host ${c} during pinned fetch`);return m},d=new r({connect:{lookup(c,f,m){let h;try{h=i(c)}catch(b){return m(b)}return f?.all?m(null,h):m(null,h[0].address,h[0].family)}}}),u=Gr((c,f={})=>n(c,{...f,dispatcher:d}),l);return{dispatcher:d,fetch:u,pin:l,resolve:i,async close(){try{await d.destroy()}catch{}}}}function Gr(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[We]=Object.freeze({pin:t}),e}function Qe(e){return typeof e=="function"&&typeof e[We]?.pin=="function"}function It(e,t,r){if(!Qe(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[We].pin(t,r)}var zr,We,kt=j(()=>{zr=new Set(["localhost","metadata.google.internal","metadata.goog"]);We=Symbol.for("oracle.egressGuard.pinCapableFetch")});import{createHash as Wr}from"node:crypto";import{types as te}from"node:util";function P(e){return oe(`HTTP JSON body refused: ${e}`)}function nn(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 on(e){let t=[],r=0,n=0,s=0,a=0,o=new WeakSet,l=u=>{if(r+=Buffer.byteLength(u,"utf8"),r>ee.bytes)throw P("serialized byte limit exceeded");t.push(u)},i=u=>{if(Buffer.byteLength(u,"utf8")>ee.bytes)throw P("serialized byte limit exceeded");return JSON.stringify(u)},d=(u,c)=>{if(n+=1,n>ee.nodes)throw P("node limit exceeded");if(c>ee.depth)throw P("depth limit exceeded");if(u===null){l("null");return}if(typeof u=="string"){l(i(u));return}if(typeof u=="boolean"){l(u?"true":"false");return}if(typeof u=="number"){if(!Number.isFinite(u))throw P("non-finite number");l(Object.is(u,-0)?"0":String(u));return}if(typeof u!="object")throw P("unsupported non-JSON value");if(te.isProxy(u))throw P("proxy value");if(nn(u))throw P("unsupported exotic object");if(o.has(u))throw P("cyclic value");o.add(u);try{if(Object.getOwnPropertySymbols(u).length>0)throw P("symbol-keyed fields are unsupported");if(Array.isArray(u)){let h=Object.getPrototypeOf(u),b=0;for(;h!==null;){if(te.isProxy(h))throw P("proxy array prototype");if(b+=1,b>ee.depth)throw P("array prototype depth limit exceeded");h=Object.getPrototypeOf(h)}if(u.length>ee.arrayLength)throw P("array length limit exceeded");for(let E=0;E<u.length;E+=1){let g=Object.getOwnPropertyDescriptor(u,String(E));if(!g||!Object.hasOwn(g,"value")||g.enumerable!==!0)throw P("array entries must be dense enumerable own data")}let y=0;for(let E in u){if(a+=1,a>ee.fields)throw P("enumeration limit exceeded");if(Object.hasOwn(u,E)&&(y+=1,y>u.length))throw P("named array fields are unsupported")}if(y!==u.length)throw P("array entries must be dense enumerable own data");l("[");for(let E=0;E<u.length;E+=1)E&&l(","),d(Object.getOwnPropertyDescriptor(u,String(E)).value,c+1);l("]");return}let f=Object.getPrototypeOf(u);if(f!==Object.prototype&&f!==null)throw P("non-plain object");let m=[];for(let h in u){if(a+=1,a>ee.fields)throw P("enumeration limit exceeded");if(!Object.hasOwn(u,h))continue;if(s+=1,s>ee.fields)throw P("field limit exceeded");let b=Object.getOwnPropertyDescriptor(u,h);if(!b||!Object.hasOwn(b,"value")||b.enumerable!==!0)throw P("object fields must be enumerable own data");m.push([h,b.value])}l("{");for(let h=0;h<m.length;h+=1)h&&l(","),l(i(m[h][0])),l(":"),d(m[h][1],c+1);l("}")}finally{o.delete(u)}};return d(e,0),t.join("")}function an(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 s=n.toLowerCase();if(r.has(s))throw new TypeError("HTTP headers contain a duplicate canonical name");r.add(s);let a=Object.getOwnPropertyDescriptor(e,n);if(!a||!Object.hasOwn(a,"value"))throw new TypeError("HTTP headers must contain own data properties");let o=a.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 sn(){return Object.assign(Object.create(null),{Accept:"application/json"})}function cn(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 un(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function Ne(e){if((typeof e!="object"||e===null)&&typeof e!="function")return`${typeof e}:${String(e)}`;let t=Rt.get(e);return t||(t=_t,_t+=1,Rt.set(e,t)),`reference:${t}`}function Ut(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?ln.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 Pt(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(Ut);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return Ut(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&dn.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function pn(e,t,r,n={},s=null){let a=Wr("sha256"),o=(i,d)=>{let u=String(d);a.update(String(Buffer.byteLength(i,"utf8"))).update(":").update(i),a.update("=").update(String(Buffer.byteLength(u,"utf8"))).update(":").update(u).update(`
2
+ `)};o("method",e),o("url",t),Object.keys(r||{}).map((i,d)=>({name:i.toLowerCase(),order:d,value:String(r[i])})).sort((i,d)=>i.name.localeCompare(d.name)||i.order-d.order).forEach((i,d)=>{o(`header-name-${d}`,i.name),o(`header-value-${d}`,i.value)}),o("body",s??"-");for(let i of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])o(`context-${i}`,n[i]??"-");return a.digest("hex")}function fn(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Tt):Math.min(250*2**e,Tt)+Math.floor(Math.random()*100)}function oe(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function Ye(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 hn(e){return e?e.byteLength??e.length??0:0}async function gn(e,t,{url:r,truncate:n=!1,onOversize:s}={}){if(t==null)return await e.text();let a=Number(e.headers?.get?.("content-length"));if(Number.isFinite(a)&&a>t&&(le(e),!n))throw Ye(r,`content-length ${a}`,t);let o=e.body?.getReader?.();if(!o){let c=await e.text(),f=Buffer.byteLength(c,"utf8");if(f>t){if(!n)throw Ye(r,`body ${f} bytes`,t);return Buffer.from(c,"utf8").subarray(0,t).toString("utf8")}return c}let l=[],i=0,d=!1;try{for(;;){let{value:c,done:f}=await o.read();if(f)break;if(c&&(l.push(Buffer.from(c)),i+=hn(c),i>t)){d=!0;break}}}finally{if(d)try{await o.cancel()}catch{}try{o.releaseLock?.()}catch{}}if(d&&(typeof s=="function"&&s(),!n))throw Ye(r,`streamed ${i} bytes`,t);let u=Buffer.concat(l);return(d?u.subarray(0,t):u).toString("utf8")}function bn(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function wn(e,{fetchImpl:t,method:r,headers:n,body:s,timeoutMs:a,lookupFn:o,realFetch:l,untrustedUrl:i=!1,maxResponseBytes:d=null,sameOriginRedirectsOnly:u=!1,importUndici:c,validateResponse:f,signal:m,redirectPolicy:h="follow",maxRedirects:b=Be}){let y=null,E=t,g=o?{lookupFn:o}:{};if(i&&!l&&!Qe(E))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 I=new AbortController,_=setTimeout(()=>I.abort(),a),O=m?Bt?Bt([m,I.signal]):m:I.signal,L=async(x,{status:B=null}={})=>{let S=await Ke(x,g);if(!S.ok)throw oe(B==null?`HTTP refused ${x}: ${S.error}`:`HTTP redirect to ${x} ${S.error}`,B==null?{}:{status:B});let k=new URL(x).hostname;if(l){if(y&&(await y.close(),y=null),!y)try{y=await Ge({requireUndici:!0,...c?{importUndici:c}:{}})}catch(A){throw oe(B==null?`HTTP refused ${x}: ${A?.message||A}`:`HTTP redirect to ${x} refused: ${A?.message||A}`,B==null?{}:{status:B})}y.pin(k,S.addresses),E=y.fetch}else It(E,k,S.addresses);return S};try{let x=String(e),B=Object.assign(Object.create(null),n||{});i&&await L(x);for(let S=0;S<=b;S+=1){let k=Object.assign(Object.create(null),{method:r,headers:B,body:s,signal:O,redirect:"manual",dispatcher:void 0}),A=await E(x,k);if((h==="error"||b===0)&&A.status>=300&&A.status<400)throw le(A),oe(`HTTP ${A.status} ${r} redirect refused`,{status:A.status,redirectRefused:!0});if(rn.has(A.status)){let R=u===!0&&r==="POST"&&[307,308].includes(A.status)&&Pt(r,s);if(r!=="GET"&&r!=="HEAD"&&!R){le(A);let C=new Error(`HTTP ${A.status} ${r} ${x} redirected non-idempotent request`);throw C.status=A.status,C}if(S===b)throw le(A),oe(`HTTP ${A.status} ${r} redirect budget exhausted`,{status:A.status,redirectRefused:!0});let V=A.headers?.get?.("location"),F;try{F=cn(V,x)}catch(C){throw le(A),C}let D=!un(F,x);if(le(A),D&&r==="POST"){let C=new Error(`HTTP ${A.status} ${r} cross-origin redirect refused`);throw C.status=A.status,C}if(D&&u){let C=new Error(`HTTP ${A.status} ${r} cross-origin redirect refused`);throw C.status=A.status,C.retryable=!1,C}if(D&&(B=sn(B)),i)await L(F,{status:A.status});else if(D){let C=await Ke(F,g);if(!C.ok){let N=new Error(`HTTP redirect from ${x} ${C.error}`);throw N.status=A.status,N.retryable=!1,N}l&&C.addresses?.length&&(y||(y=await Ge(c?{importUndici:c}:{})),y&&(y.pin(new URL(F).hostname,C.addresses),E=y.fetch))}x=F;continue}if(typeof f=="function")try{await f(A,{url:x})}catch(R){throw le(A),oe(R?.message||String(R))}let w=await gn(A,d,{url:x,onOversize:()=>I.abort()}),U=bn(w);if(!A.ok){let R=new Error(`HTTP ${A.status} ${r} ${x}`);throw R.status=A.status,R.retryAfter=A.headers?.get?.("retry-after")??null,R.body=U??w.slice(0,300),R}return U??w}throw new Error(`HTTP redirect loop for ${e}`)}catch(x){if(I.signal.aborted&&!ye(m)){let B=x&&(typeof x=="object"||typeof x=="function")&&!te.isProxy(x)?x:null,S=B?Object.getOwnPropertyDescriptor(B,"oversize"):null;if(!(S&&Object.hasOwn(S,"value")&&S.value===!0))try{if(!B)throw new TypeError("unsafe rejection");Object.defineProperties(B,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let A=new Error("HTTP request timed out");throw Object.defineProperties(A,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),A}}throw x}finally{clearTimeout(_),y&&await y.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 N of Object.getOwnPropertyNames(t)){let T=Object.getOwnPropertyDescriptor(t,N);if(!(N==="toJSON"&&T&&Object.hasOwn(T,"value")&&T.value===void 0)){if(!r.has(N))throw new TypeError("HTTP options contain unknown fields");if(!T||!T.enumerable||!Object.hasOwn(T,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=N=>{if(t==null||!Object.hasOwn(t,N))return;let T=Object.getOwnPropertyDescriptor(t,N);if(!T||!Object.hasOwn(T,"value"))throw new TypeError("HTTP options must contain own data properties");return T.value};if(typeof e!="string"||e.length===0||e.length>8192)throw new TypeError("HTTP URL must be a bounded string");let s=n("method");if(s!==void 0&&(typeof s!="string"||!/^[A-Za-z]+$/u.test(s)))throw new TypeError("HTTP method must be a string token");let a=n("timeoutMs");if(a!==void 0&&(!Number.isInteger(a)||a<1||a>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 l=n("redirectPolicy");if(l!==void 0&&l!=="follow"&&l!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let i=n("maxRedirects");if(i!==void 0&&(!Number.isInteger(i)||i<0||i>Be))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${Be}`);if(l==="error"&&i!==void 0&&i!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let d=l??"follow",u=d==="error"?0:i??Be;for(let N of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let T=n(N);if(T!==void 0&&typeof T!="boolean")throw new TypeError(`HTTP ${N} must be boolean`)}let c=n("maxResponseBytes");if(c!==void 0&&(!Number.isInteger(c)||c<1||c>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let f=n("signal");if(f!==void 0){if(te.isProxy(f)||!(f instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{ye(f)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let N of["importUndici","lookupFn","validateResponse"]){let T=n(N);if(T!==void 0&&typeof T!="function")throw new TypeError(`HTTP ${N} must be a function`)}let m=n("fetchImpl"),h=m||globalThis.fetch;if(typeof h!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let b=a??12e3,y=(s||"GET").toUpperCase(),E=n("headers"),g=an(E),I=Object.assign(Object.create(null),g);Object.keys(I).some(N=>N.toLowerCase()==="accept")||(I.Accept="application/json");let _=n("body");_!=null&&typeof _!="string"&&(Object.keys(I).find(T=>T.toLowerCase()==="content-type")||(I["Content-Type"]="application/json"),_=on(_));let O=o??Xr,L=n("lookupFn"),x=!m,B=n("untrustedUrl")===!0,S=n("sameOriginRedirectsOnly")===!0,k=n("importUndici"),A=n("validateResponse"),w=f,U=c??null,R=async()=>{let N;for(let T=0;T<=O;T++){w&&Zr.call(w);let H=Oe("http");try{let z=await wn(e,{fetchImpl:h,method:y,headers:I,body:_,timeoutMs:b,lookupFn:L,realFetch:x,untrustedUrl:B,maxResponseBytes:U,sameOriginRedirectsOnly:S,importUndici:k,validateResponse:A,signal:w,redirectPolicy:d,maxRedirects:u});return H?.("succeeded"),z}catch(z){N=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");H?.("failed",ce);let Ce=J("oracleTimeout")===!0||J("name")==="AbortError"||J("name")==="TimeoutError"||ye(w),Ie=new Set([408,425,429]),p=J("retryable")===!1?!1:ce!=null?Ie.has(ce)||Qr.has(ce)&&Ot.has(y):!Ce&&Ot.has(y);if(T===O||!p)throw z;let q=fn(T,J("retryAfter")),W=Oe("retry"),K=!1;try{w?await new Promise((de,ne)=>{let ke,we=()=>{clearTimeout(ke),Nt.call(w,"abort",we),ne(tn(w)||new DOMException("Aborted","AbortError"))};if(ye(w)){we();return}ke=setTimeout(()=>{Nt.call(w,"abort",we),de()},q),en.call(w,"abort",we,{once:!0}),ye(w)&&we()}):await mn(q),K=!0}finally{W?.(K?"succeeded":"failed")}}}throw N};if(!(n("dedupe")!==!1&&!w&&Pt(y,_)))return R();let F=pn(y,e,I,{untrustedUrl:B,maxResponseBytes:U,sameOriginRedirectsOnly:S,redirectPolicy:d,maxRedirects:u,timeoutMs:b,retries:O,fetchImpl:Ne(h),realFetch:x,lookupFn:Ne(L),importUndici:Ne(k),validateResponse:Ne(A)},_),D=Xe.get(F);if(D){let N=Oe("shared");try{let T=await D;return N?.("succeeded"),T}catch(T){throw N?.("failed"),T}}let C=R().finally(()=>Xe.delete(F));return Xe.set(F,C),C}var Qr,Ot,Xr,Tt,Yr,Jr,Zr,en,Nt,Bt,ye,tn,rn,Be,xa,ee,Xe,Rt,_t,ln,dn,mn,$=j(()=>{Ct();kt();Qr=new Set([408,425,429,500,502,503,504]),Ot=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Xr=2,Tt=4e3,Yr=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Jr=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Zr=AbortSignal.prototype.throwIfAborted,en=EventTarget.prototype.addEventListener,Nt=EventTarget.prototype.removeEventListener,Bt=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,ye=e=>e?Yr.call(e):!1,tn=e=>e?Jr.call(e):void 0,rn=new Set([301,302,303,307,308]),Be=3,xa=64*1024,ee=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});Xe=new Map,Rt=new WeakMap,_t=1;ln=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),dn=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);mn=e=>new Promise(t=>setTimeout(t,e))});import{readFileSync as yn}from"node:fs";import{homedir as Sn}from"node:os";import{join as Re}from"node:path";function An(){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=Sn();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||Re(t,".config","oracle")).trim();return[e,Re(r,"exec.env")].filter(Boolean)}return[e,Re(t,".config","oracle","exec.env"),Re(t,".config","mad-desk","exec.env")].filter(Boolean)}function Lt(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let s of An())try{let a=yn(s,"utf8"),o=a.match(new RegExp(`^${t}=(.*)$`,"m"))||a.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 $t=j(()=>{});var Dt=j(()=>{});import{createHash as En,createHmac as qt,timingSafeEqual as xn}from"node:crypto";function Ue(e){return Array.isArray(e)?`[${e.map(Ue).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Ue(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Mt(e,{required:t=!1}={}){try{return Lt(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function Ze(e){let{signature:t,...r}=e;return r}function Ht(e,{secret:t}={}){let r=Mt(t);return r?{...e,signature:qt("sha256",r).update(Ue(Ze(e))).digest("hex")}:e}function vn(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 En("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function ae(e,{chainId:t,venue:r,data:n,secret:s}={}){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 a=Mt(s);if(a){let m=qt("sha256",a).update(Ue(Ze(e))).digest("hex");if(!Cn(e.signature,m))throw new Error("auto-slippage guard signature mismatch \u2014 refusing to bind a guard this Oracle did not issue")}let o=Number(e.selectedBps),l=Number(e.capBps);if(!Number.isInteger(o)||o<0||o>_e||!Number.isInteger(l)||l<0||l>_e||o>l)throw new Error("auto-slippage guard bounds are invalid");let i=BigInt(e.quoteAmountOut??0),d=BigInt(e.minAmountOut??0);if(i<=0n||d<=0n)throw new Error("auto-slippage guard amounts must be positive");let u=i*BigInt(1e4-o),c=u/10000n;if(u%10000n!==0n&&(c+=1n),d<c)throw new Error("auto-slippage guard is under-protected relative to its quote");let f=On(n);if(f!=null&&f!==d)throw new Error(`auto-slippage: calldata encodes floor ${f}, not the guard floor ${d} \u2014 refusing to bind`);return Ht({...Ze(e),calldataHash:vn(n)},{secret:s})}function Cn(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:xn(r,n)}function Je(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function In(e){let t=e==null?_e: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,_e)}function se({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:s}={}){let a=Je(e,0),o=a>0?a>=25e4?5:a>=1e5?10:a>=5e4?20:a>=1e4?40:70:n?30:10,l=Math.min(60,Math.abs(Je(t,0))*2),i=Math.min(40,Math.floor(Math.max(0,Je(r,0))/5e3)*5),d=Math.max(25,Math.ceil(20+o+l+i)),u=In(s);return{mode:"auto",requiredBps:d,selectedBps:Math.min(d,u),capBps:u,executable:d<=u}}function kn({chainId:e,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:s=0,quoteAgeMs:a=0,crossChain:o=!1,requestedCapBps:l,quotedAtMs:i=Date.now(),ttlMs:d=Ft,secret:u}={}){let c=BigInt(r??0);if(c<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let f=se({liquidityUsd:n,priceChange5m:s,quoteAgeMs:a,crossChain:o,requestedCapBps:l});if(!f.executable)throw new Error(`auto-slippage requires ${f.requiredBps} bps above hard/requested cap ${f.capBps}; route blocked`);let m=Number(i);if(!Number.isFinite(m))throw new Error("auto-slippage: quotedAtMs must be a finite number");let h=Math.min(3e4,Math.max(1e3,Number(d)||Ft)),b=c*BigInt(1e4-f.selectedBps),y=b/10000n;if(b%10000n!==0n&&(y+=1n),y>c&&(y=c),c>0n&&y<=0n)throw new Error(`auto-slippage: quote ${c} is too small to express a ${f.selectedBps} bps floor without rounding to zero`);let E=Number((c-y)*10000n/(c===0n?1n:c));if(E>f.capBps)throw new Error(`auto-slippage: realised floor implies ${E} bps, above cap ${f.capBps} \u2014 refusing to issue a guard weaker than advertised`);return Ht({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:c.toString(),minAmountOut:y.toString(),requiredBps:f.requiredBps,selectedBps:f.selectedBps,capBps:f.capBps,quotedAtMs:m,expiresAtMs:m+h},{secret:u})}function On(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 a=10;a+64<=t.length;a+=64)n.push(t.slice(a,a+64));let s=a=>n[a]==null?null:BigInt("0x"+n[a]);switch(r){case"0x414bf389":return s(6);case"0x04e45aaf":return s(5);case"0xc04b8d59":{let a=s(0);if(a==null)return null;let o=Number(a)/32;return!Number.isInteger(o)||o<0?null:s(o+4)}case"0xb858183f":{let a=s(0);if(a==null)return null;let o=Number(a)/32;return!Number.isInteger(o)||o<0?null:s(o+3)}case"0xa026383e":return s(6);case"0x38ed1739":case"0x5c11d795":return s(1);case"0x7ff36ab5":case"0xb6f9de95":return s(0);case"0x18cbafe5":case"0x791ac947":return s(1);default:return null}}function Q(e,{chainId:t,venue:r,amountOut:n,liquidityUsd:s,priceChange5m:a,crossChain:o,requestedCapBps:l,quotedAtMs:i=Date.now(),ttlMs:d}={}){let u=kn({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:s,priceChange5m:a,crossChain:o,requestedCapBps:l,quotedAtMs:i,ttlMs:d});return{...e,autoSlippage:u,amountOutMinimum:u.minAmountOut}}var _e,Ft,re=j(()=>{$t();Dt();_e=100,Ft=2e4});var pe,Pe=j(()=>{pe="0x000000000000000000000000000000000000dEaD"});import{createHash as Tn,createHmac as Nn,timingSafeEqual as $a}from"node:crypto";function et(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(et).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${et(e[r])}`).join(",")}}`}function jt(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Vt(e=process.env){return jt(process.env)||jt(e)}function Un(e){let{prepareHash:t,prepareMac:r,note:n,...s}=e||{};return s}function Pn(e){let t=Un(e);return Tn("sha256").update(et(t)).digest("hex")}function Ln(e,t=Vt()){return t?Nn("sha256",t).update(String(e)).digest("hex"):""}function M(e,{provider:t,kind:r,env:n=process.env,nowMs:s=Date.now(),expiresAtMs:a}={}){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 l={...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(!l.provider)throw new Error("stampPrepared: provider required");if(!l.kind)throw new Error("stampPrepared: kind required");let i=Number(s),d=a==null?i+Rn:Number(a),u=d-i;if(!Number.isSafeInteger(i)||!Number.isSafeInteger(d)||u<=0||u>_n)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let f={...l,preparedAt:i,expiresAt:d,prepareVersion:Bn},m=Pn(f),h=Vt(n),b=h?Ln(m,h):void 0,y={...f,prepareHash:m};return b&&(y.prepareMac=b),y}var Bn,Rn,_n,X=j(()=>{Bn=2,Rn=300*1e3,_n=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Contract as $n,JsonRpcProvider as Dn}from"ethers";function Vn(e){return jn.test(String(e||""))}async function zt(e,{contract:t=Fn,rpc:r=Mn,chainId:n=qn,balanceOf:s}={}){if(!Vn(e))throw new Error("invalid-address");if(s)return BigInt(await s(e));let a=new Dn(r,n,{staticNetwork:!0}),o=new $n(t,Hn,a);return BigInt(await o.balanceOf(e))}var Fn,qn,Mn,Hn,jn,Kt=j(()=>{Fn="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",qn=999,Mn="https://rpc.hyperliquid.xyz/evm",Hn=["function balanceOf(address owner) view returns (uint256)"],jn=/^0x[a-fA-F0-9]{40}$/});import{existsSync as zn,readFileSync as Kn,lstatSync as Gn}from"node:fs";import{homedir as Gt}from"node:os";import{join as tt}from"node:path";function Xn(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(Wt,t)?Wt[t]:Qn}function to(e=process.env){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){if(e[Qt])return String(e[Qt]);let t=e.ORACLE_CONFIG_DIR||tt(Gt(),".config","oracle");return tt(t,"fee-recipient")}return tt(Gt(),".config","oracle","fee-recipient")}function ro(e=process.env){try{let t=to(e);if(!zn(t)||Gn(t).isSymbolicLink())return"";let r=Kn(t,"utf8").trim().toLowerCase();return/^0x[a-f0-9]{40}$/.test(r)?r:""}catch{return""}}function no(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),Wn)}function oo({env:e=process.env,action:t="swap",admin:r=!1}={}){let n=String(e[Jn]||"").trim(),s=String(e[Zn]||eo).trim();if(r===!0)return{bps:0,recipient:"",integrator:s,action:t,applies:!1,reason:"admin-oracle"};let a=Xn(t),o=no(e[Yn],{fallback:n?a:0}),l=Math.min(o,a);if(!l)return{bps:0,recipient:"",integrator:s,action:t,applies:!1,reason:"not-configured"};if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{bps:0,recipient:"",integrator:s,action:t,applies:!1,reason:"no-recipient"};let i=ro(e);return!i||i!==n.toLowerCase()?{bps:0,recipient:"",integrator:s,action:t,applies:!1,reason:"recipient-not-pinned"}:{bps:l,recipient:n,integrator:s,action:t,applies:!0,reason:"configured"}}async function rt({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={},admin:s=!1}={}){let a=oo({env:t,action:r,admin:s});if(s===!0)return{...a,holderVerificationStatus:"admin-oracle"};let o=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(o))return{...a,holderVerificationStatus:"wallet-required"};try{return BigInt(await zt(o,n))>0n?{...a,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...a,holderVerificationStatus:"non-holder"}}catch{return{...a,holderVerificationStatus:"unavailable"}}}function Xt(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 Yt(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}var Wn,Qn,Wt,Yn,Jn,Zn,Qt,eo,Le=j(()=>{Kt();Wn=100,Qn=5,Wt=Object.freeze({swap:5,bridge:5,perps:0,nft:0});Yn="ORACLE_INTEGRATOR_FEE_BPS",Jn="ORACLE_INTEGRATOR_FEE_RECIPIENT",Zn="ORACLE_INTEGRATOR_ID",Qt="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",eo="oracle"});var Zt={};Me(Zt,{LIFI_API:()=>Jt,lifiChains:()=>co,lifiHealth:()=>at,lifiPrepare:()=>io,lifiQuote:()=>me});function ot(e={}){return(e.baseUrl||process.env.LIFI_API_URL||Jt).replace(/\/$/,"")}function so(e){let t=String(e||nt).toLowerCase();return t===nt.toLowerCase()||t===ao}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 at(e={}){let t=await v(`${ot(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:s=nt,toToken:a,fromAmount:o,fromAddress:l=pe}=e;if(r==null||!a||!o)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let i=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:s,toToken:a,fromAmount:String(o),fromAddress:l}),d=se({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!d.executable)throw new Error(`lifi: route requires ${d.requiredBps} bps above cap ${d.capBps}`);i.set("slippage",String(d.selectedBps/1e4));let u=await rt({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[y,E]of Object.entries(Yt(u)))i.set(y,E);let c=await v(`${ot(t)}/quote?${i}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),f=c?.estimate?.toAmount||c?.toAmount;if(!f)return{...c,autoSlippagePolicy:d,oracleFee:u};let m=c?.transactionRequest?.to||c?.estimate?.approvalAddress||"lifi",h=Q(c,{chainId:Number(r),venue:m,amountOut:f,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),b=c?.estimate?.toAmountMin||c?.toAmountMin;if(b!=null&&BigInt(b)<BigInt(h.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...h,oracleFee:u}}async function io(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(c=>n[c]!=null))throw new Error("lifi: unsupported transaction authority");if(n.type!=null){let c=String(n.type).trim().toLowerCase();if(!/^(?:0x[0-9a-f]+|\d+)$/.test(c)||BigInt(c)>2n)throw new Error("lifi: unsupported transaction authority")}let a=Number(e.fromChain);if(n.chainId==null)throw new Error("lifi: transaction missing chain authority");if(Number(n.chainId)!==a)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 l=fe(n.to,"transaction target"),i=String(n.data);if(!/^0x(?:[0-9a-fA-F]{2})+$/.test(i))throw new Error("lifi: transaction calldata must be non-empty hex bytes");let d=String(n.value??"0x0");if(!/^(?:0x[0-9a-fA-F]+|\d+)$/.test(d))throw new Error("lifi: transaction value must be an unsigned integer string");let u=null;if(!so(e.fromToken)){let c=r?.estimate?.approvalAddress||r?.approvalAddress;if(!c)throw new Error("lifi: ERC20 route missing approvalAddress");let f=r?.action?.fromToken?.address||r?.estimate?.fromToken?.address||e.fromToken;u={token:fe(f,"approval token"),spender:fe(c,"approval spender"),amount:String(e.fromAmount)}}return M({provider:"lifi",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:a,quote:r,autoSlippage:r.autoSlippage,requiresApproval:u,transaction:{chainId:a,from:o,to:l,data:i,value:d,...n.gasLimit!=null?{gasLimit:n.gasLimit}:{},slippageGuard:ae(r.autoSlippage,{chainId:a,venue:l,data:i})}},{provider:"lifi",kind:"lifi-tx",env:t.env,nowMs:t.nowMs,expiresAtMs:t.expiresAtMs})}async function co(e={}){return v(`${ot(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var Jt,nt,ao,$e=j(()=>{$();re();Pe();X();Le();Jt="https://li.quest/v1";nt="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",ao="0x0000000000000000000000000000000000000000"});var qe={};Me(qe,{ACROSS_API:()=>nr,HOP_API:()=>or,RANGO_API:()=>sr,RELAY_API:()=>ar,acrossHealth:()=>ct,acrossSuggestedFees:()=>De,hopHealth:()=>ut,hopQuote:()=>Fe,rangoQuote:()=>pt,relayHealth:()=>dt,relayPrepare:()=>vo,relayQuote:()=>Ae});async function ct(e={}){try{return{ok:!0,estimatedFillTimeSec:(await De({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 De(e={},t={}){let{token:r,destinationToken:n=r,originChainId:s,destinationChainId:a,amount:o}=e;if(!r||s==null||a==null||!o)throw new Error("acrossSuggestedFees requires token, originChainId, destinationChainId, amount");let l=new URLSearchParams({token:r,destinationToken:n,originChainId:String(s),destinationChainId:String(a),amount:String(o)}),i=(t.baseUrl||process.env.ACROSS_API_URL||nr).replace(/\/$/,"");return v(`${i}/suggested-fees?${l}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function ut(e={}){try{let t=await Fe({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 Fe(e={},t={}){let{amount:r,token:n="ETH",fromChain:s="ethereum",toChain:a="arbitrum"}=e;if(!r)throw new Error("hopQuote requires amount");let o=e.slippage==null?void 0:Math.round(Number(e.slippage)*100),l=se({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:s!==a,requestedCapBps:e.maxSlippageBps??e.slippageBps??o});if(!l.executable)throw new Error(`hop: route requires ${l.requiredBps} bps above cap ${l.capBps}`);let i=new URLSearchParams({amount:String(r),token:n,fromChain:s,toChain:a,slippage:String(l.selectedBps/100)}),d=(t.baseUrl||process.env.HOP_API_URL||or).replace(/\/$/,""),u=await v(`${d}/quote?${i}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),c=u?.estimatedRecieved||u?.estimatedReceived;return c?Q(u,{chainId:Number(e.originChainId||e.chainId||So[s]||0),venue:u?.tx?.to||"hop",amountOut:c,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:s!==a,requestedCapBps:e.maxSlippageBps??e.slippageBps??o}):{...u,autoSlippagePolicy:l}}function ir(e){return(e?.steps||[]).flatMap(t=>(t?.items||[]).filter(r=>r?.data?.to&&r?.data?.data).map(r=>({stepId:t.id,...r.data})))}function Eo(e){let t=String(e?.data??"").toLowerCase();if(!t.startsWith(lt))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 xo(e){return ir(e).find(t=>!String(t.data).toLowerCase().startsWith(lt))??null}async function dt(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:s,originCurrency:a="0x0000000000000000000000000000000000000000",destinationCurrency:o="0x0000000000000000000000000000000000000000",amount:l,tradeType:i="EXACT_INPUT"}=e;if(n==null||s==null||!l)throw new Error("relayQuote requires originChainId, destinationChainId, amount");let d=se({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(s),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!d.executable)throw new Error(`relay: route requires ${d.requiredBps} bps above cap ${d.capBps}`);let u=(t.baseUrl||process.env.RELAY_API_URL||ar).replace(/\/$/,""),c=await v(`${u}/quote`,{method:"POST",body:{user:r,originChainId:Number(n),destinationChainId:Number(s),originCurrency:a,destinationCurrency:o,amount:String(l),tradeType:i,slippageTolerance:String(d.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),f=c?.details?.currencyOut?.amount;if(!f||!/^\d+$/.test(String(f)))return{...c,autoSlippagePolicy:d};let m=xo(c);return Q(c,{chainId:Number(n),venue:m?.to||"relay",amountOut:f,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(s),requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function vo(e={},t={}){let r=await Ae(e,t),n=Number(e.originChainId),s=ir(r);if(!s.length)throw new Error("relay: quote returned no executable transaction items");let a=String(r?.autoSlippage?.venue||"").toLowerCase(),o=[],l=[];for(let u of s){if(u.chainId!=null&&Number(u.chainId)!==n)throw new Error("relay: transaction chain mismatch");if(e.user&&u.from&&String(u.from).toLowerCase()!==String(e.user).toLowerCase())throw new Error("relay: transaction sender mismatch");let c=Eo(u);c?o.push({tx:u,approval:c}):l.push(u)}if(!l.length)throw new Error("relay: quote returned no bridge deposit transaction");if(l.some(u=>String(u.to).toLowerCase()!==a))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 i=null;if(o.length===1){let{tx:u,approval:c}=o[0],f=String(e.originCurrency||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(f)||f===Ao)throw new Error("relay: native route returned an ERC20 approval");if(String(u.to).toLowerCase()!==f)throw new Error("relay: approval token mismatch");if(c.amount!==String(e.amount))throw new Error("relay: approval amount must equal the exact input amount");if(!l.some(m=>String(m.to).toLowerCase()===c.spender))throw new Error("relay: approval spender does not match the bridge target");i={token:f,spender:c.spender,amount:String(e.amount)}}let d=s.map(u=>({chainId:n,from:u.from||e.user,to:u.to,data:u.data,value:u.value??"0x0",...u.gasLimit!=null||u.gas!=null?{gasLimit:u.gasLimit??u.gas}:{},...String(u.data).toLowerCase().startsWith(lt)?{}:{slippageGuard:ae(r.autoSlippage,{chainId:n,venue:u.to,data:u.data})}}));return M({provider:"relay",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:r,autoSlippage:r.autoSlippage,requiresApproval:i,destination:a,transactions:d},{provider:"relay",kind:"relay-tx",env:t.env,nowMs:t.nowMs,expiresAtMs:t.expiresAtMs})}async function pt({from:e,to:t,amount:r,slippage:n=1,enableCentralizedSwappers:s=!1}={},a={}){if(!e||!t||!r)throw new Error("rangoQuote requires from, to, amount");let o=a.env??process.env,l=a.rangoApiKey||o.RANGO_API_KEY;if(!l)throw new Error("rango: RANGO_API_KEY is required");let i=new URLSearchParams({from:e,to:t,amount:String(r),slippage:String(n),enableCentralizedSwappers:s?"true":"false",apiKey:l}),d=(a.rangoBaseUrl||process.env.RANGO_API_URL||sr).replace(/\/$/,""),u;try{u=await v(`${d}/basic/quote?${i}`,{fetchImpl:a.fetchImpl,timeoutMs:a.timeoutMs??2e4,retries:a.retries})}catch(c){let f=Number.isInteger(c?.status)?` (HTTP ${c.status})`:"";throw new Error(`rango: request failed${f}`)}if(u?.error||u?.resultType&&u.resultType!=="OK"){let c=String(u?.error||u.resultType).split(l).join("[redacted]").split(encodeURIComponent(l)).join("[redacted]").slice(0,160);throw new Error(`rango: ${c}`)}return{amountOut:u?.route?.outputAmount,feeUsd:u?.route?.feeUsd??null,estimatedTime:u?.route?.estimatedTimeInSeconds}}var nr,or,ar,sr,So,lt,Ao,Ee=j(()=>{$();re();Pe();X();nr="https://across.to/api",or="https://api.hop.exchange/v1",ar="https://api.relay.link",sr="https://api.rango.exchange",So={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453};lt="0x095ea7b3",Ao="0x0000000000000000000000000000000000000000"});var gr={};Me(gr,{DEBRIDGE_API:()=>mr,debridgeHealth:()=>ht,debridgePrepare:()=>Po,debridgeQuote:()=>mt});function hr(e={}){return(e.baseUrl||process.env.DEBRIDGE_API_URL||mr).replace(/\/$/,"")}function ft(e,t=200){return String(e?.message||e||"unknown error").slice(0,t)}function Uo(e){return typeof e?.to=="string"&&e.to.length>0&&/^0x(?:[0-9a-fA-F]{2})+$/.test(String(e.data||""))}async function mt({srcChainId:e,srcChainTokenIn:t,srcChainTokenInAmount:r,dstChainId:n,dstChainTokenOut:s,taker:a,slippage:o=100,affiliateFeePercent:l="0"}={},i={}){if(!e||!n||!t||!s||!r)return{error:"debridge quote requires srcChainId, dstChainId, srcChainTokenIn, dstChainTokenOut, srcChainTokenInAmount"};try{let d=new URLSearchParams({srcChainId:String(e),srcChainTokenIn:t,srcChainTokenInAmount:String(r),dstChainId:String(n),dstChainTokenOut:s,dstChainTokenOutAmount:"auto",slippage:String(o),affiliateFeePercent:String(l)});a&&(d.set("dstChainTokenOutRecipient",a),d.set("srcChainOrderAuthorityAddress",a),d.set("dstChainOrderAuthorityAddress",a));let u=await v(`${hr(i)}/dln/order/create-tx?${d}`,{fetchImpl:i.fetchImpl,timeoutMs:i.timeoutMs??2e4,retries:i.retries,headers:i.headers});return u?.error?{error:ft(u.error)}:{estimation:u?.estimation??{},order:u?.order??{},fixFee:u?.fixFee??u?.estimation?.fixFee??"0",tx:u?.tx??null,walletBinding:a?{dstChainTokenOutRecipient:a,srcChainOrderAuthorityAddress:a,dstChainOrderAuthorityAddress:a}:null}}catch(d){return{error:ft(d)}}}async function ht(e={}){try{let t=await v(`${hr(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:ft(t,160)}}}async function Po(e,{taker:t}={}){if(!t)throw new Error("debridge prepare requires taker address");if(!Uo(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(s=>String(s||"").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 M({provider:"debridge",kind:"debridge-tx",calldataReady:!0,requiresUserSignature:!0,transaction:e.tx,quote:e},{provider:"debridge",kind:"debridge-tx"})}var mr,gt=j(()=>{$();X();mr="https://dln.debridge.finance/v1.0"});var ua=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),He=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),je=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"});var Z=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"});var At=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}};function Et(e){let{source:t,amountOut:r,minOut:n=null,gasUsd:s=null,feeUsd:a=null,feeIncludedInAmountOut:o=!1,oracleFeeBps:l=0,estimatedGas:i=null,liquidityUsd:d=null,error:u=null,executionReady:c=!1,meta:f={}}=e||{};if(u||r==null)return{source:t,quality:Z.FAILED,amountOut:null,error:u||"no amountOut returned"};let m=At(r);if(m==null||m<=0n)return{source:t,quality:Z.FAILED,amountOut:null,error:"non-positive amountOut"};let h=Number(l);return{source:t,quality:s==null?Z.NO_GAS:Z.FULL,amountOut:m.toString(),minOut:At(n)?.toString()??null,gasUsd:s,feeUsd:a,feeIncludedInAmountOut:o===!0,oracleFeeBps:Number.isFinite(h)&&h>0?Math.floor(h):0,estimatedGas:i==null?null:String(i),liquidityUsd:d==null?null:Number(d),executionReady:c,meta:f}}function xt(e,{destPriceUsd:t=null,destDecimals:r=null,liquidityFirst:n=!0,liquidityBandBps:s=50,gasPriceWei:a=null,nativePriceUsd:o=null}={}){let l=e.filter(S=>S.quality!==Z.FAILED),i=e.filter(S=>S.quality===Z.FAILED),d=t!=null&&t>0&&r!=null&&r>=0,u=Number(a),c=Number(o),f=Number.isFinite(u)&&u>0&&Number.isFinite(c)&&c>0,m=l.map(S=>{let k=BigInt(S.amountOut),A=0n,w=!1,U=!1,R=BigInt(S.oracleFeeBps??0),V=R>0n?k*R/10000n:0n;if(d){let C=S.gasUsd,N=Number(S.meta?.gasUnits??S.estimatedGas);if(C==null&&f&&Number.isFinite(N)&&N>0){let H=N*u/1e18*c;Number.isFinite(H)&&H>=0&&(C=H,U=!0)}let T=(C??0)+(S.feeIncludedInAmountOut?0:S.feeUsd??0);if(T>0){let H=T/t*10**r;Number.isFinite(H)&&H>=0&&(A=BigInt(Math.floor(H)),w=!0)}else C===0&&(w=!0)}let F=A+V,D=k>F?k-F:0n;return{...S,grossOut:k.toString(),netOut:D.toString(),costInDest:A.toString(),oracleFeeInDest:V.toString(),costAccounted:w,gasEstimated:U}}),h=Number(s)>0?Number(s):0,b=m.reduce((S,k)=>BigInt(k.netOut)>S?BigInt(k.netOut):S,0n),y=S=>b>0n?Number((b-BigInt(S))*10000n/b):0,E=[],g=(S,k)=>{let A=BigInt(S.netOut),w=BigInt(k.netOut);return A!==w?w>A?1:-1:String(S.source).localeCompare(String(k.source))},I=m.slice().sort(g)[0]??null;m.sort((S,k)=>{let A=y(S.netOut)<=h?0:1,w=y(k.netOut)<=h?0:1;if(n&&h>0&&A!==w)return A-w;if(n&&h>0){let U=S.liquidityUsd??-1,R=k.liquidityUsd??-1;if(U!==R)return R-U}return g(S,k)}),n&&h>0&&I&&m[0]&&m[0].source!==I.source&&E.push(`liquidity-first: chose ${m[0].source} (liquidity $${m[0].liquidityUsd??"unknown"}) over best-price ${I.source} within ${h} bps`);let _=m.filter(S=>!S.costAccounted).map(S=>S.source);d?_.length&&E.push(`gas not reported by: ${_.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):E.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let O=m[0];if(d&&O&&O.costAccounted===!1){let S=m.find(k=>k.costAccounted&&y(k.netOut)<=h);S&&E.push(`winner ${O.source} has UNMEASURED gas; gas-measured ${S.source} is within ${h} bps and may net more once ${O.source}'s real gas is paid \u2014 prefer it if unsure.`)}let L=m.filter(S=>S.gasEstimated).map(S=>S.source);L.length&&E.push(`gas ESTIMATED (from gas units x current gas price, not measured) for: ${L.join(", ")}. Net includes this estimate so the ranking is gas-inclusive, but the on-chain gas may differ.`);let x=null,B=null;if(m.length>=2&&m[0].costAccounted&&m[1].costAccounted){let S=BigInt(m[0].netOut),k=BigInt(m[1].netOut);k>0n&&(x=Number((S-k)*10000n/k),B=`${m[0].source} vs ${m[1].source}`)}return{best:m[0]??null,routes:m,failed:i,improvementBps:x,spreadBasis:B,rankedOn:d?"net-of-cost":"gross",warnings:E}}async function vt(e,{timeoutMs:t=12e3}={}){let r=(s,a)=>{let o;return Promise.race([s,new Promise((l,i)=>{o=setTimeout(()=>i(new Error(`${a}: timeout`)),t)})]).finally(()=>clearTimeout(o))};return(await Promise.allSettled(e.map(s=>r(Promise.resolve().then(s.run),s.source)))).map((s,a)=>{let o=e[a].source;return s.status==="rejected"?Et({source:o,error:String(s.reason?.message||s.reason)}):Et({source:o,...s.value})})}$e();$();re();X();Le();$();re();X();$();re();X();$();re();import{TypedDataEncoder as ys,getAddress as Ss,isAddress as As}from"ethers";var ms=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});Pe();X();var Os=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),Ts=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"});var Ns=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"}]}),Bs=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]});import{Interface as tr,getAddress as Xs,isAddress as Ys}from"ethers";$();var er={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}},_s=new Map(Object.values(er).map(e=>[e.chainId,e]));import{Interface as po,getAddress as Ms}from"ethers";var Hs=new po(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);$();var Gs=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});re();X();var ri=new tr(["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)"]),ni=new tr(["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 ho,Interface as st,getAddress as ii,isAddress as ci,keccak256 as ui}from"ethers";re();X();var mi=ho.defaultAbiCoder();var hi=new st(["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)"]),gi=new st(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),bi=new st(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96,int24 tick,uint24 protocolFee,uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),wi=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"]]),yi=(1n<<14n)-1n;$();var go="https://coins.llama.fi",bo="https://api.llama.fi";function wo(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||go).replace(/\/$/,"")}function yo(e={}){return(e.baseUrl||process.env.DEFILLAMA_API_URL||bo).replace(/\/$/,"")}async function it(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return v(`${wo(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function rr(e={}){return v(`${yo(e)}/protocols`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??2e4})}var G=e=>{let t=Number(e);return Number.isFinite(t)?t:null};function cr(e){if(!Array.isArray(e))return null;let t=0,r=!1;for(let n of e){let s=G(n?.amountUSD);s!=null&&(t+=s,r=!0)}return r?t:null}function ur(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,""),lr=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 Co(e={}){try{let t=await rr({...e,baseUrl:e.defillamaApiBaseUrl,timeoutMs:e.defillamaTimeoutMs??Math.min(Number(e.timeoutMs??5e3),5e3)});return Array.isArray(t)?t:[]}catch{return[]}}function Io(e,t={}){let r=ie(t.tool||t.provider||t.bridge||t.protocol),n=[];return e==="lifi"&&r&&r!=="lifi"&&n.push(...lr[r]||[r]),n.push(...lr[ie(e)]||[e]),n}function ko(e,t,r={}){let n=Array.isArray(e)?e:[],s=Io(t,r).map(ie).filter(Boolean);for(let a of s){let o=n.find(i=>ie(i?.slug)===a||ie(i?.name)===a),l=G(o?.tvl);if(l!=null)return{liquidityUsd:l,protocol:o?.name??o?.slug??a}}for(let a of s){let o=n.find(i=>{let d=ie(i?.category);return!d.includes("bridge")&&!d.includes("crosschain")?!1:ie(i?.slug).includes(a)||ie(i?.name).includes(a)}),l=G(o?.tvl);if(l!=null)return{liquidityUsd:l,protocol:o?.name??o?.slug??a}}return null}function dr({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:s,taker:a,slippageBps:o,allowedSources:l,opts:i={}}){let d=[],u=null,c=async(m,h={})=>(u||=Co(i),ko(await u,m,h));if(d.push({source:"lifi",run:async()=>{let m=await me({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:s,fromAddress:a,slippageBps:o},i),h=m?.estimate??m?.[0]?.estimate,b=(m?.includedSteps??m?.steps??[]).map((g,I)=>({id:String(g?.id??`step-${I+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)})),y={tool:m?.tool??m?.toolDetails?.name,durationSeconds:G(h?.executionDuration),destinationDecimals:G(m?.action?.toToken?.decimals),routeSteps:b,feeCosts:ur(h?.feeCosts),gasCosts:ur(h?.gasCosts)},E=await c("lifi",y);return{amountOut:h?.toAmount,minOut:h?.toAmountMin,gasUsd:cr(h?.gasCosts),feeUsd:cr(h?.feeCosts),feeIncludedInAmountOut:!0,oracleFeeBps:m?.oracleFee?.applies?m.oracleFee.bps:0,liquidityUsd:E?.liquidityUsd??null,meta:{...y,liquidityProtocol:E?.protocol,oracleFee:m?.oracleFee??null}}}}),d.push({source:"relay",run:async()=>{let{relayQuote:m}=await Promise.resolve().then(()=>(Ee(),qe)),h=await m({user:a,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(s),slippageBps:o},i),b=h?.details,y=(h?.steps??[]).map((L,x)=>({id:String(L?.id??`step-${x+1}`),type:String(L?.kind??"transaction"),tool:"Relay",label:String(L?.description??L?.action??L?.id??`Step ${x+1}`),fromChainId:Number(e),toChainId:Number(t)})),E=String(h?.fees?.relayer?.amountUsd??"").trim(),g=String(h?.fees?.gas?.amountUsd??"").trim(),I=String(b?.totalImpact?.usd??"").trim(),_={durationSeconds:G(b?.timeEstimate),rate:b?.rate,destinationDecimals:G(b?.currencyOut?.currency?.decimals),routeSteps:y,feeCosts:[.../^\d+(?:\.\d+)?$/.test(E)?[{name:"relayer",amountUsd:E}]:[],.../^-?\d+(?:\.\d+)?$/.test(I)?[{name:"total-impact",amountUsd:I}]:[]],gasCosts:/^\d+(?:\.\d+)?$/.test(g)?[{name:"origin-gas",amountUsd:g}]:[]},O=await c("relay",_);return{amountOut:b?.currencyOut?.amount,minOut:b?.currencyOut?.minimumAmount,gasUsd:G(h?.fees?.gas?.amountUsd),feeUsd:G(h?.fees?.relayer?.amountUsd)??(G(b?.totalImpact?.usd)!=null?Math.abs(G(b.totalImpact.usd)):null),feeIncludedInAmountOut:!0,liquidityUsd:O?.liquidityUsd??null,meta:{..._,liquidityProtocol:O?.protocol}}}}),d.push({source:"across",run:async()=>{let{acrossSuggestedFees:m}=await Promise.resolve().then(()=>(Ee(),qe)),h=await m({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(s)},i),b=h?.totalRelayFee?.total,y=null;if(b!=null)try{let g=BigInt(String(s))-BigInt(String(b));g>0n&&(y=g.toString())}catch{}let E=await c("across");return{amountOut:y,gasUsd:null,liquidityUsd:E?.liquidityUsd??null,meta:{derivedFromFees:!0,durationSeconds:G(h?.estimatedFillTimeSec),limits:h?.limits?{min:h.limits.minDeposit,max:h.limits.maxDeposit}:void 0,liquidityProtocol:E?.protocol}}}}),!Array.isArray(l))return d;let f=new Set(l.map(m=>String(m).toLowerCase()));return d.filter(m=>f.has(m.source))}Le();var Oo={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"},pr=Object.freeze(["lifi","relay"]);function To(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 No(e,t=pr){let r=new Set((Array.isArray(t)?t:pr).map(o=>String(o).toLowerCase())),n=(e?.routes??[]).filter(o=>r.has(o.source)),s=new Set(n.map(o=>o.source)),a=(e?.failed??[]).filter(o=>r.has(o.source)&&!s.has(o.source));return[...n,...a].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 Bo(e,t,r){let n=Oo[Number(e)];if(!n)return{priceUsd:null,decimals:null};let s=`${n}:${t}`;try{let o=(await it([s],r))?.coins?.[s],l=Number(o?.price),i=Number(o?.decimals);return{priceUsd:Number.isFinite(l)?l:null,decimals:Number.isFinite(i)?i:null}}catch{return{priceUsd:null,decimals:null}}}async function fr(e,t={}){let{fromChainId:r,toChainId:n,tokenIn:s,tokenOut:a,amountIn:o}=e;if(r==null||n==null||!s||!a||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 l=To(e.slippageBps),i={...e,slippageBps:l},d=Bo(n,a,t),u=dr({...i,opts:t}),[c,f]=await Promise.all([vt(u,{timeoutMs:t.timeoutMs??15e3}),d]),m=xt(c,{destPriceUsd:f.priceUsd,destDecimals:e.decimalsOut??f.decimals,liquidityFirst:!1,liquidityBandBps:0}),h=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:s,tokenOut:a,amountIn:String(o),slippageBps:l,...m,routeOptions:No(m,e.allowedSources),durations:h,sourcesTried:u.length,sourcesAnswered:c.filter(b=>b.quality!==Z.FAILED).length,note:_o(m,u.length)}}function Ro(e){let t=e?.meta?.oracleFee;return t?.applies?` \xB7 ${Xt(t)}`:""}function _o(e,t){if(!e.best)return"no source returned a usable route";let r=e.routes.length,n=Ro(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 s=e.improvementBps,a=s/100;if(s<.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=a>=.01?`${a.toFixed(2)}%`:`${s.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}X();$e();gt();$();var bt="https://api.changenow.io/v2",he=new Map,br=0,Lo=6e5;async function $o({active:e=!0}={},t={}){let r=Date.now();if(he.size&&r-br<Lo)return[...he.values()];try{let n=await v(`${bt}/exchange/currencies?active=${e?"true":"false"}`,t);he.clear();for(let s of n??[])he.set(String(s.ticker).toLowerCase(),s);return br=r,n??[]}catch(n){return he.size?[...he.values()]:{error:String(n.message||n).slice(0,200)}}}async function Do(e,t,r={}){if(!e||!t)return{error:"changenow minAmount requires fromTicker and toTicker"};try{return{minAmount:(await v(`${bt}/exchange/min-amount/${encodeURIComponent(e)}_${encodeURIComponent(t)}`,r))?.minAmount??"0"}}catch(n){return{error:String(n.message||n).slice(0,200)}}}async function Fo(e,t,r,{flow:n="standard"}={},s={}){if(!e||!t||!r)return{error:"changenow estimate requires fromTicker, toTicker, fromAmount"};try{let a=new URLSearchParams({fromCurrency:String(e).toLowerCase(),toCurrency:String(t).toLowerCase(),fromAmount:String(r),flow:n}),o=await v(`${bt}/exchange/estimated-amount?${a}`,s);return{fromAmount:o?.fromAmount,toAmount:o?.toAmount,rate:o?.rate,flow:o?.flow??n}}catch(a){return{error:String(a.message||a).slice(0,200)}}}async function wr({fromTicker:e,toTicker:t,fromAmount:r,flow:n}={},s={}){if(!e||!t)return{error:"changenow quote requires fromTicker and toTicker"};let a=await Do(e,t,s);if(a.error)return a;let o=r??a.minAmount,l=await Fo(e,t,o,{flow:n},s);if(l.error)return l;let i=await $o({},s),d=i.find(c=>String(c?.ticker).toLowerCase()===String(e).toLowerCase()),u=i.find(c=>String(c?.ticker).toLowerCase()===String(t).toLowerCase());return{provider:"changenow",fromTicker:e,toTicker:t,fromAmount:o,toAmount:l.toAmount,estimatedRate:l.rate,minAmount:a.minAmount,flow:l.flow,networkFee:d?.networkFee??null,kycRequired:d?.kycRequired??u?.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 qo="https://api.squidrouter.com/v1";async function yr({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:s,fromAddress:a,slippage:o=1}={},l={}){if(!e||!t||!r||!n||!s||!a)return{error:"squid quote requires fromChain, toChain, fromToken, toToken, fromAmount, fromAddress"};try{let i={fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:String(s),fromAddress:a,slippage:o},d=await v(`${qo}/route`,{...l,method:"POST",body:JSON.stringify(i),headers:{"content-type":"application/json",...l.headers||{}}});return{route:d?.route??{},toAmount:d?.route?.estimate?.toAmount,fee:d?.route?.estimate?.feeCosts}}catch(i){return{error:String(i.message||i).slice(0,200)}}}$();var Mo="https://api.stargate.finance";async function Sr({srcChainId:e,dstChainId:t,token:r,amount:n,dstGasForCall:s=0,minAmountOut:a="0"}={},o={}){if(!e||!t||!r||!n)return{error:"stargate quote requires srcChainId, dstChainId, token, amount"};try{let l=new URLSearchParams({srcChainId:String(e),dstChainId:String(t),token:r,amount:String(n),dstGasForCall:String(s),minAmountOut:String(a)}),i=await v(`${Mo}/quote?${l}`,o);return{amountOut:i?.amountOut,fee:i?.fee,estimatedTime:i?.estimatedTime}}catch(l){return{error:String(l.message||l).slice(0,200)}}}$();var Ar="https://midgard.ninerealms.com/v2";async function Er({fromAsset:e,toAsset:t,amount:r,destination:n}={},s={}){if(!e||!t||!r)return{error:"thorchain quote requires fromAsset, toAsset, amount"};try{let a=new URLSearchParams({from_asset:e,to_asset:t,amount:String(r),destination:n||""}),o=await v(`${Ar}/quote/swap?${a}`,s);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(a){return{error:String(a.message||a).slice(0,200)}}}async function xr(){try{return{ok:(await v(`${Ar}/health`))?.scannerHeight>0}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}$();var Ho="https://api.socket.tech/v2";async function vr({fromChainId:e,toChainId:t,fromToken:r,toToken:n,fromAmount:s,userAddress:a}={},o={}){if(!e||!t||!r||!n||!s||!a)return{error:"bungee quote requires fromChainId, toChainId, fromToken, toToken, fromAmount, userAddress"};try{let l=new URLSearchParams({fromChainId:String(e),toChainId:String(t),fromTokenAddress:r,toTokenAddress:n,fromAmount:String(s),userAddress:a,sort:"output",singleTxOnly:"false"}),i=await v(`${Ho}/quote?${l}`,o);return{amountOut:i?.result?.toAmount,feeUsd:i?.result?.totalGasFeesInUsd,route:i?.result?.route,estimatedTime:i?.result?.serviceTime?`${i.result.serviceTime}s`:"unknown"}}catch(l){return{error:String(l.message||l).slice(0,200)}}}$();var jo="https://api.connext.network";async function Cr({originDomain:e,destinationDomain:t,originToken:r,destinationToken:n,amount:s}={},a={}){if(!e||!t||!r||!n||!s)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(s)},l=await v(`${jo}/estimate`,{...a,method:"POST",body:JSON.stringify(o),headers:{"content-type":"application/json",...a.headers||{}}});return{amountOut:l?.amountOut,fee:l?.fee,estimatedTime:l?.estimatedTransferTime}}catch(o){return{error:String(o.message||o).slice(0,200)}}}$();var Vo="https://api.portalbridge.com/v1";async function Ir({fromChain:e,toChain:t,token:r,amount:n}={},s={}){if(!e||!t||!r||!n)return{error:"wormhole quote requires fromChain, toChain, token, amount"};try{let a=new URLSearchParams({fromChain:String(e),toChain:String(t),token:r,amount:String(n)}),o=await v(`${Vo}/quote?${a}`,s);return{amountOut:o?.amountOut,fee:o?.fee,estimatedTime:o?.estimatedTime}}catch(a){return{error:String(a.message||a).slice(0,200)}}}Ee();import{Interface as kr,getAddress as Gc,id as Or}from"ethers";$();var Go=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 Yc=new kr(["function decimals() view returns (uint8)","function symbol() view returns (string)"]),Jc=new kr(["function isApprovedForAll(address owner, address operator) view returns (bool)","function name() view returns (string)"]),Zc=Or("Approval(address,address,uint256)"),eu=Or("ApprovalForAll(address,address,bool)");var tu=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)"}),ru=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"}]),nu=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"}]),ou=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"}]}),au=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}]}),Wo=(1n<<256n)-1n,su=Wo/2n,iu=4320*60*60*1e3,cu=360*60*1e3,uu=600*1e3,lu=45*1e3;var xe=Object.freeze(["debridge","lifi","relay","squid","stargate","thorchain","bungee","connext","wormhole","across","hop","changenow","rango"]),Tr=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche"}),Qo=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"}),Xo=Object.freeze({1:"ETH",56:"BSC",8453:"BASE",42161:"ARB",43114:"AVAX"}),Ur=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]);function wt(e,t=180){return String(e?.message||e||"unknown error").replace(/\s+/g," ").slice(0,t)}function Nr(e){let t=String(e??"");if(!/^\d+$/.test(t))return null;try{return BigInt(t)>0n?t:null}catch{return null}}function Yo(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 Jo(e,t){let r=ge(t),n=String(e??"");if(r==null||!/^\d+$/.test(n))return null;if(r===0)return n;let s=n.padStart(r+1,"0"),a=s.slice(0,-r),o=s.slice(-r).replace(/0+$/,"");return o?`${a}.${o}`:a}function Zo(e,t){let r=ge(t),n=/^(\d+)(?:\.(\d+))?$/.exec(String(e??""));if(r==null||!n)return null;let s=n[2]||"";if(s.length>r&&/[1-9]/.test(s.slice(r)))return null;let a=s.slice(0,r).padEnd(r,"0");try{return(BigInt(n[1])*10n**BigInt(r)+BigInt(a||"0")).toString()}catch{return null}}function Br(e,t,r){let n=ge(t),s=ge(r);if(n==null||s==null||!/^\d+$/.test(String(e??"")))return null;let a=BigInt(String(e));return s>=n?(a*10n**BigInt(s-n)).toString():(a/10n**BigInt(n-s)).toString()}function yt(e){return typeof e?.to=="string"&&e.to.length>0&&/^0x(?:[0-9a-fA-F]{2})+$/.test(String(e.data||""))}function ea(e){return(e?.steps||[]).some(t=>(t?.items||[]).some(r=>yt(r?.data)))}function Rr(e,t,r){let n=Qo[Number(e)];return n?Ur.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=Xo[Number(e)];return n?Ur.has(String(t||"").toLowerCase())?`${n}.${r}`:`${n}.${r}-${t}`:null}async function Pr(e={},t={}){let{fromChainId:r,toChainId:n,tokenIn:s,tokenOut:a,amount:o,taker:l,fromSymbol:i="?",toSymbol:d="?",fromDecimals:u,toDecimals:c,slippageBps:f}=e,m=t.includeCentralized===!0||e.includeCentralized===!0,h=ge(u),b=ge(c),y=new Map(xe.map(p=>[p,{provider:p,status:"pending"}])),E=[],g={fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs,retries:t.retries,headers:t.headers},I=(p,q,W=!1)=>{y.set(p,{provider:p,status:"unavailable",reason:wt(q),optional:W})},_=(p,q)=>{y.set(p,{provider:p,status:"skipped",reason:wt(q)})},O=(p,q,W)=>{y.set(p,{provider:p,status:"attempted"}),E.push(Promise.resolve().then(q).then(K=>{if(K?.error)throw new Error(K.error);let de=W(K),ne=Nr(de?.amountOut);if(!ne)throw new Error("no usable integer base-unit amountOut");let ke={...de,provider:p,amountOut:ne,raw:K};return y.set(p,{provider:p,status:"successful"}),ke}).catch(K=>(y.set(p,{provider:p,status:"failed",reason:wt(K)}),null)))};O("debridge",()=>mt({srcChainId:r,srcChainTokenIn:s,srcChainTokenInAmount:o,dstChainId:n,dstChainTokenOut:a,taker:l,slippage:f},g),p=>({amountOut:p.estimation?.dstChainTokenOut?.amount??p.estimation?.toAmount,feeUsd:p.estimation?.fixFee??p.fixFee,estimatedTime:p.estimation?.execution?.estimatedTransferTime?`${p.estimation.execution.estimatedTransferTime}s`:"unknown",preparable:yt(p.tx)})),O("lifi",()=>me({fromChain:r,toChain:n,fromToken:s,toToken:a,fromAmount:o,fromAddress:l},g),p=>({amountOut:p.estimate?.toAmount??p.toAmount,feeUsd:p.estimate?.feeCosts??null,estimatedTime:p.estimate?.executionDuration??"unknown",preparable:yt(p.transactionRequest)})),O("relay",()=>Ae({user:l,originChainId:r,destinationChainId:n,originCurrency:s,destinationCurrency:a,amount:String(o)},g),p=>({amountOut:p.details?.currencyOut?.amount,feeUsd:p.details?.totalImpact?.usd??null,estimatedTime:p.details?.timeEstimate??"unknown",preparable:ea(p)})),O("squid",()=>yr({fromChain:r,toChain:n,fromToken:s,toToken:a,fromAmount:o,fromAddress:l},g),p=>({amountOut:p.toAmount,feeUsd:p.fee??null,estimatedTime:"30s - 3min",preparable:!1})),O("stargate",()=>Sr({srcChainId:r,dstChainId:n,token:s,amount:o},g),p=>({amountOut:p.amountOut,feeUsd:p.fee,estimatedTime:p.estimatedTime||"1-5 min",preparable:!1}));let L=Br(o,h,8),x=_r(r,s,i),B=_r(n,a,d);h==null||b==null?I("thorchain","fromDecimals and toDecimals are required for unit conversion"):!x||!B?I("thorchain","supported chain mapping plus qualified asset symbols are required"):Nr(L)?O("thorchain",()=>Er({fromAsset:x,toAsset:B,amount:L,destination:l},g),p=>({amountOut:Br(p.expectedAmountOut,8,b),feeUsd:p.fees?.total,estimatedTime:p.estimatedTime||"10-30 min",preparable:!1})):I("thorchain","amount is below THORChain's 8-decimal quote precision"),O("bungee",()=>vr({fromChainId:r,toChainId:n,fromToken:s,toToken:a,fromAmount:o,userAddress:l},g),p=>({amountOut:p.amountOut,feeUsd:p.feeUsd,estimatedTime:p.estimatedTime,preparable:!1})),O("connext",()=>Cr({originDomain:r,destinationDomain:n,originToken:s,destinationToken:a,amount:o},g),p=>({amountOut:p.amountOut,feeUsd:p.fee,estimatedTime:p.estimatedTime||"5-20 min",preparable:!1})),O("wormhole",()=>Ir({fromChain:r,toChain:n,token:s,amount:o},g),p=>({amountOut:p.amountOut,feeUsd:p.fee,estimatedTime:p.estimatedTime||"5-15 min",preparable:!1})),O("across",()=>De({token:s,destinationToken:a,originChainId:r,destinationChainId:n,amount:String(o)},g),p=>{let q=p.outputAmount??p.expectedOutputAmount,W=p.totalRelayFee?.total??p.relayFeeTotal;return{amountOut:q??(W!=null?Yo(o,W):null),feeUsd:p.relayFeeTotalUsd??null,estimatedTime:p.estimatedFillTimeSec!=null?`${p.estimatedFillTimeSec}s`:"unknown",preparable:!1}});let S=Tr[Number(r)],k=Tr[Number(n)];!S||!k||!i||i==="?"?I("hop","supported chain mapping and fromSymbol are required"):O("hop",()=>Fe({amount:String(o),token:i,fromChain:S,toChain:k},g),p=>({amountOut:p.estimatedRecieved??p.estimatedReceived,feeUsd:p.feeUsd??null,estimatedTime:p.estimatedTime??"unknown",preparable:!1}));let A=Jo(o,h);m?h==null||b==null?I("changenow","fromDecimals and toDecimals are required for unit conversion"):!i||!d||i==="?"||d==="?"?I("changenow","fromSymbol and toSymbol are required"):A==null?I("changenow","valid integer amount is required"):O("changenow",()=>wr({fromTicker:i,toTicker:d,fromAmount:A},g),p=>({amountOut:Zo(p.toAmount,b),feeUsd:p.networkFee,estimatedTime:p.flow==="standard"?"5-30 min":"instant",preparable:!1,centralized:!0,kycRequired:!!p.kycRequired,kycRisk:!0,riskDisclosure:p.riskDisclosure||"ChangeNOW is centralized and may require KYC."})):_("changenow","centralized/KYC-risk routes require includeCentralized=true");let w=t.env??process.env,U=t.rangoApiKey||w.RANGO_API_KEY,R=Rr(r,s,i),V=Rr(n,a,d);U?!R||!V?I("rango","supported Rango chain/token identifiers are required",!0):O("rango",()=>pt({from:R,to:V,amount:String(o),enableCentralizedSwappers:!1},{...t,rangoApiKey:U}),p=>({amountOut:p.amountOut,feeUsd:p.feeUsd,estimatedTime:p.estimatedTime!=null?`${p.estimatedTime}s`:"unknown",preparable:!1})):I("rango","RANGO_API_KEY is not configured",!0);let D=(await Promise.all(E)).filter(Boolean);D.sort((p,q)=>{let W=BigInt(p.amountOut),K=BigInt(q.amountOut);return W!==K?W>K?-1:1:p.preparable!==q.preparable?p.preparable?-1:1:xe.indexOf(p.provider)-xe.indexOf(q.provider)});let C=xe.map(p=>y.get(p)),N=C.filter(p=>["successful","failed"].includes(p.status)).map(p=>p.provider),T=C.filter(p=>p.status==="successful").map(p=>p.provider),H=C.filter(p=>p.status==="failed").map(p=>p.provider),z=C.filter(p=>p.status==="unavailable").map(p=>p.provider),J=C.filter(p=>p.status==="skipped").map(p=>p.provider),ce=C.filter(p=>p.status==="failed").map(p=>`${p.provider}: ${p.reason}`),Ce=D.length>0,Ie=Ce&&C.every(p=>p.status==="successful"||p.status==="skipped"||p.status==="unavailable"&&p.optional);return{ok:Ce,providers:D.map(p=>p.provider),bestRoute:D[0]?.provider??"none",winner:D[0]??null,runnersUp:D.slice(1),errors:ce.length?ce:null,attemptedProviders:N,successfulProviders:T,failedProviders:H,unavailableProviders:z,skippedProviders:J,comparisonComplete:Ie,coverage:{roster:[...xe],attemptedProviders:N,successfulProviders:T,failedProviders:H,unavailableProviders:z,skippedProviders:J,complete:Ie,details:C}}}var vu=Object.freeze({debridge:e=>ht(e),lifi:e=>at(e),relay:e=>dt(e),thorchain:e=>xr(e),across:e=>ct(e),hop:e=>ut(e)}),Cu=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 Y=/^0x[0-9a-fA-F]{40}$/,Lr=/^0x(?:[0-9a-fA-F]{2})+$/;function St(e){return Array.isArray(e)?e.map(St):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([t])=>t!=="signature"&&t!=="rawTransaction"&&t!=="signedTransaction").map(([t,r])=>[t,St(r)]))}var ta=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),ra=100;function na(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 $r(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 oa(e){if(Array.isArray(e)){let r=$r(e);if(!r.length)return null;let n=r.reduce((s,a)=>s+Number(a.amountUsd),0);return Number.isFinite(n)?n:null}let t=Number(e);return e!=null&&e!==""&&Number.isFinite(t)?t:null}function aa(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 Dr(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(!Y.test(String(r.to??"")))return{ok:!1,reason:"deBridge paired transaction target is not a valid destination"};if(!Lr.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(!Y.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(s=>String(s??"").toLowerCase()!==String(t.taker).toLowerCase())?{ok:!1,reason:"deBridge destination recipient and order authorities are not bound to taker"}:{ok:!0,reason:null}}function sa(e,t){return be[e?.provider]?e.provider==="debridge"?Dr(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 ve(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 ia(e,t){let{fromChainId:r,toChainId:n,tokenIn:s,tokenOut:a,amountIn:o,taker:l}=e;if(r==null||n==null||!s||!a||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 i=na(e.slippageBps),d=await Pr({fromChainId:r,toChainId:n,tokenIn:s,tokenOut:a,amount:String(o),taker:l,fromSymbol:e.fromSymbol,toSymbol:e.toSymbol,fromDecimals:e.fromDecimals??e.decimalsIn,toDecimals:e.toDecimals??e.decimalsOut,slippageBps:i,includeCentralized:e.includeCentralized===!0},t),c=[d.winner,...d.runnersUp||[]].filter(Boolean).map(g=>{let I=$r(g.feeUsd),_=sa(g,e),O={source:g.provider,quality:"NO_GAS",amountOut:String(g.amountOut),grossOut:String(g.amountOut),netOut:String(g.amountOut),gasUsd:null,feeUsd:oa(g.feeUsd),preparable:_.ok,prepareReason:_.reason,centralized:g.centralized===!0,kycRequired:g.kycRequired===!0,kycRisk:g.kycRisk===!0,riskDisclosure:g.riskDisclosure??null,meta:{durationSeconds:aa(g.estimatedTime),estimatedTime:g.estimatedTime??null,destinationDecimals:Number.isInteger(e.toDecimals??e.decimalsOut)?Number(e.toDecimals??e.decimalsOut):null,routeSteps:[],feeCosts:I,gasCosts:[]}};return Object.defineProperty(O,"raw",{value:g.raw,enumerable:!1}),O}),f=c[0]??null,m=c.map((g,I)=>({provider:g.source,status:"quoted",rank:I+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===f?.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})),h=new Set(c.map(g=>g.source)),b=(d.coverage?.details||[]).filter(g=>!h.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})),y=null;if(c.length>=2&&BigInt(c[1].netOut)>0n){let g=(BigInt(c[0].netOut)-BigInt(c[1].netOut))*10000n/BigInt(c[1].netOut);g<=BigInt(Number.MAX_SAFE_INTEGER)&&(y=Number(g))}let E=[];return d.comparisonComplete!==!0&&E.push("bridge comparison coverage is incomplete; unavailable and failed providers remain explicit in routeOptions"),f&&f.preparable!==!0&&E.push(`${f.source} is the overall quote winner but is quote-only and cannot become a prepared wallet action`),{kind:"bridge",fromChainId:r,toChainId:n,tokenIn:s,tokenOut:a,amountIn:String(o),slippageBps:i,best:f,routes:c,failed:b.filter(g=>g.status==="unavailable"),routeOptions:[...m,...b],winner:ve(f),runnersUp:c.slice(1).map(ve),coverage:d.coverage,comparisonComplete:d.comparisonComplete===!0,complete:d.comparisonComplete===!0,sourcesTried:d.coverage?.roster?.length??0,sourcesAnswered:c.length,improvementBps:y,spreadBasis:c.length>=2?`${c[0].source} vs ${c[1].source}`:null,rankedOn:"exact-base-unit-output",durations:c.filter(g=>g.meta.durationSeconds!=null).map(g=>({source:g.source,seconds:g.meta.durationSeconds})),warnings:E,note:c.length?`${c.length} of ${d.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 s=Dr({provider:"debridge",preparable:!0,raw:n?.raw},{fromChainId:e,taker:t});if(!s.ok)throw new Error(s.reason);let{debridgePrepare:a}=await Promise.resolve().then(()=>(gt(),gr)),l=(await a(n.raw,{taker:t})).transaction,i=l.value??"0";if(!/^(?:0x[0-9a-fA-F]+|\d+)$/.test(String(i)))throw new Error("deBridge paired transaction value is not a canonical unsigned amount");return{transactions:[{chainId:Number(e),from:String(l.from),to:String(l.to),data:String(l.data),value:String(i),...l.gasLimit!=null||l.gas!=null?{gasLimit:l.gasLimit??l.gas}:{}}],destination:String(l.to),requiresApproval:null,amountOut:n.amountOut,minOut:null,durationSeconds:n.meta?.durationSeconds??null}},relay:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:s,taker:a,slippageBps:o},l)=>{let{relayPrepare:i}=await Promise.resolve().then(()=>(Ee(),qe)),d=await i({user:a,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(s),slippageBps:o},l);return{transactions:d.transactions||[],destination:d.destination??null,requiresApproval:d.requiresApproval??null,amountOut:d.quote?.details?.currencyOut?.amount??null,minOut:d.quote?.details?.currencyOut?.minimumAmount??null,durationSeconds:d.quote?.details?.timeEstimate??null}},lifi:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:s,taker:a,isHolder:o,slippageBps:l},i)=>{let{lifiPrepare:d}=await Promise.resolve().then(()=>($e(),Zt)),u=await d({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:s,fromAddress:a,isHolder:o,feeAction:"bridge",slippageBps:l},i);return{transactions:u.transaction?[u.transaction]:[],destination:u.transaction?.to??null,requiresApproval:u.requiresApproval??null,amountOut:u.quote?.estimate?.toAmount??null,minOut:u.quote?.estimate?.toAmountMin??null,durationSeconds:u.quote?.estimate?.executionDuration??null}}};function Nu(){return Object.keys(be)}async function Bu(e,t={}){let{taker:r,fromChainId:n,toChainId:s,tokenIn:a,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(!Y.test(r))throw new Error(`taker must be a valid 20-byte address, got "${r}"`);if(ta.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&&(!Y.test(String(a))||!Y.test(String(o))))throw new Error("wallet-review bridge preparation requires exact origin and destination token addresses");let l=!Array.isArray(e.allowedSources),i=l?await ia(e,t):await fr(e,t);if(!i.best)return{ok:!1,reason:"no source returned a usable bridge route",comparison:i};let d=i.best.source,u=l?i.routes.find(w=>w.preparable===!0&&be[w.source]):i.best,c=e.source||u?.source;if(!c)return{ok:!1,reason:`${d} 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:d,comparison:i};let f=i.routes.find(w=>w.source===c);if(!f)return{ok:!1,reason:`source "${c}" returned no usable route`,comparison:i};let m=be[c];if(!m||l&&f.preparable!==!0){let w=i.routes.find(U=>be[U.source]&&(!l||U.preparable===!0)&&U.source!==c);return{ok:!1,reason:`${c} is quote-only for this response and cannot become a prepared wallet action. `+(w?`Next preparable route is ${w.source}; pass source:"${w.source}".`:"No route in this comparison has verified unsigned bytes and a strict preparer."),failureKind:"no-prepare-path",...w?{alternative:w.source}:{},winner:d,comparison:i}}i={...i,routeOptions:(i.routeOptions||[]).map(w=>({...w,selected:w.provider===c,quoteWinner:w.provider===d}))};let h;try{h=await m(e,t,f)}catch(w){let U=typeof w?.body=="string"?w.body:w?.body?JSON.stringify(w.body):"",R=[String(w?.message||w),U].filter(Boolean).join(" :: "),V=/allowance/i.test(R),F=!V&&/not enough|insufficient|balance/i.test(R),D=i.routes.find(C=>be[C.source]&&(!l||C.preparable===!0)&&C.source!==c);return{ok:!1,reason:V?`${c} will not build calldata until the token approval exists on-chain. Approve first, then prepare again. Underlying: ${R}`:F?`${c} refused to build: ${R}. Quoting works for any address; preparing needs the real funded wallet on chain ${n}.`:`${c} bridge prepare failed: ${R}`,failureKind:V?"approval-required-first":F?"taker-not-funded":"provider-error",...D?{alternative:D.source}:{},comparison:i}}let b=h.transactions||[];if(!b.length)return{ok:!1,reason:`${c} returned no executable transaction for this route`,failureKind:"provider-error",comparison:i};let y=b.filter(w=>w.chainId==null||Number(w.chainId)!==Number(n));if(y.length)return{ok:!1,reason:`${c} returned a transaction for chain ${y[0].chainId??"missing"} but the origin chain is ${n}. Refusing to hand over a mismatched artifact.`,failureKind:"chain-mismatch",comparison:i};if(b.find(w=>!Y.test(String(w.from??""))||String(w.from).toLowerCase()!==r.toLowerCase()))return{ok:!1,reason:`${c} returned a transaction whose sender is not the exact wallet under review`,failureKind:"sender-mismatch",comparison:i};if(b.find(w=>!Y.test(String(w.to??""))))return{ok:!1,reason:`${c} returned an invalid transaction target`,failureKind:"destination-not-bound",comparison:i};if(b.find(w=>!Lr.test(String(w.data??""))))return{ok:!1,reason:`${c} returned incomplete unsigned calldata bytes`,failureKind:"provider-error",comparison:i};let _=h.requiresApproval??null,O=String(h.destination??"");if(!Y.test(O)||!b.some(w=>String(w.to).toLowerCase()===O.toLowerCase()))return{ok:!1,reason:`${c} returned no safely bound bridge deposit destination`,failureKind:"destination-not-bound",comparison:i};if(_){if(String(_.amount)!==String(e.amountIn))return{ok:!1,reason:`${c} approval amount does not equal the exact input amount`,failureKind:"approval-not-exact",comparison:i};if(!Y.test(String(_.token))||!Y.test(String(_.spender)))return{ok:!1,reason:`${c} returned an incomplete approval bound`,failureKind:"approval-not-exact",comparison:i}}let L=e.driftToleranceBps??ra,x=null,B=null;if(h.amountOut!=null&&f.grossOut!=null)try{let w=BigInt(f.grossOut),U=BigInt(h.amountOut);w>0n&&(x=Number((U-w)*10000n/w),x<-L&&(B=`route moved ${(x/100).toFixed(2)}% against you since the comparison (tolerance ${(L/100).toFixed(2)}%). Re-compare before signing.`))}catch{}let S=[...B?[B]:[],...i.warnings||[],`Bridging is NOT atomic: the origin transaction succeeding does not mean funds arrived on chain ${s}. Expect ~${h.durationSeconds!=null?`${h.durationSeconds}s`:"minutes"} before the destination credits, and do not re-send if it is pending.`];b.length>1&&S.push(`This route needs ${b.length} transactions signed IN ORDER. Signing only the first leaves funds approved but not bridged.`);let k=e.walletReviewOnly===!0?St(b):b,A=M({ok:!0,chosen:{source:c,wasWinner:c===d,netOut:f.netOut,grossOut:f.grossOut,gasUsd:f.gasUsd,feeUsd:f.feeUsd,feeCosts:Array.isArray(f.meta?.feeCosts)?f.meta.feeCosts:[],gasCosts:Array.isArray(f.meta?.gasCosts)?f.meta.gasCosts:[]},artifactKind:"unsigned-transaction-sequence",sender:r.toLowerCase(),fromChainId:Number(n),toChainId:Number(s),tokenIn:String(a),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:k,requiresApproval:_,amountOut:h.amountOut??null,minOut:h.minOut??null,durationSeconds:h.durationSeconds??null,slippageBps:i.slippageBps,routeOptions:i.routeOptions??[],winner:ve(i.best),quoteWinner:ve(i.best),coverage:i.coverage??null,comparisonComplete:i.comparisonComplete??null,complete:i.complete??null,destination:O,unsigned:!0,signedBy:"user-wallet",driftBps:x,warnings:S,runnersUp:i.routes.slice(1).map(ve),comparison:{rankedOn:i.rankedOn,sourcesAnswered:i.sourcesAnswered,sourcesTried:i.sourcesTried,improvementBps:i.improvementBps,winner:d,selectedForPreparation:c,complete:i.comparisonComplete??null},note:`UNSIGNED. ${b.length} transaction(s) on chain ${n}, crediting chain ${s}. Verify every destination address before signing.`},{provider:"router",kind:"best-bridge",env:t.env,nowMs:t.nowMs,expiresAtMs:t.expiresAtMs});if(e.walletReviewOnly===!0&&A.prepareMac){let{prepareMac:w,...U}=A;return U}return A}export{Bu as prepareBestBridgeRoute,Nu as supportedBridgePreparers};