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