@oracle-agent/oracle 0.16.0 → 0.18.0

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.
@@ -1,22 +1,22 @@
1
1
  #!/usr/bin/env node
2
- var an=Object.defineProperty;var S=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var V=(e,t)=>{for(var r in t)an(e,r,{get:t[r],enumerable:!0})};import{createHash as ln}from"node:crypto";function fn(e){let t=String(e||"").toLowerCase();return St.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function hn(e){let t={};for(let[r,n]of Object.entries(e||{}))fn(r)||(t[r]=n);return t}function gn(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 bn(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function wn(e,t,r){let n={};for(let[c,u]of Object.entries(r||{}))n[c.toLowerCase()]=u;let o=Object.keys(n).filter(c=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(c)),s=[...new Set([...St,...o])].sort().map(c=>`${c}=${n[c]??""}`).join(`
3
- `),i=ln("sha256").update(s).digest("hex").slice(0,32);return`${e} ${t} ${i}`}function En(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,vt):Math.min(250*2**e,vt)+Math.floor(Math.random()*100)}async function An(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:a}){let s=new AbortController,i=setTimeout(()=>s.abort(),a);try{let c=String(e),u={...n||{}};for(let p=0;p<=xt;p+=1){let d=await t(c,{method:r,headers:u,body:o,signal:s.signal,redirect:"manual"}),l=await d.text(),m=null;if(l)try{m=JSON.parse(l)}catch{m=null}if(mn.has(d.status)){if(r!=="GET"&&r!=="HEAD"){let g=new Error(`HTTP ${d.status} ${r} ${c} redirected non-idempotent request`);throw g.status=d.status,g.body=m??l.slice(0,300),g}if(p===xt)throw new Error(`HTTP redirect loop for ${e}`);let f=gn(d.headers?.get?.("location"),c);bn(f,c)||(u=hn(u)),c=f;continue}if(!d.ok){let f=new Error(`HTTP ${d.status} ${r} ${c}`);throw f.status=d.status,f.retryAfter=d.headers?.get?.("retry-after")??null,f.body=m??l.slice(0,300),f}return m??l}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(i)}}async function A(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,o=(t.method||"GET").toUpperCase(),a={Accept:"application/json",...t.headers||{}},s=t.body;s!=null&&typeof s!="string"&&(a["Content-Type"]=a["Content-Type"]||"application/json",s=JSON.stringify(s));let i=Number.isInteger(t.retries)?Math.max(t.retries,0):pn,c=async()=>{let m;for(let f=0;f<=i;f++)try{return await An(e,{fetchImpl:r,method:o,headers:a,body:s,timeoutMs:n})}catch(g){m=g;let h=g?.status,b=g?.name==="AbortError",v=new Set([408,425,429]),C=h!=null?v.has(h)||dn.has(h)&&At.has(o):!b&&At.has(o);if(f===i||!C)throw g;await yn(En(f,g?.retryAfter))}throw m};if(!(t.dedupe!==!1&&o==="GET"&&s==null))return c();let p=wn(o,e,a),d=Le.get(p);if(d)return d;let l=c().finally(()=>Le.delete(p));return Le.set(p,l),l}var dn,At,pn,vt,St,mn,xt,Le,yn,$=S(()=>{dn=new Set([408,425,429,500,502,503,504]),At=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),pn=2,vt=4e3,St=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],mn=new Set([301,302,303,307,308]),xt=3;Le=new Map;yn=e=>new Promise(t=>setTimeout(t,e))});import{readFileSync as vn}from"node:fs";import{homedir as xn}from"node:os";import{join as ue}from"node:path";function Sn(){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=xn();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||ue(t,".config","oracle")).trim();return[e,ue(r,"exec.env")].filter(Boolean)}return[e,ue(t,".config","oracle","exec.env"),ue(t,".config","mad-desk","exec.env")].filter(Boolean)}function It(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of Sn())try{let a=vn(o,"utf8"),s=a.match(new RegExp(`^${t}=(.*)$`,"m"))||a.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 Ct=S(()=>{});var kt=S(()=>{});import{createHash as In,createHmac as Cn,timingSafeEqual as Ua}from"node:crypto";function Fe(e){return Array.isArray(e)?`[${e.map(Fe).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Fe(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function kn(e,{required:t=!1}={}){try{return It(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function _t(e){let{signature:t,...r}=e;return r}function Tt(e,{secret:t}={}){let r=kn(t);return r?{...e,signature:Cn("sha256",r).update(Fe(_t(e))).digest("hex")}:e}function On(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 In("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function _(e,{chainId:t,venue:r,data:n,secret:o}={}){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");return Tt({..._t(e),calldataHash:On(n)},{secret:o})}function De(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function Nn(e){let t=e==null?Ot: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,Ot)}function U({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:o}={}){let a=De(e,0),s=a>0?a>=25e4?5:a>=1e5?10:a>=5e4?20:a>=1e4?40:70:n?30:10,i=Math.min(60,Math.abs(De(t,0))*2),c=Math.min(40,Math.floor(Math.max(0,De(r,0))/5e3)*5),u=Math.max(25,Math.ceil(20+s+i+c)),p=Nn(o);return{mode:"auto",requiredBps:u,selectedBps:Math.min(u,p),capBps:p,executable:u<=p}}function _n({chainId:e,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:o=0,quoteAgeMs:a=0,crossChain:s=!1,requestedCapBps:i,quotedAtMs:c=Date.now(),ttlMs:u=Nt,secret:p}={}){let d=BigInt(r??0);if(d<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let l=U({liquidityUsd:n,priceChange5m:o,quoteAgeMs:a,crossChain:s,requestedCapBps:i});if(!l.executable)throw new Error(`auto-slippage requires ${l.requiredBps} bps above hard/requested cap ${l.capBps}; route blocked`);let m=Number(c);if(!Number.isFinite(m))throw new Error("auto-slippage: quotedAtMs must be a finite number");let f=Math.min(3e4,Math.max(1e3,Number(u)||Nt)),g=d*BigInt(1e4-l.selectedBps),h=g/10000n;if(g%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 ${l.selectedBps} bps floor without rounding to zero`);let b=Number((d-h)*10000n/(d===0n?1n:d));if(b>l.capBps)throw new Error(`auto-slippage: realised floor implies ${b} bps, above cap ${l.capBps} \u2014 refusing to issue a guard weaker than advertised`);return Tt({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:d.toString(),minAmountOut:h.toString(),requiredBps:l.requiredBps,selectedBps:l.selectedBps,capBps:l.capBps,quotedAtMs:m,expiresAtMs:m+f},{secret:p})}function I(e,{chainId:t,venue:r,amountOut:n,liquidityUsd:o,priceChange5m:a,crossChain:s,requestedCapBps:i,quotedAtMs:c=Date.now(),ttlMs:u}={}){let p=_n({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:o,priceChange5m:a,crossChain:s,requestedCapBps:i,quotedAtMs:c,ttlMs:u});return{...e,autoSlippage:p,amountOutMinimum:p.minAmountOut}}var Ot,Nt,L=S(()=>{Ct();kt();Ot=100,Nt=2e4});function Pe(e){let t=String(e||"").trim();return/^0x[0-9a-fA-F]{40}$/.test(t)?t:F}var F,le=S(()=>{F="0x000000000000000000000000000000000000dEaD"});import{createHash as Tn,createHmac as Rn,timingSafeEqual as Ma}from"node:crypto";function qe(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(qe).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${qe(e[r])}`).join(",")}}`}function Rt(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Bt(e=process.env){return Rt(process.env)||Rt(e)}function Un(e){let{oraclePrepared:t,prepareHash:r,prepareMac:n,note:o,...a}=e||{};return a}function Ln(e){let t=Un(e);return Tn("sha256").update(qe(t)).digest("hex")}function Dn(e,t=Bt()){return t?Rn("sha256",t).update(String(e)).digest("hex"):""}function x(e,{provider:t,kind:r,env:n=process.env}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let o={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1};if(!o.provider)throw new Error("stampPrepared: provider required");if(!o.kind)throw new Error("stampPrepared: kind required");let a=Date.now(),s=a+$n,c={...o,preparedAt:a,expiresAt:s,prepareVersion:Bn},u=Ln(c),p=Bt(n),d=p?Dn(u,p):void 0,l={...c,oraclePrepared:!0,prepareHash:u};return d&&(l.prepareMac=d),l}var Bn,$n,Va,T=S(()=>{Bn=2,$n=300*1e3,Va=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Contract as Fn,JsonRpcProvider as Pn}from"ethers";function Kn(e){return jn.test(String(e||""))}async function $t(e,{contract:t=qn,rpc:r=Vn,chainId:n=Mn,balanceOf:o}={}){if(!Kn(e))throw new Error("invalid-address");if(o)return BigInt(await o(e));let a=new Pn(r,n,{staticNetwork:!0}),s=new Fn(t,Hn,a);return BigInt(await s.balanceOf(e))}var qn,Mn,Vn,Hn,jn,Ut=S(()=>{qn="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",Mn=999,Vn="https://rpc.hyperliquid.xyz/evm",Hn=["function balanceOf(address owner) view returns (uint256)"],jn=/^0x[a-fA-F0-9]{40}$/});function Gn(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(Lt,t)?Lt[t]:Wn}function Zn(e,{fallback:t=0}={}){if(e==null)return t;if(String(e).trim()==="")return 0;let r=Number(e);return!Number.isFinite(r)||r<=0?0:Math.min(Math.floor(r),zn)}function eo({env:e=process.env,action:t="swap"}={}){let r=String(e[Xn]||"").trim(),n=Gn(t),o=Zn(e[Yn],{fallback:r?n:0}),a=Math.min(o,n),s=String(e[Qn]||Jn).trim();return a?/^0x[a-fA-F0-9]{40}$/.test(r)?{bps:a,recipient:r,integrator:s,action:t,applies:!0,reason:"configured"}:{bps:0,recipient:"",integrator:s,action:t,applies:!1,reason:"no-recipient"}:{bps:0,recipient:"",integrator:s,action:t,applies:!1,reason:"not-configured"}}async function de({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={}}={}){let o=eo({env:t,action:r}),a=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(a))return{...o,holderVerificationStatus:"wallet-required"};try{return BigInt(await $t(a,n))>0n?{...o,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...o,holderVerificationStatus:"non-holder"}}catch{return{...o,holderVerificationStatus:"unavailable"}}}function Dt(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}function Ft(e){return e?.applies?{partner:e.integrator,partnerFeeBps:String(e.bps),partnerAddress:e.recipient}:{}}var zn,Wn,Lt,Yn,Xn,Qn,Jn,Me=S(()=>{Ut();zn=100,Wn=5,Lt=Object.freeze({swap:5,bridge:15,perps:0,nft:0});Yn="ORACLE_INTEGRATOR_FEE_BPS",Xn="ORACLE_INTEGRATOR_FEE_RECIPIENT",Qn="ORACLE_INTEGRATOR_ID",Jn="oracle"});var je={};V(je,{LIFI_API:()=>qt,lifiChains:()=>ao,lifiHealth:()=>no,lifiPrepare:()=>oo,lifiQuote:()=>J});function He(e={}){return(e.baseUrl||process.env.LIFI_API_URL||qt).replace(/\/$/,"")}function ro(e){let t=String(e||Ve).toLowerCase();return t===Ve.toLowerCase()||t===to}function Pt(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 no(e={}){let t=await A(`${He(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 J(e={},t={}){let{fromChain:r,toChain:n=r,fromToken:o=Ve,toToken:a,fromAmount:s,fromAddress:i=F}=e;if(r==null||!a||!s)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let c=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:o,toToken:a,fromAmount:String(s),fromAddress:i}),u=U({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!u.executable)throw new Error(`lifi: route requires ${u.requiredBps} bps above cap ${u.capBps}`);c.set("slippage",String(u.selectedBps/1e4));let p=await de({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[h,b]of Object.entries(Dt(p)))c.set(h,b);let d=await A(`${He(t)}/quote?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),l=d?.estimate?.toAmount||d?.toAmount;if(!l)return{...d,autoSlippagePolicy:u,oracleFee:p};let m=d?.transactionRequest?.to||d?.estimate?.approvalAddress||"lifi",f=I(d,{chainId:Number(r),venue:m,amountOut:l,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),g=d?.estimate?.toAmountMin||d?.toAmountMin;if(g!=null&&BigInt(g)<BigInt(f.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...f,oracleFee:p}}async function oo(e={},t={}){let r=await J(e,t),n=r?.transactionRequest;if(!n?.to||!n?.data)throw new Error("lifi: quote did not return an executable transactionRequest");let o=Number(e.fromChain);if(n.chainId!=null&&Number(n.chainId)!==o)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 a=null;if(!ro(e.fromToken)){let s=r?.estimate?.approvalAddress||r?.approvalAddress;if(!s)throw new Error("lifi: ERC20 route missing approvalAddress");let i=r?.action?.fromToken?.address||r?.estimate?.fromToken?.address||e.fromToken;a={token:Pt(i,"approval token"),spender:Pt(s,"approval spender"),amount:String(e.fromAmount)}}return x({provider:"lifi",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:o,quote:r,autoSlippage:r.autoSlippage,requiresApproval:a,transaction:{chainId:o,from:n.from||e.fromAddress,to:n.to,data:n.data,value:n.value??"0x0",...n.gasLimit!=null?{gasLimit:n.gasLimit}:{},slippageGuard:_(r.autoSlippage,{chainId:o,venue:n.to,data:n.data})}},{provider:"lifi",kind:"lifi-tx"})}async function ao(e={}){return A(`${He(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var qt,Ve,to,pe=S(()=>{$();L();le();T();Me();qt="https://li.quest/v1";Ve="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",to="0x0000000000000000000000000000000000000000"});var Ht={};V(Ht,{PARASWAP_API:()=>Mt,paraswapHealth:()=>so,paraswapPrepare:()=>io,paraswapPrice:()=>me,paraswapTokens:()=>Vt});function K(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 Vt(e={},t={}){let r=Number(e.chainId||1);return A(`${Ke(t)}/tokens/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function me(e={},t={}){let r=Number(e.chainId||e.network||1);if(e.amount==null)throw new Error("amount required");let n=new URLSearchParams({srcToken:K(e.srcToken,"srcToken"),destToken:K(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 o=await de({wallet:e.userAddress||e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[i,c]of Object.entries(Ft(o)))n.set(i,c);let a=await A(`${Ke(t)}/prices?${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),s=a?.priceRoute?.destAmount;return s?{...I(a,{chainId:r,venue:a?.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:o}:{...a,executionReady:!1,oracleFee:o}}async function io(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=K(e.userAddress,"userAddress"),o=await me(e,t),a=o?.priceRoute,s=String(a?.contractAddress||"").toLowerCase();if(!s)throw new Error("paraswap: price route missing contractAddress");let i={srcToken:K(e.srcToken,"srcToken"),destToken:K(e.destToken,"destToken"),srcAmount:String(a.srcAmount||e.amount),destAmount:String(o.amountOutMinimum),priceRoute:a,userAddress:n,ignoreChecks:!1,ignoreGasEstimate:!1};e.receiver&&(i.receiver=K(e.receiver,"receiver"));let c=await A(`${Ke(t)}/transactions/${r}`,{method:"POST",body:i,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()!==s)throw new Error("paraswap: transaction target mismatch");if(c.from&&String(c.from).toLowerCase()!==n)throw new Error("paraswap: transaction sender mismatch");return x({provider:"paraswap",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,quote:o,autoSlippage:o.autoSlippage,requiresApproval:i.srcToken!=="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"?{token:i.srcToken,spender:a.tokenTransferProxy||s,amount:i.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:_(o.autoSlippage,{chainId:r,venue:c.to,data:c.data})}},{provider:"paraswap",kind:"paraswap-tx"})}async function so(e={}){let t=await Vt({chainId:1},e),r=Array.isArray(t?.tokens)?t.tokens.length:Object.keys(t?.tokens||{}).length;return{ok:r>0,tokenSample:r}}var Mt,Ke,ze=S(()=>{$();L();T();Me();Mt="https://api.paraswap.io",Ke=(e={})=>(e.baseUrl||process.env.PARASWAP_API_URL||Mt).replace(/\/$/,"")});function fe({provider:e,defaultUrl:t,hosts:r=[],url:n,strict:o=!1}){let s=(String(n??"").trim()||String(t)).replace(/\/$/,"");if(s===String(t).replace(/\/$/,""))return{baseUrl:s,trusted:!0,host:Kt(t)};let i;try{i=new URL(s)}catch{throw new Error(`${e}: baseUrl must be an absolute http(s) URL`)}if(i.protocol!=="http:"&&i.protocol!=="https:")throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);let c=i.host;if(!c)throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);if(new Set([Kt(t),...r]).has(c)){let p=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(c);return i.protocol==="http:"&&!p?{baseUrl:s,trusted:!1,host:c,reason:"plaintext http downgrade"}:{baseUrl:s,trusted:!0,host:c}}if(String(process.env[jt]||"")==="1")return{baseUrl:s,trusted:!1,host:c};if(o)throw new Error(`${e}: refusing to call non-allowlisted host ${c} (set ${jt}=1 to permit it)`);return{baseUrl:s,trusted:!1,host:c}}function Kt(e){let t=new URL(String(e));if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("unsupported protocol");return t.host}function he(e,t,r){let n={...e};if(!r)return n;for(let[o,a]of Object.entries(t||{}))a&&(n[o]=a);return n}var jt,We=S(()=>{jt="ORACLE_ALLOW_CUSTOM_PROVIDER_URL"});var Qt={};V(Qt,{ZEROX_API:()=>zt,zeroxHealth:()=>co,zeroxPrepare:()=>uo,zeroxPrice:()=>Xt,zeroxQuote:()=>be});function Wt(e={}){return fe({provider:"zerox",defaultUrl:zt,hosts:["api.0x.org"],url:e.baseUrl||process.env.ZEROX_API_URL})}function Gt(e={}){return Wt(e).baseUrl}function ge(e={}){return e.apiKey||process.env.ZEROX_API_KEY||process.env.OX_API_KEY||process.env["0X_API_KEY"]||""}function Yt(e={}){return he({"0x-version":"v2",accept:"application/json"},{"0x-api-key":ge(e)},Wt(e).trusted)}async function co(e={}){if(!ge(e))return{ok:!1,configured:!1,error:"ZEROX_API_KEY not set"};try{let t=await Xt({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 Xt(e={},t={}){if(!ge(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:o,sellAmount:a,taker:s}=e;if(!n||!o||!a)throw new Error("zeroxPrice requires sellToken, buyToken, sellAmount");let i=new URLSearchParams({chainId:String(r),sellToken:n,buyToken:o,sellAmount:String(a)});return s&&i.set("taker",s),A(`${Gt(t)}/swap/allowance-holder/price?${i}`,{headers:Yt(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function be(e={},t={}){if(!ge(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:o,sellAmount:a,taker:s}=e;if(!n||!o||!a)throw new Error("zeroxQuote requires sellToken, buyToken, sellAmount");let i=U({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!i.executable)throw new Error(`0x: route requires ${i.requiredBps} bps above cap ${i.capBps}`);let c=new URLSearchParams({chainId:String(r),sellToken:n,buyToken:o,sellAmount:String(a),slippageBps:String(i.selectedBps)});s&&c.set("taker",s);let u=await A(`${Gt(t)}/swap/allowance-holder/quote?${c}`,{headers:Yt(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),p=u?.buyAmount||u?.grossBuyAmount;return p?I(u,{chainId:r,venue:u?.transaction?.to||u?.to||"0x",amountOut:p,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):{...u,autoSlippagePolicy:i}}async function uo(e={},t={}){if(!e.taker)throw new Error("0x: taker required for executable prepare");let r=await be(e,t),n=r?.transaction;if(!n?.to||!n?.data)throw new Error("0x: firm quote returned no transaction");let o=Number(e.chainId??8453),a=r?.issues?.allowance?.spender||r?.allowanceTarget;return x({provider:"zerox",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:o,quote:r,autoSlippage:r.autoSlippage,requiresApproval:r?.issues?.allowance?.actual!=null&&BigInt(r.issues.allowance.actual)<BigInt(e.sellAmount)?{token:e.sellToken,spender:a,amount:String(e.sellAmount)}:null,transaction:{chainId:o,from:e.taker,to:n.to,data:n.data,value:n.value??"0x0",...n.gas!=null?{gasLimit:n.gas}:{},slippageGuard:_(r.autoSlippage,{chainId:o,venue:n.to,data:n.data})}},{provider:"zerox",kind:"zerox-tx"})}var zt,Ge=S(()=>{$();L();We();T();zt="https://api.0x.org"});var fi,hi,tr=S(()=>{fi=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"}),hi=Object.freeze({"evm:prepare":["ORACLE_EVM_ADDRESS","EVM_KEYSTORE_FILE","ORACLE_SIGNER_ADDRESS"],"evm:execute":["EVM_KEYSTORE_FILE","ORACLE_KEYSTORE_FILE"],"btc:execute":["BTC_WIF_FILE","ORACLE_BTC_WIF_FILE"],"solana:execute":["SOLANA_KEYPAIR_FILE","ORACLE_SOLANA_KEYPAIR_FILE"],"nft:buy":[],"nft:mint":[],"cow:submit":[]})});var dr={};V(dr,{COW_CANCEL_TYPES:()=>ir,COW_HOSTS:()=>Xe,COW_ORDER_TYPES:()=>we,COW_SETTLEMENT:()=>nr,COW_VAULT_RELAYER:()=>or,cowCancelOrders:()=>Io,cowChains:()=>Oo,cowHealth:()=>wo,cowOrder:()=>lr,cowOrderStatus:()=>ur,cowOrderUid:()=>yo,cowPrepareCancel:()=>xo,cowPrepareOrder:()=>Eo,cowQuote:()=>ee,cowSignCancel:()=>So,cowSignOrder:()=>Ao,cowSubmitSignedOrder:()=>vo,cowVerifyOrderFill:()=>ko});import{TypedDataEncoder as rr,getAddress as Z,isAddress as fo}from"ethers";function Ee(e,t={}){if(t.baseUrl)return t.baseUrl.replace(/\/$/,"");let r=Xe[Number(e)];if(!r)throw new Error(`cowswap: unsupported chainId ${e}`);return r}function ho(e,t="v1",r={}){let n=Ee(e,r);return t==="v1"?n:n.replace(/\/api\/v1$/,`/api/${t}`)}function P(e,t){let r=String(e||"").trim();if(!fo(r))throw new Error(`cowswap: ${t} must be an address`);return Z(r).toLowerCase()}function z(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 sr(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 cr(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 go({digest:e,owner:t,validTo:r}={}){let n=sr(e,"order digest").slice(2),o=P(t,"owner").slice(2).toLowerCase(),a=Number(r);if(!Number.isInteger(a)||a<0||a>4294967295)throw new Error("cowswap: validTo must fit uint32");return`0x${n}${o}${a.toString(16).padStart(8,"0")}`.toLowerCase()}function Qe(e){let t=nr[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:Z(t)}}function bo(e={},t,r){let n=P(e.sellToken,"sellToken"),o=P(e.buyToken,"buyToken"),a=P(e.receiver||r,"receiver"),s=Number(e.validTo);if(!Number.isInteger(s)||s<=0)throw new Error("cowswap: quote.validTo required");let i=sr(e.appData||e.appDataHash||`0x${"0".repeat(64)}`,"appData");return{sellToken:n,buyToken:o,receiver:a,sellAmount:z(e.sellAmount,"sellAmount"),buyAmount:z(e.buyAmount,"buyAmount"),validTo:s,appData:i,feeAmount:z(e.feeAmount??"0","feeAmount"),kind:String(e.kind||"sell"),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance||"erc20"),buyTokenBalance:String(e.buyTokenBalance||"erc20")}}async function wo(e={}){try{let t=await ee({chainId:1,sellToken:Ye[1],buyToken:ar[1],sellAmountBeforeFee:"1000000000000000",from:F},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 ee(e={},t={}){let r=Number(e.chainId??1),n=Pe(e.from||e.owner),o=e.sellToken||Ye[r],a=e.buyToken||ar[r],s=String(e.sellAmountBeforeFee||e.sellAmount||"0");if(!o||!a||s==="0")throw new Error("cowQuote requires sellToken, buyToken, sellAmountBeforeFee");if(/eeeeeeee|native|^eth$/i.test(o)&&(o=Ye[r],!o))throw new Error("no WETH mapping for chain");let i={sellToken:o,buyToken:a,from:n,receiver:e.receiver||n,sellAmountBeforeFee:s,kind:e.kind||"sell",signingScheme:e.signingScheme||"eip1271"},c=await A(`${Ee(r,t)}/quote`,{method:"POST",body:i,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),u=c?.quote?.buyAmount||c?.buyAmount;return u?I(c,{chainId:r,venue:"cowswap-order",amountOut:u,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):c}async function Eo(e={},t={}){let r=Number(e.chainId??1),n=P(Pe(e.from||e.owner||e.signer),"owner"),o=await ee({...e,chainId:r,from:n,signingScheme:e.signingScheme||"eip712"},t),a=bo(o?.quote||o,r,n),s=Qe(r),i={domain:s,types:we,primaryType:"Order",message:a},c=rr.hash(s,we,a),u=or[r];if(!u)throw new Error(`cowswap: vault relayer not registered for chain ${r}`);return x({provider:"cowswap",orderReady:!0,executionReady:!1,chainId:r,owner:n,signingScheme:"eip712",settlement:s.verifyingContract.toLowerCase(),vaultRelayer:Z(u).toLowerCase(),quote:o,quoteId:o?.id??e.quoteId??null,typedData:i,cowGuard:{mode:"cow-order",version:1,provider:"cowswap",chainId:r,owner:n,settlement:s.verifyingContract.toLowerCase(),vaultRelayer:Z(u).toLowerCase(),sellToken:a.sellToken,buyToken:a.buyToken,sellAmount:a.sellAmount,buyAmount:a.buyAmount,validTo:a.validTo,quoteId:o?.id??e.quoteId??null,typedDataHash:c,issuedAtMs:Date.now(),expiresAtMs:Math.min(a.validTo*1e3,Date.now()+2e4)},requiresApproval:{token:a.sellToken,spender:Z(u).toLowerCase(),amount:a.sellAmount}},{provider:"cowswap",kind:"cow-order"})}async function ur(e={},t={}){let r=Number(e.chainId??1),n=String(e.uid||e.orderUid||"").trim();if(!n)throw new Error("cowOrderStatus requires uid");return A(`${Ee(r,t)}/orders/${encodeURIComponent(n)}/status`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function lr(e={},t={}){let r=Number(e.chainId??1),n=String(e.uid||e.orderUid||"").trim();if(!n)throw new Error("cowOrder requires uid");return A(`${Ee(r,t)}/orders/${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}function yo(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 o=e.cowGuard?.typedDataHash||rr.hash(Qe(r),we,n),a=e.owner||e.from||e.signer||n.receiver;return go({digest:o,owner:a,validTo:n.validTo})}async function Ao(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 vo(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 xo(e={}){let t=Number(e.chainId??1),r=P(e.owner||e.from||e.signer,"owner"),n=(e.orderUids||e.uids||[e.uid]).filter(Boolean).map((s,i)=>cr(s,`orderUids[${i}]`));if(!n.length)throw new Error("cowswap: orderUids required");let o=Qe(t);return x({provider:"cowswap",chainId:t,owner:r,orderUids:n,signingScheme:"eip712",typedData:{domain:o,types:ir,primaryType:"OrderCancellations",message:{orderUids:n}},cancelReady:!0,executableArtifact:!0},{provider:"cowswap",kind:"cow-cancel"})}async function So(e={},t={}){throw new Error("cowswap.cowSignCancel refused: @oracle-agent/oracle is prepare-only. Cancel-sign with the user wallet.")}async function Io(e={},t={}){throw new Error("cowswap.cowCancelOrders refused: @oracle-agent/oracle is prepare-only. Cancel from the user wallet or local operator.")}function Co(e={}){return z(e.buyAmount??e.executedBuyAmount??"0","trade.buyAmount")}async function ko(e={},t={}){let r=Number(e.chainId??1),n=cr(e.uid||e.orderUid),o=t.order||await lr({chainId:r,uid:n},t),a=t.status||o.status||await ur({chainId:r,uid:n},t).catch(()=>null),s=t.trades||await A(`${ho(r,"v2",t)}/trades?orderUid=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),i=Array.isArray(s)?s:[],c=e.expectedOwner?P(e.expectedOwner,"expectedOwner"):null;if(c&&P(o.owner||i[0]?.owner||c,"owner")!==c)return{ok:!1,provider:"cowswap",chainId:r,uid:n,reason:"owner mismatch",order:o,status:a,trades:i};let u=0n;for(let l of i.filter(m=>String(m.orderUid||"").toLowerCase()===n))u+=BigInt(Co(l));u===0n&&o.executedBuyAmount!=null&&(u=BigInt(z(o.executedBuyAmount,"executedBuyAmount")));let p=e.minBuyAmount!=null?BigInt(z(e.minBuyAmount,"minBuyAmount")):0n,d=u>=p&&String(o.status||a?.status||"").toLowerCase()!=="expired";return{ok:d,provider:"cowswap",chainId:r,uid:n,status:o.status||a?.status||null,executedBuyAmount:u.toString(),minBuyAmount:e.minBuyAmount??null,trades:i,settlementTxs:[...new Set(i.map(l=>l.txHash).filter(Boolean))],order:o,orderStatus:a,reason:d?null:"insufficient fill or expired order"}}function Oo(){return Object.keys(Xe).map(Number)}var Xe,nr,or,Ye,ar,we,ir,Je=S(()=>{$();L();tr();le();T();Xe={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"},nr=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),or=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"}),Ye={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"},ar={1:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",42161:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},we=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"}]}),ir=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]})});function mr(e){return No.get(Number(e))||null}function fr(e,t=process.env){let r=mr(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}var pr,No,hr=S(()=>{pr={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}},No=new Map(Object.values(pr).map(e=>[e.chainId,e]))});import{Interface as _o,getAddress as To}from"ethers";function br(e,t){try{return To(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}function Bo(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=fr(e,r);return n||Ro[Number(e)]||null}function Uo(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!$o.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 k(e,t,r=[],n={}){let o=String(t||"");Uo(o);let a=Bo(e,n);if(!a)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let i=await A(a,{method:"POST",body:{jsonrpc:"2.0",id:1,method:t,params:r},fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs??12e3});if(i?.error){let c=new Error(i.error.message||JSON.stringify(i.error));throw c.code=i.error.code,c}return i.result}async function wr(e,t={}){let r=await k(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function Er(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await k(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function yr(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=br(e.token||e.tokenAddress,"token"),o=br(e.account||e.owner||e.address,"account"),a=gr.encodeFunctionData("balanceOf",[o]),s=await k(r,"eth_call",[{to:n,data:a},e.blockTag||"latest"],t),i=gr.decodeFunctionResult("balanceOf",s),c=BigInt(i[0]);return{chainId:r,token:n,account:o,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:e.blockTag||"latest"}}var gr,Ro,$o,W=S(()=>{$();hr();gr=new _o(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);Ro={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"};$o=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/});var Or={};V(Or,{PANCAKE_FEE_TIERS:()=>ye,UNI_V3_CHAINS:()=>O,UNI_V3_FEE_TIERS:()=>xr,UNI_V3_VENUES:()=>Cr,uniV3Chains:()=>Mo,uniV3EthUsdc:()=>kr,uniV3Health:()=>qo,uniV3PrepareExactIn:()=>Po,uniV3QuoteExactIn:()=>re,uniV3QuoteExactInPath:()=>Fo});import{Interface as vr,getAddress as te,isAddress as Lo}from"ethers";function et(e,t){let r=Number(e),n=O[r];if(!n)throw new Error(`uniswap-v3: unsupported chainId ${e} (supported: ${Object.keys(O).join(", ")})`);let o=Cr[r]||{};if(!t){if(!n.quoter||!n.router){let c=Object.keys(o).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 a=String(t).toLowerCase();if(a===n.name&&n.quoter&&n.router)return{chainId:r,venue:n.name,...n};let s=o,i=s[a];if(!i){let c=[...n.quoter&&n.router?[n.name]:[],...Object.keys(s)].join(", ");throw new Error(`uniswap-v3: unknown venue "${t}" on chain ${r} (known: ${c})`)}return{chainId:r,venue:a,...n,quoter:i.quoter,router:i.router,feeTiers:i.feeTiers||null}}function Ze(e,t){let r=O[Number(t)];if(!e||e===Sr||e===Ir||/^eth$/i.test(String(e)))return te(r.weth);let n=String(e);if(/^weth$/i.test(n))return te(r.weth);if(/^usdc$/i.test(n))return te(r.usdc);if(!Lo(n))throw new Error(`invalid token address: ${e}`);return te(n)}function Do(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 re(e={},t={}){let{chainId:r,quoter:n,router:o,feeTiers:a}=et(e.chainId??8453,e.venue),s=Ze(e.tokenIn||"WETH",r),i=Ze(e.tokenOut||O[r].usdc,r),c=BigInt(e.amountIn??0);if(c<=0n)throw new Error("amountIn required (raw base units)");let u=a&&a.length?a:xr,p=e.fee!=null?[Number(e.fee)]:e.tryFees===!1?[u[Math.min(2,u.length-1)]]:[...u],d=[],l=null;for(let m of p){let f=Ae.encodeFunctionData("quoteExactInputSingle",[{tokenIn:s,tokenOut:i,amountIn:c,fee:m,sqrtPriceLimitX96:0n}]);try{let g=await k(r,"eth_call",[{to:n,data:f},"latest"],t);if(!g||g==="0x"){d.push({fee:m,ok:!1,error:"empty result"});continue}let h=Ae.decodeFunctionResult("quoteExactInputSingle",g),b={fee:m,ok:!0,amountOut:h[0].toString(),sqrtPriceX96After:h[1].toString(),initializedTicksCrossed:Number(h[2]),gasEstimate:h[3].toString()};d.push(b),(!l||BigInt(b.amountOut)>BigInt(l.amountOut))&&(l=b)}catch(g){d.push({fee:m,ok:!1,error:String(g.message||g).slice(0,160)})}}if(!l){let m=d.map(f=>`${f.fee}:${f.error||"fail"}`).join("; ");throw new Error(`uniswap-v3 quote failed chain=${r}: ${m}`)}return I({venue:"uniswap-v3",chainId:r,chain:O[r].name,quoter:n,tokenIn:s,tokenOut:i,amountIn:c.toString(),fee:l.fee,amountOut:l.amountOut,gasEstimate:l.gasEstimate,sqrtPriceX96After:l.sqrtPriceX96After,initializedTicksCrossed:l.initializedTicksCrossed,triedFees:d,best:!0},{chainId:r,venue:o,amountOut:l.amountOut,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Fo(e={},t={}){let{chainId:r,quoter:n,router:o}=et(e.chainId??8453),a=(e.tokens||[]).map(l=>Ze(l,r)),s=(e.fees||[]).map(Number);if(a.length<2)throw new Error("tokens[] need at least 2 addresses");let i=BigInt(e.amountIn??0);if(i<=0n)throw new Error("amountIn required");let c=Do(a,s),u=Ae.encodeFunctionData("quoteExactInput",[c,i]),p=await k(r,"eth_call",[{to:n,data:u},"latest"],t),d=Ae.decodeFunctionResult("quoteExactInput",p);return I({venue:"uniswap-v3",chainId:r,chain:O[r].name,quoter:n,tokens:a,fees:s,path:c,amountIn:i.toString(),amountOut:d[0].toString(),gasEstimate:d[3].toString()},{chainId:r,venue:o,amountOut:d[0].toString(),liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function kr(e={},t={}){let r=Number(e.chainId??8453),n=e.amountIn??"1000000000000000",o=await re({chainId:r,tokenIn:O[r].weth,tokenOut:O[r].usdc,amountIn:n,fee:e.fee},t),a=Number(o.amountOut)/1e6;return{...o,amountOutUsdc:a,pair:"WETH/USDC"}}async function Po(e={},t={}){let r=Number(e.chainId??8453),n=et(r,e.venue),o=te(e.recipient),a=String(e.tokenIn||"WETH"),s=!e.tokenIn||a===Sr||a===Ir||/^eth$/i.test(a),i=await re(e,t),c=Ar.encodeFunctionData("exactInputSingle",[{tokenIn:i.tokenIn,tokenOut:i.tokenOut,fee:i.fee,recipient:o,amountIn:BigInt(i.amountIn),amountOutMinimum:BigInt(i.amountOutMinimum),sqrtPriceLimitX96:0n}]),u=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),d=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+u,l=Ar.encodeFunctionData("multicall",[d,[c]]);return x({provider:"uniswap-v3",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,deadline:d,quote:i,autoSlippage:i.autoSlippage,requiresApproval:s?null:{token:i.tokenIn,spender:n.router,amount:i.amountIn},transaction:{chainId:r,from:o,to:n.router,data:l,value:s?i.amountIn:"0",slippageGuard:_(i.autoSlippage,{chainId:r,venue:n.router,data:l})}},{provider:"uniswap-v3",kind:"univ3-swap-tx"})}async function qo(e={}){let t=Number(e.chainId??8453);try{let r=await kr({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 Mo(){return Object.entries(O).map(([e,t])=>({chainId:Number(e),name:t.name,quoter:t.quoter,weth:t.weth,usdc:t.usdc}))}var O,xr,Ae,Ar,Sr,Ir,ye,Cr,tt=S(()=>{W();L();T();O={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"}},xr=[100,500,3e3,1e4],Ae=new vr(["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)"]),Ar=new vr(["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)"]),Sr="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",Ir="0x0000000000000000000000000000000000000000",ye=[100,500,2500,1e4],Cr={56:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ye}},8453:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ye}},42161:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ye}},999:{hyperswap:{name:"hyperswap",quoter:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",router:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D"}}}});var Ur={};V(Ur,{UNI_V4_CHAINS:()=>D,UNI_V4_FEE_TIERS:()=>Rr,computeV4PoolId:()=>$r,uniV4Chains:()=>Xo,uniV4Health:()=>Qo,uniV4PrepareExactIn:()=>Yo,uniV4QuoteExactIn:()=>xe});import{AbiCoder as Vo,Interface as Tr,getAddress as R,isAddress as ve,keccak256 as Ho}from"ethers";function rt(e){let t=Number(e),r=D[t];if(!r)throw new Error(`uniswap-v4: unsupported chainId ${e} (supported: ${Object.keys(D).join(", ")})`);return{chainId:t,...r}}function _r(e,t){let r=D[Number(t)];if(!e||e===Br||e===H||/^eth$/i.test(String(e)))return R(r.weth);let n=String(e);if(/^weth$/i.test(n))return R(r.weth);if(/^usdc$/i.test(n)||/^usdg$/i.test(n))return R(r.usdc);if(!ve(n))throw new Error(`invalid token address: ${e}`);return R(n)}function $r({currency0:e,currency1:t,fee:r,tickSpacing:n,hooks:o=H}){let a=R(e),s=R(t);if(a.toLowerCase()===s.toLowerCase())throw new Error("poolKey currencies must differ");let[i,c]=a.toLowerCase()<s.toLowerCase()?[a,s]:[s,a],u=o&&ve(o)?R(o):H;return Ho(ne.encode(["address","address","uint24","int24","address"],[i,c,Number(r),Number(n),u]))}function Go({tokenIn:e,tokenOut:t,fee:r,tickSpacing:n,hooks:o=H}){let a=R(e),s=R(t),[i,c]=a.toLowerCase()<s.toLowerCase()?[a,s]:[s,a],u=a.toLowerCase()===i.toLowerCase();return{poolKey:{currency0:i,currency1:c,fee:Number(r),tickSpacing:Number(n),hooks:o&&ve(o)?R(o):H},zeroForOne:u}}async function xe(e={},t={}){let{chainId:r,quoter:n,poolManager:o,universalRouter:a}=rt(e.chainId??8453),s=_r(e.tokenIn||"WETH",r),i=_r(e.tokenOut||D[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 u=e.fee!=null&&e.tickSpacing!=null?[{fee:Number(e.fee),tickSpacing:Number(e.tickSpacing)}]:e.tryTiers===!1?[{fee:500,tickSpacing:10}]:[...Rr],p=e.hooks||H,d=[],l=null;for(let m of u){let{poolKey:f,zeroForOne:g}=Go({tokenIn:s,tokenOut:i,fee:m.fee,tickSpacing:m.tickSpacing,hooks:p}),h=Nr.encodeFunctionData("quoteExactInputSingle",[{poolKey:f,zeroForOne:g,exactAmount:c,hookData:"0x"}]);try{let b=await k(r,"eth_call",[{to:n,data:h},"latest"],t);if(!b||b==="0x"){d.push({...m,ok:!1,error:"empty result"});continue}let v=Nr.decodeFunctionResult("quoteExactInputSingle",b),C={fee:m.fee,tickSpacing:m.tickSpacing,ok:!0,amountOut:v[0].toString(),gasEstimate:v[1].toString(),poolKey:f,zeroForOne:g,poolId:$r({...f})};d.push(C),(!l||BigInt(C.amountOut)>BigInt(l.amountOut))&&(l=C)}catch(b){d.push({...m,ok:!1,error:String(b.message||b).slice(0,160)})}}if(!l){let m=d.map(f=>`${f.fee}/${f.tickSpacing}:${f.error||"fail"}`).join("; ");throw new Error(`uniswap-v4 quote failed chain=${r}: ${m}`)}return I({venue:"uniswap-v4",chainId:r,chain:D[r].name,poolManager:o,quoter:n,universalRouter:a||null,tokenIn:s,tokenOut:i,amountIn:c.toString(),fee:l.fee,tickSpacing:l.tickSpacing,hooks:l.poolKey.hooks,poolId:l.poolId,zeroForOne:l.zeroForOne,amountOut:l.amountOut,gasEstimate:l.gasEstimate,triedTiers:d,best:!0,executionReady:!1,prepareReady:typeof e.recipient=="string"&&ve(e.recipient)&&e.slippageBps!=null},{chainId:r,venue:a||n,amountOut:l.amountOut,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Yo(e={},t={}){let r=Number(e.chainId??8453),n=rt(r);if(!e.recipient)throw new Error("uniswap-v4 prepare requires recipient");let o=R(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>=1e4)throw new Error("slippageBps must be an integer from 0 through 9999");let s=String(e.tokenIn||"");if(!s||s===Br||s===H||/^eth$/i.test(s))throw new Error("uniswap-v4 prepare currently requires an ERC-20 tokenIn; native input is not inferred");let i=await xe(e,t);if(!n.universalRouter)throw new Error(`uniswap-v4: no Universal Router on chain ${r}`);let c=BigInt(i.amountOut)*BigInt(1e4-a)/10000n,u={currency0:i.zeroForOne?i.tokenIn:i.tokenOut,currency1:i.zeroForOne?i.tokenOut:i.tokenIn,fee:i.fee,tickSpacing:i.tickSpacing,hooks:i.hooks},d=ne.encode(["tuple(tuple(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 amountIn,uint128 amountOutMinimum,uint256 minHopPriceX36,bytes hookData)"],[[u,i.zeroForOne,BigInt(i.amountIn),c,0n,"0x"]]),l=ne.encode(["address","uint256"],[i.tokenIn,BigInt(i.amountIn)]),m=ne.encode(["address","uint256"],[i.tokenOut,c]),f=ne.encode(["bytes","bytes[]"],[zo,[d,l,m]]),g=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),b=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+g,v=jo.encodeFunctionData("execute",[Ko,[f],b]);return x({provider:"uniswap-v4",prepareReady:!0,calldataReady:!0,executionReady:!1,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,deadline:b,quote:{...i,amountOutMinimum:c.toString(),slippageBps:a},requiresApproval:{token:i.tokenIn,spender:Wo,amount:i.amountIn,note:"Universal Router V4 settlement uses Permit2; Permit2 authorization for the Universal Router is also required"},transaction:{chainId:r,from:o,to:n.universalRouter,data:v,value:"0"}},{provider:"uniswap-v4",kind:"univ4-swap-tx"})}async function Xo(){return Object.entries(D).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 Qo(e={}){let t=rt(e.chainId??8453),r=await k(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 ne,H,D,Rr,Nr,jo,Ko,zo,Wo,Br,nt=S(()=>{W();L();T();ne=Vo.defaultAbiCoder(),H="0x0000000000000000000000000000000000000000",D={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"}},Rr=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200},{fee:25e3,tickSpacing:8}],Nr=new Tr(["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)"]),jo=new Tr(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),Ko="0x10",zo="0x060c0f",Wo="0x000000000022D473030F116dDEE9F6B43aC78BA3",Br="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"});var Ie={};V(Ie,{ACROSS_API:()=>Lr,HOP_API:()=>Dr,RELAY_API:()=>Fr,acrossHealth:()=>ta,acrossSuggestedFees:()=>Pr,hopHealth:()=>ra,hopQuote:()=>qr,relayHealth:()=>na,relayPrepare:()=>oa,relayQuote:()=>ot});async function ta(e={}){try{return{ok:!0,estimatedFillTimeSec:(await Pr({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 Pr(e={},t={}){let{token:r,destinationToken:n=r,originChainId:o,destinationChainId:a,amount:s}=e;if(!r||o==null||a==null||!s)throw new Error("acrossSuggestedFees requires token, originChainId, destinationChainId, amount");let i=new URLSearchParams({token:r,destinationToken:n,originChainId:String(o),destinationChainId:String(a),amount:String(s)}),c=(t.baseUrl||process.env.ACROSS_API_URL||Lr).replace(/\/$/,"");return A(`${c}/suggested-fees?${i}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function ra(e={}){try{let t=await qr({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 qr(e={},t={}){let{amount:r,token:n="ETH",fromChain:o="ethereum",toChain:a="arbitrum"}=e;if(!r)throw new Error("hopQuote requires amount");let s=e.slippage==null?void 0:Math.round(Number(e.slippage)*100),i=U({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:o!==a,requestedCapBps:e.maxSlippageBps??e.slippageBps??s});if(!i.executable)throw new Error(`hop: route requires ${i.requiredBps} bps above cap ${i.capBps}`);let c=new URLSearchParams({amount:String(r),token:n,fromChain:o,toChain:a,slippage:String(i.selectedBps/100)}),u=(t.baseUrl||process.env.HOP_API_URL||Dr).replace(/\/$/,""),p=await A(`${u}/quote?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),d=p?.estimatedRecieved||p?.estimatedReceived;return d?I(p,{chainId:Number(e.originChainId||e.chainId||ea[o]||0),venue:p?.tx?.to||"hop",amountOut:d,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:o!==a,requestedCapBps:e.maxSlippageBps??e.slippageBps??s}):{...p,autoSlippagePolicy:i}}async function na(e={}){try{let t=await ot({user:F,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 ot(e={},t={}){let{user:r=F,originChainId:n,destinationChainId:o,originCurrency:a="0x0000000000000000000000000000000000000000",destinationCurrency:s="0x0000000000000000000000000000000000000000",amount:i,tradeType:c="EXACT_INPUT"}=e;if(n==null||o==null||!i)throw new Error("relayQuote requires originChainId, destinationChainId, amount");let u=U({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(o),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!u.executable)throw new Error(`relay: route requires ${u.requiredBps} bps above cap ${u.capBps}`);let p=(t.baseUrl||process.env.RELAY_API_URL||Fr).replace(/\/$/,""),d=await A(`${p}/quote`,{method:"POST",body:{user:r,originChainId:Number(n),destinationChainId:Number(o),originCurrency:a,destinationCurrency:s,amount:String(i),tradeType:c,slippageTolerance:String(u.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),l=d?.details?.currencyOut?.amount;return!l||!/^\d+$/.test(String(l))?{...d,autoSlippagePolicy:u}:I(d,{chainId:Number(n),venue:d?.steps?.[0]?.items?.[0]?.data?.to||"relay",amountOut:l,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(o),requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function oa(e={},t={}){let r=await ot(e,t),n=Number(e.originChainId),o=(r.steps||[]).flatMap(i=>(i.items||[]).filter(c=>c?.data?.to&&c?.data?.data).map(c=>({stepId:i.id,...c.data})));if(!o.length)throw new Error("relay: quote returned no executable transaction items");let a=String(r?.autoSlippage?.venue||"").toLowerCase();if(o.some(i=>String(i.to).toLowerCase()!==a))throw new Error("relay: route includes a separate approval/transaction that is not yet safely bound");let s=o.map(i=>({chainId:n,from:i.from||e.user,to:i.to,data:i.data,value:i.value??"0x0",...i.gasLimit!=null||i.gas!=null?{gasLimit:i.gasLimit??i.gas}:{},slippageGuard:_(r.autoSlippage,{chainId:n,venue:i.to,data:i.data})}));return x({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 Lr,Dr,Fr,ea,Ce=S(()=>{$();L();le();T();Lr="https://across.to/api",Dr="https://api.hop.exchange/v1",Fr="https://api.relay.link",ea={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453}});var ie=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),E=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),w=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),sn=/^0x[0-9a-fA-F]{40}$/;function cn(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 o of e.rpcEnv)(typeof o!="string"||!/^[A-Z][A-Z0-9_]*$/.test(o))&&t.push(`rpcEnv entry "${o}" should be an UPPER_SNAKE env var name`);if(e.nativeCurrency){let o=e.nativeCurrency;(typeof o.symbol!="string"||!o.symbol)&&t.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(o.decimals)||t.push("nativeCurrency.decimals must be an integer")}for(let[o,a]of(e.venues||[]).entries()){let s=`venues[${o}]`;if(!a||typeof a!="object"){t.push(`${s} must be an object`);continue}sn.test(a.address||"")||t.push(`${s}.address is not a valid 20-byte address`),/^0x0{40}$/.test(a.address||"")&&t.push(`${s}.address is the zero address -- placeholder left in place?`),a.kind||t.push(`${s}.kind is required (router|quoter|factory|...)`),a.verified?(a.verified.method||t.push(`${s}.verified.method is required`),a.verified.source||t.push(`${s}.verified.source is required`),a.verified.date||r.push(`${s}.verified.date missing -- add one so staleness is visible`)):t.push(`${s} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let n=e.capabilities||{};for(let o of Object.keys(n))ie.includes(o)?typeof n[o]!="function"&&t.push(`capability "${o}" must be a function`):t.push(`unknown capability "${o}"`);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 un(e){let{ok:t,errors:r,warnings:n}=cn(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
2
+ var fn=Object.defineProperty;var S=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var W=(e,t)=>{for(var r in t)fn(e,r,{get:t[r],enumerable:!0})};import{createHash as wn}from"node:crypto";function vn(e){let t=String(e||"").toLowerCase();return Tt.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function xn(e){let t={};for(let[r,n]of Object.entries(e||{}))vn(r)||(t[r]=n);return t}function Sn(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 In(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function Cn(e,t,r){let n={};for(let[c,u]of Object.entries(r||{}))n[c.toLowerCase()]=u;let o=Object.keys(n).filter(c=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(c)),s=[...new Set([...Tt,...o])].sort().map(c=>`${c}=${n[c]??""}`).join(`
3
+ `),i=wn("sha256").update(s).digest("hex").slice(0,32);return`${e} ${t} ${i}`}function kn(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Nt):Math.min(250*2**e,Nt)+Math.floor(Math.random()*100)}async function Nn(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:a}){let s=new AbortController,i=setTimeout(()=>s.abort(),a);try{let c=String(e),u={...n||{}};for(let p=0;p<=_t;p+=1){let d=await t(c,{method:r,headers:u,body:o,signal:s.signal,redirect:"manual"}),l=await d.text(),m=null;if(l)try{m=JSON.parse(l)}catch{m=null}if(An.has(d.status)){if(r!=="GET"&&r!=="HEAD"){let g=new Error(`HTTP ${d.status} ${r} ${c} redirected non-idempotent request`);throw g.status=d.status,g.body=m??l.slice(0,300),g}if(p===_t)throw new Error(`HTTP redirect loop for ${e}`);let h=Sn(d.headers?.get?.("location"),c);In(h,c)||(u=xn(u)),c=h;continue}if(!d.ok){let h=new Error(`HTTP ${d.status} ${r} ${c}`);throw h.status=d.status,h.retryAfter=d.headers?.get?.("retry-after")??null,h.body=m??l.slice(0,300),h}return m??l}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(i)}}async function x(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,o=(t.method||"GET").toUpperCase(),a={Accept:"application/json",...t.headers||{}},s=t.body;s!=null&&typeof s!="string"&&(a["Content-Type"]=a["Content-Type"]||"application/json",s=JSON.stringify(s));let i=Number.isInteger(t.retries)?Math.max(t.retries,0):yn,c=async()=>{let m;for(let h=0;h<=i;h++)try{return await Nn(e,{fetchImpl:r,method:o,headers:a,body:s,timeoutMs:n})}catch(g){m=g;let f=g?.status,b=g?.name==="AbortError",w=new Set([408,425,429]),A=f!=null?w.has(f)||En.has(f)&&Ot.has(o):!b&&Ot.has(o);if(h===i||!A)throw g;await On(kn(h,g?.retryAfter))}throw m};if(!(t.dedupe!==!1&&o==="GET"&&s==null))return c();let p=Cn(o,e,a),d=He.get(p);if(d)return d;let l=c().finally(()=>He.delete(p));return He.set(p,l),l}var En,Ot,yn,Nt,Tt,An,_t,He,On,F=S(()=>{En=new Set([408,425,429,500,502,503,504]),Ot=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),yn=2,Nt=4e3,Tt=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],An=new Set([301,302,303,307,308]),_t=3;He=new Map;On=e=>new Promise(t=>setTimeout(t,e))});import{readFileSync as _n}from"node:fs";import{homedir as Tn}from"node:os";import{join as fe}from"node:path";function Bn(){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=Tn();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||fe(t,".config","oracle")).trim();return[e,fe(r,"exec.env")].filter(Boolean)}return[e,fe(t,".config","oracle","exec.env"),fe(t,".config","mad-desk","exec.env")].filter(Boolean)}function Bt(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of Bn())try{let a=_n(o,"utf8"),s=a.match(new RegExp(`^${t}=(.*)$`,"m"))||a.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 Rt=S(()=>{});var Ut=S(()=>{});import{createHash as Rn,createHmac as Un,timingSafeEqual as ei}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 $n(e,{required:t=!1}={}){try{return Bt(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function Dt(e){let{signature:t,...r}=e;return r}function Ft(e,{secret:t}={}){let r=$n(t);return r?{...e,signature:Un("sha256",r).update(Ke(Dt(e))).digest("hex")}:e}function Ln(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 Rn("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function R(e,{chainId:t,venue:r,data:n,secret:o}={}){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");return Ft({...Dt(e),calldataHash:Ln(n)},{secret:o})}function je(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function Dn(e){let t=e==null?$t: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,$t)}function q({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:o}={}){let a=je(e,0),s=a>0?a>=25e4?5:a>=1e5?10:a>=5e4?20:a>=1e4?40:70:n?30:10,i=Math.min(60,Math.abs(je(t,0))*2),c=Math.min(40,Math.floor(Math.max(0,je(r,0))/5e3)*5),u=Math.max(25,Math.ceil(20+s+i+c)),p=Dn(o);return{mode:"auto",requiredBps:u,selectedBps:Math.min(u,p),capBps:p,executable:u<=p}}function Fn({chainId:e,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:o=0,quoteAgeMs:a=0,crossChain:s=!1,requestedCapBps:i,quotedAtMs:c=Date.now(),ttlMs:u=Lt,secret:p}={}){let d=BigInt(r??0);if(d<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let l=q({liquidityUsd:n,priceChange5m:o,quoteAgeMs:a,crossChain:s,requestedCapBps:i});if(!l.executable)throw new Error(`auto-slippage requires ${l.requiredBps} bps above hard/requested cap ${l.capBps}; route blocked`);let m=Number(c);if(!Number.isFinite(m))throw new Error("auto-slippage: quotedAtMs must be a finite number");let h=Math.min(3e4,Math.max(1e3,Number(u)||Lt)),g=d*BigInt(1e4-l.selectedBps),f=g/10000n;if(g%10000n!==0n&&(f+=1n),f>d&&(f=d),d>0n&&f<=0n)throw new Error(`auto-slippage: quote ${d} is too small to express a ${l.selectedBps} bps floor without rounding to zero`);let b=Number((d-f)*10000n/(d===0n?1n:d));if(b>l.capBps)throw new Error(`auto-slippage: realised floor implies ${b} bps, above cap ${l.capBps} \u2014 refusing to issue a guard weaker than advertised`);return Ft({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:d.toString(),minAmountOut:f.toString(),requiredBps:l.requiredBps,selectedBps:l.selectedBps,capBps:l.capBps,quotedAtMs:m,expiresAtMs:m+h},{secret:p})}function C(e,{chainId:t,venue:r,amountOut:n,liquidityUsd:o,priceChange5m:a,crossChain:s,requestedCapBps:i,quotedAtMs:c=Date.now(),ttlMs:u}={}){let p=Fn({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:o,priceChange5m:a,crossChain:s,requestedCapBps:i,quotedAtMs:c,ttlMs:u});return{...e,autoSlippage:p,amountOutMinimum:p.minAmountOut}}var $t,Lt,M=S(()=>{Rt();Ut();$t=100,Lt=2e4});function ze(e){let t=String(e||"").trim();return/^0x[0-9a-fA-F]{40}$/.test(t)?t:H}var H,he=S(()=>{H="0x000000000000000000000000000000000000dEaD"});import{createHash as Pn,createHmac as qn,timingSafeEqual as ii}from"node:crypto";function We(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(We).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${We(e[r])}`).join(",")}}`}function Pt(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function qt(e=process.env){return Pt(process.env)||Pt(e)}function Hn(e){let{oraclePrepared:t,prepareHash:r,prepareMac:n,note:o,...a}=e||{};return a}function jn(e){let t=Hn(e);return Pn("sha256").update(We(t)).digest("hex")}function Kn(e,t=qt()){return t?qn("sha256",t).update(String(e)).digest("hex"):""}function I(e,{provider:t,kind:r,env:n=process.env}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let o={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1};if(!o.provider)throw new Error("stampPrepared: provider required");if(!o.kind)throw new Error("stampPrepared: kind required");let a=Date.now(),s=a+Vn,c={...o,preparedAt:a,expiresAt:s,prepareVersion:Mn},u=jn(c),p=qt(n),d=p?Kn(u,p):void 0,l={...c,oraclePrepared:!0,prepareHash:u};return d&&(l.prepareMac=d),l}var Mn,Vn,si,U=S(()=>{Mn=2,Vn=300*1e3,si=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Contract as zn,JsonRpcProvider as Wn}from"ethers";function Zn(e){return Jn.test(String(e||""))}async function Mt(e,{contract:t=Gn,rpc:r=Yn,chainId:n=Xn,balanceOf:o}={}){if(!Zn(e))throw new Error("invalid-address");if(o)return BigInt(await o(e));let a=new Wn(r,n,{staticNetwork:!0}),s=new zn(t,Qn,a);return BigInt(await s.balanceOf(e))}var Gn,Xn,Yn,Qn,Jn,Vt=S(()=>{Gn="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",Xn=999,Yn="https://rpc.hyperliquid.xyz/evm",Qn=["function balanceOf(address owner) view returns (uint256)"],Jn=/^0x[a-fA-F0-9]{40}$/});function ro(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(Ht,t)?Ht[t]:to}function so(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),eo)}function co({env:e=process.env,action:t="swap"}={}){let r=String(e[oo]||"").trim(),n=ro(t),o=so(e[no],{fallback:r?n:0}),a=Math.min(o,n),s=String(e[ao]||io).trim();return a?/^0x[a-fA-F0-9]{40}$/.test(r)?{bps:a,recipient:r,integrator:s,action:t,applies:!0,reason:"configured"}:{bps:0,recipient:"",integrator:s,action:t,applies:!1,reason:"no-recipient"}:{bps:0,recipient:"",integrator:s,action:t,applies:!1,reason:"not-configured"}}async function ge({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={}}={}){let o=co({env:t,action:r}),a=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(a))return{...o,holderVerificationStatus:"wallet-required"};try{return BigInt(await Mt(a,n))>0n?{...o,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...o,holderVerificationStatus:"non-holder"}}catch{return{...o,holderVerificationStatus:"unavailable"}}}function jt(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}function Kt(e){return e?.applies?{partner:e.integrator,partnerFeeBps:String(e.bps),partnerAddress:e.recipient}:{}}var eo,to,Ht,no,oo,ao,io,Ge=S(()=>{Vt();eo=100,to=5,Ht=Object.freeze({swap:5,bridge:15,perps:0,nft:0});no="ORACLE_INTEGRATOR_FEE_BPS",oo="ORACLE_INTEGRATOR_FEE_RECIPIENT",ao="ORACLE_INTEGRATOR_ID",io="oracle"});var Qe={};W(Qe,{LIFI_API:()=>Wt,lifiChains:()=>fo,lifiHealth:()=>po,lifiPrepare:()=>mo,lifiQuote:()=>ne});function Ye(e={}){return(e.baseUrl||process.env.LIFI_API_URL||Wt).replace(/\/$/,"")}function lo(e){let t=String(e||Xe).toLowerCase();return t===Xe.toLowerCase()||t===uo}function zt(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 po(e={}){let t=await x(`${Ye(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 ne(e={},t={}){let{fromChain:r,toChain:n=r,fromToken:o=Xe,toToken:a,fromAmount:s,fromAddress:i=H}=e;if(r==null||!a||!s)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let c=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:o,toToken:a,fromAmount:String(s),fromAddress:i}),u=q({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!u.executable)throw new Error(`lifi: route requires ${u.requiredBps} bps above cap ${u.capBps}`);c.set("slippage",String(u.selectedBps/1e4));let p=await ge({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[f,b]of Object.entries(jt(p)))c.set(f,b);let d=await x(`${Ye(t)}/quote?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),l=d?.estimate?.toAmount||d?.toAmount;if(!l)return{...d,autoSlippagePolicy:u,oracleFee:p};let m=d?.transactionRequest?.to||d?.estimate?.approvalAddress||"lifi",h=C(d,{chainId:Number(r),venue:m,amountOut:l,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),g=d?.estimate?.toAmountMin||d?.toAmountMin;if(g!=null&&BigInt(g)<BigInt(h.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...h,oracleFee:p}}async function mo(e={},t={}){let r=await ne(e,t),n=r?.transactionRequest;if(!n?.to||!n?.data)throw new Error("lifi: quote did not return an executable transactionRequest");let o=Number(e.fromChain);if(n.chainId!=null&&Number(n.chainId)!==o)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 a=null;if(!lo(e.fromToken)){let s=r?.estimate?.approvalAddress||r?.approvalAddress;if(!s)throw new Error("lifi: ERC20 route missing approvalAddress");let i=r?.action?.fromToken?.address||r?.estimate?.fromToken?.address||e.fromToken;a={token:zt(i,"approval token"),spender:zt(s,"approval spender"),amount:String(e.fromAmount)}}return I({provider:"lifi",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:o,quote:r,autoSlippage:r.autoSlippage,requiresApproval:a,transaction:{chainId:o,from:n.from||e.fromAddress,to:n.to,data:n.data,value:n.value??"0x0",...n.gasLimit!=null?{gasLimit:n.gasLimit}:{},slippageGuard:R(r.autoSlippage,{chainId:o,venue:n.to,data:n.data})}},{provider:"lifi",kind:"lifi-tx"})}async function fo(e={}){return x(`${Ye(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var Wt,Xe,uo,be=S(()=>{F();M();he();U();Ge();Wt="https://li.quest/v1";Xe="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",uo="0x0000000000000000000000000000000000000000"});var Yt={};W(Yt,{PARASWAP_API:()=>Gt,paraswapHealth:()=>go,paraswapPrepare:()=>ho,paraswapPrice:()=>we,paraswapTokens:()=>Xt});function Q(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 Xt(e={},t={}){let r=Number(e.chainId||1);return x(`${Je(t)}/tokens/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function we(e={},t={}){let r=Number(e.chainId||e.network||1);if(e.amount==null)throw new Error("amount required");let n=new URLSearchParams({srcToken:Q(e.srcToken,"srcToken"),destToken:Q(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 o=await ge({wallet:e.userAddress||e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[i,c]of Object.entries(Kt(o)))n.set(i,c);let a=await x(`${Je(t)}/prices?${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),s=a?.priceRoute?.destAmount;return s?{...C(a,{chainId:r,venue:a?.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:o}:{...a,executionReady:!1,oracleFee:o}}async function ho(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=Q(e.userAddress,"userAddress"),o=await we(e,t),a=o?.priceRoute,s=String(a?.contractAddress||"").toLowerCase();if(!s)throw new Error("paraswap: price route missing contractAddress");let i={srcToken:Q(e.srcToken,"srcToken"),destToken:Q(e.destToken,"destToken"),srcAmount:String(a.srcAmount||e.amount),destAmount:String(o.amountOutMinimum),priceRoute:a,userAddress:n,ignoreChecks:!1,ignoreGasEstimate:!1};e.receiver&&(i.receiver=Q(e.receiver,"receiver"));let c=await x(`${Je(t)}/transactions/${r}`,{method:"POST",body:i,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()!==s)throw new Error("paraswap: transaction target mismatch");if(c.from&&String(c.from).toLowerCase()!==n)throw new Error("paraswap: transaction sender mismatch");return I({provider:"paraswap",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,quote:o,autoSlippage:o.autoSlippage,requiresApproval:i.srcToken!=="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"?{token:i.srcToken,spender:a.tokenTransferProxy||s,amount:i.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:R(o.autoSlippage,{chainId:r,venue:c.to,data:c.data})}},{provider:"paraswap",kind:"paraswap-tx"})}async function go(e={}){let t=await Xt({chainId:1},e),r=Array.isArray(t?.tokens)?t.tokens.length:Object.keys(t?.tokens||{}).length;return{ok:r>0,tokenSample:r}}var Gt,Je,Ze=S(()=>{F();M();U();Ge();Gt="https://api.paraswap.io",Je=(e={})=>(e.baseUrl||process.env.PARASWAP_API_URL||Gt).replace(/\/$/,"")});function Ee({provider:e,defaultUrl:t,hosts:r=[],url:n,strict:o=!1}){let s=(String(n??"").trim()||String(t)).replace(/\/$/,"");if(s===String(t).replace(/\/$/,""))return{baseUrl:s,trusted:!0,host:Jt(t)};let i;try{i=new URL(s)}catch{throw new Error(`${e}: baseUrl must be an absolute http(s) URL`)}if(i.protocol!=="http:"&&i.protocol!=="https:")throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);let c=i.host;if(!c)throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);if(new Set([Jt(t),...r]).has(c)){let p=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(c);return i.protocol==="http:"&&!p?{baseUrl:s,trusted:!1,host:c,reason:"plaintext http downgrade"}:{baseUrl:s,trusted:!0,host:c}}if(String(process.env[Qt]||"")==="1")return{baseUrl:s,trusted:!1,host:c};if(o)throw new Error(`${e}: refusing to call non-allowlisted host ${c} (set ${Qt}=1 to permit it)`);return{baseUrl:s,trusted:!1,host:c}}function Jt(e){let t=new URL(String(e));if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("unsupported protocol");return t.host}function ye(e,t,r){let n={...e};if(!r)return n;for(let[o,a]of Object.entries(t||{}))a&&(n[o]=a);return n}var Qt,et=S(()=>{Qt="ORACLE_ALLOW_CUSTOM_PROVIDER_URL"});var or={};W(or,{ZEROX_API:()=>Zt,zeroxHealth:()=>bo,zeroxPrepare:()=>wo,zeroxPrice:()=>nr,zeroxQuote:()=>ve});function er(e={}){return Ee({provider:"zerox",defaultUrl:Zt,hosts:["api.0x.org"],url:e.baseUrl||process.env.ZEROX_API_URL})}function tr(e={}){return er(e).baseUrl}function Ae(e={}){return e.apiKey||process.env.ZEROX_API_KEY||process.env.OX_API_KEY||process.env["0X_API_KEY"]||""}function rr(e={}){return ye({"0x-version":"v2",accept:"application/json"},{"0x-api-key":Ae(e)},er(e).trusted)}async function bo(e={}){if(!Ae(e))return{ok:!1,configured:!1,error:"ZEROX_API_KEY not set"};try{let t=await nr({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 nr(e={},t={}){if(!Ae(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:o,sellAmount:a,taker:s}=e;if(!n||!o||!a)throw new Error("zeroxPrice requires sellToken, buyToken, sellAmount");let i=new URLSearchParams({chainId:String(r),sellToken:n,buyToken:o,sellAmount:String(a)});return s&&i.set("taker",s),x(`${tr(t)}/swap/allowance-holder/price?${i}`,{headers:rr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function ve(e={},t={}){if(!Ae(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:o,sellAmount:a,taker:s}=e;if(!n||!o||!a)throw new Error("zeroxQuote requires sellToken, buyToken, sellAmount");let i=q({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!i.executable)throw new Error(`0x: route requires ${i.requiredBps} bps above cap ${i.capBps}`);let c=new URLSearchParams({chainId:String(r),sellToken:n,buyToken:o,sellAmount:String(a),slippageBps:String(i.selectedBps)});s&&c.set("taker",s);let u=await x(`${tr(t)}/swap/allowance-holder/quote?${c}`,{headers:rr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),p=u?.buyAmount||u?.grossBuyAmount;return p?C(u,{chainId:r,venue:u?.transaction?.to||u?.to||"0x",amountOut:p,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):{...u,autoSlippagePolicy:i}}async function wo(e={},t={}){if(!e.taker)throw new Error("0x: taker required for executable prepare");let r=await ve(e,t),n=r?.transaction;if(!n?.to||!n?.data)throw new Error("0x: firm quote returned no transaction");let o=Number(e.chainId??8453),a=r?.issues?.allowance?.spender||r?.allowanceTarget;return I({provider:"zerox",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:o,quote:r,autoSlippage:r.autoSlippage,requiresApproval:r?.issues?.allowance?.actual!=null&&BigInt(r.issues.allowance.actual)<BigInt(e.sellAmount)?{token:e.sellToken,spender:a,amount:String(e.sellAmount)}:null,transaction:{chainId:o,from:e.taker,to:n.to,data:n.data,value:n.value??"0x0",...n.gas!=null?{gasLimit:n.gas}:{},slippageGuard:R(r.autoSlippage,{chainId:o,venue:n.to,data:n.data})}},{provider:"zerox",kind:"zerox-tx"})}var Zt,tt=S(()=>{F();M();et();U();Zt="https://api.0x.org"});var Ri,Ui,cr=S(()=>{Ri=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"}),Ui=Object.freeze({"evm:prepare":["ORACLE_EVM_ADDRESS","EVM_KEYSTORE_FILE","ORACLE_SIGNER_ADDRESS"],"evm:execute":["EVM_KEYSTORE_FILE","ORACLE_KEYSTORE_FILE"],"btc:execute":["BTC_WIF_FILE","ORACLE_BTC_WIF_FILE"],"solana:execute":["SOLANA_KEYPAIR_FILE","ORACLE_SOLANA_KEYPAIR_FILE"],"nft:buy":[],"nft:mint":[],"cow:submit":[]})});var wr={};W(wr,{COW_CANCEL_TYPES:()=>mr,COW_HOSTS:()=>nt,COW_ORDER_TYPES:()=>xe,COW_SETTLEMENT:()=>lr,COW_VAULT_RELAYER:()=>dr,cowCancelOrders:()=>Ro,cowChains:()=>Lo,cowHealth:()=>Co,cowOrder:()=>br,cowOrderStatus:()=>gr,cowOrderUid:()=>Oo,cowPrepareCancel:()=>To,cowPrepareOrder:()=>ko,cowQuote:()=>ae,cowSignCancel:()=>Bo,cowSignOrder:()=>No,cowSubmitSignedOrder:()=>_o,cowVerifyOrderFill:()=>$o});import{TypedDataEncoder as ur,getAddress as oe,isAddress as vo}from"ethers";function Se(e,t={}){if(t.baseUrl)return t.baseUrl.replace(/\/$/,"");let r=nt[Number(e)];if(!r)throw new Error(`cowswap: unsupported chainId ${e}`);return r}function xo(e,t="v1",r={}){let n=Se(e,r);return t==="v1"?n:n.replace(/\/api\/v1$/,`/api/${t}`)}function j(e,t){let r=String(e||"").trim();if(!vo(r))throw new Error(`cowswap: ${t} must be an address`);return oe(r).toLowerCase()}function J(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 fr(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 hr(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 So({digest:e,owner:t,validTo:r}={}){let n=fr(e,"order digest").slice(2),o=j(t,"owner").slice(2).toLowerCase(),a=Number(r);if(!Number.isInteger(a)||a<0||a>4294967295)throw new Error("cowswap: validTo must fit uint32");return`0x${n}${o}${a.toString(16).padStart(8,"0")}`.toLowerCase()}function ot(e){let t=lr[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:oe(t)}}function Io(e={},t,r){let n=j(e.sellToken,"sellToken"),o=j(e.buyToken,"buyToken"),a=j(e.receiver||r,"receiver"),s=Number(e.validTo);if(!Number.isInteger(s)||s<=0)throw new Error("cowswap: quote.validTo required");let i=fr(e.appData||e.appDataHash||`0x${"0".repeat(64)}`,"appData");return{sellToken:n,buyToken:o,receiver:a,sellAmount:J(e.sellAmount,"sellAmount"),buyAmount:J(e.buyAmount,"buyAmount"),validTo:s,appData:i,feeAmount:J(e.feeAmount??"0","feeAmount"),kind:String(e.kind||"sell"),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance||"erc20"),buyTokenBalance:String(e.buyTokenBalance||"erc20")}}async function Co(e={}){try{let t=await ae({chainId:1,sellToken:rt[1],buyToken:pr[1],sellAmountBeforeFee:"1000000000000000",from:H},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 ae(e={},t={}){let r=Number(e.chainId??1),n=ze(e.from||e.owner),o=e.sellToken||rt[r],a=e.buyToken||pr[r],s=String(e.sellAmountBeforeFee||e.sellAmount||"0");if(!o||!a||s==="0")throw new Error("cowQuote requires sellToken, buyToken, sellAmountBeforeFee");if(/eeeeeeee|native|^eth$/i.test(o)&&(o=rt[r],!o))throw new Error("no WETH mapping for chain");let i={sellToken:o,buyToken:a,from:n,receiver:e.receiver||n,sellAmountBeforeFee:s,kind:e.kind||"sell",signingScheme:e.signingScheme||"eip1271"},c=await x(`${Se(r,t)}/quote`,{method:"POST",body:i,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),u=c?.quote?.buyAmount||c?.buyAmount;return u?C(c,{chainId:r,venue:"cowswap-order",amountOut:u,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):c}async function ko(e={},t={}){let r=Number(e.chainId??1),n=j(ze(e.from||e.owner||e.signer),"owner"),o=await ae({...e,chainId:r,from:n,signingScheme:e.signingScheme||"eip712"},t),a=Io(o?.quote||o,r,n),s=ot(r),i={domain:s,types:xe,primaryType:"Order",message:a},c=ur.hash(s,xe,a),u=dr[r];if(!u)throw new Error(`cowswap: vault relayer not registered for chain ${r}`);return I({provider:"cowswap",orderReady:!0,executionReady:!1,chainId:r,owner:n,signingScheme:"eip712",settlement:s.verifyingContract.toLowerCase(),vaultRelayer:oe(u).toLowerCase(),quote:o,quoteId:o?.id??e.quoteId??null,typedData:i,cowGuard:{mode:"cow-order",version:1,provider:"cowswap",chainId:r,owner:n,settlement:s.verifyingContract.toLowerCase(),vaultRelayer:oe(u).toLowerCase(),sellToken:a.sellToken,buyToken:a.buyToken,sellAmount:a.sellAmount,buyAmount:a.buyAmount,validTo:a.validTo,quoteId:o?.id??e.quoteId??null,typedDataHash:c,issuedAtMs:Date.now(),expiresAtMs:Math.min(a.validTo*1e3,Date.now()+2e4)},requiresApproval:{token:a.sellToken,spender:oe(u).toLowerCase(),amount:a.sellAmount}},{provider:"cowswap",kind:"cow-order"})}async function gr(e={},t={}){let r=Number(e.chainId??1),n=String(e.uid||e.orderUid||"").trim();if(!n)throw new Error("cowOrderStatus requires uid");return x(`${Se(r,t)}/orders/${encodeURIComponent(n)}/status`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function br(e={},t={}){let r=Number(e.chainId??1),n=String(e.uid||e.orderUid||"").trim();if(!n)throw new Error("cowOrder requires uid");return x(`${Se(r,t)}/orders/${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}function Oo(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 o=e.cowGuard?.typedDataHash||ur.hash(ot(r),xe,n),a=e.owner||e.from||e.signer||n.receiver;return So({digest:o,owner:a,validTo:n.validTo})}async function No(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 _o(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 To(e={}){let t=Number(e.chainId??1),r=j(e.owner||e.from||e.signer,"owner"),n=(e.orderUids||e.uids||[e.uid]).filter(Boolean).map((s,i)=>hr(s,`orderUids[${i}]`));if(!n.length)throw new Error("cowswap: orderUids required");let o=ot(t);return I({provider:"cowswap",chainId:t,owner:r,orderUids:n,signingScheme:"eip712",typedData:{domain:o,types:mr,primaryType:"OrderCancellations",message:{orderUids:n}},cancelReady:!0,executableArtifact:!0},{provider:"cowswap",kind:"cow-cancel"})}async function Bo(e={},t={}){throw new Error("cowswap.cowSignCancel refused: @oracle-agent/oracle is prepare-only. Cancel-sign with the user wallet.")}async function Ro(e={},t={}){throw new Error("cowswap.cowCancelOrders refused: @oracle-agent/oracle is prepare-only. Cancel from the user wallet or local operator.")}function Uo(e={}){return J(e.buyAmount??e.executedBuyAmount??"0","trade.buyAmount")}async function $o(e={},t={}){let r=Number(e.chainId??1),n=hr(e.uid||e.orderUid),o=t.order||await br({chainId:r,uid:n},t),a=t.status||o.status||await gr({chainId:r,uid:n},t).catch(()=>null),s=t.trades||await x(`${xo(r,"v2",t)}/trades?orderUid=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),i=Array.isArray(s)?s:[],c=e.expectedOwner?j(e.expectedOwner,"expectedOwner"):null;if(c&&j(o.owner||i[0]?.owner||c,"owner")!==c)return{ok:!1,provider:"cowswap",chainId:r,uid:n,reason:"owner mismatch",order:o,status:a,trades:i};let u=0n;for(let l of i.filter(m=>String(m.orderUid||"").toLowerCase()===n))u+=BigInt(Uo(l));u===0n&&o.executedBuyAmount!=null&&(u=BigInt(J(o.executedBuyAmount,"executedBuyAmount")));let p=e.minBuyAmount!=null?BigInt(J(e.minBuyAmount,"minBuyAmount")):0n,d=u>=p&&String(o.status||a?.status||"").toLowerCase()!=="expired";return{ok:d,provider:"cowswap",chainId:r,uid:n,status:o.status||a?.status||null,executedBuyAmount:u.toString(),minBuyAmount:e.minBuyAmount??null,trades:i,settlementTxs:[...new Set(i.map(l=>l.txHash).filter(Boolean))],order:o,orderStatus:a,reason:d?null:"insufficient fill or expired order"}}function Lo(){return Object.keys(nt).map(Number)}var nt,lr,dr,rt,pr,xe,mr,at=S(()=>{F();M();cr();he();U();nt={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"},lr=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),dr=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"}),rt={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"},pr={1:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",42161:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},xe=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"}]}),mr=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]})});function yr(e){return Do.get(Number(e))||null}function Ar(e,t=process.env){let r=yr(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}var Er,Do,vr=S(()=>{Er={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},Do=new Map(Object.values(Er).map(e=>[e.chainId,e]))});import{Interface as Fo,getAddress as Po}from"ethers";function Sr(e,t){try{return Po(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}function Mo(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=Ar(e,r);return n||qo[Number(e)]||null}function Ho(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!Vo.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 O(e,t,r=[],n={}){let o=String(t||"");Ho(o);let a=Mo(e,n);if(!a)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let i=await x(a,{method:"POST",body:{jsonrpc:"2.0",id:1,method:t,params:r},fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs??12e3});if(i?.error){let c=new Error(i.error.message||JSON.stringify(i.error));throw c.code=i.error.code,c}return i.result}async function Ir(e,t={}){let r=await O(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function Cr(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await O(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function kr(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=Sr(e.token||e.tokenAddress,"token"),o=Sr(e.account||e.owner||e.address,"account"),a=xr.encodeFunctionData("balanceOf",[o]),s=await O(r,"eth_call",[{to:n,data:a},e.blockTag||"latest"],t),i=xr.decodeFunctionResult("balanceOf",s),c=BigInt(i[0]);return{chainId:r,token:n,account:o,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:e.blockTag||"latest"}}var xr,qo,Vo,Z=S(()=>{F();vr();xr=new Fo(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);qo={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"};Vo=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/});function Wo(e,t,r){let n=$(t),o=$(r),a=$(e?.baseToken?.address),s=$(e?.quoteToken?.address);return a===n&&s===o||a===o&&s===n}function Go(e){let t=Number(e?.liquidity?.usd);return Number.isFinite(t)&&t>=0?t:null}function Xo(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||jo).replace(/\/$/,"")}async function it(e,t={}){if(!e)throw new Error("tokenAddress required");return x(`${Xo(t)}/latest/dex/tokens/${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}async function Ie({chainId:e,tokenA:t,tokenB:r,dexIds:n=[]}={},o={}){if(e==null||!t||!r)throw new Error("chainId, tokenA, and tokenB required");let a=$(Ko[Number(e)]||e),s=new Set(zo(n).filter(Boolean).map($)),i=[...new Set([t,r].map(l=>String(l)).filter(Boolean))],c=await Promise.allSettled(i.map(l=>it(l,{...o,baseUrl:o.dexscreenerBaseUrl,timeoutMs:o.dexscreenerTimeoutMs??Math.min(Number(o.timeoutMs??4e3),4e3)}))),u=new Set,p=[];for(let l of c)if(l.status==="fulfilled")for(let m of l.value?.pairs||l.value?.data?.pairs||[]){let h=`${$(m?.chainId)}:${$(m?.dexId)}:${$(m?.pairAddress)}`;u.has(h)||(u.add(h),p.push(m))}return p.filter(l=>$(l?.chainId)===a).filter(l=>Wo(l,t,r)).filter(l=>!s.size||s.has($(l?.dexId))).map(l=>({pairAddress:l.pairAddress??null,dexId:l.dexId??null,chainId:l.chainId??null,liquidityUsd:Go(l),pairCreatedAt:l.pairCreatedAt??null})).filter(l=>l.liquidityUsd!=null).sort((l,m)=>m.liquidityUsd-l.liquidityUsd)[0]??null}var jo,Ko,$,zo,Ce=S(()=>{F();jo="https://api.dexscreener.com",Ko=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"}),$=e=>String(e??"").toLowerCase(),zo=e=>Array.isArray(e)?e:e==null?[]:[e]});var $r={};W($r,{PANCAKE_FEE_TIERS:()=>ke,UNI_V3_CHAINS:()=>T,UNI_V3_FEE_TIERS:()=>_r,UNI_V3_VENUES:()=>Rr,uniV3Chains:()=>ra,uniV3EthUsdc:()=>Ur,uniV3Health:()=>ta,uniV3PrepareExactIn:()=>ea,uniV3QuoteExactIn:()=>se,uniV3QuoteExactInPath:()=>Zo});import{Interface as Nr,getAddress as ie,isAddress as Yo}from"ethers";function ct(e,t){let r=Number(e),n=T[r];if(!n)throw new Error(`uniswap-v3: unsupported chainId ${e} (supported: ${Object.keys(T).join(", ")})`);let o=Rr[r]||{};if(!t){if(!n.quoter||!n.router){let c=Object.keys(o).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 a=String(t).toLowerCase();if(a===n.name&&n.quoter&&n.router)return{chainId:r,venue:n.name,...n};let s=o,i=s[a];if(!i){let c=[...n.quoter&&n.router?[n.name]:[],...Object.keys(s)].join(", ");throw new Error(`uniswap-v3: unknown venue "${t}" on chain ${r} (known: ${c})`)}return{chainId:r,venue:a,...n,quoter:i.quoter,router:i.router,feeTiers:i.feeTiers||null}}function st(e,t){let r=T[Number(t)];if(!e||e===Tr||e===Br||/^eth$/i.test(String(e)))return ie(r.weth);let n=String(e);if(/^weth$/i.test(n))return ie(r.weth);if(/^usdc$/i.test(n))return ie(r.usdc);if(!Yo(n))throw new Error(`invalid token address: ${e}`);return ie(n)}function Qo(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 Jo(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 se(e={},t={}){let{chainId:r,quoter:n,router:o,feeTiers:a}=ct(e.chainId??8453,e.venue),s=st(e.tokenIn||"WETH",r),i=st(e.tokenOut||T[r].usdc,r),c=BigInt(e.amountIn??0);if(c<=0n)throw new Error("amountIn required (raw base units)");let u=a&&a.length?a:_r,p=e.fee!=null?[Number(e.fee)]:e.tryFees===!1?[u[Math.min(2,u.length-1)]]:[...u],d=[],l=null;for(let g of p){let f=Oe.encodeFunctionData("quoteExactInputSingle",[{tokenIn:s,tokenOut:i,amountIn:c,fee:g,sqrtPriceLimitX96:0n}]);try{let b=await O(r,"eth_call",[{to:n,data:f},"latest"],t);if(!b||b==="0x"){d.push({fee:g,ok:!1,error:"empty result"});continue}let w=Oe.decodeFunctionResult("quoteExactInputSingle",b),A={fee:g,ok:!0,amountOut:w[0].toString(),sqrtPriceX96After:w[1].toString(),initializedTicksCrossed:Number(w[2]),gasEstimate:w[3].toString()};d.push(A),(!l||BigInt(A.amountOut)>BigInt(l.amountOut))&&(l=A)}catch(b){d.push({fee:g,ok:!1,error:String(b.message||b).slice(0,160)})}}if(!l){let g=d.map(f=>`${f.fee}:${f.error||"fail"}`).join("; ");throw new Error(`uniswap-v3 quote failed chain=${r}: ${g}`)}let m=e.liquidityUsd==null?await Ie({chainId:r,tokenA:s,tokenB:i,dexIds:Qo(e.venue)},t).catch(()=>null):null,h=e.liquidityUsd??m?.liquidityUsd??null;return C({venue:"uniswap-v3",chainId:r,chain:T[r].name,quoter:n,tokenIn:s,tokenOut:i,amountIn:c.toString(),fee:l.fee,amountOut:l.amountOut,gasEstimate:l.gasEstimate,liquidityUsd:h,liquiditySource:m,sqrtPriceX96After:l.sqrtPriceX96After,initializedTicksCrossed:l.initializedTicksCrossed,triedFees:d,best:!0},{chainId:r,venue:o,amountOut:l.amountOut,liquidityUsd:h,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Zo(e={},t={}){let{chainId:r,quoter:n,router:o}=ct(e.chainId??8453),a=(e.tokens||[]).map(l=>st(l,r)),s=(e.fees||[]).map(Number);if(a.length<2)throw new Error("tokens[] need at least 2 addresses");let i=BigInt(e.amountIn??0);if(i<=0n)throw new Error("amountIn required");let c=Jo(a,s),u=Oe.encodeFunctionData("quoteExactInput",[c,i]),p=await O(r,"eth_call",[{to:n,data:u},"latest"],t),d=Oe.decodeFunctionResult("quoteExactInput",p);return C({venue:"uniswap-v3",chainId:r,chain:T[r].name,quoter:n,tokens:a,fees:s,path:c,amountIn:i.toString(),amountOut:d[0].toString(),gasEstimate:d[3].toString()},{chainId:r,venue:o,amountOut:d[0].toString(),liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Ur(e={},t={}){let r=Number(e.chainId??8453),n=e.amountIn??"1000000000000000",o=await se({chainId:r,tokenIn:T[r].weth,tokenOut:T[r].usdc,amountIn:n,fee:e.fee},t),a=Number(o.amountOut)/1e6;return{...o,amountOutUsdc:a,pair:"WETH/USDC"}}async function ea(e={},t={}){let r=Number(e.chainId??8453),n=ct(r,e.venue),o=ie(e.recipient),a=String(e.tokenIn||"WETH"),s=!e.tokenIn||a===Tr||a===Br||/^eth$/i.test(a),i=await se(e,t),c=Or.encodeFunctionData("exactInputSingle",[{tokenIn:i.tokenIn,tokenOut:i.tokenOut,fee:i.fee,recipient:o,amountIn:BigInt(i.amountIn),amountOutMinimum:BigInt(i.amountOutMinimum),sqrtPriceLimitX96:0n}]),u=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),d=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+u,l=Or.encodeFunctionData("multicall",[d,[c]]);return I({provider:"uniswap-v3",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,deadline:d,quote:i,autoSlippage:i.autoSlippage,requiresApproval:s?null:{token:i.tokenIn,spender:n.router,amount:i.amountIn},transaction:{chainId:r,from:o,to:n.router,data:l,value:s?i.amountIn:"0",slippageGuard:R(i.autoSlippage,{chainId:r,venue:n.router,data:l})}},{provider:"uniswap-v3",kind:"univ3-swap-tx"})}async function ta(e={}){let t=Number(e.chainId??8453);try{let r=await Ur({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 ra(){return Object.entries(T).map(([e,t])=>({chainId:Number(e),name:t.name,quoter:t.quoter,weth:t.weth,usdc:t.usdc}))}var T,_r,Oe,Or,Tr,Br,ke,Rr,ut=S(()=>{Z();Ce();M();U();T={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"}},_r=[100,500,3e3,1e4],Oe=new Nr(["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)"]),Or=new Nr(["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)"]),Tr="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",Br="0x0000000000000000000000000000000000000000",ke=[100,500,2500,1e4],Rr={56:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ke}},8453:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ke}},42161:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ke}},999:{hyperswap:{name:"hyperswap",quoter:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",router:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D"}}}});var Vr={};W(Vr,{UNI_V4_CHAINS:()=>V,UNI_V4_FEE_TIERS:()=>Pr,computeV4PoolId:()=>Mr,uniV4Chains:()=>pa,uniV4Health:()=>ma,uniV4PrepareExactIn:()=>da,uniV4QuoteExactIn:()=>_e});import{AbiCoder as na,Interface as Fr,getAddress as L,isAddress as Ne,keccak256 as oa}from"ethers";function lt(e){let t=Number(e),r=V[t];if(!r)throw new Error(`uniswap-v4: unsupported chainId ${e} (supported: ${Object.keys(V).join(", ")})`);return{chainId:t,...r}}function Dr(e,t){let r=V[Number(t)];if(!e||e===qr||e===G||/^eth$/i.test(String(e)))return L(r.weth);let n=String(e);if(/^weth$/i.test(n))return L(r.weth);if(/^usdc$/i.test(n)||/^usdg$/i.test(n))return L(r.usdc);if(!Ne(n))throw new Error(`invalid token address: ${e}`);return L(n)}function Mr({currency0:e,currency1:t,fee:r,tickSpacing:n,hooks:o=G}){let a=L(e),s=L(t);if(a.toLowerCase()===s.toLowerCase())throw new Error("poolKey currencies must differ");let[i,c]=a.toLowerCase()<s.toLowerCase()?[a,s]:[s,a],u=o&&Ne(o)?L(o):G;return oa(ce.encode(["address","address","uint24","int24","address"],[i,c,Number(r),Number(n),u]))}function ua({tokenIn:e,tokenOut:t,fee:r,tickSpacing:n,hooks:o=G}){let a=L(e),s=L(t),[i,c]=a.toLowerCase()<s.toLowerCase()?[a,s]:[s,a],u=a.toLowerCase()===i.toLowerCase();return{poolKey:{currency0:i,currency1:c,fee:Number(r),tickSpacing:Number(n),hooks:o&&Ne(o)?L(o):G},zeroForOne:u}}async function _e(e={},t={}){let{chainId:r,quoter:n,poolManager:o,universalRouter:a}=lt(e.chainId??8453),s=Dr(e.tokenIn||"WETH",r),i=Dr(e.tokenOut||V[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 u=e.fee!=null&&e.tickSpacing!=null?[{fee:Number(e.fee),tickSpacing:Number(e.tickSpacing)}]:e.tryTiers===!1?[{fee:500,tickSpacing:10}]:[...Pr],p=e.hooks||G,d=[],l=null;for(let g of u){let{poolKey:f,zeroForOne:b}=ua({tokenIn:s,tokenOut:i,fee:g.fee,tickSpacing:g.tickSpacing,hooks:p}),w=Lr.encodeFunctionData("quoteExactInputSingle",[{poolKey:f,zeroForOne:b,exactAmount:c,hookData:"0x"}]);try{let A=await O(r,"eth_call",[{to:n,data:w},"latest"],t);if(!A||A==="0x"){d.push({...g,ok:!1,error:"empty result"});continue}let N=Lr.decodeFunctionResult("quoteExactInputSingle",A),k={fee:g.fee,tickSpacing:g.tickSpacing,ok:!0,amountOut:N[0].toString(),gasEstimate:N[1].toString(),poolKey:f,zeroForOne:b,poolId:Mr({...f})};d.push(k),(!l||BigInt(k.amountOut)>BigInt(l.amountOut))&&(l=k)}catch(A){d.push({...g,ok:!1,error:String(A.message||A).slice(0,160)})}}if(!l){let g=d.map(f=>`${f.fee}/${f.tickSpacing}:${f.error||"fail"}`).join("; ");throw new Error(`uniswap-v4 quote failed chain=${r}: ${g}`)}let m=e.liquidityUsd==null?await Ie({chainId:r,tokenA:s,tokenB:i,dexIds:la},t).catch(()=>null):null,h=e.liquidityUsd??m?.liquidityUsd??null;return C({venue:"uniswap-v4",chainId:r,chain:V[r].name,poolManager:o,quoter:n,universalRouter:a||null,tokenIn:s,tokenOut:i,amountIn:c.toString(),fee:l.fee,tickSpacing:l.tickSpacing,hooks:l.poolKey.hooks,poolId:l.poolId,zeroForOne:l.zeroForOne,amountOut:l.amountOut,gasEstimate:l.gasEstimate,liquidityUsd:h,liquiditySource:m,triedTiers:d,best:!0,executionReady:!1,prepareReady:typeof e.recipient=="string"&&Ne(e.recipient)&&e.slippageBps!=null},{chainId:r,venue:a||n,amountOut:l.amountOut,liquidityUsd:h,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function da(e={},t={}){let r=Number(e.chainId??8453),n=lt(r);if(!e.recipient)throw new Error("uniswap-v4 prepare requires recipient");let o=L(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>=1e4)throw new Error("slippageBps must be an integer from 0 through 9999");let s=String(e.tokenIn||"");if(!s||s===qr||s===G||/^eth$/i.test(s))throw new Error("uniswap-v4 prepare currently requires an ERC-20 tokenIn; native input is not inferred");let i=await _e(e,t);if(!n.universalRouter)throw new Error(`uniswap-v4: no Universal Router on chain ${r}`);let c=BigInt(i.amountOut)*BigInt(1e4-a)/10000n,u={currency0:i.zeroForOne?i.tokenIn:i.tokenOut,currency1:i.zeroForOne?i.tokenOut:i.tokenIn,fee:i.fee,tickSpacing:i.tickSpacing,hooks:i.hooks},d=ce.encode(["tuple(tuple(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 amountIn,uint128 amountOutMinimum,uint256 minHopPriceX36,bytes hookData)"],[[u,i.zeroForOne,BigInt(i.amountIn),c,0n,"0x"]]),l=ce.encode(["address","uint256"],[i.tokenIn,BigInt(i.amountIn)]),m=ce.encode(["address","uint256"],[i.tokenOut,c]),h=ce.encode(["bytes","bytes[]"],[sa,[d,l,m]]),g=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),b=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+g,w=aa.encodeFunctionData("execute",[ia,[h],b]);return I({provider:"uniswap-v4",prepareReady:!0,calldataReady:!0,executionReady:!1,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,deadline:b,quote:{...i,amountOutMinimum:c.toString(),slippageBps:a},requiresApproval:{token:i.tokenIn,spender:ca,amount:i.amountIn,note:"Universal Router V4 settlement uses Permit2; Permit2 authorization for the Universal Router is also required"},transaction:{chainId:r,from:o,to:n.universalRouter,data:w,value:"0"}},{provider:"uniswap-v4",kind:"univ4-swap-tx"})}async function pa(){return Object.entries(V).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 ma(e={}){let t=lt(e.chainId??8453),r=await O(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 ce,G,V,Pr,Lr,aa,ia,sa,ca,qr,la,dt=S(()=>{Z();Ce();M();U();ce=na.defaultAbiCoder(),G="0x0000000000000000000000000000000000000000",V={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"}},Pr=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200},{fee:25e3,tickSpacing:8}],Lr=new Fr(["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)"]),aa=new Fr(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),ia="0x10",sa="0x060c0f",ca="0x000000000022D473030F116dDEE9F6B43aC78BA3",qr="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";la=["uniswap-v4","uniswapv4"]});var Be={};W(Be,{ACROSS_API:()=>jr,HOP_API:()=>Kr,RELAY_API:()=>zr,acrossHealth:()=>Ea,acrossSuggestedFees:()=>Wr,hopHealth:()=>ya,hopQuote:()=>Gr,relayHealth:()=>Aa,relayPrepare:()=>va,relayQuote:()=>pt});async function Ea(e={}){try{return{ok:!0,estimatedFillTimeSec:(await Wr({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 Wr(e={},t={}){let{token:r,destinationToken:n=r,originChainId:o,destinationChainId:a,amount:s}=e;if(!r||o==null||a==null||!s)throw new Error("acrossSuggestedFees requires token, originChainId, destinationChainId, amount");let i=new URLSearchParams({token:r,destinationToken:n,originChainId:String(o),destinationChainId:String(a),amount:String(s)}),c=(t.baseUrl||process.env.ACROSS_API_URL||jr).replace(/\/$/,"");return x(`${c}/suggested-fees?${i}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function ya(e={}){try{let t=await Gr({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 Gr(e={},t={}){let{amount:r,token:n="ETH",fromChain:o="ethereum",toChain:a="arbitrum"}=e;if(!r)throw new Error("hopQuote requires amount");let s=e.slippage==null?void 0:Math.round(Number(e.slippage)*100),i=q({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:o!==a,requestedCapBps:e.maxSlippageBps??e.slippageBps??s});if(!i.executable)throw new Error(`hop: route requires ${i.requiredBps} bps above cap ${i.capBps}`);let c=new URLSearchParams({amount:String(r),token:n,fromChain:o,toChain:a,slippage:String(i.selectedBps/100)}),u=(t.baseUrl||process.env.HOP_API_URL||Kr).replace(/\/$/,""),p=await x(`${u}/quote?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),d=p?.estimatedRecieved||p?.estimatedReceived;return d?C(p,{chainId:Number(e.originChainId||e.chainId||wa[o]||0),venue:p?.tx?.to||"hop",amountOut:d,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:o!==a,requestedCapBps:e.maxSlippageBps??e.slippageBps??s}):{...p,autoSlippagePolicy:i}}async function Aa(e={}){try{let t=await pt({user:H,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 pt(e={},t={}){let{user:r=H,originChainId:n,destinationChainId:o,originCurrency:a="0x0000000000000000000000000000000000000000",destinationCurrency:s="0x0000000000000000000000000000000000000000",amount:i,tradeType:c="EXACT_INPUT"}=e;if(n==null||o==null||!i)throw new Error("relayQuote requires originChainId, destinationChainId, amount");let u=q({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(o),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!u.executable)throw new Error(`relay: route requires ${u.requiredBps} bps above cap ${u.capBps}`);let p=(t.baseUrl||process.env.RELAY_API_URL||zr).replace(/\/$/,""),d=await x(`${p}/quote`,{method:"POST",body:{user:r,originChainId:Number(n),destinationChainId:Number(o),originCurrency:a,destinationCurrency:s,amount:String(i),tradeType:c,slippageTolerance:String(u.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),l=d?.details?.currencyOut?.amount;return!l||!/^\d+$/.test(String(l))?{...d,autoSlippagePolicy:u}:C(d,{chainId:Number(n),venue:d?.steps?.[0]?.items?.[0]?.data?.to||"relay",amountOut:l,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(o),requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function va(e={},t={}){let r=await pt(e,t),n=Number(e.originChainId),o=(r.steps||[]).flatMap(i=>(i.items||[]).filter(c=>c?.data?.to&&c?.data?.data).map(c=>({stepId:i.id,...c.data})));if(!o.length)throw new Error("relay: quote returned no executable transaction items");let a=String(r?.autoSlippage?.venue||"").toLowerCase();if(o.some(i=>String(i.to).toLowerCase()!==a))throw new Error("relay: route includes a separate approval/transaction that is not yet safely bound");let s=o.map(i=>({chainId:n,from:i.from||e.user,to:i.to,data:i.data,value:i.value??"0x0",...i.gasLimit!=null||i.gas!=null?{gasLimit:i.gasLimit??i.gas}:{},slippageGuard:R(r.autoSlippage,{chainId:n,venue:i.to,data:i.data})}));return I({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 jr,Kr,zr,wa,Re=S(()=>{F();M();he();U();jr="https://across.to/api",Kr="https://api.hop.exchange/v1",zr="https://api.relay.link",wa={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453}});var de=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),y=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),E=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),hn=/^0x[0-9a-fA-F]{40}$/;function gn(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 o of e.rpcEnv)(typeof o!="string"||!/^[A-Z][A-Z0-9_]*$/.test(o))&&t.push(`rpcEnv entry "${o}" should be an UPPER_SNAKE env var name`);if(e.nativeCurrency){let o=e.nativeCurrency;(typeof o.symbol!="string"||!o.symbol)&&t.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(o.decimals)||t.push("nativeCurrency.decimals must be an integer")}for(let[o,a]of(e.venues||[]).entries()){let s=`venues[${o}]`;if(!a||typeof a!="object"){t.push(`${s} must be an object`);continue}hn.test(a.address||"")||t.push(`${s}.address is not a valid 20-byte address`),/^0x0{40}$/.test(a.address||"")&&t.push(`${s}.address is the zero address -- placeholder left in place?`),a.kind||t.push(`${s}.kind is required (router|quoter|factory|...)`),a.verified?(a.verified.method||t.push(`${s}.verified.method is required`),a.verified.source||t.push(`${s}.verified.source is required`),a.verified.date||r.push(`${s}.verified.date missing -- add one so staleness is visible`)):t.push(`${s} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let n=e.capabilities||{};for(let o of Object.keys(n))de.includes(o)?typeof n[o]!="function"&&t.push(`capability "${o}" must be a function`):t.push(`unknown capability "${o}"`);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 bn(e){let{ok:t,errors:r,warnings:n}=gn(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
4
4
  - ${r.join(`
5
- - `)}`);let o=e.capabilities||{},a=ie.filter(i=>typeof o[i]=="function"),s={key:e.key,chainId:e.chainId,name:e.name,rpcEnv:[...e.rpcEnv],nativeCurrency:e.nativeCurrency?{...e.nativeCurrency}:null,explorer:e.explorer||null,venues:(e.venues||[]).map(i=>({...i})),warnings:n,capabilities(){return{chainId:e.chainId,key:e.key,supported:[...a],unsupported:ie.filter(i=>!a.includes(i))}},supports(i){return a.includes(i)}};for(let i of ie)a.includes(i)?s[i]=async(...c)=>o[i](...c,{scanner:s}):s[i]=async()=>{throw new Error(`${e.key} (chain ${e.chainId}) does not implement "${i}". Supported: ${a.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)}var Be=new Map;function gt(e){let t=un(e);return Be.set(t.chainId,t),t}function se(e){return Be.get(Number(e))||null}function $e(){return[...Be.values()]}var B=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"}),wt={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"},Q=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}};function bt(e){let{source:t,amountOut:r,minOut:n=null,gasUsd:o=null,feeUsd:a=null,estimatedGas:s=null,error:i=null,executionReady:c=!1,meta:u={}}=e||{};if(i||r==null)return{source:t,quality:B.FAILED,amountOut:null,error:i||"no amountOut returned"};let p=Q(r);return p==null||p<=0n?{source:t,quality:B.FAILED,amountOut:null,error:"non-positive amountOut"}:{source:t,quality:o==null?B.NO_GAS:B.FULL,amountOut:p.toString(),minOut:Q(n)?.toString()??null,gasUsd:o,feeUsd:a,estimatedGas:s==null?null:String(s),executionReady:c,meta:u}}async function Et(e,t,{divisor:r=1000n}={}){let n=Q(t);if(n==null||n<=0n)return null;let o=n/r>0n?n/r:1n;if(o>=n)return null;let a,s;try{[a,s]=await Promise.all([e(o),e(n)])}catch{return null}let i=Q(a),c=Q(s);if(i==null||c==null||i<=0n)return null;let u=Number(i)/Number(o),p=Number(c)/Number(n);return!Number.isFinite(u)||!Number.isFinite(p)||u<=0?null:{impactPct:(1-p/u)*100,probeAmountIn:o.toString(),probeAmountOut:i.toString(),fullAmountOut:c.toString()}}function yt(e,t,{maxImpactPct:r=25}={}){let n=[],o=[],a=(e.routes??[]).filter(i=>{let c=t?.[i.source];return c?c.impactPct>r?(n.push({source:i.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:(o.push(i.source),!0)}),s=[...e.warnings??[]];return n.length&&s.push(`dropped ${n.length} route(s) on price impact: `+n.map(i=>`${i.source} (${i.impactPct}%)`).join(", ")),o.length&&s.push(`price impact NOT measured for: ${o.join(", ")}. These are unproven against thin liquidity, not proven safe.`),{...e,routes:a,best:a[0]??null,impactRejected:n,impactUnmeasured:o,warnings:s}}function Ue(e,{destPriceUsd:t=null,destDecimals:r=null}={}){let n=e.filter(d=>d.quality!==B.FAILED),o=e.filter(d=>d.quality===B.FAILED),a=t!=null&&t>0&&r!=null&&r>=0,s=n.map(d=>{let l=BigInt(d.amountOut),m=0n,f=!1;if(a){let h=(d.gasUsd??0)+(d.feeUsd??0);if(h>0){let b=h/t*10**r;Number.isFinite(b)&&b>=0&&(m=BigInt(Math.floor(b)),f=!0)}else d.gasUsd===0&&(f=!0)}let g=l>m?l-m:0n;return{...d,grossOut:l.toString(),netOut:g.toString(),costInDest:m.toString(),costAccounted:f}});s.sort((d,l)=>BigInt(l.netOut)>BigInt(d.netOut)?1:-1);let i=s.filter(d=>!d.costAccounted).map(d=>d.source),c=[];a?i.length&&c.push(`gas not reported by: ${i.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):c.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let u=null,p=null;if(s.length>=2&&s[0].costAccounted&&s[1].costAccounted){let d=BigInt(s[0].netOut),l=BigInt(s[1].netOut);l>0n&&(u=Number((d-l)*10000n/l),p=`${s[0].source} vs ${s[1].source}`)}return{best:s[0]??null,routes:s,failed:o,improvementBps:u,spreadBasis:p,rankedOn:a?"net-of-cost":"gross",warnings:c}}async function ce(e,{timeoutMs:t=12e3}={}){let r=(o,a)=>Promise.race([o,new Promise((s,i)=>setTimeout(()=>i(new Error(`${a}: timeout`)),t))]);return(await Promise.allSettled(e.map(o=>r(Promise.resolve().then(o.run),o.source)))).map((o,a)=>{let s=e[a].source;return o.status==="rejected"?bt({source:s,error:String(o.reason?.message||o.reason)}):bt({source:s,...o.value})})}pe();ze();Ge();$();L();We();T();var lo="https://api.1inch.dev/swap/v6.0";function Jt(e={}){return fe({provider:"oneinch",defaultUrl:lo,hosts:["api.1inch.dev"],url:e.baseUrl||process.env.ONEINCH_API_URL})}function po(e={}){return Jt(e).baseUrl}function Zt(e={}){return e.apiKey||process.env.ONEINCH_API_KEY||process.env.ONE_INCH_API_KEY||""}function mo(e={}){let t=Zt(e);return he({accept:"application/json"},{Authorization:t?`Bearer ${t}`:""},Jt(e).trusted)}async function er(e={},t={}){if(!Zt(t))throw new Error("ONEINCH_API_KEY required for 1inch");let r=Number(e.chainId??1),{src:n,dst:o,amount:a}=e;if(!n||!o||!a)throw new Error("oneinchQuote requires src, dst, amount");let s=new URLSearchParams({src:n,dst:o,amount:String(a)}),i=await A(`${po(t)}/${r}/quote?${s}`,{headers:mo(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3});return i?.dstAmount?I(i,{chainId:r,venue:"1inch-quote",amountOut:i.dstAmount,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):i}Je();tt();nt();$();var Jo="https://coins.llama.fi";function Zo(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Jo).replace(/\/$/,"")}async function Se(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return A(`${Zo(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}var q=e=>{let t=Number(e);return Number.isFinite(t)?t:null};function ke(e){if(!Array.isArray(e))return null;let t=0,r=!1;for(let n of e){let o=q(n?.amountUSD);o!=null&&(t+=o,r=!0)}return r?t:null}async function Mr(e,t={}){let r=wt[Number(e)];if(!r)return null;try{let n=await Se([r],t);return q(n?.coins?.[r]?.price)}catch{return null}}function at({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o,slippageBps:a,decimalsIn:s,decimalsOut:i,nativePriceUsd:c=null,destDecimalsPromise:u=null,opts:p={}}){let d=[];return d.push({source:"lifi",run:async()=>{let l=await J({fromChain:e,toChain:e,fromToken:t,toToken:r,fromAmount:n},p),m=l?.estimate??l?.[0]?.estimate;return{amountOut:m?.toAmount,minOut:m?.toAmountMin,gasUsd:ke(m?.gasCosts),feeUsd:ke(m?.feeCosts),meta:{tool:l?.tool??l?.toolDetails?.name}}}}),s!=null&&d.push({source:"paraswap",run:async()=>{let l=i??(await Promise.resolve(u))?.decimals;if(l==null)throw new Error("paraswap needs destination decimals; none supplied or resolvable");let f=(await me({chainId:e,srcToken:t,destToken:r,amount:n,srcDecimals:s,destDecimals:l},p))?.priceRoute;return{amountOut:f?.destAmount,gasUsd:q(f?.gasCostUSD),meta:{bestRoute:f?.bestRoute?.[0]?.swaps?.[0]?.swapExchanges?.[0]?.exchange}}}}),process.env.ZEROX_API_KEY&&d.push({source:"0x",run:async()=>{let l=await be({chainId:e,sellToken:t,buyToken:r,sellAmount:n,taker:o},p),m=null,f=l?.totalNetworkFee,g=await Promise.resolve(c);return f!=null&&g&&(m=Number(f)/1e18*g),{amountOut:l?.buyAmount,minOut:l?.minBuyAmount,gasUsd:m,meta:{source:l?.route?.fills?.[0]?.source}}}}),process.env.ONEINCH_API_KEY&&d.push({source:"1inch",run:async()=>{let l=await er({chainId:e,src:t,dst:r,amount:n},p),m=null;return l?.gas!=null&&c&&(m=null),{amountOut:l?.dstAmount,gasUsd:m,meta:{gasUnits:l?.gas}}}}),d.push({source:"cow",run:async()=>{let l=await ee({chainId:e,sellToken:t,buyToken:r,sellAmountBeforeFee:String(n),from:o},p),m=l?.quote??l,f=m?.feeAmount;return{amountOut:m?.buyAmount,gasUsd:0,meta:{intent:!0,feeAmountInSellToken:f,settlement:"solver-executed"}}}}),O[Number(e)]&&d.push({source:"uniswap-v3",run:async()=>{let l=await re({chainId:e,tokenIn:t,tokenOut:r,amountIn:n},p);return{amountOut:l?.amountOut,minOut:l?.minOut??l?.amountOutMinimum??null,gasUsd:null,meta:{onchain:!0,fee:l?.fee,gasUnits:l?.gasEstimate,quoter:l?.quoter}}}}),D[Number(e)]&&d.push({source:"uniswap-v4",run:async()=>{let l=await xe({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:o,slippageBps:a},p);return{amountOut:l?.amountOut,minOut:l?.minOut??l?.amountOutMinimum??null,gasUsd:null,meta:{onchain:!0,venue:"uniswap-v4",fee:l?.fee,tickSpacing:l?.tickSpacing,poolId:l?.poolId,hooks:l?.hooks,gasUnits:l?.gasEstimate,quoter:l?.quoter,poolManager:l?.poolManager,prepareReady:l?.prepareReady===!0,executionReady:!1}}}}),d}function Vr({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:o,taker:a,opts:s={}}){let i=[];return i.push({source:"lifi",run:async()=>{let c=await J({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:o},s),u=c?.estimate??c?.[0]?.estimate;return{amountOut:u?.toAmount,minOut:u?.toAmountMin,gasUsd:ke(u?.gasCosts),feeUsd:ke(u?.feeCosts),meta:{tool:c?.tool??c?.toolDetails?.name,durationSeconds:q(u?.executionDuration)}}}}),i.push({source:"relay",run:async()=>{let{relayQuote:c}=await Promise.resolve().then(()=>(Ce(),Ie)),p=(await c({user:a,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(o)},s))?.details;return{amountOut:p?.currencyOut?.amount,minOut:p?.currencyOut?.minimumAmount,gasUsd:q(p?.totalImpact?.usd)!=null?Math.abs(q(p.totalImpact.usd)):null,meta:{durationSeconds:q(p?.timeEstimate),rate:p?.rate}}}}),i.push({source:"across",run:async()=>{let{acrossSuggestedFees:c}=await Promise.resolve().then(()=>(Ce(),Ie)),u=await c({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(o)},s),p=u?.totalRelayFee?.total,d=null;if(p!=null)try{let l=BigInt(String(o))-BigInt(String(p));l>0n&&(d=l.toString())}catch{}return{amountOut:d,gasUsd:null,meta:{derivedFromFees:!0,durationSeconds:q(u?.estimatedFillTimeSec),limits:u?.limits?{min:u.limits.minDeposit,max:u.limits.maxDeposit}:void 0}}}}),i}var aa={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"};async function Hr(e,t,r){let n=aa[Number(e)];if(!n)return{priceUsd:null,decimals:null};let o=`${n}:${t}`;try{let s=(await Se([o],r))?.coins?.[o],i=Number(s?.price),c=Number(s?.decimals);return{priceUsd:Number.isFinite(i)?i:null,decimals:Number.isFinite(c)?c:null}}catch{return{priceUsd:null,decimals:null}}}async function Oe(e,t={}){let{chainId:r,tokenIn:n,tokenOut:o,amountIn:a}=e;if(r==null||!n||!o||a==null)throw new Error("bestSwapRoute requires chainId, tokenIn, tokenOut, amountIn");let s=Mr(r,t),i=Hr(r,o,t),c=at({...e,nativePriceUsd:s,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:t}),[u,p]=await Promise.all([ce(c,{timeoutMs:t.timeoutMs??12e3}),i]);s.catch(()=>{});let d=Ue(u,{destPriceUsd:p.priceUsd,destDecimals:e.decimalsOut??p.decimals}),l=t.maxImpactPct===void 0?25:t.maxImpactPct;if(l!=null&&d.best){let m=d.best.source,g=await Et(async h=>{let b=at({...e,amountIn:h.toString(),nativePriceUsd:s,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:t}).filter(C=>C.source===m);return b.length?(await ce(b,{timeoutMs:t.timeoutMs??12e3}))?.[0]?.amountOut??null:null},a);if(g){let h=yt(d,{[m]:g},{maxImpactPct:l});return{kind:"swap",chainId:r,tokenIn:n,tokenOut:o,amountIn:String(a),...h,sourcesTried:c.length,sourcesAnswered:u.filter(b=>b.quality!==B.FAILED).length,note:it(h,c.length),priceImpact:{[m]:Number(g.impactPct.toFixed(2))}}}}return{kind:"swap",chainId:r,tokenIn:n,tokenOut:o,amountIn:String(a),...d,sourcesTried:c.length,sourcesAnswered:u.filter(m=>m.quality!==B.FAILED).length,note:it(d,c.length)}}async function Ne(e,t={}){let{fromChainId:r,toChainId:n,tokenIn:o,tokenOut:a,amountIn:s}=e;if(r==null||n==null||!o||!a||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 i=Hr(n,a,t),c=Vr({...e,opts:t}),[u,p]=await Promise.all([ce(c,{timeoutMs:t.timeoutMs??15e3}),i]),d=Ue(u,{destPriceUsd:p.priceUsd,destDecimals:e.decimalsOut??p.decimals}),l=d.routes.map(m=>({source:m.source,seconds:m.meta?.durationSeconds??null})).filter(m=>m.seconds!=null);return{kind:"bridge",fromChainId:r,toChainId:n,tokenIn:o,tokenOut:a,amountIn:String(s),...d,durations:l,sourcesTried:c.length,sourcesAnswered:u.filter(m=>m.quality!==B.FAILED).length,note:it(d,c.length)}}function it(e,t){if(!e.best)return"no source returned a usable route";let r=e.routes.length;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.`;if(e.improvementBps!=null){let n=e.improvementBps,o=n/100;if(n<.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.`;let a=o>=.01?`${o.toFixed(2)}%`:`${n.toFixed(2)}bps`;return`best of ${r} routes, ranked on ${e.rankedOn}: ${a} better than the runner-up (${e.spreadBasis})`}return`best of ${r} routes, ranked on ${e.rankedOn}. No spread quoted: the top routes report cost differently, so the margin is not comparable.`}T();var M=Object.freeze({TRANSACTION:"unsigned-transaction",TYPED_DATA_ORDER:"typed-data-order"}),ia=100,st={"uniswap-v3":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o},a)=>{let{uniV3PrepareExactIn:s}=await Promise.resolve().then(()=>(tt(),Or)),i=await s({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:o},a);return{artifactKind:M.TRANSACTION,transaction:i.transaction,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.amountOut??null,minOut:i.quote?.amountOutMinimum??null}},"uniswap-v4":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o,slippageBps:a,fee:s,tickSpacing:i,hooks:c},u)=>{let{uniV4PrepareExactIn:p}=await Promise.resolve().then(()=>(nt(),Ur)),d=await p({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:o,slippageBps:a,fee:s,tickSpacing:i,hooks:c},u);return{artifactKind:M.TRANSACTION,transaction:d.transaction,requiresApproval:d.requiresApproval,amountOut:d.quote?.amountOut??null,minOut:d.quote?.amountOutMinimum??null,prepareReady:!0,executionReady:!1}},lifi:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o},a)=>{let{lifiPrepare:s}=await Promise.resolve().then(()=>(pe(),je)),i=await s({fromChain:e,toChain:e,fromToken:t,toToken:r,fromAmount:n,fromAddress:o},a);return{artifactKind:M.TRANSACTION,transaction:i.transaction,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.estimate?.toAmount??null,minOut:i.quote?.estimate?.toAmountMin??null}},paraswap:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o,decimalsIn:a,decimalsOut:s},i)=>{let{paraswapPrepare:c}=await Promise.resolve().then(()=>(ze(),Ht)),u=await c({chainId:e,srcToken:t,destToken:r,amount:n,srcDecimals:a,destDecimals:s,userAddress:o,side:"SELL"},i);return{artifactKind:M.TRANSACTION,transaction:u.transaction,requiresApproval:u.requiresApproval??null,amountOut:u.quote?.priceRoute?.destAmount??null,minOut:u.quote?.amountOutMinimum??null}},"0x":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o},a)=>{let{zeroxPrepare:s}=await Promise.resolve().then(()=>(Ge(),Qt)),i=await s({chainId:e,sellToken:t,buyToken:r,sellAmount:n,taker:o},a);return{artifactKind:M.TRANSACTION,transaction:i.transaction,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.buyAmount??null,minOut:i.quote?.minBuyAmount??null}},cow:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o},a)=>{let{cowPrepareOrder:s}=await Promise.resolve().then(()=>(Je(),dr)),i=await s({chainId:e,sellToken:t,buyToken:r,sellAmountBeforeFee:String(n),from:o},a);return{artifactKind:M.TYPED_DATA_ORDER,typedData:i.typedData,requiresApproval:{token:t,spender:i.vaultRelayer,amount:String(n),note:"CoW pulls funds via the vault relayer, not the settlement contract"},settlement:i.settlement,amountOut:i.quote?.quote?.buyAmount??null,minOut:null,submission:"sign the typed data, then submit the order to the CoW API"}}};var sa=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),ca=/^0x[0-9a-fA-F]{40}$/;async function jr(e,t={}){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(!ca.test(r))throw new Error(`taker must be a valid 20-byte address, got "${r}"`);if(sa.has(r.toLowerCase()))throw new Error(`taker "${r}" is a placeholder/burn address. 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 Oe(e,t);if(!n.best){let l=n.impactRejected??[];return{ok:!1,reason:l.length?l[0].reason:"no source returned a usable route",priceImpactBlocked:l.length>0,impactRejected:l,comparison:n}}let o=e.source||n.best.source,a=n.routes.find(l=>l.source===o);if(!a)return{ok:!1,reason:`source "${o}" did not return a usable route`,comparison:n};let s=st[o];if(!s){let l=n.routes.find(m=>st[m.source]&&m.source!==o);return{ok:!1,reason:`${o} won the comparison but has no prepare path in this build. `+(l?`Next preparable route is ${l.source}; pass source:"${l.source}" to use it.`:"No route in this comparison can be prepared."),comparison:n,winner:o}}let i;try{i=await s(e,t)}catch(l){let m=typeof l?.body=="string"?l.body:l?.body?JSON.stringify(l.body):"",f=[String(l?.message||l),m].filter(Boolean).join(" :: "),g=/allowance/i.test(f),h=!g&&/not enough|insufficient|balance/i.test(f),b,v;g?(v="approval-required-first",b=`${o} will not build swap calldata until the token approval exists on-chain. Approve the spender first, then prepare again. Underlying: ${f}`):h?(v="taker-not-funded",b=`${o} refused to build the transaction: ${f}. This venue verifies the taker holds the input token. Quoting works for any address; preparing needs the real funded wallet.`):(v="provider-error",b=`${o} prepare failed: ${f}`);let C=n.routes.find(X=>st[X.source]&&X.source!==o);return{ok:!1,reason:b,failureKind:v,...C?{alternative:C.source}:{},comparison:n}}let c=e.driftToleranceBps??ia,u=null,p=null;if(i.amountOut!=null&&a.grossOut!=null)try{let l=BigInt(a.grossOut),m=BigInt(i.amountOut);l>0n&&(u=Number((m-l)*10000n/l),u<-c&&(p=`route moved ${(u/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 d=n.routes.filter(l=>l.source!==o).map(l=>({source:l.source,netOut:l.netOut,gasUsd:l.gasUsd}));return x({ok:!0,chosen:{source:o,wasWinner:o===n.best.source,netOut:a.netOut,grossOut:a.grossOut,gasUsd:a.gasUsd},priceImpact:n.priceImpact??null,impactUnmeasured:n.impactUnmeasured??[],...i,unsigned:!0,signedBy:"user-wallet",destination:i.artifactKind===M.TRANSACTION?i.transaction?.to??null:i.settlement??null,driftBps:u,warnings:[...p?[p]:[],...n.warnings||[],...i.artifactKind===M.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"})}T();var ua=/^0x[0-9a-fA-F]{40}$/,la=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),da=100,ct={relay:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:o,taker:a},s)=>{let{relayPrepare:i}=await Promise.resolve().then(()=>(Ce(),Ie)),c=await i({user:a,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(o)},s);return{transactions:c.transactions||[],amountOut:c.quote?.details?.currencyOut?.amount??null,minOut:c.quote?.details?.currencyOut?.minimumAmount??null,durationSeconds:c.quote?.details?.timeEstimate??null}},lifi:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:o,taker:a,isHolder:s},i)=>{let{lifiPrepare:c}=await Promise.resolve().then(()=>(pe(),je)),u=await c({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:o,fromAddress:a,isHolder:s,feeAction:"bridge"},i);return{transactions:u.transaction?[u.transaction]:[],requiresApproval:u.requiresApproval??null,amountOut:u.quote?.estimate?.toAmount??null,minOut:u.quote?.estimate?.toAmountMin??null,durationSeconds:u.quote?.estimate?.executionDuration??null}}};async function Kr(e,t={}){let{taker:r,fromChainId:n,toChainId:o}=e;if(!r)throw new Error("prepareBestBridgeRoute requires taker: bridge transactions are built FOR an address, and the quote-only placeholder must never end up in one");if(!ua.test(r))throw new Error(`taker must be a valid 20-byte address, got "${r}"`);if(la.has(r.toLowerCase()))throw new Error(`taker "${r}" is a placeholder/burn address. Bridging to it would send funds to an address nobody controls, on a chain where you cannot undo it.`);let a=await Ne(e,t);if(!a.best)return{ok:!1,reason:"no source returned a usable bridge route",comparison:a};let s=e.source||a.best.source,i=a.routes.find(h=>h.source===s);if(!i)return{ok:!1,reason:`source "${s}" returned no usable route`,comparison:a};let c=ct[s];if(!c){let h=a.routes.find(b=>ct[b.source]&&b.source!==s);return{ok:!1,reason:`${s} won the comparison but has no bridge prepare path in this build. `+(h?`Next preparable route is ${h.source}; pass source:"${h.source}".`:"No route in this comparison can be prepared."),failureKind:"no-prepare-path",...h?{alternative:h.source}:{},winner:s,comparison:a}}let u;try{u=await c(e,t)}catch(h){let b=typeof h?.body=="string"?h.body:h?.body?JSON.stringify(h.body):"",v=[String(h?.message||h),b].filter(Boolean).join(" :: "),C=/allowance/i.test(v),X=!C&&/not enough|insufficient|balance/i.test(v),ft=a.routes.find(ht=>ct[ht.source]&&ht.source!==s);return{ok:!1,reason:C?`${s} will not build calldata until the token approval exists on-chain. Approve first, then prepare again. Underlying: ${v}`:X?`${s} refused to build: ${v}. Quoting works for any address; preparing needs the real funded wallet on chain ${n}.`:`${s} bridge prepare failed: ${v}`,failureKind:C?"approval-required-first":X?"taker-not-funded":"provider-error",...ft?{alternative:ft.source}:{},comparison:a}}let p=u.transactions||[];if(!p.length)return{ok:!1,reason:`${s} returned no executable transaction for this route`,failureKind:"provider-error",comparison:a};let d=p.filter(h=>h.chainId!=null&&Number(h.chainId)!==Number(n));if(d.length)return{ok:!1,reason:`${s} returned a transaction for chain ${d[0].chainId} but the origin chain is ${n}. Refusing to hand over a mismatched artifact.`,failureKind:"chain-mismatch",comparison:a};let l=e.driftToleranceBps??da,m=null,f=null;if(u.amountOut!=null&&i.grossOut!=null)try{let h=BigInt(i.grossOut),b=BigInt(u.amountOut);h>0n&&(m=Number((b-h)*10000n/h),m<-l&&(f=`route moved ${(m/100).toFixed(2)}% against you since the comparison (tolerance ${(l/100).toFixed(2)}%). Re-compare before signing.`))}catch{}let g=[...f?[f]:[],...a.warnings||[],`Bridging is NOT atomic: the origin transaction succeeding does not mean funds arrived on chain ${o}. Expect ~${u.durationSeconds!=null?`${u.durationSeconds}s`:"minutes"} before the destination credits, and do not re-send if it is pending.`];return p.length>1&&g.push(`This route needs ${p.length} transactions signed IN ORDER. Signing only the first leaves funds approved but not bridged.`),x({ok:!0,chosen:{source:s,wasWinner:s===a.best.source,netOut:i.netOut,grossOut:i.grossOut,gasUsd:i.gasUsd},artifactKind:"unsigned-transaction-sequence",fromChainId:Number(n),toChainId:Number(o),transactionCount:p.length,transactions:p,requiresApproval:u.requiresApproval??null,minOut:u.minOut??null,durationSeconds:u.durationSeconds??null,destination:p[0]?.to??null,unsigned:!0,signedBy:"user-wallet",driftBps:m,warnings:g,runnersUp:a.routes.filter(h=>h.source!==s).map(h=>({source:h.source,netOut:h.netOut,gasUsd:h.gasUsd})),comparison:{rankedOn:a.rankedOn,sourcesAnswered:a.sourcesAnswered,sourcesTried:a.sourcesTried,improvementBps:a.improvementBps},note:`UNSIGNED. ${p.length} transaction(s) on chain ${n}, crediting chain ${o}. Verify every destination address before signing.`},{provider:"router",kind:"best-bridge"})}W();$();var pa="https://api.dexscreener.com";function ma(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||pa).replace(/\/$/,"")}async function zr(e,t={}){if(!e)throw new Error("tokenAddress required");return A(`${ma(t)}/latest/dex/tokens/${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}W();var lt={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},N=e=>BigInt(e).toString(16).padStart(64,"0"),oe=e=>e.slice(2).toLowerCase().padStart(64,"0");function fa(e,t){return`0x${lt.getAmountsOut}`+N(e)+N(64)+N(t.length)+t.map(oe).join("")}function ha(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 o=0;o<r;o++){let a=128+o*64;if(t.length<a+64)return null;n.push(BigInt(`0x${t.slice(a,a+64)}`))}return n}function ut(e,t="router"){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}var dt=100;function ga(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>dt)throw new Error(`slippageBps ${r} exceeds the ${dt} 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 Wr(e){let{chainId:t,wrappedNative:r}=e;async function n(o,a,s,i){let c=await k(t,"eth_call",[{to:o,data:fa(a,s)},"latest"],i);return ha(c?.result??c)}return{async quote({tokenIn:o,tokenOut:a,amountIn:s,path:i},c={}){let u=ut(c.scanner);if(!u)return{chainId:t,evidence:E.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let p=i||[o,a];if(p.some(l=>!/^0x[0-9a-fA-F]{40}$/.test(l||"")))throw new Error("quote requires valid 20-byte addresses");let d=await n(u,s,p,c);return d?{chainId:t,router:u,path:p,amountIn:String(s),amountOut:d[d.length-1].toString(),hops:p.length-1,evidence:E.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:u,path:p,evidence:E.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:o,amountIn:a,base:s},i={}){let c=ut(i.scanner),u=s||r;if(u&&String(o).toLowerCase()===String(u).toLowerCase())return{chainId:t,token:o,verdict:w.UNKNOWN,evidence:E.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||!u)return{chainId:t,token:o,verdict:w.UNKNOWN,evidence:E.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,a,[u,o],i);if(!p)return{chainId:t,token:o,verdict:w.FAIL,evidence:E.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:o,verdict:w.FAIL,evidence:E.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let l=await n(c,d,[o,u],i);if(!l)return{chainId:t,token:o,verdict:w.FAIL,evidence:E.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 m=l[l.length-1],f=Number(m*10000n/BigInt(a)),g=w.PASS,h="round trip completes with expected fee/impact loss";return f<5e3?(g=w.FAIL,h=`round trip returns only ${(f/100).toFixed(2)}% -- punitive tax or no real liquidity`):f<9e3&&(g=w.CAUTION,h=`round trip returns ${(f/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:o,base:u,router:c,verdict:g,reason:h,amountIn:String(a),bought:d.toString(),returned:m.toString(),retentionBps:f,evidence:E.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:i,slippageBps:c=50,deadlineSeconds:u=900,path:p},d={}){let l=d.scanner,m=ut(l);if(!m)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(i||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=p||[o,a],g=await this.quote({tokenIn:o,tokenOut:a,amountIn:s,path:f},d);if(g.evidence!==E.LIVE)throw new Error(`cannot prepare without a live quote (${g.evidence}: ${g.reason??"no reason given"})`);let h=ga(g.amountOut,c);if(h<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=BigInt(Math.floor(Date.now()/1e3)+Number(u)),v=r&&f[0].toLowerCase()===r.toLowerCase()&&d.useNative,C=v?`0x${lt.swapExactETHForTokens}`+N(h)+N(128)+oe(i)+N(b)+N(f.length)+f.map(oe).join(""):`0x${lt.swapExactTokensForTokens}`+N(s)+N(h)+N(160)+oe(i)+N(b)+N(f.length)+f.map(oe).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:m,data:C,value:v?`0x${BigInt(s).toString(16)}`:"0x0"},guard:{quotedOut:g.amountOut,minOut:h.toString(),slippageBps:c,maxSlippageBps:dt,deadline:b.toString()},requires:v?[]:[{step:"approve",token:f[0],spender:m,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."}}}}W();var ba=[100,500,3e3,1e4],Gr={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},j=e=>BigInt(e).toString(16).padStart(64,"0"),ae=e=>e.slice(2).toLowerCase().padStart(64,"0"),Yr=/^0x[0-9a-fA-F]{40}$/,mt=100;function wa(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>mt)throw new Error(`slippageBps ${r} exceeds the ${mt} 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 pt(e,t){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function Xr(e){let{chainId:t,wrappedNative:r}=e;async function n({quoter:a,tokenIn:s,tokenOut:i,amountIn:c,fee:u},p){let d=`0x${Gr.quoteExactInputSingle}`+ae(s)+ae(i)+j(c)+j(u)+j(0),l=await k(t,"eth_call",[{to:a,data:d},"latest"],p).catch(()=>null),m=l?.result??l;if(!m||m==="0x"||m.length<66)return null;let f=BigInt(`0x${m.slice(2,66)}`);return f>0n?f:null}async function o({quoter:a,tokenIn:s,tokenOut:i,amountIn:c},u){let p=[],d=null;for(let l of ba){let m=await n({quoter:a,tokenIn:s,tokenOut:i,amountIn:c,fee:l},u);p.push({fee:l,amountOut:m?m.toString():null}),m&&(!d||m>d.amountOut)&&(d={fee:l,amountOut:m})}return{best:d,tried:p}}return{async quote({tokenIn:a,tokenOut:s,amountIn:i},c={}){let u=pt(c.scanner,"quoter");if(!u)return{chainId:t,evidence:E.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let l of[a,s])if(!Yr.test(l||""))throw new Error("quote requires valid 20-byte addresses");let{best:p,tried:d}=await o({quoter:u,tokenIn:a,tokenOut:s,amountIn:i},c);return p?{chainId:t,venue:"uniswap-v3",quoter:u,tokenIn:a,tokenOut:s,amountIn:String(i),amountOut:p.amountOut.toString(),fee:p.fee,triedFeeTiers:d,evidence:E.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:u,tokenIn:a,tokenOut:s,triedFeeTiers:d,evidence:E.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:a,amountIn:s,base:i},c={}){let u=pt(c.scanner,"quoter"),p=i||r;if(p&&String(a).toLowerCase()===String(p).toLowerCase())return{chainId:t,token:a,verdict:w.UNKNOWN,evidence:E.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||!p)return{chainId:t,token:a,verdict:w.UNKNOWN,evidence:E.UNAVAILABLE,reason:u?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let d=await o({quoter:u,tokenIn:p,tokenOut:a,amountIn:s},c);if(!d.best)return{chainId:t,token:a,verdict:w.FAIL,evidence:E.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier"};let l=await o({quoter:u,tokenIn:a,tokenOut:p,amountIn:d.best.amountOut},c);if(!l.best)return{chainId:t,token:a,verdict:w.FAIL,evidence:E.LIVE,leg:"sell",bought:d.best.amountOut.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let m=l.best.amountOut,f=Number(m*10000n/BigInt(s)),g=w.PASS,h="round trip completes with expected fee/impact loss";return f<5e3?(g=w.FAIL,h=`round trip returns only ${(f/100).toFixed(2)}% -- punitive tax or no real liquidity`):f<9e3&&(g=w.CAUTION,h=`round trip returns ${(f/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:a,base:p,verdict:g,reason:h,amountIn:String(s),bought:d.best.amountOut.toString(),returned:m.toString(),retentionBps:f,buyFee:d.best.fee,sellFee:l.best.fee,evidence:E.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:a,tokenOut:s,amountIn:i,recipient:c,slippageBps:u=50,fee:p},d={}){let l=pt(d.scanner,"router");if(!l)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(!Yr.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let m=await this.quote({tokenIn:a,tokenOut:s,amountIn:i},d);if(m.evidence!==E.LIVE)throw new Error(`cannot prepare without a live quote (${m.evidence}: ${m.reason??"no reason given"})`);let f=p??m.fee,g=wa(m.amountOut,u);if(g<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let h=`0x${Gr.exactInputSingle}`+ae(a)+ae(s)+j(f)+ae(c)+j(i)+j(g)+j(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:l,data:h,value:"0x0"},guard:{quotedOut:m.amountOut,minOut:g.toString(),slippageBps:u,maxSlippageBps:mt,fee:f},requires:[{step:"approve",token:a,spender:l,amount:String(i)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var _e={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function Qr(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function Jr(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 o=t.slice(128,128+n*2),a=Buffer.from(o,"hex").toString("utf8").replace(/\0+$/,"");if(a)return a}}return Buffer.from(t.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function Ea(e){let{chainId:t}=e;async function r(n,o,a){return k(t,"eth_call",[{to:n,data:o},"latest"],a)}return{async blockNumber(n={}){let o=await wr(t,n);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:E.LIVE}},async nativeBalance(n,o={}){let a=await Er(t,n,o);return{chainId:t,address:n,wei:a?.wei??a?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:E.LIVE}},async tokenBalance({token:n,owner:o},a={}){let s=await yr({chainId:t,token:n,owner:o},a);return{chainId:t,token:n,owner:o,raw:s?.balance??s,evidence:E.LIVE}},async resolveToken(n,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:t,token:n,evidence:E.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[a,s,i,c]=await Promise.all([r(n,_e.decimals,o).catch(()=>null),r(n,_e.symbol,o).catch(()=>null),r(n,_e.name,o).catch(()=>null),r(n,_e.totalSupply,o).catch(()=>null)]),u=Qr(a?.result??a),p=u!==null||s?.result||i?.result;return{chainId:t,address:n,decimals:u===null?null:Number(u),symbol:Jr(s?.result??s),name:Jr(i?.result??i),totalSupply:(Qr(c?.result??c)??null)?.toString()??null,evidence:p?E.LIVE:E.UNKNOWN,warning:p?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(n,o={}){let a=e.dexscreenerSlug;if(!a)return{chainId:t,token:n,pools:[],evidence:E.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let s=await zr(n,o).catch(()=>null),c=(s?.pairs||s?.data?.pairs||[]).filter(u=>String(u.chainId).toLowerCase()===String(a).toLowerCase()).map(u=>({pair:u.pairAddress,dex:u.dexId,base:u.baseToken?.address,quote:u.quoteToken?.address,liquidityUsd:u.liquidity?.usd??null,priceUsd:u.priceUsd??null,volume24hUsd:u.volume?.h24??null,createdAt:u.pairCreatedAt??null})).sort((u,p)=>(p.liquidityUsd??0)-(u.liquidityUsd??0));return{chainId:t,token:n,pools:c,evidence:c.length?E.LIVE:E.UNKNOWN}},async scanBlocks({fromBlock:n,toBlock:o,address:a,topics:s,chunkSize:i=2e3}={},c={}){if(!Number.isInteger(n)||!Number.isInteger(o))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(o<n)throw new Error("toBlock must be >= fromBlock");let u=[],p=[];for(let d=n;d<=o;d+=i){let l=Math.min(d+i-1,o);p.push([d,l])}for(let[d,l]of p){let m={fromBlock:`0x${d.toString(16)}`,toBlock:`0x${l.toString(16)}`};a&&(m.address=a),s&&(m.topics=s);let f=await k(t,"eth_getLogs",[m],c).catch(g=>({error:String(g?.message||g)}));if(f?.error)return{chainId:t,fromBlock:n,toBlock:o,logs:u,complete:!1,failedAt:[d,l],error:f.error,evidence:E.UNKNOWN};for(let g of f?.result??f??[])u.push(g)}return{chainId:t,fromBlock:n,toBlock:o,logs:u,complete:!0,chunks:p.length,evidence:E.LIVE}},async scoreRisk(n,o={}){let a=[],s=w.PASS,i=p=>{let d={[w.PASS]:0,[w.CAUTION]:1,[w.UNKNOWN]:2,[w.FAIL]:3};d[p]>d[s]&&(s=p)},c=await this.resolveToken(n,o);c.evidence!==E.LIVE?(a.push({check:"erc20-metadata",result:w.UNKNOWN,detail:c.warning}),i(w.UNKNOWN)):a.push({check:"erc20-metadata",result:w.PASS,detail:`${c.symbol} / ${c.decimals}d`});let u=await this.resolvePools(n,o);if(u.evidence===E.UNAVAILABLE)a.push({check:"liquidity",result:w.UNKNOWN,detail:u.reason}),i(w.UNKNOWN);else if(!u.pools.length)a.push({check:"liquidity",result:w.FAIL,detail:"no pool with liquidity found"}),i(w.FAIL);else{let p=u.pools[0],d=p.liquidityUsd??0;d<5e3?(a.push({check:"liquidity",result:w.CAUTION,detail:`top pool only $${d}`}),i(w.CAUTION)):a.push({check:"liquidity",result:w.PASS,detail:`$${d} on ${p.dex}`}),p.createdAt&&Date.now()-p.createdAt<24*3600*1e3&&(a.push({check:"age",result:w.CAUTION,detail:"pool under 24h old"}),i(w.CAUTION))}if(typeof this.sellSimulation=="function"){let p=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},o).catch(d=>({verdict:w.UNKNOWN,reason:String(d?.message||d)}));a.push({check:"sellability",result:p.verdict,detail:p.retentionBps!=null?`round trip returns ${(p.retentionBps/100).toFixed(2)}% -- ${p.reason}`:p.reason}),i(p.verdict)}else a.push({check:"sellability",result:w.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."}),i(w.UNKNOWN);return{chainId:t,token:n,verdict:s,checks:a,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function Zr(e){let r={...Ea(e)},n=new Set((e.venues||[]).map(a=>a.kind));e.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,Xr({chainId:e.chainId,wrappedNative:e.wrappedNative})):e.venueKind==="uniswap-v2"&&n.has("router")&&Object.assign(r,Wr({chainId:e.chainId,wrappedNative:e.wrappedNative}));let o={};for(let[a,s]of Object.entries(r))o[a]=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:o}}var ya=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",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",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",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",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",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",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",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",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 en(){return ya.map(e=>gt(Zr(e)))}en();var[tn,...Re]=process.argv.slice(2),Te=Re.includes("--json"),y=Re.filter(e=>e!=="--json"),rn="0x0000000000000000000000000000000000000000";function G(e){e||Y("missing <chain>");let t=Number(e);if(se(t))return t;let r=$e().find(n=>n.key===String(e).toLowerCase());if(r)return r.chainId;Y(`unknown chain "${e}". Known: ${$e().map(n=>n.key).join(", ")}`)}function Y(e){console.error(`error: ${e}`),process.exit(1)}function nn(e,t){return(Number(e)/10**t).toLocaleString(void 0,{maximumFractionDigits:6})}function on(e,t){if(console.log(`sources: ${e.sourcesAnswered}/${e.sourcesTried} answered`),console.log(`ranked on: ${e.rankedOn}
6
- `),!e.routes.length){console.log("no source returned a usable route.");for(let n of e.failed)console.log(` ${n.source}: ${n.error}`);return}let r=Math.max(...e.routes.map(n=>n.source.length),6);console.log(` ${"source".padEnd(r)} ${"net out".padStart(14)} ${"gross".padStart(14)} cost`);for(let[n,o]of e.routes.entries()){let a=n===0?"*":" ",s=o.gasUsd==null?"gas unknown":o.gasUsd===0?"gasless (solver)":`$${Number(o.gasUsd+(o.feeUsd??0)).toFixed(2)}`,i=o.meta?.durationSeconds!=null?` ~${o.meta.durationSeconds}s`:"";console.log(`${a} ${o.source.padEnd(r)} ${nn(o.netOut,t).padStart(14)} ${nn(o.grossOut,t).padStart(14)} ${s}${i}`)}for(let n of e.failed)console.log(` ${n.source.padEnd(r)} FAILED: ${String(n.error).slice(0,60)}`);console.log(`
5
+ - `)}`);let o=e.capabilities||{},a=de.filter(i=>typeof o[i]=="function"),s={key:e.key,chainId:e.chainId,name:e.name,rpcEnv:[...e.rpcEnv],nativeCurrency:e.nativeCurrency?{...e.nativeCurrency}:null,explorer:e.explorer||null,venues:(e.venues||[]).map(i=>({...i})),warnings:n,capabilities(){return{chainId:e.chainId,key:e.key,supported:[...a],unsupported:de.filter(i=>!a.includes(i))}},supports(i){return a.includes(i)}};for(let i of de)a.includes(i)?s[i]=async(...c)=>o[i](...c,{scanner:s}):s[i]=async()=>{throw new Error(`${e.key} (chain ${e.chainId}) does not implement "${i}". Supported: ${a.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)}var qe=new Map;function xt(e){let t=bn(e);return qe.set(t.chainId,t),t}function pe(e){return qe.get(Number(e))||null}function Me(){return[...qe.values()]}var D=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"}),It={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"},re=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}};function St(e){let{source:t,amountOut:r,minOut:n=null,gasUsd:o=null,feeUsd:a=null,estimatedGas:s=null,liquidityUsd:i=null,error:c=null,executionReady:u=!1,meta:p={}}=e||{};if(c||r==null)return{source:t,quality:D.FAILED,amountOut:null,error:c||"no amountOut returned"};let d=re(r);return d==null||d<=0n?{source:t,quality:D.FAILED,amountOut:null,error:"non-positive amountOut"}:{source:t,quality:o==null?D.NO_GAS:D.FULL,amountOut:d.toString(),minOut:re(n)?.toString()??null,gasUsd:o,feeUsd:a,estimatedGas:s==null?null:String(s),liquidityUsd:i==null?null:Number(i),executionReady:u,meta:p}}async function Ct(e,t,{divisor:r=1000n}={}){let n=re(t);if(n==null||n<=0n)return null;let o=n/r>0n?n/r:1n;if(o>=n)return null;let a,s;try{[a,s]=await Promise.all([e(o),e(n)])}catch{return null}let i=re(a),c=re(s);if(i==null||c==null||i<=0n)return null;let u=Number(i)/Number(o),p=Number(c)/Number(n);return!Number.isFinite(u)||!Number.isFinite(p)||u<=0?null:{impactPct:(1-p/u)*100,probeAmountIn:o.toString(),probeAmountOut:i.toString(),fullAmountOut:c.toString()}}function kt(e,t,{maxImpactPct:r=25}={}){let n=[],o=[],a=(e.routes??[]).filter(i=>{let c=t?.[i.source];return c?c.impactPct>r?(n.push({source:i.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:(o.push(i.source),!0)}),s=[...e.warnings??[]];return n.length&&s.push(`dropped ${n.length} route(s) on price impact: `+n.map(i=>`${i.source} (${i.impactPct}%)`).join(", ")),o.length&&s.push(`price impact NOT measured for: ${o.join(", ")}. These are unproven against thin liquidity, not proven safe.`),{...e,routes:a,best:a[0]??null,impactRejected:n,impactUnmeasured:o,warnings:s}}function Ve(e,{destPriceUsd:t=null,destDecimals:r=null,liquidityFirst:n=!0,liquidityBandBps:o=50}={}){let a=e.filter(b=>b.quality!==D.FAILED),s=e.filter(b=>b.quality===D.FAILED),i=t!=null&&t>0&&r!=null&&r>=0,c=a.map(b=>{let w=BigInt(b.amountOut),A=0n,N=!1;if(i){let _=(b.gasUsd??0)+(b.feeUsd??0);if(_>0){let Y=_/t*10**r;Number.isFinite(Y)&&Y>=0&&(A=BigInt(Math.floor(Y)),N=!0)}else b.gasUsd===0&&(N=!0)}let k=w>A?w-A:0n;return{...b,grossOut:w.toString(),netOut:k.toString(),costInDest:A.toString(),costAccounted:N}}),u=Number(o)>0?Number(o):0,p=c.reduce((b,w)=>BigInt(w.netOut)>b?BigInt(w.netOut):b,0n),d=b=>p>0n?Number((p-BigInt(b))*10000n/p):0,l=[],m=c.slice().sort((b,w)=>BigInt(w.netOut)>BigInt(b.netOut)?1:-1)[0]??null;c.sort((b,w)=>{let A=d(b.netOut)<=u?0:1,N=d(w.netOut)<=u?0:1;if(n&&u>0&&A!==N)return A-N;if(n&&u>0){let k=b.liquidityUsd??-1,_=w.liquidityUsd??-1;if(k!==_)return _-k}return BigInt(w.netOut)>BigInt(b.netOut)?1:-1}),n&&u>0&&m&&c[0]&&c[0].source!==m.source&&l.push(`liquidity-first: chose ${c[0].source} (liquidity $${c[0].liquidityUsd??"unknown"}) over best-price ${m.source} within ${u} bps`);let h=c.filter(b=>!b.costAccounted).map(b=>b.source);i?h.length&&l.push(`gas not reported by: ${h.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):l.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let g=null,f=null;if(c.length>=2&&c[0].costAccounted&&c[1].costAccounted){let b=BigInt(c[0].netOut),w=BigInt(c[1].netOut);w>0n&&(g=Number((b-w)*10000n/w),f=`${c[0].source} vs ${c[1].source}`)}return{best:c[0]??null,routes:c,failed:s,improvementBps:g,spreadBasis:f,rankedOn:i?"net-of-cost":"gross",warnings:l}}async function me(e,{timeoutMs:t=12e3}={}){let r=(o,a)=>Promise.race([o,new Promise((s,i)=>setTimeout(()=>i(new Error(`${a}: timeout`)),t))]);return(await Promise.allSettled(e.map(o=>r(Promise.resolve().then(o.run),o.source)))).map((o,a)=>{let s=e[a].source;return o.status==="rejected"?St({source:s,error:String(o.reason?.message||o.reason)}):St({source:s,...o.value})})}be();Ze();tt();F();M();et();U();var Eo="https://api.1inch.dev/swap/v6.0";function ar(e={}){return Ee({provider:"oneinch",defaultUrl:Eo,hosts:["api.1inch.dev"],url:e.baseUrl||process.env.ONEINCH_API_URL})}function yo(e={}){return ar(e).baseUrl}function ir(e={}){return e.apiKey||process.env.ONEINCH_API_KEY||process.env.ONE_INCH_API_KEY||""}function Ao(e={}){let t=ir(e);return ye({accept:"application/json"},{Authorization:t?`Bearer ${t}`:""},ar(e).trusted)}async function sr(e={},t={}){if(!ir(t))throw new Error("ONEINCH_API_KEY required for 1inch");let r=Number(e.chainId??1),{src:n,dst:o,amount:a}=e;if(!n||!o||!a)throw new Error("oneinchQuote requires src, dst, amount");let s=new URLSearchParams({src:n,dst:o,amount:String(a)}),i=await x(`${yo(t)}/${r}/quote?${s}`,{headers:Ao(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3});return i?.dstAmount?C(i,{chainId:r,venue:"1inch-quote",amountOut:i.dstAmount,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):i}at();ut();dt();F();var fa="https://coins.llama.fi",ha="https://api.llama.fi";function ga(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||fa).replace(/\/$/,"")}function ba(e={}){return(e.baseUrl||process.env.DEFILLAMA_API_URL||ha).replace(/\/$/,"")}async function Te(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return x(`${ga(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function Hr(e={}){return x(`${ba(e)}/protocols`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??2e4})}var P=e=>{let t=Number(e);return Number.isFinite(t)?t:null};function Ue(e){if(!Array.isArray(e))return null;let t=0,r=!1;for(let n of e){let o=P(n?.amountUSD);o!=null&&(t+=o,r=!0)}return r?t:null}async function Yr(e,t={}){let r=It[Number(e)];if(!r)return null;try{let n=await Te([r],t);return P(n?.coins?.[r]?.price)}catch{return null}}var K=e=>String(e??"").toLowerCase().replace(/[^a-z0-9]/g,""),Xr=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 xa(e={}){try{let t=await Hr({...e,baseUrl:e.defillamaApiBaseUrl,timeoutMs:e.defillamaTimeoutMs??Math.min(Number(e.timeoutMs??5e3),5e3)});return Array.isArray(t)?t:[]}catch{return[]}}function Sa(e,t={}){let r=K(t.tool||t.provider||t.bridge||t.protocol),n=[];return e==="lifi"&&r&&r!=="lifi"&&n.push(...Xr[r]||[r]),n.push(...Xr[K(e)]||[e]),n}function Ia(e,t,r={}){let n=Array.isArray(e)?e:[],o=Sa(t,r).map(K).filter(Boolean);for(let a of o){let s=n.find(c=>K(c?.slug)===a||K(c?.name)===a),i=P(s?.tvl);if(i!=null)return{liquidityUsd:i,protocol:s?.name??s?.slug??a}}for(let a of o){let s=n.find(c=>{let u=K(c?.category);return!u.includes("bridge")&&!u.includes("crosschain")?!1:K(c?.slug).includes(a)||K(c?.name).includes(a)}),i=P(s?.tvl);if(i!=null)return{liquidityUsd:i,protocol:s?.name??s?.slug??a}}return null}function mt({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o,slippageBps:a,decimalsIn:s,decimalsOut:i,nativePriceUsd:c=null,destDecimalsPromise:u=null,opts:p={}}){let d=[];return d.push({source:"lifi",run:async()=>{let l=await ne({fromChain:e,toChain:e,fromToken:t,toToken:r,fromAmount:n},p),m=l?.estimate??l?.[0]?.estimate;return{amountOut:m?.toAmount,minOut:m?.toAmountMin,gasUsd:Ue(m?.gasCosts),feeUsd:Ue(m?.feeCosts),meta:{tool:l?.tool??l?.toolDetails?.name}}}}),s!=null&&d.push({source:"paraswap",run:async()=>{let l=i??(await Promise.resolve(u))?.decimals;if(l==null)throw new Error("paraswap needs destination decimals; none supplied or resolvable");let h=(await we({chainId:e,srcToken:t,destToken:r,amount:n,srcDecimals:s,destDecimals:l},p))?.priceRoute;return{amountOut:h?.destAmount,gasUsd:P(h?.gasCostUSD),meta:{bestRoute:h?.bestRoute?.[0]?.swaps?.[0]?.swapExchanges?.[0]?.exchange}}}}),process.env.ZEROX_API_KEY&&d.push({source:"0x",run:async()=>{let l=await ve({chainId:e,sellToken:t,buyToken:r,sellAmount:n,taker:o},p),m=null,h=l?.totalNetworkFee,g=await Promise.resolve(c);return h!=null&&g&&(m=Number(h)/1e18*g),{amountOut:l?.buyAmount,minOut:l?.minBuyAmount,gasUsd:m,meta:{source:l?.route?.fills?.[0]?.source}}}}),process.env.ONEINCH_API_KEY&&d.push({source:"1inch",run:async()=>{let l=await sr({chainId:e,src:t,dst:r,amount:n},p),m=null;return l?.gas!=null&&c&&(m=null),{amountOut:l?.dstAmount,gasUsd:m,meta:{gasUnits:l?.gas}}}}),d.push({source:"cow",run:async()=>{let l=await ae({chainId:e,sellToken:t,buyToken:r,sellAmountBeforeFee:String(n),from:o},p),m=l?.quote??l,h=m?.feeAmount;return{amountOut:m?.buyAmount,gasUsd:0,meta:{intent:!0,feeAmountInSellToken:h,settlement:"solver-executed"}}}}),T[Number(e)]&&d.push({source:"uniswap-v3",run:async()=>{let l=await se({chainId:e,tokenIn:t,tokenOut:r,amountIn:n},p);return{amountOut:l?.amountOut,minOut:l?.minOut??l?.amountOutMinimum??null,gasUsd:null,liquidityUsd:l?.liquidityUsd??null,meta:{onchain:!0,fee:l?.fee,gasUnits:l?.gasEstimate,quoter:l?.quoter}}}}),V[Number(e)]&&d.push({source:"uniswap-v4",run:async()=>{let l=await _e({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:o,slippageBps:a},p);return{amountOut:l?.amountOut,minOut:l?.minOut??l?.amountOutMinimum??null,gasUsd:null,liquidityUsd:l?.liquidityUsd??null,meta:{onchain:!0,venue:"uniswap-v4",fee:l?.fee,tickSpacing:l?.tickSpacing,poolId:l?.poolId,hooks:l?.hooks,gasUnits:l?.gasEstimate,quoter:l?.quoter,poolManager:l?.poolManager,prepareReady:l?.prepareReady===!0,executionReady:!1}}}}),d}function Qr({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:o,taker:a,opts:s={}}){let i=[],c=null,u=async(p,d={})=>(c||=xa(s),Ia(await c,p,d));return i.push({source:"lifi",run:async()=>{let p=await ne({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:o},s),d=p?.estimate??p?.[0]?.estimate,l={tool:p?.tool??p?.toolDetails?.name,durationSeconds:P(d?.executionDuration)},m=await u("lifi",l);return{amountOut:d?.toAmount,minOut:d?.toAmountMin,gasUsd:Ue(d?.gasCosts),feeUsd:Ue(d?.feeCosts),liquidityUsd:m?.liquidityUsd??null,meta:{...l,liquidityProtocol:m?.protocol}}}}),i.push({source:"relay",run:async()=>{let{relayQuote:p}=await Promise.resolve().then(()=>(Re(),Be)),l=(await p({user:a,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(o)},s))?.details,m={durationSeconds:P(l?.timeEstimate),rate:l?.rate},h=await u("relay",m);return{amountOut:l?.currencyOut?.amount,minOut:l?.currencyOut?.minimumAmount,gasUsd:P(l?.totalImpact?.usd)!=null?Math.abs(P(l.totalImpact.usd)):null,liquidityUsd:h?.liquidityUsd??null,meta:{...m,liquidityProtocol:h?.protocol}}}}),i.push({source:"across",run:async()=>{let{acrossSuggestedFees:p}=await Promise.resolve().then(()=>(Re(),Be)),d=await p({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(o)},s),l=d?.totalRelayFee?.total,m=null;if(l!=null)try{let g=BigInt(String(o))-BigInt(String(l));g>0n&&(m=g.toString())}catch{}let h=await u("across");return{amountOut:m,gasUsd:null,liquidityUsd:h?.liquidityUsd??null,meta:{derivedFromFees:!0,durationSeconds:P(d?.estimatedFillTimeSec),limits:d?.limits?{min:d.limits.minDeposit,max:d.limits.maxDeposit}:void 0,liquidityProtocol:h?.protocol}}}}),i}var Ca={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"};async function Jr(e,t,r){let n=Ca[Number(e)];if(!n)return{priceUsd:null,decimals:null};let o=`${n}:${t}`;try{let s=(await Te([o],r))?.coins?.[o],i=Number(s?.price),c=Number(s?.decimals);return{priceUsd:Number.isFinite(i)?i:null,decimals:Number.isFinite(c)?c:null}}catch{return{priceUsd:null,decimals:null}}}async function $e(e,t={}){let{chainId:r,tokenIn:n,tokenOut:o,amountIn:a}=e;if(r==null||!n||!o||a==null)throw new Error("bestSwapRoute requires chainId, tokenIn, tokenOut, amountIn");let s=Yr(r,t),i=Jr(r,o,t),c=mt({...e,nativePriceUsd:s,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:t}),[u,p]=await Promise.all([me(c,{timeoutMs:t.timeoutMs??12e3}),i]);s.catch(()=>{});let d=Ve(u,{destPriceUsd:p.priceUsd,destDecimals:e.decimalsOut??p.decimals,liquidityBandBps:t.liquidityBandBps??50}),l=t.maxImpactPct===void 0?25:t.maxImpactPct;if(l!=null&&d.best){let m=d.best.source,g=await Ct(async f=>{let b=mt({...e,amountIn:f.toString(),nativePriceUsd:s,decimalsOut:e.decimalsOut,destDecimalsPromise:i,opts:t}).filter(A=>A.source===m);return b.length?(await me(b,{timeoutMs:t.timeoutMs??12e3}))?.[0]?.amountOut??null:null},a);if(g){let f=kt(d,{[m]:g},{maxImpactPct:l});return{kind:"swap",chainId:r,tokenIn:n,tokenOut:o,amountIn:String(a),...f,sourcesTried:c.length,sourcesAnswered:u.filter(b=>b.quality!==D.FAILED).length,note:ft(f,c.length),priceImpact:{[m]:Number(g.impactPct.toFixed(2))}}}}return{kind:"swap",chainId:r,tokenIn:n,tokenOut:o,amountIn:String(a),...d,sourcesTried:c.length,sourcesAnswered:u.filter(m=>m.quality!==D.FAILED).length,note:ft(d,c.length)}}async function Le(e,t={}){let{fromChainId:r,toChainId:n,tokenIn:o,tokenOut:a,amountIn:s}=e;if(r==null||n==null||!o||!a||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 i=Jr(n,a,t),c=Qr({...e,opts:t}),[u,p]=await Promise.all([me(c,{timeoutMs:t.timeoutMs??15e3}),i]),d=Ve(u,{destPriceUsd:p.priceUsd,destDecimals:e.decimalsOut??p.decimals,liquidityBandBps:t.liquidityBandBps??50}),l=d.routes.map(m=>({source:m.source,seconds:m.meta?.durationSeconds??null})).filter(m=>m.seconds!=null);return{kind:"bridge",fromChainId:r,toChainId:n,tokenIn:o,tokenOut:a,amountIn:String(s),...d,durations:l,sourcesTried:c.length,sourcesAnswered:u.filter(m=>m.quality!==D.FAILED).length,note:ft(d,c.length)}}function ft(e,t){if(!e.best)return"no source returned a usable route";let r=e.routes.length;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.`;if(e.improvementBps!=null){let n=e.improvementBps,o=n/100;if(n<.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.`;let a=o>=.01?`${o.toFixed(2)}%`:`${n.toFixed(2)}bps`;return`best of ${r} routes, ranked on ${e.rankedOn}: ${a} better than the runner-up (${e.spreadBasis})`}return`best of ${r} routes, ranked on ${e.rankedOn}. No spread quoted: the top routes report cost differently, so the margin is not comparable.`}U();var z=Object.freeze({TRANSACTION:"unsigned-transaction",TYPED_DATA_ORDER:"typed-data-order"}),ka=100,ht={"uniswap-v3":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o},a)=>{let{uniV3PrepareExactIn:s}=await Promise.resolve().then(()=>(ut(),$r)),i=await s({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:o},a);return{artifactKind:z.TRANSACTION,transaction:i.transaction,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.amountOut??null,minOut:i.quote?.amountOutMinimum??null}},"uniswap-v4":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o,slippageBps:a,fee:s,tickSpacing:i,hooks:c},u)=>{let{uniV4PrepareExactIn:p}=await Promise.resolve().then(()=>(dt(),Vr)),d=await p({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:o,slippageBps:a,fee:s,tickSpacing:i,hooks:c},u);return{artifactKind:z.TRANSACTION,transaction:d.transaction,requiresApproval:d.requiresApproval,amountOut:d.quote?.amountOut??null,minOut:d.quote?.amountOutMinimum??null,prepareReady:!0,executionReady:!1}},lifi:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o},a)=>{let{lifiPrepare:s}=await Promise.resolve().then(()=>(be(),Qe)),i=await s({fromChain:e,toChain:e,fromToken:t,toToken:r,fromAmount:n,fromAddress:o},a);return{artifactKind:z.TRANSACTION,transaction:i.transaction,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.estimate?.toAmount??null,minOut:i.quote?.estimate?.toAmountMin??null}},paraswap:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o,decimalsIn:a,decimalsOut:s},i)=>{let{paraswapPrepare:c}=await Promise.resolve().then(()=>(Ze(),Yt)),u=await c({chainId:e,srcToken:t,destToken:r,amount:n,srcDecimals:a,destDecimals:s,userAddress:o,side:"SELL"},i);return{artifactKind:z.TRANSACTION,transaction:u.transaction,requiresApproval:u.requiresApproval??null,amountOut:u.quote?.priceRoute?.destAmount??null,minOut:u.quote?.amountOutMinimum??null}},"0x":async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o},a)=>{let{zeroxPrepare:s}=await Promise.resolve().then(()=>(tt(),or)),i=await s({chainId:e,sellToken:t,buyToken:r,sellAmount:n,taker:o},a);return{artifactKind:z.TRANSACTION,transaction:i.transaction,requiresApproval:i.requiresApproval??null,amountOut:i.quote?.buyAmount??null,minOut:i.quote?.minBuyAmount??null}},cow:async({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o},a)=>{let{cowPrepareOrder:s}=await Promise.resolve().then(()=>(at(),wr)),i=await s({chainId:e,sellToken:t,buyToken:r,sellAmountBeforeFee:String(n),from:o},a);return{artifactKind:z.TYPED_DATA_ORDER,typedData:i.typedData,requiresApproval:{token:t,spender:i.vaultRelayer,amount:String(n),note:"CoW pulls funds via the vault relayer, not the settlement contract"},settlement:i.settlement,amountOut:i.quote?.quote?.buyAmount??null,minOut:null,submission:"sign the typed data, then submit the order to the CoW API"}}};var Oa=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),Na=/^0x[0-9a-fA-F]{40}$/;async function Zr(e,t={}){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(!Na.test(r))throw new Error(`taker must be a valid 20-byte address, got "${r}"`);if(Oa.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 $e(e,t);if(!n.best){let f=n.impactRejected??[];return{ok:!1,reason:f.length?f[0].reason:"no source returned a usable route",priceImpactBlocked:f.length>0,impactRejected:f,comparison:n}}let o=e.source||n.best.source,a=n.routes.find(f=>f.source===o);if(!a)return{ok:!1,reason:`source "${o}" did not return a usable route`,comparison:n};let s=ht[o];if(!s){let f=n.routes.find(b=>ht[b.source]&&b.source!==o);return{ok:!1,reason:`${o} won the comparison but has no prepare path in this build. `+(f?`Next preparable route is ${f.source}; pass source:"${f.source}" to use it.`:"No route in this comparison can be prepared."),comparison:n,winner:o}}let i;try{i=await s(e,t)}catch(f){let b=typeof f?.body=="string"?f.body:f?.body?JSON.stringify(f.body):"",w=[String(f?.message||f),b].filter(Boolean).join(" :: "),A=/allowance/i.test(w),N=!A&&/not enough|insufficient|balance/i.test(w),k,_;A?(_="approval-required-first",k=`${o} will not build swap calldata until the token approval exists on-chain. Approve the spender first, then prepare again. Underlying: ${w}`):N?(_="taker-not-funded",k=`${o} refused to build the transaction: ${w}. This venue verifies the taker holds the input token. Quoting works for any address; preparing needs the real funded wallet.`):(_="provider-error",k=`${o} prepare failed: ${w}`);let Y=n.routes.find(vt=>ht[vt.source]&&vt.source!==o);return{ok:!1,reason:k,failureKind:_,...Y?{alternative:Y.source}:{},comparison:n}}let c=e.driftToleranceBps??ka,u=null,p=null;if(i.amountOut!=null&&a.grossOut!=null)try{let f=BigInt(a.grossOut),b=BigInt(i.amountOut);f>0n&&(u=Number((b-f)*10000n/f),u<-c&&(p=`route moved ${(u/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 d=n.routes.filter(f=>f.source!==o).map(f=>({source:f.source,netOut:f.netOut,gasUsd:f.gasUsd})),m=n.routes.map(f=>({source:f.source,liquidityUsd:f.liquidityUsd??null})).reduce((f,b)=>Math.max(f,b.liquidityUsd??0),0)||null,h=a.liquidityUsd??null,g=h!=null&&m>0?Math.round(h/m*100):null;return I({ok:!0,chosen:{source:o,wasWinner:o===n.best.source,netOut:a.netOut,grossOut:a.grossOut,gasUsd:a.gasUsd,liquidityUsd:a.liquidityUsd??null},liquidity:{chosenUsd:h,maxUsd:m,sharePct:g},priceImpact:n.priceImpact??null,impactUnmeasured:n.impactUnmeasured??[],...i,unsigned:!0,signedBy:"user-wallet",destination:i.artifactKind===z.TRANSACTION?i.transaction?.to??null:i.settlement??null,driftBps:u,warnings:[...p?[p]:[],...n.warnings||[],...i.artifactKind===z.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"})}U();var _a=/^0x[0-9a-fA-F]{40}$/,Ta=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),Ba=100,gt={relay:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:o,taker:a},s)=>{let{relayPrepare:i}=await Promise.resolve().then(()=>(Re(),Be)),c=await i({user:a,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(o)},s);return{transactions:c.transactions||[],amountOut:c.quote?.details?.currencyOut?.amount??null,minOut:c.quote?.details?.currencyOut?.minimumAmount??null,durationSeconds:c.quote?.details?.timeEstimate??null}},lifi:async({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:o,taker:a,isHolder:s},i)=>{let{lifiPrepare:c}=await Promise.resolve().then(()=>(be(),Qe)),u=await c({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:o,fromAddress:a,isHolder:s,feeAction:"bridge"},i);return{transactions:u.transaction?[u.transaction]:[],requiresApproval:u.requiresApproval??null,amountOut:u.quote?.estimate?.toAmount??null,minOut:u.quote?.estimate?.toAmountMin??null,durationSeconds:u.quote?.estimate?.executionDuration??null}}};async function en(e,t={}){let{taker:r,fromChainId:n,toChainId:o}=e;if(!r)throw new Error("prepareBestBridgeRoute requires taker: bridge transactions are built FOR an address, and the quote-only placeholder must never end up in one");if(!_a.test(r))throw new Error(`taker must be a valid 20-byte address, got "${r}"`);if(Ta.has(r.toLowerCase()))throw new Error(`taker "${r}" is a placeholder/burn address. Bridging to it would send funds to an address nobody controls, on a chain where you cannot undo it.`);let a=await Le(e,t);if(!a.best)return{ok:!1,reason:"no source returned a usable bridge route",comparison:a};let s=e.source||a.best.source,i=a.routes.find(f=>f.source===s);if(!i)return{ok:!1,reason:`source "${s}" returned no usable route`,comparison:a};let c=gt[s];if(!c){let f=a.routes.find(b=>gt[b.source]&&b.source!==s);return{ok:!1,reason:`${s} won the comparison but has no bridge prepare path in this build. `+(f?`Next preparable route is ${f.source}; pass source:"${f.source}".`:"No route in this comparison can be prepared."),failureKind:"no-prepare-path",...f?{alternative:f.source}:{},winner:s,comparison:a}}let u;try{u=await c(e,t)}catch(f){let b=typeof f?.body=="string"?f.body:f?.body?JSON.stringify(f.body):"",w=[String(f?.message||f),b].filter(Boolean).join(" :: "),A=/allowance/i.test(w),N=!A&&/not enough|insufficient|balance/i.test(w),k=a.routes.find(_=>gt[_.source]&&_.source!==s);return{ok:!1,reason:A?`${s} will not build calldata until the token approval exists on-chain. Approve first, then prepare again. Underlying: ${w}`:N?`${s} refused to build: ${w}. Quoting works for any address; preparing needs the real funded wallet on chain ${n}.`:`${s} bridge prepare failed: ${w}`,failureKind:A?"approval-required-first":N?"taker-not-funded":"provider-error",...k?{alternative:k.source}:{},comparison:a}}let p=u.transactions||[];if(!p.length)return{ok:!1,reason:`${s} returned no executable transaction for this route`,failureKind:"provider-error",comparison:a};let d=p.filter(f=>f.chainId!=null&&Number(f.chainId)!==Number(n));if(d.length)return{ok:!1,reason:`${s} returned a transaction for chain ${d[0].chainId} but the origin chain is ${n}. Refusing to hand over a mismatched artifact.`,failureKind:"chain-mismatch",comparison:a};let l=e.driftToleranceBps??Ba,m=null,h=null;if(u.amountOut!=null&&i.grossOut!=null)try{let f=BigInt(i.grossOut),b=BigInt(u.amountOut);f>0n&&(m=Number((b-f)*10000n/f),m<-l&&(h=`route moved ${(m/100).toFixed(2)}% against you since the comparison (tolerance ${(l/100).toFixed(2)}%). Re-compare before signing.`))}catch{}let g=[...h?[h]:[],...a.warnings||[],`Bridging is NOT atomic: the origin transaction succeeding does not mean funds arrived on chain ${o}. Expect ~${u.durationSeconds!=null?`${u.durationSeconds}s`:"minutes"} before the destination credits, and do not re-send if it is pending.`];return p.length>1&&g.push(`This route needs ${p.length} transactions signed IN ORDER. Signing only the first leaves funds approved but not bridged.`),I({ok:!0,chosen:{source:s,wasWinner:s===a.best.source,netOut:i.netOut,grossOut:i.grossOut,gasUsd:i.gasUsd},artifactKind:"unsigned-transaction-sequence",fromChainId:Number(n),toChainId:Number(o),transactionCount:p.length,transactions:p,requiresApproval:u.requiresApproval??null,minOut:u.minOut??null,durationSeconds:u.durationSeconds??null,destination:p[0]?.to??null,unsigned:!0,signedBy:"user-wallet",driftBps:m,warnings:g,runnersUp:a.routes.filter(f=>f.source!==s).map(f=>({source:f.source,netOut:f.netOut,gasUsd:f.gasUsd})),comparison:{rankedOn:a.rankedOn,sourcesAnswered:a.sourcesAnswered,sourcesTried:a.sourcesTried,improvementBps:a.improvementBps},note:`UNSIGNED. ${p.length} transaction(s) on chain ${n}, crediting chain ${o}. Verify every destination address before signing.`},{provider:"router",kind:"best-bridge"})}Z();Ce();Z();var wt={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},B=e=>BigInt(e).toString(16).padStart(64,"0"),ue=e=>e.slice(2).toLowerCase().padStart(64,"0");function Ra(e,t){return`0x${wt.getAmountsOut}`+B(e)+B(64)+B(t.length)+t.map(ue).join("")}function Ua(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 o=0;o<r;o++){let a=128+o*64;if(t.length<a+64)return null;n.push(BigInt(`0x${t.slice(a,a+64)}`))}return n}function bt(e,t="router"){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}var Et=100;function $a(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Et)throw new Error(`slippageBps ${r} exceeds the ${Et} 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 tn(e){let{chainId:t,wrappedNative:r}=e;async function n(o,a,s,i){let c=await O(t,"eth_call",[{to:o,data:Ra(a,s)},"latest"],i);return Ua(c?.result??c)}return{async quote({tokenIn:o,tokenOut:a,amountIn:s,path:i},c={}){let u=bt(c.scanner);if(!u)return{chainId:t,evidence:y.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let p=i||[o,a];if(p.some(l=>!/^0x[0-9a-fA-F]{40}$/.test(l||"")))throw new Error("quote requires valid 20-byte addresses");let d=await n(u,s,p,c);return d?{chainId:t,router:u,path:p,amountIn:String(s),amountOut:d[d.length-1].toString(),hops:p.length-1,evidence:y.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:u,path:p,evidence:y.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:o,amountIn:a,base:s},i={}){let c=bt(i.scanner),u=s||r;if(u&&String(o).toLowerCase()===String(u).toLowerCase())return{chainId:t,token:o,verdict:E.UNKNOWN,evidence:y.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||!u)return{chainId:t,token:o,verdict:E.UNKNOWN,evidence:y.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,a,[u,o],i);if(!p)return{chainId:t,token:o,verdict:E.FAIL,evidence:y.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:o,verdict:E.FAIL,evidence:y.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let l=await n(c,d,[o,u],i);if(!l)return{chainId:t,token:o,verdict:E.FAIL,evidence:y.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 m=l[l.length-1],h=Number(m*10000n/BigInt(a)),g=E.PASS,f="round trip completes with expected fee/impact loss";return h<5e3?(g=E.FAIL,f=`round trip returns only ${(h/100).toFixed(2)}% -- punitive tax or no real liquidity`):h<9e3&&(g=E.CAUTION,f=`round trip returns ${(h/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:o,base:u,router:c,verdict:g,reason:f,amountIn:String(a),bought:d.toString(),returned:m.toString(),retentionBps:h,evidence:y.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:i,slippageBps:c=50,deadlineSeconds:u=900,path:p},d={}){let l=d.scanner,m=bt(l);if(!m)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(i||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let h=p||[o,a],g=await this.quote({tokenIn:o,tokenOut:a,amountIn:s,path:h},d);if(g.evidence!==y.LIVE)throw new Error(`cannot prepare without a live quote (${g.evidence}: ${g.reason??"no reason given"})`);let f=$a(g.amountOut,c);if(f<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=BigInt(Math.floor(Date.now()/1e3)+Number(u)),w=r&&h[0].toLowerCase()===r.toLowerCase()&&d.useNative,A=w?`0x${wt.swapExactETHForTokens}`+B(f)+B(128)+ue(i)+B(b)+B(h.length)+h.map(ue).join(""):`0x${wt.swapExactTokensForTokens}`+B(s)+B(f)+B(160)+ue(i)+B(b)+B(h.length)+h.map(ue).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:m,data:A,value:w?`0x${BigInt(s).toString(16)}`:"0x0"},guard:{quotedOut:g.amountOut,minOut:f.toString(),slippageBps:c,maxSlippageBps:Et,deadline:b.toString()},requires:w?[]:[{step:"approve",token:h[0],spender:m,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."}}}}Z();var La=[100,500,3e3,1e4],rn={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},X=e=>BigInt(e).toString(16).padStart(64,"0"),le=e=>e.slice(2).toLowerCase().padStart(64,"0"),nn=/^0x[0-9a-fA-F]{40}$/,At=100;function Da(e,t){let r=Number(t);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>At)throw new Error(`slippageBps ${r} exceeds the ${At} 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 yt(e,t){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function on(e){let{chainId:t,wrappedNative:r}=e;async function n({quoter:a,tokenIn:s,tokenOut:i,amountIn:c,fee:u},p){let d=`0x${rn.quoteExactInputSingle}`+le(s)+le(i)+X(c)+X(u)+X(0),l=await O(t,"eth_call",[{to:a,data:d},"latest"],p).catch(()=>null),m=l?.result??l;if(!m||m==="0x"||m.length<66)return null;let h=BigInt(`0x${m.slice(2,66)}`);return h>0n?h:null}async function o({quoter:a,tokenIn:s,tokenOut:i,amountIn:c},u){let p=[],d=null;for(let l of La){let m=await n({quoter:a,tokenIn:s,tokenOut:i,amountIn:c,fee:l},u);p.push({fee:l,amountOut:m?m.toString():null}),m&&(!d||m>d.amountOut)&&(d={fee:l,amountOut:m})}return{best:d,tried:p}}return{async quote({tokenIn:a,tokenOut:s,amountIn:i},c={}){let u=yt(c.scanner,"quoter");if(!u)return{chainId:t,evidence:y.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let l of[a,s])if(!nn.test(l||""))throw new Error("quote requires valid 20-byte addresses");let{best:p,tried:d}=await o({quoter:u,tokenIn:a,tokenOut:s,amountIn:i},c);return p?{chainId:t,venue:"uniswap-v3",quoter:u,tokenIn:a,tokenOut:s,amountIn:String(i),amountOut:p.amountOut.toString(),fee:p.fee,triedFeeTiers:d,evidence:y.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:u,tokenIn:a,tokenOut:s,triedFeeTiers:d,evidence:y.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:a,amountIn:s,base:i},c={}){let u=yt(c.scanner,"quoter"),p=i||r;if(p&&String(a).toLowerCase()===String(p).toLowerCase())return{chainId:t,token:a,verdict:E.UNKNOWN,evidence:y.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||!p)return{chainId:t,token:a,verdict:E.UNKNOWN,evidence:y.UNAVAILABLE,reason:u?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let d=await o({quoter:u,tokenIn:p,tokenOut:a,amountIn:s},c);if(!d.best)return{chainId:t,token:a,verdict:E.FAIL,evidence:y.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier"};let l=await o({quoter:u,tokenIn:a,tokenOut:p,amountIn:d.best.amountOut},c);if(!l.best)return{chainId:t,token:a,verdict:E.FAIL,evidence:y.LIVE,leg:"sell",bought:d.best.amountOut.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let m=l.best.amountOut,h=Number(m*10000n/BigInt(s)),g=E.PASS,f="round trip completes with expected fee/impact loss";return h<5e3?(g=E.FAIL,f=`round trip returns only ${(h/100).toFixed(2)}% -- punitive tax or no real liquidity`):h<9e3&&(g=E.CAUTION,f=`round trip returns ${(h/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:a,base:p,verdict:g,reason:f,amountIn:String(s),bought:d.best.amountOut.toString(),returned:m.toString(),retentionBps:h,buyFee:d.best.fee,sellFee:l.best.fee,evidence:y.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:a,tokenOut:s,amountIn:i,recipient:c,slippageBps:u=50,fee:p},d={}){let l=yt(d.scanner,"router");if(!l)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(!nn.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let m=await this.quote({tokenIn:a,tokenOut:s,amountIn:i},d);if(m.evidence!==y.LIVE)throw new Error(`cannot prepare without a live quote (${m.evidence}: ${m.reason??"no reason given"})`);let h=p??m.fee,g=Da(m.amountOut,u);if(g<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let f=`0x${rn.exactInputSingle}`+le(a)+le(s)+X(h)+le(c)+X(i)+X(g)+X(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:l,data:f,value:"0x0"},guard:{quotedOut:m.amountOut,minOut:g.toString(),slippageBps:u,maxSlippageBps:At,fee:h},requires:[{step:"approve",token:a,spender:l,amount:String(i)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var De={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function an(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function sn(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 o=t.slice(128,128+n*2),a=Buffer.from(o,"hex").toString("utf8").replace(/\0+$/,"");if(a)return a}}return Buffer.from(t.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function Fa(e){let{chainId:t}=e;async function r(n,o,a){return O(t,"eth_call",[{to:n,data:o},"latest"],a)}return{async blockNumber(n={}){let o=await Ir(t,n);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:y.LIVE}},async nativeBalance(n,o={}){let a=await Cr(t,n,o);return{chainId:t,address:n,wei:a?.wei??a?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:y.LIVE}},async tokenBalance({token:n,owner:o},a={}){let s=await kr({chainId:t,token:n,owner:o},a);return{chainId:t,token:n,owner:o,raw:s?.balance??s,evidence:y.LIVE}},async resolveToken(n,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:t,token:n,evidence:y.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[a,s,i,c]=await Promise.all([r(n,De.decimals,o).catch(()=>null),r(n,De.symbol,o).catch(()=>null),r(n,De.name,o).catch(()=>null),r(n,De.totalSupply,o).catch(()=>null)]),u=an(a?.result??a),p=u!==null||s?.result||i?.result;return{chainId:t,address:n,decimals:u===null?null:Number(u),symbol:sn(s?.result??s),name:sn(i?.result??i),totalSupply:(an(c?.result??c)??null)?.toString()??null,evidence:p?y.LIVE:y.UNKNOWN,warning:p?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(n,o={}){let a=e.dexscreenerSlug;if(!a)return{chainId:t,token:n,pools:[],evidence:y.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let s=await it(n,o).catch(()=>null),c=(s?.pairs||s?.data?.pairs||[]).filter(u=>String(u.chainId).toLowerCase()===String(a).toLowerCase()).map(u=>({pair:u.pairAddress,dex:u.dexId,base:u.baseToken?.address,quote:u.quoteToken?.address,liquidityUsd:u.liquidity?.usd??null,priceUsd:u.priceUsd??null,volume24hUsd:u.volume?.h24??null,createdAt:u.pairCreatedAt??null})).sort((u,p)=>(p.liquidityUsd??0)-(u.liquidityUsd??0));return{chainId:t,token:n,pools:c,evidence:c.length?y.LIVE:y.UNKNOWN}},async scanBlocks({fromBlock:n,toBlock:o,address:a,topics:s,chunkSize:i=2e3}={},c={}){if(!Number.isInteger(n)||!Number.isInteger(o))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(o<n)throw new Error("toBlock must be >= fromBlock");let u=[],p=[];for(let d=n;d<=o;d+=i){let l=Math.min(d+i-1,o);p.push([d,l])}for(let[d,l]of p){let m={fromBlock:`0x${d.toString(16)}`,toBlock:`0x${l.toString(16)}`};a&&(m.address=a),s&&(m.topics=s);let h=await O(t,"eth_getLogs",[m],c).catch(g=>({error:String(g?.message||g)}));if(h?.error)return{chainId:t,fromBlock:n,toBlock:o,logs:u,complete:!1,failedAt:[d,l],error:h.error,evidence:y.UNKNOWN};for(let g of h?.result??h??[])u.push(g)}return{chainId:t,fromBlock:n,toBlock:o,logs:u,complete:!0,chunks:p.length,evidence:y.LIVE}},async scoreRisk(n,o={}){let a=[],s=E.PASS,i=p=>{let d={[E.PASS]:0,[E.CAUTION]:1,[E.UNKNOWN]:2,[E.FAIL]:3};d[p]>d[s]&&(s=p)},c=await this.resolveToken(n,o);c.evidence!==y.LIVE?(a.push({check:"erc20-metadata",result:E.UNKNOWN,detail:c.warning}),i(E.UNKNOWN)):a.push({check:"erc20-metadata",result:E.PASS,detail:`${c.symbol} / ${c.decimals}d`});let u=await this.resolvePools(n,o);if(u.evidence===y.UNAVAILABLE)a.push({check:"liquidity",result:E.UNKNOWN,detail:u.reason}),i(E.UNKNOWN);else if(!u.pools.length)a.push({check:"liquidity",result:E.FAIL,detail:"no pool with liquidity found"}),i(E.FAIL);else{let p=u.pools[0],d=p.liquidityUsd??0;d<5e3?(a.push({check:"liquidity",result:E.CAUTION,detail:`top pool only $${d}`}),i(E.CAUTION)):a.push({check:"liquidity",result:E.PASS,detail:`$${d} on ${p.dex}`}),p.createdAt&&Date.now()-p.createdAt<24*3600*1e3&&(a.push({check:"age",result:E.CAUTION,detail:"pool under 24h old"}),i(E.CAUTION))}if(typeof this.sellSimulation=="function"){let p=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},o).catch(d=>({verdict:E.UNKNOWN,reason:String(d?.message||d)}));a.push({check:"sellability",result:p.verdict,detail:p.retentionBps!=null?`round trip returns ${(p.retentionBps/100).toFixed(2)}% -- ${p.reason}`:p.reason}),i(p.verdict)}else a.push({check:"sellability",result:E.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."}),i(E.UNKNOWN);return{chainId:t,token:n,verdict:s,checks:a,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function cn(e){let r={...Fa(e)},n=new Set((e.venues||[]).map(a=>a.kind));e.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,on({chainId:e.chainId,wrappedNative:e.wrappedNative})):e.venueKind==="uniswap-v2"&&n.has("router")&&Object.assign(r,tn({chainId:e.chainId,wrappedNative:e.wrappedNative}));let o={};for(let[a,s]of Object.entries(r))o[a]=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:o}}var Pa=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",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",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",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",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",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",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",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",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 un(){return Pa.map(e=>xt(cn(e)))}un();var[ln,...Pe]=process.argv.slice(2),Fe=Pe.includes("--json"),v=Pe.filter(e=>e!=="--json"),dn="0x0000000000000000000000000000000000000000";function ee(e){e||te("missing <chain>");let t=Number(e);if(pe(t))return t;let r=Me().find(n=>n.key===String(e).toLowerCase());if(r)return r.chainId;te(`unknown chain "${e}". Known: ${Me().map(n=>n.key).join(", ")}`)}function te(e){console.error(`error: ${e}`),process.exit(1)}function pn(e,t){return(Number(e)/10**t).toLocaleString(void 0,{maximumFractionDigits:6})}function mn(e,t){if(console.log(`sources: ${e.sourcesAnswered}/${e.sourcesTried} answered`),console.log(`ranked on: ${e.rankedOn}
6
+ `),!e.routes.length){console.log("no source returned a usable route.");for(let n of e.failed)console.log(` ${n.source}: ${n.error}`);return}let r=Math.max(...e.routes.map(n=>n.source.length),6);console.log(` ${"source".padEnd(r)} ${"net out".padStart(14)} ${"gross".padStart(14)} cost`);for(let[n,o]of e.routes.entries()){let a=n===0?"*":" ",s=o.gasUsd==null?"gas unknown":o.gasUsd===0?"gasless (solver)":`$${Number(o.gasUsd+(o.feeUsd??0)).toFixed(2)}`,i=o.meta?.durationSeconds!=null?` ~${o.meta.durationSeconds}s`:"";console.log(`${a} ${o.source.padEnd(r)} ${pn(o.netOut,t).padStart(14)} ${pn(o.grossOut,t).padStart(14)} ${s}${i}`)}for(let n of e.failed)console.log(` ${n.source.padEnd(r)} FAILED: ${String(n.error).slice(0,60)}`);console.log(`
7
7
  ${e.note}`);for(let n of e.warnings)console.log(`
8
- WARNING: ${n}`)}try{switch(tn){case"swap":{let e=G(y[0]);(!y[1]||!y[2])&&Y("usage: oracle-route swap <chain> <tokenIn> <tokenOut> [amountIn]");let t=y[3]||(10n**18n).toString(),r=se(e),[n,o]=await Promise.all([r.resolveToken(y[1]).then(s=>s.decimals).catch(()=>null),r.resolveToken(y[2]).then(s=>s.decimals).catch(()=>null)]),a=await Oe({chainId:e,tokenIn:y[1],tokenOut:y[2],amountIn:t,taker:y[4]||"0x000000000000000000000000000000000000dEaD",decimalsIn:n,decimalsOut:o});Te?process.stdout.write(`${JSON.stringify(a,null,2)}
9
- `):on(a,o??18);break}case"bridge":{let e=G(y[0]),t=G(y[1]),r=y[2]||rn,n=y[3]||(10n**18n).toString(),o=await Ne({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:r,amountIn:n,taker:y[4]||"0x000000000000000000000000000000000000dEaD",decimalsOut:18});Te?process.stdout.write(`${JSON.stringify(o,null,2)}
10
- `):on(o,18);break}case"prepare":{let e=G(y[0]);(!y[1]||!y[2]||!y[3])&&Y("usage: oracle-route prepare <chain> <tokenIn> <tokenOut> <taker> [amountIn] [--source=X]");let t=y[3],r=y[4]||(10n**18n).toString(),n=Re.find(c=>c.startsWith("--source=")),o=se(e),[a,s]=await Promise.all([o.resolveToken(y[1]).then(c=>c.decimals).catch(()=>null),o.resolveToken(y[2]).then(c=>c.decimals).catch(()=>null)]),i=await jr({chainId:e,tokenIn:y[1],tokenOut:y[2],amountIn:r,taker:t,decimalsIn:a,decimalsOut:s,source:n?n.split("=")[1]:void 0});if(Te){process.stdout.write(`${JSON.stringify(i,null,2)}
8
+ WARNING: ${n}`)}try{switch(ln){case"swap":{let e=ee(v[0]);(!v[1]||!v[2])&&te("usage: oracle-route swap <chain> <tokenIn> <tokenOut> [amountIn]");let t=v[3]||(10n**18n).toString(),r=pe(e),[n,o]=await Promise.all([r.resolveToken(v[1]).then(s=>s.decimals).catch(()=>null),r.resolveToken(v[2]).then(s=>s.decimals).catch(()=>null)]),a=await $e({chainId:e,tokenIn:v[1],tokenOut:v[2],amountIn:t,taker:v[4]||"0x000000000000000000000000000000000000dEaD",decimalsIn:n,decimalsOut:o});Fe?process.stdout.write(`${JSON.stringify(a,null,2)}
9
+ `):mn(a,o??18);break}case"bridge":{let e=ee(v[0]),t=ee(v[1]),r=v[2]||dn,n=v[3]||(10n**18n).toString(),o=await Le({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:r,amountIn:n,taker:v[4]||"0x000000000000000000000000000000000000dEaD",decimalsOut:18});Fe?process.stdout.write(`${JSON.stringify(o,null,2)}
10
+ `):mn(o,18);break}case"prepare":{let e=ee(v[0]);(!v[1]||!v[2]||!v[3])&&te("usage: oracle-route prepare <chain> <tokenIn> <tokenOut> <taker> [amountIn] [--source=X]");let t=v[3],r=v[4]||(10n**18n).toString(),n=Pe.find(c=>c.startsWith("--source=")),o=pe(e),[a,s]=await Promise.all([o.resolveToken(v[1]).then(c=>c.decimals).catch(()=>null),o.resolveToken(v[2]).then(c=>c.decimals).catch(()=>null)]),i=await Zr({chainId:e,tokenIn:v[1],tokenOut:v[2],amountIn:r,taker:t,decimalsIn:a,decimalsOut:s,source:n?n.split("=")[1]:void 0});if(Fe){process.stdout.write(`${JSON.stringify(i,null,2)}
11
11
  `);break}i.ok||(console.log(`could not prepare: ${i.reason}`),i.failureKind&&console.log(`kind: ${i.failureKind}`),i.alternative&&console.log(`try: --source=${i.alternative}`),process.exit(1)),console.log(`source: ${i.chosen.source}${i.chosen.wasWinner?" (winner)":" (override -- NOT the winner)"}`),console.log(`artifact: ${i.artifactKind}`),console.log(`destination: ${i.destination}`),i.minOut&&console.log(`minOut: ${i.minOut}`),i.driftBps!=null&&console.log(`drift: ${(i.driftBps/100).toFixed(3)}% vs comparison`),i.requiresApproval&&(console.log(`
12
12
  approval required first:`),console.log(` token ${i.requiresApproval.token}`),console.log(` spender ${i.requiresApproval.spender}`),i.requiresApproval.note&&console.log(` note ${i.requiresApproval.note}`)),i.runnersUp?.length&&console.log(`
13
13
  runners-up: ${i.runnersUp.map(c=>c.source).join(", ")}`);for(let c of i.warnings)console.log(`
14
14
  WARNING: ${c}`);console.log(`
15
- ${i.note}`);break}case"prepare-bridge":{let e=G(y[0]),t=G(y[1]);y[2]||Y("usage: oracle-route prepare-bridge <fromChain> <toChain> <taker> [token] [amountIn] [--source=X]");let r=y[2],n=y[3]||rn,o=y[4]||(10n**17n).toString(),a=Re.find(i=>i.startsWith("--source=")),s=await Kr({fromChainId:e,toChainId:t,tokenIn:n,tokenOut:n,amountIn:o,taker:r,decimalsOut:18,source:a?a.split("=")[1]:void 0});if(Te){process.stdout.write(`${JSON.stringify(s,null,2)}
15
+ ${i.note}`);break}case"prepare-bridge":{let e=ee(v[0]),t=ee(v[1]);v[2]||te("usage: oracle-route prepare-bridge <fromChain> <toChain> <taker> [token] [amountIn] [--source=X]");let r=v[2],n=v[3]||dn,o=v[4]||(10n**17n).toString(),a=Pe.find(i=>i.startsWith("--source=")),s=await en({fromChainId:e,toChainId:t,tokenIn:n,tokenOut:n,amountIn:o,taker:r,decimalsOut:18,source:a?a.split("=")[1]:void 0});if(Fe){process.stdout.write(`${JSON.stringify(s,null,2)}
16
16
  `);break}s.ok||(console.log(`could not prepare: ${s.reason}`),s.failureKind&&console.log(`kind: ${s.failureKind}`),s.alternative&&console.log(`try: --source=${s.alternative}`),process.exit(1)),console.log(`source: ${s.chosen.source}${s.chosen.wasWinner?" (winner)":" (override -- NOT the winner)"}`),console.log(`artifact: ${s.artifactKind}`),console.log(`route: chain ${s.fromChainId} -> chain ${s.toChainId}`),console.log(`signs: ${s.transactionCount} transaction(s) on chain ${s.fromChainId}`),console.log(`destination: ${s.destination}`),s.minOut&&console.log(`minOut: ${s.minOut}`),s.durationSeconds!=null&&console.log(`eta: ~${s.durationSeconds}s to credit`),s.driftBps!=null&&console.log(`drift: ${(s.driftBps/100).toFixed(3)}% vs comparison`),s.requiresApproval&&(console.log(`
17
17
  approval required first:`),console.log(` token ${s.requiresApproval.token}`),console.log(` spender ${s.requiresApproval.spender}`)),s.transactions.forEach((i,c)=>{console.log(`
18
18
  tx ${c+1}/${s.transactionCount}: chain ${i.chainId} -> ${i.to}`)}),s.runnersUp?.length&&console.log(`
19
19
  runners-up: ${s.runnersUp.map(i=>i.source).join(", ")}`);for(let i of s.warnings)console.log(`
20
20
  WARNING: ${i}`);console.log(`
21
21
  ${s.note}`);break}default:console.log(["oracle-route -- best-execution routing",""," oracle-route swap <chain> <tokenIn> <tokenOut> [amountIn] [taker]"," oracle-route bridge <fromChain> <toChain> [token] [amountIn] [taker]"," oracle-route prepare <chain> <tokenIn> <tokenOut> <taker> [amountIn] [--source=X]"," oracle-route prepare-bridge <fromChain> <toChain> <taker> [token] [amt] [--source=X]",""," Ranks by NET output (gross minus gas and fees), not headline quote."," A route quoting more but costing more gas can lose. --json for detail."].join(`
22
- `)),process.exit(tn?1:0)}}catch(e){Y(String(e?.message||e))}
22
+ `)),process.exit(ln?1:0)}}catch(e){te(String(e?.message||e))}