@oracle-agent/oracle 0.35.4 → 0.35.6
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/README.md +1 -1
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/bin/desk-server.mjs +25 -23
- package/dist/bin/oracle-data-mcp.mjs +13 -11
- package/dist/bin/oracle-gateway.mjs +35 -35
- package/dist/bin/oracle-mev-arb-shadow.mjs +7 -5
- package/dist/bin/oracle-mev-shadow.mjs +7 -5
- package/dist/bin/oracle-public-server.mjs +6 -4
- package/dist/bin/oracle-route.mjs +22 -20
- package/dist/bin/oracle-scan.mjs +14 -12
- package/dist/bin/oracle-telegram-mcp.mjs +10 -10
- package/dist/bin/oracle.mjs +7 -5
- package/dist/cli/commands/chat.mjs +166 -164
- package/dist/cli/commands/doctor.mjs +3 -3
- package/dist/cli/commands/eval.mjs +113 -113
- package/dist/cli/commands/farm.mjs +14 -14
- package/dist/cli/commands/follow.mjs +16 -14
- package/dist/cli/commands/model.mjs +170 -168
- package/dist/cli/commands/project.mjs +17 -0
- package/dist/cli/commands/resolve.mjs +8 -6
- package/dist/cli/commands/shadow.mjs +21 -0
- package/dist/cli/commands/signer.mjs +10 -10
- package/dist/cli/commands/snipe.mjs +10 -8
- package/dist/cli/commands/strategy.mjs +5 -5
- package/dist/cli/commands/swap.mjs +27 -25
- package/dist/cli/commands/telegram.mjs +10 -10
- package/dist/cli/commands/venues.mjs +2 -2
- package/dist/data/desk-data.mjs +23 -21
- package/dist/data/names.mjs +4 -2
- package/dist/data/providers/farming.mjs +2 -2
- package/dist/index.mjs +37 -35
- package/dist/local-signer/index.mjs +3 -3
- package/dist/local-signer/runtime.mjs +9 -9
- package/dist/nft/universal-mint-router.mjs +5 -3
- package/dist/router/index.mjs +4 -2
- package/dist/router/prepare-bridge.mjs +2 -2
- package/dist/scanner/index.mjs +5 -3
- package/dist/strategy/index.mjs +3 -3
- package/package.json +1 -1
- package/public/oracle-splash/index.html +2 -2
|
@@ -1,44 +1,46 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Xo=Object.defineProperty;var R=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var te=(e,t)=>{for(var r in t)Xo(e,r,{get:t[r],enumerable:!0})};function Zo(e={}){let t=[],r=[];if(!e||typeof e!="object")return{ok:!1,errors:["definition must be an object"],warnings:r};if((!Number.isInteger(e.chainId)||e.chainId<=0)&&t.push("chainId must be a positive integer"),(typeof e.key!="string"||!/^[a-z][a-z0-9-]*$/.test(e.key||""))&&t.push('key must be a lowercase slug (e.g. "base")'),(typeof e.name!="string"||!e.name.trim())&&t.push("name is required"),!Array.isArray(e.rpcEnv)||e.rpcEnv.length===0)t.push("rpcEnv must list at least one environment variable name");else for(let i of e.rpcEnv)(typeof i!="string"||!/^[A-Z][A-Z0-9_]*$/.test(i))&&t.push(`rpcEnv entry "${i}" should be an UPPER_SNAKE env var name`);if(e.nativeCurrency){let i=e.nativeCurrency;(typeof i.symbol!="string"||!i.symbol)&&t.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(i.decimals)||t.push("nativeCurrency.decimals must be an integer")}for(let[i,o]of(e.venues||[]).entries()){let a=`venues[${i}]`;if(!o||typeof o!="object"){t.push(`${a} must be an object`);continue}Jo.test(o.address||"")||t.push(`${a}.address is not a valid 20-byte address`),/^0x0{40}$/.test(o.address||"")&&t.push(`${a}.address is the zero address -- placeholder left in place?`),o.kind||t.push(`${a}.kind is required (router|quoter|factory|...)`),o.verified?(o.verified.method||t.push(`${a}.verified.method is required`),o.verified.source||t.push(`${a}.verified.source is required`),o.verified.date||r.push(`${a}.verified.date missing -- add one so staleness is visible`)):t.push(`${a} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let n=e.capabilities||{};for(let i of Object.keys(n))Me.includes(i)?typeof n[i]!="function"&&t.push(`capability "${i}" must be a function`):t.push(`unknown capability "${i}"`);return Object.keys(n).length===0&&r.push("scanner implements no capabilities -- it can only be registered, not used"),n.prepareUnsignedTx&&!n.quote&&r.push("prepareUnsignedTx without quote: no priced expectation to validate the built tx against"),n.prepareUnsignedTx&&!n.sellSimulation&&r.push("prepareUnsignedTx without sellSimulation: cannot prove an asset is exitable before buying"),{ok:t.length===0,errors:t,warnings:r}}function ei(e){let{ok:t,errors:r,warnings:n}=Zo(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
|
|
2
2
|
- ${r.join(`
|
|
3
|
-
- `)}`);let i=e.capabilities||{},o=qe.filter(a=>typeof i[a]=="function"),s={key:e.key,chainId:e.chainId,name:e.name,rpcEnv:[...e.rpcEnv],nativeCurrency:e.nativeCurrency?{...e.nativeCurrency}:null,wrappedNative:e.wrappedNative||null,explorer:e.explorer||null,venues:(e.venues||[]).map(a=>({...a})),warnings:n,capabilities(){return{chainId:e.chainId,key:e.key,supported:[...o],unsupported:qe.filter(a=>!o.includes(a))}},supports(a){return o.includes(a)}};for(let a of qe)o.includes(a)?s[a]=async(...u)=>i[a](...u,{scanner:s}):s[a]=async()=>{throw new Error(`${e.key} (chain ${e.chainId}) does not implement "${a}". Supported: ${o.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(s)}function Nr(e){let t=Wo(e);return xt.set(t.chainId,t),t}function Me(e){return xt.get(Number(e))||null}function _r(){return[...xt.values()]}var qe,_,O,zo,xt,fe=R(()=>{qe=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),_=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),O=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),zo=/^0x[0-9a-fA-F]{40}$/;xt=new Map});function Rr(e){let{source:t,amountOut:r,minOut:n=null,gasUsd:i=null,feeUsd:o=null,oracleFeeBps:s=0,estimatedGas:a=null,liquidityUsd:u=null,error:l=null,executionReady:p=!1,meta:d={}}=e||{};if(l||r==null)return{source:t,quality:Q.FAILED,amountOut:null,error:l||"no amountOut returned"};let c=Ie(r);if(c==null||c<=0n)return{source:t,quality:Q.FAILED,amountOut:null,error:"non-positive amountOut"};let f=Number(s);return{source:t,quality:i==null?Q.NO_GAS:Q.FULL,amountOut:c.toString(),minOut:Ie(n)?.toString()??null,gasUsd:i,feeUsd:o,oracleFeeBps:Number.isFinite(f)&&f>0?Math.floor(f):0,estimatedGas:a==null?null:String(a),liquidityUsd:u==null?null:Number(u),executionReady:p,meta:d}}async function Tr(e,t,{divisor:r=1000n}={}){let n=Ie(t);if(n==null||n<=0n)return null;let i=n/r>0n?n/r:1n;if(i>=n)return null;let o,s;try{[o,s]=await Promise.all([e(i),e(n)])}catch{return null}let a=Ie(o),u=Ie(s);if(a==null||u==null||a<=0n)return null;let l=Number(a)/Number(i),p=Number(u)/Number(n);return!Number.isFinite(l)||!Number.isFinite(p)||l<=0?null:{impactPct:(1-p/l)*100,probeAmountIn:i.toString(),probeAmountOut:a.toString(),fullAmountOut:u.toString()}}function $r(e,t,{maxImpactPct:r=25}={}){let n=[],i=[],o=(e.routes??[]).filter(a=>{let u=t?.[a.source];return u?u.impactPct>r?(n.push({source:a.source,impactPct:Number(u.impactPct.toFixed(2)),reason:`price impact ${u.impactPct.toFixed(1)}% exceeds ${r}% ceiling -- the venue cannot absorb this size near the quoted price`}),!1):!0:(i.push(a.source),!0)}),s=[...e.warnings??[]];return n.length&&s.push(`dropped ${n.length} route(s) on price impact: `+n.map(a=>`${a.source} (${a.impactPct}%)`).join(", ")),i.length&&s.push(`price impact NOT measured for: ${i.join(", ")}. These are unproven against thin liquidity, not proven safe.`),{...e,routes:o,best:o[0]??null,impactRejected:n,impactUnmeasured:i,warnings:s}}function vt(e,{destPriceUsd:t=null,destDecimals:r=null,liquidityFirst:n=!0,liquidityBandBps:i=50,gasPriceWei:o=null,nativePriceUsd:s=null}={}){let a=e.filter(w=>w.quality!==Q.FAILED),u=e.filter(w=>w.quality===Q.FAILED),l=t!=null&&t>0&&r!=null&&r>=0,p=Number(o),d=Number(s),c=Number.isFinite(p)&&p>0&&Number.isFinite(d)&&d>0,f=a.map(w=>{let A=BigInt(w.amountOut),I=0n,N=!1,U=!1,$=BigInt(w.oracleFeeBps??0),V=$>0n?A*$/10000n:0n;if(l){let de=w.gasUsd,St=Number(w.meta?.gasUnits??w.estimatedGas);if(de==null&&c&&Number.isFinite(St)&&St>0){let pe=St*p/1e18*d;Number.isFinite(pe)&&pe>=0&&(de=pe,U=!0)}let Or=(de??0)+(w.feeUsd??0);if(Or>0){let pe=Or/t*10**r;Number.isFinite(pe)&&pe>=0&&(I=BigInt(Math.floor(pe)),N=!0)}else de===0&&(N=!0)}let ye=I+V,At=A>ye?A-ye:0n;return{...w,grossOut:A.toString(),netOut:At.toString(),costInDest:I.toString(),oracleFeeInDest:V.toString(),costAccounted:N,gasEstimated:U}}),m=Number(i)>0?Number(i):0,b=f.reduce((w,A)=>BigInt(A.netOut)>w?BigInt(A.netOut):w,0n),h=w=>b>0n?Number((b-BigInt(w))*10000n/b):0,x=[],v=f.slice().sort((w,A)=>BigInt(A.netOut)>BigInt(w.netOut)?1:-1)[0]??null;f.sort((w,A)=>{let I=h(w.netOut)<=m?0:1,N=h(A.netOut)<=m?0:1;if(n&&m>0&&I!==N)return I-N;if(n&&m>0){let U=w.liquidityUsd??-1,$=A.liquidityUsd??-1;if(U!==$)return $-U}return BigInt(A.netOut)>BigInt(w.netOut)?1:-1}),n&&m>0&&v&&f[0]&&f[0].source!==v.source&&x.push(`liquidity-first: chose ${f[0].source} (liquidity $${f[0].liquidityUsd??"unknown"}) over best-price ${v.source} within ${m} bps`);let k=f.filter(w=>!w.costAccounted).map(w=>w.source);l?k.length&&x.push(`gas not reported by: ${k.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):x.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let S=f[0];if(l&&S&&S.costAccounted===!1){let w=f.find(A=>A.costAccounted&&h(A.netOut)<=m);w&&x.push(`winner ${S.source} has UNMEASURED gas; gas-measured ${w.source} is within ${m} bps and may net more once ${S.source}'s real gas is paid \u2014 prefer it if unsure.`)}let C=f.filter(w=>w.gasEstimated).map(w=>w.source);C.length&&x.push(`gas ESTIMATED (from gas units x current gas price, not measured) for: ${C.join(", ")}. Net includes this estimate so the ranking is gas-inclusive, but the on-chain gas may differ.`);let E=null,y=null;if(f.length>=2&&f[0].costAccounted&&f[1].costAccounted){let w=BigInt(f[0].netOut),A=BigInt(f[1].netOut);A>0n&&(E=Number((w-A)*10000n/A),y=`${f[0].source} vs ${f[1].source}`)}return{best:f[0]??null,routes:f,failed:u,improvementBps:E,spreadBasis:y,rankedOn:l?"net-of-cost":"gross",warnings:x}}async function He(e,{timeoutMs:t=12e3}={}){let r=(i,o)=>Promise.race([i,new Promise((s,a)=>setTimeout(()=>a(new Error(`${o}: timeout`)),t))]);return(await Promise.allSettled(e.map(i=>r(Promise.resolve().then(i.run),i.source)))).map((i,o)=>{let s=e[o].source;return i.status==="rejected"?Rr({source:s,error:String(i.reason?.message||i.reason)}):Rr({source:s,...i.value})})}var Q,Br,Ie,It=R(()=>{fe();Q=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"}),Br={1:"coingecko:ethereum",10:"coingecko:ethereum",56:"coingecko:binancecoin",137:"coingecko:matic-network",8453:"coingecko:ethereum",42161:"coingecko:ethereum",43114:"coingecko:avalanche-2",999:"coingecko:ethereum"},Ie=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}}});import me from"node:net";import Go from"node:dns";function Ve(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=p=>{if(!p)return[];let d=p.split(":"),c=d.at(-1);if(c?.includes(".")){let f=c.split(".").map(Number);if(f.length!==4||f.some(m=>!Number.isInteger(m)||m<0||m>255))return null;d.splice(d.length-1,1,(f[0]<<8|f[1]).toString(16),(f[2]<<8|f[3]).toString(16))}return d.some(f=>!/^[0-9a-f]{1,4}$/.test(f))?null:d.map(f=>Number.parseInt(f,16))},[n,i]=t.split("::"),o=r(n),s=r(i);if(!o||!s)return null;let a=t.includes("::"),u=8-o.length-s.length;if(!a&&u!==0||a&&u<1)return null;let l=[...o,...Array(Math.max(0,u)).fill(0),...s];return l.length!==8?null:Uint8Array.from(l.flatMap(p=>[p>>8,p&255]))}function Ct(e,t,r){let n=Math.floor(r/8),i=r%8;for(let s=0;s<n;s+=1)if(e[s]!==t[s])return!1;if(!i)return!0;let o=255<<8-i;return(e[n]&o)===(t[n]&o)}function kt(e){if(me.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(me.isIPv6(e)){let t=Ve(e);if(!t)return!1;let r=Ve("::ffff:0:0");return Ct(t,r,96)?kt([...t.slice(12)].join(".")):Ct(t,Ve("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([i,o])=>Ct(t,Ve(i),o)):!1}return!1}function Yo(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(Qo.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=me.isIP(r);return n!==0&&!kt(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function Ot(e,{lookupFn:t=Go.promises.lookup}={}){let r=Yo(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:me.isIPv6(r.host)?6:4}]};let n;try{n=await t(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(i=>!kt(i.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function Nt({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n;try{let d=await t();r=d.Agent,n=d.fetch}catch(d){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${d?.message||d}`);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 i=d=>String(d).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),o=new Map,s=d=>(Array.isArray(d)?d:[d]).map(c=>typeof c=="string"?{address:c}:c).filter(c=>c&&c.address).map(c=>({address:c.address,family:c.family||(me.isIPv6(c.address)?6:4)})),a=(d,c,f)=>{o.set(i(d),s(typeof c=="string"?[{address:c,family:f}]:c))},u=d=>{let c=i(d);if(me.isIP(c))return[{address:c,family:me.isIPv6(c)?6:4}];let f=o.get(c);if(!f||!f.length)throw new Error(`refused: unpinned host ${d} during pinned fetch`);return f},l=new r({connect:{lookup(d,c,f){let m;try{m=u(d)}catch(b){return f(b)}return c?.all?f(null,m):f(null,m[0].address,m[0].family)}}}),p=Xo((d,c={})=>n(d,{...c,dispatcher:l}),a);return{dispatcher:l,fetch:p,pin:a,resolve:u,async close(){try{await l.destroy()}catch{}}}}function Xo(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[_t]=Object.freeze({pin:t}),e}function Rt(e){return typeof e=="function"&&typeof e[_t]?.pin=="function"}function Lr(e,t,r){if(!Rt(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[_t].pin(t,r)}var Qo,_t,Ur=R(()=>{Qo=new Set(["localhost","metadata.google.internal","metadata.goog"]);_t=Symbol.for("oracle.egressGuard.pinCapableFetch")});import{createHash as Jo}from"node:crypto";function ni(e){let t=String(e||"").toLowerCase();return Hr.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function oi(e){let t={};for(let[r,n]of Object.entries(e||{}))ni(r)||(t[r]=n);return t}function ii(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 ai(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function si(e,t,r,n={}){let i={};for(let[p,d]of Object.entries(r||{}))i[p.toLowerCase()]=d;let o=Object.keys(i).filter(p=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(p)),a=[...new Set([...Hr,...o])].sort().map(p=>`${p}=${i[p]??""}`).join(`
|
|
4
|
-
`),u=Jo("sha256").update(a).digest("hex").slice(0,32),l=`${n.untrustedUrl?"untrusted":"trusted"}:${n.maxResponseBytes??"unbounded"}`;return`${e} ${t} ${l} ${u}`}function ci(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Dr):Math.min(250*2**e,Dr)+Math.floor(Math.random()*100)}function Ce(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function Tt(e,t,r){return Ce(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function ke(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function li(e){return e?e.byteLength??e.length??0:0}async function qr(e,t,{url:r,truncate:n=!1,onOversize:i}={}){if(t==null)return await e.text();let o=Number(e.headers?.get?.("content-length"));if(Number.isFinite(o)&&o>t&&(ke(e),!n))throw Tt(r,`content-length ${o}`,t);let s=e.body?.getReader?.();if(!s){let d=await e.text(),c=Buffer.byteLength(d,"utf8");if(c>t){if(!n)throw Tt(r,`body ${c} bytes`,t);return Buffer.from(d,"utf8").subarray(0,t).toString("utf8")}return d}let a=[],u=0,l=!1;try{for(;;){let{value:d,done:c}=await s.read();if(c)break;if(d&&(a.push(Buffer.from(d)),u+=li(d),u>t)){l=!0;break}}}finally{if(l)try{await s.cancel()}catch{}try{s.releaseLock?.()}catch{}}if(l&&(typeof i=="function"&&i(),!n))throw Tt(r,`streamed ${u} bytes`,t);let p=Buffer.concat(a);return(l?p.subarray(0,t):p).toString("utf8")}function Mr(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function di(e,{fetchImpl:t,method:r,headers:n,body:i,timeoutMs:o,lookupFn:s,realFetch:a,untrustedUrl:u=!1,maxResponseBytes:l=null,importUndici:p,validateResponse:d,signal:c}){let f=new AbortController,m=setTimeout(()=>f.abort(),o),b=c?typeof AbortSignal.any=="function"?AbortSignal.any([c,f.signal]):c:f.signal,h=null,x=t,v=s?{lookupFn:s}:{};if(u&&!a&&!Rt(x))throw Ce(`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 k=async(S,{status:C=null}={})=>{let E=await Ot(S,v);if(!E.ok)throw Ce(C==null?`HTTP refused ${S}: ${E.error}`:`HTTP redirect to ${S} ${E.error}`,C==null?{}:{status:C});let y=new URL(S).hostname;if(a){if(h&&(await h.close(),h=null),!h)try{h=await Nt({requireUndici:!0,...p?{importUndici:p}:{}})}catch(w){throw Ce(C==null?`HTTP refused ${S}: ${w?.message||w}`:`HTTP redirect to ${S} refused: ${w?.message||w}`,C==null?{}:{status:C})}h.pin(y,E.addresses),x=h.fetch}else Lr(x,y,E.addresses);return E};try{let S=String(e),C={...n||{}};u&&await k(S);for(let E=0;E<=Fr;E+=1){let y=await x(S,{method:r,headers:C,body:i,signal:b,redirect:"manual"});if(ti.has(y.status)){if(r!=="GET"&&r!=="HEAD"){let $=await qr(y,l??ri,{url:S,truncate:!0}),V=new Error(`HTTP ${y.status} ${r} ${S} redirected non-idempotent request`);throw V.status=y.status,V.body=Mr($)??$.slice(0,300),V}if(E===Fr)throw ke(y),new Error(`HTTP redirect loop for ${e}`);let I=y.headers?.get?.("location"),N;try{N=ii(I,S)}catch($){throw ke(y),$}let U=!ai(N,S);if(ke(y),U&&(C=oi(C)),u)await k(N,{status:y.status});else if(U){let $=await Ot(N,v);if(!$.ok){let V=new Error(`HTTP redirect from ${S} ${$.error}`);throw V.status=y.status,V.retryable=!1,V}a&&$.addresses?.length&&(h||(h=await Nt(p?{importUndici:p}:{})),h&&(h.pin(new URL(N).hostname,$.addresses),x=h.fetch))}S=N;continue}if(typeof d=="function")try{await d(y,{url:S})}catch(I){throw ke(y),Ce(I?.message||String(I))}let w=await qr(y,l,{url:S,onOversize:()=>f.abort()}),A=Mr(w);if(!y.ok){let I=new Error(`HTTP ${y.status} ${r} ${S}`);throw I.status=y.status,I.retryAfter=y.headers?.get?.("retry-after")??null,I.body=A??w.slice(0,300),I}return A??w}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(m),h&&await h.close()}}async function T(e,t={}){let r=t.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=t.timeoutMs??12e3,i=(t.method||"GET").toUpperCase(),o={Accept:"application/json",...t.headers||{}},s=t.body;s!=null&&typeof s!="string"&&(o["Content-Type"]=o["Content-Type"]||"application/json",s=JSON.stringify(s));let a=Number.isInteger(t.retries)?Math.max(t.retries,0):ei,u=t.lookupFn,l=!t.fetchImpl,p=t.untrustedUrl===!0,d=t.importUndici,c=t.validateResponse,f=t.signal,m=Number(t.maxResponseBytes),b=Number.isFinite(m)&&m>0?Math.floor(m):null,h=async()=>{let C;for(let E=0;E<=a;E++){f?.throwIfAborted?.();try{return await di(e,{fetchImpl:r,method:i,headers:o,body:s,timeoutMs:n,lookupFn:u,realFetch:l,untrustedUrl:p,maxResponseBytes:b,importUndici:d,validateResponse:c,signal:f})}catch(y){C=y;let w=y?.status,A=y?.name==="AbortError"||y?.name==="TimeoutError"||f?.aborted,I=new Set([408,425,429]),N=y?.retryable===!1?!1:w!=null?I.has(w)||Zo.has(w)&&Pr.has(i):!A&&Pr.has(i);if(E===a||!N)throw y;let U=ci(E,y?.retryAfter);f?await new Promise(($,V)=>{let ye=setTimeout($,U);f.addEventListener("abort",()=>{clearTimeout(ye),V(f.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await ui(U)}}throw C};if(!(t.dedupe!==!1&&!f&&i==="GET"&&s==null))return h();let v=si(i,e,o,{untrustedUrl:p,maxResponseBytes:b}),k=Bt.get(v);if(k)return k;let S=h().finally(()=>Bt.delete(v));return Bt.set(v,S),S}var Zo,Pr,ei,Dr,Hr,ti,Fr,ri,Bt,ui,Y=R(()=>{Ur();Zo=new Set([408,425,429,500,502,503,504]),Pr=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),ei=2,Dr=4e3,Hr=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],ti=new Set([301,302,303,307,308]),Fr=3,ri=64*1024;Bt=new Map;ui=e=>new Promise(t=>setTimeout(t,e))});import{readFileSync as pi}from"node:fs";import{homedir as fi}from"node:os";import{join as je}from"node:path";function mi(){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=fi();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||je(t,".config","oracle")).trim();return[e,je(r,"exec.env")].filter(Boolean)}return[e,je(t,".config","oracle","exec.env"),je(t,".config","mad-desk","exec.env")].filter(Boolean)}function Vr(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let i of mi())try{let o=pi(i,"utf8"),s=o.match(new RegExp(`^${t}=(.*)$`,"m"))||o.match(new RegExp(`^${r}=(.*)$`,"m"));if(s&&(n=s[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 jr=R(()=>{});var zr=R(()=>{});import{createHash as hi,createHmac as Wr,timingSafeEqual as bi}from"node:crypto";function Ke(e){return Array.isArray(e)?`[${e.map(Ke).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Ke(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Gr(e,{required:t=!1}={}){try{return Vr(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function Lt(e){let{signature:t,...r}=e;return r}function Qr(e,{secret:t}={}){let r=Gr(t);return r?{...e,signature:Wr("sha256",r).update(Ke(Lt(e))).digest("hex")}:e}function wi(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 hi("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function K(e,{chainId:t,venue:r,data:n,secret:i}={}){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 o=Gr(i);if(o){let f=Wr("sha256",o).update(Ke(Lt(e))).digest("hex");if(!gi(e.signature,f))throw new Error("auto-slippage guard signature mismatch \u2014 refusing to bind a guard this Oracle did not issue")}let s=Number(e.selectedBps),a=Number(e.capBps);if(!Number.isInteger(s)||s<0||s>ze||!Number.isInteger(a)||a<0||a>ze||s>a)throw new Error("auto-slippage guard bounds are invalid");let u=BigInt(e.quoteAmountOut??0),l=BigInt(e.minAmountOut??0);if(u<=0n||l<=0n)throw new Error("auto-slippage guard amounts must be positive");let p=u*BigInt(1e4-s),d=p/10000n;if(p%10000n!==0n&&(d+=1n),l<d)throw new Error("auto-slippage guard is under-protected relative to its quote");let c=Ai(n);if(c!=null&&c!==l)throw new Error(`auto-slippage: calldata encodes floor ${c}, not the guard floor ${l} \u2014 refusing to bind`);return Qr({...Lt(e),calldataHash:wi(n)},{secret:i})}function gi(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:bi(r,n)}function $t(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function yi(e){let t=e==null?ze: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,ze)}function re({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:i}={}){let o=$t(e,0),s=o>0?o>=25e4?5:o>=1e5?10:o>=5e4?20:o>=1e4?40:70:n?30:10,a=Math.min(60,Math.abs($t(t,0))*2),u=Math.min(40,Math.floor(Math.max(0,$t(r,0))/5e3)*5),l=Math.max(25,Math.ceil(20+s+a+u)),p=yi(i);return{mode:"auto",requiredBps:l,selectedBps:Math.min(l,p),capBps:p,executable:l<=p}}function Ei({chainId:e,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:i=0,quoteAgeMs:o=0,crossChain:s=!1,requestedCapBps:a,quotedAtMs:u=Date.now(),ttlMs:l=Kr,secret:p}={}){let d=BigInt(r??0);if(d<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let c=re({liquidityUsd:n,priceChange5m:i,quoteAgeMs:o,crossChain:s,requestedCapBps:a});if(!c.executable)throw new Error(`auto-slippage requires ${c.requiredBps} bps above hard/requested cap ${c.capBps}; route blocked`);let f=Number(u);if(!Number.isFinite(f))throw new Error("auto-slippage: quotedAtMs must be a finite number");let m=Math.min(3e4,Math.max(1e3,Number(l)||Kr)),b=d*BigInt(1e4-c.selectedBps),h=b/10000n;if(b%10000n!==0n&&(h+=1n),h>d&&(h=d),d>0n&&h<=0n)throw new Error(`auto-slippage: quote ${d} is too small to express a ${c.selectedBps} bps floor without rounding to zero`);let x=Number((d-h)*10000n/(d===0n?1n:d));if(x>c.capBps)throw new Error(`auto-slippage: realised floor implies ${x} bps, above cap ${c.capBps} \u2014 refusing to issue a guard weaker than advertised`);return Qr({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:d.toString(),minAmountOut:h.toString(),requiredBps:c.requiredBps,selectedBps:c.selectedBps,capBps:c.capBps,quotedAtMs:f,expiresAtMs:f+m},{secret:p})}function Ai(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 o=10;o+64<=t.length;o+=64)n.push(t.slice(o,o+64));let i=o=>n[o]==null?null:BigInt("0x"+n[o]);switch(r){case"0x414bf389":return i(6);case"0x04e45aaf":return i(5);case"0xc04b8d59":{let o=i(0);if(o==null)return null;let s=Number(o)/32;return!Number.isInteger(s)||s<0?null:i(s+4)}case"0xb858183f":{let o=i(0);if(o==null)return null;let s=Number(o)/32;return!Number.isInteger(s)||s<0?null:i(s+3)}case"0xa026383e":return i(6);case"0x38ed1739":case"0x5c11d795":return i(1);case"0x7ff36ab5":case"0xb6f9de95":return i(0);case"0x18cbafe5":case"0x791ac947":return i(1);default:return null}}function D(e,{chainId:t,venue:r,amountOut:n,liquidityUsd:i,priceChange5m:o,crossChain:s,requestedCapBps:a,quotedAtMs:u=Date.now(),ttlMs:l}={}){let p=Ei({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:i,priceChange5m:o,crossChain:s,requestedCapBps:a,quotedAtMs:u,ttlMs:l});return{...e,autoSlippage:p,amountOutMinimum:p.minAmountOut}}var ze,Kr,ne=R(()=>{jr();zr();ze=100,Kr=2e4});function Ut(e){let t=String(e||"").trim();return/^0x[0-9a-fA-F]{40}$/.test(t)?t:se}var se,We=R(()=>{se="0x000000000000000000000000000000000000dEaD"});import{createHash as Si,createHmac as xi,timingSafeEqual as Lc}from"node:crypto";function Pt(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Pt).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Pt(e[r])}`).join(",")}}`}function Yr(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Xr(e=process.env){return Yr(process.env)||Yr(e)}function ki(e){let{prepareHash:t,prepareMac:r,note:n,...i}=e||{};return i}function Oi(e){let t=ki(e);return Si("sha256").update(Pt(t)).digest("hex")}function Ni(e,t=Xr()){return t?xi("sha256",t).update(String(e)).digest("hex"):""}function F(e,{provider:t,kind:r,env:n=process.env,nowMs:i=Date.now(),expiresAtMs:o}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let s=Object.prototype.hasOwnProperty.call(e,"oraclePrepared");if(s&&typeof e.oraclePrepared!="boolean")throw new Error("stampPrepared: oraclePrepared must be boolean");let a={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1,oraclePrepared:s?e.oraclePrepared:!0};if(!a.provider)throw new Error("stampPrepared: provider required");if(!a.kind)throw new Error("stampPrepared: kind required");let u=Number(i),l=o==null?u+Ii:Number(o),p=l-u;if(!Number.isSafeInteger(u)||!Number.isSafeInteger(l)||p<=0||p>Ci)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let c={...a,preparedAt:u,expiresAt:l,prepareVersion:vi},f=Oi(c),m=Xr(n),b=m?Ni(f,m):void 0,h={...c,prepareHash:f};return b&&(h.prepareMac=b),h}var vi,Ii,Ci,X=R(()=>{vi=2,Ii=300*1e3,Ci=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Contract as _i,JsonRpcProvider as Ri}from"ethers";function Pi(e){return Ui.test(String(e||""))}async function Jr(e,{contract:t=Bi,rpc:r=$i,chainId:n=Ti,balanceOf:i}={}){if(!Pi(e))throw new Error("invalid-address");if(i)return BigInt(await i(e));let o=new Ri(r,n,{staticNetwork:!0}),s=new _i(t,Li,o);return BigInt(await s.balanceOf(e))}var Bi,Ti,$i,Li,Ui,Zr=R(()=>{Bi="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",Ti=999,$i="https://rpc.hyperliquid.xyz/evm",Li=["function balanceOf(address owner) view returns (uint256)"],Ui=/^0x[a-fA-F0-9]{40}$/});import{existsSync as Di,readFileSync as Fi,lstatSync as qi}from"node:fs";import{homedir as en}from"node:os";import{join as Dt}from"node:path";function Vi(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(tn,t)?tn[t]:Hi}function Gi(e=process.env){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){if(e[rn])return String(e[rn]);let t=e.ORACLE_CONFIG_DIR||Dt(en(),".config","oracle");return Dt(t,"fee-recipient")}return Dt(en(),".config","oracle","fee-recipient")}function Qi(e=process.env){try{let t=Gi(e);if(!Di(t)||qi(t).isSymbolicLink())return"";let r=Fi(t,"utf8").trim().toLowerCase();return/^0x[a-f0-9]{40}$/.test(r)?r:""}catch{return""}}function Yi(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),Mi)}function Xi({env:e=process.env,action:t="swap",admin:r=!1}={}){let n=String(e[zi]||"").trim(),i=String(e[Ki]||Wi).trim();if(r===!0)return{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"admin-oracle"};let o=Vi(t),s=Yi(e[ji],{fallback:n?o:0}),a=Math.min(s,o);if(!a)return{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"not-configured"};if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"no-recipient"};let u=Qi(e);return!u||u!==n.toLowerCase()?{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"recipient-not-pinned"}:{bps:a,recipient:n,integrator:i,action:t,applies:!0,reason:"configured"}}async function Ge({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={},admin:i=!1}={}){let o=Xi({env:t,action:r,admin:i});if(i===!0)return{...o,holderVerificationStatus:"admin-oracle"};let s=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(s))return{...o,holderVerificationStatus:"wallet-required"};try{return BigInt(await Jr(s,n))>0n?{...o,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...o,holderVerificationStatus:"non-holder"}}catch{return{...o,holderVerificationStatus:"unavailable"}}}function nn(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 on(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}function an(e){return e?.applies?{partner:e.integrator,partnerFeeBps:String(e.bps),partnerAddress:e.recipient}:{}}var Mi,Hi,tn,ji,zi,Ki,rn,Wi,Qe=R(()=>{Zr();Mi=100,Hi=5,tn=Object.freeze({swap:5,bridge:5,perps:0,nft:0});ji="ORACLE_INTEGRATOR_FEE_BPS",zi="ORACLE_INTEGRATOR_FEE_RECIPIENT",Ki="ORACLE_INTEGRATOR_ID",rn="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",Wi="oracle"});var un={};te(un,{LIFI_API:()=>cn,lifiChains:()=>ra,lifiHealth:()=>ea,lifiPrepare:()=>ta,lifiQuote:()=>Oe});function qt(e={}){return(e.baseUrl||process.env.LIFI_API_URL||cn).replace(/\/$/,"")}function Zi(e){let t=String(e||Ft).toLowerCase();return t===Ft.toLowerCase()||t===Ji}function sn(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 ea(e={}){let t=await T(`${qt(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 Oe(e={},t={}){let{fromChain:r,toChain:n=r,fromToken:i=Ft,toToken:o,fromAmount:s,fromAddress:a=se}=e;if(r==null||!o||!s)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let u=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:i,toToken:o,fromAmount:String(s),fromAddress:a}),l=re({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!l.executable)throw new Error(`lifi: route requires ${l.requiredBps} bps above cap ${l.capBps}`);u.set("slippage",String(l.selectedBps/1e4));let p=await Ge({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[h,x]of Object.entries(on(p)))u.set(h,x);let d=await T(`${qt(t)}/quote?${u}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),c=d?.estimate?.toAmount||d?.toAmount;if(!c)return{...d,autoSlippagePolicy:l,oracleFee:p};let f=d?.transactionRequest?.to||d?.estimate?.approvalAddress||"lifi",m=D(d,{chainId:Number(r),venue:f,amountOut:c,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),b=d?.estimate?.toAmountMin||d?.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:p}}async function ta(e={},t={}){let r=await Oe(e,t),n=r?.transactionRequest;if(!n?.to||!n?.data)throw new Error("lifi: quote did not return an executable transactionRequest");let i=Number(e.fromChain);if(n.chainId!=null&&Number(n.chainId)!==i)throw new Error("lifi: transaction chain mismatch");if(e.fromAddress&&n.from&&String(n.from).toLowerCase()!==String(e.fromAddress).toLowerCase())throw new Error("lifi: transaction sender mismatch");let o=null;if(!Zi(e.fromToken)){let s=r?.estimate?.approvalAddress||r?.approvalAddress;if(!s)throw new Error("lifi: ERC20 route missing approvalAddress");let a=r?.action?.fromToken?.address||r?.estimate?.fromToken?.address||e.fromToken;o={token:sn(a,"approval token"),spender:sn(s,"approval spender"),amount:String(e.fromAmount)}}return F({provider:"lifi",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:i,quote:r,autoSlippage:r.autoSlippage,requiresApproval:o,transaction:{chainId:i,from:n.from||e.fromAddress,to:n.to,data:n.data,value:n.value??"0x0",...n.gasLimit!=null?{gasLimit:n.gasLimit}:{},slippageGuard:K(r.autoSlippage,{chainId:i,venue:n.to,data:n.data})}},{provider:"lifi",kind:"lifi-tx"})}async function ra(e={}){return T(`${qt(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var cn,Ft,Ji,Mt=R(()=>{Y();ne();We();X();Qe();cn="https://li.quest/v1";Ft="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",Ji="0x0000000000000000000000000000000000000000"});var pn={};te(pn,{PARASWAP_API:()=>ln,paraswapHealth:()=>oa,paraswapPrepare:()=>na,paraswapPrice:()=>Ye,paraswapTokens:()=>dn});function Ee(e,t){let r=String(e||"");if(!/^0x[0-9a-fA-F]{40}$/.test(r))throw new Error(`${t} must be a 20-byte token address`);return r.toLowerCase()}async function dn(e={},t={}){let r=Number(e.chainId||1);return T(`${Ht(t)}/tokens/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function Ye(e={},t={}){let r=Number(e.chainId||e.network||1);if(e.amount==null)throw new Error("amount required");let n=new URLSearchParams({srcToken:Ee(e.srcToken,"srcToken"),destToken:Ee(e.destToken,"destToken"),amount:String(e.amount),srcDecimals:String(Number(e.srcDecimals)),destDecimals:String(Number(e.destDecimals)),side:String(e.side||"SELL").toUpperCase(),network:String(r),version:String(e.version||"6.2")});e.includeDEXS&&n.set("includeDEXS",String(e.includeDEXS)),e.excludeDEXS&&n.set("excludeDEXS",String(e.excludeDEXS));let i=await Ge({wallet:e.userAddress||e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[a,u]of Object.entries(an(i)))n.set(a,u);let o=await T(`${Ht(t)}/prices?${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),s=o?.priceRoute?.destAmount;return s?{...D(o,{chainId:r,venue:o?.priceRoute?.contractAddress||"paraswap-quote",amountOut:s,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,quoteAgeMs:0,requestedCapBps:e.maxSlippageBps??e.slippageBps}),executionReady:!1,executionBlocker:"call prepare to bind the price route to a validated transaction",oracleFee:i}:{...o,executionReady:!1,oracleFee:i}}async function na(e={},t={}){if(String(e.side||"SELL").toUpperCase()!=="SELL")throw new Error("paraswap: agentic prepare currently supports exact-input SELL only");let r=Number(e.chainId||e.network||1),n=Ee(e.userAddress,"userAddress"),i=await Ye(e,t),o=i?.priceRoute,s=String(o?.contractAddress||"").toLowerCase();if(!s)throw new Error("paraswap: price route missing contractAddress");let a={srcToken:Ee(e.srcToken,"srcToken"),destToken:Ee(e.destToken,"destToken"),srcAmount:String(o.srcAmount||e.amount),destAmount:String(i.amountOutMinimum),priceRoute:o,userAddress:n,ignoreChecks:!1,ignoreGasEstimate:!1};e.receiver&&(a.receiver=Ee(e.receiver,"receiver"));let u=await T(`${Ht(t)}/transactions/${r}`,{method:"POST",body:a,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3});if(Number(u.chainId??r)!==r)throw new Error("paraswap: transaction chain mismatch");if(String(u.to||"").toLowerCase()!==s)throw new Error("paraswap: transaction target mismatch");if(u.from&&String(u.from).toLowerCase()!==n)throw new Error("paraswap: transaction sender mismatch");return F({provider:"paraswap",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,quote:i,autoSlippage:i.autoSlippage,requiresApproval:a.srcToken!=="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"?{token:a.srcToken,spender:o.tokenTransferProxy||s,amount:a.srcAmount}:null,transaction:{chainId:r,from:u.from||n,to:u.to,data:u.data,value:u.value??"0x0",...u.gas!=null?{gasLimit:u.gas}:{},slippageGuard:K(i.autoSlippage,{chainId:r,venue:u.to,data:u.data})}},{provider:"paraswap",kind:"paraswap-tx"})}async function oa(e={}){let t=await dn({chainId:1},e),r=Array.isArray(t?.tokens)?t.tokens.length:Object.keys(t?.tokens||{}).length;return{ok:r>0,tokenSample:r}}var ln,Ht,Vt=R(()=>{Y();ne();X();Qe();ln="https://api.paraswap.io",Ht=(e={})=>(e.baseUrl||process.env.PARASWAP_API_URL||ln).replace(/\/$/,"")});function Xe({provider:e,defaultUrl:t,hosts:r=[],url:n,strict:i=!1}){let s=(String(n??"").trim()||String(t)).replace(/\/$/,"");if(s===String(t).replace(/\/$/,""))return{baseUrl:s,trusted:!0,host:mn(t)};let a;try{a=new URL(s)}catch{throw new Error(`${e}: baseUrl must be an absolute http(s) URL`)}if(a.protocol!=="http:"&&a.protocol!=="https:")throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);let u=a.host;if(!u)throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);if(new Set([mn(t),...r]).has(u)){let p=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(u);return a.protocol==="http:"&&!p?{baseUrl:s,trusted:!1,host:u,reason:"plaintext http downgrade"}:{baseUrl:s,trusted:!0,host:u}}if(String(process.env[fn]||"")==="1")return{baseUrl:s,trusted:!1,host:u};if(i)throw new Error(`${e}: refusing to call non-allowlisted host ${u} (set ${fn}=1 to permit it)`);return{baseUrl:s,trusted:!1,host:u}}function mn(e){let t=new URL(String(e));if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("unsupported protocol");return t.host}function Je(e,t,r){let n={...e};if(!r)return n;for(let[i,o]of Object.entries(t||{}))o&&(n[i]=o);return n}var fn,jt=R(()=>{fn="ORACLE_ALLOW_CUSTOM_PROVIDER_URL"});var En={};te(En,{ZEROX_API:()=>hn,zeroxHealth:()=>ia,zeroxPrepare:()=>aa,zeroxPrice:()=>yn,zeroxQuote:()=>et});function bn(e={}){return Xe({provider:"zerox",defaultUrl:hn,hosts:["api.0x.org"],url:e.baseUrl||process.env.ZEROX_API_URL})}function wn(e={}){return bn(e).baseUrl}function Ze(e={}){return e.apiKey||process.env.ZEROX_API_KEY||process.env.OX_API_KEY||process.env["0X_API_KEY"]||""}function gn(e={}){return Je({"0x-version":"v2",accept:"application/json"},{"0x-api-key":Ze(e)},bn(e).trusted)}async function ia(e={}){if(!Ze(e))return{ok:!1,configured:!1,error:"ZEROX_API_KEY not set"};try{let t=await yn({chainId:8453,sellToken:"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",buyToken:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",sellAmount:"1000000000000000"},e);return{ok:!0,configured:!0,buyAmount:t.buyAmount||t.grossBuyAmount}}catch(t){return{ok:!1,configured:!0,error:String(t.message||t).slice(0,160)}}}async function yn(e={},t={}){if(!Ze(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:i,sellAmount:o,taker:s}=e;if(!n||!i||!o)throw new Error("zeroxPrice requires sellToken, buyToken, sellAmount");let a=new URLSearchParams({chainId:String(r),sellToken:n,buyToken:i,sellAmount:String(o)});return s&&a.set("taker",s),T(`${wn(t)}/swap/allowance-holder/price?${a}`,{headers:gn(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function et(e={},t={}){if(!Ze(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:i,sellAmount:o,taker:s}=e;if(!n||!i||!o)throw new Error("zeroxQuote requires sellToken, buyToken, sellAmount");let a=re({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!a.executable)throw new Error(`0x: route requires ${a.requiredBps} bps above cap ${a.capBps}`);let u=new URLSearchParams({chainId:String(r),sellToken:n,buyToken:i,sellAmount:String(o),slippageBps:String(a.selectedBps)});s&&u.set("taker",s);let l=await T(`${wn(t)}/swap/allowance-holder/quote?${u}`,{headers:gn(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),p=l?.buyAmount||l?.grossBuyAmount;return p?D(l,{chainId:r,venue:l?.transaction?.to||l?.to||"0x",amountOut:p,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):{...l,autoSlippagePolicy:a}}async function aa(e={},t={}){if(!e.taker)throw new Error("0x: taker required for executable prepare");let r=await et(e,t),n=r?.transaction;if(!n?.to||!n?.data)throw new Error("0x: firm quote returned no transaction");let i=Number(e.chainId??8453),o=r?.issues?.allowance?.spender||r?.allowanceTarget;return F({provider:"zerox",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:i,quote:r,autoSlippage:r.autoSlippage,requiresApproval:r?.issues?.allowance?.actual!=null&&BigInt(r.issues.allowance.actual)<BigInt(e.sellAmount)?{token:e.sellToken,spender:o,amount:String(e.sellAmount)}:null,transaction:{chainId:i,from:e.taker,to:n.to,data:n.data,value:n.value??"0x0",...n.gas!=null?{gasLimit:n.gas}:{},slippageGuard:K(r.autoSlippage,{chainId:i,venue:n.to,data:n.data})}},{provider:"zerox",kind:"zerox-tx"})}var hn,zt=R(()=>{Y();ne();jt();X();hn="https://api.0x.org"});function An(e={}){return Xe({provider:"oneinch",defaultUrl:sa,hosts:["api.1inch.dev"],url:e.baseUrl||process.env.ONEINCH_API_URL})}function ca(e={}){return An(e).baseUrl}function Sn(e={}){return e.apiKey||process.env.ONEINCH_API_KEY||process.env.ONE_INCH_API_KEY||""}function ua(e={}){let t=Sn(e);return Je({accept:"application/json"},{Authorization:t?`Bearer ${t}`:""},An(e).trusted)}async function xn(e={},t={}){if(!Sn(t))throw new Error("ONEINCH_API_KEY required for 1inch");let r=Number(e.chainId??1),{src:n,dst:i,amount:o}=e;if(!n||!i||!o)throw new Error("oneinchQuote requires src, dst, amount");let s=new URLSearchParams({src:n,dst:i,amount:String(o)}),a=await T(`${ca(t)}/${r}/quote?${s}`,{headers:ua(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3});return a?.dstAmount?D(a,{chainId:r,venue:"1inch-quote",amountOut:a.dstAmount,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):a}var sa,vn=R(()=>{Y();ne();jt();X();sa="https://api.1inch.dev/swap/v6.0"});var lu,In=R(()=>{lu=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"})});import tt from"node:fs";import la from"node:os";import Se from"node:path";import{fileURLToPath as da}from"node:url";function Cn(){return process.env.ORACLE_FAKE_HOME||la.homedir()}function fa(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function rt(){return fa()?process.env.ORACLE_CONFIG_DIR||Se.join(Cn(),".config","oracle"):Se.join(Cn(),".config","oracle")}function ma(){return Se.join(rt(),"desk.json")}function ha(){return Se.join(rt(),"env")}function Ae({force:e=!1}={}){if(Ae._done&&!e)return Ae._result||null;Ae._done=!0;let t={},r=(i,o)=>{if(o==null)return;let s=String(o).trim();s&&(process.env[i]!=null&&String(process.env[i]).trim()!==""||(process.env[i]=s,t[i]=s))};try{let i=ha();if(tt.existsSync(i))for(let o of tt.readFileSync(i,"utf8").split(/\r?\n/)){let s=o.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let a=s[2];(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),r(s[1],a)}}catch{}try{let i=ma();if(tt.existsSync(i)){let o=JSON.parse(tt.readFileSync(i,"utf8"));o&&typeof o=="object"&&(r("ORACLE_DESK_URL",o.deskUrl||o.dataUrl||o.url),r("ORACLE_DATA_URL",o.dataUrl||o.deskUrl||o.url),r("ORACLE_API_URL",o.apiUrl||o.dataUrl||o.deskUrl),r("ORACLE_PUBLIC_URL",o.publicUrl||o.deskUrl||o.dataUrl),r("ORACLE_EXEC_URL",o.execUrl),r("MAD_DESK_URL",o.deskUrl||o.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),Ae._result=Object.keys(t).length?t:null,Ae._result}var pa,bu,kn=R(()=>{pa=Se.dirname(da(import.meta.url)),bu=Se.resolve(pa,"../..");try{Ae()}catch{}});var _n={};te(_n,{armPreparedAction:()=>xa,callSigner:()=>On,queueOwnerAction:()=>Nn});import{existsSync as ba,readFileSync as wa}from"node:fs";import{request as ga}from"node:http";import ya from"node:path";function Aa(e=process.env){let t=String(e.ORACLE_SIGNER_URL||Ea).replace(/\/$/,""),r;try{r=new URL(t)}catch{return null}return r.hostname!=="127.0.0.1"&&r.hostname!=="localhost"&&r.hostname!=="::1"?null:r.origin}function Sa(e=process.env){if(e.ORACLE_SIGNER_TOKEN)return String(e.ORACLE_SIGNER_TOKEN);let t=ya.join(rt(),"signer","signer-token");return ba(t)?wa(t,"utf8").trim():null}function On(e,{method:t="GET",body:r=null,env:n=process.env,timeoutMs:i=4e3}={}){let o=Aa(n),s=Sa(n);return!o||!s?Promise.resolve({ok:!1,error:"local signer is not running"}):new Promise(a=>{let u=new URL(e,o),l=r?Buffer.from(JSON.stringify(r)):null,p=ga({hostname:u.hostname,port:u.port||80,path:u.pathname,method:t,timeout:i,headers:{authorization:`Bearer ${s}`,origin:o,...l?{"content-type":"application/json","content-length":l.length}:{}}},d=>{let c=[];d.on("data",f=>c.push(f)),d.on("end",()=>{let f=Buffer.concat(c).toString("utf8"),m={};try{m=f?JSON.parse(f):{}}catch{m={error:"signer refused"}}a({httpStatus:d.statusCode,...m})})});p.on("timeout",()=>{p.destroy(),a({ok:!1,error:"local signer timed out"})}),p.on("error",()=>a({ok:!1,error:"local signer is not running"})),l&&p.write(l),p.end()})}async function Nn(e,t=process.env){if(!e||e.version!==1||!e.surface)throw new Error("queueOwnerAction: version-1 surface envelope required");return On("/pending",{method:"POST",body:{artifact:e},env:t,timeoutMs:8e3})}async function xa(e,t=process.env){let r=e?.localSignerEnvelope||e?.envelope;if(!r||r.version!==1||!r.surface)throw new Error("armPreparedAction: prepared.localSignerEnvelope v1 required");return Nn(r,t)}var Ea,Rn=R(()=>{kn();Ea="http://127.0.0.1:9462"});var qn={};te(qn,{COW_CANCEL_TYPES:()=>Ln,COW_HOSTS:()=>ot,COW_ORDER_TYPES:()=>nt,COW_SETTLEMENT:()=>Bn,COW_VAULT_RELAYER:()=>Tn,armCowOrder:()=>_a,buildArmedCowOrder:()=>Qt,cowCancelOrders:()=>Ua,cowChains:()=>Fa,cowHealth:()=>Oa,cowOrder:()=>Fn,cowOrderStatus:()=>Dn,cowOrderUid:()=>Ra,cowPrepareCancel:()=>$a,cowPrepareOrder:()=>Na,cowQuote:()=>_e,cowSignCancel:()=>La,cowSignOrder:()=>Ba,cowSubmitSignedOrder:()=>Ta,cowVerifyOrderFill:()=>Da});import{TypedDataEncoder as Wt,getAddress as Ne,isAddress as va}from"ethers";function it(e,t={}){if(t.baseUrl)return t.baseUrl.replace(/\/$/,"");let r=ot[Number(e)];if(!r)throw new Error(`cowswap: unsupported chainId ${e}`);return r}function Ia(e,t="v1",r={}){let n=it(e,r);return t==="v1"?n:n.replace(/\/api\/v1$/,`/api/${t}`)}function oe(e,t){let r=String(e||"").trim();if(!va(r))throw new Error(`cowswap: ${t} must be an address`);return Ne(r).toLowerCase()}function xe(e,t){try{let r=BigInt(String(e));if(r<0n)throw new Error("negative");return r.toString()}catch{throw new Error(`cowswap: ${t} must be a non-negative integer string`)}}function Un(e,t){let r=String(e||"").trim();if(!/^0x[0-9a-fA-F]{64}$/.test(r))throw new Error(`cowswap: ${t} must be bytes32 hex`);return r.toLowerCase()}function Pn(e,t="uid"){let r=String(e||"").trim();if(!/^0x[0-9a-fA-F]{112}$/.test(r))throw new Error(`cowswap: ${t} must be 56-byte order UID hex`);return r.toLowerCase()}function Ca({digest:e,owner:t,validTo:r}={}){let n=Un(e,"order digest").slice(2),i=oe(t,"owner").slice(2).toLowerCase(),o=Number(r);if(!Number.isInteger(o)||o<0||o>4294967295)throw new Error("cowswap: validTo must fit uint32");return`0x${n}${i}${o.toString(16).padStart(8,"0")}`.toLowerCase()}function Gt(e){let t=Bn[Number(e)];if(!t)throw new Error(`cowswap: settlement contract not registered for chain ${e}`);return{name:"Gnosis Protocol",version:"v2",chainId:Number(e),verifyingContract:Ne(t)}}function ka(e={},t,r){let n=oe(e.sellToken,"sellToken"),i=oe(e.buyToken,"buyToken"),o=oe(e.receiver||r,"receiver"),s=Number(e.validTo);if(!Number.isInteger(s)||s<=0)throw new Error("cowswap: quote.validTo required");let a=Un(e.appData||e.appDataHash||`0x${"0".repeat(64)}`,"appData");return{sellToken:n,buyToken:i,receiver:o,sellAmount:xe(e.sellAmount,"sellAmount"),buyAmount:xe(e.buyAmount,"buyAmount"),validTo:s,appData:a,feeAmount:xe(e.feeAmount??"0","feeAmount"),kind:String(e.kind||"sell"),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance||"erc20"),buyTokenBalance:String(e.buyTokenBalance||"erc20")}}async function Oa(e={}){try{let t=await _e({chainId:1,sellToken:Kt[1],buyToken:$n[1],sellAmountBeforeFee:"1000000000000000",from:se},e);return{ok:!0,buyAmount:t.quote?.buyAmount||t.buyAmount}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function _e(e={},t={}){let r=Number(e.chainId??1),n=Ut(e.from||e.owner),i=e.sellToken||Kt[r],o=e.buyToken||$n[r],s=String(e.sellAmountBeforeFee||e.sellAmount||"0");if(!i||!o||s==="0")throw new Error("cowQuote requires sellToken, buyToken, sellAmountBeforeFee");if(/eeeeeeee|native|^eth$/i.test(i)&&(i=Kt[r],!i))throw new Error("no WETH mapping for chain");let a={sellToken:i,buyToken:o,from:n,receiver:e.receiver||n,sellAmountBeforeFee:s,kind:e.kind||"sell",signingScheme:e.signingScheme||"eip1271"},u=await T(`${it(r,t)}/quote`,{method:"POST",body:a,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),l=u?.quote?.buyAmount||u?.buyAmount;return l?D(u,{chainId:r,venue:"cowswap-order",amountOut:l,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):u}async function Na(e={},t={}){let r=Number(e.chainId??1),n=oe(Ut(e.from||e.owner||e.signer),"owner"),i=await _e({...e,chainId:r,from:n,signingScheme:e.signingScheme||"eip712"},t),o=ka(i?.quote||i,r,n),s=Gt(r),a={domain:s,types:nt,primaryType:"Order",message:o},u=Wt.hash(s,nt,o),l=Tn[r];if(!l)throw new Error(`cowswap: vault relayer not registered for chain ${r}`);return F({provider:"cowswap",orderReady:!0,executionReady:!1,chainId:r,owner:n,signingScheme:"eip712",settlement:s.verifyingContract.toLowerCase(),vaultRelayer:Ne(l).toLowerCase(),quote:i,quoteId:i?.id??e.quoteId??null,typedData:a,cowGuard:{mode:"cow-order",version:1,provider:"cowswap",chainId:r,owner:n,settlement:s.verifyingContract.toLowerCase(),vaultRelayer:Ne(l).toLowerCase(),sellToken:o.sellToken,buyToken:o.buyToken,sellAmount:o.sellAmount,buyAmount:o.buyAmount,validTo:o.validTo,quoteId:i?.id??e.quoteId??null,typedDataHash:u,issuedAtMs:Date.now(),expiresAtMs:Math.min(o.validTo*1e3,Date.now()+2e4)},requiresApproval:{token:o.sellToken,spender:Ne(l).toLowerCase(),amount:o.sellAmount},localSignerEnvelope:Qt({chainId:r,owner:n,typedData:a,quoteId:i?.id??e.quoteId??null,cowGuard:{expiresAtMs:Math.min(o.validTo*1e3,Date.now()+2e4)}})},{provider:"cowswap",kind:"cow-order"})}function Qt(e={},t={}){let r=e.typedData;if(!r?.domain||!r?.types||!r?.message)throw new Error("cowswap: typedData required to arm");let n=Number(e.chainId??r.domain.chainId),i=ot[n];if(!i)throw new Error(`cowswap: unsupported chainId ${n}`);let o=oe(e.owner,"owner"),s=Number(t.nowMs??Date.now()),a=Wt.hash(r.domain,r.types,r.message);return Object.freeze({tradeId:`cow:${n}:${a.slice(2)}`,version:1,surface:"evm-order",action:"order",owner:o,destination:"cowswap",chainId:n,expiresAtMs:Number(e.cowGuard?.expiresAtMs??s+2e4),slippageBps:0,fee:{oracleFeeBps:0},artifact:Object.freeze({kind:"cow",chainId:n,submitTo:`${i}/orders`,quoteId:e.quoteId??null,domain:r.domain,types:r.types,message:r.message,typedData:r})})}async function _a(e={},t={}){let{queueOwnerAction:r}=await Promise.resolve().then(()=>(Rn(),_n)),n=e.localSignerEnvelope||Qt(e,t);return{...await r(n,t.env),envelope:n,execution:"armed-local",exec:!1}}async function Dn(e={},t={}){let r=Number(e.chainId??1),n=String(e.uid||e.orderUid||"").trim();if(!n)throw new Error("cowOrderStatus requires uid");return T(`${it(r,t)}/orders/${encodeURIComponent(n)}/status`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function Fn(e={},t={}){let r=Number(e.chainId??1),n=String(e.uid||e.orderUid||"").trim();if(!n)throw new Error("cowOrder requires uid");return T(`${it(r,t)}/orders/${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}function Ra(e={}){let t=e.typedData||e,r=Number(e.chainId??t?.domain?.chainId),n=t?.message||e.order||e.message;if(!n)throw new Error("cowswap: typed order message required");let i=e.cowGuard?.typedDataHash||Wt.hash(Gt(r),nt,n),o=e.owner||e.from||e.signer||n.receiver;return Ca({digest:i,owner:o,validTo:n.validTo})}async function Ba(e={},t={}){throw new Error("cowswap.cowSignOrder refused: @oracle-agent/oracle is prepare-only. Sign with the user wallet; do not pass private keys here.")}async function Ta(e={},t={}){throw new Error("cowswap.cowSubmitSignedOrder refused: @oracle-agent/oracle is prepare-only. Submit signed orders from the user wallet or local operator.")}function $a(e={}){let t=Number(e.chainId??1),r=oe(e.owner||e.from||e.signer,"owner"),n=(e.orderUids||e.uids||[e.uid]).filter(Boolean).map((s,a)=>Pn(s,`orderUids[${a}]`));if(!n.length)throw new Error("cowswap: orderUids required");let i=Gt(t);return F({provider:"cowswap",chainId:t,owner:r,orderUids:n,signingScheme:"eip712",typedData:{domain:i,types:Ln,primaryType:"OrderCancellations",message:{orderUids:n}},cancelReady:!0,executableArtifact:!0},{provider:"cowswap",kind:"cow-cancel"})}async function La(e={},t={}){throw new Error("cowswap.cowSignCancel refused: @oracle-agent/oracle is prepare-only. Cancel-sign with the user wallet.")}async function Ua(e={},t={}){throw new Error("cowswap.cowCancelOrders refused: @oracle-agent/oracle is prepare-only. Cancel from the user wallet or local operator.")}function Pa(e={}){return xe(e.buyAmount??e.executedBuyAmount??"0","trade.buyAmount")}async function Da(e={},t={}){let r=Number(e.chainId??1),n=Pn(e.uid||e.orderUid),i=t.order||await Fn({chainId:r,uid:n},t),o=t.status||i.status||await Dn({chainId:r,uid:n},t).catch(()=>null),s=t.trades||await T(`${Ia(r,"v2",t)}/trades?orderUid=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),a=Array.isArray(s)?s:[],u=e.expectedOwner?oe(e.expectedOwner,"expectedOwner"):null;if(u&&oe(i.owner||a[0]?.owner||u,"owner")!==u)return{ok:!1,provider:"cowswap",chainId:r,uid:n,reason:"owner mismatch",order:i,status:o,trades:a};let l=0n;for(let c of a.filter(f=>String(f.orderUid||"").toLowerCase()===n))l+=BigInt(Pa(c));l===0n&&i.executedBuyAmount!=null&&(l=BigInt(xe(i.executedBuyAmount,"executedBuyAmount")));let p=e.minBuyAmount!=null?BigInt(xe(e.minBuyAmount,"minBuyAmount")):0n,d=l>=p&&String(i.status||o?.status||"").toLowerCase()!=="expired";return{ok:d,provider:"cowswap",chainId:r,uid:n,status:i.status||o?.status||null,executedBuyAmount:l.toString(),minBuyAmount:e.minBuyAmount??null,trades:a,settlementTxs:[...new Set(a.map(c=>c.txHash).filter(Boolean))],order:i,orderStatus:o,reason:d?null:"insufficient fill or expired order"}}function Fa(){return Object.keys(ot).map(Number)}var ot,Bn,Tn,Kt,$n,nt,Ln,Yt=R(()=>{Y();ne();In();We();X();ot={1:"https://api.cow.fi/mainnet/api/v1",100:"https://api.cow.fi/xdai/api/v1",42161:"https://api.cow.fi/arbitrum_one/api/v1",8453:"https://api.cow.fi/base/api/v1"},Bn=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),Tn=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"}),Kt={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"},$n={1:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",42161:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},nt=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"}]}),Ln=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]})});function at(e){return qa.get(Number(e))||null}function Hn(e,t=process.env){let r=at(e);if(!r)return null;for(let n of r.rpcEnv){let i=(t[n]||"").trim();if(i)return i}return null}var Mn,qa,Xt=R(()=>{Mn={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}},qa=new Map(Object.values(Mn).map(e=>[e.chainId,e]))});import{Interface as Ma,getAddress as Ha}from"ethers";function jn(e,t){try{return Ha(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}function ja(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=Hn(e,r);return n||Va[Number(e)]||null}function Ka(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!za.test(r))throw new Error(`evm-rpc: ${t} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}async function P(e,t,r=[],n={}){let i=String(t||"");Ka(i);let o=ja(e,n);if(!o)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let a=await T(o,{method:"POST",body:{jsonrpc:"2.0",id:1,method:t,params:r},fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs??12e3,signal:n.signal});if(a?.error){let u=new Error(a.error.message||JSON.stringify(a.error));throw u.code=a.error.code,u}return a.result}async function zn(e,t={}){let r=await P(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function Kn(e,t={}){let r=await P(e,"eth_gasPrice",[],t);if(r==null)return null;try{return BigInt(r)}catch{return null}}async function Wn(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await P(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function Gn(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=jn(e.token||e.tokenAddress,"token"),i=jn(e.account||e.owner||e.address,"account"),o=Vn.encodeFunctionData("balanceOf",[i]),s=await P(r,"eth_call",[{to:n,data:o},e.blockTag||"latest"],t),a=Vn.decodeFunctionResult("balanceOf",s),u=BigInt(a[0]);return{chainId:r,token:n,account:i,balance:u.toString(),balanceHex:`0x${u.toString(16)}`,blockTag:e.blockTag||"latest"}}var Vn,Va,za,he=R(()=>{Y();Xt();Vn=new Ma(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);Va={1:"https://ethereum.publicnode.com",137:"https://polygon-bor-rpc.publicnode.com",42161:"https://arbitrum-one-rpc.publicnode.com",8453:"https://base-rpc.publicnode.com",10:"https://optimism-rpc.publicnode.com",988:"https://rpc.stable.xyz",56:"https://bsc-rpc.publicnode.com",43114:"https://avalanche-c-chain-rpc.publicnode.com",999:"https://rpc.hyperliquid.xyz/evm",2741:"https://api.mainnet.abs.xyz",4663:"https://rpc.mainnet.chain.robinhood.com"};za=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/});function Qn(e,t){let r=String(e||"").toLowerCase(),n=String(t?.quote||t?.quoteToken?.address||"").toLowerCase(),i=String(t?.base||t?.baseToken?.address||"").toLowerCase();return n===r?{address:t.base||t.baseToken?.address,symbol:t.baseToken?.symbol}:i===r?{address:t.quote||t.quoteToken?.address,symbol:t.quoteToken?.symbol}:{address:t.quote||t.quoteToken?.address,symbol:t.quoteToken?.symbol}}function Jt(e,t=[],{stables:r=[],wrappedNative:n=null}={}){let i=String(e||"").toLowerCase(),o=new Set((r||[]).map(u=>String(u).toLowerCase())),s=String(n||"").toLowerCase(),a=(t||[]).map((u,l)=>{let p=Qn(i,u),d=String(p.address||"").toLowerCase(),c=String(p.symbol||"").toLowerCase(),f=Number(u.liquidityUsd??u.liquidity?.usd),m=Number.isFinite(f)?f:0,b=String(u.dex||u.dexId||"").toLowerCase(),h=0;return o.has(d)||Wa.has(c)?h=300:s&&d===s&&(h=100),b.includes("v4")?h+=20:b.includes("v3")?h+=10:(b.includes("v2")||b.includes("raydium")||b.includes("orca")||b.includes("meteora"))&&(h+=8),{pool:u,score:h*1e12+m,index:l,otherAddr:d,liquidityUsd:m}});return a.sort((u,l)=>l.score-u.score||u.index-l.index),a.map(u=>u.pool)}function Yn(e,t=[]){let r=Array.isArray(t)?t:[];return r.length&&Qn(e,r[0]).address||null}var Wa,Zt=R(()=>{Wa=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"])});function Xa(e,t,r){let n=W(t),i=W(r),o=W(e?.baseToken?.address),s=W(e?.quoteToken?.address);return o===n&&s===i||o===i&&s===n}function Ja(e){let t=Number(e?.liquidity?.usd);return Number.isFinite(t)&&t>=0?t:null}function Za(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||Ga).replace(/\/$/,"")}async function er(e,t={}){if(!e)throw new Error("tokenAddress required");return T(`${Za(t)}/latest/dex/tokens/${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}async function Xn({chainId:e,tokenA:t,tokenB:r,dexIds:n=[]}={},i={}){return(await Re({chainId:e,tokenA:t,tokenB:r,dexIds:n},i))[0]??null}async function Re({chainId:e,tokenA:t,tokenB:r,dexIds:n=[]}={},i={}){if(e==null||!t||!r)throw new Error("chainId, tokenA, and tokenB required");let o=W(Qa[Number(e)]||e),s=new Set(Ya(n).filter(Boolean).map(W)),a=[...new Set([t,r].map(c=>String(c)).filter(Boolean))],u=await Promise.allSettled(a.map(c=>er(c,{...i,baseUrl:i.dexscreenerBaseUrl,timeoutMs:i.dexscreenerTimeoutMs??Math.min(Number(i.timeoutMs??4e3),4e3)}))),l=new Set,p=[];for(let c of u)if(c.status==="fulfilled")for(let f of c.value?.pairs||c.value?.data?.pairs||[]){let m=`${W(f?.chainId)}:${W(f?.dexId)}:${W(f?.pairAddress)}`;l.has(m)||(l.add(m),p.push(f))}return p.filter(c=>W(c?.chainId)===o).filter(c=>Xa(c,t,r)).filter(c=>!s.size||s.has(W(c?.dexId))).map(c=>({pairAddress:c.pairAddress??null,dexId:c.dexId??null,chainId:c.chainId??null,liquidityUsd:Ja(c),pairCreatedAt:c.pairCreatedAt??null})).filter(c=>c.liquidityUsd!=null).sort((c,f)=>f.liquidityUsd-c.liquidityUsd)}var Ga,Qa,W,Ya,st=R(()=>{Y();Zt();Ga="https://api.dexscreener.com",Qa=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"}),W=e=>String(e??"").toLowerCase(),Ya=e=>Array.isArray(e)?e:e==null?[]:[e]});var ao={};te(ao,{PANCAKE_FEE_TIERS:()=>ct,UNI_V3_CHAINS:()=>j,UNI_V3_FEE_TIERS:()=>to,UNI_V3_VENUES:()=>oo,uniV3Chains:()=>as,uniV3EthUsdc:()=>io,uniV3Health:()=>is,uniV3PrepareExactIn:()=>os,uniV3QuoteExactIn:()=>Te,uniV3QuoteExactInPath:()=>ns});import{Interface as Zn,getAddress as Be,isAddress as eo}from"ethers";function rr(e,t){let r=Number(e),n=j[r];if(!n)throw new Error(`uniswap-v3: unsupported chainId ${e} (supported: ${Object.keys(j).join(", ")})`);let i=oo[r]||{};if(!t){if(!n.quoter||!n.router){let u=Object.keys(i).join(", ")||"none registered";throw new Error(`uniswap-v3: chain ${r} (${n.name}) has no canonical Uniswap v3 deployment -- name a venue explicitly (known: ${u})`)}return{chainId:r,venue:n.name,...n}}let o=String(t).toLowerCase();if(o===n.name&&n.quoter&&n.router)return{chainId:r,venue:n.name,...n};let s=i,a=s[o];if(!a){let u=[...n.quoter&&n.router?[n.name]:[],...Object.keys(s)].join(", ");throw new Error(`uniswap-v3: unknown venue "${t}" on chain ${r} (known: ${u})`)}return{chainId:r,venue:o,...n,quoter:a.quoter,router:a.router,feeTiers:a.feeTiers||null}}function tr(e,t){let r=j[Number(t)];if(!e||e===ro||e===no||/^eth$/i.test(String(e)))return Be(r.weth);let n=String(e);if(/^weth$/i.test(n))return Be(r.weth);if(/^usdc$/i.test(n))return Be(r.usdc);if(!eo(n))throw new Error(`invalid token address: ${e}`);return Be(n)}function ts(e){let t=String(e||"uniswap").toLowerCase();return t==="uniswap"?["uniswap-v3","uniswap"]:t==="pancakeswap"?["pancakeswap-v3","pancakeswap"]:t==="hyperswap"?["hyperswap-v3","hyperswap"]:[t,`${t}-v3`]}function rs(e,t){if(e.length!==t.length+1)throw new Error("path: fees.length must be tokens.length - 1");let r="0x";for(let n=0;n<t.length;n++)r+=e[n].slice(2).toLowerCase(),r+=Number(t[n]).toString(16).padStart(6,"0");return r+=e[e.length-1].slice(2).toLowerCase(),r}async function Te(e={},t={}){let{chainId:r,quoter:n,router:i,feeTiers:o}=rr(e.chainId??8453,e.venue),s=tr(e.tokenIn||"WETH",r),a=tr(e.tokenOut||j[r].usdc,r),u=BigInt(e.amountIn??0);if(u<=0n)throw new Error("amountIn required (raw base units)");let l=o&&o.length?o:to,p=e.fee!=null?[Number(e.fee)]:e.tryFees===!1?[l[Math.min(2,l.length-1)]]:[...l],d=[],c=null;for(let E of p){let y=ut.encodeFunctionData("quoteExactInputSingle",[{tokenIn:s,tokenOut:a,amountIn:u,fee:E,sqrtPriceLimitX96:0n}]);try{let w=await P(r,"eth_call",[{to:n,data:y},"latest"],t);if(!w||w==="0x"){d.push({fee:E,ok:!1,error:"empty result"});continue}let A=ut.decodeFunctionResult("quoteExactInputSingle",w),I={fee:E,ok:!0,amountOut:A[0].toString(),sqrtPriceX96After:A[1].toString(),initializedTicksCrossed:Number(A[2]),gasEstimate:A[3].toString()};d.push(I),(!c||BigInt(I.amountOut)>BigInt(c.amountOut))&&(c=I)}catch(w){d.push({fee:E,ok:!1,error:String(w.message||w).slice(0,160)})}}if(!c){let E=d.map(y=>`${y.fee}:${y.error||"fail"}`).join("; ");throw new Error(`uniswap-v3 quote failed chain=${r}: ${E}`)}let f=e.liquidityUsd==null?await Re({chainId:r,tokenA:s,tokenB:a,dexIds:ts(e.venue)},t).catch(()=>[]):[],m={};for(let E of f.slice(0,8))if(!(!E.pairAddress||!eo(E.pairAddress)))try{let y=await P(r,"eth_call",[{to:E.pairAddress,data:es},"latest"],t),w=y&&y!=="0x"&&y.length<=66?Number.parseInt(y,16):NaN;if(!Number.isFinite(w)||w<=0||w>1e6)continue;(m[w]==null||E.liquidityUsd>m[w].liquidityUsd)&&(m[w]=E)}catch{}let b=e.liquidityBandBps==null?50:Number(e.liquidityBandBps),h=null;if(e.fee==null&&b>0&&BigInt(c.amountOut)>0n){let E=BigInt(c.amountOut),w=d.filter(A=>A.ok&&Number((E-BigInt(A.amountOut))*10000n/E)<=b).filter(A=>m[A.fee]?.liquidityUsd!=null).sort((A,I)=>m[I.fee].liquidityUsd-m[A.fee].liquidityUsd)[0];w&&w.fee!==c.fee&&(h={priceBestFee:c.fee,chosenFee:w.fee,chosenPoolUsd:m[w.fee].liquidityUsd,bandBps:b},c=w)}let x=m[c.fee]??null,v=f[0]??null,k=x??v,S=e.liquidityUsd??x?.liquidityUsd??v?.liquidityUsd??null,C=e.liquidityUsd!=null?"caller":x?"pool":v?"pair":null;return D({venue:"uniswap-v3",chainId:r,chain:j[r].name,quoter:n,tokenIn:s,tokenOut:a,amountIn:u.toString(),fee:c.fee,amountOut:c.amountOut,gasEstimate:c.gasEstimate,liquidityUsd:S,liquiditySource:k,liquidityAttribution:C,liquidityPick:h,sqrtPriceX96After:c.sqrtPriceX96After,initializedTicksCrossed:c.initializedTicksCrossed,triedFees:d,best:!0},{chainId:r,venue:i,amountOut:c.amountOut,liquidityUsd:S,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function ns(e={},t={}){let{chainId:r,quoter:n,router:i}=rr(e.chainId??8453),o=(e.tokens||[]).map(c=>tr(c,r)),s=(e.fees||[]).map(Number);if(o.length<2)throw new Error("tokens[] need at least 2 addresses");let a=BigInt(e.amountIn??0);if(a<=0n)throw new Error("amountIn required");let u=rs(o,s),l=ut.encodeFunctionData("quoteExactInput",[u,a]),p=await P(r,"eth_call",[{to:n,data:l},"latest"],t),d=ut.decodeFunctionResult("quoteExactInput",p);return D({venue:"uniswap-v3",chainId:r,chain:j[r].name,quoter:n,tokens:o,fees:s,path:u,amountIn:a.toString(),amountOut:d[0].toString(),gasEstimate:d[3].toString()},{chainId:r,venue:i,amountOut:d[0].toString(),liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function io(e={},t={}){let r=Number(e.chainId??8453),n=e.amountIn??"1000000000000000",i=await Te({chainId:r,tokenIn:j[r].weth,tokenOut:j[r].usdc,amountIn:n,fee:e.fee},t),o=Number(i.amountOut)/1e6;return{...i,amountOutUsdc:o,pair:"WETH/USDC"}}async function os(e={},t={}){let r=Number(e.chainId??8453),n=rr(r,e.venue),i=Be(e.recipient),o=String(e.tokenIn||"WETH"),s=!e.tokenIn||o===ro||o===no||/^eth$/i.test(o),a=await Te(e,t),u=Jn.encodeFunctionData("exactInputSingle",[{tokenIn:a.tokenIn,tokenOut:a.tokenOut,fee:a.fee,recipient:i,amountIn:BigInt(a.amountIn),amountOutMinimum:BigInt(a.amountOutMinimum),sqrtPriceLimitX96:0n}]),l=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),d=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+l,c=Jn.encodeFunctionData("multicall",[d,[u]]);return F({provider:"uniswap-v3",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,deadline:d,quote:a,autoSlippage:a.autoSlippage,requiresApproval:s?null:{token:a.tokenIn,spender:n.router,amount:a.amountIn},transaction:{chainId:r,from:i,to:n.router,data:c,value:s?a.amountIn:"0",slippageGuard:K(a.autoSlippage,{chainId:r,venue:n.router,data:c})}},{provider:"uniswap-v3",kind:"univ3-swap-tx"})}async function is(e={}){let t=Number(e.chainId??8453);try{let r=await io({chainId:t,amountIn:"1000000000000000"},e);return{ok:!0,chainId:t,fee:r.fee,amountOutUsdc:r.amountOutUsdc,midPxHint:r.amountOutUsdc/.001}}catch(r){return{ok:!1,chainId:t,error:String(r.message||r).slice(0,200)}}}async function as(){return Object.entries(j).map(([e,t])=>({chainId:Number(e),name:t.name,quoter:t.quoter,weth:t.weth,usdc:t.usdc}))}var j,to,es,ut,Jn,ro,no,ct,oo,lt=R(()=>{he();st();ne();X();j={1:{name:"ethereum",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",usdc:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},8453:{name:"base",quoter:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",router:"0x2626664c2603336E57B271c5C0b26F421741e481",weth:"0x4200000000000000000000000000000000000006",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"},42161:{name:"arbitrum",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",usdc:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},4663:{name:"robinhood",quoter:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",router:"0xcaf681a66d020601342297493863e78c959e5cb2",weth:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",usdc:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"},999:{name:"hyperevm",weth:"0x5555555555555555555555555555555555555555",usdc:"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb"},10:{name:"optimism",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x4200000000000000000000000000000000000006",usdc:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"},56:{name:"bsc",quoter:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",router:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",weth:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",usdc:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"},137:{name:"polygon",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",usdc:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"},43114:{name:"avalanche",quoter:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",router:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",weth:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",usdc:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"}},to=[100,500,3e3,1e4],es="0xddca3f43",ut=new Zn(["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)"]),Jn=new Zn(["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)"]),ro="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",no="0x0000000000000000000000000000000000000000",ct=[100,500,2500,1e4],oo={56:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ct}},8453:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ct}},42161:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ct}},999:{hyperswap:{name:"hyperswap",quoter:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",router:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D"}}}});var uo={};te(uo,{UNI_V4_CHAINS:()=>G,UNI_V4_FEE_TIERS:()=>ir,computeV4PoolId:()=>ft,decodeV4HookPermissions:()=>sr,uniV4Chains:()=>ys,uniV4Health:()=>Es,uniV4InspectHook:()=>bs,uniV4PrepareExactIn:()=>gs,uniV4QuoteExactIn:()=>mt,uniV4QuoteExactOut:()=>ws});import{AbiCoder as ss,Interface as nr,getAddress as J,isAddress as or,keccak256 as cs}from"ethers";function sr(e){let t=Pe(e),r=Number(BigInt(t)&ls),n=Object.fromEntries(so.map(([s,a])=>[a,!!(r&1<<s)])),o=[["beforeSwapReturnsDelta","beforeSwap"],["afterSwapReturnsDelta","afterSwap"],["afterAddLiquidityReturnsDelta","afterAddLiquidity"],["afterRemoveLiquidityReturnsDelta","afterRemoveLiquidity"]].filter(([s,a])=>n[s]&&!n[a]).map(([s,a])=>`${s} requires ${a}`);return Object.freeze({address:t,mask:r,maskHex:`0x${r.toString(16).padStart(4,"0")}`,flags:Object.freeze(n),enabled:Object.freeze(so.filter(([,s])=>n[s]).map(([,s])=>s)),valid:o.length===0,violations:Object.freeze(o)})}function Ue(e){let t=Number(e),r=G[t];if(!r)throw new Error(`uniswap-v4: unsupported chainId ${e} (supported: ${Object.keys(G).join(", ")})`);return{chainId:t,...r}}function Pe(e){if(e==null||e==="")return H;let t=String(e);if(!or(t))throw new Error(`invalid Uniswap V4 hook address: ${e}`);return J(t)}function ve(e,t){let r=G[Number(t)];if(Le(e))return J(r.weth);let n=String(e);if(/^weth$/i.test(n))return J(r.weth);if(/^usdc$/i.test(n)||/^usdg$/i.test(n))return J(r.usdc);if(!or(n))throw new Error(`invalid token address: ${e}`);return J(n)}function Le(e){let t=String(e||"").trim().toLowerCase();return!t||t===ms.toLowerCase()||t===H.toLowerCase()||t==="eth"}function ft({currency0:e,currency1:t,fee:r,tickSpacing:n,hooks:i=H}){let o=J(e),s=J(t);if(o.toLowerCase()===s.toLowerCase())throw new Error("poolKey currencies must differ");let[a,u]=o.toLowerCase()<s.toLowerCase()?[o,s]:[s,o],l=Pe(i);return cs($e.encode(["address","address","uint24","int24","address"],[a,u,Number(r),Number(n),l]))}function cr({tokenIn:e,tokenOut:t,fee:r,tickSpacing:n,hooks:i=H}){let o=J(e),s=J(t),[a,u]=o.toLowerCase()<s.toLowerCase()?[o,s]:[s,o],l=o.toLowerCase()===a.toLowerCase();return{poolKey:{currency0:a,currency1:u,fee:Number(r),tickSpacing:Number(n),hooks:Pe(i)},zeroForOne:l}}function hs({hook:e,codePresent:t,initialized:r,dynamicFee:n}){let i=sr(e),o=i.enabled.some(l=>l.endsWith("ReturnsDelta")),s=i.flags.beforeSwap||i.flags.afterSwap||i.flags.beforeDonate||i.flags.afterDonate,a=[],u="none";return e!==H&&(u="low",a.push("nonzero hook requires independent contract review")),n&&(u="medium",a.push("pool uses a dynamic LP fee")),s&&(u="medium",a.push("hook runs during swap or donate flow")),o&&(u="high",a.push("hook can return custom accounting deltas")),i.valid||(u="critical",a.push(...i.violations)),n&&e===H&&(u="critical",a.push("dynamic-fee pool has no hook authority")),e!==H&&i.enabled.length===0&&(u="critical",a.push("nonzero hook declares no permissions")),r||(u="critical",a.push("pool is not initialized")),e!==H&&!t&&(u="critical",a.push("hook address has no deployed bytecode")),Object.freeze({tier:u,audited:!1,requiresReview:e!==H,returnsDelta:o,reasons:Object.freeze(a)})}async function bs(e={},t={}){let r=Ue(e.chainId??8453);if(!r.stateView)throw new Error(`uniswap-v4: no StateView on chain ${r.chainId}`);let n=ve(e.tokenIn||"WETH",r.chainId),i=ve(e.tokenOut||r.usdc,r.chainId),o=Number(e.fee),s=Number(e.tickSpacing);if(!Number.isInteger(o)||o<0||o>16777215)throw new Error("uniswap-v4 inspectHook requires uint24 fee");if(!Number.isInteger(s)||s<-8388608||s>8388607)throw new Error("uniswap-v4 inspectHook requires int24 tickSpacing");let a=Pe(e.hooks),{poolKey:u}=cr({tokenIn:n,tokenOut:i,fee:o,tickSpacing:s,hooks:a}),l=ft(u),p=t.rpcCall||P,d=dt.encodeFunctionData("getSlot0",[l]),c=dt.encodeFunctionData("getLiquidity",[l]),[f,m,b]=await Promise.all([p(r.chainId,"eth_call",[{to:r.stateView,data:d},"latest"],t),p(r.chainId,"eth_call",[{to:r.stateView,data:c},"latest"],t),a===H?Promise.resolve(null):p(r.chainId,"eth_getCode",[a,"latest"],t)]),h=dt.decodeFunctionResult("getSlot0",f),x=dt.decodeFunctionResult("getLiquidity",m)[0],v=h[0],k=v>0n,S=a===H?null:typeof b=="string"&&b!=="0x"&&b.length>4,C=!!(o&ar),E=hs({hook:a,codePresent:S,initialized:k,dynamicFee:C});return Object.freeze({venue:"uniswap-v4",chainId:r.chainId,stateView:r.stateView,poolId:l,poolKey:Object.freeze(u),pool:Object.freeze({initialized:k,sqrtPriceX96:v.toString(),tick:Number(h[1]),protocolFee:Number(h[2]),lpFee:Number(h[3]),liquidity:x.toString(),dynamicFee:C}),hook:Object.freeze({address:a,codePresent:S,codeBytes:S?(b.length-2)/2:0,permissions:sr(a)}),risk:E})}async function mt(e={},t={}){let{chainId:r,quoter:n,poolManager:i,universalRouter:o}=Ue(e.chainId??8453),s=ve(e.tokenIn||"WETH",r),a=ve(e.tokenOut||G[r].usdc,r),u=BigInt(e.amountIn??0);if(u<=0n)throw new Error("amountIn required (raw base units)");if(u>0xffffffffffffffffffffffffffffffffn)throw new Error("amountIn exceeds uint128");let l=e.fee!=null&&e.tickSpacing!=null?[{fee:Number(e.fee),tickSpacing:Number(e.tickSpacing)}]:e.tryTiers===!1?[{fee:500,tickSpacing:10}]:[...ir],p=e.hooks||H,d=[],c=null;for(let y of l){let{poolKey:w,zeroForOne:A}=cr({tokenIn:s,tokenOut:a,fee:y.fee,tickSpacing:y.tickSpacing,hooks:p}),I=pt.encodeFunctionData("quoteExactInputSingle",[{poolKey:w,zeroForOne:A,exactAmount:u,hookData:"0x"}]);try{let N=await(t.rpcCall||P)(r,"eth_call",[{to:n,data:I},"latest"],t);if(!N||N==="0x"){d.push({...y,ok:!1,error:"empty result"});continue}let U=pt.decodeFunctionResult("quoteExactInputSingle",N),$={fee:y.fee,tickSpacing:y.tickSpacing,ok:!0,amountOut:U[0].toString(),gasEstimate:U[1].toString(),poolKey:w,zeroForOne:A,poolId:ft({...w})};d.push($),(!c||BigInt($.amountOut)>BigInt(c.amountOut))&&(c=$)}catch(N){d.push({...y,ok:!1,error:String(N.message||N).slice(0,160)})}}if(!c){let y=d.map(w=>`${w.fee}/${w.tickSpacing}:${w.error||"fail"}`).join("; ");throw new Error(`uniswap-v4 quote failed chain=${r}: ${y}`)}let f=e.liquidityUsd==null?await Re({chainId:r,tokenA:s,tokenB:a,dexIds:co},t).catch(()=>[]):[],m=new Map;for(let y of f){let w=String(y.pairAddress||"").toLowerCase();w&&m.set(w,y)}let b=y=>m.get(String(y.poolId||"").toLowerCase())??null,h=e.liquidityBandBps==null?50:Number(e.liquidityBandBps),x=null;if(!(e.fee!=null&&e.tickSpacing!=null)&&h>0&&BigInt(c.amountOut)>0n){let y=BigInt(c.amountOut),A=d.filter(I=>I.ok&&Number((y-BigInt(I.amountOut))*10000n/y)<=h).filter(I=>b(I)?.liquidityUsd!=null).sort((I,N)=>b(N).liquidityUsd-b(I).liquidityUsd)[0];A&&A.poolId!==c.poolId&&(x={priceBestFee:c.fee,chosenFee:A.fee,chosenPoolUsd:b(A).liquidityUsd,bandBps:h},c=A)}let v=b(c),k=f[0]??null,S=v??k,C=e.liquidityUsd??v?.liquidityUsd??k?.liquidityUsd??null,E=e.liquidityUsd!=null?"caller":v?"pool":k?"pair":null;return D({venue:"uniswap-v4",chainId:r,chain:G[r].name,poolManager:i,quoter:n,universalRouter:o||null,tokenIn:s,tokenOut:a,amountIn:u.toString(),fee:c.fee,tickSpacing:c.tickSpacing,hooks:c.poolKey.hooks,poolId:c.poolId,zeroForOne:c.zeroForOne,amountOut:c.amountOut,gasEstimate:c.gasEstimate,liquidityUsd:C,liquiditySource:S,liquidityAttribution:E,liquidityPick:x,triedTiers:d,best:!0,executionReady:!1,prepareReady:typeof e.recipient=="string"&&or(e.recipient)&&Number.isInteger(Number(e.slippageBps))&&Number(e.slippageBps)>=0&&Number(e.slippageBps)<=100&&Number.isInteger(Number(e.deadlineSeconds))&&Number(e.deadlineSeconds)>=30&&Number(e.deadlineSeconds)<=600&&!Le(e.tokenIn)&&!Le(e.tokenOut)&&(e.hookData==null||String(e.hookData).toLowerCase()==="0x")&&c.poolKey.hooks===H&&!(c.fee&ar)},{chainId:r,venue:o||n,amountOut:c.amountOut,liquidityUsd:C,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function ws(e={},t={}){let{chainId:r,quoter:n,poolManager:i,universalRouter:o}=Ue(e.chainId??8453),s=ve(e.tokenIn||"WETH",r),a=ve(e.tokenOut||G[r].usdc,r),u=BigInt(e.amountOut??0);if(u<=0n)throw new Error("amountOut required (raw base units)");if(u>0xffffffffffffffffffffffffffffffffn)throw new Error("amountOut exceeds uint128");let l=e.fee!=null&&e.tickSpacing!=null?[{fee:Number(e.fee),tickSpacing:Number(e.tickSpacing)}]:e.tryTiers===!1?[{fee:500,tickSpacing:10}]:[...ir],p=e.hooks||H,d=[],c=null;for(let m of l){let{poolKey:b,zeroForOne:h}=cr({tokenIn:s,tokenOut:a,fee:m.fee,tickSpacing:m.tickSpacing,hooks:p}),x=pt.encodeFunctionData("quoteExactOutputSingle",[{poolKey:b,zeroForOne:h,exactAmount:u,hookData:"0x"}]);try{let v=await(t.rpcCall||P)(r,"eth_call",[{to:n,data:x},"latest"],t);if(!v||v==="0x"){d.push({...m,ok:!1,error:"empty result"});continue}let k=pt.decodeFunctionResult("quoteExactOutputSingle",v),S={fee:m.fee,tickSpacing:m.tickSpacing,ok:!0,amountIn:k[0].toString(),gasEstimate:k[1].toString(),poolKey:b,zeroForOne:h,poolId:ft({...b})};d.push(S),(!c||BigInt(S.amountIn)<BigInt(c.amountIn))&&(c=S)}catch(v){d.push({...m,ok:!1,error:String(v.message||v).slice(0,160)})}}if(!c){let m=d.map(b=>`${b.fee}/${b.tickSpacing}:${b.error||"fail"}`).join("; ");throw new Error(`uniswap-v4 exact-output quote failed chain=${r}: ${m}`)}let f=e.liquidityUsd==null?await Xn({chainId:r,tokenA:s,tokenB:a,dexIds:co},t).catch(()=>null):null;return{venue:"uniswap-v4",chainId:r,chain:G[r].name,poolManager:i,quoter:n,universalRouter:o||null,tokenIn:s,tokenOut:a,amountIn:c.amountIn,amountOut:u.toString(),gasEstimate:c.gasEstimate,fee:c.fee,tickSpacing:c.tickSpacing,hooks:c.poolKey.hooks,poolId:c.poolId,zeroForOne:c.zeroForOne,liquidityUsd:e.liquidityUsd??f?.liquidityUsd??null,liquiditySource:f,triedTiers:d,best:!0,executionReady:!1,prepareReady:!1}}async function gs(e={},t={}){if(["operation","exactOutput","amountOut","multihop","path","positionManager","modifyLiquidities","commands","actions"].some(S=>Object.hasOwn(e,S)))throw new Error("uniswap-v4 unsupported operation shape is inspect/quote-only");let n=Number(e.chainId??8453),i=Ue(n);if(Pe(e.hooks)!==H)throw new Error("uniswap-v4 nonzero hooks are inspect/quote-only until a code-hash-specific adapter exists");if(Number(e.fee)&ar)throw new Error("uniswap-v4 dynamic-fee pools are inspect/quote-only until a code-hash-specific adapter exists");if(e.hookData!=null&&String(e.hookData).toLowerCase()!=="0x")throw new Error("uniswap-v4 opaque hookData is inspect/quote-only until a code-hash-specific adapter exists");if(!e.recipient)throw new Error("uniswap-v4 prepare requires recipient");let s=J(e.recipient);if(e.slippageBps==null)throw new Error("uniswap-v4 prepare requires explicit slippageBps");let a=Number(e.slippageBps);if(!Number.isInteger(a)||a<0||a>100)throw new Error("slippageBps must be an integer from 0 through 100");if(e.deadlineSeconds==null)throw new Error("uniswap-v4 prepare requires explicit deadlineSeconds");let u=Number(e.deadlineSeconds);if(!Number.isInteger(u)||u<30||u>600)throw new Error("deadlineSeconds must be an integer from 30 through 600");if(Le(e.tokenIn)||Le(e.tokenOut))throw new Error("uniswap-v4 prepare currently requires ERC-20 tokenIn and tokenOut; native routes are not inferred");let l=await mt(e,t);if(!i.universalRouter)throw new Error(`uniswap-v4: no Universal Router on chain ${n}`);let p=BigInt(l.amountOut)*BigInt(1e4-a)/10000n,d={currency0:l.zeroForOne?l.tokenIn:l.tokenOut,currency1:l.zeroForOne?l.tokenOut:l.tokenIn,fee:l.fee,tickSpacing:l.tickSpacing,hooks:l.hooks},f=$e.encode(["tuple(tuple(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 amountIn,uint128 amountOutMinimum,uint256 minHopPriceX36,bytes hookData)"],[[d,l.zeroForOne,BigInt(l.amountIn),p,0n,"0x"]]),m=$e.encode(["address","uint256"],[l.tokenIn,BigInt(l.amountIn)]),b=$e.encode(["address","uint256"],[l.tokenOut,p]),h=$e.encode(["bytes","bytes[]"],[ps,[f,m,b]]),v=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+u,k=us.encodeFunctionData("execute",[ds,[h],v]);return F({provider:"uniswap-v4",prepareReady:!0,calldataReady:!0,executionReady:!1,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,deadline:v,quote:{...l,amountOutMinimum:p.toString(),slippageBps:a},hookInspection:null,requiresApproval:{token:l.tokenIn,spender:fs,amount:l.amountIn,note:"Universal Router V4 settlement uses Permit2; Permit2 authorization for the Universal Router is also required"},transaction:{chainId:n,from:s,to:i.universalRouter,data:k,value:"0"}},{provider:"uniswap-v4",kind:"univ4-swap-tx"})}async function ys(){return Object.entries(G).map(([e,t])=>({chainId:Number(e),name:t.name,poolManager:t.poolManager,quoter:t.quoter,stateView:t.stateView||null,universalRouter:t.universalRouter||null,weth:t.weth,usdc:t.usdc}))}async function Es(e={}){let t=Ue(e.chainId??8453),r=await P(t.chainId,"eth_getCode",[t.quoter,"latest"],e),n=typeof r=="string"&&r!=="0x"&&r.length>4;return{ok:n,chainId:t.chainId,quoter:t.quoter,poolManager:t.poolManager,codeBytes:n?(r.length-2)/2:0}}var $e,H,G,ir,pt,us,dt,so,ls,ar,ds,ps,fs,ms,co,ur=R(()=>{he();st();ne();X();$e=ss.defaultAbiCoder(),H="0x0000000000000000000000000000000000000000",G={1:{name:"ethereum",poolManager:"0x000000000004444c5dc75cB358380D2e3dE08A90",quoter:"0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203",stateView:"0x7ffe42c4a5deea5b0fec41c94c136cf115597227",universalRouter:"0x66a9893cc07d91d95644aedd05d03f95e1dba8af",weth:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",usdc:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},10:{name:"optimism",poolManager:"0x9a13f98cb987694c9f086b1f5eb990eea8264ec3",quoter:"0x1f3131a13296fb91c90870043742c3cdbff1a8d7",stateView:"0xc18a3169788f4f75a170290584eca6395c75ecdb",universalRouter:"0x851116d9223fabed8e56c0e6b8ad0c31d98b3507",weth:"0x4200000000000000000000000000000000000006",usdc:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"},56:{name:"bsc",poolManager:"0x28e2ea090877bf75740558f6bfb36a5ffee9e9df",quoter:"0x9f75dd27d6664c475b90e105573e550ff69437b0",stateView:"0xd13dd3d6e93f276fafc9db9e6bb47c1180aee0c4",universalRouter:"0x1906c1d672b88cd1b9ac7593301ca990f94eae07",weth:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",usdc:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"},137:{name:"polygon",poolManager:"0x67366782805870060151383f4bbff9dab53e5cd6",quoter:"0xb3d5c3dfc3a7aebff71895a7191796bffc2c81b9",stateView:"0x5ea1bd7974c8a611cbab0bdcafcb1d9cc9b3ba5a",universalRouter:"0x1095692a6237d83c6a72f3f5efedb9a670c49223",weth:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",usdc:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"},8453:{name:"base",poolManager:"0x498581fF718922c3f8e6A244956aF099B2652b2b",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",stateView:"0xa3c0c9b65bad0b08107aa264b0f3db444b867a71",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",weth:"0x4200000000000000000000000000000000000006",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"},42161:{name:"arbitrum",poolManager:"0x360e68faccca8ca495c1b759fd9eee466db9fb32",quoter:"0x3972c00f7ed4885e145823eb7c655375d275a1c5",stateView:"0x76fd297e2d437cd7f76d50f01afe6160f86e9990",universalRouter:"0xa51afafe0263b40edaef0df8781ea9aa03e381a3",weth:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",usdc:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},43114:{name:"avalanche",poolManager:"0x06380c0e0912312b5150364b9dc4542ba0dbbc85",quoter:"0xbe40675bb704506a3c2ccfb762dcfd1e979845c2",stateView:"0xc3c9e198c735a4b97e3e683f391ccbdd60b69286",universalRouter:"0x94b75331ae8d42c1b61065089b7d48fe14aa73b7",weth:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",usdc:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"},4663:{name:"robinhood",poolManager:"0x8366a39cc670b4001a1121b8f6a443a643e40951",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",stateView:"0xf3334192d15450cdd385c8b70e03f9a6bd9e673b",universalRouter:"0x8876789976dEcBfCbBbe364623C63652db8C0904",weth:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",usdc:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"}},ir=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200},{fee:25e3,tickSpacing:8}],pt=new nr(["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)"]),us=new nr(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),dt=new nr(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96,int24 tick,uint24 protocolFee,uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),so=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"]]),ls=(1n<<14n)-1n,ar=8388608;ds="0x10",ps="0x060c0f",fs="0x000000000022D473030F116dDEE9F6B43aC78BA3",ms="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";co=["uniswap-v4","uniswapv4"]});function xs(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||As).replace(/\/$/,"")}function vs(e={}){return(e.baseUrl||process.env.DEFILLAMA_API_URL||Ss).replace(/\/$/,"")}async function ht(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return T(`${xs(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function lo(e={}){return T(`${vs(e)}/protocols`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??2e4})}var As,Ss,lr=R(()=>{Y();As="https://coins.llama.fi",Ss="https://api.llama.fi"});var pr={};te(pr,{ACROSS_API:()=>po,HOP_API:()=>fo,RELAY_API:()=>mo,acrossHealth:()=>Cs,acrossSuggestedFees:()=>ho,hopHealth:()=>ks,hopQuote:()=>bo,relayHealth:()=>Os,relayPrepare:()=>Ns,relayQuote:()=>dr});async function Cs(e={}){try{return{ok:!0,estimatedFillTimeSec:(await ho({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 ho(e={},t={}){let{token:r,destinationToken:n=r,originChainId:i,destinationChainId:o,amount:s}=e;if(!r||i==null||o==null||!s)throw new Error("acrossSuggestedFees requires token, originChainId, destinationChainId, amount");let a=new URLSearchParams({token:r,destinationToken:n,originChainId:String(i),destinationChainId:String(o),amount:String(s)}),u=(t.baseUrl||process.env.ACROSS_API_URL||po).replace(/\/$/,"");return T(`${u}/suggested-fees?${a}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function ks(e={}){try{let t=await bo({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 bo(e={},t={}){let{amount:r,token:n="ETH",fromChain:i="ethereum",toChain:o="arbitrum"}=e;if(!r)throw new Error("hopQuote requires amount");let s=e.slippage==null?void 0:Math.round(Number(e.slippage)*100),a=re({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:i!==o,requestedCapBps:e.maxSlippageBps??e.slippageBps??s});if(!a.executable)throw new Error(`hop: route requires ${a.requiredBps} bps above cap ${a.capBps}`);let u=new URLSearchParams({amount:String(r),token:n,fromChain:i,toChain:o,slippage:String(a.selectedBps/100)}),l=(t.baseUrl||process.env.HOP_API_URL||fo).replace(/\/$/,""),p=await T(`${l}/quote?${u}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),d=p?.estimatedRecieved||p?.estimatedReceived;return d?D(p,{chainId:Number(e.originChainId||e.chainId||Is[i]||0),venue:p?.tx?.to||"hop",amountOut:d,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:i!==o,requestedCapBps:e.maxSlippageBps??e.slippageBps??s}):{...p,autoSlippagePolicy:a}}async function Os(e={}){try{let t=await dr({user:se,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 dr(e={},t={}){let{user:r=se,originChainId:n,destinationChainId:i,originCurrency:o="0x0000000000000000000000000000000000000000",destinationCurrency:s="0x0000000000000000000000000000000000000000",amount:a,tradeType:u="EXACT_INPUT"}=e;if(n==null||i==null||!a)throw new Error("relayQuote requires originChainId, destinationChainId, amount");let l=re({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(i),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!l.executable)throw new Error(`relay: route requires ${l.requiredBps} bps above cap ${l.capBps}`);let p=(t.baseUrl||process.env.RELAY_API_URL||mo).replace(/\/$/,""),d=await T(`${p}/quote`,{method:"POST",body:{user:r,originChainId:Number(n),destinationChainId:Number(i),originCurrency:o,destinationCurrency:s,amount:String(a),tradeType:u,slippageTolerance:String(l.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),c=d?.details?.currencyOut?.amount;return!c||!/^\d+$/.test(String(c))?{...d,autoSlippagePolicy:l}:D(d,{chainId:Number(n),venue:d?.steps?.[0]?.items?.[0]?.data?.to||"relay",amountOut:c,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(i),requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Ns(e={},t={}){let r=await dr(e,t),n=Number(e.originChainId),i=(r.steps||[]).flatMap(a=>(a.items||[]).filter(u=>u?.data?.to&&u?.data?.data).map(u=>({stepId:a.id,...u.data})));if(!i.length)throw new Error("relay: quote returned no executable transaction items");let o=String(r?.autoSlippage?.venue||"").toLowerCase();if(i.some(a=>String(a.to).toLowerCase()!==o))throw new Error("relay: route includes a separate approval/transaction that is not yet safely bound");let s=i.map(a=>({chainId:n,from:a.from||e.user,to:a.to,data:a.data,value:a.value??"0x0",...a.gasLimit!=null||a.gas!=null?{gasLimit:a.gasLimit??a.gas}:{},slippageGuard:K(r.autoSlippage,{chainId:n,venue:a.to,data:a.data})}));return F({provider:"relay",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:r,autoSlippage:r.autoSlippage,transactions:s},{provider:"relay",kind:"relay-tx"})}var po,fo,mo,Is,fr=R(()=>{Y();ne();We();X();po="https://across.to/api",fo="https://api.hop.exchange/v1",mo="https://api.relay.link",Is={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453}});function bt(e){if(!Array.isArray(e))return null;let t=0,r=!1;for(let n of e){let i=Z(n?.amountUSD);i!=null&&(t+=i,r=!0)}return r?t:null}async function go(e,t={}){let r=Br[Number(e)];if(!r)return null;try{let n=await ht([r],t);return Z(n?.coins?.[r]?.price)}catch{return null}}async function _s(e={}){try{let t=await lo({...e,baseUrl:e.defillamaApiBaseUrl,timeoutMs:e.defillamaTimeoutMs??Math.min(Number(e.timeoutMs??5e3),5e3)});return Array.isArray(t)?t:[]}catch{return[]}}function Rs(e,t={}){let r=ce(t.tool||t.provider||t.bridge||t.protocol),n=[];return e==="lifi"&&r&&r!=="lifi"&&n.push(...wo[r]||[r]),n.push(...wo[ce(e)]||[e]),n}function Bs(e,t,r={}){let n=Array.isArray(e)?e:[],i=Rs(t,r).map(ce).filter(Boolean);for(let o of i){let s=n.find(u=>ce(u?.slug)===o||ce(u?.name)===o),a=Z(s?.tvl);if(a!=null)return{liquidityUsd:a,protocol:s?.name??s?.slug??o}}for(let o of i){let s=n.find(u=>{let l=ce(u?.category);return!l.includes("bridge")&&!l.includes("crosschain")?!1:ce(u?.slug).includes(o)||ce(u?.name).includes(o)}),a=Z(s?.tvl);if(a!=null)return{liquidityUsd:a,protocol:s?.name??s?.slug??o}}return null}function mr({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:i,slippageBps:o,decimalsIn:s,decimalsOut:a,nativePriceUsd:u=null,destDecimalsPromise:l=null,opts:p={}}){let d=[];return d.push({source:"lifi",run:async()=>{let c=await Oe({fromChain:e,toChain:e,fromToken:t,toToken:r,fromAmount:n},p),f=c?.estimate??c?.[0]?.estimate;return{amountOut:f?.toAmount,minOut:f?.toAmountMin,gasUsd:bt(f?.gasCosts),feeUsd:bt(f?.feeCosts),oracleFeeBps:c?.oracleFee?.applies?c.oracleFee.bps:0,meta:{tool:c?.tool??c?.toolDetails?.name,oracleFee:c?.oracleFee??null}}}}),s!=null&&d.push({source:"paraswap",run:async()=>{let c=a??(await Promise.resolve(l))?.decimals;if(c==null)throw new Error("paraswap needs destination decimals; none supplied or resolvable");let f=await Ye({chainId:e,srcToken:t,destToken:r,amount:n,srcDecimals:s,destDecimals:c},p),m=f?.priceRoute;return{amountOut:m?.destAmount,gasUsd:Z(m?.gasCostUSD),oracleFeeBps:f?.oracleFee?.applies?f.oracleFee.bps:0,meta:{bestRoute:m?.bestRoute?.[0]?.swaps?.[0]?.swapExchanges?.[0]?.exchange,oracleFee:f?.oracleFee??null}}}}),process.env.ZEROX_API_KEY&&d.push({source:"0x",run:async()=>{let c=await et({chainId:e,sellToken:t,buyToken:r,sellAmount:n,taker:i},p),f=null,m=c?.totalNetworkFee,b=await Promise.resolve(u);return m!=null&&b&&(f=Number(m)/1e18*b),{amountOut:c?.buyAmount,minOut:c?.minBuyAmount,gasUsd:f,meta:{source:c?.route?.fills?.[0]?.source}}}}),process.env.ONEINCH_API_KEY&&d.push({source:"1inch",run:async()=>{let c=await xn({chainId:e,src:t,dst:r,amount:n},p),f=null;return c?.gas!=null&&u&&(f=null),{amountOut:c?.dstAmount,gasUsd:f,meta:{gasUnits:c?.gas}}}}),d.push({source:"cow",run:async()=>{let c=await _e({chainId:e,sellToken:t,buyToken:r,sellAmountBeforeFee:String(n),from:i},p),f=c?.quote??c,m=f?.feeAmount;return{amountOut:f?.buyAmount,gasUsd:0,meta:{intent:!0,feeAmountInSellToken:m,settlement:"solver-executed"}}}}),j[Number(e)]&&d.push({source:"uniswap-v3",run:async()=>{let c=await Te({chainId:e,tokenIn:t,tokenOut:r,amountIn:n},p);return{amountOut:c?.amountOut,minOut:c?.minOut??c?.amountOutMinimum??null,gasUsd:null,liquidityUsd:c?.liquidityUsd??null,meta:{onchain:!0,fee:c?.fee,gasUnits:c?.gasEstimate,quoter:c?.quoter}}}}),G[Number(e)]&&d.push({source:"uniswap-v4",run:async()=>{let c=await mt({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:i,slippageBps:o},p);return{amountOut:c?.amountOut,minOut:c?.minOut??c?.amountOutMinimum??null,gasUsd:null,liquidityUsd:c?.liquidityUsd??null,meta:{onchain:!0,venue:"uniswap-v4",fee:c?.fee,tickSpacing:c?.tickSpacing,poolId:c?.poolId,hooks:c?.hooks,gasUnits:c?.gasEstimate,quoter:c?.quoter,poolManager:c?.poolManager,prepareReady:c?.prepareReady===!0,executionReady:!1}}}}),d}function yo({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:i,taker:o,opts:s={}}){let a=[],u=null,l=async(p,d={})=>(u||=_s(s),Bs(await u,p,d));return a.push({source:"lifi",run:async()=>{let p=await Oe({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:i},s),d=p?.estimate??p?.[0]?.estimate,c={tool:p?.tool??p?.toolDetails?.name,durationSeconds:Z(d?.executionDuration)},f=await l("lifi",c);return{amountOut:d?.toAmount,minOut:d?.toAmountMin,gasUsd:bt(d?.gasCosts),feeUsd:bt(d?.feeCosts),oracleFeeBps:p?.oracleFee?.applies?p.oracleFee.bps:0,liquidityUsd:f?.liquidityUsd??null,meta:{...c,liquidityProtocol:f?.protocol,oracleFee:p?.oracleFee??null}}}}),a.push({source:"relay",run:async()=>{let{relayQuote:p}=await Promise.resolve().then(()=>(fr(),pr)),c=(await p({user:o,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(i)},s))?.details,f={durationSeconds:Z(c?.timeEstimate),rate:c?.rate},m=await l("relay",f);return{amountOut:c?.currencyOut?.amount,minOut:c?.currencyOut?.minimumAmount,gasUsd:Z(c?.totalImpact?.usd)!=null?Math.abs(Z(c.totalImpact.usd)):null,liquidityUsd:m?.liquidityUsd??null,meta:{...f,liquidityProtocol:m?.protocol}}}}),a.push({source:"across",run:async()=>{let{acrossSuggestedFees:p}=await Promise.resolve().then(()=>(fr(),pr)),d=await p({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(i)},s),c=d?.totalRelayFee?.total,f=null;if(c!=null)try{let b=BigInt(String(i))-BigInt(String(c));b>0n&&(f=b.toString())}catch{}let m=await l("across");return{amountOut:f,gasUsd:null,liquidityUsd:m?.liquidityUsd??null,meta:{derivedFromFees:!0,durationSeconds:Z(d?.estimatedFillTimeSec),limits:d?.limits?{min:d.limits.minDeposit,max:d.limits.maxDeposit}:void 0,liquidityProtocol:m?.protocol}}}}),a}var Z,ce,wo,Eo=R(()=>{Mt();Vt();zt();vn();Yt();lt();ur();lr();It();Z=e=>{let t=Number(e);return Number.isFinite(t)?t:null};ce=e=>String(e??"").toLowerCase().replace(/[^a-z0-9]/g,""),wo=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 Ao(e,t,r){let n=Ts[Number(e)];if(!n)return{priceUsd:null,decimals:null};let i=`${n}:${t}`;try{let s=(await ht([i],r))?.coins?.[i],a=Number(s?.price),u=Number(s?.decimals);return{priceUsd:Number.isFinite(a)?a:null,decimals:Number.isFinite(u)?u:null}}catch{return{priceUsd:null,decimals:null}}}async function wt(e,t={}){let{chainId:r,tokenIn:n,tokenOut:i,amountIn:o}=e;if(r==null||!n||!i||o==null)throw new Error("bestSwapRoute requires chainId, tokenIn, tokenOut, amountIn");let s=go(r,t),a=Ao(r,i,t),u=Kn(r,t).catch(()=>null),l=mr({...e,nativePriceUsd:s,decimalsOut:e.decimalsOut,destDecimalsPromise:a,opts:t}),[p,d,c]=await Promise.all([He(l,{timeoutMs:t.timeoutMs??12e3}),a,u]);s.catch(()=>{});let f=await s.then(h=>h,()=>null),m=vt(p,{destPriceUsd:d.priceUsd,destDecimals:e.decimalsOut??d.decimals,liquidityBandBps:t.liquidityBandBps??50,gasPriceWei:c,nativePriceUsd:f}),b=t.maxImpactPct===void 0?25:t.maxImpactPct;if(b!=null&&m.best){let h=m.best.source,v=await Tr(async k=>{let S=mr({...e,amountIn:k.toString(),nativePriceUsd:s,decimalsOut:e.decimalsOut,destDecimalsPromise:a,opts:t}).filter(E=>E.source===h);return S.length?(await He(S,{timeoutMs:t.timeoutMs??12e3}))?.[0]?.amountOut??null:null},o);if(v){let k=$r(m,{[h]:v},{maxImpactPct:b});return{kind:"swap",chainId:r,tokenIn:n,tokenOut:i,amountIn:String(o),...k,sourcesTried:l.length,sourcesAnswered:p.filter(S=>S.quality!==Q.FAILED).length,note:hr(k,l.length),priceImpact:{[h]:Number(v.impactPct.toFixed(2))}}}}return{kind:"swap",chainId:r,tokenIn:n,tokenOut:i,amountIn:String(o),...m,sourcesTried:l.length,sourcesAnswered:p.filter(h=>h.quality!==Q.FAILED).length,note:hr(m,l.length)}}async function So(e,t={}){let{fromChainId:r,toChainId:n,tokenIn:i,tokenOut:o,amountIn:s}=e;if(r==null||n==null||!i||!o||s==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 a=Ao(n,o,t),u=yo({...e,opts:t}),[l,p]=await Promise.all([He(u,{timeoutMs:t.timeoutMs??15e3}),a]),d=vt(l,{destPriceUsd:p.priceUsd,destDecimals:e.decimalsOut??p.decimals,liquidityBandBps:t.liquidityBandBps??50}),c=d.routes.map(f=>({source:f.source,seconds:f.meta?.durationSeconds??null})).filter(f=>f.seconds!=null);return{kind:"bridge",fromChainId:r,toChainId:n,tokenIn:i,tokenOut:o,amountIn:String(s),...d,durations:c,sourcesTried:u.length,sourcesAnswered:l.filter(f=>f.quality!==Q.FAILED).length,note:hr(d,u.length)}}function $s(e){let t=e?.meta?.oracleFee;return t?.applies?` \xB7 ${nn(t)}`:""}function hr(e,t){if(!e.best)return"no source returned a usable route";let r=e.routes.length,n=$s(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 i=e.improvementBps,o=i/100;if(i<.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 s=o>=.01?`${o.toFixed(2)}%`:`${i.toFixed(2)}bps`;return`best of ${r} routes, ranked on ${e.rankedOn}: ${s} 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}var Ts,br=R(()=>{It();Eo();Qe();lr();he();Ts={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"}});function g(e){return L(e)?String(e).replace(Qs,t=>`\\${t}`):B}function L(e){return e==null?!1:typeof e=="number"?Number.isFinite(e):typeof e=="string"?e.trim()!=="":!0}function ee(e){if(!L(e))return B;let t=String(e).replace(/`/g,"");return t===""?B:`\`${t}\``}function we(e,{decimals:t=2}={}){if(!L(e))return B;let r=Number(e);return Number.isFinite(r)?r.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:t}):B}function M(e,{decimals:t=2}={}){let r=we(e,{decimals:t});return r===B?B:`${r} USD`}function vr(e,{decimals:t=2}={}){let r=we(e,{decimals:t});return r===B?B:`${r}%`}function yt(e){let t=we(e,{decimals:0});return t===B?B:`${t} bps`}function ge(e,t){if(!L(e))return B;let r=Number(t);if(!Number.isInteger(r)||r<0||r>77)return B;let n;try{n=BigInt(typeof e=="string"?e.trim():e)}catch{return B}let i=n<0n,o=i?-n:n,s=10n**BigInt(r),a=(o/s).toString(),u=(o%s).toString().padStart(r,"0").replace(/0+$/,"");return`${i?"-":""}${a}${u?`.${u}`:""}`}function Ys(e){if(typeof e=="number"&&Number.isFinite(e))return e<0||e>1?B:e>=.75?"HIGH":e>=.4?"MEDIUM":"LOW";if(typeof e=="string"){let t=e.trim().toUpperCase();if(t==="HIGH"||t==="MEDIUM"||t==="LOW")return t}return B}function le(e={}){let t=e.chainId;if(!L(t)||!Number.isFinite(Number(t)))return L(e.chain)?g(e.chain):B;let n=at(t)?.name||(L(e.chain)?String(e.chain):B);return`${g(n)} (chainId ${Number(t)})`}function Po(e={}){return g(e.venue??e.dex??e.pool?.venue)}function Xs(e){return e==null?"NONE (text card only)":typeof e=="string"?e.trim()?ee(e):"NONE (text card only)":e.error||e.ok===!1||e.available===!1?`UNAVAILABLE${L(e.error)?` \u2014 ${g(e.error)}`:""} (text card stands)`:L(e.url)?ee(e.url):"NONE (text card only)"}function Ir(e={},{now:t=Date.now()}={}){let r=e.grant??e.session??null;if(!r||typeof r!="object")return{allowed:!1,reason:"no local grant/session",actions:[]};if(r.local===!1)return{allowed:!1,reason:"grant is not local",actions:[]};if(r.revoked===!0)return{allowed:!1,reason:"grant revoked",actions:[]};let n=r.expiresAt??r.expiry;if(L(n)){let o=typeof n=="number"?n:Date.parse(n);if(!Number.isFinite(o))return{allowed:!1,reason:"grant expiry unreadable",actions:[]};if(o<=t)return{allowed:!1,reason:"grant expired",actions:[]}}return{allowed:!0,reason:"valid local grant",actions:Array.isArray(r.actions)&&r.actions.length?r.actions.slice():["BUY","SELL"]}}function Js(e){let t=Ir(e);return t.allowed?`${t.actions.map(r=>g(r)).join(" / ")} (${g(t.reason)})`:`prepare-only \u2014 ${g(t.reason)}`}function ie(e,t,r={}){let n=[`*${e}*`];for(let[i,o]of t)n.push(`${i}: ${o==null||o===""?B:o}`);return n.push(`Chart: ${Xs(r.chart)}`),n.push(`Actions: ${Js(r)}`),Array.isArray(r.warnings)&&r.warnings.length&&n.push(`Warnings: ${r.warnings.map(i=>g(i)).join("; ")}`),(L(r.source)||L(r.fetchedAt))&&n.push(`Source: ${g(r.source)} at ${g(r.fetchedAt)}`),n.join(`
|
|
5
|
-
|
|
6
|
-
`),cancelHint:p}}var B,jl,Qs,zl,qo=R(()=>{Xt();B="UNKNOWN",jl=Object.freeze(["token","launch","hip3","hip4","polymarket","twap","bridge","swap","approve"]),Qs=/[_*[\]`]/g;zl=Object.freeze({token:ec,launch:tc,hip3:rc,hip4:nc,polymarket:oc,twap:ic,bridge:ac,swap:Cr,approve:uc})});var Ho={};te(Ho,{buildSwapQuoteCard:()=>dc});function Mo(e){return!e||typeof e!="object"?{best:{},routes:[],rankedOn:null,improvementBps:null,warnings:[]}:{best:e.best??e.routes?.[0]??{},routes:Array.isArray(e.routes)?e.routes:[],rankedOn:e.rankedOn??null,improvementBps:e.improvementBps??null,note:e.note??null,warnings:e.warnings??[]}}function lc(e){let t=Number(e);return!Number.isFinite(t)||t<=0?null:t<60?`${Math.round(t)}s`:t<3600?`${Math.round(t/60)}m`:`${(t/3600).toFixed(1)}h`}async function dc(e={},t={}){let{chainId:r,tokenIn:n,tokenOut:i,amountIn:o,toChainId:s=null,tokenInSymbol:a,tokenOutSymbol:u,decimalsIn:l,decimalsOut:p,grant:d=null,quoteId:c=null,prepareId:f=null,executeId:m=null,bridgePrepareId:b=null,chartUrl:h=null,explorerUrl:x=null,platform:v="telegram",cancelWindowSec:k=10}=e;if(r==null||!n||!i||o==null)throw new Error("buildSwapQuoteCard requires chainId, tokenIn, tokenOut, amountIn");let S=s!=null&&Number(s)!==Number(r),C=t.swapFn??wt,E=t.bridgeFn??So,y=C({chainId:r,tokenIn:n,tokenOut:i,amountIn:o,decimalsIn:l,decimalsOut:p,taker:e.taker},t),w=S?Promise.resolve().then(()=>E({fromChainId:r,toChainId:s,tokenIn:n,tokenOut:e.bridgeTokenOut??i,amountIn:o,decimalsIn:l,decimalsOut:e.bridgeDecimalsOut??p},t)).catch(de=>({error:String(de?.message||de)})):Promise.resolve(null),[A,I]=await Promise.all([y,w]),N=Mo(A),U=I&&!I.error?Mo(I):null,$=Ir({grant:d}),V={intent:S?"swap or bridge":"swap",chainId:r,toChainId:S?s:null,tokenIn:n,tokenOut:i,tokenInSymbol:a,tokenOutSymbol:u,amountIn:String(o),decimalsIn:l,decimalsOut:p,grant:d,preparable:!!N.best?.source,confidence:N.best?.source?"high":"low",warnings:[...Array.isArray(N.warnings)?N.warnings:[],...U&&Array.isArray(U.warnings)?U.warnings:[],...I?.error?[`bridge quote failed: ${I.error}`]:[]],swap:{chainId:r,rankedOn:N.rankedOn,improvementBps:N.improvementBps,best:N.best,routes:N.routes,amountIn:String(o)},bridge:U?{toChainId:s,rankedOn:U.rankedOn,best:U.best,routes:U.routes,estimatedTime:lc(U.best?.meta?.durationSeconds)}:null,source:"oracle-best-execution"},ye=Cr(V),At=Fo({platform:v,chartUrl:h,explorerUrl:x,quoteId:c,prepareId:$.allowed?f:null,executeId:$.allowed?m:null,bridgePrepareId:$.allowed&&S?b:null,hasGrant:$.allowed,cancelWindowSec:k});return{kind:"swap",text:ye,buttons:At,grant:{allowed:$.allowed,reason:$.reason},swap:A,bridge:S?I:null,execution:!1,broadcast:!1}}var Vo=R(()=>{qo();br()});br();X();var ue=Object.freeze({TRANSACTION:"unsigned-transaction",TYPED_DATA_ORDER:"typed-data-order"}),Ls=100,wr={"uniswap-v3":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:i},o)=>{let{uniV3PrepareExactIn:s}=await Promise.resolve().then(()=>(lt(),ao)),a=await s({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:i},o);return{artifactKind:ue.TRANSACTION,transaction:a.transaction,requiresApproval:a.requiresApproval??null,amountOut:a.quote?.amountOut??null,minOut:a.quote?.amountOutMinimum??null}},"uniswap-v4":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:i,slippageBps:o,deadlineSeconds:s,fee:a,tickSpacing:u,hooks:l},p)=>{let{uniV4PrepareExactIn:d}=await Promise.resolve().then(()=>(ur(),uo)),c=await d({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:i,slippageBps:o,deadlineSeconds:s,fee:a,tickSpacing:u,hooks:l},p);return{artifactKind:ue.TRANSACTION,transaction:c.transaction,requiresApproval:c.requiresApproval,amountOut:c.quote?.amountOut??null,minOut:c.quote?.amountOutMinimum??null,prepareReady:!0,executionReady:!1}},lifi:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:i},o)=>{let{lifiPrepare:s}=await Promise.resolve().then(()=>(Mt(),un)),a=await s({fromChain:e,toChain:e,fromToken:t,toToken:r,fromAmount:n,fromAddress:i},o);return{artifactKind:ue.TRANSACTION,transaction:a.transaction,requiresApproval:a.requiresApproval??null,amountOut:a.quote?.estimate?.toAmount??null,minOut:a.quote?.estimate?.toAmountMin??null}},paraswap:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:i,decimalsIn:o,decimalsOut:s},a)=>{let{paraswapPrepare:u}=await Promise.resolve().then(()=>(Vt(),pn)),l=await u({chainId:e,srcToken:t,destToken:r,amount:n,srcDecimals:o,destDecimals:s,userAddress:i,side:"SELL"},a);return{artifactKind:ue.TRANSACTION,transaction:l.transaction,requiresApproval:l.requiresApproval??null,amountOut:l.quote?.priceRoute?.destAmount??null,minOut:l.quote?.amountOutMinimum??null}},"0x":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:i},o)=>{let{zeroxPrepare:s}=await Promise.resolve().then(()=>(zt(),En)),a=await s({chainId:e,sellToken:t,buyToken:r,sellAmount:n,taker:i},o);return{artifactKind:ue.TRANSACTION,transaction:a.transaction,requiresApproval:a.requiresApproval??null,amountOut:a.quote?.buyAmount??null,minOut:a.quote?.minBuyAmount??null}},cow:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:i},o)=>{let{cowPrepareOrder:s}=await Promise.resolve().then(()=>(Yt(),qn)),a=await s({chainId:e,sellToken:t,buyToken:r,sellAmountBeforeFee:String(n),from:i},o);return{artifactKind:ue.TYPED_DATA_ORDER,typedData:a.typedData,requiresApproval:{token:t,spender:a.vaultRelayer,amount:String(n),note:"CoW pulls funds via the vault relayer, not the settlement contract"},settlement:a.settlement,amountOut:a.quote?.quote?.buyAmount??null,minOut:null,submission:"sign the typed data, then submit the order to the CoW API"}}};var Us=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),Ps=/^0x[0-9a-fA-F]{40}$/,Ds=Object.freeze(["operation","exactOutput","amountOut","multihop","path","positionManager","modifyLiquidities","commands","actions"]);async function xo(e,t={}){if(Ds.some(h=>Object.hasOwn(e,h)))throw new Error("unsupported operation shape is inspect/quote-only");if(e.hookData!=null&&String(e.hookData).toLowerCase()!=="0x")throw new Error("opaque hookData is inspect/quote-only");let{taker:r}=e;if(!r)throw new Error("prepareBestRoute requires taker: a prepared transaction is built FOR an address, and the quote-only placeholder must never end up in one");if(!Ps.test(r))throw new Error(`taker must be a valid 20-byte address, got "${r}"`);if(Us.has(r.toLowerCase()))throw new Error(`taker "${r}" is a placeholder/burn address. It is valid for quoting but not for preparing -- that would build a transaction for an address nobody controls. Pass the real wallet that will sign.`);let n=await wt(e,t);if(!n.best){let h=n.impactRejected??[];return{ok:!1,reason:h.length?h[0].reason:"no source returned a usable route",priceImpactBlocked:h.length>0,impactRejected:h,comparison:n}}let i=e.source||n.best.source,o=n.routes.find(h=>h.source===i);if(!o)return{ok:!1,reason:`source "${i}" did not return a usable route`,comparison:n};let s=wr[i];if(!s){let h=n.routes.find(x=>wr[x.source]&&x.source!==i);return{ok:!1,reason:`${i} won the comparison but has no prepare path in this build. `+(h?`Next preparable route is ${h.source}; pass source:"${h.source}" to use it.`:"No route in this comparison can be prepared."),comparison:n,winner:i}}let a;try{a=await s(e,t)}catch(h){let x=typeof h?.body=="string"?h.body:h?.body?JSON.stringify(h.body):"",v=[String(h?.message||h),x].filter(Boolean).join(" :: "),k=/allowance/i.test(v),S=!k&&/not enough|insufficient|balance/i.test(v),C,E;k?(E="approval-required-first",C=`${i} will not build swap calldata until the token approval exists on-chain. Approve the spender first, then prepare again. Underlying: ${v}`):S?(E="taker-not-funded",C=`${i} refused to build the transaction: ${v}. This venue verifies the taker holds the input token. Quoting works for any address; preparing needs the real funded wallet.`):(E="provider-error",C=`${i} prepare failed: ${v}`);let y=n.routes.find(w=>wr[w.source]&&w.source!==i);return{ok:!1,reason:C,failureKind:E,...y?{alternative:y.source}:{},comparison:n}}let u=e.driftToleranceBps??Ls,l=null,p=null;if(a.amountOut!=null&&o.grossOut!=null)try{let h=BigInt(o.grossOut),x=BigInt(a.amountOut);h>0n&&(l=Number((x-h)*10000n/h),l<-u&&(p=`route moved ${(l/100).toFixed(2)}% against you between the comparison and this prepare (tolerance ${(u/100).toFixed(2)}%). The ranking may no longer hold -- re-run the comparison before signing.`))}catch{}let d=n.routes.filter(h=>h.source!==i).map(h=>({source:h.source,netOut:h.netOut,gasUsd:h.gasUsd})),f=n.routes.map(h=>({source:h.source,liquidityUsd:h.liquidityUsd??null})).reduce((h,x)=>Math.max(h,x.liquidityUsd??0),0)||null,m=o.liquidityUsd??null,b=m!=null&&f>0?Math.round(m/f*100):null;return F({ok:!0,chosen:{source:i,wasWinner:i===n.best.source,netOut:o.netOut,grossOut:o.grossOut,gasUsd:o.gasUsd,liquidityUsd:o.liquidityUsd??null},liquidity:{chosenUsd:m,maxUsd:f,sharePct:b},priceImpact:n.priceImpact??null,impactUnmeasured:n.impactUnmeasured??[],...a,unsigned:!0,signedBy:"user-wallet",destination:a.artifactKind===ue.TRANSACTION?a.transaction?.to??null:a.settlement??null,driftBps:l,warnings:[...p?[p]:[],...n.warnings||[],...a.artifactKind===ue.TYPED_DATA_ORDER?["This is an ORDER to sign, not a transaction to broadcast. Signing it authorizes a solver to settle on your behalf."]:[]],runnersUp:d,comparison:{rankedOn:n.rankedOn,sourcesAnswered:n.sourcesAnswered,sourcesTried:n.sourcesTried,improvementBps:n.improvementBps},note:"UNSIGNED. Verify the destination address and minOut against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."},{provider:"router",kind:"best-route"})}fe();he();st();fe();he();fe();var yr={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},z=e=>BigInt(e).toString(16).padStart(64,"0"),De=e=>e.slice(2).toLowerCase().padStart(64,"0");function Fs(e,t){return`0x${yr.getAmountsOut}`+z(e)+z(64)+z(t.length)+t.map(De).join("")}function qs(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length<128)return null;let r=Number(BigInt(`0x${t.slice(64,128)}`));if(!Number.isFinite(r)||r<1||r>16)return null;let n=[];for(let i=0;i<r;i++){let o=128+i*64;if(t.length<o+64)return null;n.push(BigInt(`0x${t.slice(o,o+64)}`))}return n}function gr(e,t="router"){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}var Er=100;function Ms(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Er)throw new Error(`slippageBps ${r} exceeds the ${Er} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(r))/10000n}function vo(e){let{chainId:t,wrappedNative:r}=e;async function n(i,o,s,a){let u=await P(t,"eth_call",[{to:i,data:Fs(o,s)},"latest"],a);return qs(u?.result??u)}return{async quote({tokenIn:i,tokenOut:o,amountIn:s,path:a},u={}){let l=gr(u.scanner);if(!l)return{chainId:t,evidence:_.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let p=a||[i,o];if(p.some(c=>!/^0x[0-9a-fA-F]{40}$/.test(c||"")))throw new Error("quote requires valid 20-byte addresses");let d=await n(l,s,p,u);return d?{chainId:t,router:l,path:p,amountIn:String(s),amountOut:d[d.length-1].toString(),hops:p.length-1,evidence:_.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:l,path:p,evidence:_.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:i,amountIn:o,base:s},a={}){let u=gr(a.scanner),l=s||r;if(l&&String(i).toLowerCase()===String(l).toLowerCase())return{chainId:t,token:i,verdict:O.UNKNOWN,evidence:_.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!u||!l)return{chainId:t,token:i,verdict:O.UNKNOWN,evidence:_.UNAVAILABLE,reason:u?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let p=await n(u,o,[l,i],a);if(!p)return{chainId:t,token:i,verdict:O.FAIL,evidence:_.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let d=p[p.length-1];if(d===0n)return{chainId:t,token:i,verdict:O.FAIL,evidence:_.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let c=await n(u,d,[i,l],a);if(!c)return{chainId:t,token:i,verdict:O.FAIL,evidence:_.LIVE,leg:"sell",bought:d.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let f=c[c.length-1],m=Number(f*10000n/BigInt(o)),b=O.PASS,h="round trip completes with expected fee/impact loss";return m<5e3?(b=O.FAIL,h=`round trip returns only ${(m/100).toFixed(2)}% -- punitive tax or no real liquidity`):m<9e3&&(b=O.CAUTION,h=`round trip returns ${(m/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:i,base:l,router:u,verdict:b,reason:h,amountIn:String(o),bought:d.toString(),returned:f.toString(),retentionBps:m,evidence:_.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:i,tokenOut:o,amountIn:s,recipient:a,slippageBps:u=50,deadlineSeconds:l=900,path:p},d={}){let c=d.scanner,f=gr(c);if(!f)throw new Error(`chain ${t} has no verified router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!/^0x[0-9a-fA-F]{40}$/.test(a||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let m=p||[i,o],b=await this.quote({tokenIn:i,tokenOut:o,amountIn:s,path:m},d);if(b.evidence!==_.LIVE)throw new Error(`cannot prepare without a live quote (${b.evidence}: ${b.reason??"no reason given"})`);let h=Ms(b.amountOut,u);if(h<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let x=BigInt(Math.floor(Date.now()/1e3)+Number(l)),v=r&&m[0].toLowerCase()===r.toLowerCase()&&d.useNative,k=v?`0x${yr.swapExactETHForTokens}`+z(h)+z(128)+De(a)+z(x)+z(m.length)+m.map(De).join(""):`0x${yr.swapExactTokensForTokens}`+z(s)+z(h)+z(160)+De(a)+z(x)+z(m.length)+m.map(De).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:f,data:k,value:v?`0x${BigInt(s).toString(16)}`:"0x0"},guard:{quotedOut:b.amountOut,minOut:h.toString(),slippageBps:u,maxSlippageBps:Er,deadline:x.toString()},requires:v?[]:[{step:"approve",token:m[0],spender:f,amount:String(s)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}he();fe();var Hs=[100,500,3e3,1e4],Io={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},be=e=>BigInt(e).toString(16).padStart(64,"0"),Fe=e=>e.slice(2).toLowerCase().padStart(64,"0"),Co=/^0x[0-9a-fA-F]{40}$/,Sr=100;function Vs(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Sr)throw new Error(`slippageBps ${r} exceeds the ${Sr} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(r))/10000n}function Ar(e,t){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function ko(e){let{chainId:t,wrappedNative:r}=e;async function n({quoter:o,tokenIn:s,tokenOut:a,amountIn:u,fee:l},p){let d=`0x${Io.quoteExactInputSingle}`+Fe(s)+Fe(a)+be(u)+be(l)+be(0),c=await P(t,"eth_call",[{to:o,data:d},"latest"],p).catch(()=>null),f=c?.result??c;if(!f||f==="0x"||f.length<66)return null;let m=BigInt(`0x${f.slice(2,66)}`);return m>0n?m:null}async function i({quoter:o,tokenIn:s,tokenOut:a,amountIn:u},l){let p=[],d=null;for(let c of Hs){let f=await n({quoter:o,tokenIn:s,tokenOut:a,amountIn:u,fee:c},l);p.push({fee:c,amountOut:f?f.toString():null}),f&&(!d||f>d.amountOut)&&(d={fee:c,amountOut:f})}return{best:d,tried:p}}return{async quote({tokenIn:o,tokenOut:s,amountIn:a},u={}){let l=Ar(u.scanner,"quoter");if(!l)return{chainId:t,evidence:_.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let c of[o,s])if(!Co.test(c||""))throw new Error("quote requires valid 20-byte addresses");let{best:p,tried:d}=await i({quoter:l,tokenIn:o,tokenOut:s,amountIn:a},u);return p?{chainId:t,venue:"uniswap-v3",quoter:l,tokenIn:o,tokenOut:s,amountIn:String(a),amountOut:p.amountOut.toString(),fee:p.fee,useNative:!!r&&String(o).toLowerCase()===String(r).toLowerCase(),triedFeeTiers:d,evidence:_.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:l,tokenIn:o,tokenOut:s,triedFeeTiers:d,evidence:_.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:o,amountIn:s,base:a},u={}){let l=Ar(u.scanner,"quoter"),p=(e.stableQuoteAssets||[]).map(C=>String(C).toLowerCase()),d=null;!a&&typeof e.resolveQuoteAsset=="function"&&(d=await e.resolveQuoteAsset(o,u).catch(()=>null));let c=String(o).toLowerCase(),f=String(r||"").toLowerCase();if(f&&c===f)return{chainId:t,token:o,verdict:O.UNKNOWN,evidence:_.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};let m=a||d||(p[0]&&c!==p[0]?p[0]:null)||r;if(m&&c===String(m).toLowerCase())return{chainId:t,token:o,verdict:O.UNKNOWN,evidence:_.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!l||!m)return{chainId:t,token:o,verdict:O.UNKNOWN,evidence:_.UNAVAILABLE,reason:l?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let b=await i({quoter:l,tokenIn:m,tokenOut:o,amountIn:s},u);if(!b.best){let C=p.find(E=>E&&E!==String(m).toLowerCase()&&E!==String(o).toLowerCase());if(C){let E=await i({quoter:l,tokenIn:C,tokenOut:o,amountIn:s},u);if(E.best){let y=await i({quoter:l,tokenIn:o,tokenOut:C,amountIn:E.best.amountOut},u);if(y.best){let w=y.best.amountOut,A=Number(w*10000n/BigInt(s)),I=O.PASS,N="round trip vs dollar book completes with expected fee/impact loss";return A<5e3?(I=O.FAIL,N=`round trip vs dollar book returns only ${(A/100).toFixed(2)}% -- punitive tax or no real liquidity`):A<9e3&&(I=O.CAUTION,N=`round trip vs dollar book returns ${(A/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:o,base:C,quoteAsset:C,verdict:I,reason:N,amountIn:String(s),bought:E.best.amountOut.toString(),returned:w.toString(),retentionBps:A,buyFee:E.best.fee,sellFee:y.best.fee,evidence:_.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:t,token:o,verdict:O.FAIL,evidence:_.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let h=await i({quoter:l,tokenIn:o,tokenOut:m,amountIn:b.best.amountOut},u);if(!h.best){let C=p.find(E=>E&&E!==String(m).toLowerCase()&&E!==String(o).toLowerCase());if(C){let E=await i({quoter:l,tokenIn:C,tokenOut:o,amountIn:s},u),y=E.best?await i({quoter:l,tokenIn:o,tokenOut:C,amountIn:E.best.amountOut},u):{best:null};if(E.best&&y.best){let w=y.best.amountOut,A=Number(w*10000n/BigInt(s)),I=O.PASS,N="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return A<5e3?(I=O.FAIL,N=`dollar-book round trip returns only ${(A/100).toFixed(2)}%`):A<9e3&&(I=O.CAUTION,N=`dollar-book round trip returns ${(A/100).toFixed(2)}%`),{chainId:t,venue:"uniswap-v3",token:o,base:C,quoteAsset:C,verdict:I,reason:N,amountIn:String(s),bought:E.best.amountOut.toString(),returned:w.toString(),retentionBps:A,buyFee:E.best.fee,sellFee:y.best.fee,evidence:_.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:t,token:o,verdict:O.FAIL,evidence:_.LIVE,leg:"sell",bought:b.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let x=h.best.amountOut,v=Number(x*10000n/BigInt(s)),k=O.PASS,S="round trip completes with expected fee/impact loss";return v<5e3?(k=O.FAIL,S=`round trip returns only ${(v/100).toFixed(2)}% -- punitive tax or no real liquidity`):v<9e3&&(k=O.CAUTION,S=`round trip returns ${(v/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:o,base:m,verdict:k,reason:S,amountIn:String(s),bought:b.best.amountOut.toString(),returned:x.toString(),retentionBps:v,buyFee:b.best.fee,sellFee:h.best.fee,evidence:_.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:s,amountIn:a,recipient:u,slippageBps:l=50,fee:p},d={}){let c=Ar(d.scanner,"router");if(!c)throw new Error(`chain ${t} has no verified V3 router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!Co.test(u||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=await this.quote({tokenIn:o,tokenOut:s,amountIn:a},d);if(f.evidence!==_.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let m=p??f.fee,b=Vs(f.amountOut,l);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let h=!!(d.useNative||f.useNative)&&r&&String(o).toLowerCase()===String(r).toLowerCase(),x=`0x${Io.exactInputSingle}`+Fe(o)+Fe(s)+be(m)+Fe(u)+be(a)+be(b)+be(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:c,data:x,value:h?String(a):"0x0"},guard:{quotedOut:f.amountOut,minOut:b.toString(),slippageBps:l,maxSlippageBps:Sr,fee:m},requires:h?[]:[{step:"approve",token:o,spender:c,amount:String(a)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}Zt();var gt={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function Oo(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function No(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length>=128){let n=Number(BigInt(`0x${t.slice(64,128)}`));if(n>0&&n<=256&&t.length>=128+n*2){let i=t.slice(128,128+n*2),o=Buffer.from(i,"hex").toString("utf8").replace(/\0+$/,"");if(o)return o}}return Buffer.from(t.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function js(e){let{chainId:t}=e;async function r(n,i,o){return P(t,"eth_call",[{to:n,data:i},"latest"],o)}return{async blockNumber(n={}){let i=await zn(t,n);return{chainId:t,blockNumber:i?.blockNumber??i,evidence:_.LIVE}},async nativeBalance(n,i={}){let o=await Wn(t,n,i);return{chainId:t,address:n,wei:o?.wei??o?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:_.LIVE}},async tokenBalance({token:n,owner:i},o={}){let s=await Gn({chainId:t,token:n,owner:i},o);return{chainId:t,token:n,owner:i,raw:s?.balance??s,evidence:_.LIVE}},async resolveToken(n,i={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:t,token:n,evidence:_.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[o,s,a,u]=await Promise.all([r(n,gt.decimals,i).catch(()=>null),r(n,gt.symbol,i).catch(()=>null),r(n,gt.name,i).catch(()=>null),r(n,gt.totalSupply,i).catch(()=>null)]),l=Oo(o?.result??o),p=l!==null||s?.result||a?.result;return{chainId:t,address:n,decimals:l===null?null:Number(l),symbol:No(s?.result??s),name:No(a?.result??a),totalSupply:(Oo(u?.result??u)??null)?.toString()??null,evidence:p?_.LIVE:_.UNKNOWN,warning:p?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(n,i={}){let o=e.dexscreenerSlug;if(!o)return{chainId:t,token:n,pools:[],evidence:_.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let s=await er(n,i).catch(()=>null),u=(s?.pairs||s?.data?.pairs||[]).filter(p=>String(p.chainId).toLowerCase()===String(o).toLowerCase()).map(p=>({pair:p.pairAddress,dex:p.dexId,base:p.baseToken?.address,quote:p.quoteToken?.address,liquidityUsd:p.liquidity?.usd??null,priceUsd:p.priceUsd??null,volume24hUsd:p.volume?.h24??null,createdAt:p.pairCreatedAt??null})).sort((p,d)=>(d.liquidityUsd??0)-(p.liquidityUsd??0)),l=Jt(n,u,{stables:e.stableQuoteAssets||[],wrappedNative:e.wrappedNative});return{chainId:t,token:n,pools:l,topPool:l[0]||null,quoteAsset:Yn(n,l),evidence:l.length?_.LIVE:_.UNKNOWN}},async scanBlocks({fromBlock:n,toBlock:i,address:o,topics:s,chunkSize:a=2e3}={},u={}){if(!Number.isInteger(n)||!Number.isInteger(i))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(i<n)throw new Error("toBlock must be >= fromBlock");let l=[],p=[];for(let d=n;d<=i;d+=a){let c=Math.min(d+a-1,i);p.push([d,c])}for(let[d,c]of p){let f={fromBlock:`0x${d.toString(16)}`,toBlock:`0x${c.toString(16)}`};o&&(f.address=o),s&&(f.topics=s);let m=await P(t,"eth_getLogs",[f],u).catch(b=>({error:String(b?.message||b)}));if(m?.error)return{chainId:t,fromBlock:n,toBlock:i,logs:l,complete:!1,failedAt:[d,c],error:m.error,evidence:_.UNKNOWN};for(let b of m?.result??m??[])l.push(b)}return{chainId:t,fromBlock:n,toBlock:i,logs:l,complete:!0,chunks:p.length,evidence:_.LIVE}},async scoreRisk(n,i={}){let o=[],s=O.PASS,a=p=>{let d={[O.PASS]:0,[O.CAUTION]:1,[O.UNKNOWN]:2,[O.FAIL]:3};d[p]>d[s]&&(s=p)},u=await this.resolveToken(n,i);u.evidence!==_.LIVE?(o.push({check:"erc20-metadata",result:O.UNKNOWN,detail:u.warning}),a(O.UNKNOWN)):o.push({check:"erc20-metadata",result:O.PASS,detail:`${u.symbol} / ${u.decimals}d`});let l=await this.resolvePools(n,i);if(l.evidence===_.UNAVAILABLE)o.push({check:"liquidity",result:O.UNKNOWN,detail:l.reason}),a(O.UNKNOWN);else if(!l.pools.length)o.push({check:"liquidity",result:O.FAIL,detail:"no pool with liquidity found"}),a(O.FAIL);else{let p=l.pools[0],d=p.liquidityUsd??0;d<5e3?(o.push({check:"liquidity",result:O.CAUTION,detail:`top pool only $${d}`}),a(O.CAUTION)):o.push({check:"liquidity",result:O.PASS,detail:`$${d} on ${p.dex}`}),p.createdAt&&Date.now()-p.createdAt<24*3600*1e3&&(o.push({check:"age",result:O.CAUTION,detail:"pool under 24h old"}),a(O.CAUTION))}if(typeof this.sellSimulation=="function"){let p=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},i).catch(d=>({verdict:O.UNKNOWN,reason:String(d?.message||d)}));o.push({check:"sellability",result:p.verdict,detail:p.retentionBps!=null?`round trip returns ${(p.retentionBps/100).toFixed(2)}% -- ${p.reason}`:p.reason}),a(p.verdict)}else o.push({check:"sellability",result:O.UNKNOWN,detail:"no verified router on this chain, so a round-trip sell simulation cannot run. Treat as unproven -- a buy path is not an exit path."}),a(O.UNKNOWN);return{chainId:t,token:n,verdict:s,checks:o,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function _o(e){let r={...js(e)},n=new Set((e.venues||[]).map(o=>o.kind));e.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,ko({chainId:e.chainId,wrappedNative:e.wrappedNative,stableQuoteAssets:e.stableQuoteAssets||[],resolveQuoteAsset:async(o,s)=>(await r.resolvePools(o,s)).quoteAsset||null})):e.venueKind==="uniswap-v2"&&n.has("router")&&Object.assign(r,vo({chainId:e.chainId,wrappedNative:e.wrappedNative}));let i={};for(let[o,s]of Object.entries(r))i[o]=s.bind(r);return{key:e.key,chainId:e.chainId,name:e.name,rpcEnv:e.rpcEnv,nativeCurrency:e.nativeCurrency,explorer:e.explorer,venues:e.venues||[],capabilities:i}}fe();var zs=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}}]}]);function Ro(){return zs.map(e=>Nr(_o(e)))}lt();var xr=/^0x[0-9a-fA-F]{40}$/,Ks=24,Bo=!1;function Lo(){Bo||(Ro(),Bo=!0)}var q=class extends Error{constructor(t,r){super(r),this.status=t}};function Ws(e){if(Lo(),e==null||e==="")throw new q(400,"chainId is required");let t=Number(e);if(Number.isFinite(t)&&Me(t))return t;let r=_r().find(n=>n.key===String(e).toLowerCase());if(r)return r.chainId;throw new q(400,`unknown chain "${e}"`)}function To(e,t){if(typeof e!="string")throw new q(400,`${t} is required`);let r=e.trim();if(r===""||r.length>Ks)throw new q(400,`${t} is invalid`);if(!/^[A-Za-z0-9._-]+$/.test(r)&&!xr.test(r))throw new q(400,`${t} is invalid`);return r}function Gs(e,t){let r=String(e).trim();if(!/^\d+(\.\d+)?$/.test(r))throw new q(400,"sellAmount must be a positive decimal number");if(Number(r)<=0)throw new q(400,"sellAmount must be greater than zero");let n=Number.isFinite(Number(t))?Number(t):18,[i,o=""]=r.split(".");if(o.length>n)throw new q(400,`sellAmount has more precision than the token's ${n} decimals`);let s=o.padEnd(n,"0"),a=(BigInt(i)*10n**BigInt(n)+BigInt(s||"0")).toString();if(a==="0")throw new q(400,"sellAmount rounds to zero at this token's precision");return a}async function $o(e,t){if(Lo(),xr.test(t)){let l=await Me(e).resolveToken(t).catch(()=>null),p=Number(l?.decimals);return{address:t,decimals:Number.isFinite(p)?p:null}}let r=j[e];if(!r)return null;let n=t.toLowerCase(),i=n==="usdc"?r.usdc:n==="weth"||n==="eth"?r.weth:null;if(!i)return null;let s=await Me(e).resolveToken(i).catch(()=>null),a=Number(s?.decimals);return{address:i,decimals:Number.isFinite(a)?a:null}}async function Uo(e={},t={}){let r=Ws(e.chainId??e.chain),n=To(e.sellSymbol??e.sellToken,"sellSymbol"),i=To(e.buySymbol??e.buyToken,"buySymbol");if(n.toLowerCase()===i.toLowerCase())throw new q(400,"sell and buy assets must differ");let o=typeof e.taker=="string"?e.taker.trim():"";if(!xr.test(o))throw new q(400,"taker must be the wallet address that will sign");let[s,a]=await Promise.all([$o(r,n),$o(r,i)]);if(!s)throw new q(400,`could not resolve sell asset "${n}" on chain ${r}`);if(!a)throw new q(400,`could not resolve buy asset "${i}" on chain ${r}`);let u=Gs(e.sellAmount,s.decimals),l=await xo({chainId:r,tokenIn:s.address||n,tokenOut:a.address||i,amountIn:u,taker:o,decimalsIn:s.decimals??null,decimalsOut:a.decimals??null,source:typeof e.source=="string"&&e.source.trim()!==""?e.source.trim():void 0},t);if(!l.ok)return{ok:!1,reason:l.reason,priceImpactBlocked:!!l.priceImpactBlocked,requiresWalletSignature:!0,backendSigner:!1};let p=a.decimals??18,d=l.minOut??l.chosen?.netOut??l.chosen?.grossOut??null;return{ok:!0,requiresWalletSignature:!0,backendSigner:!1,quote:{sellSymbol:n,buySymbol:i,sellAmount:String(e.sellAmount),buyAmount:d==null?null:String(d),buyAmountFormatted:d==null?null:(Number(d)/10**p).toString(),routeLabel:l.chosen?.source??null,priceImpactPct:Number.isFinite(Number(l.chosen?.priceImpactPct))?Number(l.chosen.priceImpactPct):null,slippageBps:Number.isFinite(Number(l.slippageBps))?Number(l.slippageBps):null,intentHash:l.intentHash??null,minOut:l.minOut??null,requiresApproval:l.requiresApproval??null,warnings:Array.isArray(l.warnings)?l.warnings:[]},transaction:l.transaction??null}}var kr=`oracle swap <chain> <sellAsset> <buyAsset> <amount> --taker <address> [--source X] [--json]
|
|
3
|
+
- `)}`);let i=e.capabilities||{},o=Me.filter(s=>typeof i[s]=="function"),a={key:e.key,chainId:e.chainId,name:e.name,rpcEnv:[...e.rpcEnv],nativeCurrency:e.nativeCurrency?{...e.nativeCurrency}:null,wrappedNative:e.wrappedNative||null,explorer:e.explorer||null,venues:(e.venues||[]).map(s=>({...s})),warnings:n,capabilities(){return{chainId:e.chainId,key:e.key,supported:[...o],unsupported:Me.filter(s=>!o.includes(s))}},supports(s){return o.includes(s)}};for(let s of Me)o.includes(s)?a[s]=async(...c)=>i[s](...c,{scanner:a}):a[s]=async()=>{throw new Error(`${e.key} (chain ${e.chainId}) does not implement "${s}". Supported: ${o.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(a)}function _r(e){let t=ei(e);return vt.set(t.chainId,t),t}function He(e){return vt.get(Number(e))||null}function Rr(){return[...vt.values()]}var Me,_,O,Jo,vt,fe=R(()=>{Me=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),_=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),O=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),Jo=/^0x[0-9a-fA-F]{40}$/;vt=new Map});function Br(e){let{source:t,amountOut:r,minOut:n=null,gasUsd:i=null,feeUsd:o=null,oracleFeeBps:a=0,estimatedGas:s=null,liquidityUsd:c=null,error:l=null,executionReady:p=!1,meta:f={}}=e||{};if(l||r==null)return{source:t,quality:Y.FAILED,amountOut:null,error:l||"no amountOut returned"};let u=Ie(r);if(u==null||u<=0n)return{source:t,quality:Y.FAILED,amountOut:null,error:"non-positive amountOut"};let d=Number(a);return{source:t,quality:i==null?Y.NO_GAS:Y.FULL,amountOut:u.toString(),minOut:Ie(n)?.toString()??null,gasUsd:i,feeUsd:o,oracleFeeBps:Number.isFinite(d)&&d>0?Math.floor(d):0,estimatedGas:s==null?null:String(s),liquidityUsd:c==null?null:Number(c),executionReady:p,meta:f}}async function Tr(e,t,{divisor:r=1000n}={}){let n=Ie(t);if(n==null||n<=0n)return null;let i=n/r>0n?n/r:1n;if(i>=n)return null;let o,a;try{[o,a]=await Promise.all([e(i),e(n)])}catch{return null}let s=Ie(o),c=Ie(a);if(s==null||c==null||s<=0n)return null;let l=Number(s)/Number(i),p=Number(c)/Number(n);return!Number.isFinite(l)||!Number.isFinite(p)||l<=0?null:{impactPct:(1-p/l)*100,probeAmountIn:i.toString(),probeAmountOut:s.toString(),fullAmountOut:c.toString()}}function Lr(e,t,{maxImpactPct:r=25}={}){let n=[],i=[],o=(e.routes??[]).filter(s=>{let c=t?.[s.source];return c?c.impactPct>r?(n.push({source:s.source,impactPct:Number(c.impactPct.toFixed(2)),reason:`price impact ${c.impactPct.toFixed(1)}% exceeds ${r}% ceiling -- the venue cannot absorb this size near the quoted price`}),!1):!0:(i.push(s.source),!0)}),a=[...e.warnings??[]];return n.length&&a.push(`dropped ${n.length} route(s) on price impact: `+n.map(s=>`${s.source} (${s.impactPct}%)`).join(", ")),i.length&&a.push(`price impact NOT measured for: ${i.join(", ")}. These are unproven against thin liquidity, not proven safe.`),{...e,routes:o,best:o[0]??null,impactRejected:n,impactUnmeasured:i,warnings:a}}function It(e,{destPriceUsd:t=null,destDecimals:r=null,liquidityFirst:n=!0,liquidityBandBps:i=50,gasPriceWei:o=null,nativePriceUsd:a=null}={}){let s=e.filter(g=>g.quality!==Y.FAILED),c=e.filter(g=>g.quality===Y.FAILED),l=t!=null&&t>0&&r!=null&&r>=0,p=Number(o),f=Number(a),u=Number.isFinite(p)&&p>0&&Number.isFinite(f)&&f>0,d=s.map(g=>{let y=BigInt(g.amountOut),x=0n,N=!1,$=!1,L=BigInt(g.oracleFeeBps??0),j=L>0n?y*L/10000n:0n;if(l){let de=g.gasUsd,xt=Number(g.meta?.gasUnits??g.estimatedGas);if(de==null&&u&&Number.isFinite(xt)&&xt>0){let pe=xt*p/1e18*f;Number.isFinite(pe)&&pe>=0&&(de=pe,$=!0)}let Nr=(de??0)+(g.feeUsd??0);if(Nr>0){let pe=Nr/t*10**r;Number.isFinite(pe)&&pe>=0&&(x=BigInt(Math.floor(pe)),N=!0)}else de===0&&(N=!0)}let ye=x+j,At=y>ye?y-ye:0n;return{...g,grossOut:y.toString(),netOut:At.toString(),costInDest:x.toString(),oracleFeeInDest:j.toString(),costAccounted:N,gasEstimated:$}}),h=Number(i)>0?Number(i):0,b=d.reduce((g,y)=>BigInt(y.netOut)>g?BigInt(y.netOut):g,0n),m=g=>b>0n?Number((b-BigInt(g))*10000n/b):0,A=[],C=d.slice().sort((g,y)=>BigInt(y.netOut)>BigInt(g.netOut)?1:-1)[0]??null;d.sort((g,y)=>{let x=m(g.netOut)<=h?0:1,N=m(y.netOut)<=h?0:1;if(n&&h>0&&x!==N)return x-N;if(n&&h>0){let $=g.liquidityUsd??-1,L=y.liquidityUsd??-1;if($!==L)return L-$}return BigInt(y.netOut)>BigInt(g.netOut)?1:-1}),n&&h>0&&C&&d[0]&&d[0].source!==C.source&&A.push(`liquidity-first: chose ${d[0].source} (liquidity $${d[0].liquidityUsd??"unknown"}) over best-price ${C.source} within ${h} bps`);let I=d.filter(g=>!g.costAccounted).map(g=>g.source);l?I.length&&A.push(`gas not reported by: ${I.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 S=d[0];if(l&&S&&S.costAccounted===!1){let g=d.find(y=>y.costAccounted&&m(y.netOut)<=h);g&&A.push(`winner ${S.source} has UNMEASURED gas; gas-measured ${g.source} is within ${h} bps and may net more once ${S.source}'s real gas is paid \u2014 prefer it if unsure.`)}let k=d.filter(g=>g.gasEstimated).map(g=>g.source);k.length&&A.push(`gas ESTIMATED (from gas units x current gas price, not measured) for: ${k.join(", ")}. Net includes this estimate so the ranking is gas-inclusive, but the on-chain gas may differ.`);let v=null,E=null;if(d.length>=2&&d[0].costAccounted&&d[1].costAccounted){let g=BigInt(d[0].netOut),y=BigInt(d[1].netOut);y>0n&&(v=Number((g-y)*10000n/y),E=`${d[0].source} vs ${d[1].source}`)}return{best:d[0]??null,routes:d,failed:c,improvementBps:v,spreadBasis:E,rankedOn:l?"net-of-cost":"gross",warnings:A}}async function je(e,{timeoutMs:t=12e3}={}){let r=(i,o)=>Promise.race([i,new Promise((a,s)=>setTimeout(()=>s(new Error(`${o}: timeout`)),t))]);return(await Promise.allSettled(e.map(i=>r(Promise.resolve().then(i.run),i.source)))).map((i,o)=>{let a=e[o].source;return i.status==="rejected"?Br({source:a,error:String(i.reason?.message||i.reason)}):Br({source:a,...i.value})})}var Y,$r,Ie,Ct=R(()=>{fe();Y=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"}),$r={1:"coingecko:ethereum",10:"coingecko:ethereum",56:"coingecko:binancecoin",137:"coingecko:matic-network",8453:"coingecko:ethereum",42161:"coingecko:ethereum",43114:"coingecko:avalanche-2",999:"coingecko:ethereum"},Ie=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}}});import me from"node:net";import ti from"node:dns";function Ve(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=p=>{if(!p)return[];let f=p.split(":"),u=f.at(-1);if(u?.includes(".")){let d=u.split(".").map(Number);if(d.length!==4||d.some(h=>!Number.isInteger(h)||h<0||h>255))return null;f.splice(f.length-1,1,(d[0]<<8|d[1]).toString(16),(d[2]<<8|d[3]).toString(16))}return f.some(d=>!/^[0-9a-f]{1,4}$/.test(d))?null:f.map(d=>Number.parseInt(d,16))},[n,i]=t.split("::"),o=r(n),a=r(i);if(!o||!a)return null;let s=t.includes("::"),c=8-o.length-a.length;if(!s&&c!==0||s&&c<1)return null;let l=[...o,...Array(Math.max(0,c)).fill(0),...a];return l.length!==8?null:Uint8Array.from(l.flatMap(p=>[p>>8,p&255]))}function kt(e,t,r){let n=Math.floor(r/8),i=r%8;for(let a=0;a<n;a+=1)if(e[a]!==t[a])return!1;if(!i)return!0;let o=255<<8-i;return(e[n]&o)===(t[n]&o)}function Ot(e){if(me.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(me.isIPv6(e)){let t=Ve(e);if(!t)return!1;let r=Ve("::ffff:0:0");return kt(t,r,96)?Ot([...t.slice(12)].join(".")):kt(t,Ve("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([i,o])=>kt(t,Ve(i),o)):!1}return!1}function ni(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(ri.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=me.isIP(r);return n!==0&&!Ot(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function Nt(e,{lookupFn:t=ti.promises.lookup}={}){let r=ni(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:me.isIPv6(r.host)?6:4}]};let n;try{n=await t(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(i=>!Ot(i.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function _t({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n;try{let f=await t();r=f.Agent,n=f.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 i=f=>String(f).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),o=new Map,a=f=>(Array.isArray(f)?f:[f]).map(u=>typeof u=="string"?{address:u}:u).filter(u=>u&&u.address).map(u=>({address:u.address,family:u.family||(me.isIPv6(u.address)?6:4)})),s=(f,u,d)=>{o.set(i(f),a(typeof u=="string"?[{address:u,family:d}]:u))},c=f=>{let u=i(f);if(me.isIP(u))return[{address:u,family:me.isIPv6(u)?6:4}];let d=o.get(u);if(!d||!d.length)throw new Error(`refused: unpinned host ${f} during pinned fetch`);return d},l=new r({connect:{lookup(f,u,d){let h;try{h=c(f)}catch(b){return d(b)}return u?.all?d(null,h):d(null,h[0].address,h[0].family)}}}),p=oi((f,u={})=>n(f,{...u,dispatcher:l}),s);return{dispatcher:l,fetch:p,pin:s,resolve:c,async close(){try{await l.destroy()}catch{}}}}function oi(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[Rt]=Object.freeze({pin:t}),e}function Bt(e){return typeof e=="function"&&typeof e[Rt]?.pin=="function"}function Pr(e,t,r){if(!Bt(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[Rt].pin(t,r)}var ri,Rt,Ur=R(()=>{ri=new Set(["localhost","metadata.google.internal","metadata.goog"]);Rt=Symbol.for("oracle.egressGuard.pinCapableFetch")});import{createHash as Fr}from"node:crypto";function ui(e){let t=String(e||"").toLowerCase();return zr.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function li(e){let t={};for(let[r,n]of Object.entries(e||{}))ui(r)||(t[r]=n);return t}function di(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 pi(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function Hr(e){let t=String(e?.method||"");return t?!fi.test(t):!1}function hi(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}return Array.isArray(r)?r.length>0&&r.every(Hr):!r||typeof r!="object"?!1:r.jsonrpc&&r.method?Hr(r):typeof r.type=="string"&&mi.has(r.type)&&r.action==null&&r.signature==null&&r.nonce==null}function bi(e,t,r,n={},i=null){let o={};for(let[u,d]of Object.entries(r||{}))o[u.toLowerCase()]=d;let a=Object.keys(o).filter(u=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(u)),c=[...new Set([...zr,...a])].sort().map(u=>`${u}=${o[u]??""}`).join(`
|
|
4
|
+
`),l=Fr("sha256").update(c).digest("hex").slice(0,32),p=`${n.untrustedUrl?"untrusted":"trusted"}:${n.maxResponseBytes??"unbounded"}`,f=i==null?"-":Fr("sha256").update(String(i)).digest("hex").slice(0,32);return`${e} ${t} ${p} ${l} ${f}`}function gi(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,qr):Math.min(250*2**e,qr)+Math.floor(Math.random()*100)}function Ce(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function Tt(e,t,r){return Ce(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function ke(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function yi(e){return e?e.byteLength??e.length??0:0}async function jr(e,t,{url:r,truncate:n=!1,onOversize:i}={}){if(t==null)return await e.text();let o=Number(e.headers?.get?.("content-length"));if(Number.isFinite(o)&&o>t&&(ke(e),!n))throw Tt(r,`content-length ${o}`,t);let a=e.body?.getReader?.();if(!a){let f=await e.text(),u=Buffer.byteLength(f,"utf8");if(u>t){if(!n)throw Tt(r,`body ${u} bytes`,t);return Buffer.from(f,"utf8").subarray(0,t).toString("utf8")}return f}let s=[],c=0,l=!1;try{for(;;){let{value:f,done:u}=await a.read();if(u)break;if(f&&(s.push(Buffer.from(f)),c+=yi(f),c>t)){l=!0;break}}}finally{if(l)try{await a.cancel()}catch{}try{a.releaseLock?.()}catch{}}if(l&&(typeof i=="function"&&i(),!n))throw Tt(r,`streamed ${c} bytes`,t);let p=Buffer.concat(s);return(l?p.subarray(0,t):p).toString("utf8")}function Vr(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function Ei(e,{fetchImpl:t,method:r,headers:n,body:i,timeoutMs:o,lookupFn:a,realFetch:s,untrustedUrl:c=!1,maxResponseBytes:l=null,importUndici:p,validateResponse:f,signal:u}){let d=new AbortController,h=setTimeout(()=>d.abort(),o),b=u?typeof AbortSignal.any=="function"?AbortSignal.any([u,d.signal]):u:d.signal,m=null,A=t,C=a?{lookupFn:a}:{};if(c&&!s&&!Bt(A))throw Ce(`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=async(S,{status:k=null}={})=>{let v=await Nt(S,C);if(!v.ok)throw Ce(k==null?`HTTP refused ${S}: ${v.error}`:`HTTP redirect to ${S} ${v.error}`,k==null?{}:{status:k});let E=new URL(S).hostname;if(s){if(m&&(await m.close(),m=null),!m)try{m=await _t({requireUndici:!0,...p?{importUndici:p}:{}})}catch(g){throw Ce(k==null?`HTTP refused ${S}: ${g?.message||g}`:`HTTP redirect to ${S} refused: ${g?.message||g}`,k==null?{}:{status:k})}m.pin(E,v.addresses),A=m.fetch}else Pr(A,E,v.addresses);return v};try{let S=String(e),k={...n||{}};c&&await I(S);for(let v=0;v<=Mr;v+=1){let E=await A(S,{method:r,headers:k,body:i,signal:b,redirect:"manual"});if(ai.has(E.status)){if(r!=="GET"&&r!=="HEAD"){let L=await jr(E,l??ci,{url:S,truncate:!0}),j=new Error(`HTTP ${E.status} ${r} ${S} redirected non-idempotent request`);throw j.status=E.status,j.body=Vr(L)??L.slice(0,300),j}if(v===Mr)throw ke(E),new Error(`HTTP redirect loop for ${e}`);let x=E.headers?.get?.("location"),N;try{N=di(x,S)}catch(L){throw ke(E),L}let $=!pi(N,S);if(ke(E),$&&(k=li(k)),c)await I(N,{status:E.status});else if($){let L=await Nt(N,C);if(!L.ok){let j=new Error(`HTTP redirect from ${S} ${L.error}`);throw j.status=E.status,j.retryable=!1,j}s&&L.addresses?.length&&(m||(m=await _t(p?{importUndici:p}:{})),m&&(m.pin(new URL(N).hostname,L.addresses),A=m.fetch))}S=N;continue}if(typeof f=="function")try{await f(E,{url:S})}catch(x){throw ke(E),Ce(x?.message||String(x))}let g=await jr(E,l,{url:S,onOversize:()=>d.abort()}),y=Vr(g);if(!E.ok){let x=new Error(`HTTP ${E.status} ${r} ${S}`);throw x.status=E.status,x.retryAfter=E.headers?.get?.("retry-after")??null,x.body=y??g.slice(0,300),x}return y??g}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(h),m&&await m.close()}}async function T(e,t={}){let r=t.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=t.timeoutMs??12e3,i=(t.method||"GET").toUpperCase(),o={Accept:"application/json",...t.headers||{}},a=t.body;a!=null&&typeof a!="string"&&(o["Content-Type"]=o["Content-Type"]||"application/json",a=JSON.stringify(a));let s=Number.isInteger(t.retries)?Math.max(t.retries,0):si,c=t.lookupFn,l=!t.fetchImpl,p=t.untrustedUrl===!0,f=t.importUndici,u=t.validateResponse,d=t.signal,h=Number(t.maxResponseBytes),b=Number.isFinite(h)&&h>0?Math.floor(h):null,m=async()=>{let k;for(let v=0;v<=s;v++){d?.throwIfAborted?.();try{return await Ei(e,{fetchImpl:r,method:i,headers:o,body:a,timeoutMs:n,lookupFn:c,realFetch:l,untrustedUrl:p,maxResponseBytes:b,importUndici:f,validateResponse:u,signal:d})}catch(E){k=E;let g=E?.status,y=E?.name==="AbortError"||E?.name==="TimeoutError"||d?.aborted,x=new Set([408,425,429]),N=E?.retryable===!1?!1:g!=null?x.has(g)||ii.has(g)&&Dr.has(i):!y&&Dr.has(i);if(v===s||!N)throw E;let $=gi(v,E?.retryAfter);d?await new Promise((L,j)=>{let ye=setTimeout(L,$);d.addEventListener("abort",()=>{clearTimeout(ye),j(d.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await wi($)}}throw k};if(!(t.dedupe!==!1&&!d&&hi(i,a)))return m();let C=bi(i,e,o,{untrustedUrl:p,maxResponseBytes:b},a),I=$t.get(C);if(I)return I;let S=m().finally(()=>$t.delete(C));return $t.set(C,S),S}async function Kr(e,t,r){let n=Array.from(e),i=Math.max(1,Math.min(Number(t)||1,n.length||1)),o=new Array(n.length),a=0;return await Promise.all(Array.from({length:i},async()=>{for(;a<n.length;){let s=a++;o[s]=await r(n[s],s)}})),o}var ii,Dr,si,qr,zr,ai,Mr,ci,$t,fi,mi,wi,K=R(()=>{Ur();ii=new Set([408,425,429,500,502,503,504]),Dr=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),si=2,qr=4e3,zr=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],ai=new Set([301,302,303,307,308]),Mr=3,ci=64*1024;$t=new Map,fi=/(?:^|_)(send|submit|broadcast|sign|requestAirdrop)(?=[A-Z_]|$)/i,mi=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);wi=e=>new Promise(t=>setTimeout(t,e))});import{readFileSync as Si}from"node:fs";import{homedir as Ai}from"node:os";import{join as ze}from"node:path";function xi(){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=Ai();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||ze(t,".config","oracle")).trim();return[e,ze(r,"exec.env")].filter(Boolean)}return[e,ze(t,".config","oracle","exec.env"),ze(t,".config","mad-desk","exec.env")].filter(Boolean)}function Wr(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let i of xi())try{let o=Si(i,"utf8"),a=o.match(new RegExp(`^${t}=(.*)$`,"m"))||o.match(new RegExp(`^${r}=(.*)$`,"m"));if(a&&(n=a[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 Gr=R(()=>{});var Qr=R(()=>{});import{createHash as vi,createHmac as Xr,timingSafeEqual as Ii}from"node:crypto";function We(e){return Array.isArray(e)?`[${e.map(We).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${We(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Jr(e,{required:t=!1}={}){try{return Wr(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function Pt(e){let{signature:t,...r}=e;return r}function Zr(e,{secret:t}={}){let r=Jr(t);return r?{...e,signature:Xr("sha256",r).update(We(Pt(e))).digest("hex")}:e}function Ci(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 vi("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function W(e,{chainId:t,venue:r,data:n,secret:i}={}){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 o=Jr(i);if(o){let d=Xr("sha256",o).update(We(Pt(e))).digest("hex");if(!ki(e.signature,d))throw new Error("auto-slippage guard signature mismatch \u2014 refusing to bind a guard this Oracle did not issue")}let a=Number(e.selectedBps),s=Number(e.capBps);if(!Number.isInteger(a)||a<0||a>Ke||!Number.isInteger(s)||s<0||s>Ke||a>s)throw new Error("auto-slippage guard bounds are invalid");let c=BigInt(e.quoteAmountOut??0),l=BigInt(e.minAmountOut??0);if(c<=0n||l<=0n)throw new Error("auto-slippage guard amounts must be positive");let p=c*BigInt(1e4-a),f=p/10000n;if(p%10000n!==0n&&(f+=1n),l<f)throw new Error("auto-slippage guard is under-protected relative to its quote");let u=_i(n);if(u!=null&&u!==l)throw new Error(`auto-slippage: calldata encodes floor ${u}, not the guard floor ${l} \u2014 refusing to bind`);return Zr({...Pt(e),calldataHash:Ci(n)},{secret:i})}function ki(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:Ii(r,n)}function Lt(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function Oi(e){let t=e==null?Ke:Number(e);if(!Number.isInteger(t)||t<0)throw new Error("auto-slippage cap must be a non-negative integer bps value");return Math.min(t,Ke)}function re({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:i}={}){let o=Lt(e,0),a=o>0?o>=25e4?5:o>=1e5?10:o>=5e4?20:o>=1e4?40:70:n?30:10,s=Math.min(60,Math.abs(Lt(t,0))*2),c=Math.min(40,Math.floor(Math.max(0,Lt(r,0))/5e3)*5),l=Math.max(25,Math.ceil(20+a+s+c)),p=Oi(i);return{mode:"auto",requiredBps:l,selectedBps:Math.min(l,p),capBps:p,executable:l<=p}}function Ni({chainId:e,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:i=0,quoteAgeMs:o=0,crossChain:a=!1,requestedCapBps:s,quotedAtMs:c=Date.now(),ttlMs:l=Yr,secret:p}={}){let f=BigInt(r??0);if(f<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let u=re({liquidityUsd:n,priceChange5m:i,quoteAgeMs:o,crossChain:a,requestedCapBps:s});if(!u.executable)throw new Error(`auto-slippage requires ${u.requiredBps} bps above hard/requested cap ${u.capBps}; route blocked`);let d=Number(c);if(!Number.isFinite(d))throw new Error("auto-slippage: quotedAtMs must be a finite number");let h=Math.min(3e4,Math.max(1e3,Number(l)||Yr)),b=f*BigInt(1e4-u.selectedBps),m=b/10000n;if(b%10000n!==0n&&(m+=1n),m>f&&(m=f),f>0n&&m<=0n)throw new Error(`auto-slippage: quote ${f} is too small to express a ${u.selectedBps} bps floor without rounding to zero`);let A=Number((f-m)*10000n/(f===0n?1n:f));if(A>u.capBps)throw new Error(`auto-slippage: realised floor implies ${A} bps, above cap ${u.capBps} \u2014 refusing to issue a guard weaker than advertised`);return Zr({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:f.toString(),minAmountOut:m.toString(),requiredBps:u.requiredBps,selectedBps:u.selectedBps,capBps:u.capBps,quotedAtMs:d,expiresAtMs:d+h},{secret:p})}function _i(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 o=10;o+64<=t.length;o+=64)n.push(t.slice(o,o+64));let i=o=>n[o]==null?null:BigInt("0x"+n[o]);switch(r){case"0x414bf389":return i(6);case"0x04e45aaf":return i(5);case"0xc04b8d59":{let o=i(0);if(o==null)return null;let a=Number(o)/32;return!Number.isInteger(a)||a<0?null:i(a+4)}case"0xb858183f":{let o=i(0);if(o==null)return null;let a=Number(o)/32;return!Number.isInteger(a)||a<0?null:i(a+3)}case"0xa026383e":return i(6);case"0x38ed1739":case"0x5c11d795":return i(1);case"0x7ff36ab5":case"0xb6f9de95":return i(0);case"0x18cbafe5":case"0x791ac947":return i(1);default:return null}}function F(e,{chainId:t,venue:r,amountOut:n,liquidityUsd:i,priceChange5m:o,crossChain:a,requestedCapBps:s,quotedAtMs:c=Date.now(),ttlMs:l}={}){let p=Ni({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:i,priceChange5m:o,crossChain:a,requestedCapBps:s,quotedAtMs:c,ttlMs:l});return{...e,autoSlippage:p,amountOutMinimum:p.minAmountOut}}var Ke,Yr,ne=R(()=>{Gr();Qr();Ke=100,Yr=2e4});function Ut(e){let t=String(e||"").trim();return/^0x[0-9a-fA-F]{40}$/.test(t)?t:ae}var ae,Ge=R(()=>{ae="0x000000000000000000000000000000000000dEaD"});import{createHash as Ri,createHmac as Bi,timingSafeEqual as Gc}from"node:crypto";function Ft(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Ft).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Ft(e[r])}`).join(",")}}`}function en(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function tn(e=process.env){return en(process.env)||en(e)}function Pi(e){let{prepareHash:t,prepareMac:r,note:n,...i}=e||{};return i}function Ui(e){let t=Pi(e);return Ri("sha256").update(Ft(t)).digest("hex")}function Fi(e,t=tn()){return t?Bi("sha256",t).update(String(e)).digest("hex"):""}function D(e,{provider:t,kind:r,env:n=process.env,nowMs:i=Date.now(),expiresAtMs:o}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let a=Object.prototype.hasOwnProperty.call(e,"oraclePrepared");if(a&&typeof e.oraclePrepared!="boolean")throw new Error("stampPrepared: oraclePrepared must be boolean");let s={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1,oraclePrepared:a?e.oraclePrepared:!0};if(!s.provider)throw new Error("stampPrepared: provider required");if(!s.kind)throw new Error("stampPrepared: kind required");let c=Number(i),l=o==null?c+Ti:Number(o),p=l-c;if(!Number.isSafeInteger(c)||!Number.isSafeInteger(l)||p<=0||p>Li)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let u={...s,preparedAt:c,expiresAt:l,prepareVersion:$i},d=Ui(u),h=tn(n),b=h?Fi(d,h):void 0,m={...u,prepareHash:d};return b&&(m.prepareMac=b),m}var $i,Ti,Li,X=R(()=>{$i=2,Ti=300*1e3,Li=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Contract as Di,JsonRpcProvider as qi}from"ethers";function Ki(e){return zi.test(String(e||""))}async function rn(e,{contract:t=Mi,rpc:r=ji,chainId:n=Hi,balanceOf:i}={}){if(!Ki(e))throw new Error("invalid-address");if(i)return BigInt(await i(e));let o=new qi(r,n,{staticNetwork:!0}),a=new Di(t,Vi,o);return BigInt(await a.balanceOf(e))}var Mi,Hi,ji,Vi,zi,nn=R(()=>{Mi="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",Hi=999,ji="https://rpc.hyperliquid.xyz/evm",Vi=["function balanceOf(address owner) view returns (uint256)"],zi=/^0x[a-fA-F0-9]{40}$/});import{existsSync as Wi,readFileSync as Gi,lstatSync as Qi}from"node:fs";import{homedir as on}from"node:os";import{join as Dt}from"node:path";function Ji(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(sn,t)?sn[t]:Xi}function ns(e=process.env){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){if(e[an])return String(e[an]);let t=e.ORACLE_CONFIG_DIR||Dt(on(),".config","oracle");return Dt(t,"fee-recipient")}return Dt(on(),".config","oracle","fee-recipient")}function os(e=process.env){try{let t=ns(e);if(!Wi(t)||Qi(t).isSymbolicLink())return"";let r=Gi(t,"utf8").trim().toLowerCase();return/^0x[a-f0-9]{40}$/.test(r)?r:""}catch{return""}}function is(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),Yi)}function ss({env:e=process.env,action:t="swap",admin:r=!1}={}){let n=String(e[es]||"").trim(),i=String(e[ts]||rs).trim();if(r===!0)return{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"admin-oracle"};let o=Ji(t),a=is(e[Zi],{fallback:n?o:0}),s=Math.min(a,o);if(!s)return{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"not-configured"};if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"no-recipient"};let c=os(e);return!c||c!==n.toLowerCase()?{bps:0,recipient:"",integrator:i,action:t,applies:!1,reason:"recipient-not-pinned"}:{bps:s,recipient:n,integrator:i,action:t,applies:!0,reason:"configured"}}async function Qe({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={},admin:i=!1}={}){let o=ss({env:t,action:r,admin:i});if(i===!0)return{...o,holderVerificationStatus:"admin-oracle"};let a=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(a))return{...o,holderVerificationStatus:"wallet-required"};try{return BigInt(await rn(a,n))>0n?{...o,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...o,holderVerificationStatus:"non-holder"}}catch{return{...o,holderVerificationStatus:"unavailable"}}}function cn(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 un(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}function ln(e){return e?.applies?{partner:e.integrator,partnerFeeBps:String(e.bps),partnerAddress:e.recipient}:{}}var Yi,Xi,sn,Zi,es,ts,an,rs,Ye=R(()=>{nn();Yi=100,Xi=5,sn=Object.freeze({swap:5,bridge:5,perps:0,nft:0});Zi="ORACLE_INTEGRATOR_FEE_BPS",es="ORACLE_INTEGRATOR_FEE_RECIPIENT",ts="ORACLE_INTEGRATOR_ID",an="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",rs="oracle"});var fn={};te(fn,{LIFI_API:()=>pn,lifiChains:()=>ds,lifiHealth:()=>us,lifiPrepare:()=>ls,lifiQuote:()=>Oe});function Mt(e={}){return(e.baseUrl||process.env.LIFI_API_URL||pn).replace(/\/$/,"")}function cs(e){let t=String(e||qt).toLowerCase();return t===qt.toLowerCase()||t===as}function dn(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 us(e={}){let t=await T(`${Mt(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 Oe(e={},t={}){let{fromChain:r,toChain:n=r,fromToken:i=qt,toToken:o,fromAmount:a,fromAddress:s=ae}=e;if(r==null||!o||!a)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let c=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:i,toToken:o,fromAmount:String(a),fromAddress:s}),l=re({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!l.executable)throw new Error(`lifi: route requires ${l.requiredBps} bps above cap ${l.capBps}`);c.set("slippage",String(l.selectedBps/1e4));let p=await Qe({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[m,A]of Object.entries(un(p)))c.set(m,A);let f=await T(`${Mt(t)}/quote?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),u=f?.estimate?.toAmount||f?.toAmount;if(!u)return{...f,autoSlippagePolicy:l,oracleFee:p};let d=f?.transactionRequest?.to||f?.estimate?.approvalAddress||"lifi",h=F(f,{chainId:Number(r),venue:d,amountOut:u,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),b=f?.estimate?.toAmountMin||f?.toAmountMin;if(b!=null&&BigInt(b)<BigInt(h.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...h,oracleFee:p}}async function ls(e={},t={}){let r=await Oe(e,t),n=r?.transactionRequest;if(!n?.to||!n?.data)throw new Error("lifi: quote did not return an executable transactionRequest");let i=Number(e.fromChain);if(n.chainId!=null&&Number(n.chainId)!==i)throw new Error("lifi: transaction chain mismatch");if(e.fromAddress&&n.from&&String(n.from).toLowerCase()!==String(e.fromAddress).toLowerCase())throw new Error("lifi: transaction sender mismatch");let o=null;if(!cs(e.fromToken)){let a=r?.estimate?.approvalAddress||r?.approvalAddress;if(!a)throw new Error("lifi: ERC20 route missing approvalAddress");let s=r?.action?.fromToken?.address||r?.estimate?.fromToken?.address||e.fromToken;o={token:dn(s,"approval token"),spender:dn(a,"approval spender"),amount:String(e.fromAmount)}}return D({provider:"lifi",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:i,quote:r,autoSlippage:r.autoSlippage,requiresApproval:o,transaction:{chainId:i,from:n.from||e.fromAddress,to:n.to,data:n.data,value:n.value??"0x0",...n.gasLimit!=null?{gasLimit:n.gasLimit}:{},slippageGuard:W(r.autoSlippage,{chainId:i,venue:n.to,data:n.data})}},{provider:"lifi",kind:"lifi-tx"})}async function ds(e={}){return T(`${Mt(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var pn,qt,as,Ht=R(()=>{K();ne();Ge();X();Ye();pn="https://li.quest/v1";qt="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",as="0x0000000000000000000000000000000000000000"});var bn={};te(bn,{PARASWAP_API:()=>mn,paraswapHealth:()=>fs,paraswapPrepare:()=>ps,paraswapPrice:()=>Xe,paraswapTokens:()=>hn});function Ee(e,t){let r=String(e||"");if(!/^0x[0-9a-fA-F]{40}$/.test(r))throw new Error(`${t} must be a 20-byte token address`);return r.toLowerCase()}async function hn(e={},t={}){let r=Number(e.chainId||1);return T(`${jt(t)}/tokens/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function Xe(e={},t={}){let r=Number(e.chainId||e.network||1);if(e.amount==null)throw new Error("amount required");let n=new URLSearchParams({srcToken:Ee(e.srcToken,"srcToken"),destToken:Ee(e.destToken,"destToken"),amount:String(e.amount),srcDecimals:String(Number(e.srcDecimals)),destDecimals:String(Number(e.destDecimals)),side:String(e.side||"SELL").toUpperCase(),network:String(r),version:String(e.version||"6.2")});e.includeDEXS&&n.set("includeDEXS",String(e.includeDEXS)),e.excludeDEXS&&n.set("excludeDEXS",String(e.excludeDEXS));let i=await Qe({wallet:e.userAddress||e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[s,c]of Object.entries(ln(i)))n.set(s,c);let o=await T(`${jt(t)}/prices?${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),a=o?.priceRoute?.destAmount;return a?{...F(o,{chainId:r,venue:o?.priceRoute?.contractAddress||"paraswap-quote",amountOut:a,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,quoteAgeMs:0,requestedCapBps:e.maxSlippageBps??e.slippageBps}),executionReady:!1,executionBlocker:"call prepare to bind the price route to a validated transaction",oracleFee:i}:{...o,executionReady:!1,oracleFee:i}}async function ps(e={},t={}){if(String(e.side||"SELL").toUpperCase()!=="SELL")throw new Error("paraswap: agentic prepare currently supports exact-input SELL only");let r=Number(e.chainId||e.network||1),n=Ee(e.userAddress,"userAddress"),i=await Xe(e,t),o=i?.priceRoute,a=String(o?.contractAddress||"").toLowerCase();if(!a)throw new Error("paraswap: price route missing contractAddress");let s={srcToken:Ee(e.srcToken,"srcToken"),destToken:Ee(e.destToken,"destToken"),srcAmount:String(o.srcAmount||e.amount),destAmount:String(i.amountOutMinimum),priceRoute:o,userAddress:n,ignoreChecks:!1,ignoreGasEstimate:!1};e.receiver&&(s.receiver=Ee(e.receiver,"receiver"));let c=await T(`${jt(t)}/transactions/${r}`,{method:"POST",body:s,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3});if(Number(c.chainId??r)!==r)throw new Error("paraswap: transaction chain mismatch");if(String(c.to||"").toLowerCase()!==a)throw new Error("paraswap: transaction target mismatch");if(c.from&&String(c.from).toLowerCase()!==n)throw new Error("paraswap: transaction sender mismatch");return D({provider:"paraswap",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,quote:i,autoSlippage:i.autoSlippage,requiresApproval:s.srcToken!=="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"?{token:s.srcToken,spender:o.tokenTransferProxy||a,amount:s.srcAmount}:null,transaction:{chainId:r,from:c.from||n,to:c.to,data:c.data,value:c.value??"0x0",...c.gas!=null?{gasLimit:c.gas}:{},slippageGuard:W(i.autoSlippage,{chainId:r,venue:c.to,data:c.data})}},{provider:"paraswap",kind:"paraswap-tx"})}async function fs(e={}){let t=await hn({chainId:1},e),r=Array.isArray(t?.tokens)?t.tokens.length:Object.keys(t?.tokens||{}).length;return{ok:r>0,tokenSample:r}}var mn,jt,Vt=R(()=>{K();ne();X();Ye();mn="https://api.paraswap.io",jt=(e={})=>(e.baseUrl||process.env.PARASWAP_API_URL||mn).replace(/\/$/,"")});function Je({provider:e,defaultUrl:t,hosts:r=[],url:n,strict:i=!1}){let a=(String(n??"").trim()||String(t)).replace(/\/$/,"");if(a===String(t).replace(/\/$/,""))return{baseUrl:a,trusted:!0,host:wn(t)};let s;try{s=new URL(a)}catch{throw new Error(`${e}: baseUrl must be an absolute http(s) URL`)}if(s.protocol!=="http:"&&s.protocol!=="https:")throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);let c=s.host;if(!c)throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);if(new Set([wn(t),...r]).has(c)){let p=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(c);return s.protocol==="http:"&&!p?{baseUrl:a,trusted:!1,host:c,reason:"plaintext http downgrade"}:{baseUrl:a,trusted:!0,host:c}}if(String(process.env[gn]||"")==="1")return{baseUrl:a,trusted:!1,host:c};if(i)throw new Error(`${e}: refusing to call non-allowlisted host ${c} (set ${gn}=1 to permit it)`);return{baseUrl:a,trusted:!1,host:c}}function wn(e){let t=new URL(String(e));if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("unsupported protocol");return t.host}function Ze(e,t,r){let n={...e};if(!r)return n;for(let[i,o]of Object.entries(t||{}))o&&(n[i]=o);return n}var gn,zt=R(()=>{gn="ORACLE_ALLOW_CUSTOM_PROVIDER_URL"});var vn={};te(vn,{ZEROX_API:()=>yn,zeroxHealth:()=>ms,zeroxPrepare:()=>hs,zeroxPrice:()=>xn,zeroxQuote:()=>tt});function En(e={}){return Je({provider:"zerox",defaultUrl:yn,hosts:["api.0x.org"],url:e.baseUrl||process.env.ZEROX_API_URL})}function Sn(e={}){return En(e).baseUrl}function et(e={}){return e.apiKey||process.env.ZEROX_API_KEY||process.env.OX_API_KEY||process.env["0X_API_KEY"]||""}function An(e={}){return Ze({"0x-version":"v2",accept:"application/json"},{"0x-api-key":et(e)},En(e).trusted)}async function ms(e={}){if(!et(e))return{ok:!1,configured:!1,error:"ZEROX_API_KEY not set"};try{let t=await xn({chainId:8453,sellToken:"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",buyToken:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",sellAmount:"1000000000000000"},e);return{ok:!0,configured:!0,buyAmount:t.buyAmount||t.grossBuyAmount}}catch(t){return{ok:!1,configured:!0,error:String(t.message||t).slice(0,160)}}}async function xn(e={},t={}){if(!et(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:i,sellAmount:o,taker:a}=e;if(!n||!i||!o)throw new Error("zeroxPrice requires sellToken, buyToken, sellAmount");let s=new URLSearchParams({chainId:String(r),sellToken:n,buyToken:i,sellAmount:String(o)});return a&&s.set("taker",a),T(`${Sn(t)}/swap/allowance-holder/price?${s}`,{headers:An(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function tt(e={},t={}){if(!et(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:i,sellAmount:o,taker:a}=e;if(!n||!i||!o)throw new Error("zeroxQuote requires sellToken, buyToken, sellAmount");let s=re({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!s.executable)throw new Error(`0x: route requires ${s.requiredBps} bps above cap ${s.capBps}`);let c=new URLSearchParams({chainId:String(r),sellToken:n,buyToken:i,sellAmount:String(o),slippageBps:String(s.selectedBps)});a&&c.set("taker",a);let l=await T(`${Sn(t)}/swap/allowance-holder/quote?${c}`,{headers:An(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),p=l?.buyAmount||l?.grossBuyAmount;return p?F(l,{chainId:r,venue:l?.transaction?.to||l?.to||"0x",amountOut:p,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):{...l,autoSlippagePolicy:s}}async function hs(e={},t={}){if(!e.taker)throw new Error("0x: taker required for executable prepare");let r=await tt(e,t),n=r?.transaction;if(!n?.to||!n?.data)throw new Error("0x: firm quote returned no transaction");let i=Number(e.chainId??8453),o=r?.issues?.allowance?.spender||r?.allowanceTarget;return D({provider:"zerox",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:i,quote:r,autoSlippage:r.autoSlippage,requiresApproval:r?.issues?.allowance?.actual!=null&&BigInt(r.issues.allowance.actual)<BigInt(e.sellAmount)?{token:e.sellToken,spender:o,amount:String(e.sellAmount)}:null,transaction:{chainId:i,from:e.taker,to:n.to,data:n.data,value:n.value??"0x0",...n.gas!=null?{gasLimit:n.gas}:{},slippageGuard:W(r.autoSlippage,{chainId:i,venue:n.to,data:n.data})}},{provider:"zerox",kind:"zerox-tx"})}var yn,Kt=R(()=>{K();ne();zt();X();yn="https://api.0x.org"});function In(e={}){return Je({provider:"oneinch",defaultUrl:bs,hosts:["api.1inch.dev"],url:e.baseUrl||process.env.ONEINCH_API_URL})}function gs(e={}){return In(e).baseUrl}function Cn(e={}){return e.apiKey||process.env.ONEINCH_API_KEY||process.env.ONE_INCH_API_KEY||""}function ws(e={}){let t=Cn(e);return Ze({accept:"application/json"},{Authorization:t?`Bearer ${t}`:""},In(e).trusted)}async function kn(e={},t={}){if(!Cn(t))throw new Error("ONEINCH_API_KEY required for 1inch");let r=Number(e.chainId??1),{src:n,dst:i,amount:o}=e;if(!n||!i||!o)throw new Error("oneinchQuote requires src, dst, amount");let a=new URLSearchParams({src:n,dst:i,amount:String(o)}),s=await T(`${gs(t)}/${r}/quote?${a}`,{headers:ws(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3});return s?.dstAmount?F(s,{chainId:r,venue:"1inch-quote",amountOut:s.dstAmount,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):s}var bs,On=R(()=>{K();ne();zt();X();bs="https://api.1inch.dev/swap/v6.0"});var xu,Nn=R(()=>{xu=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"})});import rt from"node:fs";import ys from"node:os";import Ae from"node:path";import{fileURLToPath as Es}from"node:url";function _n(){return process.env.ORACLE_FAKE_HOME||ys.homedir()}function As(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function nt(){return As()?process.env.ORACLE_CONFIG_DIR||Ae.join(_n(),".config","oracle"):Ae.join(_n(),".config","oracle")}function xs(){return Ae.join(nt(),"desk.json")}function vs(){return Ae.join(nt(),"env")}function Se({force:e=!1}={}){if(Se._done&&!e)return Se._result||null;Se._done=!0;let t={},r=(i,o)=>{if(o==null)return;let a=String(o).trim();a&&(process.env[i]!=null&&String(process.env[i]).trim()!==""||(process.env[i]=a,t[i]=a))};try{let i=vs();if(rt.existsSync(i))for(let o of rt.readFileSync(i,"utf8").split(/\r?\n/)){let a=o.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!a||a[2].startsWith("#"))continue;let s=a[2];(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),r(a[1],s)}}catch{}try{let i=xs();if(rt.existsSync(i)){let o=JSON.parse(rt.readFileSync(i,"utf8"));o&&typeof o=="object"&&(r("ORACLE_DESK_URL",o.deskUrl||o.dataUrl||o.url),r("ORACLE_DATA_URL",o.dataUrl||o.deskUrl||o.url),r("ORACLE_API_URL",o.apiUrl||o.dataUrl||o.deskUrl),r("ORACLE_PUBLIC_URL",o.publicUrl||o.deskUrl||o.dataUrl),r("ORACLE_EXEC_URL",o.execUrl),r("MAD_DESK_URL",o.deskUrl||o.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),Se._result=Object.keys(t).length?t:null,Se._result}var Ss,Nu,Rn=R(()=>{Ss=Ae.dirname(Es(import.meta.url)),Nu=Ae.resolve(Ss,"../..");try{Se()}catch{}});var Tn={};te(Tn,{armPreparedAction:()=>Bs,callSigner:()=>Bn,queueOwnerAction:()=>$n});import{existsSync as Is,readFileSync as Cs}from"node:fs";import{request as ks}from"node:http";import Os from"node:path";function _s(e=process.env){let t=String(e.ORACLE_SIGNER_URL||Ns).replace(/\/$/,""),r;try{r=new URL(t)}catch{return null}return r.hostname!=="127.0.0.1"&&r.hostname!=="localhost"&&r.hostname!=="::1"?null:r.origin}function Rs(e=process.env){if(e.ORACLE_SIGNER_TOKEN)return String(e.ORACLE_SIGNER_TOKEN);let t=Os.join(nt(),"signer","signer-token");return Is(t)?Cs(t,"utf8").trim():null}function Bn(e,{method:t="GET",body:r=null,env:n=process.env,timeoutMs:i=4e3}={}){let o=_s(n),a=Rs(n);return!o||!a?Promise.resolve({ok:!1,error:"local signer is not running"}):new Promise(s=>{let c=new URL(e,o),l=r?Buffer.from(JSON.stringify(r)):null,p=ks({hostname:c.hostname,port:c.port||80,path:c.pathname,method:t,timeout:i,headers:{authorization:`Bearer ${a}`,origin:o,...l?{"content-type":"application/json","content-length":l.length}:{}}},f=>{let u=[];f.on("data",d=>u.push(d)),f.on("end",()=>{let d=Buffer.concat(u).toString("utf8"),h={};try{h=d?JSON.parse(d):{}}catch{h={error:"signer refused"}}s({httpStatus:f.statusCode,...h})})});p.on("timeout",()=>{p.destroy(),s({ok:!1,error:"local signer timed out"})}),p.on("error",()=>s({ok:!1,error:"local signer is not running"})),l&&p.write(l),p.end()})}async function $n(e,t=process.env){if(!e||e.version!==1||!e.surface)throw new Error("queueOwnerAction: version-1 surface envelope required");return Bn("/pending",{method:"POST",body:{artifact:e},env:t,timeoutMs:8e3})}async function Bs(e,t=process.env){let r=e?.localSignerEnvelope||e?.envelope;if(!r||r.version!==1||!r.surface)throw new Error("armPreparedAction: prepared.localSignerEnvelope v1 required");return $n(r,t)}var Ns,Ln=R(()=>{Rn();Ns="http://127.0.0.1:9462"});var Vn={};te(Vn,{COW_CANCEL_TYPES:()=>Dn,COW_HOSTS:()=>it,COW_ORDER_TYPES:()=>ot,COW_SETTLEMENT:()=>Pn,COW_VAULT_RELAYER:()=>Un,armCowOrder:()=>Ds,buildArmedCowOrder:()=>Yt,cowCancelOrders:()=>zs,cowChains:()=>Gs,cowHealth:()=>Us,cowOrder:()=>jn,cowOrderStatus:()=>Hn,cowOrderUid:()=>qs,cowPrepareCancel:()=>js,cowPrepareOrder:()=>Fs,cowQuote:()=>_e,cowSignCancel:()=>Vs,cowSignOrder:()=>Ms,cowSubmitSignedOrder:()=>Hs,cowVerifyOrderFill:()=>Ws});import{TypedDataEncoder as Gt,getAddress as Ne,isAddress as $s}from"ethers";function st(e,t={}){if(t.baseUrl)return t.baseUrl.replace(/\/$/,"");let r=it[Number(e)];if(!r)throw new Error(`cowswap: unsupported chainId ${e}`);return r}function Ts(e,t="v1",r={}){let n=st(e,r);return t==="v1"?n:n.replace(/\/api\/v1$/,`/api/${t}`)}function oe(e,t){let r=String(e||"").trim();if(!$s(r))throw new Error(`cowswap: ${t} must be an address`);return Ne(r).toLowerCase()}function xe(e,t){try{let r=BigInt(String(e));if(r<0n)throw new Error("negative");return r.toString()}catch{throw new Error(`cowswap: ${t} must be a non-negative integer string`)}}function qn(e,t){let r=String(e||"").trim();if(!/^0x[0-9a-fA-F]{64}$/.test(r))throw new Error(`cowswap: ${t} must be bytes32 hex`);return r.toLowerCase()}function Mn(e,t="uid"){let r=String(e||"").trim();if(!/^0x[0-9a-fA-F]{112}$/.test(r))throw new Error(`cowswap: ${t} must be 56-byte order UID hex`);return r.toLowerCase()}function Ls({digest:e,owner:t,validTo:r}={}){let n=qn(e,"order digest").slice(2),i=oe(t,"owner").slice(2).toLowerCase(),o=Number(r);if(!Number.isInteger(o)||o<0||o>4294967295)throw new Error("cowswap: validTo must fit uint32");return`0x${n}${i}${o.toString(16).padStart(8,"0")}`.toLowerCase()}function Qt(e){let t=Pn[Number(e)];if(!t)throw new Error(`cowswap: settlement contract not registered for chain ${e}`);return{name:"Gnosis Protocol",version:"v2",chainId:Number(e),verifyingContract:Ne(t)}}function Ps(e={},t,r){let n=oe(e.sellToken,"sellToken"),i=oe(e.buyToken,"buyToken"),o=oe(e.receiver||r,"receiver"),a=Number(e.validTo);if(!Number.isInteger(a)||a<=0)throw new Error("cowswap: quote.validTo required");let s=qn(e.appData||e.appDataHash||`0x${"0".repeat(64)}`,"appData");return{sellToken:n,buyToken:i,receiver:o,sellAmount:xe(e.sellAmount,"sellAmount"),buyAmount:xe(e.buyAmount,"buyAmount"),validTo:a,appData:s,feeAmount:xe(e.feeAmount??"0","feeAmount"),kind:String(e.kind||"sell"),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance||"erc20"),buyTokenBalance:String(e.buyTokenBalance||"erc20")}}async function Us(e={}){try{let t=await _e({chainId:1,sellToken:Wt[1],buyToken:Fn[1],sellAmountBeforeFee:"1000000000000000",from:ae},e);return{ok:!0,buyAmount:t.quote?.buyAmount||t.buyAmount}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function _e(e={},t={}){let r=Number(e.chainId??1),n=Ut(e.from||e.owner),i=e.sellToken||Wt[r],o=e.buyToken||Fn[r],a=String(e.sellAmountBeforeFee||e.sellAmount||"0");if(!i||!o||a==="0")throw new Error("cowQuote requires sellToken, buyToken, sellAmountBeforeFee");if(/eeeeeeee|native|^eth$/i.test(i)&&(i=Wt[r],!i))throw new Error("no WETH mapping for chain");let s={sellToken:i,buyToken:o,from:n,receiver:e.receiver||n,sellAmountBeforeFee:a,kind:e.kind||"sell",signingScheme:e.signingScheme||"eip1271"},c=await T(`${st(r,t)}/quote`,{method:"POST",body:s,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),l=c?.quote?.buyAmount||c?.buyAmount;return l?F(c,{chainId:r,venue:"cowswap-order",amountOut:l,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):c}async function Fs(e={},t={}){let r=Number(e.chainId??1),n=oe(Ut(e.from||e.owner||e.signer),"owner"),i=await _e({...e,chainId:r,from:n,signingScheme:e.signingScheme||"eip712"},t),o=Ps(i?.quote||i,r,n),a=Qt(r),s={domain:a,types:ot,primaryType:"Order",message:o},c=Gt.hash(a,ot,o),l=Un[r];if(!l)throw new Error(`cowswap: vault relayer not registered for chain ${r}`);return D({provider:"cowswap",orderReady:!0,executionReady:!1,chainId:r,owner:n,signingScheme:"eip712",settlement:a.verifyingContract.toLowerCase(),vaultRelayer:Ne(l).toLowerCase(),quote:i,quoteId:i?.id??e.quoteId??null,typedData:s,cowGuard:{mode:"cow-order",version:1,provider:"cowswap",chainId:r,owner:n,settlement:a.verifyingContract.toLowerCase(),vaultRelayer:Ne(l).toLowerCase(),sellToken:o.sellToken,buyToken:o.buyToken,sellAmount:o.sellAmount,buyAmount:o.buyAmount,validTo:o.validTo,quoteId:i?.id??e.quoteId??null,typedDataHash:c,issuedAtMs:Date.now(),expiresAtMs:Math.min(o.validTo*1e3,Date.now()+2e4)},requiresApproval:{token:o.sellToken,spender:Ne(l).toLowerCase(),amount:o.sellAmount},localSignerEnvelope:Yt({chainId:r,owner:n,typedData:s,quoteId:i?.id??e.quoteId??null,cowGuard:{expiresAtMs:Math.min(o.validTo*1e3,Date.now()+2e4)}})},{provider:"cowswap",kind:"cow-order"})}function Yt(e={},t={}){let r=e.typedData;if(!r?.domain||!r?.types||!r?.message)throw new Error("cowswap: typedData required to arm");let n=Number(e.chainId??r.domain.chainId),i=it[n];if(!i)throw new Error(`cowswap: unsupported chainId ${n}`);let o=oe(e.owner,"owner"),a=Number(t.nowMs??Date.now()),s=Gt.hash(r.domain,r.types,r.message);return Object.freeze({tradeId:`cow:${n}:${s.slice(2)}`,version:1,surface:"evm-order",action:"order",owner:o,destination:"cowswap",chainId:n,expiresAtMs:Number(e.cowGuard?.expiresAtMs??a+2e4),slippageBps:0,fee:{oracleFeeBps:0},artifact:Object.freeze({kind:"cow",chainId:n,submitTo:`${i}/orders`,quoteId:e.quoteId??null,domain:r.domain,types:r.types,message:r.message,typedData:r})})}async function Ds(e={},t={}){let{queueOwnerAction:r}=await Promise.resolve().then(()=>(Ln(),Tn)),n=e.localSignerEnvelope||Yt(e,t);return{...await r(n,t.env),envelope:n,execution:"armed-local",exec:!1}}async function Hn(e={},t={}){let r=Number(e.chainId??1),n=String(e.uid||e.orderUid||"").trim();if(!n)throw new Error("cowOrderStatus requires uid");return T(`${st(r,t)}/orders/${encodeURIComponent(n)}/status`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function jn(e={},t={}){let r=Number(e.chainId??1),n=String(e.uid||e.orderUid||"").trim();if(!n)throw new Error("cowOrder requires uid");return T(`${st(r,t)}/orders/${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}function qs(e={}){let t=e.typedData||e,r=Number(e.chainId??t?.domain?.chainId),n=t?.message||e.order||e.message;if(!n)throw new Error("cowswap: typed order message required");let i=e.cowGuard?.typedDataHash||Gt.hash(Qt(r),ot,n),o=e.owner||e.from||e.signer||n.receiver;return Ls({digest:i,owner:o,validTo:n.validTo})}async function Ms(e={},t={}){throw new Error("cowswap.cowSignOrder refused: @oracle-agent/oracle is prepare-only. Sign with the user wallet; do not pass private keys here.")}async function Hs(e={},t={}){throw new Error("cowswap.cowSubmitSignedOrder refused: @oracle-agent/oracle is prepare-only. Submit signed orders from the user wallet or local operator.")}function js(e={}){let t=Number(e.chainId??1),r=oe(e.owner||e.from||e.signer,"owner"),n=(e.orderUids||e.uids||[e.uid]).filter(Boolean).map((a,s)=>Mn(a,`orderUids[${s}]`));if(!n.length)throw new Error("cowswap: orderUids required");let i=Qt(t);return D({provider:"cowswap",chainId:t,owner:r,orderUids:n,signingScheme:"eip712",typedData:{domain:i,types:Dn,primaryType:"OrderCancellations",message:{orderUids:n}},cancelReady:!0,executableArtifact:!0},{provider:"cowswap",kind:"cow-cancel"})}async function Vs(e={},t={}){throw new Error("cowswap.cowSignCancel refused: @oracle-agent/oracle is prepare-only. Cancel-sign with the user wallet.")}async function zs(e={},t={}){throw new Error("cowswap.cowCancelOrders refused: @oracle-agent/oracle is prepare-only. Cancel from the user wallet or local operator.")}function Ks(e={}){return xe(e.buyAmount??e.executedBuyAmount??"0","trade.buyAmount")}async function Ws(e={},t={}){let r=Number(e.chainId??1),n=Mn(e.uid||e.orderUid),i=t.order||await jn({chainId:r,uid:n},t),o=t.status||i.status||await Hn({chainId:r,uid:n},t).catch(()=>null),a=t.trades||await T(`${Ts(r,"v2",t)}/trades?orderUid=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),s=Array.isArray(a)?a:[],c=e.expectedOwner?oe(e.expectedOwner,"expectedOwner"):null;if(c&&oe(i.owner||s[0]?.owner||c,"owner")!==c)return{ok:!1,provider:"cowswap",chainId:r,uid:n,reason:"owner mismatch",order:i,status:o,trades:s};let l=0n;for(let u of s.filter(d=>String(d.orderUid||"").toLowerCase()===n))l+=BigInt(Ks(u));l===0n&&i.executedBuyAmount!=null&&(l=BigInt(xe(i.executedBuyAmount,"executedBuyAmount")));let p=e.minBuyAmount!=null?BigInt(xe(e.minBuyAmount,"minBuyAmount")):0n,f=l>=p&&String(i.status||o?.status||"").toLowerCase()!=="expired";return{ok:f,provider:"cowswap",chainId:r,uid:n,status:i.status||o?.status||null,executedBuyAmount:l.toString(),minBuyAmount:e.minBuyAmount??null,trades:s,settlementTxs:[...new Set(s.map(u=>u.txHash).filter(Boolean))],order:i,orderStatus:o,reason:f?null:"insufficient fill or expired order"}}function Gs(){return Object.keys(it).map(Number)}var it,Pn,Un,Wt,Fn,ot,Dn,Xt=R(()=>{K();ne();Nn();Ge();X();it={1:"https://api.cow.fi/mainnet/api/v1",100:"https://api.cow.fi/xdai/api/v1",42161:"https://api.cow.fi/arbitrum_one/api/v1",8453:"https://api.cow.fi/base/api/v1"},Pn=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),Un=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"}),Wt={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"},Fn={1:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",42161:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},ot=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"}]}),Dn=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]})});function at(e){return Qs.get(Number(e))||null}function Kn(e,t=process.env){let r=at(e);if(!r)return null;for(let n of r.rpcEnv){let i=(t[n]||"").trim();if(i)return i}return null}var zn,Qs,Jt=R(()=>{zn={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}},Qs=new Map(Object.values(zn).map(e=>[e.chainId,e]))});import{Interface as Ys,getAddress as Xs}from"ethers";function Gn(e,t){try{return Xs(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}function Zs(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=Kn(e,r);return n||Js[Number(e)]||null}function ta(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!ea.test(r))throw new Error(`evm-rpc: ${t} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}function ra(e){let t=new Error(e?.message||JSON.stringify(e));return t.code=e?.code,t}function na(e){if(e?.error)throw ra(e.error);return e?.result}function oa(e,t,r){return`${e}
|
|
5
|
+
${t}
|
|
6
|
+
${JSON.stringify(r??[])}`}async function ia(e,t,r){return T(e,{method:"POST",body:t,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function U(e,t,r=[],n={}){let i=String(t||""),o=ta(i),a=Zs(e,n);if(!a)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);if(o==="eth_chainid"&&n.cacheChainId!==!1){let p=Qn.get(a);if(p!=null)return p}let c=n.dedupe!==!1&&!n.signal?oa(a,i,r):null;if(c&&Re.has(c))return Re.get(c);let l=(async()=>{let p=await ia(a,{jsonrpc:"2.0",id:1,method:t,params:r},n),f=na(p);return o==="eth_chainid"&&typeof f=="string"&&Qn.set(a,f),f})();return c&&(Re.set(c,l),l.finally(()=>{Re.get(c)===l&&Re.delete(c)}).catch(()=>{})),l}async function Yn(e,t={}){let r=await U(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function Xn(e,t={}){let r=await U(e,"eth_gasPrice",[],t);if(r==null)return null;try{return BigInt(r)}catch{return null}}async function Jn(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await U(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function Zn(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=Gn(e.token||e.tokenAddress,"token"),i=Gn(e.account||e.owner||e.address,"account"),o=Wn.encodeFunctionData("balanceOf",[i]),a=await U(r,"eth_call",[{to:n,data:o},e.blockTag||"latest"],t),s=Wn.decodeFunctionResult("balanceOf",a),c=BigInt(s[0]);return{chainId:r,token:n,account:i,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:e.blockTag||"latest"}}var Wn,Js,ea,Re,Qn,he=R(()=>{K();Jt();Wn=new Ys(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);Js={1:"https://ethereum.publicnode.com",137:"https://polygon-bor-rpc.publicnode.com",42161:"https://arbitrum-one-rpc.publicnode.com",8453:"https://base-rpc.publicnode.com",10:"https://optimism-rpc.publicnode.com",988:"https://rpc.stable.xyz",56:"https://bsc-rpc.publicnode.com",43114:"https://avalanche-c-chain-rpc.publicnode.com",999:"https://rpc.hyperliquid.xyz/evm",2741:"https://api.mainnet.abs.xyz",4663:"https://rpc.mainnet.chain.robinhood.com"};ea=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;Re=new Map,Qn=new Map});function eo(e,t){let r=String(e||"").toLowerCase(),n=String(t?.quote||t?.quoteToken?.address||"").toLowerCase(),i=String(t?.base||t?.baseToken?.address||"").toLowerCase();return n===r?{address:t.base||t.baseToken?.address,symbol:t.baseToken?.symbol}:i===r?{address:t.quote||t.quoteToken?.address,symbol:t.quoteToken?.symbol}:{address:t.quote||t.quoteToken?.address,symbol:t.quoteToken?.symbol}}function Zt(e,t=[],{stables:r=[],wrappedNative:n=null}={}){let i=String(e||"").toLowerCase(),o=new Set((r||[]).map(c=>String(c).toLowerCase())),a=String(n||"").toLowerCase(),s=(t||[]).map((c,l)=>{let p=eo(i,c),f=String(p.address||"").toLowerCase(),u=String(p.symbol||"").toLowerCase(),d=Number(c.liquidityUsd??c.liquidity?.usd),h=Number.isFinite(d)?d:0,b=String(c.dex||c.dexId||"").toLowerCase(),m=0;return o.has(f)||sa.has(u)?m=300:a&&f===a&&(m=100),b.includes("v4")?m+=20:b.includes("v3")?m+=10:(b.includes("v2")||b.includes("raydium")||b.includes("orca")||b.includes("meteora"))&&(m+=8),{pool:c,score:m*1e12+h,index:l,otherAddr:f,liquidityUsd:h}});return s.sort((c,l)=>l.score-c.score||c.index-l.index),s.map(c=>c.pool)}function to(e,t=[]){let r=Array.isArray(t)?t:[];return r.length&&eo(e,r[0]).address||null}var sa,er=R(()=>{sa=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"])});function la(e,t,r){let n=G(t),i=G(r),o=G(e?.baseToken?.address),a=G(e?.quoteToken?.address);return o===n&&a===i||o===i&&a===n}function da(e){let t=Number(e?.liquidity?.usd);return Number.isFinite(t)&&t>=0?t:null}function pa(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||aa).replace(/\/$/,"")}async function tr(e,t={}){if(!e)throw new Error("tokenAddress required");return T(`${pa(t)}/latest/dex/tokens/${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}async function ro({chainId:e,tokenA:t,tokenB:r,dexIds:n=[]}={},i={}){return(await Be({chainId:e,tokenA:t,tokenB:r,dexIds:n},i))[0]??null}async function Be({chainId:e,tokenA:t,tokenB:r,dexIds:n=[]}={},i={}){if(e==null||!t||!r)throw new Error("chainId, tokenA, and tokenB required");let o=G(ca[Number(e)]||e),a=new Set(ua(n).filter(Boolean).map(G)),s=[...new Set([t,r].map(u=>String(u)).filter(Boolean))],c=await Promise.allSettled(s.map(u=>tr(u,{...i,baseUrl:i.dexscreenerBaseUrl,timeoutMs:i.dexscreenerTimeoutMs??Math.min(Number(i.timeoutMs??4e3),4e3)}))),l=new Set,p=[];for(let u of c)if(u.status==="fulfilled")for(let d of u.value?.pairs||u.value?.data?.pairs||[]){let h=`${G(d?.chainId)}:${G(d?.dexId)}:${G(d?.pairAddress)}`;l.has(h)||(l.add(h),p.push(d))}return p.filter(u=>G(u?.chainId)===o).filter(u=>la(u,t,r)).filter(u=>!a.size||a.has(G(u?.dexId))).map(u=>({pairAddress:u.pairAddress??null,dexId:u.dexId??null,chainId:u.chainId??null,liquidityUsd:da(u),pairCreatedAt:u.pairCreatedAt??null})).filter(u=>u.liquidityUsd!=null).sort((u,d)=>d.liquidityUsd-u.liquidityUsd)}var aa,ca,G,ua,ct=R(()=>{K();er();aa="https://api.dexscreener.com",ca=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"}),G=e=>String(e??"").toLowerCase(),ua=e=>Array.isArray(e)?e:e==null?[]:[e]});var po={};te(po,{PANCAKE_FEE_TIERS:()=>ut,UNI_V3_CHAINS:()=>V,UNI_V3_FEE_TIERS:()=>so,UNI_V3_VENUES:()=>uo,uniV3Chains:()=>ya,uniV3EthUsdc:()=>lo,uniV3Health:()=>wa,uniV3PrepareExactIn:()=>ga,uniV3QuoteExactIn:()=>Te,uniV3QuoteExactInPath:()=>ba});import{Interface as oo,getAddress as $e,isAddress as io}from"ethers";function nr(e,t){let r=Number(e),n=V[r];if(!n)throw new Error(`uniswap-v3: unsupported chainId ${e} (supported: ${Object.keys(V).join(", ")})`);let i=uo[r]||{};if(!t){if(!n.quoter||!n.router){let c=Object.keys(i).join(", ")||"none registered";throw new Error(`uniswap-v3: chain ${r} (${n.name}) has no canonical Uniswap v3 deployment -- name a venue explicitly (known: ${c})`)}return{chainId:r,venue:n.name,...n}}let o=String(t).toLowerCase();if(o===n.name&&n.quoter&&n.router)return{chainId:r,venue:n.name,...n};let a=i,s=a[o];if(!s){let c=[...n.quoter&&n.router?[n.name]:[],...Object.keys(a)].join(", ");throw new Error(`uniswap-v3: unknown venue "${t}" on chain ${r} (known: ${c})`)}return{chainId:r,venue:o,...n,quoter:s.quoter,router:s.router,feeTiers:s.feeTiers||null}}function rr(e,t){let r=V[Number(t)];if(!e||e===ao||e===co||/^eth$/i.test(String(e)))return $e(r.weth);let n=String(e);if(/^weth$/i.test(n))return $e(r.weth);if(/^usdc$/i.test(n))return $e(r.usdc);if(!io(n))throw new Error(`invalid token address: ${e}`);return $e(n)}function ma(e){let t=String(e||"uniswap").toLowerCase();return t==="uniswap"?["uniswap-v3","uniswap"]:t==="pancakeswap"?["pancakeswap-v3","pancakeswap"]:t==="hyperswap"?["hyperswap-v3","hyperswap"]:[t,`${t}-v3`]}function ha(e,t){if(e.length!==t.length+1)throw new Error("path: fees.length must be tokens.length - 1");let r="0x";for(let n=0;n<t.length;n++)r+=e[n].slice(2).toLowerCase(),r+=Number(t[n]).toString(16).padStart(6,"0");return r+=e[e.length-1].slice(2).toLowerCase(),r}async function Te(e={},t={}){let{chainId:r,quoter:n,router:i,feeTiers:o}=nr(e.chainId??8453,e.venue),a=rr(e.tokenIn||"WETH",r),s=rr(e.tokenOut||V[r].usdc,r),c=BigInt(e.amountIn??0);if(c<=0n)throw new Error("amountIn required (raw base units)");let l=o&&o.length?o:so,p=e.fee!=null?[Number(e.fee)]:e.tryFees===!1?[l[Math.min(2,l.length-1)]]:[...l],u=await Promise.all(p.map(async E=>{let g=lt.encodeFunctionData("quoteExactInputSingle",[{tokenIn:a,tokenOut:s,amountIn:c,fee:E,sqrtPriceLimitX96:0n}]);try{let y=await U(r,"eth_call",[{to:n,data:g},"latest"],t);if(!y||y==="0x")return{fee:E,ok:!1,error:"empty result"};let x=lt.decodeFunctionResult("quoteExactInputSingle",y);return{fee:E,ok:!0,amountOut:x[0].toString(),sqrtPriceX96After:x[1].toString(),initializedTicksCrossed:Number(x[2]),gasEstimate:x[3].toString()}}catch(y){return{fee:E,ok:!1,error:String(y.message||y).slice(0,160)}}})),d=null;for(let E of u)E.ok&&(!d||BigInt(E.amountOut)>BigInt(d.amountOut))&&(d=E);if(!d){let E=u.map(g=>`${g.fee}:${g.error||"fail"}`).join("; ");throw new Error(`uniswap-v3 quote failed chain=${r}: ${E}`)}let h=e.liquidityUsd==null?await Be({chainId:r,tokenA:a,tokenB:s,dexIds:ma(e.venue)},t).catch(()=>[]):[],b={};await Promise.all(h.slice(0,8).map(async E=>{if(!(!E.pairAddress||!io(E.pairAddress)))try{let g=await U(r,"eth_call",[{to:E.pairAddress,data:fa},"latest"],t),y=g&&g!=="0x"&&g.length<=66?Number.parseInt(g,16):NaN;if(!Number.isFinite(y)||y<=0||y>1e6)return;let x=b[y];(x==null||E.liquidityUsd>x.liquidityUsd)&&(b[y]=E)}catch{}}));let m=e.liquidityBandBps==null?50:Number(e.liquidityBandBps),A=null;if(e.fee==null&&m>0&&BigInt(d.amountOut)>0n){let E=BigInt(d.amountOut),y=u.filter(x=>x.ok&&Number((E-BigInt(x.amountOut))*10000n/E)<=m).filter(x=>b[x.fee]?.liquidityUsd!=null).sort((x,N)=>b[N.fee].liquidityUsd-b[x.fee].liquidityUsd)[0];y&&y.fee!==d.fee&&(A={priceBestFee:d.fee,chosenFee:y.fee,chosenPoolUsd:b[y.fee].liquidityUsd,bandBps:m},d=y)}let C=b[d.fee]??null,I=h[0]??null,S=C??I,k=e.liquidityUsd??C?.liquidityUsd??I?.liquidityUsd??null,v=e.liquidityUsd!=null?"caller":C?"pool":I?"pair":null;return F({venue:"uniswap-v3",chainId:r,chain:V[r].name,quoter:n,tokenIn:a,tokenOut:s,amountIn:c.toString(),fee:d.fee,amountOut:d.amountOut,gasEstimate:d.gasEstimate,liquidityUsd:k,liquiditySource:S,liquidityAttribution:v,liquidityPick:A,sqrtPriceX96After:d.sqrtPriceX96After,initializedTicksCrossed:d.initializedTicksCrossed,triedFees:u,best:!0},{chainId:r,venue:i,amountOut:d.amountOut,liquidityUsd:k,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function ba(e={},t={}){let{chainId:r,quoter:n,router:i}=nr(e.chainId??8453),o=(e.tokens||[]).map(u=>rr(u,r)),a=(e.fees||[]).map(Number);if(o.length<2)throw new Error("tokens[] need at least 2 addresses");let s=BigInt(e.amountIn??0);if(s<=0n)throw new Error("amountIn required");let c=ha(o,a),l=lt.encodeFunctionData("quoteExactInput",[c,s]),p=await U(r,"eth_call",[{to:n,data:l},"latest"],t),f=lt.decodeFunctionResult("quoteExactInput",p);return F({venue:"uniswap-v3",chainId:r,chain:V[r].name,quoter:n,tokens:o,fees:a,path:c,amountIn:s.toString(),amountOut:f[0].toString(),gasEstimate:f[3].toString()},{chainId:r,venue:i,amountOut:f[0].toString(),liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function lo(e={},t={}){let r=Number(e.chainId??8453),n=e.amountIn??"1000000000000000",i=await Te({chainId:r,tokenIn:V[r].weth,tokenOut:V[r].usdc,amountIn:n,fee:e.fee},t),o=Number(i.amountOut)/1e6;return{...i,amountOutUsdc:o,pair:"WETH/USDC"}}async function ga(e={},t={}){let r=Number(e.chainId??8453),n=nr(r,e.venue),i=$e(e.recipient),o=String(e.tokenIn||"WETH"),a=!e.tokenIn||o===ao||o===co||/^eth$/i.test(o),s=await Te(e,t),c=no.encodeFunctionData("exactInputSingle",[{tokenIn:s.tokenIn,tokenOut:s.tokenOut,fee:s.fee,recipient:i,amountIn:BigInt(s.amountIn),amountOutMinimum:BigInt(s.amountOutMinimum),sqrtPriceLimitX96:0n}]),l=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),f=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+l,u=no.encodeFunctionData("multicall",[f,[c]]);return D({provider:"uniswap-v3",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,deadline:f,quote:s,autoSlippage:s.autoSlippage,requiresApproval:a?null:{token:s.tokenIn,spender:n.router,amount:s.amountIn},transaction:{chainId:r,from:i,to:n.router,data:u,value:a?s.amountIn:"0",slippageGuard:W(s.autoSlippage,{chainId:r,venue:n.router,data:u})}},{provider:"uniswap-v3",kind:"univ3-swap-tx"})}async function wa(e={}){let t=Number(e.chainId??8453);try{let r=await lo({chainId:t,amountIn:"1000000000000000"},e);return{ok:!0,chainId:t,fee:r.fee,amountOutUsdc:r.amountOutUsdc,midPxHint:r.amountOutUsdc/.001}}catch(r){return{ok:!1,chainId:t,error:String(r.message||r).slice(0,200)}}}async function ya(){return Object.entries(V).map(([e,t])=>({chainId:Number(e),name:t.name,quoter:t.quoter,weth:t.weth,usdc:t.usdc}))}var V,so,fa,lt,no,ao,co,ut,uo,dt=R(()=>{he();ct();ne();X();V={1:{name:"ethereum",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",usdc:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},8453:{name:"base",quoter:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",router:"0x2626664c2603336E57B271c5C0b26F421741e481",weth:"0x4200000000000000000000000000000000000006",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"},42161:{name:"arbitrum",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",usdc:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},4663:{name:"robinhood",quoter:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",router:"0xcaf681a66d020601342297493863e78c959e5cb2",weth:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",usdc:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"},999:{name:"hyperevm",weth:"0x5555555555555555555555555555555555555555",usdc:"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb"},10:{name:"optimism",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x4200000000000000000000000000000000000006",usdc:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"},56:{name:"bsc",quoter:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",router:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",weth:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",usdc:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"},137:{name:"polygon",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",usdc:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"},43114:{name:"avalanche",quoter:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",router:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",weth:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",usdc:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"}},so=[100,500,3e3,1e4],fa="0xddca3f43",lt=new oo(["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)"]),no=new oo(["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)"]),ao="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",co="0x0000000000000000000000000000000000000000",ut=[100,500,2500,1e4],uo={56:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ut}},8453:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ut}},42161:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ut}},999:{hyperswap:{name:"hyperswap",quoter:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",router:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D"}}}});var ho={};te(ho,{UNI_V4_CHAINS:()=>Q,UNI_V4_FEE_TIERS:()=>sr,computeV4PoolId:()=>mt,decodeV4HookPermissions:()=>cr,uniV4Chains:()=>Ba,uniV4Health:()=>$a,uniV4InspectHook:()=>Na,uniV4PrepareExactIn:()=>Ra,uniV4QuoteExactIn:()=>ht,uniV4QuoteExactOut:()=>_a});import{AbiCoder as Ea,Interface as or,getAddress as J,isAddress as ir,keccak256 as Sa}from"ethers";function cr(e){let t=Fe(e),r=Number(BigInt(t)&xa),n=Object.fromEntries(fo.map(([a,s])=>[s,!!(r&1<<a)])),o=[["beforeSwapReturnsDelta","beforeSwap"],["afterSwapReturnsDelta","afterSwap"],["afterAddLiquidityReturnsDelta","afterAddLiquidity"],["afterRemoveLiquidityReturnsDelta","afterRemoveLiquidity"]].filter(([a,s])=>n[a]&&!n[s]).map(([a,s])=>`${a} requires ${s}`);return Object.freeze({address:t,mask:r,maskHex:`0x${r.toString(16).padStart(4,"0")}`,flags:Object.freeze(n),enabled:Object.freeze(fo.filter(([,a])=>n[a]).map(([,a])=>a)),valid:o.length===0,violations:Object.freeze(o)})}function Ue(e){let t=Number(e),r=Q[t];if(!r)throw new Error(`uniswap-v4: unsupported chainId ${e} (supported: ${Object.keys(Q).join(", ")})`);return{chainId:t,...r}}function Fe(e){if(e==null||e==="")return H;let t=String(e);if(!ir(t))throw new Error(`invalid Uniswap V4 hook address: ${e}`);return J(t)}function ve(e,t){let r=Q[Number(t)];if(Pe(e))return J(r.weth);let n=String(e);if(/^weth$/i.test(n))return J(r.weth);if(/^usdc$/i.test(n)||/^usdg$/i.test(n))return J(r.usdc);if(!ir(n))throw new Error(`invalid token address: ${e}`);return J(n)}function Pe(e){let t=String(e||"").trim().toLowerCase();return!t||t===ka.toLowerCase()||t===H.toLowerCase()||t==="eth"}function mt({currency0:e,currency1:t,fee:r,tickSpacing:n,hooks:i=H}){let o=J(e),a=J(t);if(o.toLowerCase()===a.toLowerCase())throw new Error("poolKey currencies must differ");let[s,c]=o.toLowerCase()<a.toLowerCase()?[o,a]:[a,o],l=Fe(i);return Sa(Le.encode(["address","address","uint24","int24","address"],[s,c,Number(r),Number(n),l]))}function ur({tokenIn:e,tokenOut:t,fee:r,tickSpacing:n,hooks:i=H}){let o=J(e),a=J(t),[s,c]=o.toLowerCase()<a.toLowerCase()?[o,a]:[a,o],l=o.toLowerCase()===s.toLowerCase();return{poolKey:{currency0:s,currency1:c,fee:Number(r),tickSpacing:Number(n),hooks:Fe(i)},zeroForOne:l}}function Oa({hook:e,codePresent:t,initialized:r,dynamicFee:n}){let i=cr(e),o=i.enabled.some(l=>l.endsWith("ReturnsDelta")),a=i.flags.beforeSwap||i.flags.afterSwap||i.flags.beforeDonate||i.flags.afterDonate,s=[],c="none";return e!==H&&(c="low",s.push("nonzero hook requires independent contract review")),n&&(c="medium",s.push("pool uses a dynamic LP fee")),a&&(c="medium",s.push("hook runs during swap or donate flow")),o&&(c="high",s.push("hook can return custom accounting deltas")),i.valid||(c="critical",s.push(...i.violations)),n&&e===H&&(c="critical",s.push("dynamic-fee pool has no hook authority")),e!==H&&i.enabled.length===0&&(c="critical",s.push("nonzero hook declares no permissions")),r||(c="critical",s.push("pool is not initialized")),e!==H&&!t&&(c="critical",s.push("hook address has no deployed bytecode")),Object.freeze({tier:c,audited:!1,requiresReview:e!==H,returnsDelta:o,reasons:Object.freeze(s)})}async function Na(e={},t={}){let r=Ue(e.chainId??8453);if(!r.stateView)throw new Error(`uniswap-v4: no StateView on chain ${r.chainId}`);let n=ve(e.tokenIn||"WETH",r.chainId),i=ve(e.tokenOut||r.usdc,r.chainId),o=Number(e.fee),a=Number(e.tickSpacing);if(!Number.isInteger(o)||o<0||o>16777215)throw new Error("uniswap-v4 inspectHook requires uint24 fee");if(!Number.isInteger(a)||a<-8388608||a>8388607)throw new Error("uniswap-v4 inspectHook requires int24 tickSpacing");let s=Fe(e.hooks),{poolKey:c}=ur({tokenIn:n,tokenOut:i,fee:o,tickSpacing:a,hooks:s}),l=mt(c),p=t.rpcCall||U,f=pt.encodeFunctionData("getSlot0",[l]),u=pt.encodeFunctionData("getLiquidity",[l]),[d,h,b]=await Promise.all([p(r.chainId,"eth_call",[{to:r.stateView,data:f},"latest"],t),p(r.chainId,"eth_call",[{to:r.stateView,data:u},"latest"],t),s===H?Promise.resolve(null):p(r.chainId,"eth_getCode",[s,"latest"],t)]),m=pt.decodeFunctionResult("getSlot0",d),A=pt.decodeFunctionResult("getLiquidity",h)[0],C=m[0],I=C>0n,S=s===H?null:typeof b=="string"&&b!=="0x"&&b.length>4,k=!!(o&ar),v=Oa({hook:s,codePresent:S,initialized:I,dynamicFee:k});return Object.freeze({venue:"uniswap-v4",chainId:r.chainId,stateView:r.stateView,poolId:l,poolKey:Object.freeze(c),pool:Object.freeze({initialized:I,sqrtPriceX96:C.toString(),tick:Number(m[1]),protocolFee:Number(m[2]),lpFee:Number(m[3]),liquidity:A.toString(),dynamicFee:k}),hook:Object.freeze({address:s,codePresent:S,codeBytes:S?(b.length-2)/2:0,permissions:cr(s)}),risk:v})}async function ht(e={},t={}){let{chainId:r,quoter:n,poolManager:i,universalRouter:o}=Ue(e.chainId??8453),a=ve(e.tokenIn||"WETH",r),s=ve(e.tokenOut||Q[r].usdc,r),c=BigInt(e.amountIn??0);if(c<=0n)throw new Error("amountIn required (raw base units)");if(c>0xffffffffffffffffffffffffffffffffn)throw new Error("amountIn exceeds uint128");let l=e.fee!=null&&e.tickSpacing!=null?[{fee:Number(e.fee),tickSpacing:Number(e.tickSpacing)}]:e.tryTiers===!1?[{fee:500,tickSpacing:10}]:[...sr],p=e.hooks||H,u=await Promise.all(l.map(async g=>{let{poolKey:y,zeroForOne:x}=ur({tokenIn:a,tokenOut:s,fee:g.fee,tickSpacing:g.tickSpacing,hooks:p}),N=ft.encodeFunctionData("quoteExactInputSingle",[{poolKey:y,zeroForOne:x,exactAmount:c,hookData:"0x"}]);try{let $=await(t.rpcCall||U)(r,"eth_call",[{to:n,data:N},"latest"],t);if(!$||$==="0x")return{...g,ok:!1,error:"empty result"};let L=ft.decodeFunctionResult("quoteExactInputSingle",$);return{fee:g.fee,tickSpacing:g.tickSpacing,ok:!0,amountOut:L[0].toString(),gasEstimate:L[1].toString(),poolKey:y,zeroForOne:x,poolId:mt({...y})}}catch($){return{...g,ok:!1,error:String($.message||$).slice(0,160)}}})),d=null;for(let g of u)g.ok&&(!d||BigInt(g.amountOut)>BigInt(d.amountOut))&&(d=g);if(!d){let g=u.map(y=>`${y.fee}/${y.tickSpacing}:${y.error||"fail"}`).join("; ");throw new Error(`uniswap-v4 quote failed chain=${r}: ${g}`)}let h=e.liquidityUsd==null?await Be({chainId:r,tokenA:a,tokenB:s,dexIds:mo},t).catch(()=>[]):[],b=new Map;for(let g of h){let y=String(g.pairAddress||"").toLowerCase();y&&b.set(y,g)}let m=g=>b.get(String(g.poolId||"").toLowerCase())??null,A=e.liquidityBandBps==null?50:Number(e.liquidityBandBps),C=null;if(!(e.fee!=null&&e.tickSpacing!=null)&&A>0&&BigInt(d.amountOut)>0n){let g=BigInt(d.amountOut),x=u.filter(N=>N.ok&&Number((g-BigInt(N.amountOut))*10000n/g)<=A).filter(N=>m(N)?.liquidityUsd!=null).sort((N,$)=>m($).liquidityUsd-m(N).liquidityUsd)[0];x&&x.poolId!==d.poolId&&(C={priceBestFee:d.fee,chosenFee:x.fee,chosenPoolUsd:m(x).liquidityUsd,bandBps:A},d=x)}let I=m(d),S=h[0]??null,k=I??S,v=e.liquidityUsd??I?.liquidityUsd??S?.liquidityUsd??null,E=e.liquidityUsd!=null?"caller":I?"pool":S?"pair":null;return F({venue:"uniswap-v4",chainId:r,chain:Q[r].name,poolManager:i,quoter:n,universalRouter:o||null,tokenIn:a,tokenOut:s,amountIn:c.toString(),fee:d.fee,tickSpacing:d.tickSpacing,hooks:d.poolKey.hooks,poolId:d.poolId,zeroForOne:d.zeroForOne,amountOut:d.amountOut,gasEstimate:d.gasEstimate,liquidityUsd:v,liquiditySource:k,liquidityAttribution:E,liquidityPick:C,triedTiers:u,best:!0,executionReady:!1,prepareReady:typeof e.recipient=="string"&&ir(e.recipient)&&Number.isInteger(Number(e.slippageBps))&&Number(e.slippageBps)>=0&&Number(e.slippageBps)<=100&&Number.isInteger(Number(e.deadlineSeconds))&&Number(e.deadlineSeconds)>=30&&Number(e.deadlineSeconds)<=600&&!Pe(e.tokenIn)&&!Pe(e.tokenOut)&&(e.hookData==null||String(e.hookData).toLowerCase()==="0x")&&d.poolKey.hooks===H&&!(d.fee&ar)},{chainId:r,venue:o||n,amountOut:d.amountOut,liquidityUsd:v,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function _a(e={},t={}){let{chainId:r,quoter:n,poolManager:i,universalRouter:o}=Ue(e.chainId??8453),a=ve(e.tokenIn||"WETH",r),s=ve(e.tokenOut||Q[r].usdc,r),c=BigInt(e.amountOut??0);if(c<=0n)throw new Error("amountOut required (raw base units)");if(c>0xffffffffffffffffffffffffffffffffn)throw new Error("amountOut exceeds uint128");let l=e.fee!=null&&e.tickSpacing!=null?[{fee:Number(e.fee),tickSpacing:Number(e.tickSpacing)}]:e.tryTiers===!1?[{fee:500,tickSpacing:10}]:[...sr],p=e.hooks||H,u=await Promise.all(l.map(async b=>{let{poolKey:m,zeroForOne:A}=ur({tokenIn:a,tokenOut:s,fee:b.fee,tickSpacing:b.tickSpacing,hooks:p}),C=ft.encodeFunctionData("quoteExactOutputSingle",[{poolKey:m,zeroForOne:A,exactAmount:c,hookData:"0x"}]);try{let I=await(t.rpcCall||U)(r,"eth_call",[{to:n,data:C},"latest"],t);if(!I||I==="0x")return{...b,ok:!1,error:"empty result"};let S=ft.decodeFunctionResult("quoteExactOutputSingle",I);return{fee:b.fee,tickSpacing:b.tickSpacing,ok:!0,amountIn:S[0].toString(),gasEstimate:S[1].toString(),poolKey:m,zeroForOne:A,poolId:mt({...m})}}catch(I){return{...b,ok:!1,error:String(I.message||I).slice(0,160)}}})),d=null;for(let b of u)b.ok&&(!d||BigInt(b.amountIn)<BigInt(d.amountIn))&&(d=b);if(!d){let b=u.map(m=>`${m.fee}/${m.tickSpacing}:${m.error||"fail"}`).join("; ");throw new Error(`uniswap-v4 exact-output quote failed chain=${r}: ${b}`)}let h=e.liquidityUsd==null?await ro({chainId:r,tokenA:a,tokenB:s,dexIds:mo},t).catch(()=>null):null;return{venue:"uniswap-v4",chainId:r,chain:Q[r].name,poolManager:i,quoter:n,universalRouter:o||null,tokenIn:a,tokenOut:s,amountIn:d.amountIn,amountOut:c.toString(),gasEstimate:d.gasEstimate,fee:d.fee,tickSpacing:d.tickSpacing,hooks:d.poolKey.hooks,poolId:d.poolId,zeroForOne:d.zeroForOne,liquidityUsd:e.liquidityUsd??h?.liquidityUsd??null,liquiditySource:h,triedTiers:u,best:!0,executionReady:!1,prepareReady:!1}}async function Ra(e={},t={}){if(["operation","exactOutput","amountOut","multihop","path","positionManager","modifyLiquidities","commands","actions"].some(S=>Object.hasOwn(e,S)))throw new Error("uniswap-v4 unsupported operation shape is inspect/quote-only");let n=Number(e.chainId??8453),i=Ue(n);if(Fe(e.hooks)!==H)throw new Error("uniswap-v4 nonzero hooks are inspect/quote-only until a code-hash-specific adapter exists");if(Number(e.fee)&ar)throw new Error("uniswap-v4 dynamic-fee pools are inspect/quote-only until a code-hash-specific adapter exists");if(e.hookData!=null&&String(e.hookData).toLowerCase()!=="0x")throw new Error("uniswap-v4 opaque hookData is inspect/quote-only until a code-hash-specific adapter exists");if(!e.recipient)throw new Error("uniswap-v4 prepare requires recipient");let a=J(e.recipient);if(e.slippageBps==null)throw new Error("uniswap-v4 prepare requires explicit slippageBps");let s=Number(e.slippageBps);if(!Number.isInteger(s)||s<0||s>100)throw new Error("slippageBps must be an integer from 0 through 100");if(e.deadlineSeconds==null)throw new Error("uniswap-v4 prepare requires explicit deadlineSeconds");let c=Number(e.deadlineSeconds);if(!Number.isInteger(c)||c<30||c>600)throw new Error("deadlineSeconds must be an integer from 30 through 600");if(Pe(e.tokenIn)||Pe(e.tokenOut))throw new Error("uniswap-v4 prepare currently requires ERC-20 tokenIn and tokenOut; native routes are not inferred");let l=await ht(e,t);if(!i.universalRouter)throw new Error(`uniswap-v4: no Universal Router on chain ${n}`);let p=BigInt(l.amountOut)*BigInt(1e4-s)/10000n,f={currency0:l.zeroForOne?l.tokenIn:l.tokenOut,currency1:l.zeroForOne?l.tokenOut:l.tokenIn,fee:l.fee,tickSpacing:l.tickSpacing,hooks:l.hooks},d=Le.encode(["tuple(tuple(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 amountIn,uint128 amountOutMinimum,uint256 minHopPriceX36,bytes hookData)"],[[f,l.zeroForOne,BigInt(l.amountIn),p,0n,"0x"]]),h=Le.encode(["address","uint256"],[l.tokenIn,BigInt(l.amountIn)]),b=Le.encode(["address","uint256"],[l.tokenOut,p]),m=Le.encode(["bytes","bytes[]"],[Ia,[d,h,b]]),C=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+c,I=Aa.encodeFunctionData("execute",[va,[m],C]);return D({provider:"uniswap-v4",prepareReady:!0,calldataReady:!0,executionReady:!1,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,deadline:C,quote:{...l,amountOutMinimum:p.toString(),slippageBps:s},hookInspection:null,requiresApproval:{token:l.tokenIn,spender:Ca,amount:l.amountIn,note:"Universal Router V4 settlement uses Permit2; Permit2 authorization for the Universal Router is also required"},transaction:{chainId:n,from:a,to:i.universalRouter,data:I,value:"0"}},{provider:"uniswap-v4",kind:"univ4-swap-tx"})}async function Ba(){return Object.entries(Q).map(([e,t])=>({chainId:Number(e),name:t.name,poolManager:t.poolManager,quoter:t.quoter,stateView:t.stateView||null,universalRouter:t.universalRouter||null,weth:t.weth,usdc:t.usdc}))}async function $a(e={}){let t=Ue(e.chainId??8453),r=await U(t.chainId,"eth_getCode",[t.quoter,"latest"],e),n=typeof r=="string"&&r!=="0x"&&r.length>4;return{ok:n,chainId:t.chainId,quoter:t.quoter,poolManager:t.poolManager,codeBytes:n?(r.length-2)/2:0}}var Le,H,Q,sr,ft,Aa,pt,fo,xa,ar,va,Ia,Ca,ka,mo,lr=R(()=>{he();ct();ne();X();Le=Ea.defaultAbiCoder(),H="0x0000000000000000000000000000000000000000",Q={1:{name:"ethereum",poolManager:"0x000000000004444c5dc75cB358380D2e3dE08A90",quoter:"0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203",stateView:"0x7ffe42c4a5deea5b0fec41c94c136cf115597227",universalRouter:"0x66a9893cc07d91d95644aedd05d03f95e1dba8af",weth:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",usdc:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},10:{name:"optimism",poolManager:"0x9a13f98cb987694c9f086b1f5eb990eea8264ec3",quoter:"0x1f3131a13296fb91c90870043742c3cdbff1a8d7",stateView:"0xc18a3169788f4f75a170290584eca6395c75ecdb",universalRouter:"0x851116d9223fabed8e56c0e6b8ad0c31d98b3507",weth:"0x4200000000000000000000000000000000000006",usdc:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"},56:{name:"bsc",poolManager:"0x28e2ea090877bf75740558f6bfb36a5ffee9e9df",quoter:"0x9f75dd27d6664c475b90e105573e550ff69437b0",stateView:"0xd13dd3d6e93f276fafc9db9e6bb47c1180aee0c4",universalRouter:"0x1906c1d672b88cd1b9ac7593301ca990f94eae07",weth:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",usdc:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"},137:{name:"polygon",poolManager:"0x67366782805870060151383f4bbff9dab53e5cd6",quoter:"0xb3d5c3dfc3a7aebff71895a7191796bffc2c81b9",stateView:"0x5ea1bd7974c8a611cbab0bdcafcb1d9cc9b3ba5a",universalRouter:"0x1095692a6237d83c6a72f3f5efedb9a670c49223",weth:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",usdc:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"},8453:{name:"base",poolManager:"0x498581fF718922c3f8e6A244956aF099B2652b2b",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",stateView:"0xa3c0c9b65bad0b08107aa264b0f3db444b867a71",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",weth:"0x4200000000000000000000000000000000000006",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"},42161:{name:"arbitrum",poolManager:"0x360e68faccca8ca495c1b759fd9eee466db9fb32",quoter:"0x3972c00f7ed4885e145823eb7c655375d275a1c5",stateView:"0x76fd297e2d437cd7f76d50f01afe6160f86e9990",universalRouter:"0xa51afafe0263b40edaef0df8781ea9aa03e381a3",weth:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",usdc:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},43114:{name:"avalanche",poolManager:"0x06380c0e0912312b5150364b9dc4542ba0dbbc85",quoter:"0xbe40675bb704506a3c2ccfb762dcfd1e979845c2",stateView:"0xc3c9e198c735a4b97e3e683f391ccbdd60b69286",universalRouter:"0x94b75331ae8d42c1b61065089b7d48fe14aa73b7",weth:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",usdc:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"},4663:{name:"robinhood",poolManager:"0x8366a39cc670b4001a1121b8f6a443a643e40951",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",stateView:"0xf3334192d15450cdd385c8b70e03f9a6bd9e673b",universalRouter:"0x8876789976dEcBfCbBbe364623C63652db8C0904",weth:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",usdc:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"}},sr=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200},{fee:25e3,tickSpacing:8}],ft=new or(["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)"]),Aa=new or(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),pt=new or(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96,int24 tick,uint24 protocolFee,uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),fo=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"]]),xa=(1n<<14n)-1n,ar=8388608;va="0x10",Ia="0x060c0f",Ca="0x000000000022D473030F116dDEE9F6B43aC78BA3",ka="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";mo=["uniswap-v4","uniswapv4"]});function Pa(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Ta).replace(/\/$/,"")}function Ua(e={}){return(e.baseUrl||process.env.DEFILLAMA_API_URL||La).replace(/\/$/,"")}async function bt(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return T(`${Pa(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function bo(e={}){return T(`${Ua(e)}/protocols`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??2e4})}var Ta,La,dr=R(()=>{K();Ta="https://coins.llama.fi",La="https://api.llama.fi"});var fr={};te(fr,{ACROSS_API:()=>go,HOP_API:()=>wo,RELAY_API:()=>yo,acrossHealth:()=>Da,acrossSuggestedFees:()=>Eo,hopHealth:()=>qa,hopQuote:()=>So,relayHealth:()=>Ma,relayPrepare:()=>Ha,relayQuote:()=>pr});async function Da(e={}){try{return{ok:!0,estimatedFillTimeSec:(await Eo({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 Eo(e={},t={}){let{token:r,destinationToken:n=r,originChainId:i,destinationChainId:o,amount:a}=e;if(!r||i==null||o==null||!a)throw new Error("acrossSuggestedFees requires token, originChainId, destinationChainId, amount");let s=new URLSearchParams({token:r,destinationToken:n,originChainId:String(i),destinationChainId:String(o),amount:String(a)}),c=(t.baseUrl||process.env.ACROSS_API_URL||go).replace(/\/$/,"");return T(`${c}/suggested-fees?${s}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function qa(e={}){try{let t=await So({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 So(e={},t={}){let{amount:r,token:n="ETH",fromChain:i="ethereum",toChain:o="arbitrum"}=e;if(!r)throw new Error("hopQuote requires amount");let a=e.slippage==null?void 0:Math.round(Number(e.slippage)*100),s=re({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:i!==o,requestedCapBps:e.maxSlippageBps??e.slippageBps??a});if(!s.executable)throw new Error(`hop: route requires ${s.requiredBps} bps above cap ${s.capBps}`);let c=new URLSearchParams({amount:String(r),token:n,fromChain:i,toChain:o,slippage:String(s.selectedBps/100)}),l=(t.baseUrl||process.env.HOP_API_URL||wo).replace(/\/$/,""),p=await T(`${l}/quote?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),f=p?.estimatedRecieved||p?.estimatedReceived;return f?F(p,{chainId:Number(e.originChainId||e.chainId||Fa[i]||0),venue:p?.tx?.to||"hop",amountOut:f,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:i!==o,requestedCapBps:e.maxSlippageBps??e.slippageBps??a}):{...p,autoSlippagePolicy:s}}async function Ma(e={}){try{let t=await pr({user:ae,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 pr(e={},t={}){let{user:r=ae,originChainId:n,destinationChainId:i,originCurrency:o="0x0000000000000000000000000000000000000000",destinationCurrency:a="0x0000000000000000000000000000000000000000",amount:s,tradeType:c="EXACT_INPUT"}=e;if(n==null||i==null||!s)throw new Error("relayQuote requires originChainId, destinationChainId, amount");let l=re({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(i),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!l.executable)throw new Error(`relay: route requires ${l.requiredBps} bps above cap ${l.capBps}`);let p=(t.baseUrl||process.env.RELAY_API_URL||yo).replace(/\/$/,""),f=await T(`${p}/quote`,{method:"POST",body:{user:r,originChainId:Number(n),destinationChainId:Number(i),originCurrency:o,destinationCurrency:a,amount:String(s),tradeType:c,slippageTolerance:String(l.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),u=f?.details?.currencyOut?.amount;return!u||!/^\d+$/.test(String(u))?{...f,autoSlippagePolicy:l}:F(f,{chainId:Number(n),venue:f?.steps?.[0]?.items?.[0]?.data?.to||"relay",amountOut:u,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(i),requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Ha(e={},t={}){let r=await pr(e,t),n=Number(e.originChainId),i=(r.steps||[]).flatMap(s=>(s.items||[]).filter(c=>c?.data?.to&&c?.data?.data).map(c=>({stepId:s.id,...c.data})));if(!i.length)throw new Error("relay: quote returned no executable transaction items");let o=String(r?.autoSlippage?.venue||"").toLowerCase();if(i.some(s=>String(s.to).toLowerCase()!==o))throw new Error("relay: route includes a separate approval/transaction that is not yet safely bound");let a=i.map(s=>({chainId:n,from:s.from||e.user,to:s.to,data:s.data,value:s.value??"0x0",...s.gasLimit!=null||s.gas!=null?{gasLimit:s.gasLimit??s.gas}:{},slippageGuard:W(r.autoSlippage,{chainId:n,venue:s.to,data:s.data})}));return D({provider:"relay",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:r,autoSlippage:r.autoSlippage,transactions:a},{provider:"relay",kind:"relay-tx"})}var go,wo,yo,Fa,mr=R(()=>{K();ne();Ge();X();go="https://across.to/api",wo="https://api.hop.exchange/v1",yo="https://api.relay.link",Fa={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453}});function gt(e){if(!Array.isArray(e))return null;let t=0,r=!1;for(let n of e){let i=Z(n?.amountUSD);i!=null&&(t+=i,r=!0)}return r?t:null}async function xo(e,t={}){let r=$r[Number(e)];if(!r)return null;try{let n=await bt([r],t);return Z(n?.coins?.[r]?.price)}catch{return null}}async function ja(e={}){try{let t=await bo({...e,baseUrl:e.defillamaApiBaseUrl,timeoutMs:e.defillamaTimeoutMs??Math.min(Number(e.timeoutMs??5e3),5e3)});return Array.isArray(t)?t:[]}catch{return[]}}function Va(e,t={}){let r=ce(t.tool||t.provider||t.bridge||t.protocol),n=[];return e==="lifi"&&r&&r!=="lifi"&&n.push(...Ao[r]||[r]),n.push(...Ao[ce(e)]||[e]),n}function za(e,t,r={}){let n=Array.isArray(e)?e:[],i=Va(t,r).map(ce).filter(Boolean);for(let o of i){let a=n.find(c=>ce(c?.slug)===o||ce(c?.name)===o),s=Z(a?.tvl);if(s!=null)return{liquidityUsd:s,protocol:a?.name??a?.slug??o}}for(let o of i){let a=n.find(c=>{let l=ce(c?.category);return!l.includes("bridge")&&!l.includes("crosschain")?!1:ce(c?.slug).includes(o)||ce(c?.name).includes(o)}),s=Z(a?.tvl);if(s!=null)return{liquidityUsd:s,protocol:a?.name??a?.slug??o}}return null}function hr({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:i,slippageBps:o,decimalsIn:a,decimalsOut:s,nativePriceUsd:c=null,destDecimalsPromise:l=null,opts:p={}}){let f=[];return f.push({source:"lifi",run:async()=>{let u=await Oe({fromChain:e,toChain:e,fromToken:t,toToken:r,fromAmount:n},p),d=u?.estimate??u?.[0]?.estimate;return{amountOut:d?.toAmount,minOut:d?.toAmountMin,gasUsd:gt(d?.gasCosts),feeUsd:gt(d?.feeCosts),oracleFeeBps:u?.oracleFee?.applies?u.oracleFee.bps:0,meta:{tool:u?.tool??u?.toolDetails?.name,oracleFee:u?.oracleFee??null}}}}),a!=null&&f.push({source:"paraswap",run:async()=>{let u=s??(await Promise.resolve(l))?.decimals;if(u==null)throw new Error("paraswap needs destination decimals; none supplied or resolvable");let d=await Xe({chainId:e,srcToken:t,destToken:r,amount:n,srcDecimals:a,destDecimals:u},p),h=d?.priceRoute;return{amountOut:h?.destAmount,gasUsd:Z(h?.gasCostUSD),oracleFeeBps:d?.oracleFee?.applies?d.oracleFee.bps:0,meta:{bestRoute:h?.bestRoute?.[0]?.swaps?.[0]?.swapExchanges?.[0]?.exchange,oracleFee:d?.oracleFee??null}}}}),process.env.ZEROX_API_KEY&&f.push({source:"0x",run:async()=>{let u=await tt({chainId:e,sellToken:t,buyToken:r,sellAmount:n,taker:i},p),d=null,h=u?.totalNetworkFee,b=await Promise.resolve(c);return h!=null&&b&&(d=Number(h)/1e18*b),{amountOut:u?.buyAmount,minOut:u?.minBuyAmount,gasUsd:d,meta:{source:u?.route?.fills?.[0]?.source}}}}),process.env.ONEINCH_API_KEY&&f.push({source:"1inch",run:async()=>{let u=await kn({chainId:e,src:t,dst:r,amount:n},p),d=null;return u?.gas!=null&&c&&(d=null),{amountOut:u?.dstAmount,gasUsd:d,meta:{gasUnits:u?.gas}}}}),f.push({source:"cow",run:async()=>{let u=await _e({chainId:e,sellToken:t,buyToken:r,sellAmountBeforeFee:String(n),from:i},p),d=u?.quote??u,h=d?.feeAmount;return{amountOut:d?.buyAmount,gasUsd:0,meta:{intent:!0,feeAmountInSellToken:h,settlement:"solver-executed"}}}}),Q[Number(e)]&&f.push({source:"uniswap-v4",run:async()=>{let u=await ht({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:i,slippageBps:o},p);return{amountOut:u?.amountOut,minOut:u?.minOut??u?.amountOutMinimum??null,gasUsd:null,liquidityUsd:u?.liquidityUsd??null,meta:{onchain:!0,venue:"uniswap-v4",fee:u?.fee,tickSpacing:u?.tickSpacing,poolId:u?.poolId,hooks:u?.hooks,gasUnits:u?.gasEstimate,quoter:u?.quoter,poolManager:u?.poolManager,prepareReady:u?.prepareReady===!0,executionReady:!1}}}}),V[Number(e)]&&f.push({source:"uniswap-v3",run:async()=>{let u=await Te({chainId:e,tokenIn:t,tokenOut:r,amountIn:n},p);return{amountOut:u?.amountOut,minOut:u?.minOut??u?.amountOutMinimum??null,gasUsd:null,liquidityUsd:u?.liquidityUsd??null,meta:{onchain:!0,fee:u?.fee,gasUnits:u?.gasEstimate,quoter:u?.quoter}}}}),f}function vo({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:i,taker:o,opts:a={}}){let s=[],c=null,l=async(p,f={})=>(c||=ja(a),za(await c,p,f));return s.push({source:"lifi",run:async()=>{let p=await Oe({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:i},a),f=p?.estimate??p?.[0]?.estimate,u={tool:p?.tool??p?.toolDetails?.name,durationSeconds:Z(f?.executionDuration)},d=await l("lifi",u);return{amountOut:f?.toAmount,minOut:f?.toAmountMin,gasUsd:gt(f?.gasCosts),feeUsd:gt(f?.feeCosts),oracleFeeBps:p?.oracleFee?.applies?p.oracleFee.bps:0,liquidityUsd:d?.liquidityUsd??null,meta:{...u,liquidityProtocol:d?.protocol,oracleFee:p?.oracleFee??null}}}}),s.push({source:"relay",run:async()=>{let{relayQuote:p}=await Promise.resolve().then(()=>(mr(),fr)),u=(await p({user:o,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(i)},a))?.details,d={durationSeconds:Z(u?.timeEstimate),rate:u?.rate},h=await l("relay",d);return{amountOut:u?.currencyOut?.amount,minOut:u?.currencyOut?.minimumAmount,gasUsd:Z(u?.totalImpact?.usd)!=null?Math.abs(Z(u.totalImpact.usd)):null,liquidityUsd:h?.liquidityUsd??null,meta:{...d,liquidityProtocol:h?.protocol}}}}),s.push({source:"across",run:async()=>{let{acrossSuggestedFees:p}=await Promise.resolve().then(()=>(mr(),fr)),f=await p({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(i)},a),u=f?.totalRelayFee?.total,d=null;if(u!=null)try{let b=BigInt(String(i))-BigInt(String(u));b>0n&&(d=b.toString())}catch{}let h=await l("across");return{amountOut:d,gasUsd:null,liquidityUsd:h?.liquidityUsd??null,meta:{derivedFromFees:!0,durationSeconds:Z(f?.estimatedFillTimeSec),limits:f?.limits?{min:f.limits.minDeposit,max:f.limits.maxDeposit}:void 0,liquidityProtocol:h?.protocol}}}}),s}var Z,ce,Ao,Io=R(()=>{Ht();Vt();Kt();On();Xt();dt();lr();dr();Ct();Z=e=>{let t=Number(e);return Number.isFinite(t)?t:null};ce=e=>String(e??"").toLowerCase().replace(/[^a-z0-9]/g,""),Ao=Object.freeze({across:["across"],relay:["relaychain","relay"],lifi:["jumper-(li.fi-powered)","lifi"],stargate:["stargate-v2","stargate-v1","stargate"],hop:["hop-protocol","hop"],debridge:["debridge"],synapse:["synapse"],connext:["connext"],cbridge:["celer-bridge","celer-cbridge","cbridge"],celer:["celer-bridge","celer-cbridge","cbridge"],squid:["squid"],symbiosis:["symbiosis"],wormhole:["wormhole"],mayan:["mayan"],allbridge:["allbridge"],thorchain:["thorchain"]})});async function Co(e,t,r){let n=Ka[Number(e)];if(!n)return{priceUsd:null,decimals:null};let i=`${n}:${t}`;try{let a=(await bt([i],r))?.coins?.[i],s=Number(a?.price),c=Number(a?.decimals);return{priceUsd:Number.isFinite(s)?s:null,decimals:Number.isFinite(c)?c:null}}catch{return{priceUsd:null,decimals:null}}}async function wt(e,t={}){let{chainId:r,tokenIn:n,tokenOut:i,amountIn:o}=e;if(r==null||!n||!i||o==null)throw new Error("bestSwapRoute requires chainId, tokenIn, tokenOut, amountIn");let a=xo(r,t),s=Co(r,i,t),c=Xn(r,t).catch(()=>null),l=hr({...e,nativePriceUsd:a,decimalsOut:e.decimalsOut,destDecimalsPromise:s,opts:t}),[p,f,u]=await Promise.all([je(l,{timeoutMs:t.timeoutMs??12e3}),s,c]);a.catch(()=>{});let d=await a.then(m=>m,()=>null),h=It(p,{destPriceUsd:f.priceUsd,destDecimals:e.decimalsOut??f.decimals,liquidityBandBps:t.liquidityBandBps??50,gasPriceWei:u,nativePriceUsd:d}),b=t.maxImpactPct===void 0?25:t.maxImpactPct;if(b!=null&&h.best){let m=h.best.source,C=await Tr(async I=>{let S=hr({...e,amountIn:I.toString(),nativePriceUsd:a,decimalsOut:e.decimalsOut,destDecimalsPromise:s,opts:t}).filter(v=>v.source===m);return S.length?(await je(S,{timeoutMs:t.timeoutMs??12e3}))?.[0]?.amountOut??null:null},o);if(C){let I=Lr(h,{[m]:C},{maxImpactPct:b});return{kind:"swap",chainId:r,tokenIn:n,tokenOut:i,amountIn:String(o),...I,sourcesTried:l.length,sourcesAnswered:p.filter(S=>S.quality!==Y.FAILED).length,note:br(I,l.length),priceImpact:{[m]:Number(C.impactPct.toFixed(2))}}}}return{kind:"swap",chainId:r,tokenIn:n,tokenOut:i,amountIn:String(o),...h,sourcesTried:l.length,sourcesAnswered:p.filter(m=>m.quality!==Y.FAILED).length,note:br(h,l.length)}}async function ko(e,t={}){let{fromChainId:r,toChainId:n,tokenIn:i,tokenOut:o,amountIn:a}=e;if(r==null||n==null||!i||!o||a==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 s=Co(n,o,t),c=vo({...e,opts:t}),[l,p]=await Promise.all([je(c,{timeoutMs:t.timeoutMs??15e3}),s]),f=It(l,{destPriceUsd:p.priceUsd,destDecimals:e.decimalsOut??p.decimals,liquidityBandBps:t.liquidityBandBps??50}),u=f.routes.map(d=>({source:d.source,seconds:d.meta?.durationSeconds??null})).filter(d=>d.seconds!=null);return{kind:"bridge",fromChainId:r,toChainId:n,tokenIn:i,tokenOut:o,amountIn:String(a),...f,durations:u,sourcesTried:c.length,sourcesAnswered:l.filter(d=>d.quality!==Y.FAILED).length,note:br(f,c.length)}}function Wa(e){let t=e?.meta?.oracleFee;return t?.applies?` \xB7 ${cn(t)}`:""}function br(e,t){if(!e.best)return"no source returned a usable route";let r=e.routes.length,n=Wa(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 i=e.improvementBps,o=i/100;if(i<.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 a=o>=.01?`${o.toFixed(2)}%`:`${i.toFixed(2)}bps`;return`best of ${r} routes, ranked on ${e.rankedOn}: ${a} 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}var Ka,gr=R(()=>{Ct();Io();Ye();dr();he();Ka={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"}});var Ho=R(()=>{});var sd,ad,jo=R(()=>{Ho();sd=Object.freeze([100,50,25]),ad=Object.freeze([100,50,25,10])});function w(e){return P(e)?String(e).replace(cc,t=>`\\${t}`):B}function P(e){return e==null?!1:typeof e=="number"?Number.isFinite(e):typeof e=="string"?e.trim()!=="":!0}function ee(e){if(!P(e))return B;let t=String(e).replace(/`/g,"");return t===""?B:`\`${t}\``}function ge(e,{decimals:t=2}={}){if(!P(e))return B;let r=Number(e);return Number.isFinite(r)?r.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:t}):B}function M(e,{decimals:t=2}={}){let r=ge(e,{decimals:t});return r===B?B:`${r} USD`}function Ir(e,{decimals:t=2}={}){let r=ge(e,{decimals:t});return r===B?B:`${r}%`}function Et(e){let t=ge(e,{decimals:0});return t===B?B:`${t} bps`}function we(e,t){if(!P(e))return B;let r=Number(t);if(!Number.isInteger(r)||r<0||r>77)return B;let n;try{n=BigInt(typeof e=="string"?e.trim():e)}catch{return B}let i=n<0n,o=i?-n:n,a=10n**BigInt(r),s=(o/a).toString(),c=(o%a).toString().padStart(r,"0").replace(/0+$/,"");return`${i?"-":""}${s}${c?`.${c}`:""}`}function uc(e){if(typeof e=="number"&&Number.isFinite(e))return e<0||e>1?B:e>=.75?"HIGH":e>=.4?"MEDIUM":"LOW";if(typeof e=="string"){let t=e.trim().toUpperCase();if(t==="HIGH"||t==="MEDIUM"||t==="LOW")return t}return B}function le(e={}){let t=e.chainId;if(!P(t)||!Number.isFinite(Number(t)))return P(e.chain)?w(e.chain):B;let n=at(t)?.name||(P(e.chain)?String(e.chain):B);return`${w(n)} (chainId ${Number(t)})`}function Vo(e={}){return w(e.venue??e.dex??e.pool?.venue)}function lc(e){return e==null?"NONE (text card only)":typeof e=="string"?e.trim()?ee(e):"NONE (text card only)":e.error||e.ok===!1||e.available===!1?`UNAVAILABLE${P(e.error)?` \u2014 ${w(e.error)}`:""} (text card stands)`:P(e.url)?ee(e.url):"NONE (text card only)"}function Cr(e={},{now:t=Date.now()}={}){let r=e.grant??e.session??null;if(!r||typeof r!="object")return{allowed:!1,reason:"no local grant/session",actions:[]};if(r.local===!1)return{allowed:!1,reason:"grant is not local",actions:[]};if(r.revoked===!0)return{allowed:!1,reason:"grant revoked",actions:[]};let n=r.expiresAt??r.expiry;if(P(n)){let o=typeof n=="number"?n:Date.parse(n);if(!Number.isFinite(o))return{allowed:!1,reason:"grant expiry unreadable",actions:[]};if(o<=t)return{allowed:!1,reason:"grant expired",actions:[]}}return{allowed:!0,reason:"valid local grant",actions:Array.isArray(r.actions)&&r.actions.length?r.actions.slice():["BUY","SELL"]}}function dc(e){let t=Cr(e);return t.allowed?`${t.actions.map(r=>w(r)).join(" / ")} (${w(t.reason)})`:`prepare-only \u2014 ${w(t.reason)}`}function ie(e,t,r={}){let n=[`*${e}*`];for(let[i,o]of t)n.push(`${i}: ${o==null||o===""?B:o}`);return n.push(`Chart: ${lc(r.chart)}`),n.push(`Actions: ${dc(r)}`),Array.isArray(r.warnings)&&r.warnings.length&&n.push(`Warnings: ${r.warnings.map(i=>w(i)).join("; ")}`),(P(r.source)||P(r.fetchedAt))&&n.push(`Source: ${w(r.source)} at ${w(r.fetchedAt)}`),n.join(`
|
|
7
|
+
`)}function se(e){return["Confidence",uc(e.confidence)]}function pc(e){let t=e.quote;if(!t||typeof t!="object")return[];let r=P(t.decimals)?we(t.amountOutRaw??t.out??t.raw,t.decimals):B;return[["Quote out (raw)",ee(t.amountOutRaw??t.out??t.raw)],["Quote out",r===B?B:`${w(r)} ${w(t.symbol??"")}`.trim()]]}function zo(e){let t=e.autoSlippage;if(!t||typeof t!="object")return["Auto-slippage",B];let r=Et(t.selectedBps),n=Et(t.capBps);return["Auto-slippage",r===B&&n===B?B:`${r} selected, cap ${n}`]}function fc(e={}){let t=e||{};return ie(`ORACLE TOKEN \u2014 ${w(t.symbol??t.token??t.name)}`,[["Chain",le(t)],["Venue",Vo(t)],["Name",w(t.name)],["Address",ee(t.address??t.mint??t.contract)],["Price",M(t.priceUsd,{decimals:8})],["Market cap",M(t.marketCapUsd)],["Liquidity",M(t.liquidityUsd)],["Volume 24h",M(t.volume24hUsd)],["Change 24h",Ir(t.priceChange24h)],["Fee tier",P(t.feeTier)?`${Et(Number(t.feeTier)/100)} (${ge(t.feeTier,{decimals:0})})`:B],["Age",w(t.age)],...pc(t),zo(t),se(t)],t)}function mc(e={}){let t=e||{};return ie(`ORACLE LAUNCH \u2014 ${w(t.symbol??t.token??t.name)}`,[["Chain",le(t)],["Venue",Vo(t)],["Address",ee(t.address??t.mint??t.contract)],["Pool",ee(t.pool?.address??t.poolAddress??t.pool)],["Liquidity",M(t.liquidityUsd)],["Route ready",w(t.routeReady)],["Sellable",w(t.sellable)],["Sell sim",w(t.sellSimulation??t.sellSim)],["Smart wallets",w(t.smartWalletOverlap)],["Risk",w(t.risk??t.riskStatus)],["Prepared ticket",w(t.preparedTicket??t.ticketStatus)],zo(t),se(t)],t)}function hc(e={}){let t=e||{};return ie(`ORACLE HIP-3 \u2014 ${w(t.market??t.coin??t.name)}`,[["Venue",`Hyperliquid builder-dex ${w(t.dex)}`],["Market",w(t.market??t.coin)],["Mark",M(t.markPx,{decimals:6})],["Oracle",M(t.oraclePx,{decimals:6})],["Funding",Ir(t.funding,{decimals:6})],["Open interest",M(t.openInterestUsd)],["Depth",w(t.depth)],["Liquidation notes",w(t.liquidationNotes??t.riskNotes)],["Account context",w(t.accountContext)],se(t)],t)}function bc(e={}){let t=e||{};return ie(`ORACLE HIP-4 \u2014 ${w(t.event??t.market??t.name)}`,[["Venue",`Hyperliquid HIP-4 ${w(t.dex??"outcome")}`],["Event",w(t.event)],["Outcome",w(t.outcome)],["Market id",ee(t.marketId??t.market)],["Bid",M(t.bid,{decimals:6})],["Ask",M(t.ask,{decimals:6})],["Depth",w(t.depth)],["Edge",Ir(t.edge)],["Position",w(t.position)],se(t)],t)}function gc(e={}){let t=e||{};return ie(`ORACLE POLYMARKET \u2014 ${w(t.event??t.market??t.name)}`,[["Venue","Polymarket CLOB"],["Event",w(t.event)],["Market",w(t.market)],["Market id",ee(t.marketId??t.conditionId??t.tokenId)],["Yes",M(t.yesPrice,{decimals:4})],["No",M(t.noPrice,{decimals:4})],["Best bid / ask",`${M(t.bestBid,{decimals:4})} / ${M(t.bestAsk,{decimals:4})}`],["Volume",M(t.volumeUsd)],["Resolution risk",w(t.resolutionRisk)],["Order intent",w(t.orderIntent)],se(t)],t)}function wc(e={}){let t=e||{},r=P(t.completedSplits)&&P(t.totalSplits)?`${ge(t.completedSplits,{decimals:0})} / ${ge(t.totalSplits,{decimals:0})}`:B;return ie(`ORACLE TWAP \u2014 ${w(t.pair??t.symbol??t.name)}`,[["Chain",le(t)],["Side",w(t.side??t.direction)],["Amount",`${w(we(t.amountTotal??t.amount,t.decimals??18))} ${w(t.symbol??"")}`.trim()],["Splits",`${ge(t.totalSplits,{decimals:0})} over ${w(t.window)}`],["Progress",r],["Avg price",M(t.averagePrice,{decimals:6})],["Next split",w(t.nextSplitAt)],["Slippage cap",Et(t.slippageBps)],["Status",w(t.status)],se(t)],t)}function yc(e={}){let t=e||{},r=t.approval??t.revokeCheck??{},n=r.needsRevoke&&r.spender?`revoke.cash \u2014 ${w(r.spender)}`:r.needsRevoke===!1?"revoke.cash \u2014 clean":"revoke.cash \u2014 unchecked";return ie(`ORACLE BRIDGE \u2014 ${w(t.pair??t.fromSymbol)} \u2192 ${w(t.toSymbol??"")}`.replace(/→ $/,""),[["Bridging","deBridge \xB7 LI.FI \u2014 best route wins"],["From chain",le({chainId:t.fromChainId,chain:t.fromChain})],["To chain",le({chainId:t.toChainId,chain:t.toChain})],["Amount",`${w(we(t.amount,t.fromDecimals??18))} ${w(t.fromSymbol??"")}`.trim()],["Best route",w(t.bestRoute??t.winner)],["Est. received",`${w(we(t.amountOut,t.toDecimals??18))} ${w(t.toSymbol??"")}`.trim()],["Fee",M(t.feeUsd)],["Est. time",w(t.estimatedTime)],["Revoke check",n],["All providers",w(t.providers?.join(", "))],["Preparable",w(t.preparable)],se(t)],t)}function Ec(e){let r=(Array.isArray(e)?e:[]).slice(1,4).map(n=>{let i=w(n.source??n.venue??n.name),o=n.improvementBps==null&&n.deltaBps==null?null:Number(n.improvementBps??n.deltaBps),a=Number.isFinite(o)?`${Math.abs(o).toFixed(0)} bps behind`:"spread UNKNOWN";return`${i} (${a})`});return r.length?r.join("; "):B}function Sc(e){let t=e.rankedOn??e.swap?.rankedOn??e.best?.rankedOn;return P(t)?w(t):B}function kr(e={}){let t=e||{},r=t.swap&&typeof t.swap=="object"?t.swap:t,n=t.bridge&&typeof t.bridge=="object"?t.bridge:null,i=r.best??r.winner??{},o=`${w(t.tokenInSymbol??t.fromSymbol??"IN")} \u2192 ${w(t.tokenOutSymbol??t.toSymbol??"OUT")}`,a=[["Intent",w(t.intent??"swap")],["Chain",le({chainId:t.chainId??r.chainId,chain:t.chain??r.chain})],["Pair",o],["Amount in",`${w(we(t.amountIn??r.amountIn,t.decimalsIn??18))} ${w(t.tokenInSymbol??"")}`.trim()],["Best swap",w(i.source??i.venue??r.bestRoute??t.bestRoute)],["Net out",`${w(we(i.netOut??i.amountOut??r.amountOut,t.decimalsOut??18))} ${w(t.tokenOutSymbol??"")}`.trim()],["Ranked on",Sc(r)],["Gas accounted",w(i.costAccounted===!0?"yes":i.costAccounted===!1?"no \u2014 gross ranking may flatter this route":null)],["Spread vs next",P(r.improvementBps)?`${w(r.improvementBps)} bps`:B],["Runners-up",Ec(r.routes??t.routes)]];if(n){let s=n.best??n.winner??{};a.push(["Best bridge",w(s.source??n.bestRoute??t.bestBridge)],["Bridge out",`${w(we(s.netOut??s.amountOut??n.amountOut,t.bridgeDecimalsOut??t.decimalsOut??18))} ${w(t.bridgeOutSymbol??t.tokenOutSymbol??"")}`.trim()],["Bridge to",le({chainId:n.toChainId??t.toChainId,chain:n.toChain??t.toChain})],["Est. time",w(n.estimatedTime??s.meta?.durationSeconds)])}else a.push(["Best bridge","same-chain \u2014 use Best swap"]);return a.push(["Preparable",w(t.preparable??i.executionReady)],se(t)),ie(`ORACLE SWAP \u2014 ${o}`,a,t)}function Ac(e={}){let t=e||{};return ie("ORACLE APPROVE \u2014 local signer",[["Pending id",ee(t.id??(typeof t.digest=="string"?t.digest.slice(0,8):null))],["Surface",w(t.surface)],["Action",w(t.action)],["Chain",le({chainId:t.chain??t.chainId,chain:t.chainName})],["To",ee(t.to??t.destination)],["Value",P(t.value)?w(t.value):B],["Signer",w(t.armed===!0?"running + armed":t.armed===!1?"running, disarmed":"not running")],se({confidence:t.confidence??(t.armed===!0?"high":"low")})],t)}function Ko({platform:e="telegram",chartUrl:t,explorerUrl:r,quoteId:n,prepareId:i,executeId:o,bridgePrepareId:a,hasGrant:s=!1,cancelWindowSec:c=10}={}){let l=Math.max(0,Number(c)||0),p=`Executes in ${l}s \u2014 send /cancel to stop it.`,f=[];P(t)&&f.push({text:"Chart",url:String(t)}),P(r)&&f.push({text:"Explorer",url:String(r)});let u=[];P(n)&&u.push({text:"Refresh quote",callback_data:`oracle:quote:${n}`});let d=[];if(s&&P(i)&&d.push({text:"Prepare swap",callback_data:`oracle:prepare:${i}`}),s&&P(a)&&d.push({text:"Prepare bridge",callback_data:`oracle:prepare-bridge:${a}`}),s&&P(o)&&(d.push({text:"Execute",callback_data:`oracle:execute:${o}:${l}`}),d.push({text:"Cancel",callback_data:`oracle:cancel:${o}`})),String(e)==="telegram")return{kind:"inline_keyboard",replyMarkup:{inline_keyboard:[f,u,d].filter(A=>A.length>0)},cancelHint:p};let h=[],b=0;for(let m of[...f,...u,...d])b+=1,h.push(m.url?`${b}. ${m.text}: ${m.url}`:`${b}. ${m.text} (reply ${b})`);return s&&P(o)&&h.push(p),s||h.push("prepare-only \u2014 no local grant/session"),{kind:"text_menu",text:h.join(`
|
|
8
|
+
`),cancelHint:p}}var B,pd,cc,fd,Wo=R(()=>{Jt();jo();B="UNKNOWN",pd=Object.freeze(["token","launch","hip3","hip4","polymarket","twap","bridge","swap","approve"]),cc=/[_*[\]`]/g;fd=Object.freeze({token:fc,launch:mc,hip3:hc,hip4:bc,polymarket:gc,twap:wc,bridge:yc,swap:kr,approve:Ac})});var Qo={};te(Qo,{buildSwapQuoteCard:()=>vc});function Go(e){return!e||typeof e!="object"?{best:{},routes:[],rankedOn:null,improvementBps:null,warnings:[]}:{best:e.best??e.routes?.[0]??{},routes:Array.isArray(e.routes)?e.routes:[],rankedOn:e.rankedOn??null,improvementBps:e.improvementBps??null,note:e.note??null,warnings:e.warnings??[]}}function xc(e){let t=Number(e);return!Number.isFinite(t)||t<=0?null:t<60?`${Math.round(t)}s`:t<3600?`${Math.round(t/60)}m`:`${(t/3600).toFixed(1)}h`}async function vc(e={},t={}){let{chainId:r,tokenIn:n,tokenOut:i,amountIn:o,toChainId:a=null,tokenInSymbol:s,tokenOutSymbol:c,decimalsIn:l,decimalsOut:p,grant:f=null,quoteId:u=null,prepareId:d=null,executeId:h=null,bridgePrepareId:b=null,chartUrl:m=null,explorerUrl:A=null,platform:C="telegram",cancelWindowSec:I=10}=e;if(r==null||!n||!i||o==null)throw new Error("buildSwapQuoteCard requires chainId, tokenIn, tokenOut, amountIn");let S=a!=null&&Number(a)!==Number(r),k=t.swapFn??wt,v=t.bridgeFn??ko,E=k({chainId:r,tokenIn:n,tokenOut:i,amountIn:o,decimalsIn:l,decimalsOut:p,taker:e.taker},t),g=S?Promise.resolve().then(()=>v({fromChainId:r,toChainId:a,tokenIn:n,tokenOut:e.bridgeTokenOut??i,amountIn:o,decimalsIn:l,decimalsOut:e.bridgeDecimalsOut??p},t)).catch(de=>({error:String(de?.message||de)})):Promise.resolve(null),[y,x]=await Promise.all([E,g]),N=Go(y),$=x&&!x.error?Go(x):null,L=Cr({grant:f}),j={intent:S?"swap or bridge":"swap",chainId:r,toChainId:S?a:null,tokenIn:n,tokenOut:i,tokenInSymbol:s,tokenOutSymbol:c,amountIn:String(o),decimalsIn:l,decimalsOut:p,grant:f,preparable:!!N.best?.source,confidence:N.best?.source?"high":"low",warnings:[...Array.isArray(N.warnings)?N.warnings:[],...$&&Array.isArray($.warnings)?$.warnings:[],...x?.error?[`bridge quote failed: ${x.error}`]:[]],swap:{chainId:r,rankedOn:N.rankedOn,improvementBps:N.improvementBps,best:N.best,routes:N.routes,amountIn:String(o)},bridge:$?{toChainId:a,rankedOn:$.rankedOn,best:$.best,routes:$.routes,estimatedTime:xc($.best?.meta?.durationSeconds)}:null,source:"oracle-best-execution"},ye=kr(j),At=Ko({platform:C,chartUrl:m,explorerUrl:A,quoteId:u,prepareId:L.allowed?d:null,executeId:L.allowed?h:null,bridgePrepareId:L.allowed&&S?b:null,hasGrant:L.allowed,cancelWindowSec:I});return{kind:"swap",text:ye,buttons:At,grant:{allowed:L.allowed,reason:L.reason},swap:y,bridge:S?x:null,execution:!1,broadcast:!1}}var Yo=R(()=>{Wo();gr()});gr();X();var ue=Object.freeze({TRANSACTION:"unsigned-transaction",TYPED_DATA_ORDER:"typed-data-order"}),Ga=100,wr={"uniswap-v3":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:i},o)=>{let{uniV3PrepareExactIn:a}=await Promise.resolve().then(()=>(dt(),po)),s=await a({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:i},o);return{artifactKind:ue.TRANSACTION,transaction:s.transaction,requiresApproval:s.requiresApproval??null,amountOut:s.quote?.amountOut??null,minOut:s.quote?.amountOutMinimum??null}},"uniswap-v4":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:i,slippageBps:o,deadlineSeconds:a,fee:s,tickSpacing:c,hooks:l},p)=>{let{uniV4PrepareExactIn:f}=await Promise.resolve().then(()=>(lr(),ho)),u=await f({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:i,slippageBps:o,deadlineSeconds:a,fee:s,tickSpacing:c,hooks:l},p);return{artifactKind:ue.TRANSACTION,transaction:u.transaction,requiresApproval:u.requiresApproval,amountOut:u.quote?.amountOut??null,minOut:u.quote?.amountOutMinimum??null,prepareReady:!0,executionReady:!1}},lifi:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:i},o)=>{let{lifiPrepare:a}=await Promise.resolve().then(()=>(Ht(),fn)),s=await a({fromChain:e,toChain:e,fromToken:t,toToken:r,fromAmount:n,fromAddress:i},o);return{artifactKind:ue.TRANSACTION,transaction:s.transaction,requiresApproval:s.requiresApproval??null,amountOut:s.quote?.estimate?.toAmount??null,minOut:s.quote?.estimate?.toAmountMin??null}},paraswap:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:i,decimalsIn:o,decimalsOut:a},s)=>{let{paraswapPrepare:c}=await Promise.resolve().then(()=>(Vt(),bn)),l=await c({chainId:e,srcToken:t,destToken:r,amount:n,srcDecimals:o,destDecimals:a,userAddress:i,side:"SELL"},s);return{artifactKind:ue.TRANSACTION,transaction:l.transaction,requiresApproval:l.requiresApproval??null,amountOut:l.quote?.priceRoute?.destAmount??null,minOut:l.quote?.amountOutMinimum??null}},"0x":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:i},o)=>{let{zeroxPrepare:a}=await Promise.resolve().then(()=>(Kt(),vn)),s=await a({chainId:e,sellToken:t,buyToken:r,sellAmount:n,taker:i},o);return{artifactKind:ue.TRANSACTION,transaction:s.transaction,requiresApproval:s.requiresApproval??null,amountOut:s.quote?.buyAmount??null,minOut:s.quote?.minBuyAmount??null}},cow:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:i},o)=>{let{cowPrepareOrder:a}=await Promise.resolve().then(()=>(Xt(),Vn)),s=await a({chainId:e,sellToken:t,buyToken:r,sellAmountBeforeFee:String(n),from:i},o);return{artifactKind:ue.TYPED_DATA_ORDER,typedData:s.typedData,requiresApproval:{token:t,spender:s.vaultRelayer,amount:String(n),note:"CoW pulls funds via the vault relayer, not the settlement contract"},settlement:s.settlement,amountOut:s.quote?.quote?.buyAmount??null,minOut:null,submission:"sign the typed data, then submit the order to the CoW API"}}};var Qa=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),Ya=/^0x[0-9a-fA-F]{40}$/,Xa=Object.freeze(["operation","exactOutput","amountOut","multihop","path","positionManager","modifyLiquidities","commands","actions"]);async function Oo(e,t={}){if(Xa.some(m=>Object.hasOwn(e,m)))throw new Error("unsupported operation shape is inspect/quote-only");if(e.hookData!=null&&String(e.hookData).toLowerCase()!=="0x")throw new Error("opaque hookData is inspect/quote-only");let{taker:r}=e;if(!r)throw new Error("prepareBestRoute requires taker: a prepared transaction is built FOR an address, and the quote-only placeholder must never end up in one");if(!Ya.test(r))throw new Error(`taker must be a valid 20-byte address, got "${r}"`);if(Qa.has(r.toLowerCase()))throw new Error(`taker "${r}" is a placeholder/burn address. It is valid for quoting but not for preparing -- that would build a transaction for an address nobody controls. Pass the real wallet that will sign.`);let n=await wt(e,t);if(!n.best){let m=n.impactRejected??[];return{ok:!1,reason:m.length?m[0].reason:"no source returned a usable route",priceImpactBlocked:m.length>0,impactRejected:m,comparison:n}}let i=e.source||n.best.source,o=n.routes.find(m=>m.source===i);if(!o)return{ok:!1,reason:`source "${i}" did not return a usable route`,comparison:n};let a=wr[i];if(!a){let m=n.routes.find(A=>wr[A.source]&&A.source!==i);return{ok:!1,reason:`${i} won the comparison but has no prepare path in this build. `+(m?`Next preparable route is ${m.source}; pass source:"${m.source}" to use it.`:"No route in this comparison can be prepared."),comparison:n,winner:i}}let s;try{s=await a(e,t)}catch(m){let A=typeof m?.body=="string"?m.body:m?.body?JSON.stringify(m.body):"",C=[String(m?.message||m),A].filter(Boolean).join(" :: "),I=/allowance/i.test(C),S=!I&&/not enough|insufficient|balance/i.test(C),k,v;I?(v="approval-required-first",k=`${i} will not build swap calldata until the token approval exists on-chain. Approve the spender first, then prepare again. Underlying: ${C}`):S?(v="taker-not-funded",k=`${i} refused to build the transaction: ${C}. This venue verifies the taker holds the input token. Quoting works for any address; preparing needs the real funded wallet.`):(v="provider-error",k=`${i} prepare failed: ${C}`);let E=n.routes.find(g=>wr[g.source]&&g.source!==i);return{ok:!1,reason:k,failureKind:v,...E?{alternative:E.source}:{},comparison:n}}let c=e.driftToleranceBps??Ga,l=null,p=null;if(s.amountOut!=null&&o.grossOut!=null)try{let m=BigInt(o.grossOut),A=BigInt(s.amountOut);m>0n&&(l=Number((A-m)*10000n/m),l<-c&&(p=`route moved ${(l/100).toFixed(2)}% against you between the comparison and this prepare (tolerance ${(c/100).toFixed(2)}%). The ranking may no longer hold -- re-run the comparison before signing.`))}catch{}let f=n.routes.filter(m=>m.source!==i).map(m=>({source:m.source,netOut:m.netOut,gasUsd:m.gasUsd})),d=n.routes.map(m=>({source:m.source,liquidityUsd:m.liquidityUsd??null})).reduce((m,A)=>Math.max(m,A.liquidityUsd??0),0)||null,h=o.liquidityUsd??null,b=h!=null&&d>0?Math.round(h/d*100):null;return D({ok:!0,chosen:{source:i,wasWinner:i===n.best.source,netOut:o.netOut,grossOut:o.grossOut,gasUsd:o.gasUsd,liquidityUsd:o.liquidityUsd??null},liquidity:{chosenUsd:h,maxUsd:d,sharePct:b},priceImpact:n.priceImpact??null,impactUnmeasured:n.impactUnmeasured??[],...s,unsigned:!0,signedBy:"user-wallet",destination:s.artifactKind===ue.TRANSACTION?s.transaction?.to??null:s.settlement??null,driftBps:l,warnings:[...p?[p]:[],...n.warnings||[],...s.artifactKind===ue.TYPED_DATA_ORDER?["This is an ORDER to sign, not a transaction to broadcast. Signing it authorizes a solver to settle on your behalf."]:[]],runnersUp:f,comparison:{rankedOn:n.rankedOn,sourcesAnswered:n.sourcesAnswered,sourcesTried:n.sourcesTried,improvementBps:n.improvementBps},note:"UNSIGNED. Verify the destination address and minOut against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."},{provider:"router",kind:"best-route"})}fe();he();ct();K();fe();he();fe();var Er={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},z=e=>BigInt(e).toString(16).padStart(64,"0"),De=e=>e.slice(2).toLowerCase().padStart(64,"0");function Ja(e,t){return`0x${Er.getAmountsOut}`+z(e)+z(64)+z(t.length)+t.map(De).join("")}function Za(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length<128)return null;let r=Number(BigInt(`0x${t.slice(64,128)}`));if(!Number.isFinite(r)||r<1||r>16)return null;let n=[];for(let i=0;i<r;i++){let o=128+i*64;if(t.length<o+64)return null;n.push(BigInt(`0x${t.slice(o,o+64)}`))}return n}function yr(e,t="router"){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}var Sr=100;function ec(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Sr)throw new Error(`slippageBps ${r} exceeds the ${Sr} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(r))/10000n}function No(e){let{chainId:t,wrappedNative:r}=e;async function n(i,o,a,s){let c=await U(t,"eth_call",[{to:i,data:Ja(o,a)},"latest"],s);return Za(c?.result??c)}return{async quote({tokenIn:i,tokenOut:o,amountIn:a,path:s},c={}){let l=yr(c.scanner);if(!l)return{chainId:t,evidence:_.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let p=s||[i,o];if(p.some(u=>!/^0x[0-9a-fA-F]{40}$/.test(u||"")))throw new Error("quote requires valid 20-byte addresses");let f=await n(l,a,p,c);return f?{chainId:t,router:l,path:p,amountIn:String(a),amountOut:f[f.length-1].toString(),hops:p.length-1,evidence:_.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:l,path:p,evidence:_.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:i,amountIn:o,base:a},s={}){let c=yr(s.scanner),l=a||r;if(l&&String(i).toLowerCase()===String(l).toLowerCase())return{chainId:t,token:i,verdict:O.UNKNOWN,evidence:_.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!c||!l)return{chainId:t,token:i,verdict:O.UNKNOWN,evidence:_.UNAVAILABLE,reason:c?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let p=await n(c,o,[l,i],s);if(!p)return{chainId:t,token:i,verdict:O.FAIL,evidence:_.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let f=p[p.length-1];if(f===0n)return{chainId:t,token:i,verdict:O.FAIL,evidence:_.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let u=await n(c,f,[i,l],s);if(!u)return{chainId:t,token:i,verdict:O.FAIL,evidence:_.LIVE,leg:"sell",bought:f.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let d=u[u.length-1],h=Number(d*10000n/BigInt(o)),b=O.PASS,m="round trip completes with expected fee/impact loss";return h<5e3?(b=O.FAIL,m=`round trip returns only ${(h/100).toFixed(2)}% -- punitive tax or no real liquidity`):h<9e3&&(b=O.CAUTION,m=`round trip returns ${(h/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:i,base:l,router:c,verdict:b,reason:m,amountIn:String(o),bought:f.toString(),returned:d.toString(),retentionBps:h,evidence:_.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:i,tokenOut:o,amountIn:a,recipient:s,slippageBps:c=50,deadlineSeconds:l=900,path:p},f={}){let u=f.scanner,d=yr(u);if(!d)throw new Error(`chain ${t} has no verified router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!/^0x[0-9a-fA-F]{40}$/.test(s||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let h=p||[i,o],b=await this.quote({tokenIn:i,tokenOut:o,amountIn:a,path:h},f);if(b.evidence!==_.LIVE)throw new Error(`cannot prepare without a live quote (${b.evidence}: ${b.reason??"no reason given"})`);let m=ec(b.amountOut,c);if(m<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let A=BigInt(Math.floor(Date.now()/1e3)+Number(l)),C=r&&h[0].toLowerCase()===r.toLowerCase()&&f.useNative,I=C?`0x${Er.swapExactETHForTokens}`+z(m)+z(128)+De(s)+z(A)+z(h.length)+h.map(De).join(""):`0x${Er.swapExactTokensForTokens}`+z(a)+z(m)+z(160)+De(s)+z(A)+z(h.length)+h.map(De).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:d,data:I,value:C?`0x${BigInt(a).toString(16)}`:"0x0"},guard:{quotedOut:b.amountOut,minOut:m.toString(),slippageBps:c,maxSlippageBps:Sr,deadline:A.toString()},requires:C?[]:[{step:"approve",token:h[0],spender:d,amount:String(a)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}he();fe();var tc=[100,500,3e3,1e4],_o={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},be=e=>BigInt(e).toString(16).padStart(64,"0"),qe=e=>e.slice(2).toLowerCase().padStart(64,"0"),Ro=/^0x[0-9a-fA-F]{40}$/,xr=100;function rc(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>xr)throw new Error(`slippageBps ${r} exceeds the ${xr} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(r))/10000n}function Ar(e,t){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function Bo(e){let{chainId:t,wrappedNative:r}=e;async function n({quoter:o,tokenIn:a,tokenOut:s,amountIn:c,fee:l},p){let f=`0x${_o.quoteExactInputSingle}`+qe(a)+qe(s)+be(c)+be(l)+be(0),u=await U(t,"eth_call",[{to:o,data:f},"latest"],p).catch(()=>null),d=u?.result??u;if(!d||d==="0x"||d.length<66)return null;let h=BigInt(`0x${d.slice(2,66)}`);return h>0n?h:null}async function i({quoter:o,tokenIn:a,tokenOut:s,amountIn:c},l){let p=await Promise.all(tc.map(async u=>{let d=await n({quoter:o,tokenIn:a,tokenOut:s,amountIn:c,fee:u},l);return{fee:u,amountOut:d?d.toString():null,out:d}})),f=null;for(let u of p)u.out&&(!f||u.out>f.amountOut)&&(f={fee:u.fee,amountOut:u.out});return{best:f,tried:p.map(({fee:u,amountOut:d})=>({fee:u,amountOut:d}))}}return{async quote({tokenIn:o,tokenOut:a,amountIn:s},c={}){let l=Ar(c.scanner,"quoter");if(!l)return{chainId:t,evidence:_.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let u of[o,a])if(!Ro.test(u||""))throw new Error("quote requires valid 20-byte addresses");let{best:p,tried:f}=await i({quoter:l,tokenIn:o,tokenOut:a,amountIn:s},c);return p?{chainId:t,venue:"uniswap-v3",quoter:l,tokenIn:o,tokenOut:a,amountIn:String(s),amountOut:p.amountOut.toString(),fee:p.fee,useNative:!!r&&String(o).toLowerCase()===String(r).toLowerCase(),triedFeeTiers:f,evidence:_.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:l,tokenIn:o,tokenOut:a,triedFeeTiers:f,evidence:_.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:o,amountIn:a,base:s},c={}){let l=Ar(c.scanner,"quoter"),p=(e.stableQuoteAssets||[]).map(k=>String(k).toLowerCase()),f=null;!s&&typeof e.resolveQuoteAsset=="function"&&(f=await e.resolveQuoteAsset(o,c).catch(()=>null));let u=String(o).toLowerCase(),d=String(r||"").toLowerCase();if(d&&u===d)return{chainId:t,token:o,verdict:O.UNKNOWN,evidence:_.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};let h=s||f||(p[0]&&u!==p[0]?p[0]:null)||r;if(h&&u===String(h).toLowerCase())return{chainId:t,token:o,verdict:O.UNKNOWN,evidence:_.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!l||!h)return{chainId:t,token:o,verdict:O.UNKNOWN,evidence:_.UNAVAILABLE,reason:l?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let b=await i({quoter:l,tokenIn:h,tokenOut:o,amountIn:a},c);if(!b.best){let k=p.find(v=>v&&v!==String(h).toLowerCase()&&v!==String(o).toLowerCase());if(k){let v=await i({quoter:l,tokenIn:k,tokenOut:o,amountIn:a},c);if(v.best){let E=await i({quoter:l,tokenIn:o,tokenOut:k,amountIn:v.best.amountOut},c);if(E.best){let g=E.best.amountOut,y=Number(g*10000n/BigInt(a)),x=O.PASS,N="round trip vs dollar book completes with expected fee/impact loss";return y<5e3?(x=O.FAIL,N=`round trip vs dollar book returns only ${(y/100).toFixed(2)}% -- punitive tax or no real liquidity`):y<9e3&&(x=O.CAUTION,N=`round trip vs dollar book returns ${(y/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:o,base:k,quoteAsset:k,verdict:x,reason:N,amountIn:String(a),bought:v.best.amountOut.toString(),returned:g.toString(),retentionBps:y,buyFee:v.best.fee,sellFee:E.best.fee,evidence:_.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:t,token:o,verdict:O.FAIL,evidence:_.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let m=await i({quoter:l,tokenIn:o,tokenOut:h,amountIn:b.best.amountOut},c);if(!m.best){let k=p.find(v=>v&&v!==String(h).toLowerCase()&&v!==String(o).toLowerCase());if(k){let v=await i({quoter:l,tokenIn:k,tokenOut:o,amountIn:a},c),E=v.best?await i({quoter:l,tokenIn:o,tokenOut:k,amountIn:v.best.amountOut},c):{best:null};if(v.best&&E.best){let g=E.best.amountOut,y=Number(g*10000n/BigInt(a)),x=O.PASS,N="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return y<5e3?(x=O.FAIL,N=`dollar-book round trip returns only ${(y/100).toFixed(2)}%`):y<9e3&&(x=O.CAUTION,N=`dollar-book round trip returns ${(y/100).toFixed(2)}%`),{chainId:t,venue:"uniswap-v3",token:o,base:k,quoteAsset:k,verdict:x,reason:N,amountIn:String(a),bought:v.best.amountOut.toString(),returned:g.toString(),retentionBps:y,buyFee:v.best.fee,sellFee:E.best.fee,evidence:_.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:t,token:o,verdict:O.FAIL,evidence:_.LIVE,leg:"sell",bought:b.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let A=m.best.amountOut,C=Number(A*10000n/BigInt(a)),I=O.PASS,S="round trip completes with expected fee/impact loss";return C<5e3?(I=O.FAIL,S=`round trip returns only ${(C/100).toFixed(2)}% -- punitive tax or no real liquidity`):C<9e3&&(I=O.CAUTION,S=`round trip returns ${(C/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:o,base:h,verdict:I,reason:S,amountIn:String(a),bought:b.best.amountOut.toString(),returned:A.toString(),retentionBps:C,buyFee:b.best.fee,sellFee:m.best.fee,evidence:_.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:a,amountIn:s,recipient:c,slippageBps:l=50,fee:p},f={}){let u=Ar(f.scanner,"router");if(!u)throw new Error(`chain ${t} has no verified V3 router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!Ro.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let d=await this.quote({tokenIn:o,tokenOut:a,amountIn:s},f);if(d.evidence!==_.LIVE)throw new Error(`cannot prepare without a live quote (${d.evidence}: ${d.reason??"no reason given"})`);let h=p??d.fee,b=rc(d.amountOut,l);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let m=!!(f.useNative||d.useNative)&&r&&String(o).toLowerCase()===String(r).toLowerCase(),A=`0x${_o.exactInputSingle}`+qe(o)+qe(a)+be(h)+qe(c)+be(s)+be(b)+be(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:u,data:A,value:m?String(s):"0x0"},guard:{quotedOut:d.amountOut,minOut:b.toString(),slippageBps:l,maxSlippageBps:xr,fee:h},requires:m?[]:[{step:"approve",token:o,spender:u,amount:String(s)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}er();var yt={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function $o(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function To(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length>=128){let n=Number(BigInt(`0x${t.slice(64,128)}`));if(n>0&&n<=256&&t.length>=128+n*2){let i=t.slice(128,128+n*2),o=Buffer.from(i,"hex").toString("utf8").replace(/\0+$/,"");if(o)return o}}return Buffer.from(t.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function nc(e){let{chainId:t}=e;async function r(n,i,o){return U(t,"eth_call",[{to:n,data:i},"latest"],o)}return{async blockNumber(n={}){let i=await Yn(t,n);return{chainId:t,blockNumber:i?.blockNumber??i,evidence:_.LIVE}},async nativeBalance(n,i={}){let o=await Jn(t,n,i);return{chainId:t,address:n,wei:o?.wei??o?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:_.LIVE}},async tokenBalance({token:n,owner:i},o={}){let a=await Zn({chainId:t,token:n,owner:i},o);return{chainId:t,token:n,owner:i,raw:a?.balance??a,evidence:_.LIVE}},async resolveToken(n,i={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:t,token:n,evidence:_.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[o,a,s,c]=await Promise.all([r(n,yt.decimals,i).catch(()=>null),r(n,yt.symbol,i).catch(()=>null),r(n,yt.name,i).catch(()=>null),r(n,yt.totalSupply,i).catch(()=>null)]),l=$o(o?.result??o),p=l!==null||a?.result||s?.result;return{chainId:t,address:n,decimals:l===null?null:Number(l),symbol:To(a?.result??a),name:To(s?.result??s),totalSupply:($o(c?.result??c)??null)?.toString()??null,evidence:p?_.LIVE:_.UNKNOWN,warning:p?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(n,i={}){let o=e.dexscreenerSlug;if(!o)return{chainId:t,token:n,pools:[],evidence:_.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let a=await tr(n,i).catch(()=>null),c=(a?.pairs||a?.data?.pairs||[]).filter(p=>String(p.chainId).toLowerCase()===String(o).toLowerCase()).map(p=>({pair:p.pairAddress,dex:p.dexId,base:p.baseToken?.address,quote:p.quoteToken?.address,liquidityUsd:p.liquidity?.usd??null,priceUsd:p.priceUsd??null,volume24hUsd:p.volume?.h24??null,createdAt:p.pairCreatedAt??null})).sort((p,f)=>(f.liquidityUsd??0)-(p.liquidityUsd??0)),l=Zt(n,c,{stables:e.stableQuoteAssets||[],wrappedNative:e.wrappedNative});return{chainId:t,token:n,pools:l,topPool:l[0]||null,quoteAsset:to(n,l),evidence:l.length?_.LIVE:_.UNKNOWN}},async scanBlocks({fromBlock:n,toBlock:i,address:o,topics:a,chunkSize:s=2e3}={},c={}){if(!Number.isInteger(n)||!Number.isInteger(i))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(i<n)throw new Error("toBlock must be >= fromBlock");let l=[],p=[];for(let u=n;u<=i;u+=s){let d=Math.min(u+s-1,i);p.push([u,d])}let f=await Kr(p,4,async([u,d])=>{let h={fromBlock:`0x${u.toString(16)}`,toBlock:`0x${d.toString(16)}`};o&&(h.address=o),a&&(h.topics=a);let b=await U(t,"eth_getLogs",[h],c).catch(m=>({error:String(m?.message||m)}));return{start:u,end:d,res:b}});for(let{start:u,end:d,res:h}of f){if(h?.error)return{chainId:t,fromBlock:n,toBlock:i,logs:l,complete:!1,failedAt:[u,d],error:h.error,evidence:_.UNKNOWN};for(let b of h?.result??h??[])l.push(b)}return{chainId:t,fromBlock:n,toBlock:i,logs:l,complete:!0,chunks:p.length,evidence:_.LIVE}},async scoreRisk(n,i={}){let o=[],a=O.PASS,s=p=>{let f={[O.PASS]:0,[O.CAUTION]:1,[O.UNKNOWN]:2,[O.FAIL]:3};f[p]>f[a]&&(a=p)},[c,l]=await Promise.all([this.resolveToken(n,i),this.resolvePools(n,i)]);if(c.evidence!==_.LIVE?(o.push({check:"erc20-metadata",result:O.UNKNOWN,detail:c.warning}),s(O.UNKNOWN)):o.push({check:"erc20-metadata",result:O.PASS,detail:`${c.symbol} / ${c.decimals}d`}),l.evidence===_.UNAVAILABLE)o.push({check:"liquidity",result:O.UNKNOWN,detail:l.reason}),s(O.UNKNOWN);else if(!l.pools.length)o.push({check:"liquidity",result:O.FAIL,detail:"no pool with liquidity found"}),s(O.FAIL);else{let p=l.pools[0],f=p.liquidityUsd??0;f<5e3?(o.push({check:"liquidity",result:O.CAUTION,detail:`top pool only $${f}`}),s(O.CAUTION)):o.push({check:"liquidity",result:O.PASS,detail:`$${f} on ${p.dex}`}),p.createdAt&&Date.now()-p.createdAt<24*3600*1e3&&(o.push({check:"age",result:O.CAUTION,detail:"pool under 24h old"}),s(O.CAUTION))}if(typeof this.sellSimulation=="function"){let p=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},i).catch(f=>({verdict:O.UNKNOWN,reason:String(f?.message||f)}));o.push({check:"sellability",result:p.verdict,detail:p.retentionBps!=null?`round trip returns ${(p.retentionBps/100).toFixed(2)}% -- ${p.reason}`:p.reason}),s(p.verdict)}else o.push({check:"sellability",result:O.UNKNOWN,detail:"no verified router on this chain, so a round-trip sell simulation cannot run. Treat as unproven -- a buy path is not an exit path."}),s(O.UNKNOWN);return{chainId:t,token:n,verdict:a,checks:o,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function Lo(e){let r={...nc(e)},n=new Set((e.venues||[]).map(o=>o.kind));e.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,Bo({chainId:e.chainId,wrappedNative:e.wrappedNative,stableQuoteAssets:e.stableQuoteAssets||[],resolveQuoteAsset:async(o,a)=>(await r.resolvePools(o,a)).quoteAsset||null})):e.venueKind==="uniswap-v2"&&n.has("router")&&Object.assign(r,No({chainId:e.chainId,wrappedNative:e.wrappedNative}));let i={};for(let[o,a]of Object.entries(r))i[o]=a.bind(r);return{key:e.key,chainId:e.chainId,name:e.name,rpcEnv:e.rpcEnv,nativeCurrency:e.nativeCurrency,explorer:e.explorer,venues:e.venues||[],capabilities:i}}fe();var oc=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}}]}]);function Po(){return oc.map(e=>_r(Lo(e)))}dt();var vr=/^0x[0-9a-fA-F]{40}$/,ic=24,Uo=!1;function qo(){Uo||(Po(),Uo=!0)}var q=class extends Error{constructor(t,r){super(r),this.status=t}};function sc(e){if(qo(),e==null||e==="")throw new q(400,"chainId is required");let t=Number(e);if(Number.isFinite(t)&&He(t))return t;let r=Rr().find(n=>n.key===String(e).toLowerCase());if(r)return r.chainId;throw new q(400,`unknown chain "${e}"`)}function Fo(e,t){if(typeof e!="string")throw new q(400,`${t} is required`);let r=e.trim();if(r===""||r.length>ic)throw new q(400,`${t} is invalid`);if(!/^[A-Za-z0-9._-]+$/.test(r)&&!vr.test(r))throw new q(400,`${t} is invalid`);return r}function ac(e,t){let r=String(e).trim();if(!/^\d+(\.\d+)?$/.test(r))throw new q(400,"sellAmount must be a positive decimal number");if(Number(r)<=0)throw new q(400,"sellAmount must be greater than zero");let n=Number.isFinite(Number(t))?Number(t):18,[i,o=""]=r.split(".");if(o.length>n)throw new q(400,`sellAmount has more precision than the token's ${n} decimals`);let a=o.padEnd(n,"0"),s=(BigInt(i)*10n**BigInt(n)+BigInt(a||"0")).toString();if(s==="0")throw new q(400,"sellAmount rounds to zero at this token's precision");return s}async function Do(e,t){if(qo(),vr.test(t)){let l=await He(e).resolveToken(t).catch(()=>null),p=Number(l?.decimals);return{address:t,decimals:Number.isFinite(p)?p:null}}let r=V[e];if(!r)return null;let n=t.toLowerCase(),i=n==="usdc"?r.usdc:n==="weth"||n==="eth"?r.weth:null;if(!i)return null;let a=await He(e).resolveToken(i).catch(()=>null),s=Number(a?.decimals);return{address:i,decimals:Number.isFinite(s)?s:null}}async function Mo(e={},t={}){let r=sc(e.chainId??e.chain),n=Fo(e.sellSymbol??e.sellToken,"sellSymbol"),i=Fo(e.buySymbol??e.buyToken,"buySymbol");if(n.toLowerCase()===i.toLowerCase())throw new q(400,"sell and buy assets must differ");let o=typeof e.taker=="string"?e.taker.trim():"";if(!vr.test(o))throw new q(400,"taker must be the wallet address that will sign");let[a,s]=await Promise.all([Do(r,n),Do(r,i)]);if(!a)throw new q(400,`could not resolve sell asset "${n}" on chain ${r}`);if(!s)throw new q(400,`could not resolve buy asset "${i}" on chain ${r}`);let c=ac(e.sellAmount,a.decimals),l=await Oo({chainId:r,tokenIn:a.address||n,tokenOut:s.address||i,amountIn:c,taker:o,decimalsIn:a.decimals??null,decimalsOut:s.decimals??null,source:typeof e.source=="string"&&e.source.trim()!==""?e.source.trim():void 0},t);if(!l.ok)return{ok:!1,reason:l.reason,priceImpactBlocked:!!l.priceImpactBlocked,requiresWalletSignature:!0,backendSigner:!1};let p=s.decimals??18,f=l.minOut??l.chosen?.netOut??l.chosen?.grossOut??null;return{ok:!0,requiresWalletSignature:!0,backendSigner:!1,quote:{sellSymbol:n,buySymbol:i,sellAmount:String(e.sellAmount),buyAmount:f==null?null:String(f),buyAmountFormatted:f==null?null:(Number(f)/10**p).toString(),routeLabel:l.chosen?.source??null,priceImpactPct:Number.isFinite(Number(l.chosen?.priceImpactPct))?Number(l.chosen.priceImpactPct):null,slippageBps:Number.isFinite(Number(l.slippageBps))?Number(l.slippageBps):null,intentHash:l.intentHash??null,minOut:l.minOut??null,requiresApproval:l.requiresApproval??null,warnings:Array.isArray(l.warnings)?l.warnings:[]},transaction:l.transaction??null}}var Or=`oracle swap <chain> <sellAsset> <buyAsset> <amount> --taker <address> [--source X] [--json]
|
|
7
9
|
oracle swap quote <chainId> <tokenIn> <tokenOut> <amountIn> [--to-chain <id>] [--json]
|
|
8
10
|
|
|
9
11
|
oracle swap base USDC WETH 5 --taker 0xYourWallet
|
|
10
12
|
oracle swap quote 8453 0xWETH 0xUSDC 1000000000000000000 --json
|
|
11
13
|
|
|
12
14
|
quote prints an ORACLE SWAP card (best swap + optional best bridge).
|
|
13
|
-
prepare stays UNSIGNED. Sign and broadcast with the wallet or oracle signer after review.`;function
|
|
14
|
-
`),0;if(t[0]==="quote"){let
|
|
15
|
-
`),1;let{buildSwapQuoteCard:
|
|
16
|
-
`),0):(process.stdout.write(
|
|
17
|
-
`),
|
|
15
|
+
prepare stays UNSIGNED. Sign and broadcast with the wallet or oracle signer after review.`;function St(e,t){let r=e.find(i=>i.startsWith(`--${t}=`));if(r)return r.split("=").slice(1).join("=");let n=e.indexOf(`--${t}`);return n>=0&&e[n+1]&&!e[n+1].startsWith("--")?e[n+1]:null}var wd={name:"swap",summary:"prepare an unsigned swap (quote + calldata)",group:"read",usage:Or,async run(e){let t=e.argv||[];if(t.length===0||t.includes("--help")||t.includes("-h"))return process.stdout.write(Or+`
|
|
16
|
+
`),0;if(t[0]==="quote"){let u=t.includes("--json"),d=t.filter(S=>!S.startsWith("--")),[,h,b,m,A]=d;if(!h||!b||!m||!A)return process.stderr.write(`usage: oracle swap quote <chainId> <tokenIn> <tokenOut> <amountIn> [--to-chain <id>] [--json]
|
|
17
|
+
`),1;let{buildSwapQuoteCard:C}=await Promise.resolve().then(()=>(Yo(),Qo)),I=await C({chainId:Number(h),tokenIn:b,tokenOut:m,amountIn:A,toChainId:St(t,"to-chain")?Number(St(t,"to-chain")):null,grant:null});return u?(process.stdout.write(JSON.stringify({text:I.text,buttons:I.buttons,grant:I.grant,execution:!1},null,2)+`
|
|
18
|
+
`),0):(process.stdout.write(I.text+`
|
|
19
|
+
`),I.buttons?.text&&process.stdout.write(I.buttons.text+`
|
|
18
20
|
`),process.stdout.write(`UNSIGNED quote card. Execute requires a local grant and later signer confirm.
|
|
19
|
-
`),0)}let r=t.includes("--json"),n=t.filter(
|
|
21
|
+
`),0)}let r=t.includes("--json"),n=t.filter(u=>!u.startsWith("--")),i=St(t,"taker"),o=n.filter(u=>u!==i),[a,s,c,l]=o;if(!a||!s||!c||!l)return process.stderr.write(Or+`
|
|
20
22
|
`),1;if(!i)return process.stderr.write(`error: --taker <address> is required. A prepared transaction is built FOR a wallet.
|
|
21
|
-
`),1;let p;try{p=await
|
|
22
|
-
`),1;throw
|
|
23
|
+
`),1;let p;try{p=await Mo({chainId:a,sellSymbol:s,buySymbol:c,sellAmount:l,taker:i,source:St(t,"source")||void 0})}catch(u){if(u instanceof q)return process.stderr.write(`error: ${u.message}
|
|
24
|
+
`),1;throw u}if(r)return process.stdout.write(JSON.stringify(p,null,2)+`
|
|
23
25
|
`),p.ok?0:1;if(!p.ok)return process.stdout.write(`could not prepare: ${p.reason}
|
|
24
26
|
`),p.priceImpactBlocked&&process.stdout.write(`reason kind: price impact guard rejected the venue (thin or drained liquidity)
|
|
25
|
-
`),1;let
|
|
26
|
-
`),process.stdout.write(`sell: ${
|
|
27
|
-
`),process.stdout.write(`receive: ${
|
|
28
|
-
`),
|
|
29
|
-
`),process.stdout.write(`slippage: ${
|
|
30
|
-
`),process.stdout.write(`impact: ${
|
|
31
|
-
`),
|
|
27
|
+
`),1;let f=p.quote;process.stdout.write(`route: ${f.routeLabel}
|
|
28
|
+
`),process.stdout.write(`sell: ${f.sellAmount} ${f.sellSymbol}
|
|
29
|
+
`),process.stdout.write(`receive: ${f.buyAmountFormatted??"unknown"} ${f.buySymbol}
|
|
30
|
+
`),f.minOut&&process.stdout.write(`minOut: ${f.minOut} (raw)
|
|
31
|
+
`),process.stdout.write(`slippage: ${f.slippageBps==null?"not quoted by route":(f.slippageBps/100).toFixed(2)+"%"}
|
|
32
|
+
`),process.stdout.write(`impact: ${f.priceImpactPct==null?"unknown":f.priceImpactPct.toFixed(3)+"%"}
|
|
33
|
+
`),f.requiresApproval&&(process.stdout.write(`
|
|
32
34
|
approval required first:
|
|
33
|
-
`),process.stdout.write(` token ${
|
|
34
|
-
`),process.stdout.write(` spender ${
|
|
35
|
+
`),process.stdout.write(` token ${f.requiresApproval.token}
|
|
36
|
+
`),process.stdout.write(` spender ${f.requiresApproval.spender}
|
|
35
37
|
`)),p.transaction&&(process.stdout.write(`
|
|
36
38
|
unsigned transaction:
|
|
37
39
|
`),process.stdout.write(` to ${p.transaction.to}
|
|
38
40
|
`),process.stdout.write(` value ${p.transaction.value}
|
|
39
41
|
`),process.stdout.write(` data ${String(p.transaction.data).slice(0,42)}... (${String(p.transaction.data).length} chars)
|
|
40
|
-
`));for(let
|
|
41
|
-
WARNING: ${
|
|
42
|
+
`));for(let u of f.warnings||[])process.stdout.write(`
|
|
43
|
+
WARNING: ${u}
|
|
42
44
|
`);return process.stdout.write(`
|
|
43
45
|
UNSIGNED. Review in the signing wallet or oracle signer.
|
|
44
|
-
`),0}};export{
|
|
46
|
+
`),0}};export{wd as default};
|