@oracle-agent/oracle 0.35.40 → 0.35.42

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 (118) hide show
  1. package/dist/agent-sessions.mjs +17 -17
  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 +44 -44
  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 +31 -31
  12. package/dist/bin/oracle-scan.mjs +11 -11
  13. package/dist/bin/oracle.mjs +1 -1
  14. package/dist/cli/commands/agent-session.mjs +20 -20
  15. package/dist/cli/commands/airdrop.mjs +8 -8
  16. package/dist/cli/commands/auth.mjs +5 -5
  17. package/dist/cli/commands/chat.mjs +218 -217
  18. package/dist/cli/commands/doctor.mjs +9 -9
  19. package/dist/cli/commands/eval.mjs +204 -217
  20. package/dist/cli/commands/extension-policy.mjs +3 -3
  21. package/dist/cli/commands/farm.mjs +17 -17
  22. package/dist/cli/commands/follow.mjs +17 -17
  23. package/dist/cli/commands/harness.mjs +7 -7
  24. package/dist/cli/commands/mint.mjs +10 -10
  25. package/dist/cli/commands/model.mjs +222 -221
  26. package/dist/cli/commands/portfolio-risk.mjs +1 -1
  27. package/dist/cli/commands/project.mjs +7 -7
  28. package/dist/cli/commands/quickstart.mjs +6 -6
  29. package/dist/cli/commands/receipt.mjs +12 -12
  30. package/dist/cli/commands/resolve.mjs +7 -7
  31. package/dist/cli/commands/setup.mjs +13 -13
  32. package/dist/cli/commands/sign.mjs +4 -4
  33. package/dist/cli/commands/signer.mjs +14 -14
  34. package/dist/cli/commands/snipe.mjs +9 -9
  35. package/dist/cli/commands/strategy.mjs +4 -4
  36. package/dist/cli/commands/swap.mjs +14 -14
  37. package/dist/cli/commands/venues.mjs +2 -2
  38. package/dist/cli/project-access.mjs +3 -0
  39. package/dist/data/desk-data.mjs +26 -26
  40. package/dist/data/names.mjs +3 -3
  41. package/dist/data/providers/farming.mjs +2 -2
  42. package/dist/data/providers/lp-destination-discovery.mjs +4 -4
  43. package/dist/index.mjs +44 -44
  44. package/dist/investigator/index.mjs +2 -2
  45. package/dist/launch-radar/index.mjs +5 -5
  46. package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
  47. package/dist/local-signer/index.mjs +2 -2
  48. package/dist/local-signer/runtime.mjs +8 -8
  49. package/dist/nft/universal-mint-router.mjs +4 -4
  50. package/dist/notifications/index.mjs +8 -8
  51. package/dist/portfolio-risk.mjs +1 -1
  52. package/dist/router/index.mjs +3 -3
  53. package/dist/router/prepare-bridge.mjs +2 -2
  54. package/dist/router/prepare-route.mjs +3 -3
  55. package/dist/scanner/index.mjs +4 -4
  56. package/dist/strategy/index.mjs +3 -3
  57. package/dist/tui/standalone-client.mjs +86 -85
  58. package/package.json +5 -4
  59. package/public/eval-report.json +1 -1
  60. package/public/oracle-splash/_variants/ice.html +2 -4
  61. package/public/oracle-splash/_variants/ivory.html +2 -4
  62. package/public/oracle-splash/assets/fonts/LICENSE-Cormorant-Garamond.txt +93 -0
  63. package/public/oracle-splash/assets/fonts/LICENSE-IBM-Plex-Mono.txt +93 -0
  64. package/public/oracle-splash/assets/fonts/LICENSE-Outfit.txt +93 -0
  65. package/public/oracle-splash/assets/fonts/LICENSE-UnifrakturCook.txt +94 -0
  66. package/public/oracle-splash/assets/fonts/font-provenance.json +426 -0
  67. package/public/oracle-splash/assets/fonts/oracle-font-00.woff2 +0 -0
  68. package/public/oracle-splash/assets/fonts/oracle-font-01.woff2 +0 -0
  69. package/public/oracle-splash/assets/fonts/oracle-font-02.woff2 +0 -0
  70. package/public/oracle-splash/assets/fonts/oracle-font-03.woff2 +0 -0
  71. package/public/oracle-splash/assets/fonts/oracle-font-04.woff2 +0 -0
  72. package/public/oracle-splash/assets/fonts/oracle-font-05.woff2 +0 -0
  73. package/public/oracle-splash/assets/fonts/oracle-font-06.woff2 +0 -0
  74. package/public/oracle-splash/assets/fonts/oracle-font-07.woff2 +0 -0
  75. package/public/oracle-splash/assets/fonts/oracle-font-08.woff2 +0 -0
  76. package/public/oracle-splash/assets/fonts/oracle-font-09.woff2 +0 -0
  77. package/public/oracle-splash/assets/fonts/oracle-font-10.woff2 +0 -0
  78. package/public/oracle-splash/assets/fonts/oracle-font-11.woff2 +0 -0
  79. package/public/oracle-splash/assets/fonts/oracle-font-12.woff2 +0 -0
  80. package/public/oracle-splash/assets/fonts/oracle-font-13.woff2 +0 -0
  81. package/public/oracle-splash/assets/fonts/oracle-font-14.woff2 +0 -0
  82. package/public/oracle-splash/assets/fonts/oracle-font-15.woff2 +0 -0
  83. package/public/oracle-splash/assets/fonts/oracle-font-16.woff2 +0 -0
  84. package/public/oracle-splash/assets/fonts/oracle-font-17.woff2 +0 -0
  85. package/public/oracle-splash/assets/fonts/oracle-font-18.woff2 +0 -0
  86. package/public/oracle-splash/assets/fonts/oracle-font-19.woff2 +0 -0
  87. package/public/oracle-splash/assets/fonts/oracle-font-20.woff2 +0 -0
  88. package/public/oracle-splash/assets/fonts/oracle-font-21.woff2 +0 -0
  89. package/public/oracle-splash/assets/fonts/oracle-font-22.woff2 +0 -0
  90. package/public/oracle-splash/assets/fonts/oracle-font-23.woff2 +0 -0
  91. package/public/oracle-splash/assets/fonts/oracle-font-24.woff2 +0 -0
  92. package/public/oracle-splash/assets/fonts/oracle-font-25.woff2 +0 -0
  93. package/public/oracle-splash/assets/fonts/oracle-font-26.woff2 +0 -0
  94. package/public/oracle-splash/assets/fonts/oracle-font-27.woff2 +0 -0
  95. package/public/oracle-splash/assets/fonts/oracle-fonts.css +504 -0
  96. package/public/oracle-splash/assets/transport-probe-sw.js +2 -0
  97. package/public/oracle-splash/docs/browser-and-web/index.html +6 -6
  98. package/public/oracle-splash/docs/connectors/index.html +5 -5
  99. package/public/oracle-splash/docs/docs.css +4 -4
  100. package/public/oracle-splash/docs/docs.js +119 -7
  101. package/public/oracle-splash/docs/getting-started/index.html +5 -5
  102. package/public/oracle-splash/docs/index.html +6 -6
  103. package/public/oracle-splash/docs/reference/index.html +5 -5
  104. package/public/oracle-splash/docs/security/index.html +5 -5
  105. package/public/oracle-splash/docs/using-oracle/index.html +5 -5
  106. package/public/oracle-splash/download/index.html +8 -10
  107. package/public/oracle-splash/downloads/index.html +3 -5
  108. package/public/oracle-splash/eval/archive/oracle-0.35.40.json +101 -0
  109. package/public/oracle-splash/eval/archive/oracle-0.35.41-blocked-attempt.json +672 -0
  110. package/public/oracle-splash/eval/index.html +104 -0
  111. package/public/oracle-splash/eval/releases/oracle-0.35.41.json +788 -0
  112. package/public/oracle-splash/index.html +16 -18
  113. package/public/oracle-splash/mesh-graph.svg +1 -1
  114. package/public/oracle-splash/pricing/index.html +6 -8
  115. package/public/oracle-splash/security/index.html +3 -5
  116. package/public/oracle-splash/what-it-does/index.html +4 -6
  117. package/public/oracle-splash/where-it-works/index.html +3 -5
  118. package/server.json +2 -2
@@ -1,2 +1,2 @@
1
- var Pr=Object.defineProperty;var z=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Pe=(e,t)=>{for(var r in t)Pr(e,r,{get:t[r],enumerable:!0})};import se from"node:net";import Lr from"node:dns";function xe(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 De(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 Fe(e){if(se.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(se.isIPv6(e)){let t=xe(e);if(!t)return!1;let r=xe("::ffff:0:0");return De(t,r,96)?Fe([...t.slice(12)].join(".")):De(t,xe("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([s,a])=>De(t,xe(s),a)):!1}return!1}function Dr(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($r.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=se.isIP(r);return n!==0&&!Fe(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function qe(e,{lookupFn:t=Lr.promises.lookup}={}){let r=Dr(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:se.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=>!Fe(s.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function Me({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||(se.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(se.isIP(f))return[{address:f,family:se.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=Fr((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 Fr(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[He]=Object.freeze({pin:t}),e}function je(e){return typeof e=="function"&&typeof e[He]?.pin=="function"}function Et(e,t,r){if(!je(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[He].pin(t,r)}var $r,He,xt=z(()=>{$r=new Set(["localhost","metadata.google.internal","metadata.goog"]);He=Symbol.for("oracle.egressGuard.pinCapableFetch")});import{createHash as qr}from"node:crypto";import{types as ee}from"node:util";function P(e){return re(`HTTP JSON body refused: ${e}`)}function Qr(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 Yr(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(Qr(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 x=0;x<u.length;x+=1){let g=Object.getOwnPropertyDescriptor(u,String(x));if(!g||!Object.hasOwn(g,"value")||g.enumerable!==!0)throw P("array entries must be dense enumerable own data")}let S=0;for(let x in u){if(a+=1,a>Z.fields)throw P("enumeration limit exceeded");if(Object.hasOwn(u,x)&&(S+=1,S>u.length))throw P("named array fields are unsupported")}if(S!==u.length)throw P("array entries must be dense enumerable own data");l("[");for(let x=0;x<u.length;x+=1)x&&l(","),d(Object.getOwnPropertyDescriptor(u,String(x)).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 Xr(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 Jr(){return Object.assign(Object.create(null),{Accept:"application/json"})}function Zr(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 en(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function ve(e){if((typeof e!="object"||e===null)&&typeof e!="function")return`${typeof e}:${String(e)}`;let t=kt.get(e);return t||(t=Ot,Ot+=1,kt.set(e,t)),`reference:${t}`}function Tt(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?tn.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 Nt(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(Tt);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return Tt(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&rn.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function nn(e,t,r,n={},s=null){let a=qr("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 on(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 re(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function ze(e,t,r){return re(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function ie(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function sn(e){return e?e.byteLength??e.length??0:0}async function cn(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&&(ie(e),!n))throw ze(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 ze(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+=sn(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 ze(r,`streamed ${i} bytes`,t);let u=Buffer.concat(l);return(d?u.subarray(0,t):u).toString("utf8")}function un(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function ln(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=Ce}){let S=new AbortController,x=setTimeout(()=>S.abort(),a),g=m?It?It([m,S.signal]):m:S.signal,E=null,T=t,k=o?{lookupFn:o}:{};if(i&&!l&&!je(T))throw re(`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 L=async(v,{status:R=null}={})=>{let y=await qe(v,k);if(!y.ok)throw re(R==null?`HTTP refused ${v}: ${y.error}`:`HTTP redirect to ${v} ${y.error}`,R==null?{}:{status:R});let O=new URL(v).hostname;if(l){if(E&&(await E.close(),E=null),!E)try{E=await Me({requireUndici:!0,...c?{importUndici:c}:{}})}catch(A){throw re(R==null?`HTTP refused ${v}: ${A?.message||A}`:`HTTP redirect to ${v} refused: ${A?.message||A}`,R==null?{}:{status:R})}E.pin(O,y.addresses),T=E.fetch}else Et(T,O,y.addresses);return y};try{let v=String(e),R=Object.assign(Object.create(null),n||{});i&&await L(v);for(let y=0;y<=b;y+=1){let O=Object.assign(Object.create(null),{method:r,headers:R,body:s,signal:g,redirect:"manual",dispatcher:void 0}),A=await T(v,O);if((h==="error"||b===0)&&A.status>=300&&A.status<400)throw ie(A),re(`HTTP ${A.status} ${r} redirect refused`,{status:A.status,redirectRefused:!0});if(Wr.has(A.status)){let _=u===!0&&r==="POST"&&[307,308].includes(A.status)&&Nt(r,s);if(r!=="GET"&&r!=="HEAD"&&!_){ie(A);let I=new Error(`HTTP ${A.status} ${r} ${v} redirected non-idempotent request`);throw I.status=A.status,I}if(y===b)throw ie(A),re(`HTTP ${A.status} ${r} redirect budget exhausted`,{status:A.status,redirectRefused:!0});let V=A.headers?.get?.("location"),q;try{q=Zr(V,v)}catch(I){throw ie(A),I}let D=!en(q,v);if(ie(A),D&&r==="POST"){let I=new Error(`HTTP ${A.status} ${r} cross-origin redirect refused`);throw I.status=A.status,I}if(D&&u){let I=new Error(`HTTP ${A.status} ${r} cross-origin redirect refused`);throw I.status=A.status,I.retryable=!1,I}if(D&&(R=Jr(R)),i)await L(q,{status:A.status});else if(D){let I=await qe(q,k);if(!I.ok){let N=new Error(`HTTP redirect from ${v} ${I.error}`);throw N.status=A.status,N.retryable=!1,N}l&&I.addresses?.length&&(E||(E=await Me(c?{importUndici:c}:{})),E&&(E.pin(new URL(q).hostname,I.addresses),T=E.fetch))}v=q;continue}if(typeof f=="function")try{await f(A,{url:v})}catch(_){throw ie(A),re(_?.message||String(_))}let w=await cn(A,d,{url:v,onOversize:()=>S.abort()}),U=un(w);if(!A.ok){let _=new Error(`HTTP ${A.status} ${r} ${v}`);throw _.status=A.status,_.retryAfter=A.headers?.get?.("retry-after")??null,_.body=U??w.slice(0,300),_}return U??w}throw new Error(`HTTP redirect loop for ${e}`)}catch(v){if(S.signal.aborted&&!Ke(m)){let R=v&&(typeof v=="object"||typeof v=="function")&&!ee.isProxy(v)?v:null,y=R?Object.getOwnPropertyDescriptor(R,"oversize"):null;if(!(y&&Object.hasOwn(y,"value")&&y.value===!0))try{if(!R)throw new TypeError("unsafe rejection");Object.defineProperties(R,{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 v}finally{clearTimeout(x),E&&await E.close()}}async function C(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 N of Object.getOwnPropertyNames(t)){let B=Object.getOwnPropertyDescriptor(t,N);if(!(N==="toJSON"&&B&&Object.hasOwn(B,"value")&&B.value===void 0)){if(!r.has(N))throw new TypeError("HTTP options contain unknown fields");if(!B||!B.enumerable||!Object.hasOwn(B,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=N=>{if(t==null||!Object.hasOwn(t,N))return;let B=Object.getOwnPropertyDescriptor(t,N);if(!B||!Object.hasOwn(B,"value"))throw new TypeError("HTTP options must contain own data properties");return B.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>Ce))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${Ce}`);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??Ce;for(let N of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let B=n(N);if(B!==void 0&&typeof B!="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(ee.isProxy(f)||!(f instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{Ke(f)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let N of["importUndici","lookupFn","validateResponse"]){let B=n(N);if(B!==void 0&&typeof B!="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,S=(s||"GET").toUpperCase(),x=n("headers"),g=Xr(x),E=Object.assign(Object.create(null),g);Object.keys(E).some(N=>N.toLowerCase()==="accept")||(E.Accept="application/json");let T=n("body");T!=null&&typeof T!="string"&&(Object.keys(E).find(B=>B.toLowerCase()==="content-type")||(E["Content-Type"]="application/json"),T=Yr(T));let k=o??Hr,L=n("lookupFn"),v=!m,R=n("untrustedUrl")===!0,y=n("sameOriginRedirectsOnly")===!0,O=n("importUndici"),A=n("validateResponse"),w=f,U=c??null,_=async()=>{let N;for(let B=0;B<=k;B++){w&&zr.call(w);try{return await ln(e,{fetchImpl:h,method:S,headers:E,body:T,timeoutMs:b,lookupFn:L,realFetch:v,untrustedUrl:R,maxResponseBytes:U,sameOriginRedirectsOnly:y,importUndici:O,validateResponse:A,signal:w,redirectPolicy:d,maxRedirects:u})}catch(F){N=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},ce=X("status"),Ae=X("oracleTimeout")===!0||X("name")==="AbortError"||X("name")==="TimeoutError"||Ke(w),Se=new Set([408,425,429]),Ee=X("retryable")===!1?!1:ce!=null?Se.has(ce)||Mr.has(ce)&&vt.has(S):!Ae&&vt.has(S);if(B===k||!Ee)throw F;let p=on(B,X("retryAfter"));w?await new Promise((M,H)=>{let G=setTimeout(M,p);Kr.call(w,"abort",()=>{clearTimeout(G),H(Gr(w)||new DOMException("Aborted","AbortError"))},{once:!0})}):await an(p)}}throw N};if(!(n("dedupe")!==!1&&!w&&Nt(S,T)))return _();let q=nn(S,e,E,{untrustedUrl:R,maxResponseBytes:U,sameOriginRedirectsOnly:y,redirectPolicy:d,maxRedirects:u,timeoutMs:b,retries:k,fetchImpl:ve(h),realFetch:v,lookupFn:ve(L),importUndici:ve(O),validateResponse:ve(A)},T),D=Ve.get(q);if(D)return D;let I=_().finally(()=>Ve.delete(q));return Ve.set(q,I),I}var Mr,vt,Hr,Ct,jr,Vr,zr,Kr,It,Ke,Gr,Wr,Ce,pa,Z,Ve,kt,Ot,tn,rn,an,$=z(()=>{xt();Mr=new Set([408,425,429,500,502,503,504]),vt=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Hr=2,Ct=4e3,jr=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Vr=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,zr=AbortSignal.prototype.throwIfAborted,Kr=EventTarget.prototype.addEventListener,It=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,Ke=e=>e?jr.call(e):!1,Gr=e=>e?Vr.call(e):void 0,Wr=new Set([301,302,303,307,308]),Ce=3,pa=64*1024,Z=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});Ve=new Map,kt=new WeakMap,Ot=1;tn=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),rn=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);an=e=>new Promise(t=>setTimeout(t,e))});import{readFileSync as dn}from"node:fs";import{homedir as pn}from"node:os";import{join as Ie}from"node:path";function fn(){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=pn();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||Ie(t,".config","oracle")).trim();return[e,Ie(r,"exec.env")].filter(Boolean)}return[e,Ie(t,".config","oracle","exec.env"),Ie(t,".config","mad-desk","exec.env")].filter(Boolean)}function Bt(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let s of fn())try{let a=dn(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 Rt=z(()=>{});var _t=z(()=>{});import{createHash as mn,createHmac as Pt,timingSafeEqual as hn}from"node:crypto";function Oe(e){return Array.isArray(e)?`[${e.map(Oe).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Oe(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Lt(e,{required:t=!1}={}){try{return Bt(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function We(e){let{signature:t,...r}=e;return r}function $t(e,{secret:t}={}){let r=Lt(t);return r?{...e,signature:Pt("sha256",r).update(Oe(We(e))).digest("hex")}:e}function gn(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 mn("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function ne(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=Lt(s);if(a){let m=Pt("sha256",a).update(Oe(We(e))).digest("hex");if(!bn(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>ke||!Number.isInteger(l)||l<0||l>ke||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=An(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 $t({...We(e),calldataHash:gn(n)},{secret:s})}function bn(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:hn(r,n)}function Ge(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function wn(e){let t=e==null?ke: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,ke)}function oe({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:s}={}){let a=Ge(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(Ge(t,0))*2),i=Math.min(40,Math.floor(Math.max(0,Ge(r,0))/5e3)*5),d=Math.max(25,Math.ceil(20+o+l+i)),u=wn(s);return{mode:"auto",requiredBps:d,selectedBps:Math.min(d,u),capBps:u,executable:d<=u}}function yn({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=Ut,secret:u}={}){let c=BigInt(r??0);if(c<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let f=oe({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)||Ut)),b=c*BigInt(1e4-f.selectedBps),S=b/10000n;if(b%10000n!==0n&&(S+=1n),S>c&&(S=c),c>0n&&S<=0n)throw new Error(`auto-slippage: quote ${c} is too small to express a ${f.selectedBps} bps floor without rounding to zero`);let x=Number((c-S)*10000n/(c===0n?1n:c));if(x>f.capBps)throw new Error(`auto-slippage: realised floor implies ${x} bps, above cap ${f.capBps} \u2014 refusing to issue a guard weaker than advertised`);return $t({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:c.toString(),minAmountOut:S.toString(),requiredBps:f.requiredBps,selectedBps:f.selectedBps,capBps:f.capBps,quotedAtMs:m,expiresAtMs:m+h},{secret:u})}function An(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=yn({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 ke,Ut,te=z(()=>{Rt();_t();ke=100,Ut=2e4});var ue,Te=z(()=>{ue="0x000000000000000000000000000000000000dEaD"});import{createHash as Sn,createHmac as En,timingSafeEqual as Ia}from"node:crypto";function Qe(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Qe).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Qe(e[r])}`).join(",")}}`}function Dt(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Ft(e=process.env){return Dt(process.env)||Dt(e)}function In(e){let{prepareHash:t,prepareMac:r,note:n,...s}=e||{};return s}function kn(e){let t=In(e);return Sn("sha256").update(Qe(t)).digest("hex")}function On(e,t=Ft()){return t?En("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+vn:Number(a),u=d-i;if(!Number.isSafeInteger(i)||!Number.isSafeInteger(d)||u<=0||u>Cn)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let f={...l,preparedAt:i,expiresAt:d,prepareVersion:xn},m=kn(f),h=Ft(n),b=h?On(m,h):void 0,S={...f,prepareHash:m};return b&&(S.prepareMac=b),S}var xn,vn,Cn,Q=z(()=>{xn=2,vn=300*1e3,Cn=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Contract as Tn,JsonRpcProvider as Nn}from"ethers";function Ln(e){return Pn.test(String(e||""))}async function qt(e,{contract:t=Bn,rpc:r=_n,chainId:n=Rn,balanceOf:s}={}){if(!Ln(e))throw new Error("invalid-address");if(s)return BigInt(await s(e));let a=new Nn(r,n,{staticNetwork:!0}),o=new Tn(t,Un,a);return BigInt(await o.balanceOf(e))}var Bn,Rn,_n,Un,Pn,Mt=z(()=>{Bn="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",Rn=999,_n="https://rpc.hyperliquid.xyz/evm",Un=["function balanceOf(address owner) view returns (uint256)"],Pn=/^0x[a-fA-F0-9]{40}$/});import{existsSync as $n,readFileSync as Dn,lstatSync as Fn}from"node:fs";import{homedir as Ht}from"node:os";import{join as Ye}from"node:path";function Hn(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(jt,t)?jt[t]:Mn}function Gn(e=process.env){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){if(e[Vt])return String(e[Vt]);let t=e.ORACLE_CONFIG_DIR||Ye(Ht(),".config","oracle");return Ye(t,"fee-recipient")}return Ye(Ht(),".config","oracle","fee-recipient")}function Wn(e=process.env){try{let t=Gn(e);if(!$n(t)||Fn(t).isSymbolicLink())return"";let r=Dn(t,"utf8").trim().toLowerCase();return/^0x[a-f0-9]{40}$/.test(r)?r:""}catch{return""}}function Qn(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),qn)}function Yn({env:e=process.env,action:t="swap",admin:r=!1}={}){let n=String(e[Vn]||"").trim(),s=String(e[zn]||Kn).trim();if(r===!0)return{bps:0,recipient:"",integrator:s,action:t,applies:!1,reason:"admin-oracle"};let a=Hn(t),o=Qn(e[jn],{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=Wn(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 Xe({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={},admin:s=!1}={}){let a=Yn({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 qt(o,n))>0n?{...a,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...a,holderVerificationStatus:"non-holder"}}catch{return{...a,holderVerificationStatus:"unavailable"}}}function zt(e){return e?.applies?`Oracle routing fee ${e.bps} bps (${(e.bps/100).toFixed(2)}%) to ${e.recipient}.`:e?.reason==="admin-oracle"?"No Oracle fee (admin Oracle).":e?.reason==="locals-only-holder"?"No Oracle fee (Locals Only holder).":"No Oracle fee."}function Kt(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}var qn,Mn,jt,jn,Vn,zn,Vt,Kn,Ne=z(()=>{Mt();qn=100,Mn=5,jt=Object.freeze({swap:5,bridge:5,perps:0,nft:0});jn="ORACLE_INTEGRATOR_FEE_BPS",Vn="ORACLE_INTEGRATOR_FEE_RECIPIENT",zn="ORACLE_INTEGRATOR_ID",Vt="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",Kn="oracle"});var Wt={};Pe(Wt,{LIFI_API:()=>Gt,lifiChains:()=>eo,lifiHealth:()=>et,lifiPrepare:()=>Zn,lifiQuote:()=>de});function Ze(e={}){return(e.baseUrl||process.env.LIFI_API_URL||Gt).replace(/\/$/,"")}function Jn(e){let t=String(e||Je).toLowerCase();return t===Je.toLowerCase()||t===Xn}function le(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 et(e={}){let t=await C(`${Ze(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 de(e={},t={}){let{fromChain:r,toChain:n=r,fromToken:s=Je,toToken:a,fromAmount:o,fromAddress:l=ue}=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=oe({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 Xe({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[S,x]of Object.entries(Kt(u)))i.set(S,x);let c=await C(`${Ze(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 Zn(e={},t={}){let r=await de(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?le(e.fromAddress,"transaction sender"):n.from?le(n.from,"transaction sender"):null;if(!o)throw new Error("lifi: transaction missing sender authority");if(n.from&&le(n.from,"transaction sender")!==o)throw new Error("lifi: transaction sender mismatch");let l=le(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(!Jn(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:le(f,"approval token"),spender:le(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:ne(r.autoSlippage,{chainId:a,venue:l,data:i})}},{provider:"lifi",kind:"lifi-tx",env:t.env,nowMs:t.nowMs,expiresAtMs:t.expiresAtMs})}async function eo(e={}){return C(`${Ze(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var Gt,Je,Xn,Be=z(()=>{$();te();Te();Q();Ne();Gt="https://li.quest/v1";Je="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",Xn="0x0000000000000000000000000000000000000000"});var Ue={};Pe(Ue,{ACROSS_API:()=>Jt,HOP_API:()=>Zt,RANGO_API:()=>tr,RELAY_API:()=>er,acrossHealth:()=>nt,acrossSuggestedFees:()=>Re,hopHealth:()=>ot,hopQuote:()=>_e,rangoQuote:()=>it,relayHealth:()=>st,relayPrepare:()=>go,relayQuote:()=>ge});async function nt(e={}){try{return{ok:!0,estimatedFillTimeSec:(await Re({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 Re(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||Jt).replace(/\/$/,"");return C(`${i}/suggested-fees?${l}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function ot(e={}){try{let t=await _e({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 _e(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=oe({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||Zt).replace(/\/$/,""),u=await C(`${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||po[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 rr(e){return(e?.steps||[]).flatMap(t=>(t?.items||[]).filter(r=>r?.data?.to&&r?.data?.data).map(r=>({stepId:t.id,...r.data})))}function mo(e){let t=String(e?.data??"").toLowerCase();if(!t.startsWith(at))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 ho(e){return rr(e).find(t=>!String(t.data).toLowerCase().startsWith(at))??null}async function st(e={}){try{let t=await ge({user:ue,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 ge(e={},t={}){let{user:r=ue,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=oe({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||er).replace(/\/$/,""),c=await C(`${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=ho(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 go(e={},t={}){let r=await ge(e,t),n=Number(e.originChainId),s=rr(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=mo(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===fo)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(at)?{}:{slippageGuard:ne(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 it({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||tr).replace(/\/$/,""),u;try{u=await C(`${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 Jt,Zt,er,tr,po,at,fo,be=z(()=>{$();te();Te();Q();Jt="https://across.to/api",Zt="https://api.hop.exchange/v1",er="https://api.relay.link",tr="https://api.rango.exchange",po={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453};at="0x095ea7b3",fo="0x0000000000000000000000000000000000000000"});var dr={};Pe(dr,{DEBRIDGE_API:()=>ur,debridgeHealth:()=>lt,debridgePrepare:()=>ko,debridgeQuote:()=>ut});function lr(e={}){return(e.baseUrl||process.env.DEBRIDGE_API_URL||ur).replace(/\/$/,"")}function ct(e,t=200){return String(e?.message||e||"unknown error").slice(0,t)}function Io(e){return typeof e?.to=="string"&&e.to.length>0&&/^0x(?:[0-9a-fA-F]{2})+$/.test(String(e.data||""))}async function ut({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 C(`${lr(i)}/dln/order/create-tx?${d}`,{fetchImpl:i.fetchImpl,timeoutMs:i.timeoutMs??2e4,retries:i.retries,headers:i.headers});return u?.error?{error:ct(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:ct(d)}}}async function lt(e={}){try{let t=await C(`${lr(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:ct(t,160)}}}async function ko(e,{taker:t}={}){if(!t)throw new Error("debridge prepare requires taker address");if(!Io(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 ur,dt=z(()=>{$();Q();ur="https://dln.debridge.finance/v1.0"});var ta=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),Le=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),$e=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(y=>y.quality!==J.FAILED),i=e.filter(y=>y.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(y=>{let O=BigInt(y.amountOut),A=0n,w=!1,U=!1,_=BigInt(y.oracleFeeBps??0),V=_>0n?O*_/10000n:0n;if(d){let I=y.gasUsd,N=Number(y.meta?.gasUnits??y.estimatedGas);if(I==null&&f&&Number.isFinite(N)&&N>0){let F=N*u/1e18*c;Number.isFinite(F)&&F>=0&&(I=F,U=!0)}let B=(I??0)+(y.feeIncludedInAmountOut?0:y.feeUsd??0);if(B>0){let F=B/t*10**r;Number.isFinite(F)&&F>=0&&(A=BigInt(Math.floor(F)),w=!0)}else I===0&&(w=!0)}let q=A+V,D=O>q?O-q:0n;return{...y,grossOut:O.toString(),netOut:D.toString(),costInDest:A.toString(),oracleFeeInDest:V.toString(),costAccounted:w,gasEstimated:U}}),h=Number(s)>0?Number(s):0,b=m.reduce((y,O)=>BigInt(O.netOut)>y?BigInt(O.netOut):y,0n),S=y=>b>0n?Number((b-BigInt(y))*10000n/b):0,x=[],g=(y,O)=>{let A=BigInt(y.netOut),w=BigInt(O.netOut);return A!==w?w>A?1:-1:String(y.source).localeCompare(String(O.source))},E=m.slice().sort(g)[0]??null;m.sort((y,O)=>{let A=S(y.netOut)<=h?0:1,w=S(O.netOut)<=h?0:1;if(n&&h>0&&A!==w)return A-w;if(n&&h>0){let U=y.liquidityUsd??-1,_=O.liquidityUsd??-1;if(U!==_)return _-U}return g(y,O)}),n&&h>0&&E&&m[0]&&m[0].source!==E.source&&x.push(`liquidity-first: chose ${m[0].source} (liquidity $${m[0].liquidityUsd??"unknown"}) over best-price ${E.source} within ${h} bps`);let T=m.filter(y=>!y.costAccounted).map(y=>y.source);d?T.length&&x.push(`gas not reported by: ${T.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):x.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let k=m[0];if(d&&k&&k.costAccounted===!1){let y=m.find(O=>O.costAccounted&&S(O.netOut)<=h);y&&x.push(`winner ${k.source} has UNMEASURED gas; gas-measured ${y.source} is within ${h} bps and may net more once ${k.source}'s real gas is paid \u2014 prefer it if unsure.`)}let L=m.filter(y=>y.gasEstimated).map(y=>y.source);L.length&&x.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 v=null,R=null;if(m.length>=2&&m[0].costAccounted&&m[1].costAccounted){let y=BigInt(m[0].netOut),O=BigInt(m[1].netOut);O>0n&&(v=Number((y-O)*10000n/O),R=`${m[0].source} vs ${m[1].source}`)}return{best:m[0]??null,routes:m,failed:i,improvementBps:v,spreadBasis:R,rankedOn:d?"net-of-cost":"gross",warnings:x}}async function St(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})})}Be();$();te();Q();Ne();$();te();Q();$();te();Q();$();te();import{TypedDataEncoder as cs,getAddress as us,isAddress as ls}from"ethers";var ns=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});Te();Q();var bs=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),ws=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"});var ys=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"}]}),As=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]});import{Interface as Yt,getAddress as Fs,isAddress as qs}from"ethers";$();var Qt={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}},Es=new Map(Object.values(Qt).map(e=>[e.chainId,e]));import{Interface as no,getAddress as Ns}from"ethers";var Bs=new no(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);$();var Ls=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});te();Q();var zs=new Yt(["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)"]),Ks=new Yt(["function exactInputSingle((address tokenIn,address tokenOut,uint24 fee,address recipient,uint256 amountIn,uint256 amountOutMinimum,uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)","function multicall(uint256 deadline,bytes[] data) payable returns (bytes[] results)"]);import{AbiCoder as so,Interface as tt,getAddress as Ys,isAddress as Xs,keccak256 as Js}from"ethers";te();Q();var ni=so.defaultAbiCoder();var oi=new tt(["function quoteExactInputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactOutputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountIn, uint256 gasEstimate)"]),ai=new tt(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),si=new tt(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96,int24 tick,uint24 protocolFee,uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),ii=Object.freeze([[13,"beforeInitialize"],[12,"afterInitialize"],[11,"beforeAddLiquidity"],[10,"afterAddLiquidity"],[9,"beforeRemoveLiquidity"],[8,"afterRemoveLiquidity"],[7,"beforeSwap"],[6,"afterSwap"],[5,"beforeDonate"],[4,"afterDonate"],[3,"beforeSwapReturnsDelta"],[2,"afterSwapReturnsDelta"],[1,"afterAddLiquidityReturnsDelta"],[0,"afterRemoveLiquidityReturnsDelta"]]),ci=(1n<<14n)-1n;$();var io="https://coins.llama.fi",co="https://api.llama.fi";function uo(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||io).replace(/\/$/,"")}function lo(e={}){return(e.baseUrl||process.env.DEFILLAMA_API_URL||co).replace(/\/$/,"")}async function rt(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return C(`${uo(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function Xt(e={}){return C(`${lo(e)}/protocols`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??2e4})}var K=e=>{let t=Number(e);return Number.isFinite(t)?t:null};function nr(e){if(!Array.isArray(e))return null;let t=0,r=!1;for(let n of e){let s=K(n?.amountUSD);s!=null&&(t+=s,r=!0)}return r?t:null}function or(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 ae=e=>String(e??"").toLowerCase().replace(/[^a-z0-9]/g,""),ar=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 bo(e={}){try{let t=await Xt({...e,baseUrl:e.defillamaApiBaseUrl,timeoutMs:e.defillamaTimeoutMs??Math.min(Number(e.timeoutMs??5e3),5e3)});return Array.isArray(t)?t:[]}catch{return[]}}function wo(e,t={}){let r=ae(t.tool||t.provider||t.bridge||t.protocol),n=[];return e==="lifi"&&r&&r!=="lifi"&&n.push(...ar[r]||[r]),n.push(...ar[ae(e)]||[e]),n}function yo(e,t,r={}){let n=Array.isArray(e)?e:[],s=wo(t,r).map(ae).filter(Boolean);for(let a of s){let o=n.find(i=>ae(i?.slug)===a||ae(i?.name)===a),l=K(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=ae(i?.category);return!d.includes("bridge")&&!d.includes("crosschain")?!1:ae(i?.slug).includes(a)||ae(i?.name).includes(a)}),l=K(o?.tvl);if(l!=null)return{liquidityUsd:l,protocol:o?.name??o?.slug??a}}return null}function sr({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||=bo(i),yo(await u,m,h));if(d.push({source:"lifi",run:async()=>{let m=await de({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,E)=>({id:String(g?.id??`step-${E+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)})),S={tool:m?.tool??m?.toolDetails?.name,durationSeconds:K(h?.executionDuration),destinationDecimals:K(m?.action?.toToken?.decimals),routeSteps:b,feeCosts:or(h?.feeCosts),gasCosts:or(h?.gasCosts)},x=await c("lifi",S);return{amountOut:h?.toAmount,minOut:h?.toAmountMin,gasUsd:nr(h?.gasCosts),feeUsd:nr(h?.feeCosts),feeIncludedInAmountOut:!0,oracleFeeBps:m?.oracleFee?.applies?m.oracleFee.bps:0,liquidityUsd:x?.liquidityUsd??null,meta:{...S,liquidityProtocol:x?.protocol,oracleFee:m?.oracleFee??null}}}}),d.push({source:"relay",run:async()=>{let{relayQuote:m}=await Promise.resolve().then(()=>(be(),Ue)),h=await m({user:a,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(s),slippageBps:o},i),b=h?.details,S=(h?.steps??[]).map((L,v)=>({id:String(L?.id??`step-${v+1}`),type:String(L?.kind??"transaction"),tool:"Relay",label:String(L?.description??L?.action??L?.id??`Step ${v+1}`),fromChainId:Number(e),toChainId:Number(t)})),x=String(h?.fees?.relayer?.amountUsd??"").trim(),g=String(h?.fees?.gas?.amountUsd??"").trim(),E=String(b?.totalImpact?.usd??"").trim(),T={durationSeconds:K(b?.timeEstimate),rate:b?.rate,destinationDecimals:K(b?.currencyOut?.currency?.decimals),routeSteps:S,feeCosts:[.../^\d+(?:\.\d+)?$/.test(x)?[{name:"relayer",amountUsd:x}]:[],.../^-?\d+(?:\.\d+)?$/.test(E)?[{name:"total-impact",amountUsd:E}]:[]],gasCosts:/^\d+(?:\.\d+)?$/.test(g)?[{name:"origin-gas",amountUsd:g}]:[]},k=await c("relay",T);return{amountOut:b?.currencyOut?.amount,minOut:b?.currencyOut?.minimumAmount,gasUsd:K(h?.fees?.gas?.amountUsd),feeUsd:K(h?.fees?.relayer?.amountUsd)??(K(b?.totalImpact?.usd)!=null?Math.abs(K(b.totalImpact.usd)):null),feeIncludedInAmountOut:!0,liquidityUsd:k?.liquidityUsd??null,meta:{...T,liquidityProtocol:k?.protocol}}}}),d.push({source:"across",run:async()=>{let{acrossSuggestedFees:m}=await Promise.resolve().then(()=>(be(),Ue)),h=await m({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(s)},i),b=h?.totalRelayFee?.total,S=null;if(b!=null)try{let g=BigInt(String(s))-BigInt(String(b));g>0n&&(S=g.toString())}catch{}let x=await c("across");return{amountOut:S,gasUsd:null,liquidityUsd:x?.liquidityUsd??null,meta:{derivedFromFees:!0,durationSeconds:K(h?.estimatedFillTimeSec),limits:h?.limits?{min:h.limits.minDeposit,max:h.limits.maxDeposit}:void 0,liquidityProtocol:x?.protocol}}}}),!Array.isArray(l))return d;let f=new Set(l.map(m=>String(m).toLowerCase()));return d.filter(m=>f.has(m.source))}Ne();var Ao={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"},ir=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 Eo(e,t=ir){let r=new Set((Array.isArray(t)?t:ir).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 xo(e,t,r){let n=Ao[Number(e)];if(!n)return{priceUsd:null,decimals:null};let s=`${n}:${t}`;try{let o=(await rt([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 cr(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=xo(n,a,t),u=sr({...i,opts:t}),[c,f]=await Promise.all([St(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:Eo(m,e.allowedSources),durations:h,sourcesTried:u.length,sourcesAnswered:c.filter(b=>b.quality!==J.FAILED).length,note:Co(m,u.length)}}function vo(e){let t=e?.meta?.oracleFee;return t?.applies?` \xB7 ${zt(t)}`:""}function Co(e,t){if(!e.best)return"no source returned a usable route";let r=e.routes.length,n=vo(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();Be();dt();$();var pt="https://api.changenow.io/v2",pe=new Map,pr=0,Oo=6e5;async function To({active:e=!0}={},t={}){let r=Date.now();if(pe.size&&r-pr<Oo)return[...pe.values()];try{let n=await C(`${pt}/exchange/currencies?active=${e?"true":"false"}`,t);pe.clear();for(let s of n??[])pe.set(String(s.ticker).toLowerCase(),s);return pr=r,n??[]}catch(n){return pe.size?[...pe.values()]:{error:String(n.message||n).slice(0,200)}}}async function No(e,t,r={}){if(!e||!t)return{error:"changenow minAmount requires fromTicker and toTicker"};try{return{minAmount:(await C(`${pt}/exchange/min-amount/${encodeURIComponent(e)}_${encodeURIComponent(t)}`,r))?.minAmount??"0"}}catch(n){return{error:String(n.message||n).slice(0,200)}}}async function Bo(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 C(`${pt}/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 fr({fromTicker:e,toTicker:t,fromAmount:r,flow:n}={},s={}){if(!e||!t)return{error:"changenow quote requires fromTicker and toTicker"};let a=await No(e,t,s);if(a.error)return a;let o=r??a.minAmount,l=await Bo(e,t,o,{flow:n},s);if(l.error)return l;let i=await To({},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 Ro="https://api.squidrouter.com/v1";async function mr({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 C(`${Ro}/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 _o="https://api.stargate.finance";async function hr({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 C(`${_o}/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 gr="https://midgard.ninerealms.com/v2";async function br({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 C(`${gr}/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 wr(){try{return{ok:(await C(`${gr}/health`))?.scannerHeight>0}}catch(e){return{ok:!1,error:String(e.message||e).slice(0,160)}}}$();var Uo="https://api.socket.tech/v2";async function yr({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 C(`${Uo}/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 Po="https://api.connext.network";async function Ar({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 C(`${Po}/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 Lo="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 C(`${Lo}/quote?${a}`,s);return{amountOut:o?.amountOut,fee:o?.fee,estimatedTime:o?.estimatedTime}}catch(a){return{error:String(a.message||a).slice(0,200)}}}be();import{Interface as Er,getAddress as Lc,id as xr}from"ethers";$();var Fo=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 qc=new Er(["function decimals() view returns (uint8)","function symbol() view returns (string)"]),Mc=new Er(["function isApprovedForAll(address owner, address operator) view returns (bool)","function name() view returns (string)"]),Hc=xr("Approval(address,address,uint256)"),jc=xr("ApprovalForAll(address,address,bool)");var Vc=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)"}),zc=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"}]),Kc=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"}]),Gc=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"}]}),Wc=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}]}),qo=(1n<<256n)-1n,Qc=qo/2n,Yc=4320*60*60*1e3,Xc=360*60*1e3,Jc=600*1e3,Zc=45*1e3;var we=Object.freeze(["debridge","lifi","relay","squid","stargate","thorchain","bungee","connext","wormhole","across","hop","changenow","rango"]),vr=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche"}),Mo=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"}),Ho=Object.freeze({1:"ETH",56:"BSC",8453:"BASE",42161:"ARB",43114:"AVAX"}),Tr=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]);function ft(e,t=180){return String(e?.message||e||"unknown error").replace(/\s+/g," ").slice(0,t)}function Cr(e){let t=String(e??"");if(!/^\d+$/.test(t))return null;try{return BigInt(t)>0n?t:null}catch{return null}}function jo(e,t){try{let r=BigInt(String(e))-BigInt(String(t));return r>0n?r.toString():null}catch{return null}}function fe(e){let t=Number(e);return Number.isInteger(t)&&t>=0&&t<=255?t:null}function Vo(e,t){let r=fe(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=fe(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 Ir(e,t,r){let n=fe(t),s=fe(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 mt(e){return typeof e?.to=="string"&&e.to.length>0&&/^0x(?:[0-9a-fA-F]{2})+$/.test(String(e.data||""))}function Ko(e){return(e?.steps||[]).some(t=>(t?.items||[]).some(r=>mt(r?.data)))}function kr(e,t,r){let n=Mo[Number(e)];return n?Tr.has(String(t||"").toLowerCase())?r&&r!=="?"?`${n}.${r}`:null:t?`${n}--${t}`:null:null}function Or(e,t,r){if(!r||r==="?")return null;if(r.includes("."))return r;let n=Ho[Number(e)];return n?Tr.has(String(t||"").toLowerCase())?`${n}.${r}`:`${n}.${r}-${t}`:null}async function Nr(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=fe(u),b=fe(c),S=new Map(we.map(p=>[p,{provider:p,status:"pending"}])),x=[],g={fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs,retries:t.retries,headers:t.headers},E=(p,M,H=!1)=>{S.set(p,{provider:p,status:"unavailable",reason:ft(M),optional:H})},T=(p,M)=>{S.set(p,{provider:p,status:"skipped",reason:ft(M)})},k=(p,M,H)=>{S.set(p,{provider:p,status:"attempted"}),x.push(Promise.resolve().then(M).then(G=>{if(G?.error)throw new Error(G.error);let gt=H(G),bt=Cr(gt?.amountOut);if(!bt)throw new Error("no usable integer base-unit amountOut");let Ur={...gt,provider:p,amountOut:bt,raw:G};return S.set(p,{provider:p,status:"successful"}),Ur}).catch(G=>(S.set(p,{provider:p,status:"failed",reason:ft(G)}),null)))};k("debridge",()=>ut({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:mt(p.tx)})),k("lifi",()=>de({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:mt(p.transactionRequest)})),k("relay",()=>ge({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:Ko(p)})),k("squid",()=>mr({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})),k("stargate",()=>hr({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=Ir(o,h,8),v=Or(r,s,i),R=Or(n,a,d);h==null||b==null?E("thorchain","fromDecimals and toDecimals are required for unit conversion"):!v||!R?E("thorchain","supported chain mapping plus qualified asset symbols are required"):Cr(L)?k("thorchain",()=>br({fromAsset:v,toAsset:R,amount:L,destination:l},g),p=>({amountOut:Ir(p.expectedAmountOut,8,b),feeUsd:p.fees?.total,estimatedTime:p.estimatedTime||"10-30 min",preparable:!1})):E("thorchain","amount is below THORChain's 8-decimal quote precision"),k("bungee",()=>yr({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})),k("connext",()=>Ar({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})),k("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})),k("across",()=>Re({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?jo(o,H):null),feeUsd:p.relayFeeTotalUsd??null,estimatedTime:p.estimatedFillTimeSec!=null?`${p.estimatedFillTimeSec}s`:"unknown",preparable:!1}});let y=vr[Number(r)],O=vr[Number(n)];!y||!O||!i||i==="?"?E("hop","supported chain mapping and fromSymbol are required"):k("hop",()=>_e({amount:String(o),token:i,fromChain:y,toChain:O},g),p=>({amountOut:p.estimatedRecieved??p.estimatedReceived,feeUsd:p.feeUsd??null,estimatedTime:p.estimatedTime??"unknown",preparable:!1}));let A=Vo(o,h);m?h==null||b==null?E("changenow","fromDecimals and toDecimals are required for unit conversion"):!i||!d||i==="?"||d==="?"?E("changenow","fromSymbol and toSymbol are required"):A==null?E("changenow","valid integer amount is required"):k("changenow",()=>fr({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."})):T("changenow","centralized/KYC-risk routes require includeCentralized=true");let w=t.env??process.env,U=t.rangoApiKey||w.RANGO_API_KEY,_=kr(r,s,i),V=kr(n,a,d);U?!_||!V?E("rango","supported Rango chain/token identifiers are required",!0):k("rango",()=>it({from:_,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})):E("rango","RANGO_API_KEY is not configured",!0);let D=(await Promise.all(x)).filter(Boolean);D.sort((p,M)=>{let H=BigInt(p.amountOut),G=BigInt(M.amountOut);return H!==G?H>G?-1:1:p.preparable!==M.preparable?p.preparable?-1:1:we.indexOf(p.provider)-we.indexOf(M.provider)});let I=we.map(p=>S.get(p)),N=I.filter(p=>["successful","failed"].includes(p.status)).map(p=>p.provider),B=I.filter(p=>p.status==="successful").map(p=>p.provider),F=I.filter(p=>p.status==="failed").map(p=>p.provider),X=I.filter(p=>p.status==="unavailable").map(p=>p.provider),ce=I.filter(p=>p.status==="skipped").map(p=>p.provider),Ae=I.filter(p=>p.status==="failed").map(p=>`${p.provider}: ${p.reason}`),Se=D.length>0,Ee=Se&&I.every(p=>p.status==="successful"||p.status==="skipped"||p.status==="unavailable"&&p.optional);return{ok:Se,providers:D.map(p=>p.provider),bestRoute:D[0]?.provider??"none",winner:D[0]??null,runnersUp:D.slice(1),errors:Ae.length?Ae:null,attemptedProviders:N,successfulProviders:B,failedProviders:F,unavailableProviders:X,skippedProviders:ce,comparisonComplete:Ee,coverage:{roster:[...we],attemptedProviders:N,successfulProviders:B,failedProviders:F,unavailableProviders:X,skippedProviders:ce,complete:Ee,details:I}}}var fu=Object.freeze({debridge:e=>lt(e),lifi:e=>et(e),relay:e=>st(e),thorchain:e=>wr(e),across:e=>nt(e),hop:e=>ot(e)}),mu=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}$/,Br=/^0x(?:[0-9a-fA-F]{2})+$/;function ht(e){return Array.isArray(e)?e.map(ht):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([t])=>t!=="signature"&&t!=="rawTransaction"&&t!=="signedTransaction").map(([t,r])=>[t,ht(r)]))}var Go=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),Wo=100;function Qo(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 Rr(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 Yo(e){if(Array.isArray(e)){let r=Rr(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 Xo(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 _r(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(!Br.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 Jo(e,t){return me[e?.provider]?e.provider==="debridge"?_r(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 ye(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 Zo(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=Qo(e.slippageBps),d=await Nr({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 E=Rr(g.feeUsd),T=Jo(g,e),k={source:g.provider,quality:"NO_GAS",amountOut:String(g.amountOut),grossOut:String(g.amountOut),netOut:String(g.amountOut),gasUsd:null,feeUsd:Yo(g.feeUsd),preparable:T.ok,prepareReason:T.reason,centralized:g.centralized===!0,kycRequired:g.kycRequired===!0,kycRisk:g.kycRisk===!0,riskDisclosure:g.riskDisclosure??null,meta:{durationSeconds:Xo(g.estimatedTime),estimatedTime:g.estimatedTime??null,destinationDecimals:Number.isInteger(e.toDecimals??e.decimalsOut)?Number(e.toDecimals??e.decimalsOut):null,routeSteps:[],feeCosts:E,gasCosts:[]}};return Object.defineProperty(k,"raw",{value:g.raw,enumerable:!1}),k}),f=c[0]??null,m=c.map((g,E)=>({provider:g.source,status:"quoted",rank:E+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})),S=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)&&(S=Number(g))}let x=[];return d.comparisonComplete!==!0&&x.push("bridge comparison coverage is incomplete; unavailable and failed providers remain explicit in routeOptions"),f&&f.preparable!==!0&&x.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:ye(f),runnersUp:c.slice(1).map(ye),coverage:d.coverage,comparisonComplete:d.comparisonComplete===!0,complete:d.comparisonComplete===!0,sourcesTried:d.coverage?.roster?.length??0,sourcesAnswered:c.length,improvementBps:S,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:x,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 me={debridge:async({fromChainId:e,taker:t},r,n)=>{let s=_r({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(()=>(dt(),dr)),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(()=>(be(),Ue)),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(()=>(Be(),Wt)),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 yu(){return Object.keys(me)}async function Au(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(Go.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 Zo(e,t):await cr(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&&me[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=me[c];if(!m||l&&f.preparable!==!0){let w=i.routes.find(U=>me[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):"",_=[String(w?.message||w),U].filter(Boolean).join(" :: "),V=/allowance/i.test(_),q=!V&&/not enough|insufficient|balance/i.test(_),D=i.routes.find(I=>me[I.source]&&(!l||I.preparable===!0)&&I.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: ${_}`:q?`${c} refused to build: ${_}. Quoting works for any address; preparing needs the real funded wallet on chain ${n}.`:`${c} bridge prepare failed: ${_}`,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 S=b.filter(w=>w.chainId==null||Number(w.chainId)!==Number(n));if(S.length)return{ok:!1,reason:`${c} returned a transaction for chain ${S[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=>!Br.test(String(w.data??""))))return{ok:!1,reason:`${c} returned incomplete unsigned calldata bytes`,failureKind:"provider-error",comparison:i};let T=h.requiresApproval??null,k=String(h.destination??"");if(!Y.test(k)||!b.some(w=>String(w.to).toLowerCase()===k.toLowerCase()))return{ok:!1,reason:`${c} returned no safely bound bridge deposit destination`,failureKind:"destination-not-bound",comparison:i};if(T){if(String(T.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(T.token))||!Y.test(String(T.spender)))return{ok:!1,reason:`${c} returned an incomplete approval bound`,failureKind:"approval-not-exact",comparison:i}}let L=e.driftToleranceBps??Wo,v=null,R=null;if(h.amountOut!=null&&f.grossOut!=null)try{let w=BigInt(f.grossOut),U=BigInt(h.amountOut);w>0n&&(v=Number((U-w)*10000n/w),v<-L&&(R=`route moved ${(v/100).toFixed(2)}% against you since the comparison (tolerance ${(L/100).toFixed(2)}%). Re-compare before signing.`))}catch{}let y=[...R?[R]:[],...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&&y.push(`This route needs ${b.length} transactions signed IN ORDER. Signing only the first leaves funds approved but not bridged.`);let O=e.walletReviewOnly===!0?ht(b):b,A=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:O,requiresApproval:T,amountOut:h.amountOut??null,minOut:h.minOut??null,durationSeconds:h.durationSeconds??null,slippageBps:i.slippageBps,routeOptions:i.routeOptions??[],winner:ye(i.best),quoteWinner:ye(i.best),coverage:i.coverage??null,comparisonComplete:i.comparisonComplete??null,complete:i.complete??null,destination:k,unsigned:!0,signedBy:"user-wallet",driftBps:v,warnings:y,runnersUp:i.routes.slice(1).map(ye),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{Au as prepareBestBridgeRoute,yu as supportedBridgePreparers};
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};