@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,2 +1,2 @@
1
- var at=Object.defineProperty;var O=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var it=(e,t)=>{for(var r in t)at(e,r,{get:t[r],enumerable:!0})};import{createHash as st}from"node:crypto";function pt(e){let t=String(e||"").toLowerCase();return me.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function dt(e){let t={};for(let[r,n]of Object.entries(e||{}))pt(r)||(t[r]=n);return t}function mt(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 ft(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function ht(e,t,r){let n={};for(let[c,p]of Object.entries(r||{}))n[c.toLowerCase()]=p;let o=Object.keys(n).filter(c=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(c)),a=[...new Set([...me,...o])].sort().map(c=>`${c}=${n[c]??""}`).join(`
2
- `),s=st("sha256").update(a).digest("hex").slice(0,32);return`${e} ${t} ${s}`}function wt(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,pe):Math.min(250*2**e,pe)+Math.floor(Math.random()*100)}async function bt(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:i}){let a=new AbortController,s=setTimeout(()=>a.abort(),i);try{let c=String(e),p={...n||{}};for(let d=0;d<=de;d+=1){let l=await t(c,{method:r,headers:p,body:o,signal:a.signal,redirect:"manual"}),u=await l.text(),m=null;if(u)try{m=JSON.parse(u)}catch{m=null}if(lt.has(l.status)){if(r!=="GET"&&r!=="HEAD"){let h=new Error(`HTTP ${l.status} ${r} ${c} redirected non-idempotent request`);throw h.status=l.status,h.body=m??u.slice(0,300),h}if(d===de)throw new Error(`HTTP redirect loop for ${e}`);let f=mt(l.headers?.get?.("location"),c);ft(f,c)||(p=dt(p)),c=f;continue}if(!l.ok){let f=new Error(`HTTP ${l.status} ${r} ${c}`);throw f.status=l.status,f.retryAfter=l.headers?.get?.("retry-after")??null,f.body=m??u.slice(0,300),f}return m??u}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(s)}}async function b(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(),i={Accept:"application/json",...t.headers||{}},a=t.body;a!=null&&typeof a!="string"&&(i["Content-Type"]=i["Content-Type"]||"application/json",a=JSON.stringify(a));let s=Number.isInteger(t.retries)?Math.max(t.retries,0):ut,c=async()=>{let m;for(let f=0;f<=s;f++)try{return await bt(e,{fetchImpl:r,method:o,headers:i,body:a,timeoutMs:n})}catch(h){m=h;let w=h?.status,g=h?.name==="AbortError",P=new Set([408,425,429]),_=w!=null?P.has(w)||ct.has(w)&&le.has(o):!g&&le.has(o);if(f===s||!_)throw h;await gt(wt(f,h?.retryAfter))}throw m};if(!(t.dedupe!==!1&&o==="GET"&&a==null))return c();let d=ht(o,e,i),l=X.get(d);if(l)return l;let u=c().finally(()=>X.delete(d));return X.set(d,u),u}var ct,le,ut,pe,me,lt,de,X,gt,y=O(()=>{ct=new Set([408,425,429,500,502,503,504]),le=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),ut=2,pe=4e3,me=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],lt=new Set([301,302,303,307,308]),de=3;X=new Map;gt=e=>new Promise(t=>setTimeout(t,e))});import{readFileSync as Et}from"node:fs";import{homedir as At}from"node:os";import{join as F}from"node:path";function xt(){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=At();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||F(t,".config","oracle")).trim();return[e,F(r,"exec.env")].filter(Boolean)}return[e,F(t,".config","oracle","exec.env"),F(t,".config","mad-desk","exec.env")].filter(Boolean)}function fe(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of xt())try{let i=Et(o,"utf8"),a=i.match(new RegExp(`^${t}=(.*)$`,"m"))||i.match(new RegExp(`^${r}=(.*)$`,"m"));if(a&&(n=a[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}var he=O(()=>{});var we=O(()=>{});import{createHash as yt,createHmac as St,timingSafeEqual as nn}from"node:crypto";function W(e){return Array.isArray(e)?`[${e.map(W).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${W(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function It(e,{required:t=!1}={}){try{return fe(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function Ee(e){let{signature:t,...r}=e;return r}function Ae(e,{secret:t}={}){let r=It(t);return r?{...e,signature:St("sha256",r).update(W(Ee(e))).digest("hex")}:e}function Ct(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 yt("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 Ae({...Ee(e),calldataHash:Ct(n)},{secret:o})}function Q(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function vt(e){let t=e==null?ge: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,ge)}function S({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:o}={}){let i=Q(e,0),a=i>0?i>=25e4?5:i>=1e5?10:i>=5e4?20:i>=1e4?40:70:n?30:10,s=Math.min(60,Math.abs(Q(t,0))*2),c=Math.min(40,Math.floor(Math.max(0,Q(r,0))/5e3)*5),p=Math.max(25,Math.ceil(20+a+s+c)),d=vt(o);return{mode:"auto",requiredBps:p,selectedBps:Math.min(p,d),capBps:d,executable:p<=d}}function kt({chainId:e,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:o=0,quoteAgeMs:i=0,crossChain:a=!1,requestedCapBps:s,quotedAtMs:c=Date.now(),ttlMs:p=be,secret:d}={}){let l=BigInt(r??0);if(l<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let u=S({liquidityUsd:n,priceChange5m:o,quoteAgeMs:i,crossChain:a,requestedCapBps:s});if(!u.executable)throw new Error(`auto-slippage requires ${u.requiredBps} bps above hard/requested cap ${u.capBps}; route blocked`);let 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(p)||be)),h=l*BigInt(1e4-u.selectedBps),w=h/10000n;if(h%10000n!==0n&&(w+=1n),w>l&&(w=l),l>0n&&w<=0n)throw new Error(`auto-slippage: quote ${l} is too small to express a ${u.selectedBps} bps floor without rounding to zero`);let g=Number((l-w)*10000n/(l===0n?1n:l));if(g>u.capBps)throw new Error(`auto-slippage: realised floor implies ${g} bps, above cap ${u.capBps} \u2014 refusing to issue a guard weaker than advertised`);return Ae({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:l.toString(),minAmountOut:w.toString(),requiredBps:u.requiredBps,selectedBps:u.selectedBps,capBps:u.capBps,quotedAtMs:m,expiresAtMs:m+f},{secret:d})}function E(e,{chainId:t,venue:r,amountOut:n,liquidityUsd:o,priceChange5m:i,crossChain:a,requestedCapBps:s,quotedAtMs:c=Date.now(),ttlMs:p}={}){let d=kt({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:o,priceChange5m:i,crossChain:a,requestedCapBps:s,quotedAtMs:c,ttlMs:p});return{...e,autoSlippage:d,amountOutMinimum:d.minAmountOut}}var ge,be,I=O(()=>{he();we();ge=100,be=2e4});function xe(e){let t=String(e||"").trim();return/^0x[0-9a-fA-F]{40}$/.test(t)?t:T}var T,U=O(()=>{T="0x000000000000000000000000000000000000dEaD"});import{createHash as _t,createHmac as Ot,timingSafeEqual as ln}from"node:crypto";function J(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(J).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${J(e[r])}`).join(",")}}`}function ye(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Se(e=process.env){return ye(process.env)||ye(e)}function Nt(e){let{oraclePrepared:t,prepareHash:r,prepareMac:n,note:o,...i}=e||{};return i}function Bt(e){let t=Nt(e);return _t("sha256").update(J(t)).digest("hex")}function Lt(e,t=Se()){return t?Ot("sha256",t).update(String(e)).digest("hex"):""}function C(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 i=Date.now(),a=i+Tt,c={...o,preparedAt:i,expiresAt:a,prepareVersion:Rt},p=Bt(c),d=Se(n),l=d?Lt(p,d):void 0,u={...c,oraclePrepared:!0,prepareHash:p};return l&&(u.prepareMac=l),u}var Rt,Tt,pn,v=O(()=>{Rt=2,Tt=300*1e3,pn=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});var re={};it(re,{ACROSS_API:()=>We,HOP_API:()=>Je,RELAY_API:()=>Ze,acrossHealth:()=>Pr,acrossSuggestedFees:()=>et,hopHealth:()=>$r,hopQuote:()=>tt,relayHealth:()=>Dr,relayPrepare:()=>Fr,relayQuote:()=>te});async function Pr(e={}){try{return{ok:!0,estimatedFillTimeSec:(await et({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 et(e={},t={}){let{token:r,destinationToken:n=r,originChainId:o,destinationChainId:i,amount:a}=e;if(!r||o==null||i==null||!a)throw new Error("acrossSuggestedFees requires token, originChainId, destinationChainId, amount");let s=new URLSearchParams({token:r,destinationToken:n,originChainId:String(o),destinationChainId:String(i),amount:String(a)}),c=(t.baseUrl||process.env.ACROSS_API_URL||We).replace(/\/$/,"");return b(`${c}/suggested-fees?${s}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function $r(e={}){try{let t=await tt({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 tt(e={},t={}){let{amount:r,token:n="ETH",fromChain:o="ethereum",toChain:i="arbitrum"}=e;if(!r)throw new Error("hopQuote requires amount");let a=e.slippage==null?void 0:Math.round(Number(e.slippage)*100),s=S({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:o!==i,requestedCapBps:e.maxSlippageBps??e.slippageBps??a});if(!s.executable)throw new Error(`hop: route requires ${s.requiredBps} bps above cap ${s.capBps}`);let c=new URLSearchParams({amount:String(r),token:n,fromChain:o,toChain:i,slippage:String(s.selectedBps/100)}),p=(t.baseUrl||process.env.HOP_API_URL||Je).replace(/\/$/,""),d=await b(`${p}/quote?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),l=d?.estimatedRecieved||d?.estimatedReceived;return l?E(d,{chainId:Number(e.originChainId||e.chainId||Lr[o]||0),venue:d?.tx?.to||"hop",amountOut:l,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:o!==i,requestedCapBps:e.maxSlippageBps??e.slippageBps??a}):{...d,autoSlippagePolicy:s}}async function Dr(e={}){try{let t=await te({user:T,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 te(e={},t={}){let{user:r=T,originChainId:n,destinationChainId:o,originCurrency:i="0x0000000000000000000000000000000000000000",destinationCurrency:a="0x0000000000000000000000000000000000000000",amount:s,tradeType:c="EXACT_INPUT"}=e;if(n==null||o==null||!s)throw new Error("relayQuote requires originChainId, destinationChainId, amount");let p=S({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(o),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!p.executable)throw new Error(`relay: route requires ${p.requiredBps} bps above cap ${p.capBps}`);let d=(t.baseUrl||process.env.RELAY_API_URL||Ze).replace(/\/$/,""),l=await b(`${d}/quote`,{method:"POST",body:{user:r,originChainId:Number(n),destinationChainId:Number(o),originCurrency:i,destinationCurrency:a,amount:String(s),tradeType:c,slippageTolerance:String(p.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),u=l?.details?.currencyOut?.amount;return!u||!/^\d+$/.test(String(u))?{...l,autoSlippagePolicy:p}:E(l,{chainId:Number(n),venue:l?.steps?.[0]?.items?.[0]?.data?.to||"relay",amountOut:u,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(o),requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Fr(e={},t={}){let r=await te(e,t),n=Number(e.originChainId),o=(r.steps||[]).flatMap(s=>(s.items||[]).filter(c=>c?.data?.to&&c?.data?.data).map(c=>({stepId:s.id,...c.data})));if(!o.length)throw new Error("relay: quote returned no executable transaction items");let i=String(r?.autoSlippage?.venue||"").toLowerCase();if(o.some(s=>String(s.to).toLowerCase()!==i))throw new Error("relay: route includes a separate approval/transaction that is not yet safely bound");let a=o.map(s=>({chainId:n,from:s.from||e.user,to:s.to,data:s.data,value:s.value??"0x0",...s.gasLimit!=null||s.gas!=null?{gasLimit:s.gasLimit??s.gas}:{},slippageGuard:R(r.autoSlippage,{chainId:n,venue:s.to,data:s.data})}));return C({provider:"relay",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:r,autoSlippage:r.autoSlippage,transactions:a},{provider:"relay",kind:"relay-tx"})}var We,Je,Ze,Lr,ne=O(()=>{y();I();U();v();We="https://across.to/api",Je="https://api.hop.exchange/v1",Ze="https://api.relay.link",Lr={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453}});var Hr=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),qr=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),Vr=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"});var A=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"}),se={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"},$=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}};function ie(e){let{source:t,amountOut:r,minOut:n=null,gasUsd:o=null,feeUsd:i=null,estimatedGas:a=null,error:s=null,executionReady:c=!1,meta:p={}}=e||{};if(s||r==null)return{source:t,quality:A.FAILED,amountOut:null,error:s||"no amountOut returned"};let d=$(r);return d==null||d<=0n?{source:t,quality:A.FAILED,amountOut:null,error:"non-positive amountOut"}:{source:t,quality:o==null?A.NO_GAS:A.FULL,amountOut:d.toString(),minOut:$(n)?.toString()??null,gasUsd:o,feeUsd:i,estimatedGas:a==null?null:String(a),executionReady:c,meta:p}}async function ce(e,t,{divisor:r=1000n}={}){let n=$(t);if(n==null||n<=0n)return null;let o=n/r>0n?n/r:1n;if(o>=n)return null;let i,a;try{[i,a]=await Promise.all([e(o),e(n)])}catch{return null}let s=$(i),c=$(a);if(s==null||c==null||s<=0n)return null;let p=Number(s)/Number(o),d=Number(c)/Number(n);return!Number.isFinite(p)||!Number.isFinite(d)||p<=0?null:{impactPct:(1-d/p)*100,probeAmountIn:o.toString(),probeAmountOut:s.toString(),fullAmountOut:c.toString()}}function ue(e,t,{maxImpactPct:r=25}={}){let n=[],o=[],i=(e.routes??[]).filter(s=>{let c=t?.[s.source];return c?c.impactPct>r?(n.push({source:s.source,impactPct:Number(c.impactPct.toFixed(2)),reason:`price impact ${c.impactPct.toFixed(1)}% exceeds ${r}% ceiling -- the venue cannot absorb this size near the quoted price`}),!1):!0:(o.push(s.source),!0)}),a=[...e.warnings??[]];return n.length&&a.push(`dropped ${n.length} route(s) on price impact: `+n.map(s=>`${s.source} (${s.impactPct}%)`).join(", ")),o.length&&a.push(`price impact NOT measured for: ${o.join(", ")}. These are unproven against thin liquidity, not proven safe.`),{...e,routes:i,best:i[0]??null,impactRejected:n,impactUnmeasured:o,warnings:a}}function K(e,{destPriceUsd:t=null,destDecimals:r=null}={}){let n=e.filter(l=>l.quality!==A.FAILED),o=e.filter(l=>l.quality===A.FAILED),i=t!=null&&t>0&&r!=null&&r>=0,a=n.map(l=>{let u=BigInt(l.amountOut),m=0n,f=!1;if(i){let w=(l.gasUsd??0)+(l.feeUsd??0);if(w>0){let g=w/t*10**r;Number.isFinite(g)&&g>=0&&(m=BigInt(Math.floor(g)),f=!0)}else l.gasUsd===0&&(f=!0)}let h=u>m?u-m:0n;return{...l,grossOut:u.toString(),netOut:h.toString(),costInDest:m.toString(),costAccounted:f}});a.sort((l,u)=>BigInt(u.netOut)>BigInt(l.netOut)?1:-1);let s=a.filter(l=>!l.costAccounted).map(l=>l.source),c=[];i?s.length&&c.push(`gas not reported by: ${s.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 p=null,d=null;if(a.length>=2&&a[0].costAccounted&&a[1].costAccounted){let l=BigInt(a[0].netOut),u=BigInt(a[1].netOut);u>0n&&(p=Number((l-u)*10000n/u),d=`${a[0].source} vs ${a[1].source}`)}return{best:a[0]??null,routes:a,failed:o,improvementBps:p,spreadBasis:d,rankedOn:i?"net-of-cost":"gross",warnings:c}}async function D(e,{timeoutMs:t=12e3}={}){let r=(o,i)=>Promise.race([o,new Promise((a,s)=>setTimeout(()=>s(new Error(`${i}: timeout`)),t))]);return(await Promise.allSettled(e.map(o=>r(Promise.resolve().then(o.run),o.source)))).map((o,i)=>{let a=e[i].source;return o.status==="rejected"?ie({source:a,error:String(o.reason?.message||o.reason)}):ie({source:a,...o.value})})}y();I();U();v();import{Contract as Pt,JsonRpcProvider as $t}from"ethers";var Dt="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",Ft=999,Ut="https://rpc.hyperliquid.xyz/evm",Mt=["function balanceOf(address owner) view returns (uint256)"],Ht=/^0x[a-fA-F0-9]{40}$/;function qt(e){return Ht.test(String(e||""))}async function Ie(e,{contract:t=Dt,rpc:r=Ut,chainId:n=Ft,balanceOf:o}={}){if(!qt(e))throw new Error("invalid-address");if(o)return BigInt(await o(e));let i=new $t(r,n,{staticNetwork:!0}),a=new Pt(t,Mt,i);return BigInt(await a.balanceOf(e))}var Vt=100,jt=5,Ce=Object.freeze({swap:5,bridge:15,perps:0,nft:0});function zt(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(Ce,t)?Ce[t]:jt}var Gt="ORACLE_INTEGRATOR_FEE_BPS",Yt="ORACLE_INTEGRATOR_FEE_RECIPIENT",Kt="ORACLE_INTEGRATOR_ID",Xt="oracle";function Qt(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),Vt)}function Wt({env:e=process.env,action:t="swap"}={}){let r=String(e[Yt]||"").trim(),n=zt(t),o=Qt(e[Gt],{fallback:r?n:0}),i=Math.min(o,n),a=String(e[Kt]||Xt).trim();return i?/^0x[a-fA-F0-9]{40}$/.test(r)?{bps:i,recipient:r,integrator:a,action:t,applies:!0,reason:"configured"}:{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"no-recipient"}:{bps:0,recipient:"",integrator:a,action:t,applies:!1,reason:"not-configured"}}async function M({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={}}={}){let o=Wt({env:t,action:r}),i=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(i))return{...o,holderVerificationStatus:"wallet-required"};try{return BigInt(await Ie(i,n))>0n?{...o,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...o,holderVerificationStatus:"non-holder"}}catch{return{...o,holderVerificationStatus:"unavailable"}}}function ve(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}function ke(e){return e?.applies?{partner:e.integrator,partnerFeeBps:String(e.bps),partnerAddress:e.recipient}:{}}var Jt="https://li.quest/v1";function Zt(e={}){return(e.baseUrl||process.env.LIFI_API_URL||Jt).replace(/\/$/,"")}var er="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";async function Z(e={},t={}){let{fromChain:r,toChain:n=r,fromToken:o=er,toToken:i,fromAmount:a,fromAddress:s=T}=e;if(r==null||!i||!a)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let c=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:o,toToken:i,fromAmount:String(a),fromAddress:s}),p=S({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!p.executable)throw new Error(`lifi: route requires ${p.requiredBps} bps above cap ${p.capBps}`);c.set("slippage",String(p.selectedBps/1e4));let d=await M({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[w,g]of Object.entries(ve(d)))c.set(w,g);let l=await b(`${Zt(t)}/quote?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),u=l?.estimate?.toAmount||l?.toAmount;if(!u)return{...l,autoSlippagePolicy:p,oracleFee:d};let m=l?.transactionRequest?.to||l?.estimate?.approvalAddress||"lifi",f=E(l,{chainId:Number(r),venue:m,amountOut:u,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),h=l?.estimate?.toAmountMin||l?.toAmountMin;if(h!=null&&BigInt(h)<BigInt(f.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...f,oracleFee:d}}y();I();v();var tr="https://api.paraswap.io",rr=(e={})=>(e.baseUrl||process.env.PARASWAP_API_URL||tr).replace(/\/$/,"");function _e(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 Oe(e={},t={}){let r=Number(e.chainId||e.network||1);if(e.amount==null)throw new Error("amount required");let n=new URLSearchParams({srcToken:_e(e.srcToken,"srcToken"),destToken:_e(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 M({wallet:e.userAddress||e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[s,c]of Object.entries(ke(o)))n.set(s,c);let i=await b(`${rr(t)}/prices?${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),a=i?.priceRoute?.destAmount;return a?{...E(i,{chainId:r,venue:i?.priceRoute?.contractAddress||"paraswap-quote",amountOut:a,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,quoteAgeMs:0,requestedCapBps:e.maxSlippageBps??e.slippageBps}),executionReady:!1,executionBlocker:"call prepare to bind the price route to a validated transaction",oracleFee:o}:{...i,executionReady:!1,oracleFee:o}}y();I();var Re="ORACLE_ALLOW_CUSTOM_PROVIDER_URL";function H({provider:e,defaultUrl:t,hosts:r=[],url:n,strict:o=!1}){let a=(String(n??"").trim()||String(t)).replace(/\/$/,"");if(a===String(t).replace(/\/$/,""))return{baseUrl:a,trusted:!0,host:Te(t)};let s;try{s=new URL(a)}catch{throw new Error(`${e}: baseUrl must be an absolute http(s) URL`)}if(s.protocol!=="http:"&&s.protocol!=="https:")throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);let c=s.host;if(!c)throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);if(new Set([Te(t),...r]).has(c)){let d=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(c);return s.protocol==="http:"&&!d?{baseUrl:a,trusted:!1,host:c,reason:"plaintext http downgrade"}:{baseUrl:a,trusted:!0,host:c}}if(String(process.env[Re]||"")==="1")return{baseUrl:a,trusted:!1,host:c};if(o)throw new Error(`${e}: refusing to call non-allowlisted host ${c} (set ${Re}=1 to permit it)`);return{baseUrl:a,trusted:!1,host:c}}function Te(e){let t=new URL(String(e));if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("unsupported protocol");return t.host}function q(e,t,r){let n={...e};if(!r)return n;for(let[o,i]of Object.entries(t||{}))i&&(n[o]=i);return n}v();var nr="https://api.0x.org";function Ne(e={}){return H({provider:"zerox",defaultUrl:nr,hosts:["api.0x.org"],url:e.baseUrl||process.env.ZEROX_API_URL})}function or(e={}){return Ne(e).baseUrl}function Be(e={}){return e.apiKey||process.env.ZEROX_API_KEY||process.env.OX_API_KEY||process.env["0X_API_KEY"]||""}function ar(e={}){return q({"0x-version":"v2",accept:"application/json"},{"0x-api-key":Be(e)},Ne(e).trusted)}async function Le(e={},t={}){if(!Be(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:o,sellAmount:i,taker:a}=e;if(!n||!o||!i)throw new Error("zeroxQuote requires sellToken, buyToken, sellAmount");let s=S({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!s.executable)throw new Error(`0x: route requires ${s.requiredBps} bps above cap ${s.capBps}`);let c=new URLSearchParams({chainId:String(r),sellToken:n,buyToken:o,sellAmount:String(i),slippageBps:String(s.selectedBps)});a&&c.set("taker",a);let p=await b(`${or(t)}/swap/allowance-holder/quote?${c}`,{headers:ar(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),d=p?.buyAmount||p?.grossBuyAmount;return d?E(p,{chainId:r,venue:p?.transaction?.to||p?.to||"0x",amountOut:d,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):{...p,autoSlippagePolicy:s}}y();I();v();var ir="https://api.1inch.dev/swap/v6.0";function Pe(e={}){return H({provider:"oneinch",defaultUrl:ir,hosts:["api.1inch.dev"],url:e.baseUrl||process.env.ONEINCH_API_URL})}function sr(e={}){return Pe(e).baseUrl}function $e(e={}){return e.apiKey||process.env.ONEINCH_API_KEY||process.env.ONE_INCH_API_KEY||""}function cr(e={}){let t=$e(e);return q({accept:"application/json"},{Authorization:t?`Bearer ${t}`:""},Pe(e).trusted)}async function De(e={},t={}){if(!$e(t))throw new Error("ONEINCH_API_KEY required for 1inch");let r=Number(e.chainId??1),{src:n,dst:o,amount:i}=e;if(!n||!o||!i)throw new Error("oneinchQuote requires src, dst, amount");let a=new URLSearchParams({src:n,dst:o,amount:String(i)}),s=await b(`${sr(t)}/${r}/quote?${a}`,{headers:cr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3});return s?.dstAmount?E(s,{chainId:r,venue:"1inch-quote",amountOut:s.dstAmount,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):s}y();I();import{TypedDataEncoder as zn,getAddress as Gn,isAddress as Yn}from"ethers";var Mn=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"}),Hn=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":[]});U();v();var ur={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"},eo=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),to=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"}),Fe={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"},lr={1:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",42161:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},ro=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"}]}),no=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]});function pr(e,t={}){if(t.baseUrl)return t.baseUrl.replace(/\/$/,"");let r=ur[Number(e)];if(!r)throw new Error(`cowswap: unsupported chainId ${e}`);return r}async function Ue(e={},t={}){let r=Number(e.chainId??1),n=xe(e.from||e.owner),o=e.sellToken||Fe[r],i=e.buyToken||lr[r],a=String(e.sellAmountBeforeFee||e.sellAmount||"0");if(!o||!i||a==="0")throw new Error("cowQuote requires sellToken, buyToken, sellAmountBeforeFee");if(/eeeeeeee|native|^eth$/i.test(o)&&(o=Fe[r],!o))throw new Error("no WETH mapping for chain");let s={sellToken:o,buyToken:i,from:n,receiver:e.receiver||n,sellAmountBeforeFee:a,kind:e.kind||"sell",signingScheme:e.signingScheme||"eip1271"},c=await b(`${pr(r,t)}/quote`,{method:"POST",body:s,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),p=c?.quote?.buyAmount||c?.buyAmount;return p?E(c,{chainId:r,venue:"cowswap-order",amountOut:p,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):c}import{Interface as ze,getAddress as j,isAddress as br}from"ethers";y();var Me={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}},dr=new Map(Object.values(Me).map(e=>[e.chainId,e]));function He(e){return dr.get(Number(e))||null}function qe(e,t=process.env){let r=He(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}import{Interface as mr,getAddress as lo}from"ethers";var po=new mr(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);var fr={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"};function hr(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=qe(e,r);return n||fr[Number(e)]||null}var wr=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function gr(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!wr.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 V(e,t,r=[],n={}){let o=String(t||"");gr(o);let i=hr(e,n);if(!i)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let s=await b(i,{method:"POST",body:{jsonrpc:"2.0",id:1,method:t,params:r},fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs??12e3});if(s?.error){let c=new Error(s.error.message||JSON.stringify(s.error));throw c.code=s.error.code,c}return s.result}I();v();var N={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"}},Er=[100,500,3e3,1e4],Ve=new ze(["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)"]),bo=new ze(["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)"]),Ar="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",xr="0x0000000000000000000000000000000000000000",ee=[100,500,2500,1e4],yr={56:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ee}},8453:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ee}},42161:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:ee}},999:{hyperswap:{name:"hyperswap",quoter:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",router:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D"}}};function Sr(e,t){let r=Number(e),n=N[r];if(!n)throw new Error(`uniswap-v3: unsupported chainId ${e} (supported: ${Object.keys(N).join(", ")})`);let o=yr[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 i=String(t).toLowerCase();if(i===n.name&&n.quoter&&n.router)return{chainId:r,venue:n.name,...n};let a=o,s=a[i];if(!s){let c=[...n.quoter&&n.router?[n.name]:[],...Object.keys(a)].join(", ");throw new Error(`uniswap-v3: unknown venue "${t}" on chain ${r} (known: ${c})`)}return{chainId:r,venue:i,...n,quoter:s.quoter,router:s.router,feeTiers:s.feeTiers||null}}function je(e,t){let r=N[Number(t)];if(!e||e===Ar||e===xr||/^eth$/i.test(String(e)))return j(r.weth);let n=String(e);if(/^weth$/i.test(n))return j(r.weth);if(/^usdc$/i.test(n))return j(r.usdc);if(!br(n))throw new Error(`invalid token address: ${e}`);return j(n)}async function Ge(e={},t={}){let{chainId:r,quoter:n,router:o,feeTiers:i}=Sr(e.chainId??8453,e.venue),a=je(e.tokenIn||"WETH",r),s=je(e.tokenOut||N[r].usdc,r),c=BigInt(e.amountIn??0);if(c<=0n)throw new Error("amountIn required (raw base units)");let p=i&&i.length?i:Er,d=e.fee!=null?[Number(e.fee)]:e.tryFees===!1?[p[Math.min(2,p.length-1)]]:[...p],l=[],u=null;for(let m of d){let f=Ve.encodeFunctionData("quoteExactInputSingle",[{tokenIn:a,tokenOut:s,amountIn:c,fee:m,sqrtPriceLimitX96:0n}]);try{let h=await V(r,"eth_call",[{to:n,data:f},"latest"],t);if(!h||h==="0x"){l.push({fee:m,ok:!1,error:"empty result"});continue}let w=Ve.decodeFunctionResult("quoteExactInputSingle",h),g={fee:m,ok:!0,amountOut:w[0].toString(),sqrtPriceX96After:w[1].toString(),initializedTicksCrossed:Number(w[2]),gasEstimate:w[3].toString()};l.push(g),(!u||BigInt(g.amountOut)>BigInt(u.amountOut))&&(u=g)}catch(h){l.push({fee:m,ok:!1,error:String(h.message||h).slice(0,160)})}}if(!u){let m=l.map(f=>`${f.fee}:${f.error||"fail"}`).join("; ");throw new Error(`uniswap-v3 quote failed chain=${r}: ${m}`)}return E({venue:"uniswap-v3",chainId:r,chain:N[r].name,quoter:n,tokenIn:a,tokenOut:s,amountIn:c.toString(),fee:u.fee,amountOut:u.amountOut,gasEstimate:u.gasEstimate,sqrtPriceX96After:u.sqrtPriceX96After,initializedTicksCrossed:u.initializedTicksCrossed,triedFees:l,best:!0},{chainId:r,venue:o,amountOut:u.amountOut,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}import{AbiCoder as Ir,Interface as Xe,getAddress as x,isAddress as z,keccak256 as Cr}from"ethers";I();v();var vr=Ir.defaultAbiCoder(),L="0x0000000000000000000000000000000000000000",B={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"}},kr=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200},{fee:25e3,tickSpacing:8}],Ye=new Xe(["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)"]),Io=new Xe(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]);var _r="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";function Or(e){let t=Number(e),r=B[t];if(!r)throw new Error(`uniswap-v4: unsupported chainId ${e} (supported: ${Object.keys(B).join(", ")})`);return{chainId:t,...r}}function Ke(e,t){let r=B[Number(t)];if(!e||e===_r||e===L||/^eth$/i.test(String(e)))return x(r.weth);let n=String(e);if(/^weth$/i.test(n))return x(r.weth);if(/^usdc$/i.test(n)||/^usdg$/i.test(n))return x(r.usdc);if(!z(n))throw new Error(`invalid token address: ${e}`);return x(n)}function Rr({currency0:e,currency1:t,fee:r,tickSpacing:n,hooks:o=L}){let i=x(e),a=x(t);if(i.toLowerCase()===a.toLowerCase())throw new Error("poolKey currencies must differ");let[s,c]=i.toLowerCase()<a.toLowerCase()?[i,a]:[a,i],p=o&&z(o)?x(o):L;return Cr(vr.encode(["address","address","uint24","int24","address"],[s,c,Number(r),Number(n),p]))}function Tr({tokenIn:e,tokenOut:t,fee:r,tickSpacing:n,hooks:o=L}){let i=x(e),a=x(t),[s,c]=i.toLowerCase()<a.toLowerCase()?[i,a]:[a,i],p=i.toLowerCase()===s.toLowerCase();return{poolKey:{currency0:s,currency1:c,fee:Number(r),tickSpacing:Number(n),hooks:o&&z(o)?x(o):L},zeroForOne:p}}async function Qe(e={},t={}){let{chainId:r,quoter:n,poolManager:o,universalRouter:i}=Or(e.chainId??8453),a=Ke(e.tokenIn||"WETH",r),s=Ke(e.tokenOut||B[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 p=e.fee!=null&&e.tickSpacing!=null?[{fee:Number(e.fee),tickSpacing:Number(e.tickSpacing)}]:e.tryTiers===!1?[{fee:500,tickSpacing:10}]:[...kr],d=e.hooks||L,l=[],u=null;for(let m of p){let{poolKey:f,zeroForOne:h}=Tr({tokenIn:a,tokenOut:s,fee:m.fee,tickSpacing:m.tickSpacing,hooks:d}),w=Ye.encodeFunctionData("quoteExactInputSingle",[{poolKey:f,zeroForOne:h,exactAmount:c,hookData:"0x"}]);try{let g=await V(r,"eth_call",[{to:n,data:w},"latest"],t);if(!g||g==="0x"){l.push({...m,ok:!1,error:"empty result"});continue}let P=Ye.decodeFunctionResult("quoteExactInputSingle",g),_={fee:m.fee,tickSpacing:m.tickSpacing,ok:!0,amountOut:P[0].toString(),gasEstimate:P[1].toString(),poolKey:f,zeroForOne:h,poolId:Rr({...f})};l.push(_),(!u||BigInt(_.amountOut)>BigInt(u.amountOut))&&(u=_)}catch(g){l.push({...m,ok:!1,error:String(g.message||g).slice(0,160)})}}if(!u){let m=l.map(f=>`${f.fee}/${f.tickSpacing}:${f.error||"fail"}`).join("; ");throw new Error(`uniswap-v4 quote failed chain=${r}: ${m}`)}return E({venue:"uniswap-v4",chainId:r,chain:B[r].name,poolManager:o,quoter:n,universalRouter:i||null,tokenIn:a,tokenOut:s,amountIn:c.toString(),fee:u.fee,tickSpacing:u.tickSpacing,hooks:u.poolKey.hooks,poolId:u.poolId,zeroForOne:u.zeroForOne,amountOut:u.amountOut,gasEstimate:u.gasEstimate,triedTiers:l,best:!0,executionReady:!1,prepareReady:typeof e.recipient=="string"&&z(e.recipient)&&e.slippageBps!=null},{chainId:r,venue:i||n,amountOut:u.amountOut,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}y();var Nr="https://coins.llama.fi";function Br(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Nr).replace(/\/$/,"")}async function G(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return b(`${Br(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}var k=e=>{let t=Number(e);return Number.isFinite(t)?t:null};function Y(e){if(!Array.isArray(e))return null;let t=0,r=!1;for(let n of e){let o=k(n?.amountUSD);o!=null&&(t+=o,r=!0)}return r?t:null}async function rt(e,t={}){let r=se[Number(e)];if(!r)return null;try{let n=await G([r],t);return k(n?.coins?.[r]?.price)}catch{return null}}function oe({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o,slippageBps:i,decimalsIn:a,decimalsOut:s,nativePriceUsd:c=null,destDecimalsPromise:p=null,opts:d={}}){let l=[];return l.push({source:"lifi",run:async()=>{let u=await Z({fromChain:e,toChain:e,fromToken:t,toToken:r,fromAmount:n},d),m=u?.estimate??u?.[0]?.estimate;return{amountOut:m?.toAmount,minOut:m?.toAmountMin,gasUsd:Y(m?.gasCosts),feeUsd:Y(m?.feeCosts),meta:{tool:u?.tool??u?.toolDetails?.name}}}}),a!=null&&l.push({source:"paraswap",run:async()=>{let u=s??(await Promise.resolve(p))?.decimals;if(u==null)throw new Error("paraswap needs destination decimals; none supplied or resolvable");let f=(await Oe({chainId:e,srcToken:t,destToken:r,amount:n,srcDecimals:a,destDecimals:u},d))?.priceRoute;return{amountOut:f?.destAmount,gasUsd:k(f?.gasCostUSD),meta:{bestRoute:f?.bestRoute?.[0]?.swaps?.[0]?.swapExchanges?.[0]?.exchange}}}}),process.env.ZEROX_API_KEY&&l.push({source:"0x",run:async()=>{let u=await Le({chainId:e,sellToken:t,buyToken:r,sellAmount:n,taker:o},d),m=null,f=u?.totalNetworkFee,h=await Promise.resolve(c);return f!=null&&h&&(m=Number(f)/1e18*h),{amountOut:u?.buyAmount,minOut:u?.minBuyAmount,gasUsd:m,meta:{source:u?.route?.fills?.[0]?.source}}}}),process.env.ONEINCH_API_KEY&&l.push({source:"1inch",run:async()=>{let u=await De({chainId:e,src:t,dst:r,amount:n},d),m=null;return u?.gas!=null&&c&&(m=null),{amountOut:u?.dstAmount,gasUsd:m,meta:{gasUnits:u?.gas}}}}),l.push({source:"cow",run:async()=>{let u=await Ue({chainId:e,sellToken:t,buyToken:r,sellAmountBeforeFee:String(n),from:o},d),m=u?.quote??u,f=m?.feeAmount;return{amountOut:m?.buyAmount,gasUsd:0,meta:{intent:!0,feeAmountInSellToken:f,settlement:"solver-executed"}}}}),N[Number(e)]&&l.push({source:"uniswap-v3",run:async()=>{let u=await Ge({chainId:e,tokenIn:t,tokenOut:r,amountIn:n},d);return{amountOut:u?.amountOut,minOut:u?.minOut??u?.amountOutMinimum??null,gasUsd:null,meta:{onchain:!0,fee:u?.fee,gasUnits:u?.gasEstimate,quoter:u?.quoter}}}}),B[Number(e)]&&l.push({source:"uniswap-v4",run:async()=>{let u=await Qe({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:o,slippageBps:i},d);return{amountOut:u?.amountOut,minOut:u?.minOut??u?.amountOutMinimum??null,gasUsd:null,meta:{onchain:!0,venue:"uniswap-v4",fee:u?.fee,tickSpacing:u?.tickSpacing,poolId:u?.poolId,hooks:u?.hooks,gasUnits:u?.gasEstimate,quoter:u?.quoter,poolManager:u?.poolManager,prepareReady:u?.prepareReady===!0,executionReady:!1}}}}),l}function nt({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:o,taker:i,opts:a={}}){let s=[];return s.push({source:"lifi",run:async()=>{let c=await Z({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:o},a),p=c?.estimate??c?.[0]?.estimate;return{amountOut:p?.toAmount,minOut:p?.toAmountMin,gasUsd:Y(p?.gasCosts),feeUsd:Y(p?.feeCosts),meta:{tool:c?.tool??c?.toolDetails?.name,durationSeconds:k(p?.executionDuration)}}}}),s.push({source:"relay",run:async()=>{let{relayQuote:c}=await Promise.resolve().then(()=>(ne(),re)),d=(await c({user:i,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(o)},a))?.details;return{amountOut:d?.currencyOut?.amount,minOut:d?.currencyOut?.minimumAmount,gasUsd:k(d?.totalImpact?.usd)!=null?Math.abs(k(d.totalImpact.usd)):null,meta:{durationSeconds:k(d?.timeEstimate),rate:d?.rate}}}}),s.push({source:"across",run:async()=>{let{acrossSuggestedFees:c}=await Promise.resolve().then(()=>(ne(),re)),p=await c({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(o)},a),d=p?.totalRelayFee?.total,l=null;if(d!=null)try{let u=BigInt(String(o))-BigInt(String(d));u>0n&&(l=u.toString())}catch{}return{amountOut:l,gasUsd:null,meta:{derivedFromFees:!0,durationSeconds:k(p?.estimatedFillTimeSec),limits:p?.limits?{min:p.limits.minDeposit,max:p.limits.maxDeposit}:void 0}}}}),s}var Ur={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"};async function ot(e,t,r){let n=Ur[Number(e)];if(!n)return{priceUsd:null,decimals:null};let o=`${n}:${t}`;try{let a=(await G([o],r))?.coins?.[o],s=Number(a?.price),c=Number(a?.decimals);return{priceUsd:Number.isFinite(s)?s:null,decimals:Number.isFinite(c)?c:null}}catch{return{priceUsd:null,decimals:null}}}async function Go(e,t={}){let{chainId:r,tokenIn:n,tokenOut:o,amountIn:i}=e;if(r==null||!n||!o||i==null)throw new Error("bestSwapRoute requires chainId, tokenIn, tokenOut, amountIn");let a=rt(r,t),s=ot(r,o,t),c=oe({...e,nativePriceUsd:a,decimalsOut:e.decimalsOut,destDecimalsPromise:s,opts:t}),[p,d]=await Promise.all([D(c,{timeoutMs:t.timeoutMs??12e3}),s]);a.catch(()=>{});let l=K(p,{destPriceUsd:d.priceUsd,destDecimals:e.decimalsOut??d.decimals}),u=t.maxImpactPct===void 0?25:t.maxImpactPct;if(u!=null&&l.best){let m=l.best.source,h=await ce(async w=>{let g=oe({...e,amountIn:w.toString(),nativePriceUsd:a,decimalsOut:e.decimalsOut,destDecimalsPromise:s,opts:t}).filter(_=>_.source===m);return g.length?(await D(g,{timeoutMs:t.timeoutMs??12e3}))?.[0]?.amountOut??null:null},i);if(h){let w=ue(l,{[m]:h},{maxImpactPct:u});return{kind:"swap",chainId:r,tokenIn:n,tokenOut:o,amountIn:String(i),...w,sourcesTried:c.length,sourcesAnswered:p.filter(g=>g.quality!==A.FAILED).length,note:ae(w,c.length),priceImpact:{[m]:Number(h.impactPct.toFixed(2))}}}}return{kind:"swap",chainId:r,tokenIn:n,tokenOut:o,amountIn:String(i),...l,sourcesTried:c.length,sourcesAnswered:p.filter(m=>m.quality!==A.FAILED).length,note:ae(l,c.length)}}async function Yo(e,t={}){let{fromChainId:r,toChainId:n,tokenIn:o,tokenOut:i,amountIn:a}=e;if(r==null||n==null||!o||!i||a==null)throw new Error("bestBridgeRoute requires fromChainId, toChainId, tokenIn, tokenOut, amountIn");if(Number(r)===Number(n))throw new Error("bestBridgeRoute is for cross-chain; use bestSwapRoute for same-chain");let s=ot(n,i,t),c=nt({...e,opts:t}),[p,d]=await Promise.all([D(c,{timeoutMs:t.timeoutMs??15e3}),s]),l=K(p,{destPriceUsd:d.priceUsd,destDecimals:e.decimalsOut??d.decimals}),u=l.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:i,amountIn:String(a),...l,durations:u,sourcesTried:c.length,sourcesAnswered:p.filter(m=>m.quality!==A.FAILED).length,note:ae(l,c.length)}}function ae(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 i=o>=.01?`${o.toFixed(2)}%`:`${n.toFixed(2)}bps`;return`best of ${r} routes, ranked on ${e.rankedOn}: ${i} 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.`}export{A as QUALITY,Yo as bestBridgeRoute,Go as bestSwapRoute,ae as formatComparisonNote};
1
+ var ft=Object.defineProperty;var U=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var ht=(e,t)=>{for(var r in t)ft(e,r,{get:t[r],enumerable:!0})};import{createHash as wt}from"node:crypto";function yt(e){let t=String(e||"").toLowerCase();return ye.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function At(e){let t={};for(let[r,n]of Object.entries(e||{}))yt(r)||(t[r]=n);return t}function xt(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 St(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function It(e,t,r){let n={};for(let[i,d]of Object.entries(r||{}))n[i.toLowerCase()]=d;let o=Object.keys(n).filter(i=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(i)),u=[...new Set([...ye,...o])].sort().map(i=>`${i}=${n[i]??""}`).join(`
2
+ `),c=wt("sha256").update(u).digest("hex").slice(0,32);return`${e} ${t} ${c}`}function Ct(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,be):Math.min(250*2**e,be)+Math.floor(Math.random()*100)}async function kt(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:s}){let u=new AbortController,c=setTimeout(()=>u.abort(),s);try{let i=String(e),d={...n||{}};for(let p=0;p<=Ee;p+=1){let l=await t(i,{method:r,headers:d,body:o,signal:u.signal,redirect:"manual"}),a=await l.text(),m=null;if(a)try{m=JSON.parse(a)}catch{m=null}if(Et.has(l.status)){if(r!=="GET"&&r!=="HEAD"){let w=new Error(`HTTP ${l.status} ${r} ${i} redirected non-idempotent request`);throw w.status=l.status,w.body=m??a.slice(0,300),w}if(p===Ee)throw new Error(`HTTP redirect loop for ${e}`);let h=xt(l.headers?.get?.("location"),i);St(h,i)||(d=At(d)),i=h;continue}if(!l.ok){let h=new Error(`HTTP ${l.status} ${r} ${i}`);throw h.status=l.status,h.retryAfter=l.headers?.get?.("retry-after")??null,h.body=m??a.slice(0,300),h}return m??a}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(c)}}async function y(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(),s={Accept:"application/json",...t.headers||{}},u=t.body;u!=null&&typeof u!="string"&&(s["Content-Type"]=s["Content-Type"]||"application/json",u=JSON.stringify(u));let c=Number.isInteger(t.retries)?Math.max(t.retries,0):bt,i=async()=>{let m;for(let h=0;h<=c;h++)try{return await kt(e,{fetchImpl:r,method:o,headers:s,body:u,timeoutMs:n})}catch(w){m=w;let g=w?.status,f=w?.name==="AbortError",b=new Set([408,425,429]),E=g!=null?b.has(g)||gt.has(g)&&ge.has(o):!f&&ge.has(o);if(h===c||!E)throw w;await vt(Ct(h,w?.retryAfter))}throw m};if(!(t.dedupe!==!1&&o==="GET"&&u==null))return i();let p=It(o,e,s),l=re.get(p);if(l)return l;let a=i().finally(()=>re.delete(p));return re.set(p,a),a}var gt,ge,bt,be,ye,Et,Ee,re,vt,I=U(()=>{gt=new Set([408,425,429,500,502,503,504]),ge=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),bt=2,be=4e3,ye=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],Et=new Set([301,302,303,307,308]),Ee=3;re=new Map;vt=e=>new Promise(t=>setTimeout(t,e))});import{readFileSync as _t}from"node:fs";import{homedir as Ot}from"node:os";import{join as V}from"node:path";function Rt(){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=Ot();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||V(t,".config","oracle")).trim();return[e,V(r,"exec.env")].filter(Boolean)}return[e,V(t,".config","oracle","exec.env"),V(t,".config","mad-desk","exec.env")].filter(Boolean)}function Ae(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of Rt())try{let s=_t(o,"utf8"),u=s.match(new RegExp(`^${t}=(.*)$`,"m"))||s.match(new RegExp(`^${r}=(.*)$`,"m"));if(u&&(n=u[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 xe=U(()=>{});var Se=U(()=>{});import{createHash as Tt,createHmac as Bt,timingSafeEqual as kn}from"node:crypto";function oe(e){return Array.isArray(e)?`[${e.map(oe).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${oe(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Nt(e,{required:t=!1}={}){try{return Ae(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function ve(e){let{signature:t,...r}=e;return r}function ke(e,{secret:t}={}){let r=Nt(t);return r?{...e,signature:Bt("sha256",r).update(oe(ve(e))).digest("hex")}:e}function Ut(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 Tt("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function P(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 ke({...ve(e),calldataHash:Ut(n)},{secret:o})}function ne(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}function Pt(e){let t=e==null?Ie: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,Ie)}function _({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:r=0,crossChain:n=!1,requestedCapBps:o}={}){let s=ne(e,0),u=s>0?s>=25e4?5:s>=1e5?10:s>=5e4?20:s>=1e4?40:70:n?30:10,c=Math.min(60,Math.abs(ne(t,0))*2),i=Math.min(40,Math.floor(Math.max(0,ne(r,0))/5e3)*5),d=Math.max(25,Math.ceil(20+u+c+i)),p=Pt(o);return{mode:"auto",requiredBps:d,selectedBps:Math.min(d,p),capBps:p,executable:d<=p}}function Lt({chainId:e,venue:t,quoteAmountOut:r,liquidityUsd:n,priceChange5m:o=0,quoteAgeMs:s=0,crossChain:u=!1,requestedCapBps:c,quotedAtMs:i=Date.now(),ttlMs:d=Ce,secret:p}={}){let l=BigInt(r??0);if(l<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let a=_({liquidityUsd:n,priceChange5m:o,quoteAgeMs:s,crossChain:u,requestedCapBps:c});if(!a.executable)throw new Error(`auto-slippage requires ${a.requiredBps} bps above hard/requested cap ${a.capBps}; route blocked`);let m=Number(i);if(!Number.isFinite(m))throw new Error("auto-slippage: quotedAtMs must be a finite number");let h=Math.min(3e4,Math.max(1e3,Number(d)||Ce)),w=l*BigInt(1e4-a.selectedBps),g=w/10000n;if(w%10000n!==0n&&(g+=1n),g>l&&(g=l),l>0n&&g<=0n)throw new Error(`auto-slippage: quote ${l} is too small to express a ${a.selectedBps} bps floor without rounding to zero`);let f=Number((l-g)*10000n/(l===0n?1n:l));if(f>a.capBps)throw new Error(`auto-slippage: realised floor implies ${f} bps, above cap ${a.capBps} \u2014 refusing to issue a guard weaker than advertised`);return ke({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:l.toString(),minAmountOut:g.toString(),requiredBps:a.requiredBps,selectedBps:a.selectedBps,capBps:a.capBps,quotedAtMs:m,expiresAtMs:m+h},{secret:p})}function A(e,{chainId:t,venue:r,amountOut:n,liquidityUsd:o,priceChange5m:s,crossChain:u,requestedCapBps:c,quotedAtMs:i=Date.now(),ttlMs:d}={}){let p=Lt({chainId:t,venue:r,quoteAmountOut:n,liquidityUsd:o,priceChange5m:s,crossChain:u,requestedCapBps:c,quotedAtMs:i,ttlMs:d});return{...e,autoSlippage:p,amountOutMinimum:p.minAmountOut}}var Ie,Ce,O=U(()=>{xe();Se();Ie=100,Ce=2e4});function _e(e){let t=String(e||"").trim();return/^0x[0-9a-fA-F]{40}$/.test(t)?t:L}var L,j=U(()=>{L="0x000000000000000000000000000000000000dEaD"});import{createHash as $t,createHmac as Dt,timingSafeEqual as Nn}from"node:crypto";function ae(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(ae).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${ae(e[r])}`).join(",")}}`}function Oe(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Re(e=process.env){return Oe(process.env)||Oe(e)}function qt(e){let{oraclePrepared:t,prepareHash:r,prepareMac:n,note:o,...s}=e||{};return s}function Ht(e){let t=qt(e);return $t("sha256").update(ae(t)).digest("hex")}function Vt(e,t=Re()){return t?Dt("sha256",t).update(String(e)).digest("hex"):""}function R(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 s=Date.now(),u=s+Mt,i={...o,preparedAt:s,expiresAt:u,prepareVersion:Ft},d=Ht(i),p=Re(n),l=p?Vt(d,p):void 0,a={...i,oraclePrepared:!0,prepareHash:d};return l&&(a.prepareMac=l),a}var Ft,Mt,Un,T=U(()=>{Ft=2,Mt=300*1e3,Un=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});var ue={};ht(ue,{ACROSS_API:()=>at,HOP_API:()=>it,RELAY_API:()=>st,acrossHealth:()=>tn,acrossSuggestedFees:()=>ct,hopHealth:()=>rn,hopQuote:()=>ut,relayHealth:()=>nn,relayPrepare:()=>on,relayQuote:()=>ce});async function tn(e={}){try{return{ok:!0,estimatedFillTimeSec:(await ct({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 ct(e={},t={}){let{token:r,destinationToken:n=r,originChainId:o,destinationChainId:s,amount:u}=e;if(!r||o==null||s==null||!u)throw new Error("acrossSuggestedFees requires token, originChainId, destinationChainId, amount");let c=new URLSearchParams({token:r,destinationToken:n,originChainId:String(o),destinationChainId:String(s),amount:String(u)}),i=(t.baseUrl||process.env.ACROSS_API_URL||at).replace(/\/$/,"");return y(`${i}/suggested-fees?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function rn(e={}){try{let t=await ut({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 ut(e={},t={}){let{amount:r,token:n="ETH",fromChain:o="ethereum",toChain:s="arbitrum"}=e;if(!r)throw new Error("hopQuote requires amount");let u=e.slippage==null?void 0:Math.round(Number(e.slippage)*100),c=_({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:o!==s,requestedCapBps:e.maxSlippageBps??e.slippageBps??u});if(!c.executable)throw new Error(`hop: route requires ${c.requiredBps} bps above cap ${c.capBps}`);let i=new URLSearchParams({amount:String(r),token:n,fromChain:o,toChain:s,slippage:String(c.selectedBps/100)}),d=(t.baseUrl||process.env.HOP_API_URL||it).replace(/\/$/,""),p=await y(`${d}/quote?${i}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),l=p?.estimatedRecieved||p?.estimatedReceived;return l?A(p,{chainId:Number(e.originChainId||e.chainId||en[o]||0),venue:p?.tx?.to||"hop",amountOut:l,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:o!==s,requestedCapBps:e.maxSlippageBps??e.slippageBps??u}):{...p,autoSlippagePolicy:c}}async function nn(e={}){try{let t=await ce({user:L,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 ce(e={},t={}){let{user:r=L,originChainId:n,destinationChainId:o,originCurrency:s="0x0000000000000000000000000000000000000000",destinationCurrency:u="0x0000000000000000000000000000000000000000",amount:c,tradeType:i="EXACT_INPUT"}=e;if(n==null||o==null||!c)throw new Error("relayQuote requires originChainId, destinationChainId, amount");let d=_({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(o),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!d.executable)throw new Error(`relay: route requires ${d.requiredBps} bps above cap ${d.capBps}`);let p=(t.baseUrl||process.env.RELAY_API_URL||st).replace(/\/$/,""),l=await y(`${p}/quote`,{method:"POST",body:{user:r,originChainId:Number(n),destinationChainId:Number(o),originCurrency:s,destinationCurrency:u,amount:String(c),tradeType:i,slippageTolerance:String(d.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),a=l?.details?.currencyOut?.amount;return!a||!/^\d+$/.test(String(a))?{...l,autoSlippagePolicy:d}:A(l,{chainId:Number(n),venue:l?.steps?.[0]?.items?.[0]?.data?.to||"relay",amountOut:a,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(o),requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function on(e={},t={}){let r=await ce(e,t),n=Number(e.originChainId),o=(r.steps||[]).flatMap(c=>(c.items||[]).filter(i=>i?.data?.to&&i?.data?.data).map(i=>({stepId:c.id,...i.data})));if(!o.length)throw new Error("relay: quote returned no executable transaction items");let s=String(r?.autoSlippage?.venue||"").toLowerCase();if(o.some(c=>String(c.to).toLowerCase()!==s))throw new Error("relay: route includes a separate approval/transaction that is not yet safely bound");let u=o.map(c=>({chainId:n,from:c.from||e.user,to:c.to,data:c.data,value:c.value??"0x0",...c.gasLimit!=null||c.gas!=null?{gasLimit:c.gasLimit??c.gas}:{},slippageGuard:P(r.autoSlippage,{chainId:n,venue:c.to,data:c.data})}));return R({provider:"relay",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:r,autoSlippage:r.autoSlippage,transactions:u},{provider:"relay",kind:"relay-tx"})}var at,it,st,en,le=U(()=>{I();O();j();T();at="https://across.to/api",it="https://api.hop.exchange/v1",st="https://api.relay.link",en={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453}});var dn=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),pn=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),mn=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"});var S=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"}),fe={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 me(e){let{source:t,amountOut:r,minOut:n=null,gasUsd:o=null,feeUsd:s=null,estimatedGas:u=null,liquidityUsd:c=null,error:i=null,executionReady:d=!1,meta:p={}}=e||{};if(i||r==null)return{source:t,quality:S.FAILED,amountOut:null,error:i||"no amountOut returned"};let l=q(r);return l==null||l<=0n?{source:t,quality:S.FAILED,amountOut:null,error:"non-positive amountOut"}:{source:t,quality:o==null?S.NO_GAS:S.FULL,amountOut:l.toString(),minOut:q(n)?.toString()??null,gasUsd:o,feeUsd:s,estimatedGas:u==null?null:String(u),liquidityUsd:c==null?null:Number(c),executionReady:d,meta:p}}async function he(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 s,u;try{[s,u]=await Promise.all([e(o),e(n)])}catch{return null}let c=q(s),i=q(u);if(c==null||i==null||c<=0n)return null;let d=Number(c)/Number(o),p=Number(i)/Number(n);return!Number.isFinite(d)||!Number.isFinite(p)||d<=0?null:{impactPct:(1-p/d)*100,probeAmountIn:o.toString(),probeAmountOut:c.toString(),fullAmountOut:i.toString()}}function we(e,t,{maxImpactPct:r=25}={}){let n=[],o=[],s=(e.routes??[]).filter(c=>{let i=t?.[c.source];return i?i.impactPct>r?(n.push({source:c.source,impactPct:Number(i.impactPct.toFixed(2)),reason:`price impact ${i.impactPct.toFixed(1)}% exceeds ${r}% ceiling -- the venue cannot absorb this size near the quoted price`}),!1):!0:(o.push(c.source),!0)}),u=[...e.warnings??[]];return n.length&&u.push(`dropped ${n.length} route(s) on price impact: `+n.map(c=>`${c.source} (${c.impactPct}%)`).join(", ")),o.length&&u.push(`price impact NOT measured for: ${o.join(", ")}. These are unproven against thin liquidity, not proven safe.`),{...e,routes:s,best:s[0]??null,impactRejected:n,impactUnmeasured:o,warnings:u}}function te(e,{destPriceUsd:t=null,destDecimals:r=null,liquidityFirst:n=!0,liquidityBandBps:o=50}={}){let s=e.filter(f=>f.quality!==S.FAILED),u=e.filter(f=>f.quality===S.FAILED),c=t!=null&&t>0&&r!=null&&r>=0,i=s.map(f=>{let b=BigInt(f.amountOut),E=0n,k=!1;if(c){let M=(f.gasUsd??0)+(f.feeUsd??0);if(M>0){let ee=M/t*10**r;Number.isFinite(ee)&&ee>=0&&(E=BigInt(Math.floor(ee)),k=!0)}else f.gasUsd===0&&(k=!0)}let B=b>E?b-E:0n;return{...f,grossOut:b.toString(),netOut:B.toString(),costInDest:E.toString(),costAccounted:k}}),d=Number(o)>0?Number(o):0,p=i.reduce((f,b)=>BigInt(b.netOut)>f?BigInt(b.netOut):f,0n),l=f=>p>0n?Number((p-BigInt(f))*10000n/p):0,a=[],m=i.slice().sort((f,b)=>BigInt(b.netOut)>BigInt(f.netOut)?1:-1)[0]??null;i.sort((f,b)=>{let E=l(f.netOut)<=d?0:1,k=l(b.netOut)<=d?0:1;if(n&&d>0&&E!==k)return E-k;if(n&&d>0){let B=f.liquidityUsd??-1,M=b.liquidityUsd??-1;if(B!==M)return M-B}return BigInt(b.netOut)>BigInt(f.netOut)?1:-1}),n&&d>0&&m&&i[0]&&i[0].source!==m.source&&a.push(`liquidity-first: chose ${i[0].source} (liquidity $${i[0].liquidityUsd??"unknown"}) over best-price ${m.source} within ${d} bps`);let h=i.filter(f=>!f.costAccounted).map(f=>f.source);c?h.length&&a.push(`gas not reported by: ${h.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):a.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let w=null,g=null;if(i.length>=2&&i[0].costAccounted&&i[1].costAccounted){let f=BigInt(i[0].netOut),b=BigInt(i[1].netOut);b>0n&&(w=Number((f-b)*10000n/b),g=`${i[0].source} vs ${i[1].source}`)}return{best:i[0]??null,routes:i,failed:u,improvementBps:w,spreadBasis:g,rankedOn:c?"net-of-cost":"gross",warnings:a}}async function H(e,{timeoutMs:t=12e3}={}){let r=(o,s)=>Promise.race([o,new Promise((u,c)=>setTimeout(()=>c(new Error(`${s}: timeout`)),t))]);return(await Promise.allSettled(e.map(o=>r(Promise.resolve().then(o.run),o.source)))).map((o,s)=>{let u=e[s].source;return o.status==="rejected"?me({source:u,error:String(o.reason?.message||o.reason)}):me({source:u,...o.value})})}I();O();j();T();import{Contract as jt,JsonRpcProvider as zt}from"ethers";var Gt="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",Xt=999,Yt="https://rpc.hyperliquid.xyz/evm",Kt=["function balanceOf(address owner) view returns (uint256)"],Qt=/^0x[a-fA-F0-9]{40}$/;function Wt(e){return Qt.test(String(e||""))}async function Te(e,{contract:t=Gt,rpc:r=Yt,chainId:n=Xt,balanceOf:o}={}){if(!Wt(e))throw new Error("invalid-address");if(o)return BigInt(await o(e));let s=new zt(r,n,{staticNetwork:!0}),u=new jt(t,Kt,s);return BigInt(await u.balanceOf(e))}var Jt=100,Zt=5,Be=Object.freeze({swap:5,bridge:15,perps:0,nft:0});function er(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(Be,t)?Be[t]:Zt}var tr="ORACLE_INTEGRATOR_FEE_BPS",rr="ORACLE_INTEGRATOR_FEE_RECIPIENT",nr="ORACLE_INTEGRATOR_ID",or="oracle";function ar(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),Jt)}function ir({env:e=process.env,action:t="swap"}={}){let r=String(e[rr]||"").trim(),n=er(t),o=ar(e[tr],{fallback:r?n:0}),s=Math.min(o,n),u=String(e[nr]||or).trim();return s?/^0x[a-fA-F0-9]{40}$/.test(r)?{bps:s,recipient:r,integrator:u,action:t,applies:!0,reason:"configured"}:{bps:0,recipient:"",integrator:u,action:t,applies:!1,reason:"no-recipient"}:{bps:0,recipient:"",integrator:u,action:t,applies:!1,reason:"not-configured"}}async function z({wallet:e,env:t=process.env,action:r="swap",holderCheck:n={}}={}){let o=ir({env:t,action:r}),s=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(s))return{...o,holderVerificationStatus:"wallet-required"};try{return BigInt(await Te(s,n))>0n?{...o,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...o,holderVerificationStatus:"non-holder"}}catch{return{...o,holderVerificationStatus:"unavailable"}}}function Ne(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}function Ue(e){return e?.applies?{partner:e.integrator,partnerFeeBps:String(e.bps),partnerAddress:e.recipient}:{}}var sr="https://li.quest/v1";function cr(e={}){return(e.baseUrl||process.env.LIFI_API_URL||sr).replace(/\/$/,"")}var ur="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";async function ie(e={},t={}){let{fromChain:r,toChain:n=r,fromToken:o=ur,toToken:s,fromAmount:u,fromAddress:c=L}=e;if(r==null||!s||!u)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let i=new URLSearchParams({fromChain:String(r),toChain:String(n),fromToken:o,toToken:s,fromAmount:String(u),fromAddress:c}),d=_({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!d.executable)throw new Error(`lifi: route requires ${d.requiredBps} bps above cap ${d.capBps}`);i.set("slippage",String(d.selectedBps/1e4));let p=await z({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[g,f]of Object.entries(Ne(p)))i.set(g,f);let l=await y(`${cr(t)}/quote?${i}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),a=l?.estimate?.toAmount||l?.toAmount;if(!a)return{...l,autoSlippagePolicy:d,oracleFee:p};let m=l?.transactionRequest?.to||l?.estimate?.approvalAddress||"lifi",h=A(l,{chainId:Number(r),venue:m,amountOut:a,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(n)!==Number(r),requestedCapBps:e.maxSlippageBps??e.slippageBps}),w=l?.estimate?.toAmountMin||l?.toAmountMin;if(w!=null&&BigInt(w)<BigInt(h.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...h,oracleFee:p}}I();O();T();var lr="https://api.paraswap.io",dr=(e={})=>(e.baseUrl||process.env.PARASWAP_API_URL||lr).replace(/\/$/,"");function Pe(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 Le(e={},t={}){let r=Number(e.chainId||e.network||1);if(e.amount==null)throw new Error("amount required");let n=new URLSearchParams({srcToken:Pe(e.srcToken,"srcToken"),destToken:Pe(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 z({wallet:e.userAddress||e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[c,i]of Object.entries(Ue(o)))n.set(c,i);let s=await y(`${dr(t)}/prices?${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),u=s?.priceRoute?.destAmount;return u?{...A(s,{chainId:r,venue:s?.priceRoute?.contractAddress||"paraswap-quote",amountOut:u,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}:{...s,executionReady:!1,oracleFee:o}}I();O();var $e="ORACLE_ALLOW_CUSTOM_PROVIDER_URL";function G({provider:e,defaultUrl:t,hosts:r=[],url:n,strict:o=!1}){let u=(String(n??"").trim()||String(t)).replace(/\/$/,"");if(u===String(t).replace(/\/$/,""))return{baseUrl:u,trusted:!0,host:De(t)};let c;try{c=new URL(u)}catch{throw new Error(`${e}: baseUrl must be an absolute http(s) URL`)}if(c.protocol!=="http:"&&c.protocol!=="https:")throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);let i=c.host;if(!i)throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);if(new Set([De(t),...r]).has(i)){let p=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(i);return c.protocol==="http:"&&!p?{baseUrl:u,trusted:!1,host:i,reason:"plaintext http downgrade"}:{baseUrl:u,trusted:!0,host:i}}if(String(process.env[$e]||"")==="1")return{baseUrl:u,trusted:!1,host:i};if(o)throw new Error(`${e}: refusing to call non-allowlisted host ${i} (set ${$e}=1 to permit it)`);return{baseUrl:u,trusted:!1,host:i}}function De(e){let t=new URL(String(e));if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("unsupported protocol");return t.host}function X(e,t,r){let n={...e};if(!r)return n;for(let[o,s]of Object.entries(t||{}))s&&(n[o]=s);return n}T();var pr="https://api.0x.org";function Fe(e={}){return G({provider:"zerox",defaultUrl:pr,hosts:["api.0x.org"],url:e.baseUrl||process.env.ZEROX_API_URL})}function mr(e={}){return Fe(e).baseUrl}function Me(e={}){return e.apiKey||process.env.ZEROX_API_KEY||process.env.OX_API_KEY||process.env["0X_API_KEY"]||""}function fr(e={}){return X({"0x-version":"v2",accept:"application/json"},{"0x-api-key":Me(e)},Fe(e).trusted)}async function qe(e={},t={}){if(!Me(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:r=8453,sellToken:n,buyToken:o,sellAmount:s,taker:u}=e;if(!n||!o||!s)throw new Error("zeroxQuote requires sellToken, buyToken, sellAmount");let c=_({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!c.executable)throw new Error(`0x: route requires ${c.requiredBps} bps above cap ${c.capBps}`);let i=new URLSearchParams({chainId:String(r),sellToken:n,buyToken:o,sellAmount:String(s),slippageBps:String(c.selectedBps)});u&&i.set("taker",u);let d=await y(`${mr(t)}/swap/allowance-holder/quote?${i}`,{headers:fr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),p=d?.buyAmount||d?.grossBuyAmount;return p?A(d,{chainId:r,venue:d?.transaction?.to||d?.to||"0x",amountOut:p,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):{...d,autoSlippagePolicy:c}}I();O();T();var hr="https://api.1inch.dev/swap/v6.0";function He(e={}){return G({provider:"oneinch",defaultUrl:hr,hosts:["api.1inch.dev"],url:e.baseUrl||process.env.ONEINCH_API_URL})}function wr(e={}){return He(e).baseUrl}function Ve(e={}){return e.apiKey||process.env.ONEINCH_API_KEY||process.env.ONE_INCH_API_KEY||""}function gr(e={}){let t=Ve(e);return X({accept:"application/json"},{Authorization:t?`Bearer ${t}`:""},He(e).trusted)}async function je(e={},t={}){if(!Ve(t))throw new Error("ONEINCH_API_KEY required for 1inch");let r=Number(e.chainId??1),{src:n,dst:o,amount:s}=e;if(!n||!o||!s)throw new Error("oneinchQuote requires src, dst, amount");let u=new URLSearchParams({src:n,dst:o,amount:String(s)}),c=await y(`${wr(t)}/${r}/quote?${u}`,{headers:gr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3});return c?.dstAmount?A(c,{chainId:r,venue:"1inch-quote",amountOut:c.dstAmount,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):c}I();O();import{TypedDataEncoder as ho,getAddress as wo,isAddress as go}from"ethers";var uo=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"}),lo=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":[]});j();T();var br={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"},Io=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),Co=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"}),ze={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"},Er={1:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",42161:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},vo=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"}]}),ko=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]});function yr(e,t={}){if(t.baseUrl)return t.baseUrl.replace(/\/$/,"");let r=br[Number(e)];if(!r)throw new Error(`cowswap: unsupported chainId ${e}`);return r}async function Ge(e={},t={}){let r=Number(e.chainId??1),n=_e(e.from||e.owner),o=e.sellToken||ze[r],s=e.buyToken||Er[r],u=String(e.sellAmountBeforeFee||e.sellAmount||"0");if(!o||!s||u==="0")throw new Error("cowQuote requires sellToken, buyToken, sellAmountBeforeFee");if(/eeeeeeee|native|^eth$/i.test(o)&&(o=ze[r],!o))throw new Error("no WETH mapping for chain");let c={sellToken:o,buyToken:s,from:n,receiver:e.receiver||n,sellAmountBeforeFee:u,kind:e.kind||"sell",signingScheme:e.signingScheme||"eip1271"},i=await y(`${yr(r,t)}/quote`,{method:"POST",body:c,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),d=i?.quote?.buyAmount||i?.buyAmount;return d?A(i,{chainId:r,venue:"cowswap-order",amountOut:d,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):i}import{Interface as Je,getAddress as Q,isAddress as Ur}from"ethers";I();var Xe={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}},Ar=new Map(Object.values(Xe).map(e=>[e.chainId,e]));function Ye(e){return Ar.get(Number(e))||null}function Ke(e,t=process.env){let r=Ye(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}import{Interface as xr,getAddress as Uo}from"ethers";var Po=new xr(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);var Sr={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"};function Ir(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=Ke(e,r);return n||Sr[Number(e)]||null}var Cr=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function vr(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!Cr.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 Y(e,t,r=[],n={}){let o=String(t||"");vr(o);let s=Ir(e,n);if(!s)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let c=await y(s,{method:"POST",body:{jsonrpc:"2.0",id:1,method:t,params:r},fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs??12e3});if(c?.error){let i=new Error(c.error.message||JSON.stringify(c.error));throw i.code=c.error.code,i}return c.result}I();var kr="https://api.dexscreener.com",_r=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"}),x=e=>String(e??"").toLowerCase(),Or=e=>Array.isArray(e)?e:e==null?[]:[e];function Rr(e,t,r){let n=x(t),o=x(r),s=x(e?.baseToken?.address),u=x(e?.quoteToken?.address);return s===n&&u===o||s===o&&u===n}function Tr(e){let t=Number(e?.liquidity?.usd);return Number.isFinite(t)&&t>=0?t:null}function Br(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||kr).replace(/\/$/,"")}async function Nr(e,t={}){if(!e)throw new Error("tokenAddress required");return y(`${Br(t)}/latest/dex/tokens/${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}async function K({chainId:e,tokenA:t,tokenB:r,dexIds:n=[]}={},o={}){if(e==null||!t||!r)throw new Error("chainId, tokenA, and tokenB required");let s=x(_r[Number(e)]||e),u=new Set(Or(n).filter(Boolean).map(x)),c=[...new Set([t,r].map(a=>String(a)).filter(Boolean))],i=await Promise.allSettled(c.map(a=>Nr(a,{...o,baseUrl:o.dexscreenerBaseUrl,timeoutMs:o.dexscreenerTimeoutMs??Math.min(Number(o.timeoutMs??4e3),4e3)}))),d=new Set,p=[];for(let a of i)if(a.status==="fulfilled")for(let m of a.value?.pairs||a.value?.data?.pairs||[]){let h=`${x(m?.chainId)}:${x(m?.dexId)}:${x(m?.pairAddress)}`;d.has(h)||(d.add(h),p.push(m))}return p.filter(a=>x(a?.chainId)===s).filter(a=>Rr(a,t,r)).filter(a=>!u.size||u.has(x(a?.dexId))).map(a=>({pairAddress:a.pairAddress??null,dexId:a.dexId??null,chainId:a.chainId??null,liquidityUsd:Tr(a),pairCreatedAt:a.pairCreatedAt??null})).filter(a=>a.liquidityUsd!=null).sort((a,m)=>m.liquidityUsd-a.liquidityUsd)[0]??null}O();T();var $={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"}},Pr=[100,500,3e3,1e4],Qe=new Je(["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)"]),jo=new Je(["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)"]),Lr="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",$r="0x0000000000000000000000000000000000000000",se=[100,500,2500,1e4],Dr={56:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:se}},8453:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:se}},42161:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:se}},999:{hyperswap:{name:"hyperswap",quoter:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",router:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D"}}};function Fr(e,t){let r=Number(e),n=$[r];if(!n)throw new Error(`uniswap-v3: unsupported chainId ${e} (supported: ${Object.keys($).join(", ")})`);let o=Dr[r]||{};if(!t){if(!n.quoter||!n.router){let i=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: ${i})`)}return{chainId:r,venue:n.name,...n}}let s=String(t).toLowerCase();if(s===n.name&&n.quoter&&n.router)return{chainId:r,venue:n.name,...n};let u=o,c=u[s];if(!c){let i=[...n.quoter&&n.router?[n.name]:[],...Object.keys(u)].join(", ");throw new Error(`uniswap-v3: unknown venue "${t}" on chain ${r} (known: ${i})`)}return{chainId:r,venue:s,...n,quoter:c.quoter,router:c.router,feeTiers:c.feeTiers||null}}function We(e,t){let r=$[Number(t)];if(!e||e===Lr||e===$r||/^eth$/i.test(String(e)))return Q(r.weth);let n=String(e);if(/^weth$/i.test(n))return Q(r.weth);if(/^usdc$/i.test(n))return Q(r.usdc);if(!Ur(n))throw new Error(`invalid token address: ${e}`);return Q(n)}function Mr(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`]}async function Ze(e={},t={}){let{chainId:r,quoter:n,router:o,feeTiers:s}=Fr(e.chainId??8453,e.venue),u=We(e.tokenIn||"WETH",r),c=We(e.tokenOut||$[r].usdc,r),i=BigInt(e.amountIn??0);if(i<=0n)throw new Error("amountIn required (raw base units)");let d=s&&s.length?s:Pr,p=e.fee!=null?[Number(e.fee)]:e.tryFees===!1?[d[Math.min(2,d.length-1)]]:[...d],l=[],a=null;for(let w of p){let g=Qe.encodeFunctionData("quoteExactInputSingle",[{tokenIn:u,tokenOut:c,amountIn:i,fee:w,sqrtPriceLimitX96:0n}]);try{let f=await Y(r,"eth_call",[{to:n,data:g},"latest"],t);if(!f||f==="0x"){l.push({fee:w,ok:!1,error:"empty result"});continue}let b=Qe.decodeFunctionResult("quoteExactInputSingle",f),E={fee:w,ok:!0,amountOut:b[0].toString(),sqrtPriceX96After:b[1].toString(),initializedTicksCrossed:Number(b[2]),gasEstimate:b[3].toString()};l.push(E),(!a||BigInt(E.amountOut)>BigInt(a.amountOut))&&(a=E)}catch(f){l.push({fee:w,ok:!1,error:String(f.message||f).slice(0,160)})}}if(!a){let w=l.map(g=>`${g.fee}:${g.error||"fail"}`).join("; ");throw new Error(`uniswap-v3 quote failed chain=${r}: ${w}`)}let m=e.liquidityUsd==null?await K({chainId:r,tokenA:u,tokenB:c,dexIds:Mr(e.venue)},t).catch(()=>null):null,h=e.liquidityUsd??m?.liquidityUsd??null;return A({venue:"uniswap-v3",chainId:r,chain:$[r].name,quoter:n,tokenIn:u,tokenOut:c,amountIn:i.toString(),fee:a.fee,amountOut:a.amountOut,gasEstimate:a.gasEstimate,liquidityUsd:h,liquiditySource:m,sqrtPriceX96After:a.sqrtPriceX96After,initializedTicksCrossed:a.initializedTicksCrossed,triedFees:l,best:!0},{chainId:r,venue:o,amountOut:a.amountOut,liquidityUsd:h,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}import{AbiCoder as qr,Interface as rt,getAddress as C,isAddress as W,keccak256 as Hr}from"ethers";O();T();var Vr=qr.defaultAbiCoder(),F="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"}},jr=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200},{fee:25e3,tickSpacing:8}],et=new rt(["function quoteExactInputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountOut, uint256 gasEstimate)"]),Wo=new rt(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]);var zr="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";function Gr(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 tt(e,t){let r=D[Number(t)];if(!e||e===zr||e===F||/^eth$/i.test(String(e)))return C(r.weth);let n=String(e);if(/^weth$/i.test(n))return C(r.weth);if(/^usdc$/i.test(n)||/^usdg$/i.test(n))return C(r.usdc);if(!W(n))throw new Error(`invalid token address: ${e}`);return C(n)}function Xr({currency0:e,currency1:t,fee:r,tickSpacing:n,hooks:o=F}){let s=C(e),u=C(t);if(s.toLowerCase()===u.toLowerCase())throw new Error("poolKey currencies must differ");let[c,i]=s.toLowerCase()<u.toLowerCase()?[s,u]:[u,s],d=o&&W(o)?C(o):F;return Hr(Vr.encode(["address","address","uint24","int24","address"],[c,i,Number(r),Number(n),d]))}function Yr({tokenIn:e,tokenOut:t,fee:r,tickSpacing:n,hooks:o=F}){let s=C(e),u=C(t),[c,i]=s.toLowerCase()<u.toLowerCase()?[s,u]:[u,s],d=s.toLowerCase()===c.toLowerCase();return{poolKey:{currency0:c,currency1:i,fee:Number(r),tickSpacing:Number(n),hooks:o&&W(o)?C(o):F},zeroForOne:d}}var Kr=["uniswap-v4","uniswapv4"];async function nt(e={},t={}){let{chainId:r,quoter:n,poolManager:o,universalRouter:s}=Gr(e.chainId??8453),u=tt(e.tokenIn||"WETH",r),c=tt(e.tokenOut||D[r].usdc,r),i=BigInt(e.amountIn??0);if(i<=0n)throw new Error("amountIn required (raw base units)");if(i>0xffffffffffffffffffffffffffffffffn)throw new Error("amountIn exceeds uint128");let d=e.fee!=null&&e.tickSpacing!=null?[{fee:Number(e.fee),tickSpacing:Number(e.tickSpacing)}]:e.tryTiers===!1?[{fee:500,tickSpacing:10}]:[...jr],p=e.hooks||F,l=[],a=null;for(let w of d){let{poolKey:g,zeroForOne:f}=Yr({tokenIn:u,tokenOut:c,fee:w.fee,tickSpacing:w.tickSpacing,hooks:p}),b=et.encodeFunctionData("quoteExactInputSingle",[{poolKey:g,zeroForOne:f,exactAmount:i,hookData:"0x"}]);try{let E=await Y(r,"eth_call",[{to:n,data:b},"latest"],t);if(!E||E==="0x"){l.push({...w,ok:!1,error:"empty result"});continue}let k=et.decodeFunctionResult("quoteExactInputSingle",E),B={fee:w.fee,tickSpacing:w.tickSpacing,ok:!0,amountOut:k[0].toString(),gasEstimate:k[1].toString(),poolKey:g,zeroForOne:f,poolId:Xr({...g})};l.push(B),(!a||BigInt(B.amountOut)>BigInt(a.amountOut))&&(a=B)}catch(E){l.push({...w,ok:!1,error:String(E.message||E).slice(0,160)})}}if(!a){let w=l.map(g=>`${g.fee}/${g.tickSpacing}:${g.error||"fail"}`).join("; ");throw new Error(`uniswap-v4 quote failed chain=${r}: ${w}`)}let m=e.liquidityUsd==null?await K({chainId:r,tokenA:u,tokenB:c,dexIds:Kr},t).catch(()=>null):null,h=e.liquidityUsd??m?.liquidityUsd??null;return A({venue:"uniswap-v4",chainId:r,chain:D[r].name,poolManager:o,quoter:n,universalRouter:s||null,tokenIn:u,tokenOut:c,amountIn:i.toString(),fee:a.fee,tickSpacing:a.tickSpacing,hooks:a.poolKey.hooks,poolId:a.poolId,zeroForOne:a.zeroForOne,amountOut:a.amountOut,gasEstimate:a.gasEstimate,liquidityUsd:h,liquiditySource:m,triedTiers:l,best:!0,executionReady:!1,prepareReady:typeof e.recipient=="string"&&W(e.recipient)&&e.slippageBps!=null},{chainId:r,venue:s||n,amountOut:a.amountOut,liquidityUsd:h,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}I();var Qr="https://coins.llama.fi",Wr="https://api.llama.fi";function Jr(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Qr).replace(/\/$/,"")}function Zr(e={}){return(e.baseUrl||process.env.DEFILLAMA_API_URL||Wr).replace(/\/$/,"")}async function J(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return y(`${Jr(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function ot(e={}){return y(`${Zr(e)}/protocols`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??2e4})}var v=e=>{let t=Number(e);return Number.isFinite(t)?t:null};function Z(e){if(!Array.isArray(e))return null;let t=0,r=!1;for(let n of e){let o=v(n?.amountUSD);o!=null&&(t+=o,r=!0)}return r?t:null}async function dt(e,t={}){let r=fe[Number(e)];if(!r)return null;try{let n=await J([r],t);return v(n?.coins?.[r]?.price)}catch{return null}}var N=e=>String(e??"").toLowerCase().replace(/[^a-z0-9]/g,""),lt=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 an(e={}){try{let t=await ot({...e,baseUrl:e.defillamaApiBaseUrl,timeoutMs:e.defillamaTimeoutMs??Math.min(Number(e.timeoutMs??5e3),5e3)});return Array.isArray(t)?t:[]}catch{return[]}}function sn(e,t={}){let r=N(t.tool||t.provider||t.bridge||t.protocol),n=[];return e==="lifi"&&r&&r!=="lifi"&&n.push(...lt[r]||[r]),n.push(...lt[N(e)]||[e]),n}function cn(e,t,r={}){let n=Array.isArray(e)?e:[],o=sn(t,r).map(N).filter(Boolean);for(let s of o){let u=n.find(i=>N(i?.slug)===s||N(i?.name)===s),c=v(u?.tvl);if(c!=null)return{liquidityUsd:c,protocol:u?.name??u?.slug??s}}for(let s of o){let u=n.find(i=>{let d=N(i?.category);return!d.includes("bridge")&&!d.includes("crosschain")?!1:N(i?.slug).includes(s)||N(i?.name).includes(s)}),c=v(u?.tvl);if(c!=null)return{liquidityUsd:c,protocol:u?.name??u?.slug??s}}return null}function de({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,taker:o,slippageBps:s,decimalsIn:u,decimalsOut:c,nativePriceUsd:i=null,destDecimalsPromise:d=null,opts:p={}}){let l=[];return l.push({source:"lifi",run:async()=>{let a=await ie({fromChain:e,toChain:e,fromToken:t,toToken:r,fromAmount:n},p),m=a?.estimate??a?.[0]?.estimate;return{amountOut:m?.toAmount,minOut:m?.toAmountMin,gasUsd:Z(m?.gasCosts),feeUsd:Z(m?.feeCosts),meta:{tool:a?.tool??a?.toolDetails?.name}}}}),u!=null&&l.push({source:"paraswap",run:async()=>{let a=c??(await Promise.resolve(d))?.decimals;if(a==null)throw new Error("paraswap needs destination decimals; none supplied or resolvable");let h=(await Le({chainId:e,srcToken:t,destToken:r,amount:n,srcDecimals:u,destDecimals:a},p))?.priceRoute;return{amountOut:h?.destAmount,gasUsd:v(h?.gasCostUSD),meta:{bestRoute:h?.bestRoute?.[0]?.swaps?.[0]?.swapExchanges?.[0]?.exchange}}}}),process.env.ZEROX_API_KEY&&l.push({source:"0x",run:async()=>{let a=await qe({chainId:e,sellToken:t,buyToken:r,sellAmount:n,taker:o},p),m=null,h=a?.totalNetworkFee,w=await Promise.resolve(i);return h!=null&&w&&(m=Number(h)/1e18*w),{amountOut:a?.buyAmount,minOut:a?.minBuyAmount,gasUsd:m,meta:{source:a?.route?.fills?.[0]?.source}}}}),process.env.ONEINCH_API_KEY&&l.push({source:"1inch",run:async()=>{let a=await je({chainId:e,src:t,dst:r,amount:n},p),m=null;return a?.gas!=null&&i&&(m=null),{amountOut:a?.dstAmount,gasUsd:m,meta:{gasUnits:a?.gas}}}}),l.push({source:"cow",run:async()=>{let a=await Ge({chainId:e,sellToken:t,buyToken:r,sellAmountBeforeFee:String(n),from:o},p),m=a?.quote??a,h=m?.feeAmount;return{amountOut:m?.buyAmount,gasUsd:0,meta:{intent:!0,feeAmountInSellToken:h,settlement:"solver-executed"}}}}),$[Number(e)]&&l.push({source:"uniswap-v3",run:async()=>{let a=await Ze({chainId:e,tokenIn:t,tokenOut:r,amountIn:n},p);return{amountOut:a?.amountOut,minOut:a?.minOut??a?.amountOutMinimum??null,gasUsd:null,liquidityUsd:a?.liquidityUsd??null,meta:{onchain:!0,fee:a?.fee,gasUnits:a?.gasEstimate,quoter:a?.quoter}}}}),D[Number(e)]&&l.push({source:"uniswap-v4",run:async()=>{let a=await nt({chainId:e,tokenIn:t,tokenOut:r,amountIn:n,recipient:o,slippageBps:s},p);return{amountOut:a?.amountOut,minOut:a?.minOut??a?.amountOutMinimum??null,gasUsd:null,liquidityUsd:a?.liquidityUsd??null,meta:{onchain:!0,venue:"uniswap-v4",fee:a?.fee,tickSpacing:a?.tickSpacing,poolId:a?.poolId,hooks:a?.hooks,gasUnits:a?.gasEstimate,quoter:a?.quoter,poolManager:a?.poolManager,prepareReady:a?.prepareReady===!0,executionReady:!1}}}}),l}function pt({fromChainId:e,toChainId:t,tokenIn:r,tokenOut:n,amountIn:o,taker:s,opts:u={}}){let c=[],i=null,d=async(p,l={})=>(i||=an(u),cn(await i,p,l));return c.push({source:"lifi",run:async()=>{let p=await ie({fromChain:e,toChain:t,fromToken:r,toToken:n,fromAmount:o},u),l=p?.estimate??p?.[0]?.estimate,a={tool:p?.tool??p?.toolDetails?.name,durationSeconds:v(l?.executionDuration)},m=await d("lifi",a);return{amountOut:l?.toAmount,minOut:l?.toAmountMin,gasUsd:Z(l?.gasCosts),feeUsd:Z(l?.feeCosts),liquidityUsd:m?.liquidityUsd??null,meta:{...a,liquidityProtocol:m?.protocol}}}}),c.push({source:"relay",run:async()=>{let{relayQuote:p}=await Promise.resolve().then(()=>(le(),ue)),a=(await p({user:s,originChainId:e,destinationChainId:t,originCurrency:r,destinationCurrency:n,amount:String(o)},u))?.details,m={durationSeconds:v(a?.timeEstimate),rate:a?.rate},h=await d("relay",m);return{amountOut:a?.currencyOut?.amount,minOut:a?.currencyOut?.minimumAmount,gasUsd:v(a?.totalImpact?.usd)!=null?Math.abs(v(a.totalImpact.usd)):null,liquidityUsd:h?.liquidityUsd??null,meta:{...m,liquidityProtocol:h?.protocol}}}}),c.push({source:"across",run:async()=>{let{acrossSuggestedFees:p}=await Promise.resolve().then(()=>(le(),ue)),l=await p({token:r,destinationToken:n,originChainId:e,destinationChainId:t,amount:String(o)},u),a=l?.totalRelayFee?.total,m=null;if(a!=null)try{let w=BigInt(String(o))-BigInt(String(a));w>0n&&(m=w.toString())}catch{}let h=await d("across");return{amountOut:m,gasUsd:null,liquidityUsd:h?.liquidityUsd??null,meta:{derivedFromFees:!0,durationSeconds:v(l?.estimatedFillTimeSec),limits:l?.limits?{min:l.limits.minDeposit,max:l.limits.maxDeposit}:void 0,liquidityProtocol:h?.protocol}}}}),c}var un={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"};async function mt(e,t,r){let n=un[Number(e)];if(!n)return{priceUsd:null,decimals:null};let o=`${n}:${t}`;try{let u=(await J([o],r))?.coins?.[o],c=Number(u?.price),i=Number(u?.decimals);return{priceUsd:Number.isFinite(c)?c:null,decimals:Number.isFinite(i)?i:null}}catch{return{priceUsd:null,decimals:null}}}async function Ea(e,t={}){let{chainId:r,tokenIn:n,tokenOut:o,amountIn:s}=e;if(r==null||!n||!o||s==null)throw new Error("bestSwapRoute requires chainId, tokenIn, tokenOut, amountIn");let u=dt(r,t),c=mt(r,o,t),i=de({...e,nativePriceUsd:u,decimalsOut:e.decimalsOut,destDecimalsPromise:c,opts:t}),[d,p]=await Promise.all([H(i,{timeoutMs:t.timeoutMs??12e3}),c]);u.catch(()=>{});let l=te(d,{destPriceUsd:p.priceUsd,destDecimals:e.decimalsOut??p.decimals,liquidityBandBps:t.liquidityBandBps??50}),a=t.maxImpactPct===void 0?25:t.maxImpactPct;if(a!=null&&l.best){let m=l.best.source,w=await he(async g=>{let f=de({...e,amountIn:g.toString(),nativePriceUsd:u,decimalsOut:e.decimalsOut,destDecimalsPromise:c,opts:t}).filter(E=>E.source===m);return f.length?(await H(f,{timeoutMs:t.timeoutMs??12e3}))?.[0]?.amountOut??null:null},s);if(w){let g=we(l,{[m]:w},{maxImpactPct:a});return{kind:"swap",chainId:r,tokenIn:n,tokenOut:o,amountIn:String(s),...g,sourcesTried:i.length,sourcesAnswered:d.filter(f=>f.quality!==S.FAILED).length,note:pe(g,i.length),priceImpact:{[m]:Number(w.impactPct.toFixed(2))}}}}return{kind:"swap",chainId:r,tokenIn:n,tokenOut:o,amountIn:String(s),...l,sourcesTried:i.length,sourcesAnswered:d.filter(m=>m.quality!==S.FAILED).length,note:pe(l,i.length)}}async function ya(e,t={}){let{fromChainId:r,toChainId:n,tokenIn:o,tokenOut:s,amountIn:u}=e;if(r==null||n==null||!o||!s||u==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 c=mt(n,s,t),i=pt({...e,opts:t}),[d,p]=await Promise.all([H(i,{timeoutMs:t.timeoutMs??15e3}),c]),l=te(d,{destPriceUsd:p.priceUsd,destDecimals:e.decimalsOut??p.decimals,liquidityBandBps:t.liquidityBandBps??50}),a=l.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:s,amountIn:String(u),...l,durations:a,sourcesTried:i.length,sourcesAnswered:d.filter(m=>m.quality!==S.FAILED).length,note:pe(l,i.length)}}function pe(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 s=o>=.01?`${o.toFixed(2)}%`:`${n.toFixed(2)}bps`;return`best of ${r} routes, ranked on ${e.rankedOn}: ${s} 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.`}export{S as QUALITY,ya as bestBridgeRoute,Ea as bestSwapRoute,pe as formatComparisonNote};
@@ -1,4 +1,4 @@
1
- var x=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),b=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),f=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),oe=/^0x[0-9a-fA-F]{40}$/;function ie(e={}){let t=[],o=[];if(!e||typeof e!="object")return{ok:!1,errors:["definition must be an object"],warnings:o};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 r of e.rpcEnv)(typeof r!="string"||!/^[A-Z][A-Z0-9_]*$/.test(r))&&t.push(`rpcEnv entry "${r}" should be an UPPER_SNAKE env var name`);if(e.nativeCurrency){let r=e.nativeCurrency;(typeof r.symbol!="string"||!r.symbol)&&t.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(r.decimals)||t.push("nativeCurrency.decimals must be an integer")}for(let[r,n]of(e.venues||[]).entries()){let i=`venues[${r}]`;if(!n||typeof n!="object"){t.push(`${i} must be an object`);continue}oe.test(n.address||"")||t.push(`${i}.address is not a valid 20-byte address`),/^0x0{40}$/.test(n.address||"")&&t.push(`${i}.address is the zero address -- placeholder left in place?`),n.kind||t.push(`${i}.kind is required (router|quoter|factory|...)`),n.verified?(n.verified.method||t.push(`${i}.verified.method is required`),n.verified.source||t.push(`${i}.verified.source is required`),n.verified.date||o.push(`${i}.verified.date missing -- add one so staleness is visible`)):t.push(`${i} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let a=e.capabilities||{};for(let r of Object.keys(a))x.includes(r)?typeof a[r]!="function"&&t.push(`capability "${r}" must be a function`):t.push(`unknown capability "${r}"`);return Object.keys(a).length===0&&o.push("scanner implements no capabilities -- it can only be registered, not used"),a.prepareUnsignedTx&&!a.quote&&o.push("prepareUnsignedTx without quote: no priced expectation to validate the built tx against"),a.prepareUnsignedTx&&!a.sellSimulation&&o.push("prepareUnsignedTx without sellSimulation: cannot prove an asset is exitable before buying"),{ok:t.length===0,errors:t,warnings:o}}function se(e){let{ok:t,errors:o,warnings:a}=ie(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
2
- - ${o.join(`
3
- - `)}`);let r=e.capabilities||{},n=x.filter(s=>typeof r[s]=="function"),i={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(s=>({...s})),warnings:a,capabilities(){return{chainId:e.chainId,key:e.key,supported:[...n],unsupported:x.filter(s=>!n.includes(s))}},supports(s){return n.includes(s)}};for(let s of x)n.includes(s)?i[s]=async(...c)=>r[s](...c,{scanner:i}):i[s]=async()=>{throw new Error(`${e.key} (chain ${e.chainId}) does not implement "${s}". Supported: ${n.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(i)}var S=new Map;function R(e){let t=se(e);return S.set(t.chainId,t),t}function Fe(e){return S.get(Number(e))||null}function Pe(){return[...S.values()]}function De(){S.clear()}function $e(){let e={};for(let t of S.values())e[t.chainId]={key:t.key,name:t.name,...t.capabilities(),venueCount:t.venues.length,failClosed:t.venues.length===0};return{generatedAt:new Date().toISOString(),chainCount:S.size,capabilities:[...x],chains:e}}import{createHash as ce}from"node:crypto";var ue=new Set([408,425,429,500,502,503,504]),D=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),de=2,$=4e3,H=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],le=new Set([301,302,303,307,308]),V=3;function pe(e){let t=String(e||"").toLowerCase();return H.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function he(e){let t={};for(let[o,a]of Object.entries(e||{}))pe(o)||(t[o]=a);return t}function me(e,t){if(!e)throw new Error(`HTTP redirect from ${t} missing Location`);let o=new URL(String(e),String(t));if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error(`HTTP redirect from ${t} used unsupported protocol ${o.protocol}`);return o.toString()}function fe(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}var T=new Map;function be(e,t,o){let a={};for(let[c,u]of Object.entries(o||{}))a[c.toLowerCase()]=u;let r=Object.keys(a).filter(c=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(c)),i=[...new Set([...H,...r])].sort().map(c=>`${c}=${a[c]??""}`).join(`
4
- `),s=ce("sha256").update(i).digest("hex").slice(0,32);return`${e} ${t} ${s}`}function ve(e,t){let o=Number(t);return Number.isFinite(o)&&o>0?Math.min(o*1e3,$):Math.min(250*2**e,$)+Math.floor(Math.random()*100)}var ye=e=>new Promise(t=>setTimeout(t,e));async function ge(e,{fetchImpl:t,method:o,headers:a,body:r,timeoutMs:n}){let i=new AbortController,s=setTimeout(()=>i.abort(),n);try{let c=String(e),u={...a||{}};for(let l=0;l<=V;l+=1){let d=await t(c,{method:o,headers:u,body:r,signal:i.signal,redirect:"manual"}),m=await d.text(),h=null;if(m)try{h=JSON.parse(m)}catch{h=null}if(le.has(d.status)){if(o!=="GET"&&o!=="HEAD"){let v=new Error(`HTTP ${d.status} ${o} ${c} redirected non-idempotent request`);throw v.status=d.status,v.body=h??m.slice(0,300),v}if(l===V)throw new Error(`HTTP redirect loop for ${e}`);let p=me(d.headers?.get?.("location"),c);fe(p,c)||(u=he(u)),c=p;continue}if(!d.ok){let p=new Error(`HTTP ${d.status} ${o} ${c}`);throw p.status=d.status,p.retryAfter=d.headers?.get?.("retry-after")??null,p.body=h??m.slice(0,300),p}return h??m}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(s)}}async function U(e,t={}){let o=t.fetchImpl||globalThis.fetch;if(typeof o!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let a=t.timeoutMs??12e3,r=(t.method||"GET").toUpperCase(),n={Accept:"application/json",...t.headers||{}},i=t.body;i!=null&&typeof i!="string"&&(n["Content-Type"]=n["Content-Type"]||"application/json",i=JSON.stringify(i));let s=Number.isInteger(t.retries)?Math.max(t.retries,0):de,c=async()=>{let h;for(let p=0;p<=s;p++)try{return await ge(e,{fetchImpl:o,method:r,headers:n,body:i,timeoutMs:a})}catch(v){h=v;let y=v?.status,I=v?.name==="AbortError",C=new Set([408,425,429]),k=y!=null?C.has(y)||ue.has(y)&&D.has(r):!I&&D.has(r);if(p===s||!k)throw v;await ye(ve(p,v?.retryAfter))}throw h};if(!(t.dedupe!==!1&&r==="GET"&&i==null))return c();let l=be(r,e,n),d=T.get(l);if(d)return d;let m=c().finally(()=>T.delete(l));return T.set(l,m),m}var M={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}},we=new Map(Object.values(M).map(e=>[e.chainId,e]));function j(e){return we.get(Number(e))||null}function K(e,t=process.env){let o=j(e);if(!o)return null;for(let a of o.rpcEnv){let r=(t[a]||"").trim();if(r)return r}return null}import{Interface as Ee,getAddress as Se}from"ethers";var W=new Ee(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function z(e,t){try{return Se(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}var Ie={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"};function Ce(e,{rpcUrl:t,env:o=process.env}={}){if(t)return t;let a=K(e,o);return a||Ie[Number(e)]||null}var xe=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Ae(e){let t=String(e||""),o=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!xe.test(o))throw new Error(`evm-rpc: ${t} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return o}async function w(e,t,o=[],a={}){let r=String(t||"");Ae(r);let n=Ce(e,a);if(!n)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let s=await U(n,{method:"POST",body:{jsonrpc:"2.0",id:1,method:t,params:o},fetchImpl:a.fetchImpl,timeoutMs:a.timeoutMs??12e3});if(s?.error){let c=new Error(s.error.message||JSON.stringify(s.error));throw c.code=s.error.code,c}return s.result}async function G(e,t={}){let o=await w(e,"eth_blockNumber",[],t);return parseInt(o,16)}async function Y(e,t,o={}){if(!t)throw new Error("rpcGetBalance requires address");let a=await w(e,"eth_getBalance",[t,"latest"],o);return{chainId:Number(e),address:t,balanceWei:BigInt(a).toString(),balanceHex:a}}async function Q(e={},t={}){let o=Number(e.chainId??t.chainId??1),a=z(e.token||e.tokenAddress,"token"),r=z(e.account||e.owner||e.address,"account"),n=W.encodeFunctionData("balanceOf",[r]),i=await w(o,"eth_call",[{to:a,data:n},e.blockTag||"latest"],t),s=W.decodeFunctionResult("balanceOf",i),c=BigInt(s[0]);return{chainId:o,token:a,account:r,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:e.blockTag||"latest"}}var Ne="https://api.dexscreener.com";function Ue(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||Ne).replace(/\/$/,"")}async function X(e,t={}){if(!e)throw new Error("tokenAddress required");return U(`${Ue(t)}/latest/dex/tokens/${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}var q={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},g=e=>BigInt(e).toString(16).padStart(64,"0"),A=e=>e.slice(2).toLowerCase().padStart(64,"0");function _e(e,t){return`0x${q.getAmountsOut}`+g(e)+g(64)+g(t.length)+t.map(A).join("")}function ke(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length<128)return null;let o=Number(BigInt(`0x${t.slice(64,128)}`));if(!Number.isFinite(o)||o<1||o>16)return null;let a=[];for(let r=0;r<o;r++){let n=128+r*64;if(t.length<n+64)return null;a.push(BigInt(`0x${t.slice(n,n+64)}`))}return a}function L(e,t="router"){return(e?.venues||[]).find(a=>a.kind===t)?.address??null}var B=100;function Re(e,t){let o=Number(t);if(!Number.isFinite(o)||o<0)throw new Error("slippageBps must be a non-negative number");if(o>B)throw new Error(`slippageBps ${o} exceeds the ${B} 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(o))/10000n}function J(e){let{chainId:t,wrappedNative:o}=e;async function a(r,n,i,s){let c=await w(t,"eth_call",[{to:r,data:_e(n,i)},"latest"],s);return ke(c?.result??c)}return{async quote({tokenIn:r,tokenOut:n,amountIn:i,path:s},c={}){let u=L(c.scanner);if(!u)return{chainId:t,evidence:b.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let l=s||[r,n];if(l.some(m=>!/^0x[0-9a-fA-F]{40}$/.test(m||"")))throw new Error("quote requires valid 20-byte addresses");let d=await a(u,i,l,c);return d?{chainId:t,router:u,path:l,amountIn:String(i),amountOut:d[d.length-1].toString(),hops:l.length-1,evidence:b.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:u,path:l,evidence:b.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:r,amountIn:n,base:i},s={}){let c=L(s.scanner),u=i||o;if(u&&String(r).toLowerCase()===String(u).toLowerCase())return{chainId:t,token:r,verdict:f.UNKNOWN,evidence:b.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:r,verdict:f.UNKNOWN,evidence:b.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 l=await a(c,n,[u,r],s);if(!l)return{chainId:t,token:r,verdict:f.FAIL,evidence:b.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let d=l[l.length-1];if(d===0n)return{chainId:t,token:r,verdict:f.FAIL,evidence:b.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let m=await a(c,d,[r,u],s);if(!m)return{chainId:t,token:r,verdict:f.FAIL,evidence:b.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 h=m[m.length-1],p=Number(h*10000n/BigInt(n)),v=f.PASS,y="round trip completes with expected fee/impact loss";return p<5e3?(v=f.FAIL,y=`round trip returns only ${(p/100).toFixed(2)}% -- punitive tax or no real liquidity`):p<9e3&&(v=f.CAUTION,y=`round trip returns ${(p/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:r,base:u,router:c,verdict:v,reason:y,amountIn:String(n),bought:d.toString(),returned:h.toString(),retentionBps:p,evidence:b.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:r,tokenOut:n,amountIn:i,recipient:s,slippageBps:c=50,deadlineSeconds:u=900,path:l},d={}){let m=d.scanner,h=L(m);if(!h)throw new Error(`chain ${t} has no verified router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!/^0x[0-9a-fA-F]{40}$/.test(s||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let p=l||[r,n],v=await this.quote({tokenIn:r,tokenOut:n,amountIn:i,path:p},d);if(v.evidence!==b.LIVE)throw new Error(`cannot prepare without a live quote (${v.evidence}: ${v.reason??"no reason given"})`);let y=Re(v.amountOut,c);if(y<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let I=BigInt(Math.floor(Date.now()/1e3)+Number(u)),C=o&&p[0].toLowerCase()===o.toLowerCase()&&d.useNative,k=C?`0x${q.swapExactETHForTokens}`+g(y)+g(128)+A(s)+g(I)+g(p.length)+p.map(A).join(""):`0x${q.swapExactTokensForTokens}`+g(i)+g(y)+g(160)+A(s)+g(I)+g(p.length)+p.map(A).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:h,data:k,value:C?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:v.amountOut,minOut:y.toString(),slippageBps:c,maxSlippageBps:B,deadline:I.toString()},requires:C?[]:[{step:"approve",token:p[0],spender:h,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 Te=[100,500,3e3,1e4],Z={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},E=e=>BigInt(e).toString(16).padStart(64,"0"),N=e=>e.slice(2).toLowerCase().padStart(64,"0"),ee=/^0x[0-9a-fA-F]{40}$/,F=100;function Le(e,t){let o=Number(t);if(!Number.isFinite(o)||o<0)throw new Error("slippageBps must be a non-negative number");if(o>F)throw new Error(`slippageBps ${o} exceeds the ${F} 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(o))/10000n}function O(e,t){return(e?.venues||[]).find(o=>o.kind===t)?.address??null}function te(e){let{chainId:t,wrappedNative:o}=e;async function a({quoter:n,tokenIn:i,tokenOut:s,amountIn:c,fee:u},l){let d=`0x${Z.quoteExactInputSingle}`+N(i)+N(s)+E(c)+E(u)+E(0),m=await w(t,"eth_call",[{to:n,data:d},"latest"],l).catch(()=>null),h=m?.result??m;if(!h||h==="0x"||h.length<66)return null;let p=BigInt(`0x${h.slice(2,66)}`);return p>0n?p:null}async function r({quoter:n,tokenIn:i,tokenOut:s,amountIn:c},u){let l=[],d=null;for(let m of Te){let h=await a({quoter:n,tokenIn:i,tokenOut:s,amountIn:c,fee:m},u);l.push({fee:m,amountOut:h?h.toString():null}),h&&(!d||h>d.amountOut)&&(d={fee:m,amountOut:h})}return{best:d,tried:l}}return{async quote({tokenIn:n,tokenOut:i,amountIn:s},c={}){let u=O(c.scanner,"quoter");if(!u)return{chainId:t,evidence:b.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let m of[n,i])if(!ee.test(m||""))throw new Error("quote requires valid 20-byte addresses");let{best:l,tried:d}=await r({quoter:u,tokenIn:n,tokenOut:i,amountIn:s},c);return l?{chainId:t,venue:"uniswap-v3",quoter:u,tokenIn:n,tokenOut:i,amountIn:String(s),amountOut:l.amountOut.toString(),fee:l.fee,triedFeeTiers:d,evidence:b.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:u,tokenIn:n,tokenOut:i,triedFeeTiers:d,evidence:b.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:n,amountIn:i,base:s},c={}){let u=O(c.scanner,"quoter"),l=s||o;if(l&&String(n).toLowerCase()===String(l).toLowerCase())return{chainId:t,token:n,verdict:f.UNKNOWN,evidence:b.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!u||!l)return{chainId:t,token:n,verdict:f.UNKNOWN,evidence:b.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 r({quoter:u,tokenIn:l,tokenOut:n,amountIn:i},c);if(!d.best)return{chainId:t,token:n,verdict:f.FAIL,evidence:b.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier"};let m=await r({quoter:u,tokenIn:n,tokenOut:l,amountIn:d.best.amountOut},c);if(!m.best)return{chainId:t,token:n,verdict:f.FAIL,evidence:b.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 h=m.best.amountOut,p=Number(h*10000n/BigInt(i)),v=f.PASS,y="round trip completes with expected fee/impact loss";return p<5e3?(v=f.FAIL,y=`round trip returns only ${(p/100).toFixed(2)}% -- punitive tax or no real liquidity`):p<9e3&&(v=f.CAUTION,y=`round trip returns ${(p/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:n,base:l,verdict:v,reason:y,amountIn:String(i),bought:d.best.amountOut.toString(),returned:h.toString(),retentionBps:p,buyFee:d.best.fee,sellFee:m.best.fee,evidence:b.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:n,tokenOut:i,amountIn:s,recipient:c,slippageBps:u=50,fee:l},d={}){let m=O(d.scanner,"router");if(!m)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(!ee.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let h=await this.quote({tokenIn:n,tokenOut:i,amountIn:s},d);if(h.evidence!==b.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let p=l??h.fee,v=Le(h.amountOut,u);if(v<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let y=`0x${Z.exactInputSingle}`+N(n)+N(i)+E(p)+N(c)+E(s)+E(v)+E(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:m,data:y,value:"0x0"},guard:{quotedOut:h.amountOut,minOut:v.toString(),slippageBps:u,maxSlippageBps:F,fee:p},requires:[{step:"approve",token:n,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."}}}}var _={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function ne(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function re(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length>=128){let a=Number(BigInt(`0x${t.slice(64,128)}`));if(a>0&&a<=256&&t.length>=128+a*2){let r=t.slice(128,128+a*2),n=Buffer.from(r,"hex").toString("utf8").replace(/\0+$/,"");if(n)return n}}return Buffer.from(t.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function qe(e){let{chainId:t}=e;async function o(a,r,n){return w(t,"eth_call",[{to:a,data:r},"latest"],n)}return{async blockNumber(a={}){let r=await G(t,a);return{chainId:t,blockNumber:r?.blockNumber??r,evidence:b.LIVE}},async nativeBalance(a,r={}){let n=await Y(t,a,r);return{chainId:t,address:a,wei:n?.wei??n?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:b.LIVE}},async tokenBalance({token:a,owner:r},n={}){let i=await Q({chainId:t,token:a,owner:r},n);return{chainId:t,token:a,owner:r,raw:i?.balance??i,evidence:b.LIVE}},async resolveToken(a,r={}){if(!/^0x[0-9a-fA-F]{40}$/.test(a||""))return{chainId:t,token:a,evidence:b.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[n,i,s,c]=await Promise.all([o(a,_.decimals,r).catch(()=>null),o(a,_.symbol,r).catch(()=>null),o(a,_.name,r).catch(()=>null),o(a,_.totalSupply,r).catch(()=>null)]),u=ne(n?.result??n),l=u!==null||i?.result||s?.result;return{chainId:t,address:a,decimals:u===null?null:Number(u),symbol:re(i?.result??i),name:re(s?.result??s),totalSupply:(ne(c?.result??c)??null)?.toString()??null,evidence:l?b.LIVE:b.UNKNOWN,warning:l?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(a,r={}){let n=e.dexscreenerSlug;if(!n)return{chainId:t,token:a,pools:[],evidence:b.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await X(a,r).catch(()=>null),c=(i?.pairs||i?.data?.pairs||[]).filter(u=>String(u.chainId).toLowerCase()===String(n).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,l)=>(l.liquidityUsd??0)-(u.liquidityUsd??0));return{chainId:t,token:a,pools:c,evidence:c.length?b.LIVE:b.UNKNOWN}},async scanBlocks({fromBlock:a,toBlock:r,address:n,topics:i,chunkSize:s=2e3}={},c={}){if(!Number.isInteger(a)||!Number.isInteger(r))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(r<a)throw new Error("toBlock must be >= fromBlock");let u=[],l=[];for(let d=a;d<=r;d+=s){let m=Math.min(d+s-1,r);l.push([d,m])}for(let[d,m]of l){let h={fromBlock:`0x${d.toString(16)}`,toBlock:`0x${m.toString(16)}`};n&&(h.address=n),i&&(h.topics=i);let p=await w(t,"eth_getLogs",[h],c).catch(v=>({error:String(v?.message||v)}));if(p?.error)return{chainId:t,fromBlock:a,toBlock:r,logs:u,complete:!1,failedAt:[d,m],error:p.error,evidence:b.UNKNOWN};for(let v of p?.result??p??[])u.push(v)}return{chainId:t,fromBlock:a,toBlock:r,logs:u,complete:!0,chunks:l.length,evidence:b.LIVE}},async scoreRisk(a,r={}){let n=[],i=f.PASS,s=l=>{let d={[f.PASS]:0,[f.CAUTION]:1,[f.UNKNOWN]:2,[f.FAIL]:3};d[l]>d[i]&&(i=l)},c=await this.resolveToken(a,r);c.evidence!==b.LIVE?(n.push({check:"erc20-metadata",result:f.UNKNOWN,detail:c.warning}),s(f.UNKNOWN)):n.push({check:"erc20-metadata",result:f.PASS,detail:`${c.symbol} / ${c.decimals}d`});let u=await this.resolvePools(a,r);if(u.evidence===b.UNAVAILABLE)n.push({check:"liquidity",result:f.UNKNOWN,detail:u.reason}),s(f.UNKNOWN);else if(!u.pools.length)n.push({check:"liquidity",result:f.FAIL,detail:"no pool with liquidity found"}),s(f.FAIL);else{let l=u.pools[0],d=l.liquidityUsd??0;d<5e3?(n.push({check:"liquidity",result:f.CAUTION,detail:`top pool only $${d}`}),s(f.CAUTION)):n.push({check:"liquidity",result:f.PASS,detail:`$${d} on ${l.dex}`}),l.createdAt&&Date.now()-l.createdAt<24*3600*1e3&&(n.push({check:"age",result:f.CAUTION,detail:"pool under 24h old"}),s(f.CAUTION))}if(typeof this.sellSimulation=="function"){let l=await this.sellSimulation({token:a,amountIn:(10n**16n).toString()},r).catch(d=>({verdict:f.UNKNOWN,reason:String(d?.message||d)}));n.push({check:"sellability",result:l.verdict,detail:l.retentionBps!=null?`round trip returns ${(l.retentionBps/100).toFixed(2)}% -- ${l.reason}`:l.reason}),s(l.verdict)}else n.push({check:"sellability",result:f.UNKNOWN,detail:"no verified router on this chain, so a round-trip sell simulation cannot run. Treat as unproven -- a buy path is not an exit path."}),s(f.UNKNOWN);return{chainId:t,token:a,verdict:i,checks:n,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function P(e){let o={...qe(e)},a=new Set((e.venues||[]).map(n=>n.kind));e.venueKind==="uniswap-v3"&&a.has("quoter")&&a.has("router")?Object.assign(o,te({chainId:e.chainId,wrappedNative:e.wrappedNative})):e.venueKind==="uniswap-v2"&&a.has("router")&&Object.assign(o,J({chainId:e.chainId,wrappedNative:e.wrappedNative}));let r={};for(let[n,i]of Object.entries(o))r[n]=i.bind(o);return{key:e.key,chainId:e.chainId,name:e.name,rpcEnv:e.rpcEnv,nativeCurrency:e.nativeCurrency,explorer:e.explorer,venues:e.venues||[],capabilities:r}}var ae=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 Be(){return ae.map(e=>R(P(e)))}function Oe(e){return R(P(e))}export{ae as CHAIN_CONFIGS,b as EVIDENCE,f as RISK,x as SCANNER_CAPABILITIES,De as __clearScanners,se as createScanner,Fe as getScanner,Pe as listScanners,Be as registerBuiltinScanners,Oe as registerCustomChain,R as registerScanner,$e as scannerCoverage,ie as validateScanner};
1
+ var C=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),b=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),f=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),ie=/^0x[0-9a-fA-F]{40}$/;function oe(e={}){let t=[],i=[];if(!e||typeof e!="object")return{ok:!1,errors:["definition must be an object"],warnings:i};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 n of e.rpcEnv)(typeof n!="string"||!/^[A-Z][A-Z0-9_]*$/.test(n))&&t.push(`rpcEnv entry "${n}" should be an UPPER_SNAKE env var name`);if(e.nativeCurrency){let n=e.nativeCurrency;(typeof n.symbol!="string"||!n.symbol)&&t.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(n.decimals)||t.push("nativeCurrency.decimals must be an integer")}for(let[n,r]of(e.venues||[]).entries()){let o=`venues[${n}]`;if(!r||typeof r!="object"){t.push(`${o} must be an object`);continue}ie.test(r.address||"")||t.push(`${o}.address is not a valid 20-byte address`),/^0x0{40}$/.test(r.address||"")&&t.push(`${o}.address is the zero address -- placeholder left in place?`),r.kind||t.push(`${o}.kind is required (router|quoter|factory|...)`),r.verified?(r.verified.method||t.push(`${o}.verified.method is required`),r.verified.source||t.push(`${o}.verified.source is required`),r.verified.date||i.push(`${o}.verified.date missing -- add one so staleness is visible`)):t.push(`${o} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let a=e.capabilities||{};for(let n of Object.keys(a))C.includes(n)?typeof a[n]!="function"&&t.push(`capability "${n}" must be a function`):t.push(`unknown capability "${n}"`);return Object.keys(a).length===0&&i.push("scanner implements no capabilities -- it can only be registered, not used"),a.prepareUnsignedTx&&!a.quote&&i.push("prepareUnsignedTx without quote: no priced expectation to validate the built tx against"),a.prepareUnsignedTx&&!a.sellSimulation&&i.push("prepareUnsignedTx without sellSimulation: cannot prove an asset is exitable before buying"),{ok:t.length===0,errors:t,warnings:i}}function se(e){let{ok:t,errors:i,warnings:a}=oe(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
2
+ - ${i.join(`
3
+ - `)}`);let n=e.capabilities||{},r=C.filter(s=>typeof n[s]=="function"),o={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(s=>({...s})),warnings:a,capabilities(){return{chainId:e.chainId,key:e.key,supported:[...r],unsupported:C.filter(s=>!r.includes(s))}},supports(s){return r.includes(s)}};for(let s of C)r.includes(s)?o[s]=async(...c)=>n[s](...c,{scanner:o}):o[s]=async()=>{throw new Error(`${e.key} (chain ${e.chainId}) does not implement "${s}". Supported: ${r.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(o)}var S=new Map;function R(e){let t=se(e);return S.set(t.chainId,t),t}function Pe(e){return S.get(Number(e))||null}function De(){return[...S.values()]}function Fe(){S.clear()}function $e(){let e={};for(let t of S.values())e[t.chainId]={key:t.key,name:t.name,...t.capabilities(),venueCount:t.venues.length,failClosed:t.venues.length===0};return{generatedAt:new Date().toISOString(),chainCount:S.size,capabilities:[...C],chains:e}}import{createHash as ce}from"node:crypto";var ue=new Set([408,425,429,500,502,503,504]),F=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),de=2,$=4e3,H=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],le=new Set([301,302,303,307,308]),V=3;function pe(e){let t=String(e||"").toLowerCase();return H.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function he(e){let t={};for(let[i,a]of Object.entries(e||{}))pe(i)||(t[i]=a);return t}function me(e,t){if(!e)throw new Error(`HTTP redirect from ${t} missing Location`);let i=new URL(String(e),String(t));if(i.protocol!=="http:"&&i.protocol!=="https:")throw new Error(`HTTP redirect from ${t} used unsupported protocol ${i.protocol}`);return i.toString()}function fe(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}var T=new Map;function be(e,t,i){let a={};for(let[c,u]of Object.entries(i||{}))a[c.toLowerCase()]=u;let n=Object.keys(a).filter(c=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(c)),o=[...new Set([...H,...n])].sort().map(c=>`${c}=${a[c]??""}`).join(`
4
+ `),s=ce("sha256").update(o).digest("hex").slice(0,32);return`${e} ${t} ${s}`}function ve(e,t){let i=Number(t);return Number.isFinite(i)&&i>0?Math.min(i*1e3,$):Math.min(250*2**e,$)+Math.floor(Math.random()*100)}var ye=e=>new Promise(t=>setTimeout(t,e));async function ge(e,{fetchImpl:t,method:i,headers:a,body:n,timeoutMs:r}){let o=new AbortController,s=setTimeout(()=>o.abort(),r);try{let c=String(e),u={...a||{}};for(let l=0;l<=V;l+=1){let d=await t(c,{method:i,headers:u,body:n,signal:o.signal,redirect:"manual"}),m=await d.text(),h=null;if(m)try{h=JSON.parse(m)}catch{h=null}if(le.has(d.status)){if(i!=="GET"&&i!=="HEAD"){let v=new Error(`HTTP ${d.status} ${i} ${c} redirected non-idempotent request`);throw v.status=d.status,v.body=h??m.slice(0,300),v}if(l===V)throw new Error(`HTTP redirect loop for ${e}`);let p=me(d.headers?.get?.("location"),c);fe(p,c)||(u=he(u)),c=p;continue}if(!d.ok){let p=new Error(`HTTP ${d.status} ${i} ${c}`);throw p.status=d.status,p.retryAfter=d.headers?.get?.("retry-after")??null,p.body=h??m.slice(0,300),p}return h??m}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(s)}}async function U(e,t={}){let i=t.fetchImpl||globalThis.fetch;if(typeof i!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let a=t.timeoutMs??12e3,n=(t.method||"GET").toUpperCase(),r={Accept:"application/json",...t.headers||{}},o=t.body;o!=null&&typeof o!="string"&&(r["Content-Type"]=r["Content-Type"]||"application/json",o=JSON.stringify(o));let s=Number.isInteger(t.retries)?Math.max(t.retries,0):de,c=async()=>{let h;for(let p=0;p<=s;p++)try{return await ge(e,{fetchImpl:i,method:n,headers:r,body:o,timeoutMs:a})}catch(v){h=v;let y=v?.status,I=v?.name==="AbortError",x=new Set([408,425,429]),k=y!=null?x.has(y)||ue.has(y)&&F.has(n):!I&&F.has(n);if(p===s||!k)throw v;await ye(ve(p,v?.retryAfter))}throw h};if(!(t.dedupe!==!1&&n==="GET"&&o==null))return c();let l=be(n,e,r),d=T.get(l);if(d)return d;let m=c().finally(()=>T.delete(l));return T.set(l,m),m}var M={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}},we=new Map(Object.values(M).map(e=>[e.chainId,e]));function j(e){return we.get(Number(e))||null}function K(e,t=process.env){let i=j(e);if(!i)return null;for(let a of i.rpcEnv){let n=(t[a]||"").trim();if(n)return n}return null}import{Interface as Ee,getAddress as Se}from"ethers";var W=new Ee(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function z(e,t){try{return Se(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}var Ie={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"};function xe(e,{rpcUrl:t,env:i=process.env}={}){if(t)return t;let a=K(e,i);return a||Ie[Number(e)]||null}var Ce=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Ae(e){let t=String(e||""),i=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!Ce.test(i))throw new Error(`evm-rpc: ${t} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return i}async function w(e,t,i=[],a={}){let n=String(t||"");Ae(n);let r=xe(e,a);if(!r)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let s=await U(r,{method:"POST",body:{jsonrpc:"2.0",id:1,method:t,params:i},fetchImpl:a.fetchImpl,timeoutMs:a.timeoutMs??12e3});if(s?.error){let c=new Error(s.error.message||JSON.stringify(s.error));throw c.code=s.error.code,c}return s.result}async function G(e,t={}){let i=await w(e,"eth_blockNumber",[],t);return parseInt(i,16)}async function Y(e,t,i={}){if(!t)throw new Error("rpcGetBalance requires address");let a=await w(e,"eth_getBalance",[t,"latest"],i);return{chainId:Number(e),address:t,balanceWei:BigInt(a).toString(),balanceHex:a}}async function Q(e={},t={}){let i=Number(e.chainId??t.chainId??1),a=z(e.token||e.tokenAddress,"token"),n=z(e.account||e.owner||e.address,"account"),r=W.encodeFunctionData("balanceOf",[n]),o=await w(i,"eth_call",[{to:a,data:r},e.blockTag||"latest"],t),s=W.decodeFunctionResult("balanceOf",o),c=BigInt(s[0]);return{chainId:i,token:a,account:n,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:e.blockTag||"latest"}}var Ne="https://api.dexscreener.com",Xe=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function Ue(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||Ne).replace(/\/$/,"")}async function X(e,t={}){if(!e)throw new Error("tokenAddress required");return U(`${Ue(t)}/latest/dex/tokens/${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}var L={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},g=e=>BigInt(e).toString(16).padStart(64,"0"),A=e=>e.slice(2).toLowerCase().padStart(64,"0");function _e(e,t){return`0x${L.getAmountsOut}`+g(e)+g(64)+g(t.length)+t.map(A).join("")}function ke(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length<128)return null;let i=Number(BigInt(`0x${t.slice(64,128)}`));if(!Number.isFinite(i)||i<1||i>16)return null;let a=[];for(let n=0;n<i;n++){let r=128+n*64;if(t.length<r+64)return null;a.push(BigInt(`0x${t.slice(r,r+64)}`))}return a}function q(e,t="router"){return(e?.venues||[]).find(a=>a.kind===t)?.address??null}var B=100;function Re(e,t){let i=Number(t);if(!Number.isFinite(i)||i<0)throw new Error("slippageBps must be a non-negative number");if(i>B)throw new Error(`slippageBps ${i} exceeds the ${B} 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(i))/10000n}function J(e){let{chainId:t,wrappedNative:i}=e;async function a(n,r,o,s){let c=await w(t,"eth_call",[{to:n,data:_e(r,o)},"latest"],s);return ke(c?.result??c)}return{async quote({tokenIn:n,tokenOut:r,amountIn:o,path:s},c={}){let u=q(c.scanner);if(!u)return{chainId:t,evidence:b.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let l=s||[n,r];if(l.some(m=>!/^0x[0-9a-fA-F]{40}$/.test(m||"")))throw new Error("quote requires valid 20-byte addresses");let d=await a(u,o,l,c);return d?{chainId:t,router:u,path:l,amountIn:String(o),amountOut:d[d.length-1].toString(),hops:l.length-1,evidence:b.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:u,path:l,evidence:b.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:n,amountIn:r,base:o},s={}){let c=q(s.scanner),u=o||i;if(u&&String(n).toLowerCase()===String(u).toLowerCase())return{chainId:t,token:n,verdict:f.UNKNOWN,evidence:b.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:n,verdict:f.UNKNOWN,evidence:b.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 l=await a(c,r,[u,n],s);if(!l)return{chainId:t,token:n,verdict:f.FAIL,evidence:b.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let d=l[l.length-1];if(d===0n)return{chainId:t,token:n,verdict:f.FAIL,evidence:b.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let m=await a(c,d,[n,u],s);if(!m)return{chainId:t,token:n,verdict:f.FAIL,evidence:b.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 h=m[m.length-1],p=Number(h*10000n/BigInt(r)),v=f.PASS,y="round trip completes with expected fee/impact loss";return p<5e3?(v=f.FAIL,y=`round trip returns only ${(p/100).toFixed(2)}% -- punitive tax or no real liquidity`):p<9e3&&(v=f.CAUTION,y=`round trip returns ${(p/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:n,base:u,router:c,verdict:v,reason:y,amountIn:String(r),bought:d.toString(),returned:h.toString(),retentionBps:p,evidence:b.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:n,tokenOut:r,amountIn:o,recipient:s,slippageBps:c=50,deadlineSeconds:u=900,path:l},d={}){let m=d.scanner,h=q(m);if(!h)throw new Error(`chain ${t} has no verified router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!/^0x[0-9a-fA-F]{40}$/.test(s||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let p=l||[n,r],v=await this.quote({tokenIn:n,tokenOut:r,amountIn:o,path:p},d);if(v.evidence!==b.LIVE)throw new Error(`cannot prepare without a live quote (${v.evidence}: ${v.reason??"no reason given"})`);let y=Re(v.amountOut,c);if(y<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let I=BigInt(Math.floor(Date.now()/1e3)+Number(u)),x=i&&p[0].toLowerCase()===i.toLowerCase()&&d.useNative,k=x?`0x${L.swapExactETHForTokens}`+g(y)+g(128)+A(s)+g(I)+g(p.length)+p.map(A).join(""):`0x${L.swapExactTokensForTokens}`+g(o)+g(y)+g(160)+A(s)+g(I)+g(p.length)+p.map(A).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:h,data:k,value:x?`0x${BigInt(o).toString(16)}`:"0x0"},guard:{quotedOut:v.amountOut,minOut:y.toString(),slippageBps:c,maxSlippageBps:B,deadline:I.toString()},requires:x?[]:[{step:"approve",token:p[0],spender:h,amount:String(o)}],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 Te=[100,500,3e3,1e4],Z={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},E=e=>BigInt(e).toString(16).padStart(64,"0"),N=e=>e.slice(2).toLowerCase().padStart(64,"0"),ee=/^0x[0-9a-fA-F]{40}$/,P=100;function qe(e,t){let i=Number(t);if(!Number.isFinite(i)||i<0)throw new Error("slippageBps must be a non-negative number");if(i>P)throw new Error(`slippageBps ${i} exceeds the ${P} 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(i))/10000n}function O(e,t){return(e?.venues||[]).find(i=>i.kind===t)?.address??null}function te(e){let{chainId:t,wrappedNative:i}=e;async function a({quoter:r,tokenIn:o,tokenOut:s,amountIn:c,fee:u},l){let d=`0x${Z.quoteExactInputSingle}`+N(o)+N(s)+E(c)+E(u)+E(0),m=await w(t,"eth_call",[{to:r,data:d},"latest"],l).catch(()=>null),h=m?.result??m;if(!h||h==="0x"||h.length<66)return null;let p=BigInt(`0x${h.slice(2,66)}`);return p>0n?p:null}async function n({quoter:r,tokenIn:o,tokenOut:s,amountIn:c},u){let l=[],d=null;for(let m of Te){let h=await a({quoter:r,tokenIn:o,tokenOut:s,amountIn:c,fee:m},u);l.push({fee:m,amountOut:h?h.toString():null}),h&&(!d||h>d.amountOut)&&(d={fee:m,amountOut:h})}return{best:d,tried:l}}return{async quote({tokenIn:r,tokenOut:o,amountIn:s},c={}){let u=O(c.scanner,"quoter");if(!u)return{chainId:t,evidence:b.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let m of[r,o])if(!ee.test(m||""))throw new Error("quote requires valid 20-byte addresses");let{best:l,tried:d}=await n({quoter:u,tokenIn:r,tokenOut:o,amountIn:s},c);return l?{chainId:t,venue:"uniswap-v3",quoter:u,tokenIn:r,tokenOut:o,amountIn:String(s),amountOut:l.amountOut.toString(),fee:l.fee,triedFeeTiers:d,evidence:b.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:u,tokenIn:r,tokenOut:o,triedFeeTiers:d,evidence:b.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:r,amountIn:o,base:s},c={}){let u=O(c.scanner,"quoter"),l=s||i;if(l&&String(r).toLowerCase()===String(l).toLowerCase())return{chainId:t,token:r,verdict:f.UNKNOWN,evidence:b.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!u||!l)return{chainId:t,token:r,verdict:f.UNKNOWN,evidence:b.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 n({quoter:u,tokenIn:l,tokenOut:r,amountIn:o},c);if(!d.best)return{chainId:t,token:r,verdict:f.FAIL,evidence:b.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier"};let m=await n({quoter:u,tokenIn:r,tokenOut:l,amountIn:d.best.amountOut},c);if(!m.best)return{chainId:t,token:r,verdict:f.FAIL,evidence:b.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 h=m.best.amountOut,p=Number(h*10000n/BigInt(o)),v=f.PASS,y="round trip completes with expected fee/impact loss";return p<5e3?(v=f.FAIL,y=`round trip returns only ${(p/100).toFixed(2)}% -- punitive tax or no real liquidity`):p<9e3&&(v=f.CAUTION,y=`round trip returns ${(p/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:r,base:l,verdict:v,reason:y,amountIn:String(o),bought:d.best.amountOut.toString(),returned:h.toString(),retentionBps:p,buyFee:d.best.fee,sellFee:m.best.fee,evidence:b.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:r,tokenOut:o,amountIn:s,recipient:c,slippageBps:u=50,fee:l},d={}){let m=O(d.scanner,"router");if(!m)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(!ee.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let h=await this.quote({tokenIn:r,tokenOut:o,amountIn:s},d);if(h.evidence!==b.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let p=l??h.fee,v=qe(h.amountOut,u);if(v<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let y=`0x${Z.exactInputSingle}`+N(r)+N(o)+E(p)+N(c)+E(s)+E(v)+E(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:m,data:y,value:"0x0"},guard:{quotedOut:h.amountOut,minOut:v.toString(),slippageBps:u,maxSlippageBps:P,fee:p},requires:[{step:"approve",token:r,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."}}}}var _={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function re(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function ne(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length>=128){let a=Number(BigInt(`0x${t.slice(64,128)}`));if(a>0&&a<=256&&t.length>=128+a*2){let n=t.slice(128,128+a*2),r=Buffer.from(n,"hex").toString("utf8").replace(/\0+$/,"");if(r)return r}}return Buffer.from(t.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function Le(e){let{chainId:t}=e;async function i(a,n,r){return w(t,"eth_call",[{to:a,data:n},"latest"],r)}return{async blockNumber(a={}){let n=await G(t,a);return{chainId:t,blockNumber:n?.blockNumber??n,evidence:b.LIVE}},async nativeBalance(a,n={}){let r=await Y(t,a,n);return{chainId:t,address:a,wei:r?.wei??r?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:b.LIVE}},async tokenBalance({token:a,owner:n},r={}){let o=await Q({chainId:t,token:a,owner:n},r);return{chainId:t,token:a,owner:n,raw:o?.balance??o,evidence:b.LIVE}},async resolveToken(a,n={}){if(!/^0x[0-9a-fA-F]{40}$/.test(a||""))return{chainId:t,token:a,evidence:b.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[r,o,s,c]=await Promise.all([i(a,_.decimals,n).catch(()=>null),i(a,_.symbol,n).catch(()=>null),i(a,_.name,n).catch(()=>null),i(a,_.totalSupply,n).catch(()=>null)]),u=re(r?.result??r),l=u!==null||o?.result||s?.result;return{chainId:t,address:a,decimals:u===null?null:Number(u),symbol:ne(o?.result??o),name:ne(s?.result??s),totalSupply:(re(c?.result??c)??null)?.toString()??null,evidence:l?b.LIVE:b.UNKNOWN,warning:l?void 0:"no ERC-20 metadata returned -- may not be a token contract"}},async resolvePools(a,n={}){let r=e.dexscreenerSlug;if(!r)return{chainId:t,token:a,pools:[],evidence:b.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let o=await X(a,n).catch(()=>null),c=(o?.pairs||o?.data?.pairs||[]).filter(u=>String(u.chainId).toLowerCase()===String(r).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,l)=>(l.liquidityUsd??0)-(u.liquidityUsd??0));return{chainId:t,token:a,pools:c,evidence:c.length?b.LIVE:b.UNKNOWN}},async scanBlocks({fromBlock:a,toBlock:n,address:r,topics:o,chunkSize:s=2e3}={},c={}){if(!Number.isInteger(a)||!Number.isInteger(n))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(n<a)throw new Error("toBlock must be >= fromBlock");let u=[],l=[];for(let d=a;d<=n;d+=s){let m=Math.min(d+s-1,n);l.push([d,m])}for(let[d,m]of l){let h={fromBlock:`0x${d.toString(16)}`,toBlock:`0x${m.toString(16)}`};r&&(h.address=r),o&&(h.topics=o);let p=await w(t,"eth_getLogs",[h],c).catch(v=>({error:String(v?.message||v)}));if(p?.error)return{chainId:t,fromBlock:a,toBlock:n,logs:u,complete:!1,failedAt:[d,m],error:p.error,evidence:b.UNKNOWN};for(let v of p?.result??p??[])u.push(v)}return{chainId:t,fromBlock:a,toBlock:n,logs:u,complete:!0,chunks:l.length,evidence:b.LIVE}},async scoreRisk(a,n={}){let r=[],o=f.PASS,s=l=>{let d={[f.PASS]:0,[f.CAUTION]:1,[f.UNKNOWN]:2,[f.FAIL]:3};d[l]>d[o]&&(o=l)},c=await this.resolveToken(a,n);c.evidence!==b.LIVE?(r.push({check:"erc20-metadata",result:f.UNKNOWN,detail:c.warning}),s(f.UNKNOWN)):r.push({check:"erc20-metadata",result:f.PASS,detail:`${c.symbol} / ${c.decimals}d`});let u=await this.resolvePools(a,n);if(u.evidence===b.UNAVAILABLE)r.push({check:"liquidity",result:f.UNKNOWN,detail:u.reason}),s(f.UNKNOWN);else if(!u.pools.length)r.push({check:"liquidity",result:f.FAIL,detail:"no pool with liquidity found"}),s(f.FAIL);else{let l=u.pools[0],d=l.liquidityUsd??0;d<5e3?(r.push({check:"liquidity",result:f.CAUTION,detail:`top pool only $${d}`}),s(f.CAUTION)):r.push({check:"liquidity",result:f.PASS,detail:`$${d} on ${l.dex}`}),l.createdAt&&Date.now()-l.createdAt<24*3600*1e3&&(r.push({check:"age",result:f.CAUTION,detail:"pool under 24h old"}),s(f.CAUTION))}if(typeof this.sellSimulation=="function"){let l=await this.sellSimulation({token:a,amountIn:(10n**16n).toString()},n).catch(d=>({verdict:f.UNKNOWN,reason:String(d?.message||d)}));r.push({check:"sellability",result:l.verdict,detail:l.retentionBps!=null?`round trip returns ${(l.retentionBps/100).toFixed(2)}% -- ${l.reason}`:l.reason}),s(l.verdict)}else r.push({check:"sellability",result:f.UNKNOWN,detail:"no verified router on this chain, so a round-trip sell simulation cannot run. Treat as unproven -- a buy path is not an exit path."}),s(f.UNKNOWN);return{chainId:t,token:a,verdict:o,checks:r,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function D(e){let i={...Le(e)},a=new Set((e.venues||[]).map(r=>r.kind));e.venueKind==="uniswap-v3"&&a.has("quoter")&&a.has("router")?Object.assign(i,te({chainId:e.chainId,wrappedNative:e.wrappedNative})):e.venueKind==="uniswap-v2"&&a.has("router")&&Object.assign(i,J({chainId:e.chainId,wrappedNative:e.wrappedNative}));let n={};for(let[r,o]of Object.entries(i))n[r]=o.bind(i);return{key:e.key,chainId:e.chainId,name:e.name,rpcEnv:e.rpcEnv,nativeCurrency:e.nativeCurrency,explorer:e.explorer,venues:e.venues||[],capabilities:n}}var ae=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 Be(){return ae.map(e=>R(D(e)))}function Oe(e){return R(D(e))}export{ae as CHAIN_CONFIGS,b as EVIDENCE,f as RISK,C as SCANNER_CAPABILITIES,Fe as __clearScanners,se as createScanner,Pe as getScanner,De as listScanners,Be as registerBuiltinScanners,Oe as registerCustomChain,R as registerScanner,$e as scannerCoverage,oe as validateScanner};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@oracle-agent/oracle",
3
- "version": "0.16.0",
4
- "description": "Oracle: standalone prepare-only multichain agent control plane with optional Hermes integration. Policy-bounded intents for a user-signed wallet; the public package never takes your key.",
3
+ "version": "0.18.0",
4
+ "description": "Oracle: standalone prepare-only multichain agent control plane. Runs its own agent loop, or plugs into any MCP-compatible harness. Policy-bounded intents for a user-signed wallet; the public package never takes your key.",
5
5
  "license": "BUSL-1.1",
6
6
  "type": "module",
7
7
  "publishConfig": {
@@ -18,9 +18,8 @@
18
18
  "evm",
19
19
  "self-custody",
20
20
  "defi",
21
- "hermes",
22
- "nous",
23
- "mcp"
21
+ "mcp",
22
+ "agent-plugins"
24
23
  ],
25
24
  "engines": {
26
25
  "node": ">=20.19.0"
@@ -34,7 +33,8 @@
34
33
  "oracle-upgrade": "./dist/bin/oracle-upgrade.mjs",
35
34
  "oracle-scan": "./dist/bin/oracle-scan.mjs",
36
35
  "oracle-route": "./dist/bin/oracle-route.mjs",
37
- "oracle-equities": "./dist/bin/oracle-equities.mjs"
36
+ "oracle-equities": "./dist/bin/oracle-equities.mjs",
37
+ "oracle-gateway": "./dist/bin/oracle-gateway.mjs"
38
38
  },
39
39
  "exports": {
40
40
  ".": "./dist/index.mjs",
@@ -66,6 +66,26 @@
66
66
  "ethers": "^6.16.0",
67
67
  "viem": "^2.55.8"
68
68
  },
69
+ "peerDependencies": {
70
+ "grammy": "*",
71
+ "discord.js": "*",
72
+ "whatsapp-web.js": "*",
73
+ "qrcode-terminal": "*"
74
+ },
75
+ "peerDependenciesMeta": {
76
+ "grammy": {
77
+ "optional": true
78
+ },
79
+ "discord.js": {
80
+ "optional": true
81
+ },
82
+ "whatsapp-web.js": {
83
+ "optional": true
84
+ },
85
+ "qrcode-terminal": {
86
+ "optional": true
87
+ }
88
+ },
69
89
  "files": [
70
90
  "dist/",
71
91
  "public/",